"""Verified Worker ownership of originals, followed by journaled local eviction.""" from __future__ import annotations import hashlib import os import re from pathlib import Path from typing import TYPE_CHECKING, Any from k1link.simulation.gaussian_pipeline_gateway import ( GaussianArchiveUpload, GaussianPipelineIntegrityError, GaussianSourceBundleUpload, _source_bundle_upload, discover_gaussian_source_bundle, ) if TYPE_CHECKING: from k1link.simulation.gaussian_pipeline_gateway import GaussianPipelineGateway from k1link.simulation.projects import SimulationProjectStore def validate_receipt(value: Any, *, expected: dict[str, Any] | None = None) -> None: if ( not isinstance(value, dict) or value.get("schema_version") != "gaussian-pipeline.source-receipt/v1" or value.get("retention") != "independent-of-jobs" or not re.fullmatch(r"src-[a-f0-9]{64}", str(value.get("source_id"))) or not isinstance(value.get("verified_at_utc"), str) ): raise GaussianPipelineIntegrityError("Worker did not confirm durable source storage") original = value.get("input") if not isinstance(original, dict): raise GaussianPipelineIntegrityError("Worker source identity missing") if original.get("kind") == "folder": _source_bundle_upload(original.get("source")) elif original.get("kind") == "archive": archive = original.get("archive") if ( not isinstance(archive, dict) or not re.fullmatch(r"[a-zA-Z0-9_-]+", str(archive.get("upload_id"))) or archive.get("format") not in {"zip", "rar", "7z"} or not re.fullmatch(r"[a-f0-9]{64}", str(archive.get("sha256"))) or not isinstance(archive.get("byte_length"), int) or archive["byte_length"] <= 0 or not isinstance(archive.get("archive_name"), str) or Path(archive["archive_name"]).name != archive["archive_name"] ): raise GaussianPipelineIntegrityError("Worker archive receipt invalid") else: raise GaussianPipelineIntegrityError("Worker source kind invalid") if expected is not None and original != expected: raise GaussianPipelineIntegrityError("Worker retained different source files") def receipt_files(receipt: dict[str, Any]) -> dict[str, tuple[int, str]]: validate_receipt(receipt) original = receipt["input"] if original["kind"] == "archive": archive = original["archive"] return {archive["archive_name"]: (archive["byte_length"], archive["sha256"])} return { f["logical_path"]: (f["byte_length"], f["sha256"]) for f in original["source"]["members"] } def confirm_storage( store: SimulationProjectStore, project_id: str, provider: GaussianPipelineGateway, receipt: dict[str, Any], ) -> None: """Persist the verified ownership receipt BEFORE allowing any local unlink.""" provider.retained_source(receipt) project = store.get(project_id) local = {f["logical_path"]: (f["byte_length"], f["sha256"]) for f in project["source"]["files"]} if project["source"]["kind"] != receipt["input"]["kind"] or local != receipt_files(receipt): raise GaussianPipelineIntegrityError("Worker did not retain every imported source file") store.update_source_storage( project_id, storage={ "provider_endpoint": provider.endpoint, "receipt": receipt, "local_state": "verified", }, ) def retire_local_source( store: SimulationProjectStore, project_id: str, provider: GaussianPipelineGateway ) -> int: """Exact-file deletion only; partial retirement can resume after a crash.""" project = store.get(project_id) source = project["source"] storage = source.get("storage") or {} if storage.get("local_state") == "remote": provider.retained_source(storage["receipt"]) return 0 receipt = provider.retained_source(storage["receipt"], verify=True) expected = receipt_files(receipt) local_files = {f["logical_path"]: (f["byte_length"], f["sha256"]) for f in source["files"]} if expected != local_files: raise GaussianPipelineIntegrityError("Source receipt differs from local project") root = store.source_root(project_id) if root.is_symlink(): raise GaussianPipelineIntegrityError("Source root is a symlink") # Older Core releases could evict a complete archive for artifact capacity. # Recover its ownership from fresh Worker hashes; no local bytes are deleted. legacy_remote_archive = source["kind"] == "archive" and all( not (root / name).exists() for name in expected ) paths = [] fingerprints = {} for name, (size, digest) in expected.items(): candidate = root / name if candidate.is_symlink() or not candidate.resolve().is_relative_to(root.resolve()): raise GaussianPipelineIntegrityError("Local source path is unsafe") if not candidate.exists(): if ( not legacy_remote_archive and storage.get("local_state") not in {"retiring", "remote"} ): raise GaussianPipelineIntegrityError("Original disappeared before retirement") continue stat = candidate.stat() if ( not candidate.is_file() or candidate.stat().st_size != size or _digest(candidate) != digest ): raise GaussianPipelineIntegrityError("Local original changed; retirement refused") fingerprints[candidate] = (stat.st_ino, stat.st_size, stat.st_mtime_ns) paths.append(candidate) for candidate in root.rglob("*"): if candidate.is_symlink() or ( candidate.is_file() and candidate.relative_to(root).as_posix() not in expected ): raise GaussianPipelineIntegrityError("Unregistered source file; retirement refused") with store._lock: current = store.get(project_id)["source"] if ( current["files"] != source["files"] or current.get("storage", {}).get("receipt", {}).get("input") != receipt["input"] ): raise GaussianPipelineIntegrityError("Source ownership changed during verification") if current["storage"].get("local_state") == "remote": return 0 for candidate in paths: stat = candidate.lstat() if ( candidate.is_symlink() or (stat.st_ino, stat.st_size, stat.st_mtime_ns) != fingerprints[candidate] ): raise GaussianPipelineIntegrityError("Source changed after verification") # The analysis contract already permits only one small trajectory JSON. # Retain this metadata, not another copy of the cloud/archive. trajectories = [p for p in paths if p.name.lower() == "poses.json"] if len(trajectories) == 1 and trajectories[0].stat().st_size <= 16 * 1024**2: target = root.parent / "metadata" / "poses.json" target.parent.mkdir(exist_ok=True) with target.open("wb") as stream: stream.write(trajectories[0].read_bytes()) stream.flush() os.fsync(stream.fileno()) if os.name != "nt": directory_fd = os.open(target.parent, os.O_RDONLY) try: os.fsync(directory_fd) finally: os.close(directory_fd) storage = {**storage, "local_state": "retiring"} store.update_source_storage(project_id, storage=storage) removed = 0 for candidate in paths: removed += candidate.stat().st_size candidate.unlink() directories = sorted( (p for p in root.rglob("*") if p.is_dir()), key=lambda p: len(p.parts), reverse=True ) for directory in directories: directory.rmdir() store.update_source_storage(project_id, storage={**storage, "local_state": "remote"}) return removed def prepare_source( store: SimulationProjectStore, project_id: str, provider: GaussianPipelineGateway ) -> GaussianSourceBundleUpload: project = store.get(project_id) storage = project["source"].get("storage") if storage: receipt = provider.retained_source(storage["receipt"]) else: provider.require_source_retention() root = store.source_root(project_id) if project["source"]["kind"] == "archive": item = project["source"]["files"][0] archive = provider.upload_source_archive(root / item["logical_path"]) original = {"kind": "archive", "archive": archive.to_dict()} else: entrypoint, source_format = discover_gaussian_source_bundle(root) bundle = provider.upload_source_bundle( root, entrypoint=entrypoint, source_format=source_format, additional_paths=[f["logical_path"] for f in project["source"]["files"]], ) original = {"kind": "folder", "source": bundle.to_dict()} receipt = provider.retain_source(original) confirm_storage(store, project_id, provider, receipt) retire_local_source(store, project_id, provider) original = receipt["input"] if original["kind"] == "folder": return _source_bundle_upload(original["source"]) prepared = store.get(project_id)["source"].get("prepared_receipt") if prepared: return _source_bundle_upload(provider.retained_source(prepared)["input"]["source"]) bundle = provider.normalize_archive(GaussianArchiveUpload(**original["archive"])) prepared = provider.retain_source({"kind": "folder", "source": bundle.to_dict()}) store.update_source_storage(project_id, prepared_receipt=prepared) return bundle def _digest(path: Path) -> str: with path.open("rb") as stream: return hashlib.file_digest(stream, "sha256").hexdigest()