Files
NODEDC_MISSION_CORE/simulation/ai-polygon/qualify_gaussian_episode.py
T
DCCONSTRUCTIONS d0e5f90952 Preserve installed operator workspace before consolidation
Local preservation snapshot, not a new deployment or simulation acceptance.
2026-10-08 09:59:51 +03:00

465 lines
20 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Bounded candidate qualification using the production Gaussian/AI loop.
The operator-side caller holds the canonical Core GPU reservation throughout.
No worker registration, installed release change, or physical device command.
Reference episodes and cached scene assets remain immutable.
"""
import argparse
import copy
import hashlib
import json
import math
import re
import subprocess
import sys
import time
import traceback
from contextlib import suppress
from datetime import UTC, datetime
from pathlib import Path
ROOT = Path(__file__).resolve().parent
sys.path.insert(0, str(ROOT.parents[1] / "src"))
def sha256(path):
with Path(path).open("rb") as stream:
return hashlib.file_digest(stream, "sha256").hexdigest()
def gaussian_scene_proof(source, episode):
from gaussian_cache import verify_loaded_gaussian
path = Path(episode) / "gaussian-visual.json"
if not path.is_file():
return {"gaussian_usd_sha256": None, "gaussian_visual_status": "not-loaded"}
receipt = json.loads(path.read_text())
verify_loaded_gaussian(source, receipt)
return {"gaussian_usd_sha256": receipt["usd_sha256"],
"gaussian_visual_status": "verified",
"gaussian_visual_receipt_sha256": sha256(path),
"gaussian_cache_key": receipt["cache_key"]}
def prepare_run(
reference,
run_id,
seconds,
length,
manifest,
scenario=None,
rover_settings=None,
routing=None,
mounted_sensors=False,
surface_provider=None,
continuous_sensors=False,
preserve_task=False,
):
from k1link.simulation.ai_polygon.composition import compose, digest, registry
from k1link.simulation.ai_polygon.robots import select_robot
if not re.fullmatch(r"airun-[a-f0-9]{32}", run_id):
raise ValueError("Invalid qualification identity")
# The positional seconds argument remains for old experiment callers only.
# It grants no deadline. Every route now runs to its actual terminal state.
if not math.isfinite(length) or not 2 <= length <= 8:
raise ValueError("Synthetic qualification length must be 2–8 metres")
run = copy.deepcopy(reference)
if preserve_task:
if scenario is not None or routing is not None or not reference.get("plan", {}).get("settings"):
raise ValueError("Original-task qualification requires an intact reference plan and no scenario override")
run["world"]["settings"] = copy.deepcopy(reference["plan"]["settings"])
if rover_settings is None:
rover_settings = copy.deepcopy(reference["request"].get("rover_settings"))
robot = select_robot("dcd006-v020")
if robot["physics"].get("contact_model") != "tracks":
raise ValueError("Gaussian tracked qualification requires a pinned tracks profile")
run["run_id"], run["robot"] = run_id, robot
run["request_id"] = run_id.removeprefix("airun-")
run["created_at"] = datetime.now(UTC).isoformat()
run["control"], run["control_sequence"], run["state"] = "play", 0, "starting"
run["planning_commands"], run["planning_sequence"] = [], 0
settings = run["world"]["settings"]
heading = math.radians(settings["heading_degrees"])
x, y = settings["spawn_xy"]
# Three task goals within the original forward corridor. They do not grant
# surface permission or bypass the live semantic/range planner.
short_route = [
[
x + forward * math.cos(heading) - lateral * math.sin(heading),
y + forward * math.sin(heading) + lateral * math.cos(heading),
]
for forward, lateral in ((length / 3, 0.15), (2 * length / 3, -0.15), (length, 0))
]
if not preserve_task:
settings["route_xy"] = short_route
settings["max_speed_mps"] = min(settings["max_speed_mps"], 0.15)
if routing is not None:
from k1link.simulation.ai_polygon.route_graph import validate_routing
if scenario is not None and scenario not in {
"obstacle",
"route-obstacle",
"route-obstacle-clearance",
"route-obstacle-after-travel",
}:
raise ValueError("Declared routes currently admit only the frozen obstacle challenge")
nodes = {node["id"]: node["xy"] for node in routing["map"]["nodes"]}
goals = [nodes[key] for key in routing["goal_nodes"]]
validate_routing(routing, run["world"]["sha256"], goals)
if nodes[routing["start_node"]] != settings["spawn_xy"]:
raise ValueError("Declared qualification must retain the reference spawn")
settings["route_xy"] = copy.deepcopy(goals)
elif scenario in {"route-obstacle", "route-obstacle-clearance", "route-obstacle-after-travel"}:
raise ValueError("Persistent route obstacle requires a declared route")
run.pop("execution_inputs", None)
run.pop("rover_configuration", None)
run["request"].pop("rover_settings", None)
if rover_settings is not None:
from k1link.simulation.ai_polygon.run_robot import configure_robot
if scenario is not None:
raise ValueError("Legacy disturbance scenarios require their frozen speed profile")
_, configuration = configure_robot(robot, rover_settings)
run["request"]["rover_settings"] = configuration["settings"]
run["rover_configuration"] = configuration
settings["max_speed_mps"] = configuration["settings"]["max_speed_mps"]
installed = {module.module_id: module for module in registry(ROOT).modules}
selection = copy.deepcopy(reference["request"]["composition"])
if surface_provider not in (None, "simulation-ddrnet-goose", "simulation-segformer-ade", "simulation-segformer-cityscapes", "simulation-mask2former-mapillary", "simulation-sam3-surfaces"):
raise ValueError("Unknown qualification surface provider")
for selected in selection["selections"]:
if selected["group"] == "segmentation" and surface_provider is not None:
selected["module_id"] = surface_provider
selected["module_sha256"] = installed[selected["module_id"]].sha256
graph = compose(ROOT, selection)
plan = {
"schema_version": "missioncore.simulation-plan/v1",
"plan_id": "aiplan-" + run_id.removeprefix("airun-"),
"source": ("bounded-qualification-original-task" if preserve_task else
"bounded-qualification-declared-route" if routing is not None else
"bounded-qualification-reference-corridor"),
"source_run_id": reference["run_id"],
"robot_id": robot["robot_id"],
"robot_sha256": robot["sha256"],
"world_sha256": run["world"]["sha256"],
"collider_sha256": run["world"]["collider_sha256"],
"settings": copy.deepcopy(settings),
"arrival_radius_m": 0.4,
}
plan["sha256"] = digest(plan)
run["plan"] = plan
run["request"].update(
robot_sha256=robot["sha256"],
composition=selection,
start_paused=False,
purpose="evaluation",
plan_id=plan["plan_id"],
clock="realtime",
)
run["request"].pop("duration_seconds", None)
run["request"].pop("max_steps", None)
run["worker"] = {
"worker_id": "worker-006-bounded-qualification",
"runtime": "isaac-sim-6.1",
"runtime_sources": {
"scene": digest(manifest),
"worker": sha256(Path(__file__)),
"robot": robot["sha256"],
"models": sha256(ROOT / "models.worker-006.json"),
},
}
run["qualification"] = {
"authority": "virtual-only",
"reference_run_id": reference["run_id"],
"composition_sha256": graph.sha256,
"source_sha256": manifest,
"contact_model": "tracks",
"livestream": "disabled; renderer and inference camera remain active",
"operator_release_changed": False,
}
if preserve_task:
run["qualification"]["reference_plan_sha256"] = reference["plan"]["sha256"]
run["qualification"]["original_task_preserved"] = True
if scenario is not None:
from qualification_scenarios import scenario_spec
run["qualification"]["scenario"] = scenario_spec(scenario)
from k1link.simulation.ai_polygon.run_inputs import legacy_run_inputs
from k1link.simulation.ai_polygon.run_robot import resolve_run_robot
run["execution_inputs"] = legacy_run_inputs(run, resolve_run_robot(run))
if mounted_sensors or continuous_sensors:
from k1link.simulation.ai_polygon.run_inputs import mounted_run_inputs
run["execution_inputs"] = mounted_run_inputs(
run["execution_inputs"], resolve_run_robot(run), continuous=continuous_sensors
)
if routing is not None:
from k1link.simulation.ai_polygon.route_graph import build_route
from k1link.simulation.ai_polygon.run_inputs import declared_route_inputs
run["execution_inputs"] = declared_route_inputs(
run["execution_inputs"], routing, resolve_run_robot(run), run["world"]["sha256"]
)
route = build_route(run["execution_inputs"])
if (
any(leg["status"] != "ready" for leg in route["legs"])
or sum(leg["length_m"] for leg in route["legs"]) > 30
):
raise ValueError("Gaussian route qualification requires a ready route within 30m")
run["qualification"]["route_map_sha256"] = routing["map"]["sha256"]
return run
def read_routing(path, expected):
if path is None and expected is None:
return None
if (
path is None
or not isinstance(expected, str)
or not re.fullmatch(r"[a-f0-9]{64}", expected)
or path.stat().st_size > 256 * 1024
or sha256(path) != expected
):
raise ValueError("A bounded route file with its exact SHA-256 is required")
return json.loads(path.read_text(encoding="utf-8"))
def await_native_scene(child, directory, cancelled, *, timeout_seconds=120,
clock=time.monotonic, sleep=time.sleep):
"""Initialize native rendering before allocating inference GPU contexts."""
from local_state import read_json
deadline = clock() + timeout_seconds
while True:
if cancelled():
raise RuntimeError("Native preparation cancelled")
if child.poll() is not None:
raise RuntimeError("Native child exited during preparation")
if read_json(directory / "startup.json", {}).get("phase") == "ready":
return
if clock() >= deadline:
raise TimeoutError("Native scene preparation deadline")
sleep(0.25)
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--reference-run", type=Path, required=True)
parser.add_argument("--output", type=Path, required=True)
parser.add_argument("--runtime-root", type=Path, required=True)
parser.add_argument("--bundle-manifest", type=Path, required=True)
parser.add_argument("--reservation-receipt", type=Path, required=True)
parser.add_argument("--run-id", required=True)
parser.add_argument("--seconds", type=int, default=None, help=argparse.SUPPRESS)
parser.add_argument("--length", type=float, default=4.2)
from qualification_scenarios import SCENARIOS
parser.add_argument("--scenario", choices=SCENARIOS)
parser.add_argument("--rover-settings", type=Path)
parser.add_argument("--routing", type=Path)
parser.add_argument("--routing-sha256")
parser.add_argument("--mounted-sensors", action="store_true")
parser.add_argument("--continuous-sensors", action="store_true")
parser.add_argument("--preserve-task", action="store_true")
parser.add_argument(
"--surface-provider", choices=("simulation-ddrnet-goose", "simulation-segformer-ade", "simulation-segformer-cityscapes", "simulation-mask2former-mapillary", "simulation-sam3-surfaces")
)
args = parser.parse_args()
from local_state import StateChannel, read_json, write_json
from model_stack import ModelStack
from realtime_worker import NativeJob
from run_report import seal_episode
receipt = read_json(args.reservation_receipt)
if receipt.get("owner_id") != args.run_id or receipt.get("state") != "reserved":
raise ValueError("An exact Core reservation receipt is required")
age = (datetime.now(UTC) - datetime.fromisoformat(receipt["utc"])).total_seconds()
if not 0 <= age <= 900:
raise ValueError("Reservation receipt is stale")
manifest = read_json(args.bundle_manifest)
for name, expected in manifest.items():
if sha256(ROOT.parents[1] / name) != expected:
raise ValueError("Candidate source changed: " + name)
reference = read_json(args.reference_run)
run = prepare_run(
reference,
args.run_id,
args.seconds,
args.length,
manifest,
args.scenario,
json.loads(args.rover_settings.read_text()) if args.rover_settings else None,
read_routing(args.routing, args.routing_sha256),
args.mounted_sensors,
args.surface_provider,
args.continuous_sensors,
args.preserve_task,
)
run["qualification"]["reference_run_sha256"] = sha256(args.reference_run)
run["qualification"]["bundle_identity"] = sha256(args.bundle_manifest)
active = args.runtime_root / "state/active.json"
if active.exists():
raise RuntimeError("Operator episode active")
from qualification_assets import cached_scene
source, terrain, scene_proof = cached_scene(args.runtime_root, run)
args.output.mkdir(parents=True, exist_ok=False)
write_json(args.output / "run.json", run)
write_json(args.output / "execution-inputs.json", run["execution_inputs"])
write_json(args.output / "reservation.json", receipt)
channel = StateChannel(args.output)
channel.write("control", run)
job, stack = NativeJob(), ModelStack()
child = None
result = {"outcome": "failed", "mission_outcome": "error", "message": "Qualification failed"}
acquired = []
cleanup_ok = False
try:
def acquired_ids(ids):
acquired[:] = ids
write_json(args.output / "owned-containers.json", {"ids": ids})
isaac = args.runtime_root / "isaac-sim-6.1.0"
with (args.output / "isaac.log").open("wb") as log:
child = subprocess.Popen(
[
str(isaac / "python.bat"),
str(ROOT / "run_realtime.py"),
"--run",
str(args.output / "run.json"),
"--source",
str(source),
"--stream-address",
"127.0.0.1",
"--no-stream",
],
cwd=isaac,
stdout=log,
stderr=subprocess.STDOUT,
)
job.assign(child)
await_native_scene(child, args.output, active.exists)
stack.start(
cancelled=active.exists,
on_acquired=acquired_ids,
selection=run["request"]["composition"],
inputs_path=args.output / "execution-inputs.json",
)
channel.write("models", {"ready": True})
last_status = 0.0
while child.poll() is None:
if active.exists():
raise InterruptedError("Operator episode requested the Worker")
if time.monotonic() - last_status > 15:
snapshot = channel.read("snapshot", {})
print(
json.dumps(
{
"phase": read_json(args.output / "startup.json"),
"status": {
key: snapshot.get(key)
for key in (
"simulation_time_ns",
"pose_xy",
"speed_mps",
"rtf",
"inference_count",
"stop_reason",
"ai_ready",
)
},
}
),
flush=True,
)
last_status = time.monotonic()
time.sleep(0.25)
result = read_json(args.output / "result.json", result)
if args.continuous_sensors:
# Preserve the last causal planner transaction before its owned
# container is removed. This is diagnosis only, never replay input
# or a source of navigation authority.
try:
import urllib.request
with urllib.request.urlopen('http://127.0.0.1:18093/diagnostic-snapshot', timeout=5) as response:
raw = response.read(16 * 1024 * 1024 + 1)
if len(raw) > 16 * 1024 * 1024:
raise ValueError('Diagnostic snapshot exceeds bound')
diagnostic = json.loads(raw)
if diagnostic['execution_inputs_sha256'] != run['execution_inputs']['sha256']:
raise ValueError('Diagnostic snapshot belongs to another episode')
write_json(args.output / 'navigation-diagnostic.json', diagnostic)
except Exception as exc:
write_json(args.output / 'navigation-diagnostic-error.json',
{'error': type(exc).__name__, 'message': str(exc)})
if child.returncode != 0:
result = {
"outcome": "failed",
"mission_outcome": "error",
"message": "Native child exit " + str(child.returncode),
}
except Exception:
(args.output / "qualification-error.txt").write_text(traceback.format_exc())
finally:
cleanup_errors = []
try:
if child is not None and child.poll() is None:
channel.write("control", {**run, "control": "stop"})
with suppress(subprocess.TimeoutExpired):
child.wait(timeout=10)
except Exception as exc:
cleanup_errors.append("stop-request: " + type(exc).__name__)
try:
job.close()
if child is not None:
child.wait(timeout=30)
except Exception as exc:
cleanup_errors.append("native-release: " + type(exc).__name__)
try:
stack.stop()
except Exception as exc:
cleanup_errors.append("model-release: " + type(exc).__name__)
finally:
channel.close()
cleanup_ok = not cleanup_errors
write_json(
args.output / "cleanup.json",
{
"owner_id": args.run_id,
"utc": datetime.now(UTC).isoformat(),
"monotonic": time.monotonic(),
"released": cleanup_ok,
"errors": cleanup_errors,
"native_pid": child.pid if child else None,
"container_ids": acquired,
},
)
try:
visual_proof = gaussian_scene_proof(source, args.output)
except (OSError, ValueError, TypeError) as exc:
visual_proof = {"gaussian_usd_sha256": None, "gaussian_visual_status": "invalid",
"gaussian_visual_error": str(exc)}
if visual_proof["gaussian_visual_status"] != "verified" and result["outcome"] == "completed":
result = {**result, "outcome": "failed", "mission_outcome": "error",
"message": "Loaded Gaussian visual evidence could not be verified"}
write_json(args.output / "worker-result.json", result)
write_json(
args.output / "scene-assets.json",
{
**scene_proof,
"gaussian_source_sha256": sha256(source),
**visual_proof,
"terrain_manifest_sha256": sha256(run["terrain_manifest"]),
"collider_sha256": sha256(terrain["collider"]),
},
)
report = seal_episode(args.output, result)
print(json.dumps({"cleanup_released": cleanup_ok, "report": report}), flush=True)
if __name__ == "__main__":
main()