cjc0013's picture
Publish private Ouroboros Pasterski research program for review
db6c8f1 verified
Raw
History Blame
3.26 kB
from __future__ import annotations
import hashlib
import json
import os
import time
import urllib.request
from pathlib import Path
PACKAGE_ROOT = Path(__file__).resolve().parents[1]
LOCK_PATH = PACKAGE_ROOT / "data" / "sources.lock.json"
def _load_lock() -> dict:
return json.loads(LOCK_PATH.read_text(encoding="utf-8"))
def cache_root() -> Path:
override = os.environ.get("OUROBOROS_SOURCE_CACHE", "").strip()
return Path(override).expanduser().resolve() if override else Path.home() / ".cache" / "ouroboros-pasterski-v1" / "sources"
def _sha256(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as handle:
for chunk in iter(lambda: handle.read(1024 * 1024), b""):
digest.update(chunk)
return digest.hexdigest()
def _entry(expected_sha: str) -> dict:
for item in _load_lock()["sources"]:
if item["sha256"] == expected_sha:
return item
raise KeyError(f"source hash not present in lock: {expected_sha}")
def verify_source(path: Path, expected_sha: str) -> Path:
actual = _sha256(path)
if actual != expected_sha:
raise RuntimeError(f"public source SHA mismatch: expected {expected_sha}, got {actual}")
return path
def fetch_source(expected_sha: str, *, pause_seconds: float = 1.0) -> Path:
entry = _entry(expected_sha)
root = cache_root()
root.mkdir(parents=True, exist_ok=True)
target = root / f"{expected_sha}.source"
if target.is_file():
return verify_source(target, expected_sha)
errors = []
for url in entry["urls"]:
try:
request = urllib.request.Request(url, headers={"User-Agent": "Ouroboros-Pasterski-Replay/1.0 reproducibility@example.invalid"})
with urllib.request.urlopen(request, timeout=90) as response:
payload = response.read()
if hashlib.sha256(payload).hexdigest() != expected_sha:
errors.append("hash_mismatch")
continue
temporary = target.with_suffix(".partial")
temporary.write_bytes(payload)
os.replace(temporary, target)
time.sleep(max(0.0, pause_seconds))
return target
except Exception as exc:
errors.append(type(exc).__name__)
raise RuntimeError(f"unable to fetch SHA-pinned public source {entry['arxiv_id']}: {','.join(errors)}")
def source_path(expected_sha: str) -> Path:
target = cache_root() / f"{expected_sha}.source"
if not target.is_file():
raise FileNotFoundError("public source cache is empty; run `python -m ouroboros_replay fetch` first")
return verify_source(target, expected_sha)
def fixture_path(expected_sha: str) -> Path:
target = PACKAGE_ROOT / "data" / "predecessors" / f"{expected_sha}.json"
return verify_source(target, expected_sha)
def fetch_all(*, pause_seconds: float = 1.0) -> list[dict]:
rows = []
for entry in _load_lock()["sources"]:
path = fetch_source(entry["sha256"], pause_seconds=pause_seconds)
rows.append({"arxiv_id": entry["arxiv_id"], "sha256": entry["sha256"], "byte_count": path.stat().st_size, "verified": True})
return rows