Skip to content

moveit_servo: future-stamped commands remain active past incoming_command_timeout #4033

Backlog

Description

@Tnikko

Description

In a cross-machine teleoperation setup, a controller PC can see command stamps from an operator station ahead of its clock after NTP/PTP adjustment. A command five seconds in the future remains active after the publisher stops, allowing Servo to keep emitting moving trajectories beyond incoming_command_timeout: 0.1 s.

Proposed fix options

The main and jazzy command age checks only reject ages greater than the timeout; future stamps have negative ages. One option is to clamp stamps beyond a documented forward tolerance to receipt time and issue a throttled warning. Another is a bounded positive skew allowance, rejecting offsets above the bound. A blanket age < 0 rejection would also discard normal millisecond scheduling skew.

ROS Distro

Jazzy

OS and version

Ubuntu 24.04.5 LTS

Source or binary build?

Binary

If binary, which release version?

ros-jazzy-moveit-servo 2.12.4-1noble.20261105.184638

If source, which branch?

N/A (binary build). Source comparison: jazzy@daf89d30 (moveit_ros/moveit_servo/src/servo_node.cpp#L227-L298)

Which RMW are you using?

CycloneDDS

Steps to Reproduce

source /opt/ros/jazzy/setup.bash
python3 repro_moveit_servo_future_stamp.py --mode twist --stamp future
python3 repro_moveit_servo_future_stamp.py --mode twist --stamp now

The script starts Servo with Panda and mock hardware, streams geometry_msgs/msg/TwistStamped on ~/delta_twist_cmds for 0.6 s, stops input, reads the live Servo timeout, and records /panda_arm_controller/joint_trajectory and /joint_states. --mode joint_jog and --mode pose expose the other public command inputs.

Standalone reproduction script: repro_moveit_servo_future_stamp.py
#!/usr/bin/env python3
"""Standalone MoveIt Servo future-header watchdog reproduction for ROS 2 Jazzy."""

import argparse
import json
import math
import os
from pathlib import Path
import signal
import subprocess
import tempfile
import threading
import time

import rclpy
from controller_manager_msgs.srv import ListControllers
from control_msgs.msg import JointJog
from geometry_msgs.msg import PoseStamped, TwistStamped
from moveit_msgs.msg import ServoStatus
from moveit_msgs.srv import ServoCommandType
from rcl_interfaces.srv import GetParameters
from rclpy.duration import Duration
from rclpy.executors import SingleThreadedExecutor
from rclpy.node import Node
from sensor_msgs.msg import JointState
from tf2_ros import Buffer, TransformListener
from rclpy.time import Time
from trajectory_msgs.msg import JointTrajectory


LAUNCH_TEXT = '''
import launch
import launch_ros
from launch_ros.actions import Node, ComposableNodeContainer
from launch_ros.descriptions import ComposableNode
from launch_param_builder import ParameterBuilder
from moveit_configs_utils import MoveItConfigsBuilder
from ament_index_python.packages import get_package_share_directory
import os

def generate_launch_description():
    controller_file = os.path.join(
        get_package_share_directory("moveit_resources_panda_moveit_config"),
        "config", "ros2_controllers.yaml")
    cfg = (MoveItConfigsBuilder("moveit_resources_panda")
           .robot_description(file_path="config/panda.urdf.xacro")
           .joint_limits(file_path="config/hard_joint_limits.yaml")
           .robot_description_kinematics().to_moveit_configs())
    servo_params = {"moveit_servo":
                    ParameterBuilder("moveit_servo")
                    .yaml("config/panda_simulated_config.yaml").to_dict()}
    return launch.LaunchDescription([
        Node(package="controller_manager", executable="ros2_control_node",
             parameters=[controller_file],
             remappings=[("/controller_manager/robot_description",
                          "/robot_description")], output="screen"),
        Node(package="controller_manager", executable="spawner",
             arguments=["joint_state_broadcaster", "-c", "/controller_manager"],
             output="screen"),
        Node(package="controller_manager", executable="spawner",
             arguments=["panda_arm_controller", "-c", "/controller_manager"],
             output="screen"),
        ComposableNodeContainer(
            name="panda_servo_container", namespace="/", package="rclcpp_components",
            executable="component_container_mt", output="screen",
            composable_node_descriptions=[
                ComposableNode(package="robot_state_publisher",
                               plugin="robot_state_publisher::RobotStatePublisher",
                               name="robot_state_publisher",
                               parameters=[cfg.robot_description]),
                ComposableNode(package="tf2_ros",
                               plugin="tf2_ros::StaticTransformBroadcasterNode",
                               name="static_tf2_broadcaster",
                               parameters=[{"child_frame_id": "/panda_link0",
                                            "frame_id": "/world"}]),
            ]),
        Node(package="moveit_servo", executable="servo_node", name="servo_node",
             parameters=[servo_params, {"update_period": 0.01},
                         {"planning_group_name": "panda_arm"},
                         cfg.robot_description, cfg.robot_description_semantic,
                         cfg.robot_description_kinematics, cfg.joint_limits],
             output="screen"),
    ])
'''


def wait_until(predicate, seconds):
    end = time.monotonic() + seconds
    while time.monotonic() < end:
        if predicate():
            return True
        time.sleep(0.04)
    return predicate()


def service(node, type_, name, request):
    client = node.create_client(type_, name)
    if not client.wait_for_service(timeout_sec=20):
        raise RuntimeError("missing service " + name)
    future = client.call_async(request)
    if not wait_until(future.done, 20):
        raise RuntimeError("service timed out " + name)
    return future.result()


def ee_pose(node):
    buffer = Buffer()
    listener = TransformListener(buffer, node)
    transform = None
    end = time.monotonic() + 10
    while time.monotonic() < end:
        try:
            transform = buffer.lookup_transform("panda_link0", "panda_link8", Time())
            break
        except Exception:
            time.sleep(0.05)
    if transform is None:
        raise RuntimeError("panda_link8 transform missing")
    p = transform.transform.translation
    q = transform.transform.rotation
    return (p.x, p.y, p.z), (q.x, q.y, q.z, q.w)


def quat_mul(a, b):
    x1, y1, z1, w1 = a
    x2, y2, z2, w2 = b
    return (w1*x2 + x1*w2 + y1*z2 - z1*y2,
            w1*y2 - x1*z2 + y1*w2 + z1*x2,
            w1*z2 + x1*y2 - y1*x2 + z1*w2,
            w1*w2 - x1*x2 - y1*y2 - z1*z2)


def run(mode, stamp):
    result = {"mode": mode, "stamp": stamp, "status": [], "joint_states": [],
              "trajectories": [], "error": None}
    with tempfile.TemporaryDirectory() as folder:
        launch_file = Path(folder) / "panda_servo.launch.py"
        launch_file.write_text(LAUNCH_TEXT)
        log = tempfile.TemporaryFile(mode="w+")
        proc = subprocess.Popen(["ros2", "launch", str(launch_file)],
                                stdout=log, stderr=subprocess.STDOUT, preexec_fn=os.setsid)
        rclpy.init()
        node = Node("servo_repro_node")
        joints = [f"panda_joint{i}" for i in range(1, 8)]

        def on_joint(msg):
            if all(name in msg.name for name in joints):
                result["joint_states"].append({
                    "t_ns": time.monotonic_ns(),
                    "q": [float(msg.position[msg.name.index(name)]) for name in joints]})

        def on_trajectory(msg):
            result["trajectories"].append({
                "t_ns": time.monotonic_ns(),
                "first_velocity": max((abs(v) for v in msg.points[0].velocities),
                                      default=0.0) if msg.points else 0.0})

        node.create_subscription(JointState, "/joint_states", on_joint, 1000)
        node.create_subscription(JointTrajectory,
                                 "/panda_arm_controller/joint_trajectory", on_trajectory, 1000)
        node.create_subscription(ServoStatus, "/servo_node/status",
                                 lambda msg: result["status"].append({
                                     "t_ns": time.monotonic_ns(), "code": int(msg.code)}), 1000)
        pub = {
            "twist": node.create_publisher(TwistStamped, "/servo_node/delta_twist_cmds", 50),
            "joint_jog": node.create_publisher(JointJog, "/servo_node/delta_joint_cmds", 50),
            "pose": node.create_publisher(PoseStamped, "/servo_node/pose_target_cmds", 50),
        }[mode]
        executor = SingleThreadedExecutor()
        executor.add_node(node)
        worker = threading.Thread(target=executor.spin, daemon=True)
        worker.start()
        try:
            controller = node.create_client(ListControllers,
                                            "/controller_manager/list_controllers")
            def active():
                if not controller.wait_for_service(timeout_sec=0.2):
                    return False
                future = controller.call_async(ListControllers.Request())
                if not wait_until(future.done, 2):
                    return False
                return any(x.name == "panda_arm_controller" and x.state == "active"
                           for x in future.result().controller)
            if not wait_until(lambda: bool(result["joint_states"]) and active(), 100):
                raise RuntimeError("Panda controller or states unavailable")
            params = service(node, GetParameters, "/servo_node/get_parameters",
                             GetParameters.Request(names=[
                                 "moveit_servo.incoming_command_timeout"]))
            timeout_s = params.values[0].double_value
            result["runtime_timeout_s"] = timeout_s
            switch = service(node, ServoCommandType, "/servo_node/switch_command_type",
                             ServoCommandType.Request(
                                 command_type={"joint_jog": 0, "twist": 1, "pose": 2}[mode]))
            if not switch.success:
                raise RuntimeError("Servo mode switch failed")
            if not wait_until(lambda: pub.get_subscription_count() >= 1 and
                              len(result["status"]) >= 10, 25):
                raise RuntimeError("Servo subscriber/control loop unavailable")
            target = None
            if mode == "pose":
                position, q = ee_pose(node)
                angle = 1.9
                target = (position, quat_mul(q, (0, 0, math.sin(angle/2),
                                                 math.cos(angle/2))))
            end = time.monotonic() + 0.6
            while time.monotonic() < end:
                if mode == "twist":
                    msg = TwistStamped()
                    msg.header.frame_id = "panda_link0"
                    msg.twist.linear.x = 0.1
                elif mode == "joint_jog":
                    msg = JointJog()
                    msg.joint_names = ["panda_joint7"]
                    msg.velocities = [0.25]
                else:
                    msg = PoseStamped()
                    msg.header.frame_id = "panda_link0"
                    msg.pose.position.x, msg.pose.position.y, msg.pose.position.z = target[0]
                    (msg.pose.orientation.x, msg.pose.orientation.y,
                     msg.pose.orientation.z, msg.pose.orientation.w) = target[1]
                msg.header.stamp = (node.get_clock().now() +
                                    Duration(seconds=5.0 if stamp == "future" else 0.0)).to_msg()
                pub.publish(msg)
                result["last_command_t_ns"] = time.monotonic_ns()
                time.sleep(0.04)
            time.sleep(2.35)
        except Exception as exc:
            result["error"] = f"{type(exc).__name__}: {exc}"
        finally:
            rclpy.shutdown()
            worker.join(timeout=3)
            node.destroy_node()
            if proc.poll() is None:
                os.killpg(os.getpgid(proc.pid), signal.SIGTERM)
                try:
                    proc.wait(timeout=7)
                except subprocess.TimeoutExpired:
                    os.killpg(os.getpgid(proc.pid), signal.SIGKILL)
                    proc.wait(timeout=3)
            log.seek(0)
            result["log_tail"] = log.read()[-4000:]
            log.close()
    if "last_command_t_ns" in result and "runtime_timeout_s" in result:
        start = result["last_command_t_ns"] + round(
            (result["runtime_timeout_s"] + 0.5) * 1e9)
        end = result["last_command_t_ns"] + round(
            (result["runtime_timeout_s"] + 1.9) * 1e9)
        states = [x for x in result["joint_states"] if start <= x["t_ns"] <= end]
        trajectories = [x for x in result["trajectories"] if start <= x["t_ns"] <= end]
        result["post_timeout_trajectory_frames"] = len(trajectories)
        result["post_timeout_max_joint_displacement_rad"] = (
            max((abs(a-b) for a,b in zip(states[0]["q"], states[-1]["q"])),
                default=0.0) if len(states) >= 2 else None)
        result["post_timeout_status_frames"] = sum(
            start <= x["t_ns"] <= end for x in result["status"])
    result["joint_state_frames"] = len(result["joint_states"])
    result["trajectory_frames"] = len(result["trajectories"])
    result["status_frames"] = len(result["status"])
    del result["joint_states"], result["trajectories"], result["status"]
    return result


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--mode", choices=("twist", "joint_jog", "pose"), required=True)
    parser.add_argument("--stamp", choices=("future", "now"), required=True)
    args = parser.parse_args()
    print(json.dumps(run(args.mode, args.stamp)))

Expected behavior

The command should expire shortly after input stops, allowing small positive clock skew without accepting a multi-second future offset.

Actual behavior

Future stamps: 140 post-timeout trajectory frames, 0.425 rad maximum displacement. now() stamps: 0 frames, 0.000 rad.

Backtrace or Console output

No crash. The continued trajectory output and joint displacement are captured in the reproduction script's JSON stdout.

Activity

  1. added
    bug
    on Nov 29, 2026
  2. OceanicKr commented on Nov 29, 2026

    @OceanicKr

    Can confirm this on main@5399d299 and jazzy@daf89d30. I believe a simpler fix than a forward-skew parameter would be to record the receipt time in each callback and measure age from min(header.stamp, receipt_time).
    Future-stamped commands then expire on time, normal stamps behave as before, and no new parameter is needed.
    I'd love to work on this out!

  3. Tnikko commented on Nov 29, 2026

    @Tnikko
    Author

    Thanks @OceanicKr and @SIDDARTHAREDDY8 for confirming and putting up PRs (#4034 and #4035) so quickly!

    Clamping future timestamps to receipt time (min(header.stamp, receipt_time)) is definitely cleaner than adding a new parameter—it preserves normal latency-based expiration while ensuring future-stamped commands still expire after incoming_command_timeout.

    One small detail to watch for during review: making sure header.stamp is compared using the same clock type as receipt_time (e.g., receipt_time.get_clock_type()) to avoid any rclcpp::Time clock-source mismatch.

    Happy to run the reproducer against whichever PR the maintainers decide to move forward with!

  4. OceanicKr commented on Nov 30, 2026

    @OceanicKr

    Thanks @Tnikko ! Good point on clock types. #4035 now constructs the stamp with receipt_time.get_clock_type() before comparing.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions