← Back to Pull requests

Don't let exceptions escape destructors #3278

Open
unknown opened this pull request with 650 lines diff across 8 files
View on GitHub
unknown unknown commented on Sep 19, 2026 04:01 UTC
Author

Description

Space ROS runs clang-tidy over rclcpp. ament_lint_common does not, and there is no .clang-tidy in this repo, so bugprone-exception-escape has not been pointed at this code before. It flags three destructors that can reach std::terminate.

These three destructors call something that throws:

TimeSource::NodeState::~NodeState calls detachNode(), which calls NodeParameters::remove_on_set_parameters_callback(). That constructs a ParameterMutationRecursionGuard, which throws ParameterModifiedInCallbackException while a set-parameters callback is running.
EventsCBGExecutor::~EventsCBGExecutor calls shutdown(), then remove_all_nodes_and_callback_groups(), then remove_node(), which throws std::runtime_error when a node is no longer associated with the executor.
WaitResult::~WaitResult calls wait_result_release(), which throws std::runtime_error when the wait set is not holding the result (wait_set_template.hpp:750).

The three are not equally reachable, and it is worth saying which is which. The first happens today and the added test hits it. For the second I have no reproducer: it needs the node disassociated from the executor by some other path first. The third is likely unreachable without prior misuse, since wait_result_holding_ is cleared only in that function and the move constructor nulls the moved-from pointer, so guarding it is defensive. Same defect and same fix in all three, so they go together.

On the noexcept point, since it came up on #2948: a destructor's implicit exception specification is noexcept(true) unless a base or member destructor is itself potentially throwing, which none of these three have. The gdb trace below is the confirmation rather than the argument, since it lands in __cxa_call_terminate.

~Context already guards this case, and #2953 did the same for ~ServerGoalHandle after #2948 reported it as a throwing destructor. Those two picked different severities: ~ServerGoalHandle logs at RCLCPP_DEBUG, ~Context at RCLCPP_ERROR. I followed ~Context on the grounds that failed teardown is worth seeing by default, but I will happily drop these to DEBUG if you would rather they stay quiet.

Evidence

The test added to test_time_source.cpp destroys a TimeSource from inside an on-set-parameters callback. Before the change it takes down the whole test binary instead of failing an assertion:

[ RUN      ] TestTimeSource.destructor_does_not_terminate_when_detach_throws
-- run_test.py: return code 245

Under gdb:

#2  std::terminate ()
#3  __cxa_call_terminate ()
#4  in ?? () from librclcpp.so                   <- ~TimeSource
#6  std::default_delete<rclcpp::TimeSource>::operator() (...)
#10 operator() (...) at test_time_source.cpp:216 <- inside the parameter callback

After:

[ERROR] [my_node]: unhandled exception in ~NodeState(): cannot set or declare a parameter, or change the callback from within set callback
[       OK ] TestTimeSource.destructor_does_not_terminate_when_detach_throws (27 ms)

Full rclcpp suite with this patch applied, Ubuntu 24.04 on aarch64: 3096 tests, 0 failures.

What the guard changes

The guarded call is abandoned partway, which is the part worth checking. In ~NodeState that skips resets of members that are about to be destroyed anyway. In ~EventsCBGExecutor it skips context_->remove_on_shutdown_callback(), so the registration outlives the executor; that callback holds a weak_ptr to the guard condition, so it becomes a no-op rather than a dangling call, but the entry does stay on the context until shutdown. Both are better than terminating.

No API or ABI change: destructor bodies only, no members, bases, signatures or vtables. One of the three is an inline destructor in a public header (wait_result.hpp) and adds #include "rclcpp/logging.hpp" there, which that header already pulled in transitively via client.hpp and service.hpp.

No linked issue. Related: #2948 and #2953 (same defect class in rclcpp_action).

Is this user-facing behavior change?

Yes. These three paths previously aborted the process; they now log and finish destroying the object. ~Context and ~ServerGoalHandle already made the same tradeoff. A destructor cannot report failure to its caller, and terminating denies the application any chance to shut down in an orderly way.

Did you use Generative AI?

Yes. The patch, the regression test and this description were written with Claude Opus 5 via Claude Code. The clang-tidy run, the gdb backtrace and the full-suite result quoted above were produced and checked locally rather than asserted by the model, and the three throw paths were each read in the source.

Additional Information

To see the warnings, inside docker run --rm -it ros:rolling-ros-base bash:

apt-get update && apt-get install -y clang-tidy git python3-colcon-common-extensions ros-rolling-rclcpp
mkdir -p /ws/src && cd /ws/src && git clone https://github.com/ros2/rclcpp.git
cd rclcpp && git checkout 29de98c   # rolling as of writing
cd /ws && . /opt/ros/rolling/setup.sh
colcon build --packages-select rclcpp --cmake-args -DCMAKE_EXPORT_COMPILE_COMMANDS=ON -DBUILD_TESTING=OFF
run-clang-tidy -p /ws/build/rclcpp -quiet \
  -header-filter=".*/ws/src/rclcpp/rclcpp/include/rclcpp/.*" \
  -checks="-*,bugprone-exception-escape"

Three warnings on that tree, zero with this branch checked out instead. The ros-rolling-rclcpp package is only there to pull the dependency closure; rosdep install --from-paths src -y does the same.

Scope. The same clang-tidy run reports roughly a thousand other findings in this package and I left all of them out. The large ones are style rules whose fix would break the public API (google-explicit-constructor, google-default-arguments) or would change exported signatures and break ABI (misc-const-correctness, performance-unnecessary-value-param). cppcoreguidelines-owning-memory wants gsl::owner, which this project does not use.

Two more are worth fixing but not here:

bugprone-use-after-move at node_logging.cpp:84. A SetLoggerLevelsResult declared outside the loop is moved into the response on every iteration, so later iterations write into a moved-from object and the success branch never clears reason. libstdc++ leaves the string empty, so you will not see it today, but the state is unspecified.

  • bugprone-exception-escape on main() in rclcpp_components/src/component_container.cpp. That one has history (#1890, and #3184 which tried to silence it with NOLINT and was closed), so it does not belong in a patch about destructors.
  • Backport. All three sites exist on jazzy, so this wants backport-jazzy. Space ROS pins rclcpp on the jazzy branch, so without the backport the fix does not reach it.

    Diff: 650 lines (+487 / -163) across 8 files Reviewer: jmachowinski Review duration: 33565m
    All Vouch review confidence checks passed
    Residual risk 0.30 = Change Risk (0.52) × (1 − Review Confidence (0.43)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.52 · 650 lines diff across 8 files
    0.52
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.02 · 1 substantive comment(s)
    0.02
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    42%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.388
    Shallow Review Depth shallow_review_depth
    0.344
    Real PR Conversation Timeline
    1 comments
    "Review active on #3278"
    general weight: 0.35
    Reviewers
    Assignees
    Unassigned
    Labels
    risk: low confidence: 43.0% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 52% (MEDIUM) · Higher = larger blast radius
    52%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 43.0% · Lower = rushed or shallow review
    43.0%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 29.7% · Safe to merge
    29.7%
    Repository