"""Whole-scene Gaussian/trajectory analysis with owned Worker lifecycle.""" import contextlib import json import logging import shutil import subprocess import time from pathlib import Path from core_client import CoreRequestRejected from evidence_closeout import canonical, closeout, usage from infrastructure_containers import cleanup, docker, run_container from infrastructure_gaussian_sources import prepare_native from infrastructure_pipeline import MODULE, run_pipeline from infrastructure_sources import checksum from infrastructure_transport import registered_request, report_progress, unavailable from local_state import read_json, write_json from k1link.simulation.ai_polygon.infrastructure_jobs import provider_identity def capability(state): profile = json.loads((MODULE / "pipeline/worker-profile.json").read_text()) runtime = Path(state).parent try: for key in ("mapper_image", "semantic_image"): actual = docker("image", "inspect", profile[key], "--format", "{{.Id}}").stdout.strip() if actual != profile[key]: return None import runpy for pin in runpy.run_path(str(MODULE / "catalog_pass/catalog_dependency_pins.py"))["PINS"]: if checksum(MODULE / "pipeline/vendor" / pin["file"]) != pin["sha256"]: return None for path in [runtime / profile["splat_transform"], Path(profile["sevenzip"])]: if not path.is_file(): return None cfg = read_json(MODULE / "pipeline/config-mv.json") for model in cfg["models"].values(): for name, sha in model["files"].items(): if checksum(runtime / model["directory"] / name) != sha: return None model = read_json(Path(__file__).with_name("sam3-research") / "large-model.json") for name, sha in model["files"].items(): if checksum(runtime / profile["semantic_model"] / name) != sha: return None return provider_identity() except (OSError, ValueError, RuntimeError, subprocess.TimeoutExpired): logging.exception("Gaussian infrastructure capability is unavailable") return None def reconcile(client, marker, hello=None): record = read_json(marker) if not record: return cleanup(marker) record = read_json(marker) endpoint = "/worker/infrastructure-analysis/" + record["key"] if record.get("completion"): # The result outbox is durable before the first HTTP attempt. Replaying # identical complete is validated/idempotent at Core, including lost ACKs. output = ( Path(read_json(MODULE / "pipeline/worker-profile.json")["job_root"]) / record["key"] ) document = output / "urban-map.json" if checksum(document) != record["completion"]["sha256"]: raise ValueError("Pending infrastructure result changed") try: registered_request( client, endpoint, dict(action="complete", map=read_json(document)), hello=hello ) except CoreRequestRejected as exc: if exc.status != 400 and not ( exc.status == 409 and exc.detail in ("Analysis cancellation requested", "Analysis is not owned by this worker") ): raise # A confirmed cancellation/validation rejection is terminal, unlike # an unavailable Core. Preserve evidence; never publish around it. write_json( output / "publication-rejection.json", dict(status=exc.status, detail=exc.detail) ) record.pop("completion") write_json(marker, record) if not record.get("released"): registered_request( client, endpoint, dict(action="release", previous_owner=record["owner"]), hello=hello ) record["released"] = True write_json(marker, record) retention = record.get("retention") if retention: # Retain this durable marker across restart until archival and unlink # finish. Core ACK alone must never discard the cleanup obligation. closeout( Path(retention["root"]), Path(retention["archive_root"]), record["key"], keep=("urban-map.json", "publication-request.json", "failure.json"), limit=retention["archive_limit"], reserve=retention["reserve"], ) marker.unlink() def source_package(client, endpoint, pulse, deadline): # This is a read, so an interrupted response may safely be fetched again. while True: pulse() try: return client.request(endpoint, max_response_bytes=24 * 1024**2) except Exception as exc: if not unavailable(exc): raise if time.monotonic() >= deadline: raise TimeoutError( "Infrastructure source wait exceeded its runtime budget" ) from exc time.sleep(3) def prepare_infrastructure(client, row, state, marker, hello=None): state = Path(state) profile = read_json(MODULE / "pipeline/worker-profile.json") if row["identity"]["provider_sha256"] != provider_identity(): raise ValueError("Infrastructure provider changed") runtime = state.parent output = canonical(Path(profile["job_root"]) / row["key"]) existing = output.exists() and any(output.iterdir()) output.mkdir(parents=True, exist_ok=True) retention = None if not existing and profile.get("archive_root"): retention = dict( root=str(output), archive_root=profile["archive_root"], archive_limit=profile["archive_limit_gib"] * 1024**3, reserve=profile["minimum_free_gib"] * 1024**3, ) write_json( marker, dict(key=row["key"], owner=client.instance, containers=[], retention=retention) ) endpoint = "/worker/infrastructure-analysis/" + row["key"] last_pulse = -float("inf") connected = True last_storage_check = -float("inf") phase = dict(phase="preparing", completed=0, total=0) def pulse(): nonlocal last_pulse, phase, connected, last_storage_check if time.monotonic() - last_pulse < 3: return if time.monotonic() - last_storage_check >= 20 and profile.get("maximum_job_gib"): if usage(output) > profile["maximum_job_gib"] * 1024**3: raise RuntimeError("Infrastructure job storage limit reached") if shutil.disk_usage(output).free < profile["minimum_free_gib"] * 1024**3: raise RuntimeError("Infrastructure storage reserve reached") last_storage_check = time.monotonic() progress = output / "progress.json" if progress.exists(): with contextlib.suppress(ValueError, OSError): phase = read_json(progress) response = report_progress(client, endpoint, phase, hello=hello) online = response is not None if online != connected: logging.warning( "Infrastructure control %s; local computation retained", "restored" if online else "unavailable", ) connected = online last_pulse = time.monotonic() try: if existing: raise RuntimeError( "Existing infrastructure output is immutable; use a new job identity" ) if profile.get("maximum_jobs_gib"): reserved = profile["maximum_job_gib"] * 1024**3 if usage(output.parent) + reserved > profile["maximum_jobs_gib"] * 1024**3: raise RuntimeError("Infrastructure jobs storage quota reached") archive_root = Path(profile["archive_root"]) archive_root.mkdir(parents=True, exist_ok=True) if usage(archive_root) + reserved > profile["archive_limit_gib"] * 1024**3: raise RuntimeError("Infrastructure archive quota reached") if ( shutil.disk_usage(archive_root).free < reserved + profile["minimum_free_gib"] * 1024**3 ): raise RuntimeError("Infrastructure archive reserve reached") if shutil.disk_usage(output).free < profile["minimum_free_gib"] * 1024**3: raise RuntimeError("Insufficient space for Gaussian analysis results") pulse() package = source_package( client, "/worker/worlds/" + row["world"]["world_id"] + "/infrastructure-source", pulse, time.monotonic() + profile["maximum_seconds"], ) inputs, source = prepare_native(package, row["world"], state, profile, pulse, client=client) plan, snapshot = run_pipeline(inputs, source, output, marker, profile, runtime, pulse) if row["identity"]["provider_sha256"] != provider_identity(): raise ValueError("Infrastructure provider changed during execution") write_json( output / "publication-request.json", dict( plan=plan.relative_to(output).as_posix(), world=row["world"], key=row["key"], snapshot=snapshot, provider=row["identity"]["provider_sha256"], ), ) release = Path(__file__).resolve().parents[2] run_container( marker, "publication", profile["mapper_image"], [(release, "/release", True), (output, "/analysis", False)], ["-B", "/release/simulation/ai-polygon/infrastructure_document.py"], output, pulse, 300, gpu=False, executable="python3", environment={"PYTHONPATH": "/release/src"}, readonly=True, ) record = read_json(marker) record["completion"] = dict(sha256=checksum(output / "urban-map.json")) write_json(marker, record) except Exception as exc: logging.exception("Infrastructure analysis failed") failure = dict(type=type(exc).__name__, message=str(exc)) if existing: record = read_json(marker) record["rejected_existing_output"] = failure write_json(marker, record) else: write_json(output / "failure.json", failure) try: registered_request(client, endpoint, dict(action="fail"), hello=hello) except Exception: logging.warning("Infrastructure failure receipt awaits reconciliation") finally: try: reconcile(client, marker, hello) except Exception: # Keep the durable marker. The coordinator's existing reconnect loop # retries cleanup/release before polling any subsequent job. logging.exception("Infrastructure release awaits reconciliation")