Add prepared urban route guidance to Gaussian simulation planning
Introduce a content-bound scene route provider, advisory runtime graph and plan-preview-launch workflow. Preserve live sensing authority and retire blocked intermediate goals without discarding final-arrival evidence. Bound native visual context losslessly and provide verified cache relocation. Full Maroseyka route qualification remains open.
This commit is contained in:
@@ -190,7 +190,7 @@ def registry(adapter_root: Path) -> ModuleRegistry:
|
||||
),
|
||||
ModuleSpec(
|
||||
"simulation-declared-route",
|
||||
"Маршрут · объявленная карта",
|
||||
"Маршрут · карта или сцена",
|
||||
"preparation",
|
||||
nav["image"].removeprefix("sha256:"),
|
||||
digest(
|
||||
@@ -198,8 +198,9 @@ def registry(adapter_root: Path) -> ModuleRegistry:
|
||||
name: hashlib.sha256(
|
||||
Path(__file__).with_name(name).read_bytes()
|
||||
).hexdigest()
|
||||
for name in ("route_graph.py", "run_inputs.py")
|
||||
}
|
||||
for name in ("route_graph.py", "run_inputs.py", "route_preparation.py")
|
||||
} | {name: hashlib.sha256((adapter_root/name).read_bytes()).hexdigest()
|
||||
for name in ("scene_route_field.py", "route_preparer.py")}
|
||||
),
|
||||
None,
|
||||
digest({"route": "missioncore.global-route/v1", "authority": "route-intent-only"}),
|
||||
|
||||
@@ -151,6 +151,7 @@ class WorkerHello(Contract):
|
||||
rover_settings_versions: list[Literal["missioncore.rover-settings/v1", "missioncore.rover-settings/v2"]] = Field(
|
||||
default_factory=list, max_length=2
|
||||
)
|
||||
route_provider_sha256: str | None = Field(default=None, pattern=r"^[a-f0-9]{64}$")
|
||||
execution_inputs_versions: list[
|
||||
Literal[
|
||||
"missioncore.simulation-inputs/v1",
|
||||
@@ -386,7 +387,15 @@ class RealtimeSnapshot(Contract):
|
||||
planning: PlanningState | None = None
|
||||
|
||||
|
||||
class RoutePrepare(Contract):
|
||||
cache_key: str = Field(pattern=r"^[a-f0-9]{64}$")
|
||||
robot_id: str = Field(max_length=80)
|
||||
robot_sha256: str = Field(pattern=r"^[a-f0-9]{64}$")
|
||||
points: list[RoutePoint] = Field(min_length=2, max_length=33)
|
||||
|
||||
|
||||
class LocalPlanCreate(Contract):
|
||||
route_preparation_key: str | None = Field(default=None, pattern=r"^[a-f0-9]{64}$")
|
||||
cache_key: str = Field(pattern=r"^[a-f0-9]{64}$")
|
||||
draft_id: str = Field(pattern=r"^[a-f0-9]{32}$")
|
||||
sequence: int = Field(ge=0)
|
||||
|
||||
@@ -57,6 +57,7 @@ class PlanStore:
|
||||
draft_id=None,
|
||||
cache_key=None,
|
||||
editor_collider_sha256=None,
|
||||
prepared_route=None,
|
||||
):
|
||||
if not 2 <= len(points) <= 33:
|
||||
raise ValueError("Нужны старт и финиш: от 2 до 33 точек.")
|
||||
@@ -72,6 +73,7 @@ class PlanStore:
|
||||
and old["robot_sha256"] == run["robot"]["sha256"]
|
||||
and old["name"] == name
|
||||
and old["points"] == points
|
||||
and old.get("prepared_route") == prepared_route
|
||||
):
|
||||
return old
|
||||
for point in points:
|
||||
@@ -119,6 +121,12 @@ class PlanStore:
|
||||
editor_cache_key=cache_key,
|
||||
editor_collider_sha256=editor_collider_sha256,
|
||||
)
|
||||
if prepared_route is not None:
|
||||
value["prepared_route"] = prepared_route
|
||||
value["route_preparation_key"] = self.digest(prepared_route["identity"])
|
||||
value["length_m"] = prepared_route["length_m"]
|
||||
next_point = prepared_route["preview_xyz"][1]
|
||||
settings["heading_degrees"] = math.degrees(math.atan2(next_point[1]-first[1], next_point[0]-first[0]))
|
||||
row = {**value, "sha256": self.digest(value)}
|
||||
write_json(self.root / (row["plan_id"] + ".json"), row)
|
||||
return row
|
||||
|
||||
@@ -13,6 +13,7 @@ from k1link.simulation.ai_polygon.run_inputs import digest, number
|
||||
|
||||
MAP_SCHEMA = "missioncore.route-map/v1"
|
||||
ROUTE_SCHEMA = "missioncore.global-route/v1"
|
||||
PRIOR_MAP_SCHEMA = "missioncore.route-map/v2"
|
||||
|
||||
|
||||
def fields(value, expected):
|
||||
@@ -35,29 +36,44 @@ def xy(value):
|
||||
def validate_routing(routing, world_sha256, goals):
|
||||
fields(routing, "map start_node goal_nodes blocked_edges")
|
||||
graph = routing["map"]
|
||||
fields(graph, "schema_version frame world_sha256 nodes edges no_go sha256")
|
||||
prior = graph.get("schema_version") == PRIOR_MAP_SCHEMA
|
||||
fields(graph, "schema_version frame world_sha256 nodes edges no_go sha256"
|
||||
+ (" corridor_policy source" if prior else ""))
|
||||
if prior:
|
||||
if graph["corridor_policy"] != "advisory":
|
||||
raise ValueError("Unsupported route prior policy")
|
||||
fields(graph["source"], "provider provider_sha256 collider_sha256")
|
||||
if (not isinstance(graph["source"]["provider"], str)
|
||||
or not 1 <= len(graph["source"]["provider"]) <= 100
|
||||
or any(not re.fullmatch(r"[a-f0-9]{64}",str(graph["source"][k]))
|
||||
for k in ("provider_sha256", "collider_sha256"))):
|
||||
raise ValueError("Invalid route source identity")
|
||||
if (
|
||||
graph["schema_version"] != MAP_SCHEMA
|
||||
graph["schema_version"] not in {MAP_SCHEMA, PRIOR_MAP_SCHEMA}
|
||||
or graph["frame"] != "world-xy-metres"
|
||||
or not re.fullmatch(r"[a-f0-9]{64}", str(world_sha256))
|
||||
or graph["world_sha256"] != world_sha256
|
||||
or graph["sha256"] != digest({k: v for k, v in graph.items() if k != "sha256"})
|
||||
):
|
||||
raise ValueError("Route map identity or world mismatch")
|
||||
if not isinstance(graph["nodes"], list) or not 1 <= len(graph["nodes"]) <= 2048:
|
||||
if not isinstance(graph["nodes"], list) or not 1 <= len(graph["nodes"]) <= (16384 if prior else 2048):
|
||||
raise ValueError("Invalid route node budget")
|
||||
nodes = {}
|
||||
for node in graph["nodes"]:
|
||||
fields(node, "id xy")
|
||||
fields(node, "id xy" + (" z" if prior else ""))
|
||||
if prior:
|
||||
number(node["z"], -1e7, 1e7)
|
||||
key = identity(node["id"])
|
||||
if key in nodes:
|
||||
raise ValueError("Duplicate route node")
|
||||
nodes[key] = xy(node["xy"])
|
||||
if not isinstance(graph["edges"], list) or len(graph["edges"]) > 8192:
|
||||
if not isinstance(graph["edges"], list) or len(graph["edges"]) > (65536 if prior else 8192):
|
||||
raise ValueError("Invalid route edge budget")
|
||||
edges = set()
|
||||
for edge in graph["edges"]:
|
||||
fields(edge, "id start end half_width_m bidirectional")
|
||||
fields(edge, "id start end half_width_m bidirectional" + (" cost_m" if prior else ""))
|
||||
if prior:
|
||||
number(edge["cost_m"], 0.05, 1e7)
|
||||
key = identity(edge["id"])
|
||||
if (
|
||||
key in edges
|
||||
@@ -159,7 +175,7 @@ def build_route(inputs, *, unavailable_edges=(), start_node=None, goal_offset=0)
|
||||
reason = "declared-blocked"
|
||||
elif edge["id"] in unavailable:
|
||||
reason = "observed-unavailable"
|
||||
elif edge["half_width_m"] < radius:
|
||||
elif graph.get("corridor_policy") != "advisory" and edge["half_width_m"] < radius:
|
||||
reason = "insufficient-corridor-width"
|
||||
elif any(
|
||||
segment_intersects_box(
|
||||
@@ -187,7 +203,7 @@ def build_route(inputs, *, unavailable_edges=(), start_node=None, goal_offset=0)
|
||||
if node == goal:
|
||||
break
|
||||
for target, edge, a, b in adjacency[node]:
|
||||
candidate = cost + math.dist(a, b)
|
||||
candidate = cost + edge.get("cost_m", math.dist(a, b))
|
||||
if candidate < distances.get(target, math.inf):
|
||||
distances[target] = candidate
|
||||
previous[target] = (node, edge, a, b)
|
||||
@@ -204,6 +220,8 @@ def build_route(inputs, *, unavailable_edges=(), start_node=None, goal_offset=0)
|
||||
)
|
||||
cursor = parent
|
||||
segments.reverse()
|
||||
if graph.get("corridor_policy") == "advisory":
|
||||
segments = simplify_prior_segments(segments)
|
||||
legs.append(
|
||||
dict(
|
||||
start_node=start,
|
||||
@@ -211,7 +229,7 @@ def build_route(inputs, *, unavailable_edges=(), start_node=None, goal_offset=0)
|
||||
start_xy=nodes[start],
|
||||
goal_xy=nodes[goal],
|
||||
status="ready" if goal in distances else "unreachable",
|
||||
length_m=distances.get(goal),
|
||||
length_m=sum(math.dist(s["start_xy"],s["end_xy"]) for s in segments) if goal in distances else None,
|
||||
segments=segments,
|
||||
)
|
||||
)
|
||||
@@ -237,7 +255,7 @@ def disc_permitted(point, radius, segments, no_go):
|
||||
Conservative at junctions: no claim that separately safe corners imply a
|
||||
safe body inside a non-convex union. No-go rectangles have independent veto.
|
||||
"""
|
||||
if not any(
|
||||
if not any(s.get("guidance_only") is True for s in segments) and not any(
|
||||
projection(point, s["start_xy"], s["end_xy"])[1] + radius <= s["half_width_m"]
|
||||
for s in segments
|
||||
):
|
||||
@@ -261,7 +279,7 @@ def discs_permitted(points, radius, segments, no_go):
|
||||
points = np.asarray(points, dtype=float).reshape(-1, 2)
|
||||
if not np.isfinite(points).all() or not math.isfinite(radius) or radius < 0:
|
||||
raise ValueError("Invalid corridor goal candidates")
|
||||
allowed = np.zeros(len(points), dtype=bool)
|
||||
allowed = np.full(len(points), any(s.get("guidance_only") is True for s in segments), dtype=bool)
|
||||
for segment in segments:
|
||||
start, end = np.asarray(segment["start_xy"]), np.asarray(segment["end_xy"])
|
||||
delta = end - start
|
||||
@@ -275,3 +293,46 @@ def discs_permitted(points, radius, segments, no_go):
|
||||
)
|
||||
allowed &= np.linalg.norm(distance, axis=1) > radius
|
||||
return allowed
|
||||
|
||||
|
||||
def simplify_prior_segments(segments):
|
||||
"""Simplify direction intent with RDP, retaining every graph edge identity.
|
||||
|
||||
Grid steps may individually look like corners. Fit the entire chain before
|
||||
splitting long references, so a shallow street does not become alternating
|
||||
straight/45-degree instructions. No simplified chord grants motion support.
|
||||
"""
|
||||
if not segments:
|
||||
return []
|
||||
points = [segments[0]["start_xy"]] + [s["end_xy"] for s in segments]
|
||||
keep = {0, len(points)-1}
|
||||
pending = [(0,len(points)-1)]
|
||||
while pending:
|
||||
a,b = pending.pop()
|
||||
if b-a <= 1:
|
||||
continue
|
||||
distances = [(math.dist(points[i],points[a]) if math.dist(points[a],points[b]) < .05
|
||||
else projection(points[i],points[a],points[b])[1], i)
|
||||
for i in range(a+1,b)]
|
||||
error,index = max(distances)
|
||||
if error > 1.5:
|
||||
keep.add(index)
|
||||
pending.extend(((a,index),(index,b)))
|
||||
corners = sorted(keep)
|
||||
stops = [0]
|
||||
for a,b in zip(corners,corners[1:]):
|
||||
cursor = a
|
||||
while math.dist(points[cursor],points[b]) > 20 and cursor+1 < b:
|
||||
end = cursor+1
|
||||
while end+1 < b and math.dist(points[cursor],points[end+1]) <= 20:
|
||||
end += 1
|
||||
stops.append(end)
|
||||
cursor = end
|
||||
stops.append(b)
|
||||
result = []
|
||||
for a,b in zip(stops,stops[1:]):
|
||||
chain = segments[a:b]
|
||||
result.append({**chain[0], "end_xy": chain[-1]["end_xy"],
|
||||
"half_width_m": min(s["half_width_m"] for s in chain),
|
||||
"guidance_only": True, "edge_ids": [s["edge_id"] for s in chain]})
|
||||
return result
|
||||
|
||||
@@ -75,7 +75,7 @@ class RoutedMission(WaypointMission):
|
||||
)
|
||||
if receipt is None:
|
||||
return None
|
||||
self.unavailable_edges.add(segment["edge_id"])
|
||||
self.unavailable_edges.update(segment.get("edge_ids", [segment["edge_id"]]))
|
||||
event = {
|
||||
"schema_version": "missioncore.route-revision/v1",
|
||||
"revision": self.route_revision + 1,
|
||||
@@ -181,7 +181,8 @@ class RoutedMission(WaypointMission):
|
||||
self.route_failure, self.fault = "outside-route-corridor", "stuck"
|
||||
return
|
||||
along, lateral = projection(pose[:2], segment["start_xy"], segment["end_xy"])
|
||||
self.remaining = max(0.0, self.leg["length_m"] - self.completed_length - along) + lateral
|
||||
self.remaining = max(0.0, self.leg["length_m"] - self.completed_length - along) + lateral * (
|
||||
.15 if segment.get("guidance_only") else 1.)
|
||||
# Supply a stable segment endpoint. The visual/local planner already
|
||||
# chooses observed intermediate goals within its own lookahead. A second
|
||||
# 0.8m target here sits in the camera blind strip and can make it choose
|
||||
@@ -331,9 +332,17 @@ class RoutedMission(WaypointMission):
|
||||
return goal is None
|
||||
|
||||
def retire_local_goal(self, target, *, failed=False):
|
||||
# Recovery belongs to the current corner/return anchor. Comparing with
|
||||
# the final task goal discarded a valid corner goal on every retry.
|
||||
super().retire_local_goal(self.route_target, failed=failed)
|
||||
segments = self.leg["segments"]
|
||||
advisory_joint = (
|
||||
self.segment_index < len(segments) - 1
|
||||
and segments[self.segment_index].get("guidance_only")
|
||||
and not segments[self.segment_index].get("return_to_anchor")
|
||||
)
|
||||
# A route hint is not a required body destination. In particular, a
|
||||
# native planner abort must retire a measured goal near that hint;
|
||||
# preserving it as task-arrival evidence pins the rover to a blocked
|
||||
# intermediate point. Explicit goals and return anchors retain it.
|
||||
super().retire_local_goal(None if advisory_joint else self.route_target, failed=failed)
|
||||
|
||||
def arrival_candidate(self, pose):
|
||||
return (
|
||||
@@ -414,6 +423,12 @@ class RoutedMission(WaypointMission):
|
||||
):
|
||||
return None
|
||||
adjacent = segments[self.segment_index : self.segment_index + 2]
|
||||
if adjacent[0].get("guidance_only"):
|
||||
along, lateral = projection(pose[:2], adjacent[0]["start_xy"], adjacent[0]["end_xy"])
|
||||
length = math.dist(adjacent[0]["start_xy"], adjacent[0]["end_xy"])
|
||||
# A soft line must not allow instant graph progress at a distance.
|
||||
if length - along > 1.5 or lateral > max(2., adjacent[0]["half_width_m"]):
|
||||
return None
|
||||
directions = [np.asarray(s["end_xy"]) - s["start_xy"] for s in adjacent]
|
||||
# A reversal is a visit and return, not a corner that can be cut.
|
||||
if np.dot(*directions) <= -0.95 * np.linalg.norm(directions[0]) * np.linalg.norm(
|
||||
|
||||
@@ -0,0 +1,170 @@
|
||||
"""Content-bound route preparation; providers supply intent, never live support."""
|
||||
import copy
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
import threading
|
||||
from pathlib import Path
|
||||
|
||||
from .run_inputs import digest, robot_geometry
|
||||
from .route_graph import validate_routing, build_route
|
||||
|
||||
PROVIDER = "scene-ground-envelope/v1"
|
||||
SCHEMA = "missioncore.prepared-route/v1"
|
||||
KEY = re.compile(r"^[a-f0-9]{64}$")
|
||||
|
||||
|
||||
def provider_identity():
|
||||
root = Path(__file__).resolve().parents[4]
|
||||
paths = [root / "simulation/ai-polygon/scene_route_field.py",
|
||||
root / "simulation/ai-polygon/route_preparer.py",
|
||||
Path(__file__).with_name("route_graph.py"), Path(__file__)]
|
||||
return digest({p.name: hashlib.sha256(p.read_bytes()).hexdigest() for p in paths})
|
||||
|
||||
|
||||
def preparation_identity(world, robot, points):
|
||||
return dict(schema_version=SCHEMA, provider=PROVIDER, provider_sha256=provider_identity(),
|
||||
world_sha256=world["sha256"], collider_sha256=world.get("collider_sha256"),
|
||||
settings=world["settings"], robot_sha256=robot["sha256"],
|
||||
geometry=robot_geometry(robot), points=points)
|
||||
|
||||
|
||||
def validate_prepared(result, identity):
|
||||
if (not isinstance(result, dict) or result.get("schema_version") != SCHEMA
|
||||
or result.get("identity") != identity
|
||||
or result.get("sha256") != digest({k:v for k,v in result.items() if k != "sha256"})):
|
||||
raise ValueError("Подготовленный маршрут не соответствует заданию.")
|
||||
positions = [p["position"] for p in identity["points"]]
|
||||
routing = validate_routing(result["routing"], identity["world_sha256"], [p[:2] for p in positions[1:]])
|
||||
graph = routing["map"]
|
||||
if (graph.get("source") != {"provider": identity["provider"],
|
||||
"provider_sha256": identity["provider_sha256"],
|
||||
"collider_sha256": identity["collider_sha256"]}
|
||||
or graph.get("corridor_policy") != "advisory"
|
||||
or next(n["xy"] for n in graph["nodes"] if n["id"] == routing["start_node"]) != positions[0][:2]):
|
||||
raise ValueError("Источник или начало маршрута изменились.")
|
||||
preview = result.get("preview_xyz")
|
||||
if not isinstance(preview, list) or not 2 <= len(preview) <= 4096:
|
||||
raise ValueError("Нет траектории для просмотра.")
|
||||
import math
|
||||
if any(not isinstance(p,list) or len(p)!=3 or any(type(v) not in (int,float) or not math.isfinite(v) or abs(v)>1e7 for v in p) for p in preview):
|
||||
raise ValueError("Некорректная траектория.")
|
||||
if preview[0] != positions[0] or preview[-1] != positions[-1]:
|
||||
raise ValueError("Траектория не замыкает заданные точки.")
|
||||
route = build_route(dict(routing=routing, robot={"geometry":identity["geometry"]},
|
||||
mission={"route_xy":[p[:2] for p in positions[1:]]},sha256=digest(identity)))
|
||||
if any(leg["status"] != "ready" for leg in route["legs"]):
|
||||
raise ValueError("Маршрут не соединяет все точки задания.")
|
||||
heights={tuple(n["xy"]):n["z"] for n in graph["nodes"]}
|
||||
expected=[positions[0]]
|
||||
for leg in route["legs"]:
|
||||
expected.extend([*s["end_xy"],heights[tuple(s["end_xy"])]] for s in leg["segments"])
|
||||
if preview != expected or not math.isclose(result.get("length_m",-1),
|
||||
sum(l["length_m"] for l in route["legs"]),abs_tol=1e-6):
|
||||
raise ValueError("Предпросмотр не соответствует исполняемому маршруту.")
|
||||
return copy.deepcopy(result)
|
||||
|
||||
|
||||
def write_json(path, row):
|
||||
# The preparation contract is imported by the lean Worker. Core storage
|
||||
# dependencies must not be pulled into its scientific Python runtime.
|
||||
from .worlds import write_json as persist
|
||||
persist(path, row)
|
||||
|
||||
|
||||
class RoutePreparationStore:
|
||||
def __init__(self, data_dir):
|
||||
self.root = Path(data_dir) / "ai-polygon/route-preparations"
|
||||
self.root.mkdir(parents=True, exist_ok=True, mode=0o700)
|
||||
self.lock = threading.RLock()
|
||||
|
||||
def path(self, key):
|
||||
if not KEY.fullmatch(key):
|
||||
raise FileNotFoundError(key)
|
||||
path = self.root / (key + ".json")
|
||||
if path.is_symlink():
|
||||
raise ValueError("Invalid route preparation file")
|
||||
return path
|
||||
|
||||
def get(self, key):
|
||||
with self.lock:
|
||||
row = json.loads(self.path(key).read_text())
|
||||
if row["key"] != key or digest(row["identity"]) != key:
|
||||
raise ValueError("Route preparation identity changed")
|
||||
if row["status"] == "ready":
|
||||
validate_prepared(row["result"], row["identity"])
|
||||
return row
|
||||
|
||||
def request(self, world, robot, points):
|
||||
with self.lock:
|
||||
if not world.get("local_scene"):
|
||||
raise ValueError("Для подготовки маршрута нужна локальная геометрия сцены.")
|
||||
# Reuse the task's existing point validation without publishing a task.
|
||||
if not 2 <= len(points) <= 33 or len({p["id"] for p in points}) != len(points):
|
||||
raise ValueError("Нужны разные старт и финиш.")
|
||||
import math
|
||||
positions = [p["position"] for p in points]
|
||||
if any(len(p)!=3 or any(not math.isfinite(v) or abs(v)>10000 for v in p) for p in positions):
|
||||
raise ValueError("Некорректная точка маршрута.")
|
||||
if any(math.dist(a[:2],b[:2])<.15 for a,b in zip(positions,positions[1:])):
|
||||
raise ValueError("Соседние точки должны быть дальше 15 см.")
|
||||
identity = preparation_identity(world, robot, points)
|
||||
key = digest(identity)
|
||||
path = self.path(key)
|
||||
if path.exists():
|
||||
row = self.get(key)
|
||||
if row["status"] != "failed":
|
||||
return row
|
||||
row = dict(key=key, identity=identity, world=world, robot=robot,
|
||||
status="queued", error=None, result=None, owner=None)
|
||||
write_json(path,row)
|
||||
return row
|
||||
|
||||
def pending(self):
|
||||
with self.lock:
|
||||
for path in sorted(self.root.glob("*.json")):
|
||||
row = json.loads(path.read_text())
|
||||
if row["status"] in {"queued", "preparing"}:
|
||||
return self.get(path.stem)
|
||||
return None
|
||||
|
||||
def claim(self, key, owner):
|
||||
with self.lock:
|
||||
row = self.get(key)
|
||||
if row["owner"] not in (None, owner):
|
||||
raise RuntimeError("Route preparation belongs to another Worker session")
|
||||
if row["status"] in {"queued", "preparing"}:
|
||||
row.update(status="preparing",owner=owner)
|
||||
write_json(self.path(key),row)
|
||||
return row
|
||||
|
||||
def update(self, key, body, owner):
|
||||
with self.lock:
|
||||
row = self.get(key)
|
||||
if row["owner"] != owner:
|
||||
raise RuntimeError("Route preparation owner changed")
|
||||
action = body.get("action")
|
||||
if action == "complete":
|
||||
result = validate_prepared(body.get("result"), row["identity"])
|
||||
if row["status"] == "ready":
|
||||
if row["result"] != result:
|
||||
raise ValueError("Route preparation already sealed")
|
||||
return row
|
||||
if row["status"] != "preparing":
|
||||
raise RuntimeError("Route preparation is not running")
|
||||
row.update(status="ready",result=result,error=None)
|
||||
elif action == "fail" and row["status"] != "ready":
|
||||
row.update(status="failed",error="По данным сцены маршрут построить не удалось. Проверьте точки и доступную поверхность.")
|
||||
elif action == "release":
|
||||
if row["status"] == "preparing":
|
||||
row.update(status="failed",error="Подготовка маршрута прервана. Повторите планирование.")
|
||||
else:
|
||||
raise ValueError("Unknown route preparation action")
|
||||
write_json(self.path(key),row)
|
||||
return row
|
||||
|
||||
def for_plan(self, key, world, robot, points):
|
||||
row = self.get(key)
|
||||
if row["status"] != "ready":
|
||||
raise ValueError("Сначала спланируйте маршрут.")
|
||||
return validate_prepared(row["result"],preparation_identity(world,robot,points))
|
||||
@@ -356,6 +356,21 @@ class RunStore:
|
||||
CONTINUOUS_SENSOR_SCHEMA)),
|
||||
continuous=CONTINUOUS_SENSOR_SCHEMA in versions,
|
||||
)
|
||||
if plan and plan.get("prepared_route"):
|
||||
from .route_preparation import validate_prepared, preparation_identity
|
||||
from .run_inputs import declared_route_inputs
|
||||
# Admission uses the unmodified world/profile, before speed/mass
|
||||
# settings alter execution. The prior grants no motion authority.
|
||||
original_world = self.worlds.get(request.world_id)
|
||||
prepared = validate_prepared(plan["prepared_route"],
|
||||
preparation_identity(original_world, robot, plan["points"]))
|
||||
if self.worker.get("route_provider_sha256") != prepared["identity"]["provider_sha256"]:
|
||||
raise ValueError("Worker не поддерживает подготовленный маршрут.")
|
||||
row["execution_inputs"] = declared_route_inputs(
|
||||
row["execution_inputs"], prepared["routing"], effective_robot, world["sha256"])
|
||||
# One map payload per immutable run; the plan identity still binds
|
||||
# the complete saved task, while this is its execution projection.
|
||||
row["plan"] = {**plan, "prepared_route": {k:v for k,v in prepared.items() if k != "routing"}}
|
||||
self._publish(row)
|
||||
try:
|
||||
self.queue.reserve_simulation(run_id)
|
||||
|
||||
@@ -30,6 +30,8 @@ from k1link.simulation.ai_polygon.contracts import (
|
||||
WorldSettings,
|
||||
)
|
||||
from k1link.simulation.ai_polygon.editor_cache import EditorCache
|
||||
from k1link.simulation.ai_polygon.route_preparation import RoutePreparationStore, provider_identity
|
||||
from k1link.web.route_preparation_api import build_route_preparation_router, public_plan, public_run
|
||||
from k1link.simulation.ai_polygon.robots import robot_catalog, select_robot
|
||||
from k1link.simulation.ai_polygon.runs import RunStore
|
||||
from k1link.simulation.ai_polygon.worlds import CHUNK_BYTES, SOURCES, WorldStore
|
||||
@@ -41,6 +43,7 @@ def build_ai_polygon_router(
|
||||
worlds = WorldStore(data_dir)
|
||||
runs = RunStore(worlds, queue)
|
||||
editor = EditorCache(data_dir, worlds)
|
||||
routes = RoutePreparationStore(data_dir)
|
||||
router = APIRouter(prefix="/api/v1/ai-polygon", tags=["ai-polygon"])
|
||||
adapters = Path(__file__).resolve().parents[3] / "simulation/ai-polygon"
|
||||
from k1link.web.ai_profile_api import build_ai_profile_router
|
||||
@@ -62,9 +65,12 @@ def build_ai_polygon_router(
|
||||
if not authorization or not secrets.compare_digest(authorization, expected):
|
||||
raise HTTPException(401, "Worker authentication required")
|
||||
|
||||
router.include_router(build_route_preparation_router(routes, worlds, editor, runs, invoke, authenticate))
|
||||
|
||||
@router.get("/catalog")
|
||||
def catalog():
|
||||
runtime = runs.status()
|
||||
runtime = {**runtime, "active_run": public_run(runtime.get("active_run"))}
|
||||
locations = worlds.list()
|
||||
if "project-sog" not in (runtime.get("worker") or {}).get("scene_formats", []):
|
||||
locations = [
|
||||
@@ -83,8 +89,8 @@ def build_ai_polygon_router(
|
||||
"robots": robot_catalog(adapters),
|
||||
"worlds": locations,
|
||||
"runtime": runtime,
|
||||
"runs": runs.library.visible(runs.list(), "run_id")[:30],
|
||||
"plans": runs.plans.visible_list(),
|
||||
"runs": [public_run(r) for r in runs.library.visible(runs.list(), "run_id")[:30]],
|
||||
"plans": [public_plan(p) for p in runs.plans.visible_list()],
|
||||
}
|
||||
|
||||
@router.get("/worker/worlds/{world_id}/project-assets")
|
||||
@@ -169,16 +175,19 @@ def build_ai_polygon_router(
|
||||
if cached["status"] != "ready" or editor.identity(world) != cached["identity"]:
|
||||
raise HTTPException(409, "Локация изменилась. Откройте планирование заново.")
|
||||
robot = invoke(select_robot, body.robot_id, body.robot_sha256)
|
||||
prepared = invoke(routes.for_plan, body.route_preparation_key, world, robot,
|
||||
[p.model_dump(mode="json") for p in body.points]) if body.route_preparation_key else None
|
||||
context = {"world": world, "robot": robot, "run_id": None}
|
||||
return invoke(
|
||||
lambda: runs.plans.create(
|
||||
context,
|
||||
body.name,
|
||||
[p.model_dump() for p in body.points],
|
||||
[p.model_dump(mode="json") for p in body.points],
|
||||
body.sequence,
|
||||
draft_id=body.draft_id,
|
||||
cache_key=body.cache_key,
|
||||
editor_collider_sha256=cached["files"]["collision.glb"]["sha256"],
|
||||
prepared_route=prepared,
|
||||
)
|
||||
)
|
||||
|
||||
@@ -192,8 +201,8 @@ def build_ai_polygon_router(
|
||||
|
||||
@router.post("/runs", status_code=201)
|
||||
def start(body: RunCreate, idempotency_key: str = Header(alias="Idempotency-Key")):
|
||||
if editor.pending():
|
||||
raise HTTPException(409, "Дождитесь загрузки локальной сцены.")
|
||||
if editor.pending() or routes.pending():
|
||||
raise HTTPException(409, "Дождитесь подготовки сцены и маршрута.")
|
||||
if body.clock == "realtime":
|
||||
graph = invoke(compose, adapters, body.composition)
|
||||
body = body.model_copy(update={"composition": graph.selection_document()})
|
||||
@@ -306,6 +315,16 @@ def build_ai_polygon_router(
|
||||
except RuntimeError:
|
||||
return value
|
||||
return {"action": "editor-cache", "cache": pending}
|
||||
if value["action"] == "idle" and runs.queue is not None:
|
||||
pending = routes.pending()
|
||||
worker = runs.status().get("worker") or {}
|
||||
if pending and worker.get("route_provider_sha256") == provider_identity():
|
||||
try:
|
||||
runs.queue.reserve_simulation("aicache-" + pending["key"])
|
||||
claimed = routes.claim(pending["key"],body.instance_id)
|
||||
except RuntimeError:
|
||||
return value
|
||||
return {"action": "route-preparation", "preparation": claimed}
|
||||
return value
|
||||
|
||||
@router.post("/worker/editor-cache/{key}")
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
"""Existing simulation planning surface's bounded asynchronous route port."""
|
||||
import json
|
||||
from fastapi import APIRouter, Header, HTTPException, Request
|
||||
|
||||
from k1link.simulation.ai_polygon.contracts import RoutePrepare
|
||||
from k1link.simulation.ai_polygon.robots import select_robot
|
||||
from k1link.simulation.ai_polygon.route_preparation import provider_identity
|
||||
|
||||
|
||||
def public_plan(plan):
|
||||
if not plan or not plan.get('prepared_route'):
|
||||
return plan
|
||||
return {**plan,'prepared_route':{k:v for k,v in plan['prepared_route'].items() if k!='routing'}}
|
||||
|
||||
|
||||
def public_run(run):
|
||||
if not run or not (run.get('plan') or {}).get('prepared_route'):
|
||||
return run
|
||||
return {**run,'plan':public_plan(run['plan']),
|
||||
'execution_inputs':{k:v for k,v in run.get('execution_inputs',{}).items() if k!='routing'}}
|
||||
|
||||
|
||||
def public_preparation(row):
|
||||
return {k:v for k,v in row.items() if k not in ('world','robot','owner','result')} | {
|
||||
'result': {k:v for k,v in row['result'].items() if k!='routing'} if row.get('result') else None}
|
||||
|
||||
|
||||
def build_route_preparation_router(store, worlds, editor, runs, invoke, authenticate):
|
||||
router=APIRouter()
|
||||
|
||||
@router.post('/route-preparations',status_code=201)
|
||||
def prepare(body:RoutePrepare):
|
||||
with runs.lock:
|
||||
cached=invoke(editor.get,body.cache_key)
|
||||
world=invoke(worlds.get,cached['world']['world_id'])
|
||||
if cached['status']!='ready' or editor.identity(world)!=cached['identity']:
|
||||
raise HTTPException(409,'Локация изменилась. Откройте планирование заново.')
|
||||
worker=runs.status().get('worker') or {}
|
||||
if worker.get('route_provider_sha256')!=provider_identity():
|
||||
raise HTTPException(409,'Подключите Worker с модулем подготовки маршрута.')
|
||||
robot=invoke(select_robot,body.robot_id,body.robot_sha256)
|
||||
row=invoke(store.request,world,robot,[p.model_dump(mode="json") for p in body.points])
|
||||
return public_preparation(row)
|
||||
|
||||
@router.get('/route-preparations/{key}')
|
||||
def status(key:str):
|
||||
return public_preparation(invoke(store.get,key))
|
||||
|
||||
@router.post('/worker/route-preparations/{key}')
|
||||
async def update(key:str,request:Request,authorization:str|None=Header(default=None),
|
||||
instance_id:str=Header(alias='Worker-Instance')):
|
||||
authenticate(authorization)
|
||||
invoke(runs.heartbeat,instance_id)
|
||||
raw=bytearray()
|
||||
async for block in request.stream():
|
||||
raw.extend(block)
|
||||
if len(raw)>4*1024**2:
|
||||
raise HTTPException(413,'Route result exceeds budget')
|
||||
try:
|
||||
body=json.loads(raw)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(400,'Invalid route result') from exc
|
||||
row=invoke(store.update,key,body,instance_id)
|
||||
if body.get('action')=='release' and runs.queue is not None:
|
||||
invoke(runs.queue.release_simulation,'aicache-'+key)
|
||||
return public_preparation(row)
|
||||
|
||||
return router
|
||||
Reference in New Issue
Block a user