Files
NODEDC_MISSION_CORE/simulation/ai-polygon/realtime_worker.py
T

611 lines
25 KiB
Python

"""Persistent host coordinator. Control/telemetry I/O never runs in the simulator.
The Windows task owns the coordinator; a Job Object fences its native children.
Closing the viewer or the private control tunnel cannot stop the physics clock.
Runs are bounded locally; reconnect reconciles the same identity, without replay.
"""
import argparse
import ctypes
import hashlib
import json
import logging
import os
import subprocess
import threading
import time
from pathlib import Path
from uuid import uuid4
from core_client import CoreClient, CoreRequestRejected
from local_state import StateChannel, create_episode, read_json, write_json
from model_stack import ROOT, ModelStack, docker, sha256, wait_for_docker
from worker import terminate_episode
class NativeJob:
"""Windows kills all native descendants if the coordinator unexpectedly exits."""
def __init__(self):
from ctypes import wintypes
self.kernel = ctypes.WinDLL("kernel32", use_last_error=True)
self.kernel.CreateJobObjectW.restype = wintypes.HANDLE
self.kernel.CreateJobObjectW.argtypes = [ctypes.c_void_p, wintypes.LPCWSTR]
self.kernel.SetInformationJobObject.argtypes = [
wintypes.HANDLE,
ctypes.c_int,
ctypes.c_void_p,
wintypes.DWORD,
]
self.kernel.AssignProcessToJobObject.argtypes = [wintypes.HANDLE, wintypes.HANDLE]
self.kernel.CloseHandle.argtypes = [wintypes.HANDLE]
self.handle = self.kernel.CreateJobObjectW(None, None)
# JOBOBJECT_EXTENDED_LIMIT_INFORMATION: 144 bytes on 64-bit Windows;
# BasicLimitInformation.LimitFlags is DWORD at offset 16.
limits = ctypes.create_string_buffer(144)
ctypes.c_uint32.from_buffer(limits, 16).value = 0x2000 # KILL_ON_JOB_CLOSE
if not self.handle or not self.kernel.SetInformationJobObject(self.handle, 9, limits, 144):
raise ctypes.WinError(ctypes.get_last_error())
def assign(self, child):
if not self.kernel.AssignProcessToJobObject(self.handle, int(child._handle)):
terminate_episode(child)
raise ctypes.WinError(ctypes.get_last_error())
def close(self):
if self.handle:
self.kernel.CloseHandle(self.handle)
self.handle = None
def acquire_service_lock(path):
import msvcrt
stream = path.open("a+b")
stream.seek(0)
if not stream.read(1):
stream.write(b"0")
stream.flush()
stream.seek(0)
msvcrt.locking(stream.fileno(), msvcrt.LK_NBLCK, 1)
return stream
def publish_previews(client, episode, run_id, stopped):
"""Best-effort view telemetry has its own connection and never delays control."""
last_frame, last_modified = -1, None
path = episode / "inference-preview.json"
while not stopped.wait(0.05):
try:
if not path.exists():
continue
modified = path.stat().st_mtime_ns
if modified == last_modified:
continue
preview = read_json(path)
if preview and preview["frame_id"] > last_frame:
client.request("/worker/runs/" + run_id + "/inference-preview", preview)
last_frame = preview["frame_id"]
last_modified = modified
except Exception as exc:
logging.warning("Inference preview unavailable: %s", type(exc).__name__)
stopped.wait(1)
def preparation_heartbeat(client, hello, run_id):
"""One-thread lease/control pulse; reconnect only this same expired owner."""
last_poll = -float("inf")
def pulse():
nonlocal last_poll
if time.monotonic() - last_poll < 1:
return
import http.client
for attempt in range(3):
try:
try:
desired = client.request(
"/worker/poll", {"instance_id": hello["instance_id"], "run_id": run_id}
)
except CoreRequestRejected as exc:
if (exc.status != 409 or exc.detail !=
"Сессия Worker истекла; требуется переподключение."):
raise
# Core checks the persisted run's complete hello identity.
# Never adopt another instance or infer a GPU release.
client.request("/worker/register", hello)
desired = client.request(
"/worker/poll", {"instance_id": hello["instance_id"], "run_id": run_id}
)
break
except (OSError, http.client.HTTPException):
if attempt == 2:
raise
time.sleep(0.2)
last_poll = time.monotonic()
control = desired.get("run")
if not control or control.get("run_id") != run_id:
raise RuntimeError("Preparation run ownership changed")
if control["control"] == "stop":
raise InterruptedError("Scene preparation cancelled")
return pulse
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--core", default="http://127.0.0.1:18080")
parser.add_argument("--token-file", type=Path, required=True)
parser.add_argument("--state", type=Path, required=True)
parser.add_argument("--evidence-root", type=Path,
help="Optional local volume for complete episode evidence")
parser.add_argument("--isaac", type=Path, required=True)
parser.add_argument("--stream-address", required=True)
args = parser.parse_args()
args.state.mkdir(parents=True, exist_ok=True)
lock = acquire_service_lock(args.state / "realtime-service.lock")
logging.basicConfig(
filename=args.state / "realtime-service.log",
level=logging.INFO,
format="%(asctime)s %(levelname)s %(message)s",
)
identity_path = args.state / "realtime-identity.json"
identity = read_json(identity_path)
release = sha256(ROOT / "realtime_worker.py")
active_path = args.state / "active.json"
if identity is None or (identity["release"] != release and not active_path.exists()):
identity = {"instance_id": uuid4().hex, "release": release}
write_json(identity_path, identity)
instance = identity["instance_id"]
client = CoreClient(args.core, args.token_file, instance)
stack = ModelStack()
wait_for_docker(args.state / "service-status.json")
from k1link.simulation.ai_polygon.composition import registry
sources = {
"worker": hashlib.sha256((release + sha256(ROOT / "run_report.py")).encode()).hexdigest(),
"scene": hashlib.sha256(
"".join(
sha256(ROOT / n)
for n in (
"run_realtime.py",
"native_experience.py",
"scheduling_policy.py",
"motion_control.py",
"rover_profile.py",
"tracked_rover.py",
"track_dynamics.py",
"../../src/k1link/fleet/differential_drive.py",
"realtime_ai.py",
"local_state.py",
"terrain.py",
"mounted_sensors.py",
"spawn_clearance.py",
"prepare_terrain.py",
"project_assets.py",
"decode_collision.cjs",
"navigation_client.py",
"route_view.py",
"observer_camera.py",
"inference_preview.py",
"terrain_picker.py",
"navigation/server.py",
"navigation/turn_staging.py",
"navigation/semantic_surface.py",
"navigation/footprint.py",
"navigation/fastdds.xml",
"navigation/Prepare-Terrain.ps1",
)
).encode()
+ "".join(
sha256(ROOT.parents[1] / "src/k1link/simulation/ai_polygon" / n)
for n in (
"inference.py",
"policy.py",
"contracts.py",
"run_robot.py",
"run_inputs.py",
"source_projection.py",
"camera_optics.py",
"sensor_mounts.py",
"composition.py",
"driving_profiles.py",
"terrain_contract.py",
)
).encode()
+ "".join(
sha256(ROOT.parents[1] / "src/k1link" / n)
for n in (
"artifacts.py",
"observatory/__init__.py",
"observatory/modular_composition.py",
"simulation/__init__.py",
)
).encode()
).hexdigest(),
"models": hashlib.sha256(
"".join(
sha256(ROOT / name)
for name in (
"models.worker-006.json",
"model_stack.py",
"compose.models.yaml",
"ddrnet_server.py",
"segformer/server.py",
)
).encode()
+ json.dumps(registry(ROOT).catalog(), sort_keys=True,
separators=(",", ":")).encode()
).hexdigest(),
"robot": hashlib.sha256(
"".join(
sha256(ROOT / name)
for name in ("rover_profile.py", "rover_visual.py", "robots/dcd006-v020.json")
).encode()
).hexdigest(),
}
from k1link.simulation.ai_polygon.route_preparation import provider_identity
hello = {
"route_provider_sha256": provider_identity(),
"worker_id": "worker-006-ai-polygon",
"instance_id": instance,
"runtime": "isaac-sim-6.1",
"execution_modes": ["realtime"],
"scene_formats": ["gaussian-ply", "project-sog"],
"sensor_rig_versions": [
"missioncore.simulation-sensor-rig/v2",
"missioncore.simulation-sensor-rig/v3",
"missioncore.simulation-sensor-rig/v4",
],
"rover_settings_versions": ["missioncore.rover-settings/v1", "missioncore.rover-settings/v2"],
"execution_inputs_versions": [
"missioncore.simulation-inputs/v1",
"missioncore.simulation-inputs/v2",
"missioncore.simulation-inputs/v3",
],
"model_ids": [m["id"] for m in stack.profile["models"]]
+ [stack.profile["navigation"]["id"]]
+ ([stack.profile["nav2"]["id"]] if "nav2" in stack.profile else []),
"profile_sha256": hashlib.sha256(json.dumps(sources, sort_keys=True).encode()).hexdigest(),
"runtime_sources": sources,
"robots": {
"dcd006-v020": sha256(ROOT / "robots/dcd006-v020.json"),
},
"stream": {
"server": args.stream_address,
"signaling_port": 49100,
"media_port": 47998,
"width": 1280,
"height": 720,
"fps": 30,
},
}
write_json(
args.state / "service-status.json",
{"pid": os.getpid(), "instance_id": instance, "hello": hello},
)
def connect():
while True:
try:
client.request("/worker/register", hello)
return
except Exception as exc:
logging.warning("Control unavailable: %s", type(exc).__name__)
time.sleep(3)
# A previous process died. Its Job Object has killed native children.
# Reconcile only exact persisted container IDs; never infer release from a lease.
orphan = read_json(active_path)
if orphan:
if orphan.get("instance_id") != instance:
raise RuntimeError("Reconciliation identity mismatch")
for cid in orphan.get("model_container_ids", []):
record = docker("container", "inspect", cid, check=False)
if record.returncode == 0:
data = json.loads(record.stdout)[0]
if data["Config"]["Labels"].get("com.nodedc.stack") != "ai-polygon":
raise RuntimeError("Reconciliation resource owner changed")
stack.ids.append(cid)
stack.stop()
connect()
client.request(
"/worker/runs/" + orphan["run_id"] + "/finish",
orphan.get("finish")
or {
"instance_id": instance,
"outcome": "failed",
"resources_released": True,
"message": "Worker перезапустился. Прогон завершён без повторного запуска.",
},
)
active_path.unlink()
try:
stack.preflight()
except Exception:
write_json(
args.state / "service-status.json",
{"state": "invalid-installation", "pid": os.getpid()},
)
raise
connect()
editor_marker = args.state / "editor-active.json"
route_marker = args.state / "route-active.json"
while True:
try:
# A prior coordinator's Windows Job killed all native descendants on exit.
# Retain the marker until Core accepts that resource-release receipt.
if route_marker.exists():
key = read_json(route_marker)["key"]
client.request("/worker/route-preparations/" + key, {"action": "release"})
route_marker.unlink()
if editor_marker.exists():
key = read_json(editor_marker)["key"]
client.request("/worker/editor-cache/" + key, {"action": "release"})
editor_marker.unlink()
polled = client.request("/worker/poll", {"instance_id": instance})
except Exception:
connect()
continue
if polled["action"] == "idle":
time.sleep(0.5)
continue
if polled["action"] == "route-preparation":
from route_preparer import prepare_route
route_job = NativeJob()
write_json(route_marker, {"key": polled["preparation"]["key"]})
try:
prepare_route(client, polled["preparation"], args.state, args.isaac, route_job)
finally:
route_job.close()
continue
if polled["action"] == "editor-cache":
from editor_assets import prepare_editor
editor_job = NativeJob()
write_json(editor_marker, {"key": polled["cache"]["key"]})
try:
prepare_editor(client, polled["cache"], args.state, editor_job)
finally:
editor_job.close()
# Receipt is sent at the top of the loop, after the Job is closed.
continue
run = polled["run"]
if run.get("clock") != "realtime":
raise RuntimeError("A realtime worker cannot execute lockstep work")
episode = args.state / run["run_id"]
if episode.exists():
raise RuntimeError("An existing episode must never be replayed")
episode = create_episode(args.state, run["run_id"], args.evidence_root)
run_file = episode / "run.json"
write_json(run_file, run)
channel = StateChannel(episode)
channel.write("control", run)
active = {"run_id": run["run_id"], "instance_id": instance, "model_container_ids": []}
write_json(active_path, active)
child = job = starter = preview_sender = None
preview_stopped = threading.Event()
cancelled = threading.Event()
models_ready = threading.Event()
model_failure = []
result = {
"outcome": "failed",
"mission_outcome": "error",
"message": "Прогон прерван. Журнал сохранён на Worker.",
}
try:
from k1link.simulation.ai_polygon.run_inputs import resolve_run_inputs
from k1link.simulation.ai_polygon.run_robot import resolve_run_robot
inputs = resolve_run_inputs(run, resolve_run_robot(run))
write_json(episode / "execution-inputs.json", inputs)
preparation_pulse = preparation_heartbeat(client, hello, run["run_id"])
cache = args.state / "worlds"
cache.mkdir(exist_ok=True)
source = cache / (run["world"]["sha256"] + ".ply")
if not run["world"].get("local_scene"):
client.download(run["world"], source, pulse=preparation_pulse)
preparation_pulse()
client.request("/worker/runs/" + run["run_id"] + "/progress", {"phase": "scene"})
from prepare_terrain import prepare_terrain
job = NativeJob()
if run["world"].get("local_scene"):
from project_assets import prepare_project
source, terrain_path = prepare_project(
client, run, args.state, episode, job, preparation_pulse, args.isaac
)
else:
terrain_path = prepare_terrain(
args.state.parent, episode, run["world"], job, preparation_pulse
)
expected = (run.get("plan") or {}).get("editor_collider_sha256")
terrain_manifest = read_json(terrain_path)
if (
expected
and terrain_manifest.get(
"source_collider_sha256", terrain_manifest.get("collider_sha256")
)
!= expected
):
raise ValueError("Saved task and simulation surface identities differ")
run["terrain_manifest"] = str(terrain_path)
write_json(run_file, run)
with (episode / "isaac.log").open("wb") as output:
child = subprocess.Popen(
[
str(args.isaac / "python.bat"),
str(ROOT / "run_realtime.py"),
"--run",
str(run_file),
"--source",
str(source),
"--stream-address",
args.stream_address,
],
stdout=output,
stderr=subprocess.STDOUT,
)
job.assign(child)
def acquired(ids, active=active):
active["model_container_ids"] = ids
write_json(active_path, active)
def start_models(
cancelled=cancelled,
model_failure=model_failure,
acquired=acquired,
run=run,
models_ready=models_ready,
inputs_path=episode / "execution-inputs.json",
):
try:
stack.start(
cancelled=cancelled.is_set,
on_acquired=acquired,
selection=run["request"].get("composition"),
inputs_path=inputs_path,
)
models_ready.set()
except InterruptedError:
pass
except Exception as exc:
model_failure.append(type(exc).__name__)
logging.exception("Model startup failed")
stop_deadline = None
last_snapshot = -1
preview_sender = threading.Thread(
target=publish_previews,
args=(client, episode, run["run_id"], preview_stopped),
name="polygon-inference-preview",
daemon=True,
)
preview_sender.start()
registered = True
readiness_sent = False
while child.poll() is None:
now = time.monotonic()
if stop_deadline and now >= stop_deadline:
terminate_episode(child)
break
if model_failure:
raise RuntimeError("Local model startup failed")
if models_ready.is_set() and not readiness_sent:
channel.write("models", {"ready": True})
readiness_sent = True
try:
if not registered:
client.request("/worker/register", hello)
registered = True
polled = client.request(
"/worker/poll", {"instance_id": instance, "run_id": run["run_id"]}
)
desired = polled["run"]
channel.write("control", desired)
if desired["control"] == "stop":
cancelled.set()
stop_deadline = stop_deadline or now + 15
if (
desired["control"] == "play"
and starter is None
and run["request"].get("purpose") != "planning"
):
starter = threading.Thread(
target=start_models, name="polygon-model-start", daemon=True
)
starter.start()
snapshot = channel.read("snapshot")
if snapshot and snapshot["sequence"] > last_snapshot:
client.request("/worker/runs/" + run["run_id"] + "/snapshot", snapshot)
last_snapshot = snapshot["sequence"]
except Exception as exc:
registered = False
logging.warning(
"Episode control/telemetry disconnected: %s", type(exc).__name__
)
time.sleep(0.05)
result = read_json(episode / "result.json", result)
if cancelled.is_set():
result = {
"outcome": "stopped",
"mission_outcome": "operator-stop",
"message": "Движение и inference остановлены.",
}
except InterruptedError:
result = {
"outcome": "stopped",
"mission_outcome": "operator-stop",
"message": "Подготовка симуляции остановлена.",
}
except Exception as exc:
from scene_capacity import ScenePreparationError
import traceback
logging.exception("Episode failed")
write_json(episode / "failure.json", {
"type": type(exc).__name__, "detail": str(exc),
"traceback": traceback.format_exc(),
})
if isinstance(exc, ScenePreparationError):
result["message"] = str(exc)
finally:
preview_stopped.set()
if preview_sender is not None:
preview_sender.join(timeout=11)
channel.close()
cancelled.set()
if child is not None and child.poll() is None:
terminate_episode(child)
if job is not None:
job.close()
if starter is not None:
starter.join(timeout=150)
if starter.is_alive():
raise RuntimeError("Model startup has not released ownership")
stack.stop()
active["resources_released"] = True
write_json(active_path, active)
write_json(episode / "worker-result.json", result)
finish = {key: result[key] for key in ("outcome", "message")}
finish.update(instance_id=instance, resources_released=True)
try:
from run_report import seal_episode
finish["report"] = seal_episode(episode, result)
except Exception:
logging.exception("Episode report could not be sealed")
finish["message"] += (
" Не удалось сформировать сводный отчёт. Исходные журналы на Worker."
)
active["finish"] = finish
write_json(active_path, active)
while True:
try:
client.request("/worker/register", hello)
client.request(
"/worker/runs/" + run["run_id"] + "/finish",
finish,
)
active_path.unlink()
break
except Exception:
logging.warning("Finish pending reconciliation")
time.sleep(3)
lock.close()
if __name__ == "__main__":
try:
main()
except Exception:
logging.exception("Simulation coordinator failed")
raise