"""Durable exact-proof archives within the existing private KV free boundary. The encrypted working bundle contains the authenticated catalogue. Immutable pieces are uploaded and read back before that bundle can omit large reporting artifacts. Restore hydrates a bounded sibling cache, never the working bundle. """ from __future__ import annotations import copy import hashlib import json from pathlib import Path from ops import proof_archive MAX_ARCHIVE_STORED = 256 * 1024 * 1024 MAX_ARCHIVE_EXPANDED = 512 * 1024 * 1024 MAX_ARCHIVE_PIECES = 256 class ArchiveCapacityError(ValueError): """The existing free proof archive cannot fit another piece.""" def check_budget(index: dict) -> dict: proof_archive.validate_archive_index(index) entries = list(index["pieces"].values()) totals = { "pieces": len(entries), "stored_bytes": sum(entry["descriptor"]["bytes"] for entry in entries), "expanded_bytes": sum(entry["descriptor"]["plaintext_bytes"] for entry in entries), } if (totals["pieces"] > MAX_ARCHIVE_PIECES or totals["stored_bytes"] > MAX_ARCHIVE_STORED or totals["expanded_bytes"] > MAX_ARCHIVE_EXPANDED): raise ArchiveCapacityError("Exact proof archive reached its free-storage safety boundary") return totals def references(index: dict) -> list[dict]: check_budget(index) return [entry["storage"] for _, entry in sorted(index["pieces"].items())] def _check_cache(bundle: Path, identity: str, entry: dict) -> bool: root = proof_archive.cache_root(bundle) destination = root / identity if root.is_symlink() or destination.is_symlink(): raise ValueError("Proof cache must not contain linked directories") if not destination.exists(): return False if not destination.is_dir(): raise ValueError("Proof cache is not a directory") paths = list(destination.rglob("*")) if any(path.is_symlink() for path in paths): raise ValueError("Proof cache must not contain linked files") files = {path.relative_to(destination).as_posix(): path for path in paths if path.is_file()} if set(files) != set(entry["inventory"]["files"]): raise ValueError("Proof cache inventory differs from authenticated archive") for relative, metadata in entry["inventory"]["files"].items(): path = files[relative] if (path.stat().st_size != metadata["bytes"] or hashlib.sha256(path.read_bytes()).hexdigest() != metadata["sha256"]): raise ValueError("Proof cache bytes differ from authenticated archive") return True def _hydrate(store, bundle: Path, identity: str, entry: dict, encrypted: bytes | None = None) -> None: if _check_cache(bundle, identity, entry): return if encrypted is None: encrypted = store.get_sealed_proof(entry["storage"]) inventory, _ = proof_archive.inspect_piece(encrypted, store.key, entry["descriptor"]) if inventory != entry["inventory"]: raise ValueError("Restored proof inventory differs from the publication catalogue") cache = proof_archive.cache_root(bundle) cache.mkdir(parents=True, exist_ok=True) proof_archive.restore_piece(encrypted, store.key, entry["descriptor"], cache / identity) if not _check_cache(bundle, identity, entry): raise ValueError("Verified proof cache was not installed") def restore_archives(store, bundle: Path, journal: dict) -> dict: index = proof_archive.load_archive_index(bundle) expected = references(index) if journal.get("proofs", []) != expected: raise ValueError("Cloud journal and encrypted proof catalogue disagree") for identity, entry in index["pieces"].items(): _hydrate(store, bundle, identity, entry) return check_budget(index) def prepare_archives(store, bundle: Path, journal: dict, staged: list[dict]) -> dict: """Prepare archive references for one normal single-writer checkpoint. The caller journals the new bundle and these opaque references together. Existing authority remains intact on upload, verification or commit failure. """ original = proof_archive.load_archive_index(bundle) if references(original) != journal.get("proofs", []): raise ValueError("Restored proof catalogue differs from current journal") for identity, entry in original["pieces"].items(): _hydrate(store, bundle, identity, entry) index = copy.deepcopy(original) state_path = bundle / "state.json" if not state_path.is_file(): return index if state_path.is_symlink() or state_path.stat().st_size > 4 * 1024 * 1024: raise ValueError("Invalid publication state for proof archiving") state = json.loads(state_path.read_text(encoding="utf-8")) archived = {(binding["cycle_key"], binding["packet_sha256"]) for entry in index["pieces"].values() if (binding := entry["inventory"]["bindings"]).get("stage") == "published"} for cycle_key, run in sorted(state.get("runs", {}).items()): if (run.get("status") != "complete" or run.get("stage") != "published" or run.get("review_decision") != "approve" or not run.get("reporting_record")): continue if (cycle_key, run.get("packet_sha256")) in archived: continue descriptor, encrypted = proof_archive.build_completed_piece(bundle, cycle_key, store.key) _stage_piece(store, bundle, journal, staged, index, descriptor, encrypted) archived.add((cycle_key, run["packet_sha256"])) from ops.cloud_state import MAX_OBJECT from ops.reporting_memory import MAX_RECORD_BYTES, has_review_headroom, reporting_headroom, reporting_inventory records = reporting_inventory(bundle) excluded = checked_exclusions(bundle, index) previous = proof_archive.archive_exclusions(original) initial = reporting_headroom(records, previous) headroom = reporting_headroom(records, excluded) last_bundle_bytes = (journal.get("bundle") or {}).get("bytes", 0) # Outer compression can change the actual saving. Treat the previous # envelope as a pressure signal, then seal the new bundle in the normal # checkpoint path to enforce its exact provider-object limit. outer_pressure = max(0, last_bundle_bytes + MAX_RECORD_BYTES - MAX_OBJECT) def has_margin() -> bool: reclaimed = headroom["stored_bytes_available"] - initial["stored_bytes_available"] return has_review_headroom(headroom, pairs=2) and reclaimed >= outer_pressure if has_margin(): return index archived_records = {entry["inventory"]["bindings"]["reporting_record"] for entry in index["pieces"].values()} for directory, manifest in sorted(records, key=lambda item: (item[1]["recorded_at"], item[0].name)): reference = f"bundle:reporting/{directory.name}/manifest.json" if manifest["retention_status"] != "exact" or reference in archived_records: continue descriptor, encrypted = proof_archive.build_reporting_piece(bundle, directory, store.key) try: excluded.update(_stage_piece(store, bundle, journal, staged, index, descriptor, encrypted)) except ArchiveCapacityError: if not has_review_headroom(headroom): raise break # The next pair fits. A later checkpoint can reassess more work. headroom = reporting_headroom(records, excluded) if has_margin(): break return index def _stage_piece(store, bundle: Path, journal: dict, staged: list[dict], index: dict, descriptor: dict, encrypted: bytes) -> set[str]: inventory, _ = proof_archive.inspect_piece(encrypted, store.key, descriptor) reference = {"key": "v1/proof/" + descriptor["sha256"], "sha256": descriptor["sha256"], "bytes": descriptor["bytes"]} identity = descriptor["proof_id"] entry = {"descriptor": descriptor, "storage": reference, "inventory": inventory} candidate = {**index, "pieces": {**index["pieces"], identity: entry}} check_budget(candidate) # Reserve before PUT so even an interrupted upload remains accounted for. store.reserve_proof(reference, journal, bundle) staged.append(reference) downloaded = store.put_sealed_proof(reference, encrypted) actual, _ = proof_archive.inspect_piece(downloaded, store.key, descriptor) if actual != inventory: raise ValueError("Cloud proof readback changed its exact inventory") _hydrate(store, bundle, identity, entry, downloaded) index["pieces"][identity] = entry return proof_archive.archive_exclusions({"schema_version": index["schema_version"], "format": index["format"], "pieces": {identity: entry}}) def index_bytes(index: dict) -> bytes: check_budget(index) return (json.dumps(index, ensure_ascii=False, sort_keys=True) + "\n").encode() def install_archive_index(bundle: Path, index: dict) -> None: """Install locally only after the containing cloud generation is confirmed.""" if not index["pieces"]: return data = index_bytes(index) directory = bundle / "proof-archive" if directory.is_symlink(): raise ValueError("Proof catalogue directory must not be linked") directory.mkdir(exist_ok=True) path, temporary = directory / "index.json", directory / "index.next" if path.is_symlink() or temporary.is_symlink(): raise ValueError("Proof catalogue files must not be linked") temporary.write_bytes(data) temporary.chmod(0o600) temporary.replace(path) def checked_exclusions(bundle: Path, index: dict | None = None) -> set[str]: """Validate every omitted byte against its separately restored exact copy.""" index = proof_archive.load_archive_index(bundle) if index is None else index check_budget(index) excluded = proof_archive.archive_exclusions(index) expected = {} for identity, entry in index["pieces"].items(): if not _check_cache(bundle, identity, entry): raise ValueError("Exact proof cache is missing") expected.update(entry["inventory"]["files"]) for relative in excluded: local = bundle / relative metadata = expected[relative] if local.is_symlink() or (local.exists() and ( local.stat().st_size != metadata["bytes"] or hashlib.sha256(local.read_bytes()).hexdigest() != metadata["sha256"])): raise ValueError("Hot proof artifact differs from its verified archive") return excluded