Preserve installed operator workspace before consolidation
Local preservation snapshot, not a new deployment or simulation acceptance.
This commit is contained in:
@@ -17,9 +17,9 @@ import time
|
||||
from pathlib import Path
|
||||
from uuid import uuid4
|
||||
|
||||
from core_client import CoreClient
|
||||
from local_state import StateChannel, read_json, write_json
|
||||
from model_stack import ROOT, ModelStack, docker, sha256
|
||||
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
|
||||
|
||||
|
||||
@@ -72,11 +72,67 @@ def acquire_service_lock(path):
|
||||
return stream
|
||||
|
||||
|
||||
def publish_previews(client, episode, run_id, stopped):
|
||||
"""Best-effort view telemetry has its own connection and never delays control."""
|
||||
last_frame = -1
|
||||
while not stopped.wait(0.5):
|
||||
try:
|
||||
preview = read_json(episode / "inference-preview.json")
|
||||
if preview and preview["frame_id"] > last_frame:
|
||||
client.request("/worker/runs/" + run_id + "/inference-preview", preview)
|
||||
last_frame = preview["frame_id"]
|
||||
except Exception as exc:
|
||||
logging.warning("Inference preview unavailable: %s", type(exc).__name__)
|
||||
|
||||
|
||||
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()
|
||||
@@ -97,22 +153,37 @@ def main():
|
||||
instance = identity["instance_id"]
|
||||
client = CoreClient(args.core, args.token_file, instance)
|
||||
stack = ModelStack()
|
||||
stack.preflight()
|
||||
wait_for_docker(args.state / "service-status.json")
|
||||
from k1link.simulation.ai_polygon.composition import registry
|
||||
|
||||
sources = {
|
||||
"worker": release,
|
||||
"worker": hashlib.sha256((release + sha256(ROOT / "run_report.py")).encode()).hexdigest(),
|
||||
"scene": hashlib.sha256(
|
||||
"".join(
|
||||
sha256(ROOT / n)
|
||||
for n in (
|
||||
"run_realtime.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",
|
||||
@@ -124,7 +195,13 @@ def main():
|
||||
"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()
|
||||
@@ -149,18 +226,41 @@ def main():
|
||||
"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(),
|
||||
"robot": sha256(ROOT / "rover_profile.py"),
|
||||
}
|
||||
hello = {
|
||||
"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["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,
|
||||
@@ -201,7 +301,8 @@ def main():
|
||||
connect()
|
||||
client.request(
|
||||
"/worker/runs/" + orphan["run_id"] + "/finish",
|
||||
{
|
||||
orphan.get("finish")
|
||||
or {
|
||||
"instance_id": instance,
|
||||
"outcome": "failed",
|
||||
"resources_released": True,
|
||||
@@ -209,9 +310,24 @@ def main():
|
||||
},
|
||||
)
|
||||
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"
|
||||
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 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()
|
||||
@@ -219,43 +335,78 @@ def main():
|
||||
if polled["action"] == "idle":
|
||||
time.sleep(0.5)
|
||||
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.mkdir()
|
||||
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 = None
|
||||
child = job = starter = preview_sender = None
|
||||
preview_stopped = threading.Event()
|
||||
cancelled = threading.Event()
|
||||
models_ready = threading.Event()
|
||||
model_failure = []
|
||||
result = {"outcome": "failed", "message": "Прогон прерван. Журнал сохранён на Worker."}
|
||||
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")
|
||||
client.download(run["world"], source)
|
||||
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()
|
||||
|
||||
def preparation_pulse(run=run):
|
||||
desired = client.request(
|
||||
"/worker/poll", {"instance_id": instance, "run_id": run["run_id"]}
|
||||
)
|
||||
if desired["run"]["control"] == "stop":
|
||||
raise InterruptedError("Terrain preparation cancelled")
|
||||
if run["world"].get("local_scene"):
|
||||
from project_assets import prepare_project
|
||||
|
||||
terrain_path = prepare_terrain(
|
||||
args.state.parent, episode, run["world"], job, preparation_pulse
|
||||
)
|
||||
source, terrain_path = prepare_project(
|
||||
client, run, args.state, episode, job, preparation_pulse
|
||||
)
|
||||
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:
|
||||
@@ -280,14 +431,21 @@ def main():
|
||||
write_json(active_path, active)
|
||||
|
||||
def start_models(
|
||||
cancelled=cancelled, model_failure=model_failure, acquired=acquired, run=run
|
||||
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:
|
||||
@@ -295,16 +453,26 @@ def main():
|
||||
logging.exception("Model startup failed")
|
||||
|
||||
stop_deadline = None
|
||||
deadline = time.monotonic() + 300 + run["request"]["duration_seconds"]
|
||||
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 now >= deadline or (stop_deadline and now >= stop_deadline):
|
||||
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)
|
||||
@@ -317,7 +485,11 @@ def main():
|
||||
if desired["control"] == "stop":
|
||||
cancelled.set()
|
||||
stop_deadline = stop_deadline or now + 15
|
||||
if desired["control"] == "play" and starter is None:
|
||||
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
|
||||
)
|
||||
@@ -331,15 +503,35 @@ def main():
|
||||
logging.warning(
|
||||
"Episode control/telemetry disconnected: %s", type(exc).__name__
|
||||
)
|
||||
time.sleep(0.25)
|
||||
time.sleep(0.05)
|
||||
result = read_json(episode / "result.json", result)
|
||||
if cancelled.is_set():
|
||||
result = {"outcome": "stopped", "message": "Движение и inference остановлены."}
|
||||
result = {
|
||||
"outcome": "stopped",
|
||||
"mission_outcome": "operator-stop",
|
||||
"message": "Движение и inference остановлены.",
|
||||
}
|
||||
except InterruptedError:
|
||||
result = {"outcome": "stopped", "message": "Подготовка симуляции остановлена."}
|
||||
except Exception:
|
||||
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:
|
||||
@@ -354,12 +546,25 @@ def main():
|
||||
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",
|
||||
{**result, "instance_id": instance, "resources_released": True},
|
||||
finish,
|
||||
)
|
||||
active_path.unlink()
|
||||
break
|
||||
|
||||
Reference in New Issue
Block a user