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:
DCCONSTRUCTIONS
2026-10-08 23:42:26 +03:00
parent 2e85d95c71
commit 31b74e4571
34 changed files with 1451 additions and 83 deletions
@@ -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
+72 -11
View File
@@ -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))
+15
View File
@@ -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)