diff --git a/simulation/ai-polygon/nav2/check_native_adapter.py b/simulation/ai-polygon/nav2/check_native_adapter.py index 59559c1c..575bace6 100644 --- a/simulation/ai-polygon/nav2/check_native_adapter.py +++ b/simulation/ai-polygon/nav2/check_native_adapter.py @@ -88,7 +88,14 @@ def main(): before = bridge.command_sequence continuous_updates.set() refresh_ms=[] - for _ in range(6): + refresh_goals = [] + for index in range(6): + # Measured local destinations advance inside one route leg. Use + # actual different Smac paths, not six copies of one endpoint. + goal = [3. + .15*index, 1. + .05*(index%2)] + planned, status = bridge.plan(pose, goal, math.atan2(goal[1], goal[0])) + assert planned is not None and len(planned.poses) > 1 + refresh_goals.append(goal) began=time.monotonic() assert bridge.follow(planned, continuing=True) is not None refresh_ms.append((time.monotonic()-began)*1000) @@ -96,7 +103,8 @@ def main(): continuous_updates.clear() assert continuity_samples and all(x is not None for x in continuity_samples) report['uninterrupted_command_samples'] = len(continuity_samples) - report['same_goal_refresh_ms'] = refresh_ms + report['refined_goal_refresh_ms'] = refresh_ms + report['refined_goals'] = refresh_goals with bridge.condition: updates = [row for row in bridge.history if row[0] > before] assert updates and all(row[2:] != (0., 0.) for row in updates), updates diff --git a/simulation/ai-polygon/nav2/ros_navigation.py b/simulation/ai-polygon/nav2/ros_navigation.py index 8f2f5796..b75f246c 100644 --- a/simulation/ai-polygon/nav2/ros_navigation.py +++ b/simulation/ai-polygon/nav2/ros_navigation.py @@ -2,7 +2,8 @@ The caller spins this node and owns observation/command leases. Repeating TF uses the original measurement stamp. FollowPath updates use Nav2's native -preemption; command admission resumes after feedback for the new goal. +preemption within one caller-bound route context. A new motion task requires +fresh action feedback before command admission resumes. """ import math import threading @@ -254,8 +255,8 @@ class RosNavigation(Node): token = object() received = threading.Event() with self.condition: - # Updating geometry for the same goal preserves the native - # command stream. A changed goal still needs new feedback. + # Refining the path within the same caller-bound route context + # preserves its native stream. New tasks need fresh feedback. self.pending_feedback = None if continuing else token if not continuing: self.latest_command = None @@ -280,7 +281,7 @@ class RosNavigation(Node): raise RuntimeError('Nav2 path update rejected') self.action_handle, self.terminal = handle, handle.get_result_async() if continuing: - # This same-goal stream is already admitted during preemption. + # This continuing stream is already admitted during preemption. # Waiting for its feedback only delays the next sensor frame; # accept() still fences rejection and late action acceptance. return self.native_command() diff --git a/simulation/ai-polygon/nav2/server.py b/simulation/ai-polygon/nav2/server.py index 9c195bff..d8109f4b 100644 --- a/simulation/ai-polygon/nav2/server.py +++ b/simulation/ai-polygon/nav2/server.py @@ -45,6 +45,8 @@ class Navigation: self.collision = ObservedCollision(node, self.monitor.max_step, 2) self.plan_lock, self.owner_lock = threading.Lock(), threading.Lock() self.action_key = None + self.command_generation = 0 + self.path_context = None self.completed_orientation = None self.attempted_alignment = None self.path = None @@ -68,20 +70,41 @@ class Navigation: with self.control.lock: plan = self.control.plans.get(self.control.path_id) with self.owner_lock: - if plan is None or plan['result'].get('controller_goal') != self.action_key: + if plan is None or plan['result'].get('controller_generation') != self.command_generation: return None return self.node.native_command() def tick(self, value): self.node.observe_pose(value['pose'], float(value['pose_age_seconds']), value['measured_twist']) with self.owner_lock: - owner = self.action_key + owner = self.command_generation result = self.control.tick(value) with self.owner_lock: - if owner != self.action_key: + if owner != self.command_generation: result.update(speed_mps=0., yaw_rate_rps=0., reason='changed-path') return result + def revoke_command(self): + with self.owner_lock: + self.command_generation += 1 + self.action_key = None + + def stop(self): + self.revoke_command() + self.node.stop() + + @staticmethod + def forward_context(value, orientation): + # Only refinements within the same ordinary route leg may share a + # native command stream. Recovery, an unbound intent, a changed speed + # limit or terminal placement all require a new action/feedback fence. + if (orientation is None or value.get('recovery_orientation', False) + or not value.get('continuous', False)): + return None + target = value.get('arrival_target') + return (orientation['key'], tuple(orientation['xy']), + value['max_speed_mps'], tuple(target) if target is not None else None) + @staticmethod def reply(reason, *, status='waiting-for-plan', **extra): return dict(speed_mps=0., yaw_rate_rps=0., status=status, path=[], @@ -166,9 +189,7 @@ class Navigation: if math.dist(pose[:2], target) <= self.inputs['mission']['arrival_radius_m']: assessment = self.monitor.assess_pose(terrain, pose, value['body_contact_height_m']) if assessment['admitted']: - self.node.stop() - with self.owner_lock: - self.action_key = None + self.stop() return self.reply('arrival', status='arrival-accepted', arrival={**assessment, 'observation':dict(pose=pose.tolist(), target_xy=list(target), simulation_time_seconds=value['simulation_time_seconds'], @@ -209,7 +230,7 @@ class Navigation: and orientation_key != self.completed_orientation and not value['translation_allowed']) if not value['translation_allowed'] and not orienting: - self.node.stop() + self.stop() return self.reply('no-permitted-goal', status='blocked', route_observation=route) if orienting: automatic = aligning or turn is not None @@ -218,8 +239,7 @@ class Navigation: angle = math.atan2(math.sin(heading-yaw_of(pose)), math.cos(heading-yaw_of(pose))) key = alignment_key if automatic else orientation_key if key != self.action_key: - with self.owner_lock: - self.action_key = None + self.revoke_command() # Existing mission budgets use simulation time. Do not invent # a second wall-clock maneuver budget in a slower simulation. # The unchanged command/data leases still gate every output. @@ -236,40 +256,42 @@ class Navigation: heading = yaw_of(pose) rear = -float(delta @ [math.cos(heading), math.sin(heading)]) if rear <= 0: - self.node.stop() + self.stop() return self.reply('reverse-goal-is-not-behind', status='blocked') if key != self.action_key: - with self.owner_lock: - self.action_key = None + self.revoke_command() self.node.backup(rear, min(limit,.1), 0.) local_path = [[0.,0.,0.],[-rear,0.,0.]] else: - # A sensor refresh is not a new motion goal. ROS feedback fences - # a path update; the existing capture leases and raw range gates - # still validate every command against the caller's observation. + # Local endpoint refinements can share one route command stream. + # A different route/recovery context gets a fresh feedback fence; + # every tick still uses its capture leases and raw range gates. key = ('path', tuple(goal[:2]), limit) completed = self.completed_action(key, route) if completed is not None: return completed - continuing = key == self.action_key + context = self.forward_context(value, orientation) + continuing = ((key == self.action_key and context == self.path_context) + or (following and context is not None and context == self.path_context)) # Match the pinned Nav2 BT's 1 Hz ComputePathToPose cadence. # The path is an intent, not a sensor sample: terrain, costmaps, # capture leases and command gates still refresh above/every tick. - if (not continuing or self.path is None or self.node.native_command() is None + if (key != self.action_key or not continuing or self.path is None + or self.node.native_command() is None or entered-self.path_planned_at >= 1.0): path, status = self.node.plan(pose, goal, math.atan2(goal[1]-pose[1],goal[0]-pose[0])) if path is None or len(path.poses) < 2: - self.node.stop() + self.stop() # Humble has no typed planner error code. Preserve its # terminal abort without inventing an obstacle diagnosis. feedback = (dict(planning_result=dict(status='aborted', goal_xy=goal[:2].tolist())) if status == GoalStatus.STATUS_ABORTED else {}) return self.reply('no-path', status='blocked', route_observation=route, **feedback) if not continuing: - with self.owner_lock: - self.action_key = None + self.revoke_command() self.node.follow(path, continuing=continuing) self.path, self.path_planned_at = path, entered + self.path_context = context path = self.path c, s = math.cos(yaw_of(pose)), math.sin(yaw_of(pose)) local_path = [[(p.pose.position.x-pose[0])*c+(p.pose.position.y-pose[1])*s, @@ -286,7 +308,7 @@ class Navigation: return self.reply('native-action-complete' if terminal and terminal.status==GoalStatus.STATUS_SUCCEEDED else 'waiting-for-controller', route_observation=route) result = dict(speed_mps=native[1], yaw_rate_rps=native[2], status='path', path=local_path, - controller_goal=key, + controller_goal=key, controller_generation=self.command_generation, route_observation=route, diagnostic=dict(terrain=observed['metrics'], controller='nav2')) # This is a proposal returned to the mission layer; /control supplies # the separately admitted command bound to current pose/range/intent. @@ -334,6 +356,8 @@ def main(): current_observation_id=observed['observation_id'] if observed else None, current_metrics=observed['metrics'] if observed else None, current_detected=observed['detected'].tolist() if observed else [], + current_collision_terrain=observed['collision_terrain'].tolist() if observed else [], + current_surface_terrain=observed['terrain'].tolist() if observed else [], geometry=observed['physical_terrain'].tolist() if observed else [])) return ready = process.poll() is None and terrain_ready.service_is_ready() and not navigation.failure diff --git a/tests/test_nav2_route_support.py b/tests/test_nav2_route_support.py index 526f1499..eacc56e2 100644 --- a/tests/test_nav2_route_support.py +++ b/tests/test_nav2_route_support.py @@ -31,6 +31,9 @@ def bridge(monkeypatch): navigation.failure = None navigation.active = navigation.activating = True navigation.action_key = navigation.attempted_alignment = None + navigation.command_generation = 0 + navigation.path_context = None + navigation.owner_lock = threading.Lock() 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.)) @@ -134,3 +137,85 @@ def test_goal_clearance_uses_solids_without_waiving_search_or_surface_costs(brid assert result['clearance_observation']['obstacles_xy'] == ([[.8, .2]] if layer == 'physical' else []) assert seen[0][-1, 3] == 1. # Smac keeps the complete search exclusion. assert observed['terrain'][-1, 3] == (0. if layer == 'search' else 1.) + + +@pytest.fixture +def moving_bridge(bridge): + navigation, observed, value = bridge + orientation = dict(key='route-0-1', xy=[20., 0.]) + value = {**value, 'translation_allowed': True, 'continuous': True, + 'orientation_target': orientation, 'recovery_orientation': False, + 'goal': [4., .2, 0.]} + navigation.command_generation = 7 + navigation.action_key = ('path', (3., 0.), 1.) + navigation.path_context = navigation.forward_context(value, orientation) + navigation.path = None + navigation.path_planned_at = float('-inf') + navigation.completed_orientation = None + navigation.node.terminal = Future() + navigation.node.native_command = lambda: (time.monotonic(), .4, .02) + navigation.node.observe_pose = lambda *args: None + planned = [] + def plan(pose, goal, yaw): + planned.append(list(goal)) + return SimpleNamespace(poses=[SimpleNamespace(pose=SimpleNamespace( + position=SimpleNamespace(x=x, y=y))) for x, y in [(0., 0.), goal[:2]]]), 4 + navigation.node.plan = plan + navigation.control.lock = threading.Lock() + navigation.control.path_id = 'old' + navigation.control.plans = {'old': dict(result={'controller_generation': 7})} + navigation.control.accept = lambda *args, **kwargs: None + seen = [] + navigation.node.follow = lambda path, **kwargs: seen.append( + dict(continuing=kwargs['continuing'], command=navigation.native_command())) + observed['metrics'] = {} + globals_ = navigation._plan.__globals__ + globals_.update(validate_orientation=lambda x: x, yaw_of=lambda _: 0., + GoalStatus=SimpleNamespace(STATUS_SUCCEEDED=4, STATUS_ABORTED=6)) + return navigation, value, planned, seen + + +def test_refined_endpoint_keeps_same_route_command_owner_during_actual_plan(moving_bridge): + navigation, value, planned, seen = moving_bridge + # A control tick straddles the goal update, while the old observed plan is + # still held by its caller. It must retain its original live admission. + def tick(_): + result = navigation.plan(value) + assert result['controller_goal'] == ('path', (4., .2), 1.) + assert result['controller_generation'] == 7 + return dict(speed_mps=.4, yaw_rate_rps=.02, reason='none') + navigation.control.tick = tick + result = navigation.tick(dict(pose=value['pose'], pose_age_seconds=0., measured_twist=[.4,0.,0.])) + assert result == dict(speed_mps=.4, yaw_rate_rps=.02, reason='none') + assert planned == [[4., .2, 0.]] # A different goal gets a new native path. + assert seen[0]['continuing'] is True and seen[0]['command'] is not None + + +@pytest.mark.parametrize('change', ['leg', 'direction', 'limit', 'recovery', 'unbound', 'placement', 'discrete']) +def test_task_change_revokes_previous_plan_even_when_followpath_is_live(moving_bridge, change): + navigation, value, _, seen = moving_bridge + if change == 'leg': value['orientation_target'] = dict(key='route-0-2', xy=[20., 0.]) + elif change == 'direction': value['orientation_target'] = dict(key='route-0-1', xy=[20., 4.]) + elif change == 'limit': value['max_speed_mps'] = .3 + elif change == 'recovery': value['recovery_orientation'] = True + elif change == 'unbound': value['orientation_target'] = None + elif change == 'placement': value['arrival_target'] = [20., 0.] + else: value['continuous'] = False + result = navigation.plan(value) + assert result['controller_generation'] == 8 + assert seen == [dict(continuing=False, command=None)] + assert navigation.native_command() is None # Old capture cannot own the new task. + + +def test_planner_rejection_revokes_inflight_command_before_native_stop(moving_bridge): + navigation, value, _, _ = moving_bridge + navigation.node.plan = lambda *args: (None, 6) + seen = [] + navigation.node.stop = lambda: seen.append(navigation.native_command()) + def tick(_): + assert navigation.plan(value)['diagnostic']['failure'] == 'no-path' + return dict(speed_mps=.4, yaw_rate_rps=.02, reason='none') + navigation.control.tick = tick + result = navigation.tick(dict(pose=value['pose'], pose_age_seconds=0., measured_twist=[.4,0.,0.])) + assert result == dict(speed_mps=0., yaw_rate_rps=0., reason='changed-path') + assert seen == [None]