from __future__ import annotations import hashlib import json import os import shutil import uuid from datetime import UTC, datetime from pathlib import Path import yaml # type: ignore[import-untyped] from pydantic import BaseModel, ConfigDict, Field from packages.core.files import atomic_write_text class ArtifactLifecyclePolicy(BaseModel): model_config = ConfigDict(extra="forbid") schema_version: str enabled: bool = True compact_after_release: bool = True preserve_globs: list[str] = Field(default_factory=list) remove_paths: list[str] = Field(default_factory=list) DEFAULT_POLICY = ( Path(__file__).resolve().parents[2] / "configs" / "artifact_lifecycle_v1.yaml" ) def load_artifact_lifecycle_policy(path: Path | None = None) -> ArtifactLifecyclePolicy: selected = path or Path(os.environ.get("RHG_ARTIFACT_POLICY", DEFAULT_POLICY)) payload = yaml.safe_load(selected.expanduser().resolve().read_text(encoding="utf-8")) return ArtifactLifecyclePolicy.model_validate(payload) def compact_released_attempt( output: Path, portable_package: Path, *, expected_package_sha256: str | None = None, policy: ArtifactLifecyclePolicy | None = None, apply: bool = True, ) -> dict[str, object]: """Prune reproducible generation workspaces after a portable package is verified.""" output = output.resolve() portable_package = portable_package.resolve() selected = policy or load_artifact_lifecycle_policy() if not output.is_dir(): raise NotADirectoryError(output) if not portable_package.exists(): raise FileNotFoundError(portable_package) package_sha256 = _package_sha256(portable_package) if expected_package_sha256 and package_sha256 != expected_package_sha256: raise ValueError("portable package checksum changed before artifact compaction") before_bytes = _physical_size(output) targets = _resolve_targets(output, selected.remove_paths) plan = [ { "path": path.relative_to(output).as_posix(), "physical_bytes": _physical_size(path), } for path in targets if path.exists() ] report: dict[str, object] = { "schema_version": "1.0", "created_at": datetime.now(UTC).isoformat(), "mode": "apply" if apply else "dry_run", "status": "planned", "portable_package": str(portable_package), "portable_sha256": package_sha256, "before_physical_bytes": before_bytes, "targets": plan, "preserved_files": [], } if not selected.enabled or not selected.compact_after_release or not apply: return report preserved = _preserve_evidence(output, targets, selected.preserve_globs) for path in targets: if path.is_dir() and not path.is_symlink(): shutil.rmtree(path) elif path.exists() or path.is_symlink(): path.unlink() after_bytes = _physical_size(output) report.update( { "status": "complete", "completed_at": datetime.now(UTC).isoformat(), "after_physical_bytes_before_report": after_bytes, "reclaimed_physical_bytes": max(before_bytes - after_bytes, 0), "preserved_files": preserved, } ) report_path = output / "supervisor" / "artifact_lifecycle_report.json" atomic_write_text(report_path, json.dumps(report, ensure_ascii=False, indent=2) + "\n") _write_checksums(output) return report def build_compact_copy( source: Path, destination: Path, *, policy: ArtifactLifecyclePolicy | None = None, ) -> dict[str, object]: """Build a pruned copy without mutating the immutable version directory.""" source = source.resolve() destination = destination.resolve() selected = policy or load_artifact_lifecycle_policy() if not source.is_dir(): raise NotADirectoryError(source) if destination == source or destination.is_relative_to(source): raise ValueError("compact copy destination must be outside the source version") if destination.exists(): raise FileExistsError(destination) excluded = { Path(relative).as_posix().strip("/") for relative in selected.remove_paths } def ignore(directory: str, names: list[str]) -> set[str]: relative_dir = Path(directory).resolve().relative_to(source) ignored: set[str] = set() for name in names: if (Path(directory) / name).is_symlink(): ignored.add(name) continue relative = (relative_dir / name).as_posix().strip(".").strip("/") if any(relative == item or relative.startswith(f"{item}/") for item in excluded): ignored.add(name) return ignored shutil.copytree(source, destination, symlinks=False, ignore=ignore) _preserve_evidence_from_source(source, destination, selected) report: dict[str, object] = { "schema_version": "1.0", "created_at": datetime.now(UTC).isoformat(), "status": "complete", "source_version": source.name, "source_physical_bytes": _physical_size(source), "major_physical_bytes_before_report": _physical_size(destination), "excluded_paths": sorted(excluded), } report_path = destination / "supervisor" / "artifact_lifecycle_report.json" atomic_write_text(report_path, json.dumps(report, ensure_ascii=False, indent=2) + "\n") _write_checksums(destination) return report def replace_major_copy( source: Path, major: Path, *, policy: ArtifactLifecyclePolicy | None = None, ) -> dict[str, object]: """Atomically replace ``major`` with a compact copy of ``source``.""" major = major.resolve() major.parent.mkdir(parents=True, exist_ok=True) token = uuid.uuid4().hex staging = major.parent / f".{major.name}.staging-{token}" backup = major.parent / f".{major.name}.backup-{token}" try: report = build_compact_copy(source, staging, policy=policy) if major.exists(): major.rename(backup) staging.rename(major) except Exception: if backup.exists() and not major.exists(): backup.rename(major) raise finally: if staging.exists(): shutil.rmtree(staging) if backup.exists(): shutil.rmtree(backup) return report def replace_major_from_portable( portable: Path, major: Path, *, source_version: Path, ) -> dict[str, object]: """Atomically materialize ``major`` from an already verified portable bundle.""" from packages.benchmark.portable import refresh_checksums, verify_portable_bundle portable = portable.resolve() major = major.resolve() source_version = source_version.resolve() if not portable.is_dir(): raise NotADirectoryError(portable) if not (portable / "portable_manifest.json").is_file(): raise FileNotFoundError(portable / "portable_manifest.json") major.parent.mkdir(parents=True, exist_ok=True) token = uuid.uuid4().hex staging = major.parent / f".{major.name}.staging-{token}" backup = major.parent / f".{major.name}.backup-{token}" try: symlinks = [path for path in portable.rglob("*") if path.is_symlink()] if symlinks: raise RuntimeError(f"portable source contains symlinks: {symlinks[:3]}") # Preserve the portable staging hardlinks. This keeps both the live major # directory and its tar archive compact without coupling path validity. shutil.copytree(portable, staging, symlinks=False, copy_function=os.link) snapshot_source = source_version / "snapshot.jpg" if not (staging / "snapshot.jpg").is_file(): if not snapshot_source.is_file(): raise FileNotFoundError(snapshot_source) shutil.copy2(snapshot_source, staging / "snapshot.jpg") # ``major`` has a backend-independent, fixed media contract. Older # portable bundles stored the video only under ``scenesmith/``; expose # it at the major root without duplicating file data. preview = staging / "preview.mp4" if not preview.is_file(): preview_source = staging / "scenesmith" / "preview.mp4" if not preview_source.is_file(): preview_source = source_version / "scenesmith" / "preview.mp4" if not preview_source.is_file(): raise FileNotFoundError( f"major preview is missing for source version: {source_version}" ) os.link(preview_source, preview) history = staging / "iteration_history.mp4" if not history.is_file(): history_source = staging / "scenesmith" / "iteration_history.mp4" if not history_source.is_file(): history_source = source_version / "iteration_history.mp4" if not history_source.is_file(): history_source = source_version / "scenesmith" / "iteration_history.mp4" if not history_source.is_file(): raise FileNotFoundError( f"major iteration history is missing for source version: {source_version}" ) os.link(history_source, history) provenance = { "schema_version": "1.0", "materialization_version": "5.0", "created_at": datetime.now(UTC).isoformat(), "source_version": source_version.name, "source_portable_bundle": str(portable), "self_contained": True, "media": { "snapshot": "snapshot.jpg", "preview": "preview.mp4", "iteration_history": "iteration_history.mp4", }, } atomic_write_text( staging / "major_manifest.json", json.dumps(provenance, ensure_ascii=False, indent=2) + "\n", ) refresh_checksums(staging) verification = verify_portable_bundle(staging, require_pxr=False) if not verification["passed"]: raise RuntimeError(f"major portable verification failed: {verification['failures']}") if major.exists(): major.rename(backup) staging.rename(major) except Exception: if backup.exists() and not major.exists(): backup.rename(major) raise finally: if staging.exists(): shutil.rmtree(staging) if backup.exists(): shutil.rmtree(backup) return { "schema_version": "1.0", "status": "complete", "source_version": source_version.name, "source_portable_bundle": str(portable), "verification": verification, } def _resolve_targets(output: Path, relative_paths: list[str]) -> list[Path]: targets: list[Path] = [] for relative in relative_paths: candidate = (output / relative).resolve() if not candidate.is_relative_to(output): raise ValueError(f"artifact cleanup path escapes the run: {relative}") if candidate == output: raise ValueError("artifact cleanup cannot target the run root") targets.append(candidate) return targets def _preserve_evidence(output: Path, targets: list[Path], globs: list[str]) -> list[str]: destination_root = output / "supervisor" / "generation_evidence" preserved: list[str] = [] for target in targets: if not target.is_dir(): continue for pattern in globs: for source in sorted(target.glob(pattern)): if not source.is_file(): continue relative = source.relative_to(output) destination = destination_root / relative destination.parent.mkdir(parents=True, exist_ok=True) shutil.copy2(source, destination) preserved.append(destination.relative_to(output).as_posix()) return sorted(set(preserved)) def _preserve_evidence_from_source( source_root: Path, destination_root: Path, policy: ArtifactLifecyclePolicy, ) -> list[str]: evidence_root = destination_root / "supervisor" / "generation_evidence" preserved: list[str] = [] for target in _resolve_targets(source_root, policy.remove_paths): if not target.is_dir(): continue for pattern in policy.preserve_globs: for source in sorted(target.glob(pattern)): if not source.is_file(): continue relative = source.relative_to(source_root) destination = evidence_root / relative destination.parent.mkdir(parents=True, exist_ok=True) shutil.copy2(source, destination) preserved.append(destination.relative_to(destination_root).as_posix()) return sorted(set(preserved)) def _physical_size(path: Path) -> int: if not path.exists(): return 0 files = [path] if path.is_file() else path.rglob("*") seen: set[tuple[int, int]] = set() total = 0 for item in files: if not item.is_file(): continue stat = item.stat() key = (stat.st_dev, stat.st_ino) if key in seen: continue seen.add(key) total += stat.st_blocks * 512 return total def _package_sha256(path: Path) -> str: if path.is_dir(): digest = hashlib.sha256() for item in sorted(path.rglob("*")): if item.is_file(): digest.update(item.relative_to(path).as_posix().encode()) digest.update(_sha256_file(item).encode()) return digest.hexdigest() return _sha256_file(path) def _sha256_file(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 _write_checksums(output: Path) -> None: checksums = [] for path in sorted(output.rglob("*")): if path.is_file() and path.name != "checksums.sha256": checksums.append(f"{_sha256_file(path)} {path.relative_to(output)}") atomic_write_text(output / "checksums.sha256", "\n".join(checksums) + "\n")