Skip to content

Insulate /clock callback on specific thread #792

Open

Description

@fujitatomoya

Feature request

Feature description

rclpy follow-up of ros2/rclcpp#1542.

the current implementation of simulation time which listen to the /clock topic, this behavior breaks the symmetry between the usage of real time (system time internally accessed without the need of subscribing to a topic, and hence always updated) and simulation time (time received on the /clock topic and hence frozen in a callback).
the symmetry should be maintain in order to not draw false conclusions about the behavior of a code developed in simulation VS real time, and thus independently from good/bad code practice.

Implementation considerations

N.A

Activity

  1. added
    enhancement
    on May 10, 2021
  2. fujitatomoya commented on May 10, 2021

    @fujitatomoya
    CollaboratorAuthor

    Reproducible Sample

    • How to build
    > cd <colcon_workspace>/src
    > git clone [email protected]:fujitatomoya/ros2_test_prover.git
    > cd <colcon_workspace>
    > colcon build --symlink-install --packages-select prover_rclpy prover_rclpy
    > source install/local_setup.bash
    • use_sim_time is NOT enabled. (default, real time)
    root@134f29e8f25f:~/ros2_ws/colcon_ws# ros2 run prover_rclpy rclpy_792
    [INFO] [1620620313.030122595] [test_node]: Timer expired!
    [INFO] [1620620313.030652940] [test_node]: Current time: builtin_interfaces.msg.Time(sec=1620620313, nanosec=30261016)
    [INFO] [1620620313.131537800] [test_node]: Current time: builtin_interfaces.msg.Time(sec=1620620313, nanosec=130820724)
    [INFO] [1620620313.233182128] [test_node]: Current time: builtin_interfaces.msg.Time(sec=1620620313, nanosec=232245229)
    [INFO] [1620620313.334565491] [test_node]: Current time: builtin_interfaces.msg.Time(sec=1620620313, nanosec=333647523)
    [INFO] [1620620313.436254238] [test_node]: Current time: builtin_interfaces.msg.Time(sec=1620620313, nanosec=435334840)
    [INFO] [1620620313.537922876] [test_node]: Current time: builtin_interfaces.msg.Time(sec=1620620313, nanosec=536981457)
    [INFO] [1620620313.639613674] [test_node]: Current time: builtin_interfaces.msg.Time(sec=1620620313, nanosec=638694465)
    [INFO] [1620620313.741326942] [test_node]: Current time: builtin_interfaces.msg.Time(sec=1620620313, nanosec=740385533)
    [INFO] [1620620313.842932769] [test_node]: Current time: builtin_interfaces.msg.Time(sec=1620620313, nanosec=841742538)
    [INFO] [1620620313.944124850] [test_node]: Current time: builtin_interfaces.msg.Time(sec=1620620313, nanosec=943217412)
    [INFO] [1620620314.045225243] [test_node]: Current time: builtin_interfaces.msg.Time(sec=1620620314, nanosec=44351785)
    [INFO] [1620620315.014339364] [test_node]: Timer expired!
    [INFO] [1620620315.015234882] [test_node]: Current time: builtin_interfaces.msg.Time(sec=1620620315, nanosec=14510385)
    [INFO] [1620620315.116864219] [test_node]: Current time: builtin_interfaces.msg.Time(sec=1620620315, nanosec=115837950)
    [INFO] [1620620315.218562187] [test_node]: Current time: builtin_interfaces.msg.Time(sec=1620620315, nanosec=217637459)
    ...<snip>
    • use_sim_time is enabled.
    # start simulation clock publisher
    root@134f29e8f25f:~/ros2_ws/colcon_ws# ros2 run prover_rclcpp sim_clock_publisher
    
    # start node with timer
    root@134f29e8f25f:~/ros2_ws/colcon_ws# ros2 run prover_rclpy rclpy_792
    [INFO] [1620620428.799579528] [test_node]: Timer expired!
    [INFO] [1620620428.800055133] [test_node]: Current time: builtin_interfaces.msg.Time(sec=1620620428, nanosec=788452724)
    [INFO] [1620620428.900954073] [test_node]: Current time: builtin_interfaces.msg.Time(sec=1620620428, nanosec=788452724)
    [INFO] [1620620429.001873214] [test_node]: Current time: builtin_interfaces.msg.Time(sec=1620620428, nanosec=788452724)
    [INFO] [1620620429.102788923] [test_node]: Current time: builtin_interfaces.msg.Time(sec=1620620428, nanosec=788452724)
    [INFO] [1620620429.203695413] [test_node]: Current time: builtin_interfaces.msg.Time(sec=1620620428, nanosec=788452724)
    [INFO] [1620620429.304654575] [test_node]: Current time: builtin_interfaces.msg.Time(sec=1620620428, nanosec=788452724)
    [INFO] [1620620429.405622946] [test_node]: Current time: builtin_interfaces.msg.Time(sec=1620620428, nanosec=788452724)
    ...<snip>
    
    
  3. fujitatomoya commented on May 10, 2021

    @fujitatomoya
    CollaboratorAuthor
  4. Flova commented on Mar 3, 2022

    @Flova
    Contributor

    This PR needs #850. Otherwise a new Node would be needed and this would result in a cyclic dependency (Node -> TimeSource -> Node) and is additionally very ugly.

  5. Flova commented on Mar 3, 2022

    @Flova
    Contributor

    Adapting TimeSource itself should be quite easy.

  6. Flova commented on Mar 4, 2022

    @Flova
    Contributor

    I hacked together a solution for #850 and #792 which seems to work. The clock is updated on the same Node without an explicit spin call. It is done via a thread with a seperate spin in the TimeSource. The said spin uses a patched Executor which also accepts callback_groups in addition to nodes. The implementation is quite ugly at the moment, but it seems to work. I will do a PR. Feel free to comment comment on my implementation so we can improve it.

  7. peci1 commented on May 6, 2026

    @peci1

    I've just hit an issue with /clock that was quite hard to debug. I'm running an autonomous exploration pipeline in Gazebo with a Turtlebot, so just a lidar, camera and a few other things. Physics step is 0.004 s. RTF is around 70%. I'm on Kilted in Docker (the numbers I present here are slightly better when running in Apptainer, but not substantially better).

    It showed that there were 2 problems:

    • FastDDS in default config is just unusable (the difference of two consecutive delivered clock messages was more than 0.25 s instead of 0.004 s).
    • Zenoh is much better in this regard, but still not perfect; however, putting the clock subscriber into its own callback group helped in most cases

    I know that moving /clock to a separate thread would be the best solution, but at least a dedicated callback group could be easily added. This is how I mock it in:

        sim_time_active = self._time_source.ros_time_is_active
        if sim_time_active:
            from rclpy.callback_groups import MutuallyExclusiveCallbackGroup
            def _subscribe_to_clock_topic(self):
                self.group = MutuallyExclusiveCallbackGroup()
                if self._clock_sub is None:
                    node = self._get_node()
                    if node is not None:
                        node.get_logger().warning("Subscribing to clock topic on separate callback group")
                        self._clock_sub = node.create_subscription(
                            Clock,
                            "/clock",
                            self.clock_callback,
                            QoSProfile(depth=1, reliability=rclpy.qos.ReliabilityPolicy.BEST_EFFORT),
                            callback_group=self.group,
                        )
            self._time_source.ros_time_is_active = False
            from functools import partial
            self._time_source._subscribe_to_clock_topic = partial(_subscribe_to_clock_topic, self._time_source)
            self._time_source.ros_time_is_active = True
    

    Here are some plots that show the dt distribution in three different nodes: occ (occupancy mapper, subscribes laserscan and icp odom, publishes occupancy grid), icp (ICP SLAM, subsribes laser scans and odometry), loc (factorgraph localization, subscribes odometry, ICP odometry and a few other things, has slow updates). All nodes are rclpy with MultiThreadedExecutor.

    It seems that except the loc node, moving clock callback into its own callback group helped quite a bit. So is there interest into a PR that would do that?

    The legends of the plots are as follows: times_NODE_CALLBACKGROUP_(_dds)_cbg/_Column_0, where NODE is loc/occ/icp, CALLBACKGROUP is def for the current implementation and cus for the proposed variant with a separated callback group, and _dds (if present) means FastDDS (otherwise Zenoh).

    ICP SLAM:

    Image

    Localization:

    Image

    Occupancy mapper:

    Image

    For clearer interpretation with Zenoh, here are the same plots with Zenoh only, custom callback group shifted by 0.002 upwards so that its dots are not overlaid with the default implementation dots:

    ICP SLAM:

    Image

    Localization:

    Image

    Occupancy mapper:

    Image

    I hope it's easy to see that for ICP and occupancy mapper, the proposed change is purely positive. For the localization node, it seems the default behavior is better on the average, but worse in extremes. And I'd say the extremes are what can really kill your node (time jumping by large chunks).

    These are the source data:

    times_occ_cus_cbg.csv
    times_loc_cus_cbg.csv
    times_icp_cus_cbg.csv
    times_icp_def_cbg.csv
    times_loc_def_cbg.csv
    times_occ_def_cbg.csv
    times_occ_def_dds_cbg.csv
    times_loc_def_dds_cbg.csv
    times_icp_def_dds_cbg.csv
    times_icp_cus_dds_cbg.csv
    times_loc_cus_dds_cbg.csv
    times_occ_cus_dds_cbg.csv

    And these are the ROS nodes:

    loc: https://gitlab.fel.cvut.cz/robolab/aro/student-packages/-/blob/master/aro_exploration/aro_exploration/localization/aro_localization.py?ref_type=heads
    icp: https://gitlab.fel.cvut.cz/robolab/aro/student-packages/-/blob/master/aro_exploration/aro_exploration/slam/icp_slam.py?ref_type=heads
    occ: https://gitlab.fel.cvut.cz/robolab/aro/student-packages/-/blob/master/aro_exploration/aro_exploration/slam/occupancy_mapper.py?ref_type=heads

  8. peci1 commented on May 6, 2026

    @peci1

    These are dt histograms (beware of logarithmic axis):

    Image
  9. peci1 commented on May 6, 2026

    @peci1

    It is possible that some portion of the observed problems is caused by the fact that some of our callbacks run long (even 0.1-0.2 s). I think that could explain why some clock messages get dropped without the custom callback group for clock. But our multithreaded executors have at least 4 threads and the long callback can occupy just one of them, so the rest should be quite free for clock processing.

    But that's for multithreaded executors. Single-threaded executors currently can't handle anything that needs any kind of time handling. I think that's very suboptimal user experience that basically excludes a large portion of nodes written for real-time from being usable in simulation.

    TransformListener has already started the "tradition" of extra node and thread for its messages. I think clock should go the same way. Maybe with #850 this would no longer needed, but until that is implemented, the easier way to go is to run a full node similar to TransformListener. Flova was earlier concerned about a dependency cycle, but that wouldn't happen. The clock node itself definitely doesn't need use_sim_time set to true (similar to how I do it in https://github.com/ros2/geometry2/pull/935/changes#diff-3ac7519984dfceb384e07ab87559df7954a636226ef8b831fcdcf9b298177cdfR93).

    @fujitatomoya @Flova do you agree the sketched direction makes sense? (creating an extra clock node and thread, with possible future replacing of the full node by just a CB group when #850 is done)

  10. Flova commented on May 7, 2026

    @Flova
    Contributor

    I think the extra node thing is a hack and should not be the official direction. That being said I also created the bitbots_tf_buffer which is a drop-in tf implementation for python which uses a cpp node under the hood. It was needed as TF can stall a python node in a complex robot with a high frequency robot state update. But I think we should fix these issues from the root cause.

    Python nodes work really well if you use async / await as it allows the single threaded executor to process things like tf, clock or other sensor msgs while you e.g. wait for a service to respond or an action to complete. This is essentially all async does. There are a few downsides, for example the async tf lookup does not support timeouts, which could lead to the robot locking up. I did a PR for that but sadly it (like many PRs for major issues in ROS right now) it has gotten no/little attention by the team.

    Generally speaking async executors should not be blocked by long running tasks. This is not just a ROS thing, but also the case for e.g. Tokio in rust. Relying on the multi threaded executor is a hack, as the thread count needs to be manually adjusted every time we add a relevant subscription and we might accidentally introduce hard to find race conditions of we do that. Also it's performance is significantly worse compared to the standard single threaded executor or even better the events executor. Other async frameworks like Tokio have a specific primitive for long running tasks. I think this is missing right now. You can easily implement it yourself though. In it's simple form it essentially spawns a thread for your task and gives the executor a future that can be awaited. This way you can spawn the long running task without blocking the executor, which regularly checks if the task is finished and continues after the await keyword if this is the case. It would be cool if ROS enforced this kind of behavior, provided better ergonomics or used a more standard async python implementation. Also I think the support for normal blocking service calls etc. misleads many beginners to deadlocks down the line. You either need a threading based model like ros1 that handles things like blocking calls well, or enforce an async model. Mixing them makes rarely sense and sadly the documentation or implementation never highlights these differences in a sufficient way.

    So what would be my "ideal" solution. An internal executor that is separate from the user one and can be used for things like the clock. Proper documentation and convenience functions for async or an ros1 style executor with a thread for each type of subscription.

  11. jmachowinski commented on May 8, 2026

    @jmachowinski
    Contributor

    @Flova I just noticed that you basically tried to address exactly this issue 4 years back, and as always, there was no progress due to the lack of maintainers / manpower. You also did some in depth bug fixing in rclpy, and now I am wondering, if you would be open to helping out with maintaining rclpy.

  12. Flova commented on May 9, 2026

    @Flova
    Contributor

    While my time is limited too, I would be willing to help.

  13. jmachowinski commented on May 15, 2026

    @jmachowinski
    Contributor
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

    backlogenhancement

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions