Files
NODEDC_MISSION_CORE/simulation/ai-polygon/infrastructure_preparer.py
T
DCCONSTRUCTIONS f48411f8fe feat(simulation): integrate infrastructure jobs and semantic scene editing
Integrate infrastructure preparation and qualified map delivery with local scenes. Add semantic editing, object provenance, survey caching and operator scene tools.
2026-10-29 09:10:01 +03:00

197 lines
8.0 KiB
Python

"""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 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)
registered_request(
client, endpoint, dict(action="release", previous_owner=record["owner"]), hello=hello
)
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 = Path(profile["job_root"]) / row["key"]
output.mkdir(parents=True, exist_ok=True)
write_json(marker, dict(key=row["key"], owner=client.instance, containers=[]))
endpoint = "/worker/infrastructure-analysis/" + row["key"]
last_pulse = -float("inf")
connected = True
phase = dict(phase="preparing", completed=0, total=0)
def pulse():
nonlocal last_pulse, phase, connected
if time.monotonic() - last_pulse < 3:
return
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 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")
write_json(output / "failure.json", dict(type=type(exc).__name__, message=str(exc)))
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")