20261112 完成#187真实序列录制回放与七指标评估
This commit is contained in:
2
scripts/experiments/reuse_eval/.gitignore
vendored
Normal file
2
scripts/experiments/reuse_eval/.gitignore
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
__pycache__/
|
||||
*.pyc
|
||||
133
scripts/experiments/reuse_eval/README.md
Normal file
133
scripts/experiments/reuse_eval/README.md
Normal file
@@ -0,0 +1,133 @@
|
||||
# #187 原始传输录制与五策略回放评估
|
||||
|
||||
实现采集、归档、闭包核验、固定 epoch HTTPS/rsync 服务、缓存归因、完整序列控制器和单轮正式七指标导出。
|
||||
186 上 v18 预跑与 v20 第一轮正式测试均已完成65/65,后者七指标已逐项重算并与预跑校验。
|
||||
2026-11-12用户决定收尾本次交付:后续两轮正式测试暂不执行,不启动新录制或回放;186的原始录制、预跑、正式结果、state及历史失败现场全部保留,不清理或改写。
|
||||
正式独立重复数为1,预跑不并入正式统计;不能把功能测试的 timing 当性能结果。
|
||||
普通 `rpki` 不启用录制;显式传 `--record-transport-dir <capture-root>` 才归档。
|
||||
记录的是解码后 HTTP 实体字节和 rsync 文件,不是 TLS 报文。
|
||||
|
||||
## 录制入口
|
||||
|
||||
在已经分配独占窗口的 186 上执行;不得使用/操作 231。
|
||||
旧 Panda 的状态与恢复脚本见 `specs/develop/20261109_2/`。
|
||||
所有二进制、输入、临时文件、状态与归档位于独立 `/data/rpki187/20261109/`。
|
||||
|
||||
配置示例(所有路径显式给出,capture_root 每次唯一):
|
||||
|
||||
```json
|
||||
{
|
||||
"run_root": "/data/rpki187/20261109",
|
||||
"archive_root": "/data/rpki187/20261109/archive/capture_YYYYMMDDTHHMMSSZ",
|
||||
"binary": "/data/rpki187/20261109/bin/rpki-recording",
|
||||
"tals": ["/data/rpki187/20261109/fixtures/tal/afrinic.tal", "/data/rpki187/20261109/fixtures/tal/apnic.tal", "/data/rpki187/20261109/fixtures/tal/arin.tal", "/data/rpki187/20261109/fixtures/tal/lacnic.tal", "/data/rpki187/20261109/fixtures/tal/ripe.tal"],
|
||||
"duration_secs": 3600,
|
||||
"poll_secs": 60,
|
||||
"step_secs": 300,
|
||||
"workers": 4,
|
||||
"max_repositories": 1000,
|
||||
"bootstrap_attempts": 3,
|
||||
"rp_timeout_secs": 1800,
|
||||
"rp_args": ["--parallel-max-repo-sync-workers-global", "4", "--parallel-phase2-object-workers", "4", "--rsync-scope", "module-root"],
|
||||
"limits": {"min_free_bytes": 161061273600, "min_root_free_inodes": 10000, "max_growth_bytes": 214748364800, "max_body_bytes": 2147483648, "request_timeout_secs": 30, "body_deadline_secs": 240, "observation_deadline_secs": 600, "attempts": 2}
|
||||
}
|
||||
```
|
||||
|
||||
```bash
|
||||
python3 preflight.py --config /data/rpki187/20261109/config/capture.json --out /data/rpki187/20261109/proof/capture-preflight.json
|
||||
python3 capture.py --config /data/rpki187/20261109/config/capture.json
|
||||
python3 verify.py --archive /data/rpki187/20261109/archive/capture_YYYYMMDDTHHMMSSZ
|
||||
```
|
||||
|
||||
真实内部 RP 完整 bootstrap 后,采集器补齐每个已发现 notification 的当前 snapshot 与可取得的 delta。
|
||||
内部 RP 当前文件 TAL 模式要求显式 TA 路径;控制器在每轮发现运行前,从 TAL 原始 HTTPS 地址(必要时 rsync)下载真实 TA,归档为 `source=ta_refresh` 事件,再将该轮固定的证书文件传给 RP 验证。不会使用旧的测试 TA。
|
||||
只有完整初始 epoch 合格才定义 t0 并计时一小时。每仓库的轮询器至多每 60 秒发起一轮,单仓库不重叠;
|
||||
较慢仓库可能落后,实际请求/完成时间保留。内部 RP 每 300 秒额外做一次真实发现/传输探测,其请求通过 `source=rpki` 区分;
|
||||
新增仓库在发现后进入采集,不声称互联网全量或每次短暂发布皆被捕获。
|
||||
采集过程不测性能;正式测量使用 release 构建与冻结归档。
|
||||
|
||||
## 归档契约
|
||||
|
||||
- `capture.json`:配置、二进制哈希、真实 TAL/constraints、发现 run 命令/状态、t0/end/status。
|
||||
- `inputs/`:真实 TAL 和对应 constraints 的固定副本;TA 证书通过实际 HTTP/rsync-object 事件保存,内部 RP 保持真实信任链验签。
|
||||
文件 TAL 导出 CIR 时必须提供 HTTP(S) TAL locator;本工具使用 `https://capture.rpki187.invalid/tal/<TAL哈希>/<文件名>` 作为明确的内容标识,不访问该地址、不更改 TAL 字节。实际 RRDP/TA 网络 URI 始终保留原值。
|
||||
- `blobs/sha256/<前两位>/<hash>`:不可变原始 XML/DER 内容;同 URI 可以对应多个 hash。原始 URI 和签名内容不改写。
|
||||
- `events/<uuid>.json`:原子事件,schema=`rpki-transport-capture-v1`;source/transport/kind/URI/start/complete/status/有限 headers/body;失败 complete=false。无认证头/cookie。rsync `view` 含完整 URI→blob map,空 view 可表示删除;partial 不作为成功视图。
|
||||
- `observations/<uuid>.json`:notification 引用、可用/缺失文件、session/serial、snapshot view、delta 与 snapshot 一致性结论。
|
||||
- `views/<hash>.json`:用于闭包核验的 URI→对象内容哈希,不代替真实原始文件;视图摘要定义为按 URI 排序、每行紧凑 JSON `[uri,hash]` 加换行的 SHA-256。
|
||||
- `epochs/epoch_XXXX.json`:逻辑时刻之前已完成的最新完整 observation、最新失败尝试、TA/rsync 事件及缺口;绝不使用未来完成的数据。理论 13 步。
|
||||
- `closure-report.json`:blob、epoch 绑定、snapshot view 与时间边界核验。
|
||||
- `discovery/`:内部 RP 私有 state/mirror/CIR/CCR/真实验证报告;不接触旧 Panda 状态。
|
||||
|
||||
采集初始的非必需旧 delta 已淘汰时明确列出,完整 snapshot 仍可建立起点;
|
||||
同 session 更新所需 delta 链缺失/前置 hash 错误/应用结果与 snapshot 不同,该 observation 不合格。
|
||||
初始闭包不完整时 status=bootstrap_incomplete,保留证据并退出 2,不开启一小时正式窗口。
|
||||
显式配置 `bootstrap_gap_policy: "record-with-gaps"` 可继续保存诊断性一小时原始序列,
|
||||
状态为 `recording_with_gaps` / `recorded_with_gaps`,并固化 bootstrap 缺口。所有失败地址继续采样,
|
||||
epoch 的严格 complete 标志不放宽;没有显式范围契约时,verify/server 仍拒绝不完整输入。
|
||||
该模式退出 0 仅表示采集完成,不能作为正式实验准入;范围选择和证书图闭包另行核验。
|
||||
不得仅凭录制成功声称五组或全部 replay 已验收。
|
||||
|
||||
停止:SIGTERM/SIGINT 停止提交新采样,已有请求有界 drain,保留真实完成时间;
|
||||
controller 会终止自己创建的 RP 进程组。新 capture 必须新目录,禁止覆盖旧录制。
|
||||
原始文件、发现报告可能较大,首轮 disk-growth 预算 200 GiB(保守包含同盘其他增长),最低空闲 150 GiB;
|
||||
root 空闲 inode <10k 停止。归档中断 status=interrupted/failed,不冒作完整一小时。
|
||||
|
||||
## 用户已批准的 109 仓库范围
|
||||
|
||||
`scope.py` 只生成原 archive 外的显式契约,不修改原始 `complete=false`、八个 missing 或对象字节。
|
||||
契约冻结 13 个原 epoch、109 个 included、8 个 excluded、五个真实 TA,以及最后一步真实 rsync view 的事件来源。
|
||||
`verify.py --scope` 重新核验原 blob/更新链和时间绑定,输出独立 `scoped-closure-report.json`;
|
||||
scoped server/prepare 必须先有这份成功报告。生成 scope 的 metadata 检查本身不代表原始文件闭包通过。
|
||||
|
||||
```bash
|
||||
python3 scope.py --archive /data/rpki187/20261109/archive/capture_03 \
|
||||
--routes CONFIG/native_routes.json --out /data/rpki187/20261109/scoped109_v12/scope.json
|
||||
python3 verify.py --archive /data/rpki187/20261109/archive/capture_03 \
|
||||
--scope /data/rpki187/20261109/scoped109_v12/scope.json
|
||||
python3 sequence_matrix.py --config CONFIG/pilot186_v12.json
|
||||
```
|
||||
|
||||
配置与执行说明见 workspace `specs/develop/20261109_4/remote_pilot_runbook.md`。
|
||||
最后一步通过受控立即 HTTP 503 触发 `rpki.xindi.eu` 的原始只读 rsync view;不重现原公网 TLS 超时延迟。
|
||||
八个 excluded notification 也固定 503,未知实体 404,无上游补取。原 TAL/TA、对象签名、逻辑验证时间和 policy 保持真实验证路径。
|
||||
|
||||
`sequence_matrix.py` 仅允许指定 186 主机/root/独立持久化目录。它保存旧 Panda 的初始活动状态,暂停后检查竞争 RP,
|
||||
创建实验 namespace,五组依次运行全部 13 步;每步从自己的前态推进,核对契约、全部五 TA、CIR/CCR、T1/T2 和真实传输分支。
|
||||
每次 RP 单独的 cgroup 采集 CPU/MemoryPeak(server 在另一 namespace/CPU),exact cache-size 在计时外采集。
|
||||
成功步骤删除控制器新建的 pre-state/T2 scratch DB,仅保留哈希和测量证明;T1 权威 state、完整 run 输出及原始录制全部保留,失败步骤的 scratch 留作排查。
|
||||
正常完成、异常或 SIGINT/SIGTERM 时清理本控制器的 namespace,并恢复它暂停的旧 Panda;原本 inactive 的服务不会主动启动。
|
||||
硬断电/SIGKILL 后需按 runbook 检查并恢复,不能据旧 summary 推断当前状态。
|
||||
|
||||
完整 pilot 为 65 个 T1 和 65 个 T2,v18 已在186全部通过。
|
||||
未启用正式测量的 pilot 显式输出 `performance_ready=false`,其 sync wall union、payload-ready 原子发布边界缺失,不能补造这两项或将 pilot 作为完整七指标正式结果。
|
||||
T1 cgroup CPU/内存、T2 engine wall/CPU、分层命中计数和 cache-size 可作为 pilot 原始证据;T1/T2 不相加推导端到端时间。
|
||||
|
||||
## 单轮正式入口与当前保留位置
|
||||
|
||||
`single_formal.py` 读取冻结配置,先校验原预跑65项证明、工具/ELF/scope哈希,在独立新结果根调用同一矩阵引擎,结束后重读原始证明并导出 `single-report.json` 与65行 `all-steps.csv`。正式模式要求 `--evaluation-metrics-out` 的原生同步区间及CCR原子发布时钟;HTTP/rsync测量scope归一化后仍须与原始传输结果完全匹配。
|
||||
|
||||
七指标为同步执行区间并集、独立T2冻结输入验证wall、trigger至CCR原子发布、各层hits/queries、T1整个cgroup CPU秒、GNU time最大RSS、所选策略必要缓存字节。T2从T1前缓存开始,输入覆盖不得导入本步新验证结论,包含必要缓存持久化与I/O drain。
|
||||
|
||||
当前原件均留在186的 `/data/rpki187/20261109/`:
|
||||
|
||||
- `archive/capture_03`:原始录制,109个成功RRDP仓库,八个持续缺口单列,五个真实TA,一小时13个逻辑时点。
|
||||
- `results/scoped109_pilot_v18`:已完成预跑,65/65。
|
||||
- `results/scoped109_formal_v20_r1`:已完成第一轮正式测试,65/65。
|
||||
- `results/scoped109_single_v20`:正式单轮状态与最终导出。
|
||||
|
||||
五策略均关闭prefetch,使用CPU1–3、3个worker及5GiB内存上限,server使用CPU0;同机共享存储、page cache和CPU sibling,不能声称物理资源完全隔离。当前没有第二、第三轮正式结果,后续运行须按用户新的安排另行启动。
|
||||
|
||||
分析和最终收尾见工作区 `specs/develop/20261112/`,原PPT第10/11页已填入第一轮配置与结果。本地仅保存提取指标、统计和紧凑证明,不复制原始实验目录。
|
||||
|
||||
## 验证
|
||||
|
||||
```bash
|
||||
python3 -m unittest discover -s scripts/experiments/reuse_eval -p 'test_*.py' -v
|
||||
cargo test --lib recording
|
||||
cargo test --lib transport_recording
|
||||
```
|
||||
|
||||
本地 HTTP 夹具只检查协议和归档逻辑;真实验收必须运行内部 RP 加真实 TAL/TA,测试性能使用 release。
|
||||
|
||||
2026-11-12收尾:Python控制测试77项通过;Rust沿用仓库coverage默认跳过配置,累计1,277项通过、15项忽略,99个集成测试目标均完成。原有CLI“离线”用例在默认网络环境停留,终止后以串行及外部HTTP拒绝代理完成剩余目标;不将首次默认命令记为成功。现有过滤口径行覆盖率88.68%,未达到90%门槛,全仓未过滤83.51%。质量缺口与日志记录在收尾目录;本次没有追加远端实验。
|
||||
135
scripts/experiments/reuse_eval/cache_size.py
Normal file
135
scripts/experiments/reuse_eval/cache_size.py
Normal file
@@ -0,0 +1,135 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Attribute retained validation bytes from exact DB statistics and a run contract."""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
import stat
|
||||
|
||||
from common import atomic_json, file_sha256, read_json
|
||||
|
||||
COMPONENTS = {
|
||||
"roa": "roa_cache_projection",
|
||||
"child_certificate": "child_certificate_cache_projection",
|
||||
"publication_point": "publication_point_cache_projection",
|
||||
"common_vcir": "vcir",
|
||||
"common_manifest_replay": "manifest_replay_meta",
|
||||
"common_failed_fetch_identity": "vcir_failed_fetch_reuse_identity",
|
||||
"transport_prefetch": "transport_prefetch",
|
||||
}
|
||||
PROFILES = {
|
||||
"baseline": (False, False, False, False),
|
||||
"signature": (False, False, False, True),
|
||||
"object": (False, True, True, False),
|
||||
"pp": (True, False, False, False),
|
||||
"hybrid": (True, True, True, False),
|
||||
}
|
||||
|
||||
|
||||
def profile_from_contract(contract: dict) -> tuple[str, dict]:
|
||||
cache = contract["cache"]
|
||||
keys = ("publicationPoint", "roa", "childCertificate", "cryptoSignature", "transportPrefetch")
|
||||
if any(type(cache.get(key)) is not bool for key in keys):
|
||||
raise ValueError("contract must explicitly contain boolean cache settings")
|
||||
if cache["transportPrefetch"]:
|
||||
raise ValueError("transport prefetch is outside the five-profile matrix")
|
||||
flags = tuple(cache[key] for key in keys[:4])
|
||||
for name, expected in PROFILES.items():
|
||||
if flags == expected:
|
||||
return name, {"roa": cache["roa"], "child_certificate": cache["childCertificate"],
|
||||
"publication_point": cache["publicationPoint"], "signature": cache["cryptoSignature"]}
|
||||
raise ValueError("cache combination is outside the five-profile matrix")
|
||||
|
||||
|
||||
def file_inventory(path: Path) -> dict:
|
||||
if path.is_symlink():
|
||||
raise ValueError(f"cache sidecar must not be a symlink: {path}")
|
||||
if not path.exists():
|
||||
return {"path": str(path), "exists": False, "files": 0, "file_bytes": 0, "allocated_bytes": 0}
|
||||
files = [path] if path.is_file() else sorted(path.rglob("*"))
|
||||
size, allocated, count, inodes = 0, 0, 0, set()
|
||||
for item in files:
|
||||
meta = item.lstat()
|
||||
if stat.S_ISDIR(meta.st_mode):
|
||||
continue
|
||||
if not stat.S_ISREG(meta.st_mode):
|
||||
raise ValueError(f"non-regular cache sidecar: {item}")
|
||||
size += meta.st_size
|
||||
count += 1
|
||||
identity = (meta.st_dev, meta.st_ino)
|
||||
if identity not in inodes:
|
||||
if not hasattr(meta, "st_blocks"):
|
||||
raise ValueError("allocated-byte measurement requires filesystem block counts")
|
||||
allocated += meta.st_blocks * 512
|
||||
inodes.add(identity)
|
||||
return {"path": str(path), "exists": True, "files": count, "file_bytes": size, "allocated_bytes": allocated}
|
||||
|
||||
|
||||
def account(db: Path, stats_path: Path, contract_path: Path) -> dict:
|
||||
db = db.resolve()
|
||||
stats = {}
|
||||
for line in stats_path.read_text().splitlines():
|
||||
key, sep, value = line.partition("=")
|
||||
if not sep:
|
||||
continue
|
||||
if key in stats:
|
||||
raise ValueError(f"duplicate DB statistics field: {key}")
|
||||
stats[key] = value
|
||||
if stats.get("mode") != "exact" or stats.get("logical_bytes_available") != "true":
|
||||
raise ValueError("cache accounting requires db_stats --exact")
|
||||
if Path(stats["db"]).resolve() != db:
|
||||
raise ValueError("DB statistics belong to a different state path")
|
||||
contract = read_json(contract_path)
|
||||
profile, enabled = profile_from_contract(contract)
|
||||
components = {}
|
||||
for name, cf in COMPONENTS.items():
|
||||
item = {"column_family": cf, "required_for_selected_reuse": enabled.get(name, False)}
|
||||
for field in ("keys", "key_bytes", "value_bytes", "live_sst_size_bytes"):
|
||||
value = int(stats[f"cf.{cf}.{field}"])
|
||||
if value < 0:
|
||||
raise ValueError("negative DB statistics")
|
||||
item[field] = value
|
||||
item["logical_bytes"] = item["key_bytes"] + item["value_bytes"]
|
||||
components[name] = item
|
||||
sidecars = {
|
||||
"signature": file_inventory(db.with_name(db.name + ".crypto-sig-cache")),
|
||||
"publication_point": file_inventory(db.with_name(db.name + ".pp-cache-index")),
|
||||
"child_certificate": file_inventory(db.with_name(db.name + ".child-cert-cache-index")),
|
||||
}
|
||||
required_cf = sum(item["logical_bytes"] for item in components.values() if item["required_for_selected_reuse"])
|
||||
required_files = sum(item["file_bytes"] for name, item in sidecars.items() if enabled[name])
|
||||
required = required_cf + required_files
|
||||
return {
|
||||
"schema": "rpki-validation-cache-accounting-v1", "db": str(db), "profile": profile,
|
||||
"validation_contract_sha256": file_sha256(contract_path), "db_stats_sha256": file_sha256(stats_path),
|
||||
"cache_settings": contract["cache"], "measurement_outside_timed_window": True,
|
||||
"required_serialized_bytes": required, "required_serialized_mib": required / 1024**2,
|
||||
"required_cf_key_value_bytes": required_cf, "required_sidecar_file_bytes": required_files,
|
||||
"all_retained_validation_cf_key_value_bytes": sum(item["logical_bytes"] for item in components.values()),
|
||||
"all_retained_sidecar_file_bytes": sum(item["file_bytes"] for item in sidecars.values()),
|
||||
"components": components, "sidecars": sidecars,
|
||||
"accounting_notes": [
|
||||
"Raw repository objects, RRDP state, logs and reports are excluded from validation cache bytes.",
|
||||
"Disabled reuse may still retain common validation projections; those bytes are listed separately.",
|
||||
"Separate CF records and index files are actual serialized copies and are counted separately.",
|
||||
"CF compressed SST file lengths and sidecar allocated blocks are separate measures; shared DB WAL/metadata are not apportioned.",
|
||||
"This is retained serialized cache size, not in-memory cache usage or a minimal theoretical representation.",
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--db", type=Path, required=True)
|
||||
parser.add_argument("--db-stats", type=Path, required=True)
|
||||
parser.add_argument("--contract", type=Path, required=True)
|
||||
parser.add_argument("--out", type=Path, required=True)
|
||||
args = parser.parse_args()
|
||||
result = account(args.db, args.db_stats, args.contract)
|
||||
atomic_json(args.out, result)
|
||||
print(json.dumps({key: result[key] for key in ("profile", "required_serialized_bytes", "required_serialized_mib")}))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
167
scripts/experiments/reuse_eval/campaign.py
Normal file
167
scripts/experiments/reuse_eval/campaign.py
Normal file
@@ -0,0 +1,167 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Wait for the full correctness pilot, then run three independent repeats."""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
from collections import defaultdict
|
||||
import csv
|
||||
from datetime import datetime, timezone
|
||||
import json
|
||||
from pathlib import Path
|
||||
import signal
|
||||
import statistics
|
||||
import time
|
||||
|
||||
from common import atomic_json, file_sha256, read_json
|
||||
from sequence_matrix import EXPECTED_HOST, PROFILE_FLAGS, run_pilot
|
||||
import os
|
||||
import socket
|
||||
|
||||
SCALARS = ("repository_sync_ns", "rp_validation_ns", "update_to_payload_ns", "cpu_ns",
|
||||
"peak_rss_bytes", "cgroup_memory_peak_bytes", "cache_size_bytes")
|
||||
|
||||
|
||||
def require_matrix(summary: dict, scope_hash: str, formal: bool) -> None:
|
||||
pairs = [(row["profile"], row["step"]) for row in summary["runs"]]
|
||||
expected = {(profile, step) for profile in PROFILE_FLAGS for step in range(13)}
|
||||
if (summary.get("status") != "completed" or summary.get("pass") is not True
|
||||
or len(pairs) != 65 or set(pairs) != expected or any(row.get("pass") is not True for row in summary["runs"])
|
||||
or summary.get("scope_sha256") != scope_hash):
|
||||
raise ValueError("full 65-pair correctness prerequisite is not satisfied")
|
||||
if formal and (summary.get("performance_ready") is not True or any(not row.get("seven_metrics") for row in summary["runs"])):
|
||||
raise ValueError("formal matrix lacks all seven directly measured metrics")
|
||||
restoration = summary.get("restoration", {})
|
||||
if any(restoration.get(name, 0) != 0 for name in ("rp187rp", "rp187srv")):
|
||||
raise ValueError("matrix namespace restoration failed")
|
||||
if restoration.get("panda_active", True) is not True or restoration.get("panda_container_running", True) is not True:
|
||||
raise ValueError("matrix original Panda restoration failed")
|
||||
|
||||
|
||||
def distribution(values: list[float]) -> dict:
|
||||
return {"n": len(values), "mean": statistics.mean(values), "stdev": statistics.stdev(values) if len(values) > 1 else 0,
|
||||
"min": min(values), "max": max(values), "values": values}
|
||||
|
||||
|
||||
def aggregate(summaries: list[dict]) -> dict:
|
||||
if len(summaries) != 3:
|
||||
raise ValueError("exactly three independent complete repeats are required")
|
||||
scope = summaries[0]["scope_sha256"]
|
||||
binary = summaries[0]["tool_sha256"]["binary"]
|
||||
tools = summaries[0]["tool_sha256"]
|
||||
for summary in summaries:
|
||||
require_matrix(summary, scope, formal=True)
|
||||
if summary["tool_sha256"] != tools:
|
||||
raise ValueError("formal repeats used different RP binaries")
|
||||
groups = defaultdict(list)
|
||||
for repeat, summary in enumerate(summaries, 1):
|
||||
for profile in PROFILE_FLAGS:
|
||||
rows = [row for row in summary["runs"] if row["profile"] == profile]
|
||||
for label, selected in (("cold", [r for r in rows if r["step"] == 0]),
|
||||
("incremental", [r for r in rows if 1 <= r["step"] <= 12]),
|
||||
("incremental_without_fallback", [r for r in rows if 1 <= r["step"] <= 11]),
|
||||
("native_fallback", [r for r in rows if r["step"] == 12])):
|
||||
metrics = [row["seven_metrics"] for row in selected]
|
||||
value = {"repeat": repeat, "steps": len(selected),
|
||||
"means": {key: statistics.mean(m[key] for m in metrics) for key in SCALARS},
|
||||
"cache_size_at_end_bytes": max(selected, key=lambda r: r["step"])["seven_metrics"]["cache_size_bytes"],
|
||||
"hit_ratios": {}}
|
||||
for layer in ("signature", "roa", "child_certificate", "publication_point"):
|
||||
numerator = sum(m["cache_hit_ratio"][layer]["hits"] for m in metrics)
|
||||
denominator = sum(m["cache_hit_ratio"][layer]["queries"] for m in metrics)
|
||||
value["hit_ratios"][layer] = {"hits": numerator, "queries": denominator,
|
||||
"ratio": numerator / denominator if denominator else None}
|
||||
groups[(profile, label)].append(value)
|
||||
output = []
|
||||
for (profile, label), values in groups.items():
|
||||
output.append({"profile": profile, "steps": label, "repeats": values,
|
||||
"metrics": {key: distribution([v["means"][key] for v in values]) for key in SCALARS},
|
||||
"hit_ratios": {layer: distribution([v["hit_ratios"][layer]["ratio"] for v in values])
|
||||
if all(v["hit_ratios"][layer]["ratio"] is not None for v in values) else None
|
||||
for layer in ("signature", "roa", "child_certificate", "publication_point")}})
|
||||
return {"pass": True, "performance_ready": True, "repeats": 3, "pairs": 195, "scope_sha256": scope,
|
||||
"binary_sha256": binary, "groups": output,
|
||||
"limitations": ["109 observed successful repositories; eight declared gaps; not global RPKI coverage",
|
||||
"one-hour capture; fixed five-minute logical steps; controlled final-step HTTP failure triggers recorded rsync view",
|
||||
"same 186 host with separate CPU/network namespaces for server and RP; no independent-machine network latency claim",
|
||||
"baseline first within every repeat; other profiles rotate; OS page cache is not forcibly dropped",
|
||||
"three independent repeat means are statistical replicates; individual epochs are not independent repeats",
|
||||
"RSS and cgroup charged/page-cache memory are reported separately; all RP units have the same 5 GiB limit"]}
|
||||
|
||||
|
||||
def run(config: dict) -> dict:
|
||||
if socket.gethostname() != EXPECTED_HOST or os.geteuid() != 0:
|
||||
raise ValueError("campaign is restricted to root on the designated 186 host")
|
||||
output = Path(config["out"]).resolve()
|
||||
if not str(output).startswith("/data/rpki187/20261109/results/"):
|
||||
raise ValueError("campaign must use the dedicated persistent experiment root")
|
||||
output.mkdir(parents=True, exist_ok=False)
|
||||
configurations = config["repeats"]
|
||||
if len(configurations) != 3 or len({item["out"] for item in configurations}) != 3:
|
||||
raise ValueError("campaign requires three distinct state/output roots")
|
||||
scope_hash = configurations[0]["expected_scope_sha256"]
|
||||
if any(item.get("formal_metrics") is not True or item["expected_scope_sha256"] != scope_hash
|
||||
or item["expected_binary_sha256"] != configurations[0]["expected_binary_sha256"] for item in configurations):
|
||||
raise ValueError("campaign repeat contracts differ")
|
||||
state = {"status": "waiting_for_correctness_pilot", "pass": False, "performance_ready": False,
|
||||
"config": config, "repeat_summaries": []}
|
||||
def save():
|
||||
state["updated_utc"] = datetime.now(timezone.utc).isoformat()
|
||||
atomic_json(output / "campaign-status.json", state)
|
||||
try:
|
||||
deadline = time.monotonic() + config.get("pilot_wait_secs", 86400)
|
||||
prerequisite = Path(config["pilot_summary"])
|
||||
while True:
|
||||
if prerequisite.exists():
|
||||
pilot = read_json(prerequisite)
|
||||
state["pilot_progress_pairs"] = len(pilot.get("runs", []))
|
||||
if pilot["status"] == "completed":
|
||||
require_matrix(pilot, scope_hash, formal=False)
|
||||
state["pilot_summary_sha256"] = file_sha256(prerequisite)
|
||||
break
|
||||
if pilot["status"] != "running":
|
||||
raise ValueError(f"correctness pilot failed: {pilot.get('error', pilot['status'])}")
|
||||
if time.monotonic() >= deadline:
|
||||
raise TimeoutError("correctness pilot did not complete before campaign deadline")
|
||||
save()
|
||||
time.sleep(30)
|
||||
summaries = []
|
||||
for index, item in enumerate(configurations, 1):
|
||||
state.update(status="running", active_repeat=index)
|
||||
save()
|
||||
summary = run_pilot(item)
|
||||
require_matrix(summary, scope_hash, formal=True)
|
||||
summaries.append(summary)
|
||||
path = Path(item["out"]) / "summary.json"
|
||||
state["repeat_summaries"].append({"repeat": index, "path": str(path), "sha256": file_sha256(path)})
|
||||
save()
|
||||
report = aggregate(summaries)
|
||||
atomic_json(output / "campaign-report.json", report)
|
||||
with (output / "all-steps.csv").open("w", newline="") as file:
|
||||
writer = csv.DictWriter(file, fieldnames=["repeat", "profile", "step", *SCALARS])
|
||||
writer.writeheader()
|
||||
for repeat, summary in enumerate(summaries, 1):
|
||||
for row in summary["runs"]:
|
||||
writer.writerow({"repeat": repeat, "profile": row["profile"], "step": row["step"],
|
||||
**{key: row["seven_metrics"][key] for key in SCALARS}})
|
||||
state.update(status="completed", performance_ready=True)
|
||||
state["pass"] = True
|
||||
save()
|
||||
return state
|
||||
except BaseException as exc:
|
||||
state.update(status="failed", error=f"{type(exc).__name__}: {exc}")
|
||||
save()
|
||||
raise
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--config", type=Path, required=True)
|
||||
args = parser.parse_args()
|
||||
def interrupted(*_):
|
||||
raise KeyboardInterrupt("campaign interrupted")
|
||||
signal.signal(signal.SIGTERM, interrupted)
|
||||
print(json.dumps(run(read_json(args.config))))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
413
scripts/experiments/reuse_eval/capture.py
Normal file
413
scripts/experiments/reuse_eval/capture.py
Normal file
@@ -0,0 +1,413 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Record real internal-RP discovery plus minute RRDP observations on one host."""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import signal
|
||||
import subprocess
|
||||
import threading
|
||||
import tempfile
|
||||
import time
|
||||
import urllib.parse
|
||||
import uuid
|
||||
|
||||
from common import Archive, SCHEMA, atomic_json, file_sha256, now_ms, read_json
|
||||
from rrdp import notification, payload_view, view_digest
|
||||
|
||||
|
||||
class Collector:
|
||||
def __init__(self, archive: Archive):
|
||||
self.archive = archive
|
||||
self.verified: set[str] = set()
|
||||
self.lock = threading.Lock()
|
||||
self.sequence = 0
|
||||
|
||||
def reference(self, ref: dict) -> dict:
|
||||
path = self.archive.blob_path(ref["sha256"])
|
||||
if path.is_file():
|
||||
with self.lock:
|
||||
if ref["sha256"] not in self.verified:
|
||||
self.archive.verify_blob({"sha256": ref["sha256"], "size": path.stat().st_size})
|
||||
self.verified.add(ref["sha256"])
|
||||
return {**ref, "available": True, "size": path.stat().st_size, "cache": True}
|
||||
events = []
|
||||
for _ in range(self.archive.limits.get("attempts", 2)):
|
||||
event = self.archive.fetch(ref["uri"], ref["kind"])
|
||||
events.append(event["id"])
|
||||
if event["complete"] and event["body"]["sha256"] == ref["sha256"]:
|
||||
return {**ref, "available": True, "size": event["body"]["size"], "event_ids": events}
|
||||
return {**ref, "available": False, "event_ids": events,
|
||||
"error": "reference unavailable or hash mismatch"}
|
||||
|
||||
def observe(self, uri: str, previous: dict | None = None) -> dict:
|
||||
archive = self.archive
|
||||
observation = {"id": str(uuid.uuid4()), "uri": uri, "started_ms": now_ms(), "complete": False}
|
||||
with self.lock:
|
||||
self.sequence += 1
|
||||
observation["sequence"] = self.sequence
|
||||
if previous and previous.get("complete"):
|
||||
observation["base_observation_id"] = previous["id"]
|
||||
try:
|
||||
event = archive.fetch(uri, "notification", previous.get("http") if previous else None)
|
||||
observation["http"] = event
|
||||
if not event["complete"]:
|
||||
raise ValueError(event["error"])
|
||||
parsed = notification(archive.blob_path(event["body"]["sha256"]), uri)
|
||||
observation.update(session=parsed["session"], serial=parsed["serial"], notification=event["body"])
|
||||
# Snapshot first: preserve an independent starting point and fallback.
|
||||
refs = sorted(parsed["references"], key=lambda r: (r["kind"] != "snapshot", r["serial"]))
|
||||
deadline = time.monotonic() + archive.limits.get("observation_deadline_secs", 600)
|
||||
captured = []
|
||||
for ref in refs:
|
||||
if time.monotonic() > deadline:
|
||||
captured.append({**ref, "available": False, "error": "observation deadline exceeded"})
|
||||
else:
|
||||
captured.append(self.reference(ref))
|
||||
refs = captured
|
||||
observation["references"] = refs
|
||||
snapshot = next(ref for ref in refs if ref["kind"] == "snapshot")
|
||||
if not snapshot["available"]:
|
||||
raise ValueError("current snapshot is missing")
|
||||
same = previous and previous.get("complete") and previous.get("session") == parsed["session"]
|
||||
if same and previous["serial"] == parsed["serial"]:
|
||||
old_snapshot = next(ref for ref in previous["references"] if ref["kind"] == "snapshot")
|
||||
if old_snapshot["sha256"] != snapshot["sha256"]:
|
||||
raise ValueError("snapshot changed without session/serial advancement")
|
||||
observation.update(view=previous["view"], object_count=previous["object_count"], chain="no_change")
|
||||
else:
|
||||
view = payload_view(archive.blob_path(snapshot["sha256"]), "snapshot", parsed["session"], parsed["serial"])
|
||||
view_hash = view_digest(view)
|
||||
atomic_json(archive.root / "views" / f"{view_hash}.json", view)
|
||||
observation.update(view=view_hash, object_count=len(view), chain="initial_snapshot")
|
||||
if same:
|
||||
if parsed["serial"] < previous["serial"]:
|
||||
raise ValueError("serial rollback within the same session")
|
||||
old_view = read_json(archive.root / "views" / f"{previous['view']}.json")
|
||||
deltas = {ref["serial"]: ref for ref in refs if ref["kind"] == "delta"}
|
||||
needed = range(previous["serial"] + 1, parsed["serial"] + 1)
|
||||
if parsed["serial"] - previous["serial"] > 10000:
|
||||
raise ValueError("required delta chain exceeds bound")
|
||||
for serial in needed:
|
||||
delta = deltas.get(serial)
|
||||
if not delta or not delta["available"]:
|
||||
raise ValueError(f"required delta {serial} missing")
|
||||
old_view = payload_view(archive.blob_path(delta["sha256"]), "delta", parsed["session"], serial, old_view)
|
||||
if old_view != view:
|
||||
raise ValueError("applied delta chain differs from snapshot")
|
||||
observation["chain"] = "delta_matches_snapshot"
|
||||
elif previous and previous.get("complete"):
|
||||
observation["chain"] = "session_reset_snapshot"
|
||||
observation["complete"] = True
|
||||
except Exception as exc:
|
||||
observation["error"] = f"{type(exc).__name__}: {exc}"
|
||||
observation["completed_ms"] = now_ms()
|
||||
atomic_json(archive.root / "observations" / f"{observation['id']}.json", observation)
|
||||
print(json.dumps({k: observation.get(k) for k in ("uri", "serial", "complete", "chain", "error")}), flush=True)
|
||||
return observation
|
||||
|
||||
|
||||
def select_epoch(root: Path, registry: dict, cutoff: int) -> dict:
|
||||
selected, latest, missing, blocked = {}, {}, [], []
|
||||
for path in (root / "observations").glob("*.json"):
|
||||
item = read_json(path)
|
||||
if item["completed_ms"] > cutoff:
|
||||
continue
|
||||
uri = item["uri"]
|
||||
order = (item["completed_ms"], item.get("sequence", 0))
|
||||
if uri not in latest or order > (latest[uri]["completed_ms"], latest[uri].get("sequence", 0)):
|
||||
latest[uri] = item
|
||||
if item["complete"] and (uri not in selected or order > (selected[uri]["completed_ms"], selected[uri].get("sequence", 0))):
|
||||
selected[uri] = item
|
||||
for uri, entry in registry.items():
|
||||
if entry["first_seen_ms"] <= cutoff and uri not in selected:
|
||||
missing.append(uri)
|
||||
elif entry["first_seen_ms"] <= cutoff and not latest[uri]["complete"]:
|
||||
blocked.append(uri)
|
||||
# Bind real TA HTTP/rsync-object versions and complete rsync module views.
|
||||
objects, rsync = {}, {}
|
||||
for path in (root / "events").glob("*.json"):
|
||||
event = read_json(path)
|
||||
if not event["complete"] or event["completed_ms"] > cutoff or event["source"] not in ("rpki", "ta_refresh"):
|
||||
continue
|
||||
target = rsync if event["transport"] == "rsync" and event["kind"] == "view" else objects
|
||||
if event["kind"] not in ("object", "view"):
|
||||
continue
|
||||
if event["uri"] not in target or target[event["uri"]]["completed_ms"] < event["completed_ms"]:
|
||||
target[event["uri"]] = event
|
||||
contract = root / "contract.json"
|
||||
return {"schema": SCHEMA, "validation_time_ms": cutoff, "complete": not missing and not blocked,
|
||||
"contract_sha256": file_sha256(contract) if contract.is_file() else None,
|
||||
"repositories": {u: {k: o[k] for k in ("id", "session", "serial", "notification", "view", "completed_ms")}
|
||||
for u, o in selected.items()},
|
||||
"latest_attempts": {u: {k: o.get(k) for k in ("id", "complete", "completed_ms", "error")} for u, o in latest.items()},
|
||||
"missing": sorted(missing), "blocked_latest_attempts": sorted(blocked), "ta_object_events": {u: e["id"] for u, e in objects.items()},
|
||||
"rsync_view_events": {u: e["id"] for u, e in rsync.items()}}
|
||||
|
||||
|
||||
class Capture:
|
||||
def __init__(self, config: dict):
|
||||
self.config = config
|
||||
poll, step, duration = config.get("poll_secs", 60), config.get("step_secs", 300), config.get("duration_secs", 3600)
|
||||
if poll < 60 or step < poll or duration < step or duration % step:
|
||||
raise ValueError("require poll>=60, step>=poll, duration>=step and a whole number of steps")
|
||||
if not 1 <= config.get("workers", 4) <= 8:
|
||||
raise ValueError("capture workers must be between 1 and 8")
|
||||
if len(config["tals"]) != 5 or len(set(config["tals"])) != 5:
|
||||
raise ValueError("main capture requires five distinct real TAL paths")
|
||||
if config.get("bootstrap_gap_policy", "abort") not in ("abort", "record-with-gaps"):
|
||||
raise ValueError("bootstrap_gap_policy must be abort or record-with-gaps")
|
||||
self.root = Path(config["archive_root"]).resolve()
|
||||
if self.root.exists() and any(self.root.iterdir()):
|
||||
raise ValueError("capture root already exists; use a new capture ID")
|
||||
self.archive = Archive(self.root, config.get("limits"))
|
||||
self.collector = Collector(self.archive)
|
||||
self.registry, self.latest, self.seen_events = {}, {}, set()
|
||||
self.rp = None
|
||||
self.run_number = 0
|
||||
self.stopping = False
|
||||
self.metadata = {"schema": SCHEMA, "status": "bootstrap", "started_ms": now_ms(), "config": config,
|
||||
"binary_sha256": file_sha256(Path(config["binary"])), "runs": []}
|
||||
self.metadata["scripts_sha256"] = {p.name: file_sha256(p) for p in Path(__file__).parent.glob("*.py")}
|
||||
self.metadata["machine"] = {"uname": list(os.uname()), "cpus": os.cpu_count()}
|
||||
self.pin_inputs()
|
||||
self.save()
|
||||
|
||||
def pin_inputs(self) -> None:
|
||||
tals = []
|
||||
for name in self.config["tals"]:
|
||||
source = Path(name)
|
||||
data = source.read_bytes()
|
||||
body = self.archive.put_stream(__import__("io").BytesIO(data))
|
||||
target = self.root / "inputs" / source.name
|
||||
target.parent.mkdir(exist_ok=True)
|
||||
target.write_bytes(data)
|
||||
item = {"path": str(target), **body}
|
||||
# CIR requires an HTTP(S) locator even for file TAL inputs. This is
|
||||
# an explicit content-addressed label, never a download endpoint.
|
||||
item["cir_tal_uri"] = f"https://capture.rpki187.invalid/tal/{body['sha256']}/{source.name}"
|
||||
constraint = source.with_suffix(".constraints")
|
||||
if constraint.exists():
|
||||
target.with_suffix(".constraints").write_bytes(constraint.read_bytes())
|
||||
item["constraints_sha256"] = file_sha256(constraint)
|
||||
tals.append(item)
|
||||
self.metadata["tals"] = tals
|
||||
|
||||
def save(self) -> None:
|
||||
atomic_json(self.root / "capture.json", self.metadata)
|
||||
atomic_json(self.root / "registry.json", self.registry)
|
||||
|
||||
def discover(self) -> None:
|
||||
for path in (self.root / "events").glob("*.json"):
|
||||
if path.name in self.seen_events:
|
||||
continue
|
||||
event = read_json(path)
|
||||
self.seen_events.add(path.name)
|
||||
if event["source"] == "rpki" and event["kind"] == "notification":
|
||||
self.registry.setdefault(event["uri"], {"first_seen_ms": event["started_ms"]})
|
||||
if len(self.registry) > self.config.get("max_repositories", 1000):
|
||||
raise RuntimeError("repository count limit exceeded")
|
||||
|
||||
def start_rp(self) -> None:
|
||||
self.archive.guard()
|
||||
self.run_number += 1
|
||||
run = self.root / "discovery" / f"run_{self.run_number:04d}"
|
||||
run.mkdir(parents=True)
|
||||
(self.root / "discovery/state").mkdir(parents=True, exist_ok=True)
|
||||
(run / "ta").mkdir()
|
||||
ta_versions = []
|
||||
for tal in self.metadata["tals"]:
|
||||
ta_versions.append(self.refresh_ta(Path(tal["path"]), run / "ta"))
|
||||
command = [self.config["binary"], "--db", str(self.root / "discovery/state/db"),
|
||||
"--record-transport-dir", str(self.root), "--rsync-mirror-root", str(self.root / "discovery/mirror"),
|
||||
"--report-json", str(run / "report.json"), "--report-json-compact",
|
||||
"--validation-contract-out", str(run / "validation-contract.json"),
|
||||
"--ccr-out", str(run / "result.ccr"), "--cir-enable", "--cir-out", str(run / "input.cir"),
|
||||
"--analyze", "--analysis-out", str(run / "analysis")]
|
||||
for tal, ta in zip(self.metadata["tals"], ta_versions):
|
||||
command += ["--tal-path", tal["path"], "--ta-path", ta["path"], "--cir-tal-uri", tal["cir_tal_uri"]]
|
||||
command += self.config.get("rp_args", [])
|
||||
env = dict(os.environ, TMPDIR=str(self.root / "partial"))
|
||||
self.rp_started = time.monotonic()
|
||||
with (run / "stdout.log").open("wb") as out, (run / "stderr.log").open("wb") as err:
|
||||
self.rp = subprocess.Popen(command, stdout=out, stderr=err, env=env, start_new_session=True)
|
||||
self.metadata["runs"].append({"path": str(run), "command": command, "started_ms": now_ms(), "pid": self.rp.pid, "ta_versions": ta_versions})
|
||||
self.save()
|
||||
|
||||
def refresh_ta(self, tal: Path, destination: Path) -> dict:
|
||||
"""Existing internal CLI file mode requires an explicit, genuine TA file.
|
||||
|
||||
Refresh from original TAL endpoints before each run, then let the real
|
||||
RP verify the DER/SPKI, validity and trust-anchor profile as usual.
|
||||
"""
|
||||
uris = [line.strip() for line in tal.read_text().splitlines()
|
||||
if line.strip().startswith(("https://", "rsync://"))]
|
||||
uris.sort(key=lambda uri: not uri.startswith("https://"))
|
||||
for uri in uris:
|
||||
if uri.startswith("https://"):
|
||||
event = self.archive.fetch(uri, "object", source="ta_refresh")
|
||||
ref = event.get("body")
|
||||
else:
|
||||
event = {"source": "ta_refresh", "transport": "rsync", "kind": "object", "uri": uri,
|
||||
"started_ms": now_ms(), "complete": False, "objects": {}}
|
||||
ref = None
|
||||
try:
|
||||
with tempfile.TemporaryDirectory(dir=self.root / "partial") as name:
|
||||
result = subprocess.run(["rsync", "-rt", "--contimeout=15", "--timeout=30", "--", uri, name + "/"],
|
||||
capture_output=True, timeout=60)
|
||||
if result.returncode:
|
||||
raise ValueError(result.stderr.decode(errors="replace")[:2000])
|
||||
path = Path(name) / Path(urllib.parse.urlsplit(uri).path).name
|
||||
with path.open("rb") as stream:
|
||||
ref = self.archive.put_stream(stream)
|
||||
event.update(complete=True, objects={uri: ref})
|
||||
except Exception as exc:
|
||||
event["error"] = f"{type(exc).__name__}: {exc}"
|
||||
self.archive.event(event)
|
||||
if event["complete"]:
|
||||
target = destination / (tal.stem + ".cer")
|
||||
target.write_bytes(self.archive.blob_path(ref["sha256"]).read_bytes())
|
||||
return {"path": str(target), "uri": uri, "event_id": event["id"], **ref}
|
||||
raise RuntimeError(f"could not download genuine TA from TAL endpoints: {tal}")
|
||||
|
||||
def check_rp(self) -> None:
|
||||
if self.rp is None:
|
||||
return
|
||||
if time.monotonic() - self.rp_started > self.config.get("rp_timeout_secs", 1800):
|
||||
self.stop_rp()
|
||||
raise RuntimeError("discovery RP exceeded wall-clock timeout")
|
||||
status = self.rp.poll()
|
||||
if status is not None:
|
||||
run = self.metadata["runs"][-1]
|
||||
run.update(exit_code=status, completed_ms=now_ms())
|
||||
self.rp = None
|
||||
self.save()
|
||||
if status != 0:
|
||||
raise RuntimeError(f"real discovery RP failed: {status}")
|
||||
stderr = (Path(run["path"]) / "stderr.log").read_text(errors="replace")
|
||||
anchors = re.findall(r"wrote CIR: .*?trust_anchors=(\d+)", stderr)
|
||||
if not anchors or int(anchors[-1]) != len(self.metadata["tals"]):
|
||||
raise RuntimeError("discovery did not produce a CIR with all five genuine trust anchors")
|
||||
stdout = (Path(run["path"]) / "stdout.log").read_text(errors="replace")
|
||||
counts = {key: int(value) for key, value in re.findall(r"^(vrps|aspas|rrdp_repos_unique|audit_publication_points)=(\d+)$", stdout, re.MULTILINE)}
|
||||
run.update(trust_anchors=int(anchors[-1]), counts=counts)
|
||||
self.save()
|
||||
|
||||
def stop_rp(self) -> None:
|
||||
if self.rp is not None and self.rp.poll() is None:
|
||||
os.killpg(self.rp.pid, signal.SIGTERM)
|
||||
try:
|
||||
self.rp.wait(timeout=10)
|
||||
except subprocess.TimeoutExpired:
|
||||
os.killpg(self.rp.pid, signal.SIGKILL)
|
||||
self.rp.wait(timeout=10)
|
||||
if self.metadata["runs"]:
|
||||
self.metadata["runs"][-1].update(exit_code=self.rp.returncode, completed_ms=now_ms(), stopped_by_controller=True)
|
||||
self.rp = None
|
||||
|
||||
def run(self) -> None:
|
||||
workers = self.config.get("workers", 4)
|
||||
self.start_rp()
|
||||
while self.rp is not None and not self.stopping:
|
||||
self.archive.guard()
|
||||
self.check_rp()
|
||||
self.discover()
|
||||
time.sleep(1)
|
||||
self.discover()
|
||||
if self.stopping:
|
||||
raise RuntimeError("capture stopped during bootstrap")
|
||||
if not self.registry:
|
||||
raise RuntimeError("internal RP discovered no RRDP repositories")
|
||||
normal_contract = read_json(Path(self.metadata["runs"][0]["path"]) / "validation-contract.json")
|
||||
atomic_json(self.root / "contract.json", {"schema": SCHEMA, "binary_sha256": self.metadata["binary_sha256"],
|
||||
"scripts_sha256": self.metadata["scripts_sha256"], "machine": self.metadata["machine"],
|
||||
"tals": self.metadata["tals"], "normal_validation_contract": normal_contract, "rp_args": self.config.get("rp_args", [])})
|
||||
# Bounded bootstrap retries. A partial starting point is never relabelled complete.
|
||||
with ThreadPoolExecutor(max_workers=workers) as pool:
|
||||
for _ in range(self.config.get("bootstrap_attempts", 3)):
|
||||
pending = {pool.submit(self.collector.observe, uri, self.latest.get(uri)): uri
|
||||
for uri in self.registry if not self.latest.get(uri, {}).get("complete")}
|
||||
for future in as_completed(pending):
|
||||
self.latest[pending[future]] = future.result()
|
||||
if all(self.latest.get(uri, {}).get("complete") for uri in self.registry):
|
||||
break
|
||||
t0 = now_ms()
|
||||
initial = select_epoch(self.root, self.registry, t0)
|
||||
atomic_json(self.root / "epochs/epoch_0000.json", initial)
|
||||
self.metadata.update(bootstrap_complete=initial["complete"], bootstrap_missing=initial["missing"],
|
||||
bootstrap_blocked_latest_attempts=initial["blocked_latest_attempts"])
|
||||
if not initial["complete"] and self.config.get("bootstrap_gap_policy", "abort") == "abort":
|
||||
self.metadata.update(status="bootstrap_incomplete", missing=initial["missing"])
|
||||
self.save()
|
||||
return
|
||||
duration = self.config.get("duration_secs", 3600)
|
||||
poll_secs = self.config.get("poll_secs", 60)
|
||||
step_secs = self.config.get("step_secs", 300)
|
||||
self.metadata.update(status="recording" if initial["complete"] else "recording_with_gaps",
|
||||
t0_ms=t0, end_ms=t0 + duration * 1000)
|
||||
self.save()
|
||||
end = time.monotonic() + duration
|
||||
next_rp = time.monotonic() + step_secs
|
||||
due = {uri: time.monotonic() + poll_secs for uri in self.registry}
|
||||
in_flight = {}
|
||||
while time.monotonic() < end and not self.stopping:
|
||||
self.archive.guard()
|
||||
self.check_rp()
|
||||
self.discover()
|
||||
moment = time.monotonic()
|
||||
if moment >= next_rp and self.rp is None:
|
||||
self.start_rp()
|
||||
next_rp = moment + step_secs
|
||||
for uri in self.registry:
|
||||
due.setdefault(uri, moment)
|
||||
if uri not in in_flight and moment >= due[uri]:
|
||||
in_flight[uri] = pool.submit(self.collector.observe, uri, self.latest.get(uri))
|
||||
due[uri] = moment + poll_secs
|
||||
for uri, future in list(in_flight.items()):
|
||||
if future.done():
|
||||
item = future.result()
|
||||
# Keep the last complete base for chain validation after a failed observation.
|
||||
if item["complete"]:
|
||||
self.latest[uri] = item
|
||||
del in_flight[uri]
|
||||
self.save()
|
||||
time.sleep(1)
|
||||
# Requests have per-body deadlines. Drained responses keep their real completion time.
|
||||
for future in in_flight.values():
|
||||
future.result()
|
||||
self.stop_rp()
|
||||
captured_secs = min(duration, max(0, (now_ms() - t0) // 1000))
|
||||
for index, offset in enumerate(range(0, captured_secs + 1, step_secs)):
|
||||
epoch = select_epoch(self.root, self.registry, t0 + offset * 1000)
|
||||
atomic_json(self.root / "epochs" / f"epoch_{index:04d}.json", epoch)
|
||||
status = "recorded" if initial["complete"] else "recorded_with_gaps"
|
||||
self.metadata.update(status="interrupted" if self.stopping else status, finished_ms=now_ms(), repositories=len(self.registry), captured_secs=captured_secs)
|
||||
self.save()
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--config", type=Path, required=True)
|
||||
args = parser.parse_args()
|
||||
capture = Capture(read_json(args.config))
|
||||
def stop(*_):
|
||||
capture.stopping = True
|
||||
signal.signal(signal.SIGTERM, stop)
|
||||
signal.signal(signal.SIGINT, stop)
|
||||
try:
|
||||
capture.run()
|
||||
except Exception as exc:
|
||||
capture.metadata.update(status="failed", error=f"{type(exc).__name__}: {exc}", finished_ms=now_ms())
|
||||
raise
|
||||
finally:
|
||||
capture.stop_rp()
|
||||
capture.save()
|
||||
return 0 if capture.metadata["status"] in ("recorded", "recorded_with_gaps") else 2
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
194
scripts/experiments/reuse_eval/common.py
Normal file
194
scripts/experiments/reuse_eval/common.py
Normal file
@@ -0,0 +1,194 @@
|
||||
"""Immutable transport capture primitives shared by collection and replay."""
|
||||
from __future__ import annotations
|
||||
|
||||
import gzip
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import tempfile
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
import uuid
|
||||
|
||||
SCHEMA = "rpki-transport-capture-v1"
|
||||
HEADERS = ("etag", "last-modified", "content-type", "content-length", "content-encoding", "date", "location")
|
||||
|
||||
|
||||
def now_ms() -> int:
|
||||
return time.time_ns() // 1_000_000
|
||||
|
||||
|
||||
def atomic_json(path: Path, value: object) -> None:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
fd, name = tempfile.mkstemp(prefix=".pending-", dir=path.parent)
|
||||
try:
|
||||
with os.fdopen(fd, "w", encoding="utf-8") as stream:
|
||||
json.dump(value, stream, sort_keys=True, separators=(",", ":"), ensure_ascii=True)
|
||||
stream.flush()
|
||||
os.replace(name, path)
|
||||
finally:
|
||||
Path(name).unlink(missing_ok=True)
|
||||
|
||||
|
||||
def read_json(path: Path) -> object:
|
||||
return json.loads(path.read_text(encoding="utf-8"))
|
||||
|
||||
|
||||
def digest_bytes(data: bytes) -> str:
|
||||
return hashlib.sha256(data).hexdigest()
|
||||
|
||||
|
||||
def file_sha256(path: Path) -> str:
|
||||
with path.open("rb") as stream:
|
||||
return hashlib.file_digest(stream, "sha256").hexdigest()
|
||||
|
||||
|
||||
def origin(uri: str) -> tuple[str, str, int]:
|
||||
url = urllib.parse.urlsplit(uri)
|
||||
if url.scheme not in ("http", "https") or not url.hostname or url.username or url.password or url.fragment:
|
||||
raise ValueError(f"invalid HTTP URI: {uri}")
|
||||
return url.scheme, url.hostname.lower(), url.port or (443 if url.scheme == "https" else 80)
|
||||
|
||||
|
||||
class SameOriginRedirect(urllib.request.HTTPRedirectHandler):
|
||||
def __init__(self, allowed: tuple[str, str, int]):
|
||||
self.allowed = allowed
|
||||
|
||||
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
||||
if origin(newurl) != self.allowed:
|
||||
raise ValueError(f"cross-origin redirect rejected: {newurl}")
|
||||
return super().redirect_request(req, fp, code, msg, headers, newurl)
|
||||
|
||||
|
||||
class TaRedirect(urllib.request.HTTPRedirectHandler):
|
||||
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
||||
if origin(newurl)[0] != "https":
|
||||
raise ValueError("TA redirect downgraded HTTPS")
|
||||
return super().redirect_request(req, fp, code, msg, headers, newurl)
|
||||
|
||||
|
||||
class Archive:
|
||||
def __init__(self, root: Path, limits: dict | None = None, *, read_only: bool = False):
|
||||
self.root = root
|
||||
self.limits = limits or {}
|
||||
self.read_only = read_only
|
||||
self.initial_free = shutil.disk_usage(root.parent).free
|
||||
if not read_only:
|
||||
for name in ("blobs/sha256", "events", "partial", "observations", "views", "epochs"):
|
||||
(root / name).mkdir(parents=True, exist_ok=True)
|
||||
|
||||
def guard(self) -> None:
|
||||
if self.read_only:
|
||||
raise ValueError("archive is read-only")
|
||||
free = shutil.disk_usage(self.root).free
|
||||
if free < self.limits.get("min_free_bytes", 0):
|
||||
raise RuntimeError(f"archive disk guard: {free} bytes free")
|
||||
if self.initial_free - free > self.limits.get("max_growth_bytes", 200 * 1024**3):
|
||||
raise RuntimeError("capture total disk-growth budget exceeded")
|
||||
if os.statvfs("/").f_favail < self.limits.get("min_root_free_inodes", 0):
|
||||
raise RuntimeError("root filesystem inode guard")
|
||||
|
||||
def blob_path(self, sha256: str) -> Path:
|
||||
if len(sha256) != 64 or any(c not in "0123456789abcdef" for c in sha256):
|
||||
raise ValueError("invalid SHA-256")
|
||||
return self.root / "blobs/sha256" / sha256[:2] / sha256
|
||||
|
||||
def put_stream(self, stream) -> dict:
|
||||
self.guard()
|
||||
maximum = self.limits.get("max_body_bytes", 2 * 1024**3)
|
||||
deadline = time.monotonic() + self.limits.get("body_deadline_secs", 240)
|
||||
fd, name = tempfile.mkstemp(dir=self.root / "partial")
|
||||
digest, size = hashlib.sha256(), 0
|
||||
try:
|
||||
with os.fdopen(fd, "wb") as output:
|
||||
while True:
|
||||
chunk = stream.read(65536)
|
||||
if not chunk:
|
||||
break
|
||||
size += len(chunk)
|
||||
if size > maximum or time.monotonic() > deadline:
|
||||
raise ValueError("body size or wall-clock limit exceeded")
|
||||
digest.update(chunk)
|
||||
output.write(chunk)
|
||||
sha256 = digest.hexdigest()
|
||||
path = self.blob_path(sha256)
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
if path.exists():
|
||||
Path(name).unlink()
|
||||
else:
|
||||
os.replace(name, path)
|
||||
return {"sha256": sha256, "size": size}
|
||||
finally:
|
||||
Path(name).unlink(missing_ok=True)
|
||||
|
||||
def event(self, value: dict) -> dict:
|
||||
if self.read_only:
|
||||
raise ValueError("archive is read-only")
|
||||
value.setdefault("schema", SCHEMA)
|
||||
value.setdefault("id", str(uuid.uuid4()))
|
||||
value.setdefault("completed_ms", now_ms())
|
||||
atomic_json(self.root / "events" / f"{value['id']}.json", value)
|
||||
return value
|
||||
|
||||
def fetch(self, uri: str, kind: str, previous: dict | None = None, source: str = "poller") -> dict:
|
||||
"""Keep failed requests; 304 explicitly binds the prior entity hash."""
|
||||
self.guard()
|
||||
allowed = origin(uri)
|
||||
if allowed[0] != "https" and not self.limits.get("allow_test_http", False):
|
||||
raise ValueError("live capture requires HTTPS")
|
||||
event = {"source": source, "transport": "http", "kind": kind,
|
||||
"uri": uri, "started_ms": now_ms(), "complete": False}
|
||||
headers = {"User-Agent": "panda-rpki-evaluation-recorder/1", "Accept-Encoding": "identity"}
|
||||
if previous:
|
||||
old_headers = previous.get("headers", {})
|
||||
if old_headers.get("etag"):
|
||||
headers["If-None-Match"] = old_headers["etag"]
|
||||
if old_headers.get("last-modified"):
|
||||
headers["If-Modified-Since"] = old_headers["last-modified"]
|
||||
request = urllib.request.Request(uri, headers=headers)
|
||||
# Ignore machine proxy variables: record direct origin traffic on 186.
|
||||
redirect = TaRedirect() if kind == "object" else SameOriginRedirect(allowed)
|
||||
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}), redirect)
|
||||
try:
|
||||
try:
|
||||
response = opener.open(request, timeout=self.limits.get("request_timeout_secs", 30))
|
||||
except urllib.error.HTTPError as exc:
|
||||
response = exc
|
||||
with response:
|
||||
event.update(status=response.code, final_uri=response.url,
|
||||
headers={k: response.headers[k] for k in HEADERS if k in response.headers})
|
||||
if response.code == 304:
|
||||
if not previous or not previous.get("body"):
|
||||
raise ValueError("304 without a prior body")
|
||||
if not self.blob_path(previous["body"]["sha256"]).is_file():
|
||||
raise ValueError("304 prior body is missing")
|
||||
event.update(body=previous["body"], prior_event_id=previous["id"], complete=True)
|
||||
elif response.code == 200:
|
||||
encoding = response.headers.get("Content-Encoding", "identity").lower()
|
||||
if encoding not in ("identity", "gzip"):
|
||||
raise ValueError(f"unsupported content encoding: {encoding}")
|
||||
body = gzip.GzipFile(fileobj=response) if encoding == "gzip" else response
|
||||
blob = self.put_stream(body)
|
||||
if encoding == "identity" and response.headers.get("Content-Length") is not None:
|
||||
if blob["size"] != int(response.headers["Content-Length"]):
|
||||
raise ValueError("truncated HTTP entity")
|
||||
event.update(body=blob, complete=True)
|
||||
else:
|
||||
raise ValueError(f"HTTP {response.code}")
|
||||
except Exception as exc:
|
||||
event["error"] = f"{type(exc).__name__}: {exc}"
|
||||
return self.event(event)
|
||||
|
||||
def verify_blob(self, ref: dict) -> None:
|
||||
path = self.blob_path(ref["sha256"])
|
||||
digest, size = hashlib.sha256(), 0
|
||||
with path.open("rb") as stream:
|
||||
for chunk in iter(lambda: stream.read(1024 * 1024), b""):
|
||||
digest.update(chunk)
|
||||
size += len(chunk)
|
||||
if digest.hexdigest() != ref["sha256"] or size != ref["size"]:
|
||||
raise ValueError(f"corrupt archive blob: {ref['sha256']}")
|
||||
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
|
||||
46
scripts/experiments/reuse_eval/preflight.py
Normal file
46
scripts/experiments/reuse_eval/preflight.py
Normal file
@@ -0,0 +1,46 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Read-only resource checks for the allocated capture host."""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
|
||||
from common import atomic_json, now_ms, read_json
|
||||
|
||||
|
||||
def preflight(config: dict) -> dict:
|
||||
root = Path(config["run_root"]).resolve()
|
||||
if not root.is_dir():
|
||||
raise ValueError(f"create allocated run_root before preflight: {root}")
|
||||
disk = shutil.disk_usage(root)
|
||||
root_stats = os.statvfs("/")
|
||||
checks = {"data_free": disk.free >= config.get("limits", {}).get("min_free_bytes", 150 * 1024**3),
|
||||
"data_utilization": disk.used / disk.total < 0.8,
|
||||
"root_inode_margin": root_stats.f_favail >= 10000,
|
||||
"rsync_available": shutil.which("rsync") is not None,
|
||||
"binary_available": Path(config["binary"]).is_file(),
|
||||
"all_five_tals": len(config["tals"]) == 5 and all(Path(t).is_file() for t in config["tals"])}
|
||||
service = subprocess.run(["systemctl", "is-active", "panda-rpki.service"], capture_output=True, text=True, timeout=10)
|
||||
checks["old_panda_inactive"] = service.stdout.strip() == "inactive"
|
||||
return {"at_ms": now_ms(), "host": os.uname().nodename, "pass": all(checks.values()), "checks": checks,
|
||||
"data_total": disk.total, "data_free": disk.free, "root_free_inodes": root_stats.f_favail,
|
||||
"cpus": os.cpu_count(), "panda_state": service.stdout.strip(), "config": config}
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--config", type=Path, required=True)
|
||||
parser.add_argument("--out", type=Path, required=True)
|
||||
args = parser.parse_args()
|
||||
result = preflight(read_json(args.config))
|
||||
atomic_json(args.out, result)
|
||||
print(json.dumps(result))
|
||||
return 0 if result["pass"] else 2
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
219
scripts/experiments/reuse_eval/prepare_replay.py
Normal file
219
scripts/experiments/reuse_eval/prepare_replay.py
Normal file
@@ -0,0 +1,219 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Prepare immutable epoch assets and an isolated pair of network namespaces."""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import ipaddress
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import urllib.parse
|
||||
|
||||
from common import atomic_json, file_sha256, read_json
|
||||
from serve import ReplayState
|
||||
|
||||
|
||||
def command(*args: str) -> None:
|
||||
subprocess.run(args, check=True, timeout=30, capture_output=True, text=True)
|
||||
|
||||
|
||||
def all_hosts(root: Path) -> list[str]:
|
||||
hosts = set()
|
||||
def add(uri):
|
||||
url = urllib.parse.urlsplit(uri)
|
||||
host = url.hostname
|
||||
if not host:
|
||||
raise ValueError(f"missing host: {uri}")
|
||||
host = host.encode("idna").decode("ascii").lower()
|
||||
if ":" in host:
|
||||
raise ValueError("IPv6 literal URI requires an explicit additional replay mapping")
|
||||
if not re.fullmatch(r"[a-z0-9.-]+", host):
|
||||
raise ValueError(f"unsafe hostname: {host}")
|
||||
hosts.add(host)
|
||||
for path in (root / "events").glob("*.json"):
|
||||
add(read_json(path)["uri"])
|
||||
for path in (root / "observations").glob("*.json"):
|
||||
for ref in read_json(path).get("references", []):
|
||||
add(ref["uri"])
|
||||
if len(hosts) > 1000:
|
||||
raise ValueError("host mapping count bound")
|
||||
return sorted(hosts)
|
||||
|
||||
|
||||
def host_mapping(hosts: list[str]) -> dict[str, str]:
|
||||
result = {}
|
||||
for index, host in enumerate(hosts, 1):
|
||||
try:
|
||||
address = ipaddress.ip_address(host)
|
||||
if address.version != 4 or address.is_loopback or address.is_unspecified or address.is_multicast:
|
||||
raise ValueError("unsupported literal origin address")
|
||||
result[host] = str(address)
|
||||
except ValueError as exc:
|
||||
if re.fullmatch(r"[0-9.]+", host):
|
||||
raise ValueError(f"invalid/unsupported literal address: {host}") from exc
|
||||
result[host] = str(ipaddress.ip_address("10.187.1.0") + index)
|
||||
return result
|
||||
|
||||
|
||||
def tls_assets(output: Path, hosts: list[str]) -> dict:
|
||||
tls = output / "tls"
|
||||
tls.mkdir(parents=True, exist_ok=True)
|
||||
host_file = tls / "hosts.json"
|
||||
if host_file.exists():
|
||||
if read_json(host_file) != hosts:
|
||||
raise ValueError("archive hosts changed after TLS freeze; use a new replay root")
|
||||
return {"ca": str(tls / "ca.pem"), "cert": str(tls / "server.pem"), "key": str(tls / "server.key")}
|
||||
if any(tls.iterdir()):
|
||||
raise ValueError("partial TLS setup exists; inspect it before retrying")
|
||||
san = []
|
||||
for host in hosts:
|
||||
try:
|
||||
ipaddress.ip_address(host)
|
||||
san.append("IP:" + host)
|
||||
except ValueError:
|
||||
san.append("DNS:" + host)
|
||||
ext = tls / "server.ext"
|
||||
ext.write_text("basicConstraints=critical,CA:FALSE\nkeyUsage=critical,digitalSignature,keyEncipherment\nextendedKeyUsage=serverAuth\nsubjectAltName=" + ",".join(san) + "\n")
|
||||
command("openssl", "req", "-x509", "-newkey", "rsa:2048", "-nodes", "-keyout", str(tls / "ca.key"),
|
||||
"-out", str(tls / "ca.pem"), "-days", "30", "-subj", "/CN=RPKI-187 transport experiment CA",
|
||||
"-addext", "basicConstraints=critical,CA:TRUE", "-addext", "keyUsage=critical,keyCertSign,cRLSign")
|
||||
command("openssl", "req", "-new", "-newkey", "rsa:2048", "-nodes", "-keyout", str(tls / "server.key"),
|
||||
"-out", str(tls / "server.csr"), "-subj", "/CN=RPKI-187 replay")
|
||||
command("openssl", "x509", "-req", "-in", str(tls / "server.csr"), "-CA", str(tls / "ca.pem"),
|
||||
"-CAkey", str(tls / "ca.key"), "-CAcreateserial", "-out", str(tls / "server.pem"),
|
||||
"-days", "30", "-extfile", str(ext))
|
||||
for key in (tls / "ca.key", tls / "server.key"):
|
||||
key.chmod(0o600)
|
||||
atomic_json(host_file, hosts)
|
||||
return {"ca": str(tls / "ca.pem"), "cert": str(tls / "server.pem"), "key": str(tls / "server.key")}
|
||||
|
||||
|
||||
def rsync_tree(state: ReplayState, output: Path, mapping: dict) -> list[str]:
|
||||
views, origins = {}, {}
|
||||
for event in sorted(state.rsync_events, key=lambda e: e["completed_ms"]):
|
||||
parsed_scope = urllib.parse.urlsplit(event["uri"])
|
||||
scope_parts = parsed_scope.path.lstrip("/").split("/")
|
||||
module = scope_parts[0]
|
||||
if module in ("", ".", "..") or not re.fullmatch(r"[a-zA-Z0-9_.-]+", module):
|
||||
raise ValueError("unsafe/missing rsync scope module")
|
||||
key = (parsed_scope.hostname.lower(), parsed_scope.port or 873)
|
||||
origins.setdefault(key, set()).add(module)
|
||||
(output / f"{key[0]}-{key[1]}" / "modules" / module).mkdir(parents=True, exist_ok=True)
|
||||
if event["kind"] == "view":
|
||||
for uri in list(views):
|
||||
if uri.startswith(event["uri"]):
|
||||
del views[uri]
|
||||
views.update(event["objects"])
|
||||
for uri, ref in views.items():
|
||||
parsed = urllib.parse.urlsplit(uri)
|
||||
parts = parsed.path.lstrip("/").split("/")
|
||||
if parsed.scheme != "rsync" or parsed.username or parsed.password or parsed.query or parsed.fragment:
|
||||
raise ValueError("invalid rsync object origin")
|
||||
if len(parts) < 2 or any(p in ("", ".", "..") or "\x00" in p or "\\" in p for p in parts):
|
||||
raise ValueError(f"unsafe rsync publication path: {uri}")
|
||||
hostname, port = parsed.hostname.lower(), parsed.port or 873
|
||||
key = (hostname, port)
|
||||
root = output / f"{hostname}-{port}"
|
||||
module = parts[0]
|
||||
if not re.fullmatch(r"[a-zA-Z0-9_.-]+", module):
|
||||
raise ValueError("unsafe rsync module name")
|
||||
path = root / "modules" / Path(*parts)
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
source = state.archive.blob_path(ref["sha256"])
|
||||
if source.stat().st_size != ref["size"]:
|
||||
raise ValueError("rsync blob size mismatch")
|
||||
if not path.exists():
|
||||
# A hard link followed by chmod also changes the archived inode.
|
||||
shutil.copyfile(source, path)
|
||||
path.chmod(0o444)
|
||||
origins.setdefault(key, set()).add(module)
|
||||
configs = []
|
||||
for (hostname, port), modules in origins.items():
|
||||
root = output / f"{hostname}-{port}"
|
||||
config = root / "rsyncd.conf"
|
||||
lines = [f"address = {mapping[hostname]}", f"port = {port}", "use chroot = no", "read only = yes",
|
||||
"uid = 65534", "gid = 65534", f"pid file = {root}/rsyncd.pid", f"lock file = {root}/rsyncd.lock",
|
||||
f"log file = {root}/rsyncd.log", "max connections = 16"]
|
||||
for module in sorted(modules):
|
||||
lines += [f"[{module}]", f"path = {root}/modules/{module}"]
|
||||
config.write_text("\n".join(lines) + "\n")
|
||||
configs.append(str(config))
|
||||
return configs
|
||||
|
||||
|
||||
def create_network(mapping: dict) -> None:
|
||||
existing = subprocess.run(["ip", "netns", "list"], capture_output=True, text=True, check=True, timeout=10).stdout
|
||||
names = {line.split()[0] for line in existing.splitlines() if line}
|
||||
if names.intersection({"rp187srv", "rp187rp"}) or Path("/etc/netns/rp187rp").exists():
|
||||
raise ValueError("experiment namespace/name already exists; inspect before replacing")
|
||||
created = []
|
||||
try:
|
||||
for name in ("rp187srv", "rp187rp"):
|
||||
command("ip", "netns", "add", name)
|
||||
created.append(name)
|
||||
command("ip", "-n", "rp187srv", "link", "add", "r187s", "type", "veth", "peer", "name", "r187r", "netns", "rp187rp")
|
||||
for name, dev, address in (("rp187srv", "r187s", "10.187.0.1/16"), ("rp187rp", "r187r", "10.187.0.2/16")):
|
||||
command("ip", "-n", name, "addr", "add", address, "dev", dev)
|
||||
command("ip", "-n", name, "link", "set", dev, "up")
|
||||
command("ip", "-n", name, "link", "set", "lo", "up")
|
||||
for address in sorted(set(mapping.values())):
|
||||
if address in ("10.187.0.1", "10.187.0.2"):
|
||||
raise ValueError("literal origin collides with namespace gateway")
|
||||
command("ip", "-n", "rp187srv", "addr", "add", address + "/32", "dev", "lo")
|
||||
if ipaddress.ip_address(address) not in ipaddress.ip_network("10.187.0.0/16"):
|
||||
command("ip", "-n", "rp187rp", "route", "add", address + "/32", "via", "10.187.0.1")
|
||||
folder = Path("/etc/netns/rp187rp")
|
||||
folder.mkdir(parents=True)
|
||||
(folder / "hosts").write_text("127.0.0.1 localhost\n" + "".join(f"{address} {host}\n" for host, address in sorted(mapping.items())))
|
||||
(folder / "resolv.conf").write_text("nameserver 127.0.0.1\noptions timeout:1 attempts:1\n")
|
||||
except Exception:
|
||||
for name in reversed(created):
|
||||
subprocess.run(["ip", "netns", "delete", name], capture_output=True, timeout=10)
|
||||
if created and Path("/etc/netns/rp187rp").exists():
|
||||
shutil.rmtree("/etc/netns/rp187rp")
|
||||
raise
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--archive", type=Path, required=True)
|
||||
parser.add_argument("--epoch", type=Path, required=True)
|
||||
parser.add_argument("--scope", type=Path)
|
||||
parser.add_argument("--out", type=Path, required=True)
|
||||
parser.add_argument("--create-network", action="store_true")
|
||||
args = parser.parse_args()
|
||||
if args.scope:
|
||||
from scope import require_closure
|
||||
require_closure(args.archive, args.scope)
|
||||
state = ReplayState(args.archive, args.epoch, args.scope)
|
||||
hosts = all_hosts(args.archive)
|
||||
mapping = host_mapping(hosts)
|
||||
args.out.mkdir(parents=True, exist_ok=True)
|
||||
tls = tls_assets(args.out, hosts)
|
||||
epoch_root = args.out / state.epoch_hash
|
||||
if epoch_root.exists():
|
||||
raise ValueError("epoch assets already exist; reuse their manifest or choose a new output")
|
||||
epoch_root.mkdir()
|
||||
configs = rsync_tree(state, epoch_root / "rsync", mapping)
|
||||
http_ports = sorted({key[2] for key in state.entries if key[0] == "http"})
|
||||
https_ports = sorted({key[2] for key in state.entries if key[0] == "https"})
|
||||
http_ports = sorted(set(http_ports) | {key[2] for key in state.failures if key[0] == "http"})
|
||||
https_ports = sorted(set(https_ports) | {key[2] for key in state.failures if key[0] == "https"})
|
||||
if set(http_ports).intersection(https_ports):
|
||||
raise ValueError("HTTP and HTTPS share a port; explicit origin-specific listeners required")
|
||||
manifest = {"epoch": state.epoch_hash, "archive": str(args.archive), "epoch_path": str(args.epoch),
|
||||
"hosts": mapping, "tls": tls, "rsync_configs": configs, "http_ports": http_ports, "https_ports": https_ports,
|
||||
"server_namespace": "rp187srv", "rp_namespace": "rp187rp", "server_cpus": "0", "rp_cpus": "1-3"}
|
||||
if args.scope:
|
||||
manifest.update(scope_path=str(args.scope.resolve()), scope_sha256=file_sha256(args.scope))
|
||||
atomic_json(epoch_root / "replay.json", manifest)
|
||||
if args.create_network:
|
||||
create_network(mapping)
|
||||
print(json.dumps(manifest))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
142
scripts/experiments/reuse_eval/rrdp.py
Normal file
142
scripts/experiments/reuse_eval/rrdp.py
Normal file
@@ -0,0 +1,142 @@
|
||||
"""Validate recorded RRDP references and object update semantics without resigning."""
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
import urllib.parse
|
||||
import xml.etree.ElementTree as ET
|
||||
|
||||
from common import origin
|
||||
|
||||
NS = "{http://www.ripe.net/rpki/rrdp}"
|
||||
SHA256 = re.compile(r"^[0-9a-fA-F]{64}$")
|
||||
|
||||
|
||||
def positive(value: str) -> int:
|
||||
if not value.isascii() or not value.isdecimal() or int(value) < 1:
|
||||
raise ValueError(f"invalid positive serial: {value}")
|
||||
return int(value)
|
||||
|
||||
|
||||
def checked_hash(value: str) -> str:
|
||||
if not SHA256.fullmatch(value):
|
||||
raise ValueError("invalid reference SHA-256")
|
||||
return value.lower()
|
||||
|
||||
|
||||
def safe_xml(path: Path) -> None:
|
||||
"""Reject non-ASCII/DTD before parsing, without loading a large snapshot."""
|
||||
tail = b""
|
||||
with path.open("rb") as stream:
|
||||
for chunk in iter(lambda: stream.read(1024 * 1024), b""):
|
||||
chunk.decode("ascii")
|
||||
combined = tail + chunk
|
||||
if b"<!DOCTYPE" in combined or b"<!ENTITY" in combined:
|
||||
raise ValueError("DTD/entities are forbidden in RRDP")
|
||||
tail = combined[-16:]
|
||||
|
||||
|
||||
def notification(path: Path, uri: str, max_refs: int = 10000) -> dict:
|
||||
if path.stat().st_size > 8 * 1024**2:
|
||||
raise ValueError("notification size limit")
|
||||
safe_xml(path)
|
||||
root = ET.parse(path).getroot()
|
||||
if root.tag != NS + "notification" or root.attrib.get("version") != "1":
|
||||
raise ValueError("invalid notification root/version")
|
||||
import uuid
|
||||
session = str(uuid.UUID(root.attrib["session_id"]))
|
||||
serial = positive(root.attrib["serial"])
|
||||
refs, seen, snapshots = [], set(), 0
|
||||
for child in root:
|
||||
if child.tag not in (NS + "snapshot", NS + "delta"):
|
||||
raise ValueError("unknown notification child")
|
||||
kind = child.tag.removeprefix(NS)
|
||||
target = child.attrib["uri"]
|
||||
if origin(target) != origin(uri):
|
||||
raise ValueError("cross-origin notification reference")
|
||||
ref = {"kind": kind, "uri": target, "sha256": checked_hash(child.attrib["hash"])}
|
||||
if kind == "snapshot":
|
||||
snapshots += 1
|
||||
ref["serial"] = serial
|
||||
else:
|
||||
ref["serial"] = positive(child.attrib["serial"])
|
||||
if ref["serial"] > serial or ref["serial"] in seen:
|
||||
raise ValueError("duplicate/future delta serial")
|
||||
seen.add(ref["serial"])
|
||||
refs.append(ref)
|
||||
if len(refs) > max_refs:
|
||||
raise ValueError("notification reference limit")
|
||||
if snapshots != 1:
|
||||
raise ValueError("notification must contain exactly one snapshot")
|
||||
return {"session": session, "serial": serial, "references": refs}
|
||||
|
||||
|
||||
def object_uri(value: str) -> str:
|
||||
parsed = urllib.parse.urlsplit(value)
|
||||
if parsed.scheme != "rsync" or not parsed.hostname or parsed.username or parsed.password or parsed.fragment or parsed.query:
|
||||
raise ValueError(f"invalid publication URI: {value}")
|
||||
if not parsed.path or parsed.path.endswith("/"):
|
||||
raise ValueError("publication URI must name an object")
|
||||
return value
|
||||
|
||||
|
||||
def payload_view(path: Path, kind: str, session: str, serial: int,
|
||||
base: dict[str, str] | None = None, max_objects: int = 2_000_000) -> dict[str, str]:
|
||||
safe_xml(path)
|
||||
view = {} if kind == "snapshot" else dict(base or {})
|
||||
iterator = ET.iterparse(path, events=("start", "end"))
|
||||
_, root = next(iterator)
|
||||
if (root.tag != NS + kind or root.attrib.get("version") != "1"
|
||||
or root.attrib.get("session_id", "").lower() != session
|
||||
or positive(root.attrib["serial"]) != serial):
|
||||
raise ValueError(f"{kind} session/serial/version mismatch")
|
||||
seen, depth = set(), 0
|
||||
for event, element in iterator:
|
||||
if event == "start":
|
||||
depth += 1
|
||||
if depth > 1:
|
||||
raise ValueError("nested RRDP payload element")
|
||||
continue
|
||||
if element is root:
|
||||
break
|
||||
uri = object_uri(element.attrib["uri"])
|
||||
if kind == "snapshot" and uri in seen:
|
||||
raise ValueError("duplicate URI in RRDP payload")
|
||||
seen.add(uri)
|
||||
if len(seen) > max_objects:
|
||||
raise ValueError("object count limit")
|
||||
if element.tag == NS + "publish":
|
||||
previous = element.attrib.get("hash")
|
||||
if kind == "snapshot" and previous is not None:
|
||||
raise ValueError("snapshot publish has previous hash")
|
||||
if kind == "delta":
|
||||
if previous is None and uri in view:
|
||||
raise ValueError("delta adds existing object")
|
||||
if previous is not None and view.get(uri) != checked_hash(previous):
|
||||
raise ValueError("delta replacement previous hash mismatch")
|
||||
encoded = "".join((element.text or "").split())
|
||||
raw = base64.b64decode(encoded, validate=True)
|
||||
if not raw:
|
||||
raise ValueError("empty publish")
|
||||
view[uri] = hashlib.sha256(raw).hexdigest()
|
||||
elif element.tag == NS + "withdraw" and kind == "delta":
|
||||
if view.get(uri) != checked_hash(element.attrib["hash"]):
|
||||
raise ValueError("delta withdrawal previous hash mismatch")
|
||||
del view[uri]
|
||||
else:
|
||||
raise ValueError("invalid RRDP payload element")
|
||||
depth -= 1
|
||||
element.clear()
|
||||
root.clear()
|
||||
return view
|
||||
|
||||
|
||||
def view_digest(view: dict[str, str]) -> str:
|
||||
digest = hashlib.sha256()
|
||||
for uri, hash_value in sorted(view.items()):
|
||||
digest.update(json.dumps([uri, hash_value], separators=(",", ":")).encode("ascii"))
|
||||
digest.update(b"\n")
|
||||
return digest.hexdigest()
|
||||
57
scripts/experiments/reuse_eval/run_server.py
Normal file
57
scripts/experiments/reuse_eval/run_server.py
Normal file
@@ -0,0 +1,57 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Run HTTP(S) and origin-separated read-only rsync daemons in the server namespace."""
|
||||
import argparse
|
||||
from pathlib import Path
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
|
||||
from common import file_sha256, read_json
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--manifest", type=Path, required=True)
|
||||
parser.add_argument("--log", type=Path, required=True)
|
||||
parser.add_argument("--ready", type=Path, required=True)
|
||||
args = parser.parse_args()
|
||||
if args.ready.exists():
|
||||
raise ValueError("stale/live readiness file exists; inspect the old server first")
|
||||
manifest = read_json(args.manifest)
|
||||
command = [sys.executable, str(Path(__file__).with_name("serve.py")), "--archive", manifest["archive"],
|
||||
"--epoch", manifest["epoch_path"], "--bind", "0.0.0.0", "--cert", manifest["tls"]["cert"],
|
||||
"--key", manifest["tls"]["key"], "--log", str(args.log), "--ready", str(args.ready)]
|
||||
if manifest.get("scope_path"):
|
||||
if file_sha256(Path(manifest["scope_path"])) != manifest["scope_sha256"]:
|
||||
raise ValueError("replay scope changed since asset preparation")
|
||||
command += ["--scope", manifest["scope_path"]]
|
||||
for scheme in ("http", "https"):
|
||||
for port in manifest[scheme + "_ports"]:
|
||||
command += ["--" + scheme + "-port", str(port)]
|
||||
children = []
|
||||
stopped = threading.Event()
|
||||
signal.signal(signal.SIGTERM, lambda *_: stopped.set())
|
||||
signal.signal(signal.SIGINT, lambda *_: stopped.set())
|
||||
try:
|
||||
for config in manifest["rsync_configs"]:
|
||||
children.append(subprocess.Popen(["rsync", "--daemon", "--no-detach", "--config", config]))
|
||||
children.append(subprocess.Popen(command))
|
||||
while not stopped.wait(0.2):
|
||||
if any(child.poll() is not None for child in children):
|
||||
raise RuntimeError("a replay child exited unexpectedly")
|
||||
finally:
|
||||
for child in reversed(children):
|
||||
if child.poll() is None:
|
||||
child.terminate()
|
||||
for child in children:
|
||||
try:
|
||||
child.wait(timeout=10)
|
||||
except subprocess.TimeoutExpired:
|
||||
child.kill()
|
||||
child.wait(timeout=5)
|
||||
args.ready.unlink(missing_ok=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
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()
|
||||
449
scripts/experiments/reuse_eval/sequence_matrix.py
Normal file
449
scripts/experiments/reuse_eval/sequence_matrix.py
Normal file
@@ -0,0 +1,449 @@
|
||||
#!/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()
|
||||
182
scripts/experiments/reuse_eval/serve.py
Normal file
182
scripts/experiments/reuse_eval/serve.py
Normal file
@@ -0,0 +1,182 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Serve one immutable epoch using archived entity bytes, without upstream access."""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
import json
|
||||
from pathlib import Path
|
||||
import signal
|
||||
import ssl
|
||||
import threading
|
||||
import urllib.parse
|
||||
|
||||
from common import Archive, atomic_json, digest_bytes, file_sha256, now_ms, origin, read_json
|
||||
|
||||
|
||||
def uri_key(uri: str) -> tuple:
|
||||
scheme, hostname, port = origin(uri)
|
||||
parsed = urllib.parse.urlsplit(uri)
|
||||
return scheme, hostname, port, parsed.path or "/", parsed.query
|
||||
|
||||
|
||||
class ReplayState:
|
||||
def __init__(self, root: Path, epoch_path: Path, scope_path: Path | None = None):
|
||||
self.archive = Archive(root, read_only=True)
|
||||
self.epoch_path = epoch_path
|
||||
self.epoch_hash = digest_bytes(epoch_path.read_bytes())
|
||||
self.epoch = read_json(epoch_path)
|
||||
if self.epoch.get("contract_sha256"):
|
||||
if file_sha256(root / "contract.json") != self.epoch["contract_sha256"]:
|
||||
raise ValueError("capture contract hash mismatch")
|
||||
self.scope = None
|
||||
self.scope_hash = None
|
||||
self.failures = {}
|
||||
if scope_path is not None:
|
||||
from scope import select_epoch
|
||||
self.scope = select_epoch(root, scope_path, epoch_path)
|
||||
self.scope_hash = file_sha256(scope_path)
|
||||
self.failures = {uri_key(uri): 503 for uri in self.scope["excluded_repositories"]}
|
||||
self.failures.update({uri_key(uri): route["http_status"]
|
||||
for uri, route in self.scope["routes"].get(epoch_path.name, {}).items()})
|
||||
if not self.epoch["complete"] and self.scope is None:
|
||||
raise ValueError("cannot serve an incomplete epoch")
|
||||
self.entries = {}
|
||||
for uri, binding in self.epoch["repositories"].items():
|
||||
observation = read_json(root / "observations" / f"{binding['id']}.json")
|
||||
if not observation["complete"] or observation["completed_ms"] > self.epoch["validation_time_ms"]:
|
||||
raise ValueError("incomplete/future observation")
|
||||
if any(observation[key] != binding[key] for key in ("session", "serial", "notification", "view", "completed_ms")):
|
||||
raise ValueError("epoch binding mismatch")
|
||||
self.add(uri, binding["notification"], "application/xml")
|
||||
for ref in observation["references"]:
|
||||
if ref["available"]:
|
||||
self.add(ref["uri"], {"sha256": ref["sha256"], "size": ref["size"]}, "application/xml")
|
||||
self.rsync_events = []
|
||||
for uri, event_id in self.epoch["ta_object_events"].items():
|
||||
event = read_json(root / "events" / f"{event_id}.json")
|
||||
self.check_event(event, uri)
|
||||
if event["transport"] == "http":
|
||||
self.add(uri, event["body"], "application/octet-stream")
|
||||
else:
|
||||
self.rsync_events.append(event)
|
||||
for uri, event_id in self.epoch["rsync_view_events"].items():
|
||||
event = read_json(root / "events" / f"{event_id}.json")
|
||||
self.check_event(event, uri)
|
||||
self.rsync_events.append(event)
|
||||
|
||||
def check_event(self, event: dict, uri: str) -> None:
|
||||
if event["uri"] != uri or not event["complete"] or event["completed_ms"] > self.epoch["validation_time_ms"]:
|
||||
raise ValueError("invalid selected transport event")
|
||||
|
||||
def add(self, uri: str, ref: dict, content_type: str) -> None:
|
||||
key = uri_key(uri)
|
||||
existing = self.entries.get(key)
|
||||
if existing and existing["sha256"] != ref["sha256"]:
|
||||
raise ValueError(f"conflicting contents for one epoch URI: {uri}")
|
||||
path = self.archive.blob_path(ref["sha256"])
|
||||
if not path.is_file() or path.stat().st_size != ref["size"]:
|
||||
raise ValueError(f"missing/truncated blob: {uri}")
|
||||
self.entries[key] = {**ref, "content_type": content_type}
|
||||
|
||||
|
||||
def handler_for(state: ReplayState, scheme: str, log_path: Path | None = None):
|
||||
log_lock = threading.Lock()
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
protocol_version = "HTTP/1.1"
|
||||
def log_message(self, *_):
|
||||
pass
|
||||
|
||||
def do_HEAD(self):
|
||||
self.handle_entity(head=True)
|
||||
|
||||
def do_GET(self):
|
||||
self.handle_entity(head=False)
|
||||
|
||||
def handle_entity(self, head: bool):
|
||||
uri = f"{scheme}://{self.headers.get('Host', '')}{self.path}"
|
||||
started = now_ms()
|
||||
ref = None
|
||||
try:
|
||||
if not self.path.startswith("/") or self.path.startswith("//"):
|
||||
raise ValueError("origin-form request required")
|
||||
ref = state.entries.get(uri_key(uri))
|
||||
status = state.failures.get(uri_key(uri), 404 if ref is None else 200)
|
||||
if status != 200:
|
||||
ref = None
|
||||
except ValueError:
|
||||
status = 400
|
||||
etag = f'"sha256:{ref["sha256"]}"' if ref else None
|
||||
if status == 200 and self.headers.get("If-None-Match") == etag:
|
||||
status = 304
|
||||
self.send_response(status)
|
||||
self.send_header("Content-Length", str(ref["size"] if status == 200 else 0))
|
||||
self.send_header("X-RPKI-Epoch", state.epoch_hash)
|
||||
if state.scope_hash:
|
||||
self.send_header("X-RPKI-Scope", state.scope_hash)
|
||||
if ref:
|
||||
self.send_header("ETag", etag)
|
||||
self.send_header("Content-Type", ref["content_type"])
|
||||
self.end_headers()
|
||||
try:
|
||||
if status == 200 and not head:
|
||||
with state.archive.blob_path(ref["sha256"]).open("rb") as stream:
|
||||
while chunk := stream.read(65536):
|
||||
self.wfile.write(chunk)
|
||||
except (BrokenPipeError, ConnectionResetError):
|
||||
pass
|
||||
if log_path:
|
||||
event = {"uri": uri, "status": status, "sha256": ref["sha256"] if ref else None,
|
||||
"epoch": state.epoch_hash, "scope": state.scope_hash,
|
||||
"controlled_failure": uri_key(uri) in state.failures if status != 400 else False,
|
||||
"started_ms": started, "completed_ms": now_ms()}
|
||||
with log_lock, log_path.open("a", encoding="utf-8") as stream:
|
||||
stream.write(json.dumps(event, separators=(",", ":")) + "\n")
|
||||
return Handler
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--archive", type=Path, required=True)
|
||||
parser.add_argument("--epoch", type=Path, required=True)
|
||||
parser.add_argument("--scope", type=Path)
|
||||
parser.add_argument("--bind", default="127.0.0.1")
|
||||
parser.add_argument("--http-port", type=int, action="append", default=[])
|
||||
parser.add_argument("--https-port", type=int, action="append", default=[])
|
||||
parser.add_argument("--cert", type=Path)
|
||||
parser.add_argument("--key", type=Path)
|
||||
parser.add_argument("--log", type=Path, required=True)
|
||||
parser.add_argument("--ready", type=Path, required=True)
|
||||
args = parser.parse_args()
|
||||
if args.scope:
|
||||
from scope import require_closure
|
||||
require_closure(args.archive, args.scope)
|
||||
state = ReplayState(args.archive, args.epoch, args.scope)
|
||||
if not args.http_port and not args.https_port:
|
||||
parser.error("at least one server port is required")
|
||||
servers, listeners = [], []
|
||||
pairs = [(scheme, port) for scheme, ports in (("http", args.http_port), ("https", args.https_port)) for port in ports]
|
||||
for scheme, port in pairs:
|
||||
server = ThreadingHTTPServer((args.bind, port), handler_for(state, scheme, args.log))
|
||||
if scheme == "https":
|
||||
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
|
||||
context.minimum_version = ssl.TLSVersion.TLSv1_2
|
||||
context.load_cert_chain(args.cert, args.key)
|
||||
server.socket = context.wrap_socket(server.socket, server_side=True)
|
||||
threading.Thread(target=server.serve_forever, daemon=True).start()
|
||||
servers.append(server)
|
||||
listeners.append({"scheme": scheme, "address": server.server_address})
|
||||
atomic_json(args.ready, {"epoch": state.epoch_hash, "scope": state.scope_hash,
|
||||
"listeners": listeners, "http_entities": len(state.entries)})
|
||||
stopped = threading.Event()
|
||||
signal.signal(signal.SIGTERM, lambda *_: stopped.set())
|
||||
signal.signal(signal.SIGINT, lambda *_: stopped.set())
|
||||
stopped.wait()
|
||||
for server in servers:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
args.ready.unlink(missing_ok=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
228
scripts/experiments/reuse_eval/single_formal.py
Normal file
228
scripts/experiments/reuse_eval/single_formal.py
Normal file
@@ -0,0 +1,228 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Run one complete formal matrix using a preserved, byte-bound pilot."""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import csv
|
||||
from datetime import datetime, timezone
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
from pathlib import Path
|
||||
import signal
|
||||
import socket
|
||||
import statistics
|
||||
|
||||
from cache_size import profile_from_contract
|
||||
from campaign import SCALARS, require_matrix
|
||||
from common import atomic_json, file_sha256, read_json
|
||||
from sequence_matrix import (EXPECTED_HOST, PROFILE_FLAGS, compare_profile_contracts,
|
||||
require_t2_fallback_bindings, resource_guard, run_pilot)
|
||||
from smoke_matrix import cache_counters, require_comparison
|
||||
|
||||
|
||||
def require_row_proofs(row: dict, matrix: Path) -> None:
|
||||
"""Re-read compact proofs; never open the large report/event streams."""
|
||||
profile, step = row['profile'], row['step']
|
||||
run = matrix / profile / f'step_{step:04d}'
|
||||
benchmark = matrix / profile / f'benchmark_{step:04d}'
|
||||
if row.get('pass') is not True or row.get('path') != str(run):
|
||||
raise ValueError('row identity or success proof differs')
|
||||
if any(type(row.get('counts', {}).get(k)) is not int or row['counts'][k] <= 0
|
||||
for k in ['vrps', 'aspas', 'publication_points']):
|
||||
raise ValueError('empty or missing payload counts')
|
||||
require_comparison(run / 'ccr-comparison.json', 'ccr')
|
||||
require_comparison(run / 'cir-comparison.json', 'cir')
|
||||
equivalent = read_json(benchmark / 'equivalence.json')
|
||||
if (equivalent.get('pass') is not True or equivalent.get('inputs_match') is not True
|
||||
or equivalent.get('ccr', {}).get('stateDigestMatch') is not True):
|
||||
raise ValueError('T1/T2 input or CCR equivalence failed')
|
||||
contract = read_json(run / 'contract.json')
|
||||
baseline = read_json(matrix / 'baseline' / run.name / 'contract.json')
|
||||
if read_json(run / 'contract-comparison.json') != compare_profile_contracts(contract, baseline):
|
||||
raise ValueError('cross-profile contract proof differs from recomputation')
|
||||
require_t2_fallback_bindings(contract, equivalent)
|
||||
if profile_from_contract(contract)[0] != profile or contract['cache']['transportPrefetch'] is not False:
|
||||
raise ValueError('effective reuse profile or disabled prefetch differs')
|
||||
overlay = read_json(benchmark / 'input-overlay.json')
|
||||
proof = overlay.get('overlay', {})
|
||||
if (overlay.get('pre_state_files_verified') is not True or proof.get('background_io_drained') is not True
|
||||
or proof.get('cache_before') != proof.get('cache_after')):
|
||||
raise ValueError('pre-T1 cache or frozen-input overlay proof failed')
|
||||
counters = read_json(run / 'cache-counters.json')
|
||||
if counters['t1'] != counters['t2'] or counters['t1'] != cache_counters(run) or counters['t2'] != cache_counters(benchmark):
|
||||
raise ValueError('T1/T2 raw cache hit/miss counters differ')
|
||||
if read_json(benchmark / 'engine-timing.json') != row['engine']:
|
||||
raise ValueError('engine timing differs from source')
|
||||
if read_json(run / 'cache-size.json')['required_serialized_bytes'] != row['cache_size_bytes']:
|
||||
raise ValueError('cache size differs from source')
|
||||
|
||||
|
||||
def require_prerequisite(config: dict) -> dict:
|
||||
"""Bind an existing pilot to this identical RP and unchanged run engine."""
|
||||
path = Path(config['pilot_summary'])
|
||||
if file_sha256(path) != config['expected_pilot_summary_sha256']:
|
||||
raise ValueError('preserved pilot summary hash differs')
|
||||
pilot = read_json(path)
|
||||
repeat = config['repeat']
|
||||
require_matrix(pilot, repeat['expected_scope_sha256'], formal=False)
|
||||
if (repeat.get('formal_metrics') is not True
|
||||
or repeat.get('profile_order') != list(PROFILE_FLAGS)
|
||||
or repeat.get('run_timeout_secs') != 1800):
|
||||
raise ValueError('requires exactly one full formal matrix under the original execution policy')
|
||||
for key in ['archive', 'scope', 'expected_binary_sha256', 'expected_scope_sha256']:
|
||||
if repeat[key] != pilot['config'][key]:
|
||||
raise ValueError('formal input/build differs from preserved pilot: ' + key)
|
||||
if pilot['tool_sha256'] != config['expected_tools_sha256']:
|
||||
raise ValueError('preserved pilot tool hashes differ')
|
||||
for name, digest in config['expected_tools_sha256'].items():
|
||||
if file_sha256(Path(repeat[name])) != digest:
|
||||
raise ValueError('formal tool differs from preserved pilot: ' + name)
|
||||
if file_sha256(path.parent / 'bin/binary') != repeat['expected_binary_sha256']:
|
||||
raise ValueError('actual preserved pilot RP bytes differ')
|
||||
if file_sha256(Path(repeat['scope'])) != repeat['expected_scope_sha256']:
|
||||
raise ValueError('original repository scope changed')
|
||||
original_scripts = config['expected_pilot_scripts_sha256']
|
||||
if pilot['scripts_sha256'] != original_scripts:
|
||||
raise ValueError('preserved pilot script hashes differ')
|
||||
package = Path(__file__).resolve().parent
|
||||
scripts = {p.name: file_sha256(p) for p in sorted(package.glob('*.py')) if not p.name.startswith('test_')}
|
||||
if scripts != config['expected_scripts_sha256']:
|
||||
raise ValueError('frozen single-formal package differs')
|
||||
if set(scripts) != set(original_scripts) | {'single_formal.py'}:
|
||||
raise ValueError('unexpected controller additions/removals')
|
||||
if any(scripts[name] != digest for name, digest in original_scripts.items() if name != 'formal_metrics.py'):
|
||||
raise ValueError('RP run engine changed; preserved pilot cannot be reused')
|
||||
expected = [(p, step) for p in PROFILE_FLAGS for step in range(13)]
|
||||
if [(r['profile'], r['step']) for r in pilot['runs']] != expected:
|
||||
raise ValueError('preserved pilot order or completeness differs')
|
||||
for row in pilot['runs']:
|
||||
require_row_proofs(row, path.parent)
|
||||
return {'pass': True, 'pilot_summary': str(path), 'pilot_summary_sha256': file_sha256(path),
|
||||
'pairs_checked': 65, 'binary_sha256': repeat['expected_binary_sha256'],
|
||||
'scope_sha256': repeat['expected_scope_sha256'],
|
||||
'reuse_reason': 'same RP/tools/input/policy/resources; only transport measurement collector fixed and single-repeat entry added'}
|
||||
|
||||
|
||||
def require_metrics(metrics: dict, profile: str) -> None:
|
||||
if not isinstance(metrics, dict) or metrics.get('schema') != 'rpki-reuse-seven-metrics-v1' or metrics.get('profile') != profile:
|
||||
raise ValueError('missing seven-metric schema/profile')
|
||||
for key in SCALARS:
|
||||
value = metrics.get(key)
|
||||
if type(value) not in (int, float) or not math.isfinite(value) or value < 0:
|
||||
raise ValueError('missing or invalid metric: ' + key)
|
||||
if any(metrics[key] <= 0 for key in ['rp_validation_ns', 'update_to_payload_ns', 'peak_rss_bytes']):
|
||||
raise ValueError('validation/payload/RSS must be positive')
|
||||
enabled = {'signature': profile == 'signature', 'roa': profile in ('object', 'hybrid'),
|
||||
'child_certificate': profile in ('object', 'hybrid'), 'publication_point': profile in ('pp', 'hybrid')}
|
||||
for layer, on in enabled.items():
|
||||
r = metrics.get('cache_hit_ratio', {}).get(layer, {})
|
||||
hits, queries = r.get('hits'), r.get('queries')
|
||||
if (r.get('enabled') is not on or type(hits) is not int or type(queries) is not int
|
||||
or not 0 <= hits <= queries or (not on and (hits or queries))
|
||||
or r.get('ratio') != (hits / queries if on and queries else None)):
|
||||
raise ValueError('cache hit denominator/profile differs: ' + layer)
|
||||
|
||||
|
||||
def report(summary: dict) -> dict:
|
||||
"""Descriptive statistics for one trajectory, with no repeat CI claims."""
|
||||
require_matrix(summary, summary['scope_sha256'], formal=True)
|
||||
for row in summary['runs']:
|
||||
require_metrics(row['seven_metrics'], row['profile'])
|
||||
selections = {'cold': [0], 'incremental': list(range(1, 13)),
|
||||
'before_manifest_fallback': list(range(1, 11)), 'manifest_fallback': [11], 'native_transport_fallback': [12]}
|
||||
groups = []
|
||||
for profile in PROFILE_FLAGS:
|
||||
for label, steps in selections.items():
|
||||
rows = [r for r in summary['runs'] if r['profile'] == profile and r['step'] in steps]
|
||||
values = [r['seven_metrics'] for r in rows]
|
||||
group = {'profile': profile, 'steps': label, 'logical_steps': steps, 'n_steps': len(rows),
|
||||
'independent_repeats': 1, 'metrics': {}, 'cache_hit_ratio': {},
|
||||
'cache_size_at_end_bytes': max(rows, key=lambda r: r['step'])['seven_metrics']['cache_size_bytes']}
|
||||
for key in SCALARS:
|
||||
data = [m[key] for m in values]
|
||||
group['metrics'][key] = {'mean': statistics.mean(data), 'median': statistics.median(data),
|
||||
'min': min(data), 'max': max(data)}
|
||||
for layer in ['signature', 'roa', 'child_certificate', 'publication_point']:
|
||||
hits = sum(m['cache_hit_ratio'][layer]['hits'] for m in values)
|
||||
queries = sum(m['cache_hit_ratio'][layer]['queries'] for m in values)
|
||||
group['cache_hit_ratio'][layer] = {'hits': hits, 'queries': queries, 'ratio': hits / queries if queries else None}
|
||||
groups.append(group)
|
||||
return {'schema': 'rpki-reuse-single-formal-report-v1', 'pass': True, 'performance_ready': True,
|
||||
'repeats': 1, 'pairs': 65, 'scope_sha256': summary['scope_sha256'],
|
||||
'tool_sha256': summary['tool_sha256'], 'groups': groups,
|
||||
'limitations': ['one replay per profile; logical steps are not independent statistical repetitions',
|
||||
'same 186 host server/RP; shared storage, page cache and CPU siblings',
|
||||
'109 successful repository scope plus eight declared gaps; one-hour capture',
|
||||
'final controlled RRDP failure exercises the recorded native rsync fallback',
|
||||
'all profiles disable transport prefetch; uniform CPU1-3/workers3/5GiB',
|
||||
'cache is required serialized CF key/value plus sidecar copies, not whole DB disk usage']}
|
||||
|
||||
|
||||
def csv_rows(summary: dict) -> list[dict]:
|
||||
result = []
|
||||
for row in summary['runs']:
|
||||
metrics = row['seven_metrics']
|
||||
require_metrics(metrics, row['profile'])
|
||||
result.append({'repeat': 1, 'profile': row['profile'], 'step': row['step'],
|
||||
**{key: metrics[key] for key in SCALARS},
|
||||
**{f'{layer}_{key}': metrics['cache_hit_ratio'][layer][key]
|
||||
for layer in ['signature', 'roa', 'child_certificate', 'publication_point']
|
||||
for key in ['hits', 'queries', 'ratio']}})
|
||||
return result
|
||||
|
||||
|
||||
def run(config: dict) -> dict:
|
||||
if socket.gethostname() != EXPECTED_HOST or os.geteuid() != 0:
|
||||
raise ValueError('single formal is restricted to root on the designated 186 host')
|
||||
output, matrix = Path(config['out']).resolve(), Path(config['repeat']['out']).resolve()
|
||||
parent = Path('/data/rpki187/20261109/results')
|
||||
if output.parent != parent or matrix.parent != parent or output == matrix or output.exists() or matrix.exists():
|
||||
raise ValueError('single formal requires distinct new empty roots under the dedicated results parent')
|
||||
resources = resource_guard(parent)
|
||||
if resources['data_free_bytes'] < config['minimum_available_bytes']:
|
||||
raise ValueError('insufficient capacity for one matrix plus the unchanged guard')
|
||||
prerequisite = require_prerequisite(config)
|
||||
output.mkdir(exist_ok=False)
|
||||
atomic_json(output / 'pilot-prerequisite.json', prerequisite)
|
||||
state = {'status': 'running', 'pass': False, 'performance_ready': False, 'config': config,
|
||||
'repeats': 1, 'pilot_summary_sha256': prerequisite['pilot_summary_sha256'], 'initial_resources': resources}
|
||||
|
||||
def save() -> None:
|
||||
state['updated_utc'] = datetime.now(timezone.utc).isoformat()
|
||||
atomic_json(output / 'single-status.json', state)
|
||||
|
||||
save()
|
||||
try:
|
||||
summary = run_pilot(config['repeat'])
|
||||
result = report(summary)
|
||||
for row in summary['runs']:
|
||||
require_row_proofs(row, matrix)
|
||||
atomic_json(output / 'single-report.json', result)
|
||||
rows = csv_rows(summary)
|
||||
with (output / 'all-steps.csv').open('x', newline='') as stream:
|
||||
writer = csv.DictWriter(stream, fieldnames=list(rows[0]))
|
||||
writer.writeheader()
|
||||
writer.writerows(rows)
|
||||
state.update(status='completed', **{'pass': True}, performance_ready=True, pairs=65,
|
||||
formal_summary_sha256=file_sha256(matrix / 'summary.json'))
|
||||
save()
|
||||
return state
|
||||
except BaseException as error:
|
||||
state.update(status='failed', error=f'{type(error).__name__}: {error}')
|
||||
save()
|
||||
raise
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--config', type=Path, required=True)
|
||||
args = parser.parse_args()
|
||||
def interrupted(*_):
|
||||
raise KeyboardInterrupt('single formal interrupted')
|
||||
signal.signal(signal.SIGTERM, interrupted)
|
||||
print(json.dumps(run(read_json(args.config))))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
32
scripts/experiments/reuse_eval/smoke_live.py
Normal file
32
scripts/experiments/reuse_eval/smoke_live.py
Normal file
@@ -0,0 +1,32 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Bounded single-repository protocol smoke; RP cryptographic acceptance is separate."""
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
from capture import Collector, select_epoch
|
||||
from common import Archive, atomic_json, now_ms
|
||||
from verify import verify
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--notification", required=True)
|
||||
parser.add_argument("--archive", type=Path, required=True)
|
||||
args = parser.parse_args()
|
||||
if args.archive.exists():
|
||||
raise ValueError("smoke archive must be new")
|
||||
archive = Archive(args.archive, {"min_free_bytes": 150 * 1024**3, "min_root_free_inodes": 10000,
|
||||
"attempts": 1, "request_timeout_secs": 20, "observation_deadline_secs": 180})
|
||||
observation = Collector(archive).observe(args.notification)
|
||||
epoch = select_epoch(args.archive, {args.notification: {"first_seen_ms": 0}}, now_ms())
|
||||
atomic_json(args.archive / "epochs/epoch_0000.json", epoch)
|
||||
result = verify(args.archive)
|
||||
atomic_json(args.archive / "smoke.json", {"observation": observation, "closure": result,
|
||||
"real_rp_crypto_acceptance": "not_run_by_this_protocol_smoke"})
|
||||
print(json.dumps(result), flush=True)
|
||||
return 0 if result["pass"] else 2
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
187
scripts/experiments/reuse_eval/smoke_matrix.py
Normal file
187
scripts/experiments/reuse_eval/smoke_matrix.py
Normal file
@@ -0,0 +1,187 @@
|
||||
#!/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()
|
||||
68
scripts/experiments/reuse_eval/smoke_rp.py
Normal file
68
scripts/experiments/reuse_eval/smoke_rp.py
Normal file
@@ -0,0 +1,68 @@
|
||||
#!/usr/bin/env python3
|
||||
"""One real-TA publication-point RP smoke inside the prepared replay namespace."""
|
||||
import argparse
|
||||
from datetime import datetime, timezone
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import subprocess
|
||||
import time
|
||||
|
||||
from common import atomic_json, read_json
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--binary", type=Path, required=True)
|
||||
parser.add_argument("--tal", type=Path, required=True)
|
||||
parser.add_argument("--ta", type=Path, required=True)
|
||||
parser.add_argument("--manifest", type=Path, required=True)
|
||||
parser.add_argument("--out", type=Path, required=True)
|
||||
parser.add_argument("--disable-rrdp", action="store_true", help="Force real rsync for a separately identified transport fixture")
|
||||
args = parser.parse_args()
|
||||
args.out.mkdir(parents=True)
|
||||
(args.out / "tmp").mkdir()
|
||||
manifest = read_json(args.manifest)
|
||||
epoch = read_json(Path(manifest["epoch_path"]))
|
||||
validation_time = datetime.fromtimestamp(epoch["validation_time_ms"] // 1000, timezone.utc).isoformat().replace("+00:00", "Z")
|
||||
command = ["/usr/bin/time", "-v", str(args.binary), "--db", str(args.out / "db"), "--tal-path", str(args.tal),
|
||||
"--cir-tal-uri", f"https://capture.rpki187.invalid/tal/{hashlib.sha256(args.tal.read_bytes()).hexdigest()}/{args.tal.name}",
|
||||
"--ta-path", str(args.ta), "--http-root-cert", manifest["tls"]["ca"], "--max-instances", "1",
|
||||
"--validation-time", validation_time, "--report-json", str(args.out / "report.json"),
|
||||
"--report-json-compact", "--ccr-out", str(args.out / "result.ccr"),
|
||||
"--cir-enable", "--cir-out", str(args.out / "input.cir"),
|
||||
"--record-transport-dir", str(args.out / "transport"), "--rsync-mirror-root", str(args.out / "mirror")]
|
||||
if args.disable_rrdp:
|
||||
command.append("--disable-rrdp")
|
||||
env = {key: value for key, value in os.environ.items() if key.lower() not in ("http_proxy", "https_proxy", "all_proxy")}
|
||||
env["TMPDIR"] = str(args.out / "tmp")
|
||||
started = time.monotonic()
|
||||
with (args.out / "stdout.log").open("wb") as out, (args.out / "stderr.log").open("wb") as err:
|
||||
result = subprocess.run(command, stdout=out, stderr=err, env=env, timeout=900)
|
||||
log = (args.out / "stderr.log").read_text(errors="replace")
|
||||
anchors = re.findall(r"wrote CIR: .*?trust_anchors=(\d+)", log)
|
||||
report = read_json(args.out / "report.json") if (args.out / "report.json").exists() else {}
|
||||
proof = {"exit_code": result.returncode, "wall_secs": time.monotonic() - started,
|
||||
"profile": "functional_smoke_not_performance", "command": command,
|
||||
"binary_sha256": hashlib.sha256(args.binary.read_bytes()).hexdigest(),
|
||||
"ta_sha256": hashlib.sha256(args.ta.read_bytes()).hexdigest(), "ta_mode": "pinned genuine TA checked against real TAL",
|
||||
"network_namespace": os.readlink("/proc/self/ns/net"), "validation_time": validation_time,
|
||||
"trust_anchors": int(anchors[-1]) if anchors else 0, "tree": report.get("tree"),
|
||||
"publication_points": len(report.get("publication_points", []))}
|
||||
events = [read_json(path) for path in (args.out / "transport/events").glob("*.json")]
|
||||
proof["forced_rsync_fixture"] = args.disable_rrdp
|
||||
proof["successful_transport_events"] = {kind: sum(event["complete"] and event["transport"] == kind for event in events)
|
||||
for kind in ("http", "rsync")}
|
||||
proof["pass"] = (result.returncode == 0 and proof["trust_anchors"] == 1 and proof["publication_points"] == 1
|
||||
and report["tree"]["instances_failed"] == 0)
|
||||
if args.disable_rrdp:
|
||||
proof["pass"] = proof["pass"] and proof["successful_transport_events"]["rsync"] > 0 and not proof["successful_transport_events"]["http"]
|
||||
atomic_json(args.out / "smoke-proof.json", proof)
|
||||
print(json.dumps(proof), flush=True)
|
||||
return 0 if proof["pass"] else 2
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
86
scripts/experiments/reuse_eval/test_cache_size.py
Normal file
86
scripts/experiments/reuse_eval/test_cache_size.py
Normal file
@@ -0,0 +1,86 @@
|
||||
"""Check strategy attribution without treating the whole DB as validation cache."""
|
||||
import json
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
from cache_size import COMPONENTS, account, file_inventory
|
||||
|
||||
|
||||
class CacheSizeTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.tmp.cleanup)
|
||||
self.root = Path(self.tmp.name)
|
||||
self.db = self.root / "state"
|
||||
self.db.mkdir()
|
||||
self.stats = self.root / "stats.txt"
|
||||
lines = [f"db={self.db}", "mode=exact", "logical_bytes_available=true"]
|
||||
for cf in COMPONENTS.values():
|
||||
lines += [f"cf.{cf}.{key}={value}" for key, value in
|
||||
(("keys", 2), ("key_bytes", 10), ("value_bytes", 90), ("live_sst_size_bytes", 55))]
|
||||
# Large public object data must never enter the validation cache total.
|
||||
lines += ["cf.raw_by_hash.value_bytes=900000000", "db.files.total_size_bytes=999999999"]
|
||||
self.stats.write_text("\n".join(lines))
|
||||
self.contract = self.root / "contract.json"
|
||||
|
||||
def contract_for(self, **changes):
|
||||
cache = dict(publicationPoint=False, roa=False, childCertificate=False, cryptoSignature=False, transportPrefetch=False)
|
||||
cache.update(changes)
|
||||
self.contract.write_text(json.dumps({"cache": cache}))
|
||||
|
||||
def test_baseline_reports_common_retention_separately(self):
|
||||
self.contract_for()
|
||||
report = account(self.db, self.stats, self.contract)
|
||||
self.assertEqual(report["required_serialized_bytes"], 0)
|
||||
self.assertEqual(report["all_retained_validation_cf_key_value_bytes"], 700)
|
||||
self.assertEqual(report["profile"], "baseline")
|
||||
|
||||
def test_hybrid_counts_selected_projections_and_real_index_copy(self):
|
||||
self.contract_for(publicationPoint=True, roa=True, childCertificate=True)
|
||||
index = self.root / "state.pp-cache-index"
|
||||
index.mkdir()
|
||||
(index / "current.idx").write_bytes(b"index copy")
|
||||
child = self.root / "state.child-cert-cache-index"
|
||||
child.mkdir()
|
||||
(child / "pp.idx").write_bytes(b"child index")
|
||||
# A disabled but retained signature sidecar must be exposed, not attributed to Hybrid.
|
||||
(self.root / "state.crypto-sig-cache").write_bytes(b"stale signature")
|
||||
report = account(self.db, self.stats, self.contract)
|
||||
self.assertEqual(report["required_serialized_bytes"], 321)
|
||||
self.assertEqual(report["required_cf_key_value_bytes"], 300)
|
||||
self.assertEqual(report["all_retained_sidecar_file_bytes"], 36)
|
||||
self.assertGreaterEqual(report["sidecars"]["publication_point"]["allocated_bytes"], 10)
|
||||
|
||||
def test_signature_counts_file_without_object_or_pp_projections(self):
|
||||
self.contract_for(cryptoSignature=True)
|
||||
(self.root / "state.crypto-sig-cache").write_bytes(b"serialized signature conclusions")
|
||||
report = account(self.db, self.stats, self.contract)
|
||||
self.assertEqual(report["profile"], "signature")
|
||||
self.assertEqual(report["required_cf_key_value_bytes"], 0)
|
||||
self.assertEqual(report["required_serialized_bytes"], len(b"serialized signature conclusions"))
|
||||
|
||||
def test_rejects_estimates_other_db_and_out_of_matrix_contract(self):
|
||||
self.contract_for()
|
||||
text = self.stats.read_text()
|
||||
self.stats.write_text(text.replace("mode=exact", "mode=estimate"))
|
||||
with self.assertRaisesRegex(ValueError, "--exact"):
|
||||
account(self.db, self.stats, self.contract)
|
||||
self.stats.write_text(text)
|
||||
with self.assertRaisesRegex(ValueError, "different state"):
|
||||
account(self.root / "other", self.stats, self.contract)
|
||||
for changes in ({"transportPrefetch": True}, {"roa": True}, {"cryptoSignature": "false"}):
|
||||
self.contract_for(**changes)
|
||||
with self.assertRaises(ValueError):
|
||||
account(self.db, self.stats, self.contract)
|
||||
|
||||
def test_sidecar_symlink_never_scans_another_profiles_files(self):
|
||||
(self.root / "outside").mkdir()
|
||||
path = self.root / "state.pp-cache-index"
|
||||
path.symlink_to(self.root / "outside", target_is_directory=True)
|
||||
with self.assertRaisesRegex(ValueError, "symlink"):
|
||||
file_inventory(path)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
55
scripts/experiments/reuse_eval/test_campaign.py
Normal file
55
scripts/experiments/reuse_eval/test_campaign.py
Normal file
@@ -0,0 +1,55 @@
|
||||
import copy
|
||||
import unittest
|
||||
|
||||
from campaign import SCALARS, aggregate, require_matrix
|
||||
from sequence_matrix import PROFILE_FLAGS
|
||||
|
||||
|
||||
def fixture(repeat):
|
||||
rows = []
|
||||
for profile in PROFILE_FLAGS:
|
||||
for step in range(13):
|
||||
ratios = {name: {"hits": 0, "queries": 0, "ratio": None}
|
||||
for name in ("signature", "roa", "child_certificate", "publication_point")}
|
||||
metrics = {key: repeat * 10 + step for key in SCALARS}
|
||||
metrics["cache_hit_ratio"] = ratios
|
||||
rows.append({"profile": profile, "step": step, "pass": True, "seven_metrics": metrics})
|
||||
return {"status": "completed", "pass": True, "performance_ready": True, "scope_sha256": "scope",
|
||||
"tool_sha256": {"binary": "binary", "ccr_compare": "comparator"}, "runs": rows,
|
||||
"restoration": {"rp187rp": 0, "rp187srv": 0, "panda_active": True, "panda_container_running": True}}
|
||||
|
||||
|
||||
class CampaignTests(unittest.TestCase):
|
||||
def test_three_repeat_means_are_replicates_instead_of_individual_epochs(self):
|
||||
result = aggregate([fixture(n) for n in (1, 2, 3)])
|
||||
self.assertEqual(result["pairs"], 195)
|
||||
regular = next(g for g in result["groups"] if g["profile"] == "baseline" and g["steps"] == "incremental_without_fallback")
|
||||
self.assertEqual(regular["metrics"]["rp_validation_ns"]["values"], [16, 26, 36])
|
||||
self.assertEqual(regular["metrics"]["rp_validation_ns"]["n"], 3)
|
||||
self.assertEqual(regular["metrics"]["rp_validation_ns"]["stdev"], 10)
|
||||
self.assertIsNone(regular["hit_ratios"]["signature"])
|
||||
|
||||
def test_duplicate_missing_pairs_and_changed_build_or_restore_are_rejected(self):
|
||||
original = fixture(1)
|
||||
for altered in ("duplicate", "scope", "restore", "metrics"):
|
||||
summary = copy.deepcopy(original)
|
||||
if altered == "duplicate":
|
||||
summary["runs"][-1] = summary["runs"][0]
|
||||
elif altered == "scope":
|
||||
summary["scope_sha256"] = "different"
|
||||
elif altered == "restore":
|
||||
summary["restoration"]["panda_container_running"] = False
|
||||
else:
|
||||
summary["runs"][0]["seven_metrics"] = None
|
||||
with self.subTest(altered=altered), self.assertRaises(ValueError):
|
||||
require_matrix(summary, "scope", formal=True)
|
||||
different = fixture(3)
|
||||
different["tool_sha256"]["binary"] = "changed"
|
||||
with self.assertRaises(ValueError):
|
||||
aggregate([fixture(1), fixture(2), different])
|
||||
with self.assertRaises(ValueError):
|
||||
aggregate([fixture(1)])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
310
scripts/experiments/reuse_eval/test_capture.py
Normal file
310
scripts/experiments/reuse_eval/test_capture.py
Normal file
@@ -0,0 +1,310 @@
|
||||
"""Protocol-focused tests; no public network or genuine TA substitutes as evidence."""
|
||||
import base64
|
||||
import gzip
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
import io
|
||||
import json
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import threading
|
||||
import sys
|
||||
import time
|
||||
import unittest
|
||||
from unittest.mock import Mock, patch
|
||||
|
||||
from capture import Capture, Collector, select_epoch
|
||||
from common import Archive, atomic_json, digest_bytes, file_sha256, now_ms
|
||||
from rrdp import notification, payload_view, view_digest
|
||||
from verify import verify
|
||||
|
||||
SESSION = "11111111-1111-4111-8111-111111111111"
|
||||
OTHER_SESSION = "22222222-2222-4222-8222-222222222222"
|
||||
OBJECT = "rsync://repo.example/module/a.roa"
|
||||
OTHER_OBJECT = "rsync://repo.example/module/b.roa"
|
||||
|
||||
|
||||
def publish(uri, data, previous=None):
|
||||
attr = f' hash="{digest_bytes(previous)}"' if previous is not None else ""
|
||||
return f'<publish uri="{uri}"{attr}>{base64.b64encode(data).decode()}</publish>'
|
||||
|
||||
|
||||
def xml(kind, serial, content, session=SESSION):
|
||||
return (f'<{kind} xmlns="http://www.ripe.net/rpki/rrdp" version="1" session_id="{session}" serial="{serial}">'
|
||||
f'{content}</{kind}>').encode()
|
||||
|
||||
|
||||
class CaptureTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.tmp.cleanup)
|
||||
self.resources = {}
|
||||
self.requests = []
|
||||
resources, requests = self.resources, self.requests
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
def log_message(self, *_):
|
||||
pass
|
||||
def do_GET(self):
|
||||
requests.append((self.path, self.headers.get("If-None-Match")))
|
||||
resource = resources.get(self.path)
|
||||
if resource is None:
|
||||
self.send_error(404)
|
||||
return
|
||||
body, headers = resource
|
||||
status = 304 if headers.get("ETag") == self.headers.get("If-None-Match") and headers.get("ETag") else headers.get("status", 200)
|
||||
self.send_response(status)
|
||||
for key, value in headers.items():
|
||||
if key not in ("status", "Content-Length"):
|
||||
self.send_header(key, value)
|
||||
self.send_header("Content-Length", headers.get("Content-Length", str(len(body))))
|
||||
self.end_headers()
|
||||
if status != 304:
|
||||
self.wfile.write(body)
|
||||
self.server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
|
||||
self.thread = threading.Thread(target=self.server.serve_forever, daemon=True)
|
||||
self.thread.start()
|
||||
self.addCleanup(self.server.server_close)
|
||||
self.addCleanup(self.server.shutdown)
|
||||
self.base = f"http://127.0.0.1:{self.server.server_port}"
|
||||
self.uri = self.base + "/notification.xml"
|
||||
self.archive = Archive(Path(self.tmp.name) / "archive", {"allow_test_http": True, "attempts": 1, "request_timeout_secs": 1})
|
||||
self.collector = Collector(self.archive)
|
||||
|
||||
def install(self, serial, snapshot, deltas=None, session=SESSION, etag=None):
|
||||
self.resources["/snapshot.xml"] = (snapshot, {})
|
||||
content = f'<snapshot uri="{self.base}/snapshot.xml" hash="{digest_bytes(snapshot)}"/>'
|
||||
for number, body in (deltas or {}).items():
|
||||
self.resources[f"/delta-{number}.xml"] = (body, {})
|
||||
content += f'<delta serial="{number}" uri="{self.base}/delta-{number}.xml" hash="{digest_bytes(body)}"/>'
|
||||
self.resources["/notification.xml"] = (xml("notification", serial, content, session), {"ETag": etag} if etag else {})
|
||||
|
||||
def initial(self):
|
||||
self.install(1, xml("snapshot", 1, publish(OBJECT, b"a")), etag='"one"')
|
||||
observation = self.collector.observe(self.uri)
|
||||
self.assertTrue(observation["complete"], observation)
|
||||
return observation
|
||||
|
||||
def test_initial_and_304_reuse_exact_body(self):
|
||||
first = self.initial()
|
||||
second = self.collector.observe(self.uri, first)
|
||||
self.assertTrue(second["complete"])
|
||||
self.assertEqual(second["http"]["status"], 304)
|
||||
self.assertEqual(first["notification"], second["notification"])
|
||||
self.assertEqual(second["chain"], "no_change")
|
||||
self.assertEqual(sum(path == "/snapshot.xml" for path, _ in self.requests), 1)
|
||||
|
||||
def test_multiple_delta_replacement_and_withdrawal_match_snapshot(self):
|
||||
first = self.initial()
|
||||
d2 = xml("delta", 2, publish(OBJECT, b"changed", b"a") + publish(OTHER_OBJECT, b"b"))
|
||||
d3 = xml("delta", 3, f'<withdraw uri="{OTHER_OBJECT}" hash="{digest_bytes(b"b")}"/>')
|
||||
self.install(3, xml("snapshot", 3, publish(OBJECT, b"changed")), {2: d2, 3: d3})
|
||||
final = self.collector.observe(self.uri, first)
|
||||
self.assertTrue(final["complete"], final)
|
||||
self.assertEqual(final["chain"], "delta_matches_snapshot")
|
||||
self.assertTrue(self.archive.blob_path(first["notification"]["sha256"]).exists())
|
||||
|
||||
def test_missing_required_delta_rejects_observation(self):
|
||||
first = self.initial()
|
||||
self.install(3, xml("snapshot", 3, publish(OBJECT, b"a")), {3: xml("delta", 3, "")})
|
||||
result = self.collector.observe(self.uri, first)
|
||||
self.assertFalse(result["complete"])
|
||||
self.assertIn("required delta 2 missing", result["error"])
|
||||
|
||||
def test_wrong_previous_hash_rejects_delta(self):
|
||||
first = self.initial()
|
||||
self.install(2, xml("snapshot", 2, publish(OBJECT, b"new")),
|
||||
{2: xml("delta", 2, publish(OBJECT, b"new", b"wrong"))})
|
||||
self.assertIn("previous hash mismatch", self.collector.observe(self.uri, first)["error"])
|
||||
|
||||
def test_delta_snapshot_disagreement_rejects_observation(self):
|
||||
first = self.initial()
|
||||
self.install(2, xml("snapshot", 2, publish(OBJECT, b"other")),
|
||||
{2: xml("delta", 2, publish(OBJECT, b"new", b"a"))})
|
||||
self.assertIn("differs from snapshot", self.collector.observe(self.uri, first)["error"])
|
||||
|
||||
def test_session_reset_uses_real_new_snapshot(self):
|
||||
first = self.initial()
|
||||
self.install(1, xml("snapshot", 1, publish(OTHER_OBJECT, b"b"), OTHER_SESSION), session=OTHER_SESSION)
|
||||
result = self.collector.observe(self.uri, first)
|
||||
self.assertTrue(result["complete"], result)
|
||||
self.assertEqual(result["chain"], "session_reset_snapshot")
|
||||
|
||||
def test_snapshot_reference_hash_mismatch_is_not_complete(self):
|
||||
self.initial()
|
||||
self.resources["/snapshot.xml"] = (b"corrupt", {})
|
||||
# New archive prevents a valid previously saved body satisfying the reference.
|
||||
other = Archive(Path(self.tmp.name) / "other", self.archive.limits)
|
||||
self.assertFalse(Collector(other).observe(self.uri)["complete"])
|
||||
|
||||
def test_same_serial_changed_snapshot_rejected(self):
|
||||
first = self.initial()
|
||||
self.install(1, xml("snapshot", 1, publish(OBJECT, b"changed")))
|
||||
self.assertIn("without session/serial", self.collector.observe(self.uri, first)["error"])
|
||||
|
||||
def test_old_optional_delta_failure_is_reported_but_initial_usable(self):
|
||||
self.install(2, xml("snapshot", 2, publish(OBJECT, b"a")), {1: xml("delta", 1, "")})
|
||||
del self.resources["/delta-1.xml"]
|
||||
result = self.collector.observe(self.uri)
|
||||
self.assertTrue(result["complete"], result)
|
||||
self.assertFalse(next(r for r in result["references"] if r["kind"] == "delta")["available"])
|
||||
|
||||
def test_304_without_prior_entity_is_failure(self):
|
||||
self.resources["/x"] = (b"", {"status": 304})
|
||||
result = self.archive.fetch(self.base + "/x", "notification")
|
||||
self.assertFalse(result["complete"])
|
||||
|
||||
def test_http_gzip_preserves_decoded_entity(self):
|
||||
raw = b"<original>signed content</original>"
|
||||
self.resources["/gzip"] = (gzip.compress(raw), {"Content-Encoding": "gzip"})
|
||||
result = self.archive.fetch(self.base + "/gzip", "snapshot")
|
||||
self.assertTrue(result["complete"], result)
|
||||
self.assertEqual(result["body"]["sha256"], digest_bytes(raw))
|
||||
|
||||
def test_truncated_body_is_failure(self):
|
||||
self.resources["/short"] = (b"short", {"Content-Length": "100"})
|
||||
self.assertFalse(self.archive.fetch(self.base + "/short", "snapshot")["complete"])
|
||||
|
||||
def test_cross_origin_redirect_never_follows(self):
|
||||
self.resources["/redirect"] = (b"", {"status": 302, "Location": "http://localhost:1/forbidden"})
|
||||
result = self.archive.fetch(self.base + "/redirect", "notification")
|
||||
self.assertFalse(result["complete"])
|
||||
self.assertIn("cross-origin", result["error"])
|
||||
|
||||
def test_cross_origin_reference_rejected(self):
|
||||
body = xml("notification", 1, f'<snapshot uri="https://other.example/s.xml" hash="{digest_bytes(b"x")}"/>')
|
||||
ref = self.archive.put_stream(io.BytesIO(body))
|
||||
with self.assertRaisesRegex(ValueError, "cross-origin"):
|
||||
notification(self.archive.blob_path(ref["sha256"]), self.uri)
|
||||
|
||||
def test_future_completion_never_used_for_earlier_epoch(self):
|
||||
first = self.initial()
|
||||
registry = {self.uri: {"first_seen_ms": 0}}
|
||||
early = select_epoch(self.archive.root, registry, first["completed_ms"] - 1)
|
||||
self.assertFalse(early["complete"])
|
||||
exact = select_epoch(self.archive.root, registry, first["completed_ms"])
|
||||
self.assertTrue(exact["complete"])
|
||||
self.assertEqual(exact["repositories"][self.uri]["id"], first["id"])
|
||||
|
||||
def test_latest_failure_cannot_silently_turn_into_a_successful_noop_epoch(self):
|
||||
first = self.initial()
|
||||
self.resources.pop("/notification.xml")
|
||||
failed = self.collector.observe(self.uri, first)
|
||||
self.assertFalse(failed["complete"])
|
||||
epoch = select_epoch(self.archive.root, {self.uri: {"first_seen_ms": 0}}, now_ms())
|
||||
self.assertFalse(epoch["complete"])
|
||||
self.assertEqual(epoch["blocked_latest_attempts"], [self.uri])
|
||||
self.assertEqual(epoch["repositories"][self.uri]["id"], first["id"])
|
||||
|
||||
def test_closure_verifier_detects_corrupt_blob(self):
|
||||
first = self.initial()
|
||||
epoch = select_epoch(self.archive.root, {self.uri: {"first_seen_ms": 0}}, now_ms())
|
||||
atomic_json(self.archive.root / "epochs/epoch_0000.json", epoch)
|
||||
self.assertTrue(verify(self.archive.root)["pass"])
|
||||
self.archive.blob_path(first["notification"]["sha256"]).write_bytes(b"corrupt")
|
||||
self.assertFalse(verify(self.archive.root)["pass"])
|
||||
|
||||
def test_epoch_rejects_changed_capture_policy_contract(self):
|
||||
self.initial()
|
||||
contract = self.archive.root / "contract.json"
|
||||
atomic_json(contract, {"tals": [], "policy": "fixed"})
|
||||
epoch = select_epoch(self.archive.root, {self.uri: {"first_seen_ms": 0}}, now_ms())
|
||||
atomic_json(self.archive.root / "epochs/epoch_0000.json", epoch)
|
||||
self.assertTrue(verify(self.archive.root)["pass"])
|
||||
atomic_json(contract, {"tals": [], "policy": "different"})
|
||||
self.assertFalse(verify(self.archive.root)["pass"])
|
||||
|
||||
def test_zero_exit_with_only_four_anchors_never_qualifies_main_capture(self):
|
||||
tals = []
|
||||
for index in range(5):
|
||||
path = Path(self.tmp.name) / f"fixture-{index}.tal"
|
||||
path.write_text(f"https://fixture.example/{index}.cer\n\nunit-test-input\n")
|
||||
tals.append(str(path))
|
||||
capture = Capture({"archive_root": str(Path(self.tmp.name) / "main"), "binary": sys.executable, "tals": tals})
|
||||
run = capture.root / "unit-run"
|
||||
run.mkdir()
|
||||
(run / "stderr.log").write_text("wrote CIR: unit (objects=1, trust_anchors=4, total_ms=1)\n")
|
||||
(run / "stdout.log").write_text("vrps=100\n")
|
||||
capture.metadata["runs"] = [{"path": str(run)}]
|
||||
capture.rp = Mock()
|
||||
capture.rp.poll.return_value = 0
|
||||
capture.rp_started = time.monotonic()
|
||||
with self.assertRaisesRegex(RuntimeError, "all five"):
|
||||
capture.check_rp()
|
||||
|
||||
def test_ta_refresh_event_is_bound_to_the_epoch(self):
|
||||
ref = self.archive.put_stream(io.BytesIO(b"unit TA entity"))
|
||||
uri = "https://ta.example/real-endpoint.cer"
|
||||
event = self.archive.event({"source": "ta_refresh", "transport": "http", "kind": "object", "uri": uri,
|
||||
"started_ms": now_ms(), "complete": True, "body": ref})
|
||||
epoch = select_epoch(self.archive.root, {}, now_ms())
|
||||
self.assertEqual(epoch["ta_object_events"][uri], event["id"])
|
||||
|
||||
def test_gap_recording_keeps_incomplete_epochs_and_strict_default_gate(self):
|
||||
# Exercise controller policy only; the real five-TA acceptance is remote.
|
||||
tals = []
|
||||
for index in range(5):
|
||||
tal = Path(self.tmp.name) / f"policy-{index}.tal"
|
||||
tal.write_text(f"https://fixture.example/{index}.cer\n\nunit-input\n")
|
||||
tals.append(str(tal))
|
||||
for policy in ("abort", "record-with-gaps"):
|
||||
with self.subTest(policy=policy):
|
||||
config = {"archive_root": str(Path(self.tmp.name) / policy), "binary": sys.executable,
|
||||
"tals": tals, "duration_secs": 300, "bootstrap_attempts": 1}
|
||||
if policy != "abort":
|
||||
config["bootstrap_gap_policy"] = policy
|
||||
capture = Capture(config)
|
||||
run = capture.root / "controller-unit-run"
|
||||
run.mkdir()
|
||||
atomic_json(run / "validation-contract.json", {"test_only": True})
|
||||
capture.start_rp = lambda: capture.metadata["runs"].append({"path": str(run)})
|
||||
capture.discover = lambda: capture.registry.update({self.base + "/unreachable.xml": {"first_seen_ms": 0}})
|
||||
clock = Mock()
|
||||
clock.monotonic.side_effect = iter(range(0, 10000, 1000))
|
||||
with patch("capture.time", clock):
|
||||
capture.run()
|
||||
expected = "bootstrap_incomplete" if policy == "abort" else "recorded_with_gaps"
|
||||
self.assertEqual(capture.metadata["status"], expected)
|
||||
self.assertFalse(capture.metadata["bootstrap_complete"])
|
||||
self.assertEqual(capture.metadata["bootstrap_missing"], [self.base + "/unreachable.xml"])
|
||||
epoch = json.loads((capture.root / "epochs/epoch_0000.json").read_text())
|
||||
self.assertFalse(epoch["complete"])
|
||||
self.assertFalse(verify(capture.root)["pass"])
|
||||
self.assertEqual("t0_ms" in capture.metadata, policy != "abort")
|
||||
|
||||
def test_ta_refresh_tries_next_original_uri_and_pins_exact_entity(self):
|
||||
# A controller unit test; genuine SPKI/crypto acceptance is covered by the remote RP smoke.
|
||||
capture = Capture.__new__(Capture)
|
||||
capture.archive, capture.root = self.archive, self.archive.root
|
||||
tal = Path(self.tmp.name) / "test.tal"
|
||||
tal.write_text("https://ta.example/unavailable.cer\nhttps://ta.example/current.cer\n\nunit-input\n")
|
||||
destination = Path(self.tmp.name) / "ta"
|
||||
destination.mkdir()
|
||||
ref = self.archive.put_stream(io.BytesIO(b"exact downloaded TA bytes"))
|
||||
calls = []
|
||||
def download(uri, kind, previous=None, source="poller"):
|
||||
calls.append(uri)
|
||||
return self.archive.event({"source": source, "transport": "http", "kind": kind, "uri": uri,
|
||||
"started_ms": now_ms(), "complete": len(calls) == 2, "body": ref})
|
||||
capture.archive.fetch = download
|
||||
result = capture.refresh_ta(tal, destination)
|
||||
self.assertEqual(calls, ["https://ta.example/unavailable.cer", "https://ta.example/current.cer"])
|
||||
self.assertEqual(Path(result["path"]).read_bytes(), b"exact downloaded TA bytes")
|
||||
self.assertEqual(result["sha256"], ref["sha256"])
|
||||
|
||||
def test_dtd_and_duplicate_snapshot_objects_rejected(self):
|
||||
for body in (b'<!DOCTYPE snapshot [<!ENTITY a "test">]><snapshot/>',
|
||||
xml("snapshot", 1, publish(OBJECT, b"a") + publish(OBJECT, b"b"))):
|
||||
ref = self.archive.put_stream(io.BytesIO(body))
|
||||
with self.assertRaises(ValueError):
|
||||
payload_view(self.archive.blob_path(ref["sha256"]), "snapshot", SESSION, 1)
|
||||
|
||||
def test_blob_path_traversal_and_size_guard(self):
|
||||
with self.assertRaises(ValueError):
|
||||
self.archive.blob_path("../escape")
|
||||
small = Archive(Path(self.tmp.name) / "small", {"max_body_bytes": 2})
|
||||
with self.assertRaises(ValueError):
|
||||
small.put_stream(io.BytesIO(b"large"))
|
||||
self.assertFalse(list((small.root / "partial").iterdir()))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
106
scripts/experiments/reuse_eval/test_formal_metrics.py
Normal file
106
scripts/experiments/reuse_eval/test_formal_metrics.py
Normal file
@@ -0,0 +1,106 @@
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
from common import atomic_json
|
||||
from formal_metrics import collect, hit_ratios, interval_union
|
||||
|
||||
|
||||
class FormalMetricsTests(unittest.TestCase):
|
||||
def test_parallel_sync_union_and_reversed_bounds(self):
|
||||
self.assertEqual(interval_union([(20, 40), (0, 10), (5, 25), (50, 55)]), 45)
|
||||
self.assertEqual(interval_union([]), 0)
|
||||
with self.assertRaises(ValueError):
|
||||
interval_union([(5, 4)])
|
||||
|
||||
def test_hybrid_denominators_keep_layers_separate_and_do_not_double_count_context(self):
|
||||
stage = {"analysis_counts": {"child_certificate_cache_hit": 7, "child_certificate_cache_lookup": 10,
|
||||
"publication_point_cache_reuse_hits": 9, "publication_point_cache_lookup_total": 20},
|
||||
"roa_validation_cache": {"hit_roas": 50, "miss_roas": 20, "blocked_roas": 30, "context_blocked_roas": 15}}
|
||||
ratios = hit_ratios(stage, "hybrid")
|
||||
self.assertEqual(ratios["roa"]["ratio"], 0.5)
|
||||
self.assertEqual(ratios["child_certificate"]["ratio"], 0.7)
|
||||
self.assertEqual(ratios["publication_point"]["ratio"], 0.45)
|
||||
self.assertIsNone(ratios["signature"]["ratio"])
|
||||
stage["analysis_counts"]["publication_point_cache_reuse_hits"] = 21
|
||||
with self.assertRaises(ValueError):
|
||||
hit_ratios(stage, "hybrid")
|
||||
|
||||
def test_seven_metrics_fail_closed_on_clock_coverage_and_background_boundary(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
run, benchmark = root / "run", root / "t2"
|
||||
run.mkdir(); benchmark.mkdir()
|
||||
direct = {"schema_version": 1, "clock": "Linux CLOCK_MONOTONIC nanoseconds",
|
||||
"rp_start_ns": 20, "payload_ready_ns": 100, "sync_wall_union_ns": 40,
|
||||
"sync_intervals": [{"protocol": "rrdp", "uri": "good", "start_ns": 30, "end_ns": 60, "success": True},
|
||||
{"protocol": "rsync", "uri": "rsync://failed/repo/pp/", "start_ns": 50, "end_ns": 70, "success": False}],
|
||||
"rrdp_modes": {"good": "delta"}, "sync_boundary": "native union", "payload_boundary": "atomic CCR"}
|
||||
atomic_json(run / "evaluation.json", direct)
|
||||
atomic_json(run / "contract.json", {"rsyncScopePolicy": "module-root"})
|
||||
stage = {"analysis_counts": {}, "roa_validation_cache": {"hit_roas": 0, "miss_roas": 0, "blocked_roas": 0}}
|
||||
atomic_json(run / "stage-timing.json", stage)
|
||||
engine = {"boundary": "validation with background write drain", "wall_ns": 15, "user_cpu_secs": 0.1, "system_cpu_secs": 0.1}
|
||||
atomic_json(benchmark / "engine-timing.json", engine)
|
||||
(run / "process-time.txt").write_text("Maximum resident set size (kbytes): 1234\n")
|
||||
process = {"controller_trigger_monotonic_ns": 10, "cpu_ns": 500, "memory_peak_bytes": 9999}
|
||||
table = {"rrdp": {"good": "Success"}, "rsync": {"rsync://failed/repo/": {"Failure": "captured gap"}}}
|
||||
result = collect(run, benchmark, process, {"required_serialized_bytes": 0}, "baseline", table)
|
||||
self.assertEqual(result["update_to_payload_ns"], 90)
|
||||
self.assertEqual(result["repository_sync_ns"], 40)
|
||||
self.assertEqual(result["peak_rss_bytes"], 1234 * 1024)
|
||||
self.assertTrue((run / "transport-measurement-comparison.json").exists())
|
||||
with self.assertRaises(ValueError):
|
||||
collect(run, benchmark, {**process, "controller_trigger_monotonic_ns": 21}, {"required_serialized_bytes": 0}, "baseline", table)
|
||||
with self.assertRaises(ValueError):
|
||||
collect(run, benchmark, process, {"required_serialized_bytes": 0}, "baseline", {**table, "rrdp": {}})
|
||||
atomic_json(benchmark / "engine-timing.json", {**engine, "boundary": "missing drain"})
|
||||
with self.assertRaises(ValueError):
|
||||
collect(run, benchmark, process, {"required_serialized_bytes": 0}, "baseline", table)
|
||||
|
||||
def test_transport_scope_mapping_preserves_each_raw_success_and_failure(self):
|
||||
from formal_metrics import compare_transport_measurements
|
||||
rows = [{"protocol": "rsync", "uri": "rsync://host:873/repo/a/0/", "success": True},
|
||||
{"protocol": "rsync", "uri": "rsync://host:873/repo/b/", "success": True},
|
||||
{"protocol": "rsync", "uri": "rsync://gap/repo/pp/", "success": False},
|
||||
{"protocol": "rrdp", "uri": "https://host/notification.xml", "success": True}]
|
||||
table = {"rrdp": {"https://host/notification.xml": "Success"},
|
||||
"rsync": {"rsync://host:873/repo/": "Success", "rsync://gap/repo/": {"Failure": "gap"}}}
|
||||
proof = compare_transport_measurements(rows, table, "module-root")
|
||||
self.assertTrue(proof["pass"])
|
||||
self.assertEqual([r["uri"] for r in proof["intervals"]], [r["uri"] for r in rows])
|
||||
self.assertEqual([r["scope_uri"] for r in proof["intervals"][:2]], ["rsync://host:873/repo/"] * 2)
|
||||
self.assertEqual([r["success"] for r in proof["intervals"]], [True, True, False, True])
|
||||
|
||||
def test_transport_scope_mapping_rejects_missing_extra_wrong_or_conflicting_rows(self):
|
||||
from formal_metrics import compare_transport_measurements
|
||||
good = {"protocol": "rsync", "uri": "rsync://host/repo/pp/", "success": True}
|
||||
table = {"rrdp": {}, "rsync": {"rsync://host/repo/": "Success"}}
|
||||
cases = [[], [{**good, "uri": "rsync://other/repo/pp/"}],
|
||||
[{**good, "uri": "rsync://host/repository/pp/"}],
|
||||
[good, {**good, "uri": "rsync://host/other/pp/"}],
|
||||
[good, {**good, "success": False}], [{**good, "success": 1}],
|
||||
[{**good, "protocol": "unknown"}]]
|
||||
for rows in cases:
|
||||
with self.subTest(rows=rows), self.assertRaises(ValueError):
|
||||
compare_transport_measurements(rows, table, "module-root")
|
||||
for outcome in ["Skipped", {}, {"Failure": None}]:
|
||||
with self.subTest(outcome=outcome), self.assertRaises(ValueError):
|
||||
compare_transport_measurements([good], {"rrdp": {}, "rsync": {"rsync://host/repo/": outcome}}, "module-root")
|
||||
|
||||
def test_publication_and_host_scope_keep_fetch_uri_and_reject_unknown_policy(self):
|
||||
from formal_metrics import compare_transport_measurements
|
||||
row = {"protocol": "rsync", "uri": "rsync://host/repo/pp/", "success": True}
|
||||
exact = {"rrdp": {}, "rsync": {row["uri"]: "Success"}}
|
||||
module = {"rrdp": {}, "rsync": {"rsync://host/repo/": "Success"}}
|
||||
for scope in ["publication-point", "host"]:
|
||||
self.assertTrue(compare_transport_measurements([row], exact, scope)["pass"])
|
||||
with self.assertRaises(ValueError):
|
||||
compare_transport_measurements([row], module, scope)
|
||||
for scope in [None, "", "unknown"]:
|
||||
with self.assertRaises(ValueError):
|
||||
compare_transport_measurements([row], exact, scope)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
114
scripts/experiments/reuse_eval/test_replay.py
Normal file
114
scripts/experiments/reuse_eval/test_replay.py
Normal file
@@ -0,0 +1,114 @@
|
||||
from http.server import ThreadingHTTPServer
|
||||
import io
|
||||
import json
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import threading
|
||||
import unittest
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
from common import Archive, atomic_json, now_ms
|
||||
from prepare_replay import host_mapping, rsync_tree, tls_assets
|
||||
from serve import ReplayState, handler_for, uri_key
|
||||
|
||||
|
||||
class ReplayTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.tmp.cleanup)
|
||||
self.root = Path(self.tmp.name)
|
||||
self.archive = Archive(self.root / "archive")
|
||||
self.ref = self.archive.put_stream(io.BytesIO(b"original notification bytes"))
|
||||
self.observation = {"id": "observation", "uri": "https://rp.example/notification.xml", "complete": True,
|
||||
"session": "session", "serial": 1, "notification": self.ref, "view": "view", "completed_ms": 1,
|
||||
"references": []}
|
||||
atomic_json(self.archive.root / "observations/observation.json", self.observation)
|
||||
self.epoch = {"complete": True, "validation_time_ms": 2, "repositories": {
|
||||
self.observation["uri"]: {k: self.observation[k] for k in ("id", "session", "serial", "notification", "view", "completed_ms")}},
|
||||
"ta_object_events": {}, "rsync_view_events": {}}
|
||||
self.epoch_path = self.archive.root / "epochs/epoch_0000.json"
|
||||
atomic_json(self.epoch_path, self.epoch)
|
||||
|
||||
def test_uri_identity_preserves_query_and_normalizes_default_origin(self):
|
||||
self.assertEqual(uri_key("https://RP.EXAMPLE:443/a?x=1"), uri_key("https://rp.example/a?x=1"))
|
||||
self.assertNotEqual(uri_key("https://rp.example/a?x=1"), uri_key("https://rp.example/a?x=2"))
|
||||
self.assertNotEqual(uri_key("https://rp.example:8443/a"), uri_key("https://rp.example/a"))
|
||||
|
||||
def test_running_state_does_not_drift_when_epoch_file_changes(self):
|
||||
state = ReplayState(self.archive.root, self.epoch_path)
|
||||
self.observation["notification"] = self.archive.put_stream(io.BytesIO(b"future version"))
|
||||
atomic_json(self.archive.root / "observations/observation.json", self.observation)
|
||||
self.assertEqual(state.entries[uri_key("https://rp.example/notification.xml")]["sha256"], self.ref["sha256"])
|
||||
|
||||
def test_http_exact_bytes_conditional_and_unknown_uri(self):
|
||||
state = ReplayState(self.archive.root, self.epoch_path)
|
||||
server = ThreadingHTTPServer(("127.0.0.1", 0), handler_for(state, "https"))
|
||||
self.addCleanup(server.server_close)
|
||||
self.addCleanup(server.shutdown)
|
||||
threading.Thread(target=server.serve_forever, daemon=True).start()
|
||||
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
|
||||
actual = f"http://127.0.0.1:{server.server_port}"
|
||||
def request(path, **headers):
|
||||
return opener.open(urllib.request.Request(actual + path, headers={"Host": "rp.example", **headers}), timeout=3)
|
||||
with request("/notification.xml") as response:
|
||||
self.assertEqual(response.read(), b"original notification bytes")
|
||||
etag = response.headers["ETag"]
|
||||
with self.assertRaises(urllib.error.HTTPError) as exc:
|
||||
request("/notification.xml", **{"If-None-Match": etag})
|
||||
self.assertEqual(exc.exception.code, 304)
|
||||
with self.assertRaises(urllib.error.HTTPError) as exc:
|
||||
request("/missing.xml")
|
||||
self.assertEqual(exc.exception.code, 404)
|
||||
|
||||
def test_incomplete_and_future_bindings_are_rejected(self):
|
||||
self.epoch["complete"] = False
|
||||
atomic_json(self.epoch_path, self.epoch)
|
||||
with self.assertRaises(ValueError):
|
||||
ReplayState(self.archive.root, self.epoch_path)
|
||||
self.epoch["complete"] = True
|
||||
self.epoch["validation_time_ms"] = 0
|
||||
atomic_json(self.epoch_path, self.epoch)
|
||||
with self.assertRaisesRegex(ValueError, "future"):
|
||||
ReplayState(self.archive.root, self.epoch_path)
|
||||
|
||||
def test_rsync_same_module_on_different_hosts_is_separated(self):
|
||||
state = ReplayState(self.archive.root, self.epoch_path)
|
||||
state.rsync_events = [{"completed_ms": 1, "kind": "view", "uri": f"rsync://{host}/repo/",
|
||||
"objects": {f"rsync://{host}/repo/a.roa": self.ref}} for host in ("a.example", "b.example")]
|
||||
mapping = host_mapping(["a.example", "b.example"])
|
||||
self.assertNotEqual(mapping["a.example"], mapping["b.example"])
|
||||
configs = rsync_tree(state, self.root / "rsync", mapping)
|
||||
self.assertEqual(len(configs), 2)
|
||||
for path in configs:
|
||||
file = Path(path).parent / "modules/repo/a.roa"
|
||||
self.assertEqual(file.read_bytes(), b"original notification bytes")
|
||||
|
||||
def test_newer_rsync_scope_preserves_deletions(self):
|
||||
state = ReplayState(self.archive.root, self.epoch_path)
|
||||
state.rsync_events = [{"completed_ms": 1, "kind": "view", "uri": "rsync://a.example/repo/",
|
||||
"objects": {"rsync://a.example/repo/a.roa": self.ref}},
|
||||
{"completed_ms": 2, "kind": "view", "uri": "rsync://a.example/repo/", "objects": {}}]
|
||||
configs = rsync_tree(state, self.root / "rsync", host_mapping(["a.example"]))
|
||||
self.assertEqual(len(configs), 1)
|
||||
self.assertFalse(list((Path(configs[0]).parent / "modules/repo").iterdir()))
|
||||
|
||||
def test_rsync_path_traversal_is_rejected(self):
|
||||
state = ReplayState(self.archive.root, self.epoch_path)
|
||||
state.rsync_events = [{"completed_ms": 1, "kind": "view", "uri": "rsync://a.example/repo/",
|
||||
"objects": {"rsync://a.example/repo/../../escape": self.ref}}]
|
||||
with self.assertRaisesRegex(ValueError, "unsafe"):
|
||||
rsync_tree(state, self.root / "rsync", host_mapping(["a.example"]))
|
||||
|
||||
def test_tls_assets_are_stable_and_do_not_accept_new_hosts_silently(self):
|
||||
hosts = ["a.example", "b.example"]
|
||||
first = tls_assets(self.root / "replay", hosts)
|
||||
content = Path(first["ca"]).read_bytes()
|
||||
second = tls_assets(self.root / "replay", hosts)
|
||||
self.assertEqual(content, Path(second["ca"]).read_bytes())
|
||||
with self.assertRaises(ValueError):
|
||||
tls_assets(self.root / "replay", hosts + ["c.example"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
257
scripts/experiments/reuse_eval/test_scope.py
Normal file
257
scripts/experiments/reuse_eval/test_scope.py
Normal file
@@ -0,0 +1,257 @@
|
||||
import base64
|
||||
from email.message import Message
|
||||
import io
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import Mock
|
||||
|
||||
from common import Archive, atomic_json, file_sha256, read_json
|
||||
from prepare_replay import host_mapping, rsync_tree
|
||||
from rrdp import payload_view, view_digest
|
||||
from scope import describe, load_scope, require_closure
|
||||
from serve import ReplayState, handler_for, uri_key
|
||||
from verify import verify
|
||||
|
||||
|
||||
class ScopeTests(unittest.TestCase):
|
||||
"""Synthetic protocol/eligibility tests; never real-TA or performance evidence."""
|
||||
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.tmp.cleanup)
|
||||
self.base = Path(self.tmp.name)
|
||||
self.root = self.base / "archive"
|
||||
self.archive = Archive(self.root)
|
||||
self.uri = "https://rp.example/notification.xml"
|
||||
self.excluded = "https://gap.example/notification.xml"
|
||||
self.ta_uri = "https://ta.example/root.cer"
|
||||
self.counts = {"repositories": 1, "excluded": 1, "epochs": 2, "trust_anchors": 1, "step_ms": 300_000}
|
||||
tal = self.archive.put_stream(io.BytesIO(b"unit TAL"))
|
||||
(self.root / "inputs").mkdir()
|
||||
(self.root / "inputs/test.tal").write_bytes(b"unit TAL")
|
||||
atomic_json(self.root / "contract.json", {"tals": [{**tal, "path": "test.tal"}]})
|
||||
atomic_json(self.root / "capture.json", {"t0_ms": 300_000, "end_ms": 600_000})
|
||||
atomic_json(self.root / "registry.json", {self.uri: {}, self.excluded: {}})
|
||||
self.body = b"exact unit publication bytes"
|
||||
snapshot = (b'<snapshot xmlns="http://www.ripe.net/rpki/rrdp" version="1" session_id="11111111-1111-4111-8111-111111111111" serial="1">'
|
||||
b'<publish uri="rsync://rp.example/repo/a.roa">' + base64.b64encode(self.body) + b'</publish></snapshot>')
|
||||
snap = self.archive.put_stream(io.BytesIO(snapshot))
|
||||
note = self.archive.put_stream(io.BytesIO(
|
||||
(f'<notification xmlns="http://www.ripe.net/rpki/rrdp" version="1" session_id="11111111-1111-4111-8111-111111111111" serial="1">'
|
||||
f'<snapshot uri="https://rp.example/snapshot.xml" hash="{snap["sha256"]}"/></notification>').encode()))
|
||||
self.view = payload_view(self.archive.blob_path(snap["sha256"]), "snapshot", "11111111-1111-4111-8111-111111111111", 1)
|
||||
digest = view_digest(self.view)
|
||||
atomic_json(self.root / f"views/{digest}.json", self.view)
|
||||
ta_body = self.archive.put_stream(io.BytesIO(b"unit TA"))
|
||||
atomic_json(self.root / "events/ta.json", {"id": "ta", "uri": self.ta_uri, "complete": True,
|
||||
"completed_ms": 1, "transport": "http", "kind": "object", "body": ta_body})
|
||||
self.epoch_paths = []
|
||||
reports = []
|
||||
for i in range(2):
|
||||
obs = {"id": f"obs{i}", "uri": self.uri, "complete": True, "completed_ms": i * 300_000 + 2,
|
||||
"started_ms": i * 300_000 + 1, "session": "11111111-1111-4111-8111-111111111111", "serial": 1, "notification": note,
|
||||
"view": digest, "references": [{**snap, "kind": "snapshot", "uri": "https://rp.example/snapshot.xml",
|
||||
"serial": 1, "available": True}]}
|
||||
atomic_json(self.root / f"observations/{obs['id']}.json", obs)
|
||||
epoch = {"complete": False, "validation_time_ms": (i + 1) * 300_000,
|
||||
"contract_sha256": file_sha256(self.root / "contract.json"), "missing": [self.excluded],
|
||||
"blocked_latest_attempts": [], "repositories": {self.uri: {k: obs[k] for k in
|
||||
("id", "session", "serial", "notification", "view", "completed_ms")}},
|
||||
"latest_attempts": {self.uri: {k: obs[k] for k in ("id", "complete", "completed_ms")},
|
||||
self.excluded: {"complete": False}},
|
||||
"ta_object_events": {self.ta_uri: "ta"}, "rsync_view_events": {}}
|
||||
path = self.root / f"epochs/epoch_{i:04d}.json"
|
||||
atomic_json(path, epoch)
|
||||
self.epoch_paths.append(path)
|
||||
reports.append({"epoch": path.name, "pass": False, "repositories": 1,
|
||||
"errors": [f"missing repositories: {[self.excluded]}"]})
|
||||
atomic_json(self.root / "closure-report.json", {"pass": False, "errors": [], "epochs": reports})
|
||||
self.scope_path = self.base / "scope/scope.json"
|
||||
|
||||
def scope(self, routes=None):
|
||||
result = describe(self.root, routes or {}, self.counts)
|
||||
atomic_json(self.scope_path, result)
|
||||
return result
|
||||
|
||||
def fingerprint(self):
|
||||
return {str(p.relative_to(self.root)): (file_sha256(p), p.stat().st_mode)
|
||||
for p in self.root.rglob("*") if p.is_file()}
|
||||
|
||||
def native_route(self):
|
||||
scope_uri = "rsync://rp.example/repo/"
|
||||
obj = self.archive.put_stream(io.BytesIO(self.body))
|
||||
event = {"id": "native", "uri": scope_uri, "complete": True, "source": "rpki", "kind": "view",
|
||||
"transport": "rsync", "started_ms": 400_000, "completed_ms": 500_000,
|
||||
"objects": {"rsync://rp.example/repo/a.roa": obj}}
|
||||
atomic_json(self.root / "events/native.json", event)
|
||||
epoch = read_json(self.epoch_paths[1])
|
||||
epoch["rsync_view_events"] = {scope_uri: "native"}
|
||||
atomic_json(self.epoch_paths[1], epoch)
|
||||
return {self.epoch_paths[1].name: {self.uri: {"rsync_uri": scope_uri, "event_id": "native", "http_status": 503}}}
|
||||
|
||||
def request(self, state, uri, etag=None):
|
||||
handler = handler_for(state, "https").__new__(handler_for(state, "https"))
|
||||
handler.path = "/" + uri.split("/", 3)[3]
|
||||
handler.headers = Message()
|
||||
handler.headers["Host"] = uri.split("/", 3)[2]
|
||||
if etag:
|
||||
handler.headers["If-None-Match"] = etag
|
||||
handler.wfile = io.BytesIO()
|
||||
handler.send_response, handler.send_header, handler.end_headers = Mock(), Mock(), Mock()
|
||||
handler.handle_entity(head=False)
|
||||
return handler.send_response.call_args.args[0], handler.wfile.getvalue()
|
||||
|
||||
def test_scope_verify_keeps_original_incomplete_and_all_source_bytes(self):
|
||||
before = self.fingerprint()
|
||||
self.scope()
|
||||
self.assertEqual(load_scope(self.root, self.scope_path)["counts"], self.counts)
|
||||
result = verify(self.root, self.scope_path)
|
||||
self.assertTrue(result["pass"], result)
|
||||
self.assertFalse(result["original_complete"])
|
||||
self.assertEqual(len(result["epochs"]), 2)
|
||||
self.assertEqual(self.fingerprint(), before)
|
||||
|
||||
def test_scope_and_report_cannot_overwrite_original(self):
|
||||
self.scope()
|
||||
with self.assertRaisesRegex(ValueError, "outside"):
|
||||
load_scope(self.root, self.root / "scope.json")
|
||||
with self.assertRaisesRegex(ValueError, "outside"):
|
||||
verify(self.root, self.scope_path, self.root / "closure-report.json")
|
||||
with self.assertRaisesRegex(ValueError, "overwrite scope"):
|
||||
verify(self.root, self.scope_path, self.scope_path)
|
||||
(self.root / "escape.json").symlink_to(self.base / "outside.json")
|
||||
with self.assertRaisesRegex(ValueError, "outside"):
|
||||
verify(self.root, self.scope_path, self.root / "escape.json")
|
||||
|
||||
def test_no_scope_still_rejects_incomplete_epoch(self):
|
||||
with self.assertRaisesRegex(ValueError, "incomplete"):
|
||||
ReplayState(self.root, self.epoch_paths[0])
|
||||
self.scope()
|
||||
state = ReplayState(self.root, self.epoch_paths[0], self.scope_path)
|
||||
self.assertEqual(self.request(state, self.ta_uri), (200, b"unit TA"))
|
||||
self.assertEqual(self.request(state, self.excluded), (503, b""))
|
||||
self.assertEqual(self.request(state, "https://unknown.example/a"), (404, b""))
|
||||
|
||||
def test_unavailable_blob_fails_scoped_closure_without_modifying_original_report(self):
|
||||
self.scope()
|
||||
before = file_sha256(self.root / "closure-report.json")
|
||||
ta = read_json(self.root / "events/ta.json")
|
||||
self.archive.blob_path(ta["body"]["sha256"]).unlink()
|
||||
result = verify(self.root, self.scope_path)
|
||||
self.assertFalse(result["pass"])
|
||||
self.assertTrue(result["errors"])
|
||||
self.assertEqual(file_sha256(self.root / "closure-report.json"), before)
|
||||
|
||||
def test_server_requires_successful_independent_scoped_closure(self):
|
||||
self.scope()
|
||||
with self.assertRaises(FileNotFoundError):
|
||||
require_closure(self.root, self.scope_path)
|
||||
verify(self.root, self.scope_path)
|
||||
require_closure(self.root, self.scope_path)
|
||||
path = self.scope_path.with_name("scoped-closure-report.json")
|
||||
report = read_json(path)
|
||||
report["scope_sha256"] = "0" * 64
|
||||
atomic_json(path, report)
|
||||
with self.assertRaisesRegex(ValueError, "closure"):
|
||||
require_closure(self.root, self.scope_path)
|
||||
|
||||
def test_source_or_scope_tampering_rejected(self):
|
||||
scope = self.scope()
|
||||
scope["included_repositories"] = []
|
||||
atomic_json(self.scope_path, scope)
|
||||
with self.assertRaisesRegex(ValueError, "provenance"):
|
||||
load_scope(self.root, self.scope_path)
|
||||
self.scope()
|
||||
atomic_json(self.root / "contract.json", {"tals": []})
|
||||
with self.assertRaisesRegex(ValueError, "trust anchors"):
|
||||
load_scope(self.root, self.scope_path)
|
||||
|
||||
def test_new_epoch_missing_epoch_or_shifted_time_rejected(self):
|
||||
for change in ("extra", "missing", "time"):
|
||||
with self.subTest(change=change):
|
||||
path = self.epoch_paths[1]
|
||||
original = read_json(path)
|
||||
if change == "extra":
|
||||
atomic_json(self.root / "epochs/epoch_0002.json", original)
|
||||
elif change == "missing":
|
||||
path.unlink()
|
||||
else:
|
||||
atomic_json(path, {**original, "validation_time_ms": 600_001})
|
||||
with self.assertRaises(ValueError):
|
||||
self.scope()
|
||||
(self.root / "epochs/epoch_0002.json").unlink(missing_ok=True)
|
||||
atomic_json(path, original)
|
||||
|
||||
def test_failed_latest_future_binding_and_lost_ta_rejected(self):
|
||||
path = self.epoch_paths[1]
|
||||
original = read_json(path)
|
||||
for change in ("latest", "future", "ta", "scope"):
|
||||
epoch = read_json(path)
|
||||
if change == "latest":
|
||||
epoch["latest_attempts"][self.uri]["complete"] = False
|
||||
elif change == "future":
|
||||
epoch["repositories"][self.uri]["completed_ms"] = 600_001
|
||||
epoch["latest_attempts"][self.uri]["completed_ms"] = 600_001
|
||||
elif change == "ta":
|
||||
epoch["ta_object_events"] = {}
|
||||
else:
|
||||
epoch["repositories"]["https://changed.example/n"] = epoch["repositories"].pop(self.uri)
|
||||
atomic_json(path, epoch)
|
||||
with self.subTest(change=change), self.assertRaises(ValueError):
|
||||
self.scope()
|
||||
atomic_json(path, original)
|
||||
|
||||
def test_non_coverage_closure_error_cannot_be_waived(self):
|
||||
report = read_json(self.root / "closure-report.json")
|
||||
report["epochs"][1]["errors"].append("bad delta hash")
|
||||
atomic_json(self.root / "closure-report.json", report)
|
||||
with self.assertRaisesRegex(ValueError, "unapproved"):
|
||||
self.scope()
|
||||
|
||||
def test_native_route_only_applies_to_bound_epoch_and_never_returns_304(self):
|
||||
routes = self.native_route()
|
||||
self.scope(routes)
|
||||
early = ReplayState(self.root, self.epoch_paths[0], self.scope_path)
|
||||
final = ReplayState(self.root, self.epoch_paths[1], self.scope_path)
|
||||
self.assertEqual(self.request(early, self.uri)[0], 200)
|
||||
etag = '"sha256:' + final.entries[uri_key(self.uri)]["sha256"] + '"'
|
||||
self.assertEqual(self.request(final, self.uri, etag), (503, b""))
|
||||
self.assertEqual(len(early.rsync_events), 0)
|
||||
self.assertEqual(len(final.rsync_events), 1)
|
||||
self.assertTrue(verify(self.root, self.scope_path)["pass"])
|
||||
|
||||
def test_native_route_rejects_future_foreign_or_unbound_event(self):
|
||||
routes = self.native_route()
|
||||
original = read_json(self.root / "events/native.json")
|
||||
for change in ({"completed_ms": 600_001}, {"source": "derived"}, {"complete": False}):
|
||||
atomic_json(self.root / "events/native.json", {**original, **change})
|
||||
with self.subTest(change=change), self.assertRaises(ValueError):
|
||||
self.scope(routes)
|
||||
atomic_json(self.root / "events/native.json", original)
|
||||
with self.assertRaisesRegex(ValueError, "explicit route"):
|
||||
self.scope()
|
||||
|
||||
def test_rsync_assets_do_not_change_or_share_archived_inode(self):
|
||||
self.scope(self.native_route())
|
||||
state = ReplayState(self.root, self.epoch_paths[1], self.scope_path)
|
||||
before = self.fingerprint()
|
||||
configs = rsync_tree(state, self.base / "rsync", host_mapping(["rp.example"]))
|
||||
target = Path(configs[0]).parent / "modules/repo/a.roa"
|
||||
source = self.archive.blob_path(state.rsync_events[0]["objects"]["rsync://rp.example/repo/a.roa"]["sha256"])
|
||||
self.assertEqual(target.read_bytes(), self.body)
|
||||
self.assertNotEqual(target.stat().st_ino, source.stat().st_ino)
|
||||
self.assertEqual(self.fingerprint(), before)
|
||||
|
||||
def test_readonly_archive_never_creates_directories_or_events(self):
|
||||
root = self.base / "missing"
|
||||
archive = Archive(root, read_only=True)
|
||||
self.assertFalse(root.exists())
|
||||
with self.assertRaisesRegex(ValueError, "read-only"):
|
||||
archive.put_stream(io.BytesIO(b"no"))
|
||||
with self.assertRaisesRegex(ValueError, "read-only"):
|
||||
archive.event({})
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
166
scripts/experiments/reuse_eval/test_sequence_matrix.py
Normal file
166
scripts/experiments/reuse_eval/test_sequence_matrix.py
Normal file
@@ -0,0 +1,166 @@
|
||||
from pathlib import Path
|
||||
import copy
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import Mock, patch
|
||||
|
||||
from common import atomic_json, read_json
|
||||
from sequence_matrix import PROFILE_FLAGS, compare_profile_contracts, payload_counts, require_ready, require_t2_fallback_bindings, require_transport, rp_command, run_pilot, systemd_measure
|
||||
|
||||
|
||||
class SequenceMatrixTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.tmp.cleanup)
|
||||
self.root = Path(self.tmp.name)
|
||||
|
||||
def test_commands_preserve_protocol_state_and_use_full_scope(self):
|
||||
private = self.root / "object"
|
||||
manifest = {"tls": {"ca": "/fixture/ca.pem"}}
|
||||
command1 = rp_command(Path("/fixture/rpki"), private, private / "step_0000", manifest,
|
||||
1794218084957, "object", ["--tal-path", "/fixture/a.tal", "--ta-path", "/fixture/a.cer"])
|
||||
command2 = rp_command(Path("/fixture/rpki"), private, private / "step_0001", manifest,
|
||||
1794218384957, "object", ["--tal-path", "/fixture/a.tal", "--ta-path", "/fixture/a.cer"])
|
||||
self.assertEqual(command1[command1.index("--db") + 1], command2[command2.index("--db") + 1])
|
||||
self.assertNotIn("--max-instances", command1)
|
||||
self.assertNotIn("--disable-rrdp", command1)
|
||||
self.assertNotIn("--enable-crypto-signature-cache", command1)
|
||||
self.assertEqual(command2[command2.index("--validation-time") + 1], "2026-11-09T09:59:44Z")
|
||||
self.assertEqual(set(PROFILE_FLAGS), {"baseline", "signature", "object", "pp", "hybrid"})
|
||||
self.assertEqual(PROFILE_FLAGS["baseline"], [])
|
||||
self.assertEqual(set(PROFILE_FLAGS["hybrid"]), set(PROFILE_FLAGS["object"] + PROFILE_FLAGS["pp"]))
|
||||
|
||||
def test_native_route_and_scope_must_match_actual_outcomes(self):
|
||||
scope = {"included_repositories": ["good", "fallback"], "excluded_repositories": ["gap"],
|
||||
"routes": {"epoch_0012.json": {"fallback": {"rsync_uri": "rsync://native/repo/"}}}}
|
||||
table = {"rrdp": {"good": "Success", "fallback": {"Failure": "recorded"}, "gap": {"Failure": "excluded"}},
|
||||
"rsync": {"rsync://native/repo/": "Success"}}
|
||||
require_transport(table, scope, "epoch_0012.json")
|
||||
for key, value in (("fallback", "Success"), ("good", {"Failure": "new failure"}), ("gap", "Success")):
|
||||
changed = {"rrdp": {**table["rrdp"], key: value}, "rsync": table["rsync"]}
|
||||
with self.subTest(key=key), self.assertRaises(ValueError):
|
||||
require_transport(changed, scope, "epoch_0012.json")
|
||||
with self.assertRaises(ValueError):
|
||||
require_transport({**table, "rsync": {}}, scope, "epoch_0012.json")
|
||||
with self.assertRaises(ValueError):
|
||||
require_transport({**table, "rrdp": {**table["rrdp"], "unbound": "Success"}}, scope, "epoch_0012.json")
|
||||
|
||||
def test_full_payload_counts_do_not_require_loading_the_report(self):
|
||||
stdout = self.root / "stdout.log"
|
||||
stdout.write_text("vrps=1046609\naspas=4046\naudit_publication_points=56142\n")
|
||||
self.assertEqual(payload_counts(self.root), {"vrps": 1046609, "aspas": 4046, "publication_points": 56142})
|
||||
for body in ("vrps=0\naspas=1\naudit_publication_points=1\n", "vrps=1\n",
|
||||
"vrps=1\nvrps=2\naspas=1\naudit_publication_points=1\n"):
|
||||
stdout.write_text(body)
|
||||
with self.assertRaises(ValueError):
|
||||
payload_counts(self.root)
|
||||
|
||||
def test_readiness_rejects_wrong_scope_or_dead_server(self):
|
||||
ready = self.root / "ready.json"
|
||||
atomic_json(ready, {"epoch": "epoch", "scope": "scope"})
|
||||
server = Mock()
|
||||
server.poll.return_value = None
|
||||
self.assertEqual(require_ready(ready, server, "epoch", "scope")["epoch"], "epoch")
|
||||
with self.assertRaisesRegex(ValueError, "different"):
|
||||
require_ready(ready, server, "epoch", "another-scope")
|
||||
server.poll.return_value = 1
|
||||
with self.assertRaisesRegex(RuntimeError, "exited"):
|
||||
require_ready(ready, server, "epoch", "scope")
|
||||
|
||||
def test_cgroup_measurement_retains_accounting_then_stops_only_own_unit(self):
|
||||
properties = "\n".join(["ActiveState=active", "SubState=exited", "Result=success", "ExecMainCode=1",
|
||||
"ExecMainStatus=0", "CPUUsageNSec=1000000000", "MemoryPeak=2000000"])
|
||||
with patch("sequence_matrix.call", side_effect=[Mock(), Mock(stdout=properties)]) as call_mock, \
|
||||
patch("sequence_matrix.subprocess.run") as stop_mock:
|
||||
result = systemd_measure(["/fixture/rpki", "--db", "/fixture/state/db"], self.root, {"TMPDIR": "/fixture/tmp"}, 5)
|
||||
self.assertEqual(result["cpu_ns"], 1000000000)
|
||||
self.assertEqual(result["memory_peak_bytes"], 2000000)
|
||||
launcher = call_mock.call_args_list[0].args[0]
|
||||
self.assertIn("RemainAfterExit=yes", launcher)
|
||||
self.assertIn("AllowedCPUs=1-3", launcher)
|
||||
self.assertIn("MemoryMax=5G", launcher)
|
||||
self.assertIn("rp187rp", launcher)
|
||||
self.assertEqual(stop_mock.call_args.args[0], ["systemctl", "stop", result["unit"]])
|
||||
self.assertEqual(read_json(self.root / "process-resource.json")["cpu_ns"], 1000000000)
|
||||
|
||||
def test_failed_cgroup_sample_does_not_publish_valid_metrics_and_is_stopped(self):
|
||||
props = "ActiveState=failed\nSubState=failed\nResult=oom-kill\nExecMainStatus=9\n"
|
||||
with patch("sequence_matrix.call", side_effect=[Mock(), Mock(stdout=props)]), \
|
||||
patch("sequence_matrix.subprocess.run") as stop_mock:
|
||||
with self.assertRaisesRegex(RuntimeError, "failed"):
|
||||
systemd_measure(["/fixture/rpki"], self.root, {"TMPDIR": "/fixture/tmp"}, 5)
|
||||
self.assertFalse((self.root / "process-resource.json").exists())
|
||||
self.assertTrue((self.root / "systemd-final.json").exists())
|
||||
self.assertEqual(stop_mock.call_args.args[0][:2], ["systemctl", "stop"])
|
||||
|
||||
def test_pilot_never_executes_on_an_unassigned_machine(self):
|
||||
with patch("sequence_matrix.socket.gethostname", return_value="unassigned"), \
|
||||
patch("sequence_matrix.call") as call_mock:
|
||||
with self.assertRaisesRegex(ValueError, "designated 186"):
|
||||
run_pilot({})
|
||||
call_mock.assert_not_called()
|
||||
|
||||
def test_cross_profile_contract_allows_different_cache_histories_only(self):
|
||||
baseline = {"cache": {"publicationPoint": False}, "validationTime": "2026-11-09T10:49:44Z",
|
||||
"binarySha256": "33" * 32, "policy": {"strict": True},
|
||||
"fallbackReplaySelections": [{"manifestRsyncUri": "rsync://example/repo/a.mft",
|
||||
"vcirSha256": "11" * 32, "reuseIdentitySha256": "22" * 32}]}
|
||||
actual = copy.deepcopy(baseline)
|
||||
actual["cache"]["publicationPoint"] = True
|
||||
actual["fallbackReplaySelections"][0].update(vcirSha256="44" * 32, reuseIdentitySha256="55" * 32)
|
||||
proof = compare_profile_contracts(actual, baseline)
|
||||
self.assertTrue(proof["pass"])
|
||||
self.assertEqual(proof["baseline_fallback"], baseline["fallbackReplaySelections"])
|
||||
self.assertEqual(proof["actual_fallback"], actual["fallbackReplaySelections"])
|
||||
for field, value in [("validationTime", "2026-11-09T10:44:44Z"),
|
||||
("binarySha256", "66" * 32), ("policy", {"strict": False}),
|
||||
("unexpectedPolicyField", True)]:
|
||||
bad = copy.deepcopy(actual)
|
||||
bad[field] = value
|
||||
with self.subTest(field=field), self.assertRaisesRegex(ValueError, "configuration"):
|
||||
compare_profile_contracts(bad, baseline)
|
||||
for mutation in [lambda rows: rows.clear(),
|
||||
lambda rows: rows.append(copy.deepcopy(rows[0])),
|
||||
lambda rows: rows[0].update(manifestRsyncUri="rsync://example/repo/b.mft"),
|
||||
lambda rows: rows[0].update(vcirSha256="bad"),
|
||||
lambda rows: rows[0].update(reuseIdentitySha256=""),
|
||||
lambda rows: rows[0].update(extra=True)]:
|
||||
bad = copy.deepcopy(actual)
|
||||
mutation(bad["fallbackReplaySelections"])
|
||||
with self.assertRaises(ValueError):
|
||||
compare_profile_contracts(bad, baseline)
|
||||
self.assertEqual(actual["fallbackReplaySelections"][0]["vcirSha256"], "44" * 32)
|
||||
|
||||
def test_cross_profile_contract_checks_no_fallback_and_ordering(self):
|
||||
self.assertTrue(compare_profile_contracts({"cache": {}}, {"cache": {}})["pass"])
|
||||
a = {"manifestRsyncUri": "rsync://example/a.mft", "vcirSha256": "11" * 32,
|
||||
"reuseIdentitySha256": "22" * 32}
|
||||
b = {**a, "manifestRsyncUri": "rsync://example/b.mft"}
|
||||
for rows in [[b, a], [a, a], None, {}, "bad"]:
|
||||
with self.subTest(rows=rows), self.assertRaises(ValueError):
|
||||
compare_profile_contracts({"fallbackReplaySelections": rows}, {})
|
||||
|
||||
def test_t2_must_use_its_own_exact_cache_binding(self):
|
||||
selected = [{"manifestRsyncUri": "rsync://example/a.mft", "vcirSha256": "11" * 32,
|
||||
"reuseIdentitySha256": "22" * 32}]
|
||||
contract = {"fallbackReplaySelections": selected}
|
||||
equivalence = {"fallback": {"matches": True, "expected": copy.deepcopy(selected),
|
||||
"actual": copy.deepcopy(selected), "missing": [], "unexpected": []}}
|
||||
require_t2_fallback_bindings(contract, equivalence)
|
||||
for part in ("expected", "actual"):
|
||||
for field in ("manifestRsyncUri", "vcirSha256", "reuseIdentitySha256"):
|
||||
bad = copy.deepcopy(equivalence)
|
||||
bad["fallback"][part][0][field] = "different"
|
||||
with self.subTest(part=part, field=field), self.assertRaises(ValueError):
|
||||
require_t2_fallback_bindings(contract, bad)
|
||||
for field, value in [("matches", False), ("missing", selected), ("unexpected", selected)]:
|
||||
bad = copy.deepcopy(equivalence)
|
||||
bad["fallback"][field] = value
|
||||
with self.subTest(field=field), self.assertRaises(ValueError):
|
||||
require_t2_fallback_bindings(contract, bad)
|
||||
with self.assertRaises(ValueError):
|
||||
require_t2_fallback_bindings(contract, {})
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
141
scripts/experiments/reuse_eval/test_single_formal.py
Normal file
141
scripts/experiments/reuse_eval/test_single_formal.py
Normal file
@@ -0,0 +1,141 @@
|
||||
import copy
|
||||
import json
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
from campaign import SCALARS
|
||||
from common import file_sha256
|
||||
from sequence_matrix import PROFILE_FLAGS
|
||||
import single_formal as single
|
||||
|
||||
|
||||
def matrix_fixture():
|
||||
rows = []
|
||||
for profile in PROFILE_FLAGS:
|
||||
enabled = {'signature': profile == 'signature', 'roa': profile in ('object', 'hybrid'),
|
||||
'child_certificate': profile in ('object', 'hybrid'), 'publication_point': profile in ('pp', 'hybrid')}
|
||||
for step in range(13):
|
||||
ratios = {layer: {'enabled': on, 'hits': step if on else 0, 'queries': step + 1 if on else 0,
|
||||
'ratio': step / (step + 1) if on else None} for layer, on in enabled.items()}
|
||||
metrics = {'schema': 'rpki-reuse-seven-metrics-v1', 'profile': profile,
|
||||
**{key: 1000 + step for key in SCALARS}, 'cache_hit_ratio': ratios}
|
||||
rows.append({'profile': profile, 'step': step, 'pass': True, 'seven_metrics': metrics})
|
||||
return {'status': 'completed', 'pass': True, 'performance_ready': True, 'scope_sha256': 'scope',
|
||||
'tool_sha256': {'binary': 'binary'}, 'runs': rows,
|
||||
'restoration': {'rp187rp': 0, 'rp187srv': 0, 'panda_active': True, 'panda_container_running': True}}
|
||||
|
||||
|
||||
class SingleFormalTests(unittest.TestCase):
|
||||
def test_one_repeat_keeps_all_65_measurements_and_no_repeat_confidence_claims(self):
|
||||
summary = matrix_fixture()
|
||||
result = single.report(summary)
|
||||
self.assertEqual((result['repeats'], result['pairs']), (1, 65))
|
||||
self.assertEqual(len(result['groups']), 25)
|
||||
warm = next(g for g in result['groups'] if g['profile'] == 'pp' and g['steps'] == 'incremental')
|
||||
self.assertEqual(warm['independent_repeats'], 1)
|
||||
self.assertEqual(warm['n_steps'], 12)
|
||||
self.assertEqual(warm['metrics']['rp_validation_ns']['mean'], 1006.5)
|
||||
self.assertNotIn('stdev', warm['metrics']['rp_validation_ns'])
|
||||
self.assertEqual(warm['cache_hit_ratio']['publication_point'], {'hits': 78, 'queries': 90, 'ratio': 78 / 90})
|
||||
|
||||
def test_csv_has_65_unique_rows_and_raw_hit_denominators(self):
|
||||
rows = single.csv_rows(matrix_fixture())
|
||||
self.assertEqual(len(rows), 65)
|
||||
self.assertEqual(len({(r['repeat'], r['profile'], r['step']) for r in rows}), 65)
|
||||
self.assertEqual(rows[-1]['publication_point_hits'], 12)
|
||||
self.assertEqual(rows[-1]['publication_point_queries'], 13)
|
||||
self.assertTrue(all(r['repeat'] == 1 for r in rows))
|
||||
|
||||
def test_missing_metric_nonfinite_and_wrong_layer_are_rejected(self):
|
||||
for case in ['missing', 'nan', 'negative', 'wrong-layer', 'zero-payload']:
|
||||
summary = matrix_fixture()
|
||||
metric = summary['runs'][0]['seven_metrics']
|
||||
if case == 'missing':
|
||||
del metric['repository_sync_ns']
|
||||
elif case == 'nan':
|
||||
metric['cpu_ns'] = float('nan')
|
||||
elif case == 'negative':
|
||||
metric['cache_size_bytes'] = -1
|
||||
elif case == 'zero-payload':
|
||||
metric['update_to_payload_ns'] = 0
|
||||
else:
|
||||
metric['cache_hit_ratio']['signature'].update(hits=1, queries=1, ratio=1)
|
||||
with self.subTest(case=case), self.assertRaises(ValueError):
|
||||
single.report(summary)
|
||||
|
||||
def test_missing_duplicate_and_unrestored_matrices_cannot_finish(self):
|
||||
for case in ['missing', 'duplicate', 'restore', 'not-formal']:
|
||||
summary = matrix_fixture()
|
||||
if case == 'missing':
|
||||
summary['runs'].pop()
|
||||
elif case == 'duplicate':
|
||||
summary['runs'][-1] = summary['runs'][0]
|
||||
elif case == 'restore':
|
||||
summary['restoration']['panda_active'] = False
|
||||
else:
|
||||
summary['performance_ready'] = False
|
||||
with self.subTest(case=case), self.assertRaises(ValueError):
|
||||
single.report(summary)
|
||||
|
||||
def prerequisite_fixture(self, root):
|
||||
tools = {}
|
||||
for name in ['binary', 'ccr_compare', 'cir_compare', 'db_stats']:
|
||||
path = root / name
|
||||
path.write_text(name)
|
||||
tools[name] = str(path)
|
||||
scope = root / 'scope.json'
|
||||
scope.write_text('{}')
|
||||
build = {name: file_sha256(Path(path)) for name, path in tools.items()}
|
||||
repeat = dict(tools, archive=str(root / 'archive'), scope=str(scope), expected_binary_sha256=build['binary'],
|
||||
expected_scope_sha256=file_sha256(scope), formal_metrics=True,
|
||||
profile_order=list(PROFILE_FLAGS), run_timeout_secs=1800)
|
||||
package = Path(single.__file__).parent
|
||||
scripts = {p.name: file_sha256(p) for p in package.glob('*.py') if not p.name.startswith('test_')}
|
||||
previous = {k: v for k, v in scripts.items() if k != 'single_formal.py'}
|
||||
previous['formal_metrics.py'] = 'old-collector'
|
||||
pilot = matrix_fixture()
|
||||
pilot.update(config=repeat.copy(), tool_sha256=build, scope_sha256=repeat['expected_scope_sha256'], scripts_sha256=previous)
|
||||
pilot['config']['formal_metrics'] = False
|
||||
path = root / 'pilot/summary.json'
|
||||
path.parent.mkdir()
|
||||
(path.parent / 'bin').mkdir()
|
||||
(path.parent / 'bin/binary').write_text('binary')
|
||||
path.write_text(json.dumps(pilot))
|
||||
config = {'pilot_summary': str(path), 'expected_pilot_summary_sha256': file_sha256(path),
|
||||
'repeat': repeat, 'expected_tools_sha256': build, 'expected_pilot_scripts_sha256': previous,
|
||||
'expected_scripts_sha256': scripts}
|
||||
return config
|
||||
|
||||
def test_preserved_pilot_reused_only_with_identical_inputs_build_and_65_proofs(self):
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
config = self.prerequisite_fixture(Path(temp))
|
||||
with patch.object(single, 'require_row_proofs') as proofs:
|
||||
result = single.require_prerequisite(config)
|
||||
self.assertTrue(result['pass'])
|
||||
self.assertEqual(proofs.call_count, 65)
|
||||
self.assertEqual(result['pairs_checked'], 65)
|
||||
|
||||
def test_changed_pilot_scope_binary_order_engine_or_disabled_formal_rejected(self):
|
||||
for case in ['pilot-hash', 'scope', 'binary', 'order', 'engine', 'formal-off']:
|
||||
with self.subTest(case=case), tempfile.TemporaryDirectory() as temp:
|
||||
config = self.prerequisite_fixture(Path(temp))
|
||||
if case == 'pilot-hash':
|
||||
config['expected_pilot_summary_sha256'] = 'other'
|
||||
elif case == 'scope':
|
||||
config['repeat']['scope'] = str(Path(temp) / 'other')
|
||||
elif case == 'binary':
|
||||
Path(config['repeat']['binary']).write_text('changed')
|
||||
elif case == 'order':
|
||||
config['repeat']['profile_order'] = ['baseline']
|
||||
elif case == 'engine':
|
||||
config['expected_scripts_sha256']['sequence_matrix.py'] = 'changed'
|
||||
else:
|
||||
config['repeat']['formal_metrics'] = False
|
||||
with patch.object(single, 'require_row_proofs'), self.assertRaises(ValueError):
|
||||
single.require_prerequisite(config)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
65
scripts/experiments/reuse_eval/test_smoke_matrix.py
Normal file
65
scripts/experiments/reuse_eval/test_smoke_matrix.py
Normal file
@@ -0,0 +1,65 @@
|
||||
"""Regression for comparator tools whose successful exit only means they wrote a report."""
|
||||
import json
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
from smoke_matrix import cache_counters, require_comparison, snapshot_pre_state
|
||||
|
||||
|
||||
class SemanticGateTests(unittest.TestCase):
|
||||
def test_checkpoint_includes_signature_and_mmap_sidecars_without_shared_writes(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
state = root / "state"
|
||||
(state / "db").mkdir(parents=True)
|
||||
(state / "db/000001.sst").write_bytes(b"old-db")
|
||||
for suffix in (".crypto-sig-cache", ".pp-cache-index", ".child-cert-cache-index"):
|
||||
(state / ("db" + suffix)).write_bytes(b"old-sidecar")
|
||||
proof = snapshot_pre_state(state, root / "checkpoint")
|
||||
self.assertEqual(len(proof["files_sha256"]), 4)
|
||||
(state / "db.crypto-sig-cache").write_bytes(b"post-step-success")
|
||||
self.assertEqual((root / "checkpoint/db.crypto-sig-cache").read_bytes(), b"old-sidecar")
|
||||
|
||||
def test_signature_gate_checks_loaded_entries_and_per_point_hits(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
stage = {"crypto_signature_cache_observe": {"entries_loaded": 0, "entries_total": 1,
|
||||
"per_point": {"crl": {"calls": 1, "would_hit": 0, "verify_executed": 1,
|
||||
"verify_skipped": 0, "verify_nanos_on_new_key": 100}}},
|
||||
"roa_validation_cache": {"hit_roas": 0, "lookup_nanos": 10},
|
||||
"analysis_counts": {"roa_validation_cache_context_gate_nanos": 100,
|
||||
"publication_point_cache_reuse_nonzero_ms_total": 2,
|
||||
"publication_point_cache_reuse_nonzero_ms_hits": 1,
|
||||
"child_certificate_cache_hit": 5}}
|
||||
path = root / "stage-timing.json"
|
||||
path.write_text(json.dumps(stage))
|
||||
cold = cache_counters(root)
|
||||
stage["analysis_counts"]["roa_validation_cache_context_gate_nanos"] = 200
|
||||
stage["analysis_counts"]["publication_point_cache_reuse_nonzero_ms_total"] = 3
|
||||
stage["analysis_counts"]["publication_point_cache_reuse_nonzero_ms_hits"] = 2
|
||||
path.write_text(json.dumps(stage))
|
||||
self.assertEqual(cold, cache_counters(root))
|
||||
stage["analysis_counts"]["child_certificate_cache_hit"] = 6
|
||||
path.write_text(json.dumps(stage))
|
||||
self.assertNotEqual(cold, cache_counters(root))
|
||||
stage["analysis_counts"]["child_certificate_cache_hit"] = 5
|
||||
stage["crypto_signature_cache_observe"]["entries_loaded"] = 1
|
||||
path.write_text(json.dumps(stage))
|
||||
self.assertNotEqual(cold, cache_counters(root))
|
||||
self.assertNotIn("lookup_nanos", cold["roa"])
|
||||
|
||||
def test_zero_exit_difference_report_is_rejected(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
path = Path(directory) / "comparison.json"
|
||||
for kind, field in (("cir", "allMatch"), ("ccr", "stateDigestMatch")):
|
||||
for value in (False, None, "true", 1):
|
||||
path.write_text(json.dumps({field: value}))
|
||||
with self.assertRaisesRegex(ValueError, "semantic comparison failed"):
|
||||
require_comparison(path, kind)
|
||||
path.write_text(json.dumps({field: True}))
|
||||
require_comparison(path, kind)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
156
scripts/experiments/reuse_eval/verify.py
Normal file
156
scripts/experiments/reuse_eval/verify.py
Normal file
@@ -0,0 +1,156 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Check blob integrity, selected observation closure and time boundaries."""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
from common import Archive, atomic_json, file_sha256, read_json
|
||||
from rrdp import notification, payload_view, view_digest
|
||||
|
||||
|
||||
def verify(root: Path, scope_path: Path | None = None, report_path: Path | None = None) -> dict:
|
||||
scope = None
|
||||
if scope_path is not None:
|
||||
from scope import load_scope, outside_archive
|
||||
scope = load_scope(root, scope_path)
|
||||
report_path = report_path or scope_path.with_name("scoped-closure-report.json")
|
||||
outside_archive(root, report_path)
|
||||
if report_path.resolve() == scope_path.resolve():
|
||||
raise ValueError("scoped report cannot overwrite scope")
|
||||
archive = Archive(root, read_only=True)
|
||||
checked, errors, epochs = {}, [], []
|
||||
def check(ref):
|
||||
if ref["sha256"] in checked and checked[ref["sha256"]] != ref["size"]:
|
||||
raise ValueError("inconsistent blob size references")
|
||||
if ref["sha256"] not in checked:
|
||||
archive.verify_blob(ref)
|
||||
checked[ref["sha256"]] = ref["size"]
|
||||
# Check even unselected successful content and preserved failed/partial views.
|
||||
events = {}
|
||||
for path in (root / "events").glob("*.json"):
|
||||
event = read_json(path)
|
||||
events[event["id"]] = event
|
||||
try:
|
||||
if event.get("body"):
|
||||
check(event["body"])
|
||||
for ref in event.get("objects", {}).values():
|
||||
check(ref)
|
||||
except Exception as exc:
|
||||
errors.append({"event": event["id"], "error": str(exc)})
|
||||
observations = {p.stem: read_json(p) for p in (root / "observations").glob("*.json")}
|
||||
contract_hash = None
|
||||
if (root / "contract.json").exists():
|
||||
contract_hash = file_sha256(root / "contract.json")
|
||||
try:
|
||||
contract = read_json(root / "contract.json")
|
||||
for tal in contract["tals"]:
|
||||
check(tal)
|
||||
pinned = root / "inputs" / Path(tal["path"]).name
|
||||
if file_sha256(pinned) != tal["sha256"]:
|
||||
raise ValueError("pinned TAL content mismatch")
|
||||
if tal.get("constraints_sha256") and file_sha256(pinned.with_suffix(".constraints")) != tal["constraints_sha256"]:
|
||||
raise ValueError("pinned constraints mismatch")
|
||||
except Exception as exc:
|
||||
errors.append({"contract": "contract.json", "error": str(exc)})
|
||||
# Independently recheck every accepted transition, including minute states
|
||||
# between selected five-minute epochs. Never just trust the collector's label.
|
||||
for item in observations.values():
|
||||
if not item["complete"] or not item.get("base_observation_id"):
|
||||
continue
|
||||
try:
|
||||
base = observations[item["base_observation_id"]]
|
||||
if not base["complete"] or base["uri"] != item["uri"] or base["completed_ms"] > item["started_ms"]:
|
||||
raise ValueError("invalid observation predecessor")
|
||||
if base["session"] != item["session"]:
|
||||
if item["chain"] != "session_reset_snapshot":
|
||||
raise ValueError("session reset not recorded")
|
||||
continue
|
||||
if item["serial"] < base["serial"]:
|
||||
raise ValueError("serial rollback")
|
||||
view = read_json(root / "views" / f"{base['view']}.json")
|
||||
if item["serial"] - base["serial"] > 10000:
|
||||
raise ValueError("delta chain size bound")
|
||||
deltas = {r["serial"]: r for r in item["references"] if r["kind"] == "delta"}
|
||||
for serial in range(base["serial"] + 1, item["serial"] + 1):
|
||||
ref = deltas[serial]
|
||||
if not ref["available"]:
|
||||
raise ValueError("required delta missing")
|
||||
check({"sha256": ref["sha256"], "size": ref["size"]})
|
||||
view = payload_view(archive.blob_path(ref["sha256"]), "delta", item["session"], serial, view)
|
||||
if view_digest(view) != item["view"]:
|
||||
raise ValueError("delta transition view mismatch")
|
||||
except Exception as exc:
|
||||
errors.append({"observation": item["id"], "error": str(exc)})
|
||||
views_checked = set()
|
||||
for path in sorted((root / "epochs").glob("epoch_*.json")):
|
||||
epoch = read_json(path)
|
||||
epoch_errors = []
|
||||
if epoch.get("contract_sha256") != contract_hash:
|
||||
epoch_errors.append("capture contract hash mismatch")
|
||||
if not epoch["complete"] and scope is None:
|
||||
epoch_errors.append(f"missing repositories: {epoch['missing']}")
|
||||
if epoch.get("blocked_latest_attempts"):
|
||||
epoch_errors.append(f"latest observations failed: {epoch['blocked_latest_attempts']}")
|
||||
for uri, binding in epoch["repositories"].items():
|
||||
try:
|
||||
observation = observations[binding["id"]]
|
||||
if not observation["complete"] or observation["completed_ms"] > epoch["validation_time_ms"]:
|
||||
raise ValueError("incomplete/future observation selected")
|
||||
for key in ("uri", "session", "serial", "notification", "view", "completed_ms"):
|
||||
expected = uri if key == "uri" else binding[key]
|
||||
if observation[key] != expected:
|
||||
raise ValueError(f"observation binding mismatch: {key}")
|
||||
check(observation["notification"])
|
||||
parsed = notification(archive.blob_path(observation["notification"]["sha256"]), uri)
|
||||
if parsed["session"] != binding["session"] or parsed["serial"] != binding["serial"]:
|
||||
raise ValueError("notification binding mismatch")
|
||||
refs = {(r["kind"], r["serial"], r["uri"], r["sha256"]) for r in parsed["references"]}
|
||||
recorded = {(r["kind"], r["serial"], r["uri"], r["sha256"]) for r in observation["references"]}
|
||||
if refs != recorded:
|
||||
raise ValueError("notification reference list mismatch")
|
||||
for ref in observation["references"]:
|
||||
if ref["available"]:
|
||||
check({"sha256": ref["sha256"], "size": ref["size"]})
|
||||
snapshot = next(r for r in observation["references"] if r["kind"] == "snapshot")
|
||||
identity = (snapshot["sha256"], binding["view"])
|
||||
if identity not in views_checked:
|
||||
view = payload_view(archive.blob_path(snapshot["sha256"]), "snapshot", binding["session"], binding["serial"])
|
||||
if view_digest(view) != binding["view"]:
|
||||
raise ValueError("snapshot view digest mismatch")
|
||||
if read_json(root / "views" / f"{binding['view']}.json") != view:
|
||||
raise ValueError("stored view differs from snapshot")
|
||||
views_checked.add(identity)
|
||||
except Exception as exc:
|
||||
epoch_errors.append({"uri": uri, "error": str(exc)})
|
||||
for uri, event_id in list(epoch["ta_object_events"].items()) + list(epoch["rsync_view_events"].items()):
|
||||
event = events.get(event_id)
|
||||
if not event or event["uri"] != uri or not event["complete"] or event["completed_ms"] > epoch["validation_time_ms"]:
|
||||
epoch_errors.append({"event": event_id, "error": "missing/incomplete/future transport view"})
|
||||
epochs.append({"epoch": path.name, "repositories": len(epoch["repositories"]), "pass": not epoch_errors, "errors": epoch_errors})
|
||||
if not epochs:
|
||||
errors.append({"error": "no epochs"})
|
||||
result = {"pass": not errors and all(e["pass"] for e in epochs), "checked_blobs": len(checked),
|
||||
"events": len(events), "observations": len(observations), "epochs": epochs, "errors": errors}
|
||||
if scope is not None:
|
||||
result.update(scope_sha256=file_sha256(scope_path), source_contract_sha256=contract_hash,
|
||||
coverage=scope["coverage"], excluded_repositories=scope["excluded_repositories"],
|
||||
original_complete=False)
|
||||
atomic_json(report_path or root / "closure-report.json", result)
|
||||
return result
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--archive", type=Path, required=True)
|
||||
parser.add_argument("--scope", type=Path)
|
||||
parser.add_argument("--out", type=Path)
|
||||
args = parser.parse_args()
|
||||
result = verify(args.archive, args.scope, args.out)
|
||||
print(json.dumps(result))
|
||||
return 0 if result["pass"] else 2
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Reference in New Issue
Block a user