Bind Nav2 route transitions to current observed body support

Return a separate positive-surface body receipt before reaching a guide vertex. Keep mission arrival and command admission independent, reject stale transaction reuse, and include the bridge helper in module identity. Validate the actual Nav2 plan entry with observed, unknown and obstructed support.
This commit is contained in:
DCCONSTRUCTIONS
2026-10-08 23:54:38 +03:00
parent 31b74e4571
commit a14158e483
8 changed files with 128 additions and 4 deletions
+6 -1
View File
@@ -100,7 +100,12 @@ SOG-кэш используется редактором и локальным
`advisory` снимает жёсткое удержание корпуса в капсуле линии. Локальные цели
и объезды по наблюдаемой поверхности разрешены вне неё, явные `no_go`
продолжают действовать. Соседний участок засчитывается только при фактическом
продвижении и текущем положительном whole-body receipt. Финальная точка
продвижении и текущем положительном whole-body receipt. Для Nav2 отдельный
`route_transition_target` запрашивает `route_support`: текущую геометрическую
опору по положительно наблюдённой семантической поверхности. Этот ответ
привязан к pose, времени мира, цели и SHA входов; он не означает прибытие и
не даёт команду движения. Устаревшая транзакция не переносит старый ответ.
Финальная точка
сохраняет отдельное подтверждение прибытия. Локальная цель рядом с промежуточным
advisory-ориентиром после отказа native-планировщика исключается из кандидатов;
она не сохраняется как обязательный финиш. Финальная цель и обязательный
@@ -0,0 +1,24 @@
"""Current observed body support for an intent transition, never a drive goal."""
import math
import numpy as np
def route_support(monitor, observed, value, inputs):
target = value.get("route_transition_target")
if target is None:
return None
pose = np.asarray(value["pose"], dtype=float)
target = np.asarray(target, dtype=float)
if (target.shape != (2,) or not np.isfinite(target).all()
or math.dist(pose[:2], target) > 3.5
or value["execution_inputs_sha256"] != inputs["sha256"]):
raise ValueError("Invalid route transition observation")
support = observed["permitted_terrain"]
receipt = monitor.assess_pose(observed["terrain"], pose,
value["body_contact_height_m"], support_terrain=support)
return {**receipt, "positive_surface_required": True,
"authority": "current-body; intent-transition-only",
"observation": dict(pose=pose.tolist(), target_xy=target.tolist(),
simulation_time_seconds=value["simulation_time_seconds"],
execution_inputs_sha256=inputs["sha256"])}
+10
View File
@@ -27,6 +27,7 @@ from navigation.route_observation import route_observation
from navigation.support_policy import SupportPolicy
from observed_collision import ObservedCollision
from rig_collision import collision_geometry
from route_support import route_support
from ros_navigation import RosNavigation, yaw_of
from std_srvs.srv import Trigger
from terrain_process import TerrainProcess
@@ -98,6 +99,12 @@ class Navigation:
return None
def plan(self, value):
# Transaction-local metadata cannot survive a stale/failed observation.
receipts = {}
result = self._plan(value, receipts)
return {**result, **receipts}
def _plan(self, value, receipts):
entered = time.monotonic()
if self.failure:
raise RuntimeError(self.failure)
@@ -130,6 +137,9 @@ class Navigation:
detected=observed['detected']):
return self.reply('stale-range')
route = route_observation(terrain, pose, value, self.monitor.max_step)
support = route_support(self.monitor, observed, value, self.inputs)
if support is not None:
receipts["route_support"] = support
orientation = validate_orientation(value.get('orientation_target'))
target = value.get('arrival_target')
if target is not None:
@@ -133,6 +133,8 @@ class TerrainObservation:
points, forbidden = self.semantics.apply(points, time.monotonic())
search, _ = self.support_obstacles.apply(points, pose=pose, monitor=self.monitor)
return dict(terrain=points, search_terrain=search, physical_terrain=physical, detected=detected,
permitted_terrain=(self.semantics.permitted_terrain(points, time.monotonic())
if request.get("route_transition_target") is not None else None),
current_points=current,
metrics=dict(detection_candidates=len(candidates),
detection_ground_returns=len(candidates)-len(detected),
+4 -1
View File
@@ -831,6 +831,8 @@ class ComposedInference:
"arrival_target": arrival_target
if arrival_candidate or body_goal_query
else None,
"route_transition_target": arrival_target
if nearby and isinstance(self.mission, RoutedMission) else None,
"max_speed_mps": min(self.max_speed, 0.1)
if intent["state"] == "reversing" or intent.get("corner_approach")
else min(self.max_speed, inputs.get("source.crossing-admission", {}).get("speed_limit_mps") or self.max_speed),
@@ -931,7 +933,8 @@ class ComposedInference:
intent = self.mission.intent(self.mission.state)
elif isinstance(self.mission, RoutedMission) and revision is None:
transition = self.mission.confirm_corridor_transition(
pose, inputs["source.simulation-time"], result.get("arrival") or {}
pose, inputs["source.simulation-time"],
result.get("route_support") or result.get("arrival") or {}
)
if transition is not None:
result.update(
@@ -344,7 +344,7 @@ def registry(adapter_root: Path) -> ModuleRegistry:
"detection_obstacles.py", "route_observation.py", "arrival_approach.py", "pcl_ground.py")
runtime = ("configuration.py", "nodes.py", "observed_collision.py", "ros_navigation.py",
"server.py", "terrain_node.py", "terrain_observation.py", "terrain_process.py",
"detector_exclusion.py", "differential_motion.py")
"detector_exclusion.py", "differential_motion.py", "route_support.py")
files = [adapter_root/"nav2"/name for name in runtime]
files += [adapter_root/"navigation"/name for name in shared]
files += [adapter_root/name for name in ("model_stack.py", "navigation_client.py", "rig_collision.py")]
+1 -1
View File
@@ -102,7 +102,7 @@ def test_unknown_future_track_ground_does_not_select_an_incomplete_turn(motion):
assert alignment_angle(pose(),[0.,2.,0.],hole,[],monitor,.37) is None
@pytest.mark.parametrize('helper',['detector_exclusion.py','differential_motion.py'])
@pytest.mark.parametrize('helper',['detector_exclusion.py','differential_motion.py','route_support.py'])
def test_native_module_identity_includes_behavior_helpers(monkeypatch,helper):
from k1link.simulation.ai_polygon.composition import registry
+80
View File
@@ -0,0 +1,80 @@
"""Real Nav2 plan entry returns bound current support without declaring arrival."""
import ast
import copy
import math
from pathlib import Path
from types import SimpleNamespace
import time
import numpy as np
import pytest
@pytest.fixture
def bridge(monkeypatch):
root = Path(__file__).parents[1] / 'simulation/ai-polygon'
monkeypatch.syspath_prepend(str(root))
monkeypatch.syspath_prepend(str(root / 'nav2'))
from navigation.footprint import Footprint
from navigation.route_observation import route_observation
from route_support import route_support
# Load the actual adapter class without unavailable ROS imports on the Mac.
tree = ast.parse((root / 'nav2/server.py').read_text())
cls = next(n for n in tree.body if isinstance(n, ast.ClassDef) and n.name == 'Navigation')
scope = dict(np=np, math=math, time=time, route_support=route_support,
route_observation=route_observation, validate_orientation=lambda _: None,
alignment_angle=lambda *args: None)
exec(compile(ast.Module(body=[cls], type_ignores=[]), str(root / 'nav2/server.py'), 'exec'), scope)
navigation = scope['Navigation'].__new__(scope['Navigation'])
navigation.failure = None
navigation.active = navigation.activating = True
navigation.action_key = navigation.attempted_alignment = None
navigation.inputs = dict(sha256='a'*64, behavior={'max_speed_mps': 1.},
mission={'arrival_radius_m': .4})
navigation.monitor = Footprint(dict(length_m=1., width_m=.6, max_step_m=.1, max_slope_degrees=25.))
navigation.node = SimpleNamespace(pose=(time.monotonic(), None, [0., 0., 0.]), stop=lambda: None)
navigation.control = SimpleNamespace(observe=lambda _: None)
navigation.collision = SimpleNamespace(publish=lambda *args, **kwargs: True)
floor = np.array([[x, y, 0., 0.] for x in np.arange(-2, 2.01, .05)
for y in np.arange(-2, 2.01, .05)])
observed = dict(terrain=floor, permitted_terrain=floor, search_terrain=floor,
detected=np.empty((0, 3)))
navigation.terrain = SimpleNamespace(observe=lambda _: observed)
value = dict(pose=[0., 0., .37, 0., 0., 0., 1.], goal=[1., 0., 0.],
geometry_age_seconds=0., detection_age_seconds=0., max_speed_mps=1.,
allow_reverse=False, translation_allowed=False, observation_id='sample-1',
route_transition_target=[1., 0.], arrival_target=None,
body_contact_height_m=.37, simulation_time_seconds=4.,
execution_inputs_sha256='a'*64)
return navigation, observed, value
@pytest.mark.parametrize('condition', ['permitted', 'unknown', 'obstacle'])
def test_support_is_current_and_positive_but_does_not_grant_a_path_or_arrival(bridge, condition):
navigation, observed, value = bridge
if condition == 'unknown':
observed['permitted_terrain'] = np.empty((0, 4))
if condition == 'obstacle':
observed['terrain'] = np.vstack((observed['terrain'], [[.3, 0., .4, 1.]]))
result = navigation.plan(value)
receipt = result['route_support']
assert receipt['admitted'] is (condition == 'permitted')
assert receipt['positive_surface_required'] is True
assert receipt['observation'] == dict(pose=value['pose'], target_xy=[1., 0.],
simulation_time_seconds=4., execution_inputs_sha256='a'*64)
assert result['status'] == 'blocked' and 'arrival' not in result
assert result['speed_mps'] == result['yaw_rate_rps'] == 0.
# A stale or unrelated next request must not inherit the previous receipt.
stale = copy.deepcopy(value)
stale['geometry_age_seconds'] = .9
assert 'route_support' not in navigation.plan(stale)
unrelated = copy.deepcopy(value)
unrelated.pop('route_transition_target')
assert 'route_support' not in navigation.plan(unrelated)
def test_route_support_rejects_remote_or_wrongly_bound_target(bridge):
navigation, _, value = bridge
for change in ({'route_transition_target': [4., 0.]}, {'execution_inputs_sha256': 'b'*64}):
with pytest.raises(ValueError, match='transition observation'):
navigation.plan({**value, **change})