"""Atomic durable manifests. Paths and bytes are validated before result recovery.""" import hashlib, json, os from pathlib import Path from app.adapters.storage import confined, safe_file def digest_file(path): digest = hashlib.sha256() with Path(path).open("rb") as stream: while chunk := stream.read(1024 * 1024): digest.update(chunk) return digest.hexdigest() def write_manifest(root, directory, execution_id, fence_token, outputs, result, metadata): directory = confined(root, directory, exists=True) entries = [] for output in outputs: path = confined(root, output, exists=True) with safe_file(root, path): pass entries.append( { "path": path.relative_to(root).as_posix(), "size": path.stat().st_size, "sha256": digest_file(path), } ) manifest = { "schema": 1, "execution_id": execution_id, "fence_token": fence_token, "outputs": entries, "result": result, "metadata": metadata, } target = directory / "result-manifest.json" temporary = target.with_suffix(".tmp") with temporary.open("w", encoding="utf-8") as stream: json.dump(manifest, stream, ensure_ascii=False, allow_nan=False) stream.flush() os.fsync(stream.fileno()) os.replace(temporary, target) return manifest def verify_manifest(root, manifest): if manifest.get("schema") != 1 or not manifest.get("outputs"): raise ValueError("Invalid manifest") paths = [] for entry in manifest["outputs"]: if Path(entry["path"]).is_absolute(): raise ValueError("Manifest path must be relative") path = confined(root, entry["path"], exists=True) with safe_file(root, path): pass if path.stat().st_size != entry["size"] or digest_file(path) != entry["sha256"]: raise ValueError("Artifact hash mismatch") paths.append(str(path)) return paths def reconcile_artifacts(root): verified = [] invalid = [] for path in Path(root).rglob("result-manifest.json"): try: verify_manifest(root, json.loads(path.read_text(encoding="utf-8"))) verified.append(str(path)) except (OSError, ValueError, KeyError): invalid.append(str(path)) return {"verified": verified, "invalid": invalid, "deleted": []}