← Back to Pull requests

Fix navigator state mutation before preemption validation #6646

Open
mini-1235 opened this pull request with 938 lines diff across 13 files
View on GitHub
mini-1235 mini-1235 commented on Oct 11, 2026 07:15 UTC
Author

<!-- Please fill out the following pull request template for non-trivial changes to help us process your PR faster and more efficiently.-->

---

Basic Info

| Info | Please fill out this column |
| ------ | ----------- |
| Ticket(s) this addresses | Fixes https://github.com/ros-navigation/navigation2/issues/6644 |
| Primary OS tested on | MacOS |
| Robotic platform tested on | Tb4 |
| Does this PR contain AI generated software? | Yes, I iterated with my agent and validated it manually |
| Was this PR description generated by AI software? | Yes, assisted with Codex 6.1 Sol and Claude Opus 5.5 (claude-opus-5-5) |

---

Description of contribution in a few bullet points

goalReceived now only validates the goal (TF lookups). It no longer changes the running BT's
blackboard or feedback. Reception-time TF validation from #6279 is kept.
New pure virtual goalStarted hook on BehaviorTreeNavigator. BtActionServer calls it when a
goal starts executing, including a pending goal promoted after the current one completes. It
initializes the blackboard.
NavigatorMuxer::startNavigating is now atomic and returns false if another navigator owns the
muxer, instead of logging "Major error!" and taking it over.
Cross-navigator preemption (allow_navigator_preemption) retries preemptCurrentNavigator()
until the muxer is free or the timeout expires, so a request is not lost when the owner changes
while waiting. preemptCurrentNavigator() is now null-safe.
If a goal fails to start without setting an error code, it is aborted with UNKNOWN.
muxer_preemption_requested_ is cleared only after the goal finished and released the muxer, so
a cross-navigator preemption requested before execution starts is not lost.
Same-navigator preemption still goes through onPreempt, which is unchanged from main.

Description of documentation updates required from your changes

Migration guide: goalStarted is pure virtual, so external BehaviorTreeNavigator plugins must
implement it and move blackboard initialization out of goalReceived.

Description of how this change was tested

Unit tests for the muxer, navigator and goal start failure paths. colcon test for
nav2_core, nav2_bt_navigator and nav2_behavior_tree passes, except test_loop_rate,
which also fails on main on macOS (timing).
TB4 simulation, each case on a fresh launch, for both NavigateToPose and NavigateThroughPoses:

| New goal sent while the first is running | New goal | First goal | Robot ends |
|---|---|---|---|
| Different BT | aborted | succeeded | 0.05–0.25 m from the first goal |
| Frame that cannot be transformed | rejected | succeeded | 0.01–0.24 m from the first goal |
| Same BT | succeeded | aborted (preempted) | 0.12–0.18 m from the new goal |

Cross-navigator preemption (allow_navigator_preemption: true) and pending goal promotion
also pass. No "Major error!" in any run. On main without this PR, the NavigateToPose
different-BT case reports success for the first goal while the robot ends 10.7 m from it and
0.07 m from the rejected goal.

Future work that may be required in bullet points

Follow-up PR: validate a same-BT preemption's transforms before aborting the current goal
(today onPreempt accepts first, so a late TF failure aborts the current goal, and
NavigateThroughPoses throws). This predates #6279.
Follow-up PR: NavigateThroughPoses can keep stale waypoints when a preemption fails. This
predates #6279.

<!--
I think there might be some optimizations to be made from STL vector
I see a lot of redundancy in this package, we might want to add a function bool XYZ() to reduce clutter
I tested on a differential drive robot, but there might be issues turning near corners on an omnidirectional platform
-->

For Maintainers: <!-- DO NOT EDIT OR REMOVE -->


  • Check that any new parameters added are updated in docs.nav2.org

  • Check that any significant change is added to the migration guide

  • Check that any new features OR changes to existing behaviors are reflected in the tuning guide

  • Check that any new functions have Doxygen added

  • Check that any new features have test coverage

  • Check that any new plugins is added to the plugins page

  • If BT Node, Additionally: add to BT's XML index of nodes for groot, BT package's readme table, and BT library lists

  • Should this be backported to current distributions? If so, tag with backport-*.
  • Diff: 938 lines (+863 / -75) across 13 files Reviewer: mini-1235 Review duration: 79020m
    All Vouch review confidence checks passed
    Residual risk 0.16 = Change Risk (0.87) × (1 − Review Confidence (0.82)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.87 · 938 lines diff across 13 files
    0.87
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.90 · 5 substantive comment(s)
    0.90
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    81%
    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.400
    Self Review self_review
    0.140
    Ai Authored ai_authored
    0.050
    Real PR Conversation Timeline
    38 items
    mini-1235 mini-1235 commented on code on Oct 11, 2026 07:20 UTC
    Code Review
    nav2_ros_common/include/nav2_ros_common/simple_action_server.hpp:1
    @@ -387,9 +387,12 @@ class SimpleActionServer
     
       /**
        * @brief Accept pending goals
    -   * @return Goal Ptr to the  goal that's going to be accepted
    +   * @param expected_goal Goal validated by the caller; nullptr accepts any pending goal
    +   * @return Shared pointer to the accepted goal, or nullptr if no active pending goal
    +   * exists or it no longer matches expected_goal
        */
    -  const std::shared_ptr<const typename ActionT::Goal> accept_pending_goal()
    +  const std::shared_ptr<const typename ActionT::Goal> accept_pending_goal(
    +    const std::shared_ptr<const typename ActionT::Goal> & expected_goal = nullptr)

    Note that this is not directly related to the regression, but rather an issue I noticed with how pending goals are handled. For example:

  • A is running, and B becomes pending.

  • onPreempt starts validating B's TF.

  • While B is being validated, C arrives and replaces B as the pending goal.

  • Validation of B finishes.
  • Without the argument, accept_pending_goal() would accept C based on B's validation, while the caller could end up writing B's prepared pose to the blackboard.

    With accept_pending_goal(B), the server first checks whether B is still the pending goal. Since C has already replaced B, it returns nullptr instead. This allows A to keep running while C remains pending until its own validation is completed.

    mini-1235 mini-1235 commented on Oct 11, 2026 07:24 UTC
    Author

    Here are a couple of flow diagrams I generated while debugging. Not sure if they are helpful, but feel free to ignore them if they are not :)

    Before:

    <img width="1667" height="1266" alt="image" src="https://github.com/user-attachments/assets/8c193d2e-cecc-4c8f-ab44-e07fa4c346de" />

    After:

    <img width="1817" height="1276" alt="image" src="https://github.com/user-attachments/assets/1e34c9bb-444b-455a-bcc5-9536f68248d4" />

    codecov[bot] codecov[bot] commented on Oct 11, 2026 09:42 UTC
    Bot

    Codecov Report


    :white_check_mark: All modified and coverable lines are covered by tests.

    | Files with missing lines | Coverage Δ | |
    |---|---|---|
    | ...ee/include/nav2\_behavior\_tree/bt\_action\_server.hpp | 100.00% <ø> (+16.66%) | :arrow_up: |
    | ...clude/nav2\_behavior\_tree/bt\_action\_server\_impl.hpp | 89.42% <100.00%> (+1.53%) | :arrow_up: |
    | ...bt\_navigator/navigators/navigate\_through\_poses.hpp | 100.00% <ø> (ø) | |
    | .../nav2\_bt\_navigator/navigators/navigate\_to\_pose.hpp | 100.00% <ø> (ø) | |
    | ...avigator/src/navigators/navigate\_through\_poses.cpp | 97.43% <100.00%> (+8.24%) | :arrow_up: |
    | ...2\_bt\_navigator/src/navigators/navigate\_to\_pose.cpp | 97.05% <100.00%> (+10.19%) | :arrow_up: |
    | ...core/include/nav2\_core/behavior\_tree\_navigator.hpp | 96.62% <100.00%> (+0.33%) | :arrow_up: |

    ... and 8 files with indirect coverage changes
    <details><summary> :rocket: New features to boost your workflow: </summary>

  • :snowflake: Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

  • </details>

    SteveMacenski SteveMacenski commented on Oct 16, 2026 00:28 UTC
    Contributor

    I am not fully understanding this problem, or I suppose not in a way that makes this solution make sense to me. This is alot of changes that warps my brain a little bit. Let me establish my chain of thought since this is an involved point

    Basically the chain is
    https://github.com/ros-navigation/navigation2/blob/d4533a60b927885fa762e5ec909bd139fb49fa01/nav2_ros_common/include/nav2_ros_common/simple_action_server.hpp#L170
    https://github.com/ros-navigation/navigation2/blob/d4533a60b927885fa762e5ec909bd139fb49fa01/nav2_behavior_tree/include/nav2_behavior_tree/bt_action_server_impl.hpp#L155
    https://github.com/ros-navigation/navigation2/blob/d4533a60b927885fa762e5ec909bd139fb49fa01/nav2_core/include/nav2_core/behavior_tree_navigator.hpp#L365C26-L365C38
    https://github.com/ros-navigation/navigation2/blob/d4533a60b927885fa762e5ec909bd139fb49fa01/nav2_bt_navigator/src/navigators/navigate_to_pose.cpp#L226

    So a new goal comes in and gets piped through to initializeGoalPose. We only reject due to TF errors. We actually swap out the info for the new request at this point. Preempt is only checked on the BT ticking loop lambda at which times its rejected, but the change to the BT is already done.

    Can't we just add some checks to initializeGoalPose to reject, checking if bt_action_server_ is actively processing a goal (or the muxer) and if so check on the request's fields like in onPreempt?

    Or, can't we at a lower level to make this automatic for all BT navigators call the preemption API onPreempt in onGoalReceived when plugin_muxer_->isNavigating() && plugin_muxer_->isCurrentNavigator(this) (so we're navigating and its this plugin; aka _preemption_). We could remove the preemption from the onLoop lambda then, I suppose - or just keep it? It probably needs to return a true/false bool instead of void return, though. But that is small. There may be some threading considerations there to consider that I have not.

    Last and probably worst thought, just have in onGoalReceived in the nav2_core navigator a check on isCurrentNavigatorin general, regardless of isNavigating, and do the check on the BT field there. It is fragile that we only check the BT field, but supposedly that's the only thing we do anyway (for now).

    mini-1235 mini-1235 commented on Oct 18, 2026 16:14 UTC
    Author

    This is a fairly large change, so I was not able to reply immediately, as I needed some time to think through this PR again.

    Can't we just add some checks to initializeGoalPose to reject, checking if bt_action_server_ is actively processing a goal (or the muxer) and if so check on the request's fields like in onPreempt?

    I assume you mean adding something like this to initializeGoalPose:

    if (bt_action_server_ is currently running a goal &&
        goal->behavior_tree != the BT currently running) {
      return false;
    }
    // ...otherwise continue as today
    

    I think this would work when goals A and B use different BTs. However, when they use the same BT, I think a new goal could modify the blackboard before preemption actually happens.

    Or, can't we at a lower level to make this automatic for all BT navigators call the preemption API onPreempt in onGoalReceived when plugin_muxer_->isNavigating() && plugin_muxer_->isCurrentNavigator(this) (so we're navigating and its this plugin; aka preemption). We could remove the preemption from the onLoop lambda then, I suppose - or just keep it?

    I assume you mean adding something like this to onGoalReceived:

    if (plugin_muxer_->isNavigating() && plugin_muxer_->isCurrentNavigator(this)) {
      return onPreempt(goal);  // changed to return bool
    }
    

    However, handle_goal only decides whether to ACCEPT or REJECT a goal. Goal B only gets a handle and becomes pending_handle_ later, in handle_accepted. The current onPreempt implementation calls acceptPendingGoal().

    I am also not sure if this is a good option. I think it might introduce other issues without fully solving the problem. I would need to think through this approach more carefully if we decide to go with it.

    Last and probably worst thought, just have in onGoalReceived in the nav2_core navigator a check on isCurrentNavigatorin general, regardless of isNavigating, and do the check on the BT field there. It is fragile that we only check the BT field, but supposedly that's the only thing we do anyway (for now).

    This seems similar to the first option(?) and I think it would have the same problem.

    These are just some of the potential issues that came to mind while reading through your suggestions. I might be misunderstanding something or missing other regression cases, so please correct me if I am wrong. If you could ask an AI agent to implement the option you think would work and push it to my branch, it would be easier for me to understand it :)

    I am also wondering whether I should split this into smaller PRs. I could focus on the major regression first and follow up with the minor issues separately. The first PR would be a bit smaller, although probably not by much :) since the fix still needs to touch quite a few files

    SteveMacenski SteveMacenski commented on Oct 22, 2026 22:27 UTC
    Contributor

    As you said, takes some time to think about this :wink:

    Fair points on my comments, they leads the goal a little bit. This would be very nasty and _at best_ hides a major defect, though functionally should 'work' in the worst sense. That was a bad idea on my part.

    After thinking through a few more ideas, I can understand better why you did what you did. Is there a chance that we can move the "Begin navigating from current location..." and afterward from initializeGoalPose and into a new method piped to run in the work() thread of the simple action server (possibly within accept_pending_goal? I'm not totally following why expected_goal is the better option. We already have some callbacks piped up the stack, so doing so here would be no sweat

    @redvinaa I'd appreciate if you chimed in since this relates to your previous PR.

    mini-1235 mini-1235 commented on Oct 26, 2026 08:48 UTC
    Author

    After thinking through a few more ideas, I can understand better why you did what you did. Is there a chance that we can move the "Begin navigating from current location..." and afterward from initializeGoalPose and into a new method piped to run in the work() thread of the simple action server (possibly within accept_pending_goal? I'm not totally following why expected_goal is the better option. We already have some callbacks piped up the stack, so doing so here would be no sweat

    Sorry, I should not have tried to address multiple issues at once, as I mentioned in https://github.com/ros-navigation/navigation2/pull/6646#discussion_r4240671299. I think that ended up making the discussion confusing for both of us.

    I have reverted the changes unrelated to this regression and can open a follow-up PR for them after this is merged. I believe that issue likely affects all branches, whereas this regression(as described in #6644) only affects main and Lyrical.

    Could you take another look at the updated version?

    SteveMacenski SteveMacenski commented on code on Oct 27, 2026 20:18 UTC
    Code Review
    nav2_core/include/nav2_core/behavior_tree_navigator.hpp:1
    @@ -364,31 +365,59 @@ class BehaviorTreeNavigator : public NavigatorBase
     
         bool goal_accepted = goalReceived(goal);
     
    -    if (goal_accepted) {
    +    if (goal_accepted && !plugin_muxer_->isCurrentNavigator(this)) {
           plugin_muxer_->startNavigating(this);
         }
     
         return goal_accepted;
       }
     
    +  /**
    +   * @brief Acquire navigator ownership and initialize a goal on the execution thread
    +   * Called for each fresh BT execution, including a pending goal promoted after completion.
    +   * @param goal Action template's goal message to process
    +   * @return bool If navigator ownership was acquired and goal initialization succeeded
    +   */
    +  bool onGoalStarted(typename ActionT::Goal::ConstSharedPtr goal)
    +  {
    +    // Completion releases ownership before the action worker promotes a pending goal.
    +    if (!plugin_muxer_->isCurrentNavigator(this) && !onGoalReceived(goal)) {
    +      return false;
    +    }
    +    return goalStarted(goal);
    +  }
    +
       /**
        * @brief An intermediate completion function to mux navigators
        */
       void onCompletion(
         typename ActionT::Result::SharedPtr result,
         nav2_behavior_tree::BtStatus & final_bt_status)
       {
    -    plugin_muxer_->stopNavigating(this);
    +    if (plugin_muxer_->isCurrentNavigator(this)) {
    +      plugin_muxer_->stopNavigating(this);
    +    }
         goalCompleted(result, final_bt_status);
       }
     
       /**
        * @brief A callback to be called when a new goal is received by the BT action server
    -   * Can be used to check if goal is valid and put values on
    -   * the blackboard which depend on the received goal
    +   * Validate without modifying execution state: this also runs for pending goals
    +   * while the current behavior tree is executing.
    +   * @param goal Action template's goal message to validate
    +   * @return bool If the goal is valid and can be accepted
        */
       virtual bool goalReceived(typename ActionT::Goal::ConstSharedPtr goal) = 0;
     
    +  /**
    +   * @brief Initialize blackboard and feedback state when a goal starts execution
    +   * The goal argument identifies the action whose BT is about to run.
    +   * Same-navigator preemption is initialized by onPreempt instead of this callback.
    +   * The default preserves compatibility with plugins that initialize in goalReceived.
    +   * @return bool If the goal was initialized successfully; the default returns true
    +   */
    +  virtual bool goalStarted(typename ActionT::Goal::ConstSharedPtr) {return true;}

    Should this be a required implementation? This is the only one that has a default implementation. I think this should be strictly required

    SteveMacenski SteveMacenski commented on code on Oct 27, 2026 20:19 UTC
    Code Review
    nav2_core/include/nav2_core/behavior_tree_navigator.hpp:1
    @@ -364,31 +365,59 @@ class BehaviorTreeNavigator : public NavigatorBase
     
         bool goal_accepted = goalReceived(goal);
     
    -    if (goal_accepted) {
    +    if (goal_accepted && !plugin_muxer_->isCurrentNavigator(this)) {
           plugin_muxer_->startNavigating(this);

    What does this buy us?

    SteveMacenski SteveMacenski commented on code on Oct 27, 2026 20:20 UTC
    Code Review
    nav2_core/include/nav2_core/behavior_tree_navigator.hpp:1
    @@ -364,31 +365,59 @@ class BehaviorTreeNavigator : public NavigatorBase
     
         bool goal_accepted = goalReceived(goal);
     
    -    if (goal_accepted) {
    +    if (goal_accepted && !plugin_muxer_->isCurrentNavigator(this)) {
           plugin_muxer_->startNavigating(this);
         }
     
         return goal_accepted;
       }
     
    +  /**
    +   * @brief Acquire navigator ownership and initialize a goal on the execution thread
    +   * Called for each fresh BT execution, including a pending goal promoted after completion.
    +   * @param goal Action template's goal message to process
    +   * @return bool If navigator ownership was acquired and goal initialization succeeded
    +   */
    +  bool onGoalStarted(typename ActionT::Goal::ConstSharedPtr goal)
    +  {
    +    // Completion releases ownership before the action worker promotes a pending goal.
    +    if (!plugin_muxer_->isCurrentNavigator(this) && !onGoalReceived(goal)) {

    Isn't on goal received still already run? This would mean we call it twice, no?

    SteveMacenski SteveMacenski commented on code on Oct 27, 2026 20:21 UTC
    Code Review
    nav2_core/include/nav2_core/behavior_tree_navigator.hpp:1
    @@ -364,31 +365,59 @@ class BehaviorTreeNavigator : public NavigatorBase
     
         bool goal_accepted = goalReceived(goal);
     
    -    if (goal_accepted) {
    +    if (goal_accepted && !plugin_muxer_->isCurrentNavigator(this)) {
           plugin_muxer_->startNavigating(this);
         }
     
         return goal_accepted;
       }
     
    +  /**
    +   * @brief Acquire navigator ownership and initialize a goal on the execution thread
    +   * Called for each fresh BT execution, including a pending goal promoted after completion.
    +   * @param goal Action template's goal message to process
    +   * @return bool If navigator ownership was acquired and goal initialization succeeded
    +   */
    +  bool onGoalStarted(typename ActionT::Goal::ConstSharedPtr goal)
    +  {
    +    // Completion releases ownership before the action worker promotes a pending goal.
    +    if (!plugin_muxer_->isCurrentNavigator(this) && !onGoalReceived(goal)) {
    +      return false;
    +    }
    +    return goalStarted(goal);
    +  }
    +
       /**
        * @brief An intermediate completion function to mux navigators
        */
       void onCompletion(
         typename ActionT::Result::SharedPtr result,
         nav2_behavior_tree::BtStatus & final_bt_status)
       {
    -    plugin_muxer_->stopNavigating(this);
    +    if (plugin_muxer_->isCurrentNavigator(this)) {
    +      plugin_muxer_->stopNavigating(this);

    Similarly, what does this buy us if the muxer is working properly?

    SteveMacenski SteveMacenski commented on code on Oct 27, 2026 20:24 UTC
    Code Review
    nav2_bt_navigator/src/navigators/navigate_to_pose.cpp:1
    @@ -223,32 +236,41 @@ NavigateToPoseNavigator::onPreempt(ActionT::Goal::ConstSharedPtr goal)
     }
     
     bool
    -NavigateToPoseNavigator::initializeGoalPose(ActionT::Goal::ConstSharedPtr goal)
    +NavigateToPoseNavigator::prepareGoalPose(
    +  ActionT::Goal::ConstSharedPtr goal,
    +  geometry_msgs::msg::PoseStamped & current_pose,
    +  geometry_msgs::msg::PoseStamped & goal_pose, std::string & error)
     {
    -  geometry_msgs::msg::PoseStamped current_pose;
       if (!nav2_util::getFreshPose(
           *feedback_utils_.tf, feedback_utils_.global_frame,
           feedback_utils_.robot_frame, clock_->now(),
           transform_staleness_threshold_, current_pose))
       {
    -    bt_action_server_->setInternalError(
    -      ActionT::Result::TF_ERROR,
    -      "Initial robot pose is not available.");
    +    error = "Initial robot pose is not available.";
         return false;
       }
     
    -  geometry_msgs::msg::PoseStamped goal_pose;
       if (!nav2_util::transformPoseInTargetFrame(
           goal->pose, goal_pose, *feedback_utils_.tf, feedback_utils_.global_frame,
           feedback_utils_.transform_tolerance))
       {
    -    bt_action_server_->setInternalError(
    -      ActionT::Result::TF_ERROR,
    -      "Failed to transform a goal pose provided with frame_id '" +
    -      goal->pose.header.frame_id +
    -      "' to the global frame '" +
    -      feedback_utils_.global_frame +
    -      "'.");
    +    error = "Failed to transform a goal pose provided with frame_id '" +
    +      goal->pose.header.frame_id + "' to the global frame '" +
    +      feedback_utils_.global_frame + "'.";
    +    return false;
    +  }
    +
    +  return true;
    +}
    +
    +bool
    +NavigateToPoseNavigator::initializeGoalPose(ActionT::Goal::ConstSharedPtr goal)
    +{
    +  geometry_msgs::msg::PoseStamped current_pose;
    +  geometry_msgs::msg::PoseStamped goal_pose;
    +  std::string error;
    +  if (!prepareGoalPose(goal, current_pose, goal_pose, error)) {
    +    bt_action_server_->setInternalError(ActionT::Result::TF_ERROR, error);
         return false;

    This also appears to me to be duplicated, this should already be done in the goal received callback. Shouldn't we know that this is OK from that?

    If so, then prepareGoalPose can go directly into goalReceived without the new method.

    mini-1235 mini-1235 commented on code on Oct 30, 2026 15:40 UTC
    Code Review
    nav2_core/include/nav2_core/behavior_tree_navigator.hpp:1
    @@ -364,31 +365,59 @@ class BehaviorTreeNavigator : public NavigatorBase
     
         bool goal_accepted = goalReceived(goal);
     
    -    if (goal_accepted) {
    +    if (goal_accepted && !plugin_muxer_->isCurrentNavigator(this)) {
           plugin_muxer_->startNavigating(this);

    Without this, every same-navigator preemption calls startNavigating while this navigator already owns the muxer. That logs a false "Major error".

    mini-1235 mini-1235 commented on code on Oct 30, 2026 15:40 UTC
    Code Review
    nav2_core/include/nav2_core/behavior_tree_navigator.hpp:1
    @@ -364,31 +365,59 @@ class BehaviorTreeNavigator : public NavigatorBase
     
         bool goal_accepted = goalReceived(goal);
     
    -    if (goal_accepted) {
    +    if (goal_accepted && !plugin_muxer_->isCurrentNavigator(this)) {
           plugin_muxer_->startNavigating(this);
         }
     
         return goal_accepted;
       }
     
    +  /**
    +   * @brief Acquire navigator ownership and initialize a goal on the execution thread
    +   * Called for each fresh BT execution, including a pending goal promoted after completion.
    +   * @param goal Action template's goal message to process
    +   * @return bool If navigator ownership was acquired and goal initialization succeeded
    +   */
    +  bool onGoalStarted(typename ActionT::Goal::ConstSharedPtr goal)
    +  {
    +    // Completion releases ownership before the action worker promotes a pending goal.
    +    if (!plugin_muxer_->isCurrentNavigator(this) && !onGoalReceived(goal)) {
    +      return false;
    +    }
    +    return goalStarted(goal);
    +  }
    +
       /**
        * @brief An intermediate completion function to mux navigators
        */
       void onCompletion(
         typename ActionT::Result::SharedPtr result,
         nav2_behavior_tree::BtStatus & final_bt_status)
       {
    -    plugin_muxer_->stopNavigating(this);
    +    if (plugin_muxer_->isCurrentNavigator(this)) {
    +      plugin_muxer_->stopNavigating(this);
    +    }
         goalCompleted(result, final_bt_status);
       }
     
       /**
        * @brief A callback to be called when a new goal is received by the BT action server
    -   * Can be used to check if goal is valid and put values on
    -   * the blackboard which depend on the received goal
    +   * Validate without modifying execution state: this also runs for pending goals
    +   * while the current behavior tree is executing.
    +   * @param goal Action template's goal message to validate
    +   * @return bool If the goal is valid and can be accepted
        */
       virtual bool goalReceived(typename ActionT::Goal::ConstSharedPtr goal) = 0;
     
    +  /**
    +   * @brief Initialize blackboard and feedback state when a goal starts execution
    +   * The goal argument identifies the action whose BT is about to run.
    +   * Same-navigator preemption is initialized by onPreempt instead of this callback.
    +   * The default preserves compatibility with plugins that initialize in goalReceived.
    +   * @return bool If the goal was initialized successfully; the default returns true
    +   */
    +  virtual bool goalStarted(typename ActionT::Goal::ConstSharedPtr) {return true;}

    Agreed. Will update today

    mini-1235 mini-1235 commented on code on Oct 30, 2026 16:25 UTC
    Code Review
    nav2_core/include/nav2_core/behavior_tree_navigator.hpp:1
    @@ -364,31 +365,59 @@ class BehaviorTreeNavigator : public NavigatorBase
     
         bool goal_accepted = goalReceived(goal);
     
    -    if (goal_accepted) {
    +    if (goal_accepted && !plugin_muxer_->isCurrentNavigator(this)) {
           plugin_muxer_->startNavigating(this);
         }
     
         return goal_accepted;
       }
     
    +  /**
    +   * @brief Acquire navigator ownership and initialize a goal on the execution thread
    +   * Called for each fresh BT execution, including a pending goal promoted after completion.
    +   * @param goal Action template's goal message to process
    +   * @return bool If navigator ownership was acquired and goal initialization succeeded
    +   */
    +  bool onGoalStarted(typename ActionT::Goal::ConstSharedPtr goal)
    +  {
    +    // Completion releases ownership before the action worker promotes a pending goal.
    +    if (!plugin_muxer_->isCurrentNavigator(this) && !onGoalReceived(goal)) {
    +      return false;
    +    }
    +    return goalStarted(goal);
    +  }
    +
       /**
        * @brief An intermediate completion function to mux navigators
        */
       void onCompletion(
         typename ActionT::Result::SharedPtr result,
         nav2_behavior_tree::BtStatus & final_bt_status)
       {
    -    plugin_muxer_->stopNavigating(this);
    +    if (plugin_muxer_->isCurrentNavigator(this)) {
    +      plugin_muxer_->stopNavigating(this);

    Similar to https://github.com/ros-navigation/navigation2/pull/6646#discussion_r4425464819. Without this, stopNavigating would log a false "Major error".

    mini-1235 mini-1235 commented on code on Oct 30, 2026 16:49 UTC
    Code Review
    nav2_core/include/nav2_core/behavior_tree_navigator.hpp:1
    @@ -364,31 +365,59 @@ class BehaviorTreeNavigator : public NavigatorBase
     
         bool goal_accepted = goalReceived(goal);
     
    -    if (goal_accepted) {
    +    if (goal_accepted && !plugin_muxer_->isCurrentNavigator(this)) {
           plugin_muxer_->startNavigating(this);
         }
     
         return goal_accepted;
       }
     
    +  /**
    +   * @brief Acquire navigator ownership and initialize a goal on the execution thread
    +   * Called for each fresh BT execution, including a pending goal promoted after completion.
    +   * @param goal Action template's goal message to process
    +   * @return bool If navigator ownership was acquired and goal initialization succeeded
    +   */
    +  bool onGoalStarted(typename ActionT::Goal::ConstSharedPtr goal)
    +  {
    +    // Completion releases ownership before the action worker promotes a pending goal.
    +    if (!plugin_muxer_->isCurrentNavigator(this) && !onGoalReceived(goal)) {

    There are two cases:

    1. For a fresh goal: It already owns the mutex, so the function should not be called twice.
    2. For a pending goal promoted after the current goal completes: The function still needs to be called, since completion releases the muxer, and another navigator may have acquired it in the meantime.

    I however agree that this is partly redundant. See 5e72d5f

    mini-1235 mini-1235 commented on code on Oct 30, 2026 16:59 UTC
    Code Review
    nav2_bt_navigator/src/navigators/navigate_to_pose.cpp:1
    @@ -223,32 +236,41 @@ NavigateToPoseNavigator::onPreempt(ActionT::Goal::ConstSharedPtr goal)
     }
     
     bool
    -NavigateToPoseNavigator::initializeGoalPose(ActionT::Goal::ConstSharedPtr goal)
    +NavigateToPoseNavigator::prepareGoalPose(
    +  ActionT::Goal::ConstSharedPtr goal,
    +  geometry_msgs::msg::PoseStamped & current_pose,
    +  geometry_msgs::msg::PoseStamped & goal_pose, std::string & error)
     {
    -  geometry_msgs::msg::PoseStamped current_pose;
       if (!nav2_util::getFreshPose(
           *feedback_utils_.tf, feedback_utils_.global_frame,
           feedback_utils_.robot_frame, clock_->now(),
           transform_staleness_threshold_, current_pose))
       {
    -    bt_action_server_->setInternalError(
    -      ActionT::Result::TF_ERROR,
    -      "Initial robot pose is not available.");
    +    error = "Initial robot pose is not available.";
         return false;
       }
     
    -  geometry_msgs::msg::PoseStamped goal_pose;
       if (!nav2_util::transformPoseInTargetFrame(
           goal->pose, goal_pose, *feedback_utils_.tf, feedback_utils_.global_frame,
           feedback_utils_.transform_tolerance))
       {
    -    bt_action_server_->setInternalError(
    -      ActionT::Result::TF_ERROR,
    -      "Failed to transform a goal pose provided with frame_id '" +
    -      goal->pose.header.frame_id +
    -      "' to the global frame '" +
    -      feedback_utils_.global_frame +
    -      "'.");
    +    error = "Failed to transform a goal pose provided with frame_id '" +
    +      goal->pose.header.frame_id + "' to the global frame '" +
    +      feedback_utils_.global_frame + "'.";
    +    return false;
    +  }
    +
    +  return true;
    +}
    +
    +bool
    +NavigateToPoseNavigator::initializeGoalPose(ActionT::Goal::ConstSharedPtr goal)
    +{
    +  geometry_msgs::msg::PoseStamped current_pose;
    +  geometry_msgs::msg::PoseStamped goal_pose;
    +  std::string error;
    +  if (!prepareGoalPose(goal, current_pose, goal_pose, error)) {
    +    bt_action_server_->setInternalError(ActionT::Result::TF_ERROR, error);
         return false;

    Hmm, I disagree with this.

    goalReceived runs when the goal arrives and discards the poses, while this needs them when the goal starts. A pending goal can wait until the current one finishes, so anything computed earlier may be stale

    SteveMacenski SteveMacenski commented on code on Oct 30, 2026 22:21 UTC
    Code Review
    nav2_bt_navigator/src/navigators/navigate_to_pose.cpp:1
    @@ -223,32 +236,41 @@ NavigateToPoseNavigator::onPreempt(ActionT::Goal::ConstSharedPtr goal)
     }
     
     bool
    -NavigateToPoseNavigator::initializeGoalPose(ActionT::Goal::ConstSharedPtr goal)
    +NavigateToPoseNavigator::prepareGoalPose(
    +  ActionT::Goal::ConstSharedPtr goal,
    +  geometry_msgs::msg::PoseStamped & current_pose,
    +  geometry_msgs::msg::PoseStamped & goal_pose, std::string & error)
     {
    -  geometry_msgs::msg::PoseStamped current_pose;
       if (!nav2_util::getFreshPose(
           *feedback_utils_.tf, feedback_utils_.global_frame,
           feedback_utils_.robot_frame, clock_->now(),
           transform_staleness_threshold_, current_pose))
       {
    -    bt_action_server_->setInternalError(
    -      ActionT::Result::TF_ERROR,
    -      "Initial robot pose is not available.");
    +    error = "Initial robot pose is not available.";
         return false;
       }
     
    -  geometry_msgs::msg::PoseStamped goal_pose;
       if (!nav2_util::transformPoseInTargetFrame(
           goal->pose, goal_pose, *feedback_utils_.tf, feedback_utils_.global_frame,
           feedback_utils_.transform_tolerance))
       {
    -    bt_action_server_->setInternalError(
    -      ActionT::Result::TF_ERROR,
    -      "Failed to transform a goal pose provided with frame_id '" +
    -      goal->pose.header.frame_id +
    -      "' to the global frame '" +
    -      feedback_utils_.global_frame +
    -      "'.");
    +    error = "Failed to transform a goal pose provided with frame_id '" +
    +      goal->pose.header.frame_id + "' to the global frame '" +
    +      feedback_utils_.global_frame + "'.";
    +    return false;
    +  }
    +
    +  return true;
    +}
    +
    +bool
    +NavigateToPoseNavigator::initializeGoalPose(ActionT::Goal::ConstSharedPtr goal)
    +{
    +  geometry_msgs::msg::PoseStamped current_pose;
    +  geometry_msgs::msg::PoseStamped goal_pose;
    +  std::string error;
    +  if (!prepareGoalPose(goal, current_pose, goal_pose, error)) {
    +    bt_action_server_->setInternalError(ActionT::Result::TF_ERROR, error);
         return false;

    runs when the goal arrives and discards the poses

    Why not store it? These should be run in quick succession. The current_pose and goal_pose are only used to update the blackboard, so if we did that it wouldn't matter if they were out of sync with the currently operating goal.

    SteveMacenski SteveMacenski commented on code on Oct 30, 2026 22:24 UTC
    Code Review
    nav2_behavior_tree/include/nav2_behavior_tree/bt_action_server_impl.hpp:1
    @@ -409,7 +411,9 @@ void BtActionServer<ActionT, NodeT>::executeCallback()
           "No current goal available when starting BT execution.");
       }
     
    -  if (!current_goal || !loadBehaviorTree(current_goal->behavior_tree)) {
    +  if (!current_goal || !loadBehaviorTree(current_goal->behavior_tree) ||
    +    !on_goal_started_callback_(current_goal))

    Check this is non-null

    SteveMacenski SteveMacenski commented on Oct 30, 2026 22:39 UTC
    Reviewer

    I generally approve of this, however Claude brings up some problems with asynchrony.

    Rather than pass these off as my own, just check out my chat: https://claude.ai/share/7a9377a9-27ce-48fd-b301-cf33544088da

    I don't fully buy into its proposed solutions 100% (lots of new functions to track) but probably brings up legit async issues that need some solution.

    Edit: I just inquired for a smaller change and I see it can be done vastly more simply (though also needs some scrutiny & not using some existing methods like isCurrentNavigator where it probably should). See the chat.

    mini-1235 mini-1235 commented on Oct 31, 2026 07:49 UTC
    Author

    Edit: I just inquired for a smaller change and I see it can be done vastly more simply (though also needs some scrutiny & not using some existing methods like isCurrentNavigator where it probably should). See the chat.

    I don't think this is in the shared link (?)

    mini-1235 mini-1235 commented on code on Oct 31, 2026 09:06 UTC
    Code Review
    nav2_behavior_tree/include/nav2_behavior_tree/bt_action_server_impl.hpp:1
    @@ -409,7 +411,9 @@ void BtActionServer<ActionT, NodeT>::executeCallback()
           "No current goal available when starting BT execution.");
       }
     
    -  if (!current_goal || !loadBehaviorTree(current_goal->behavior_tree)) {
    +  if (!current_goal || !loadBehaviorTree(current_goal->behavior_tree) ||
    +    !on_goal_started_callback_(current_goal))

    Done in 9fc6e27

    mini-1235 mini-1235 commented on code on Oct 31, 2026 09:28 UTC
    Code Review
    nav2_bt_navigator/src/navigators/navigate_to_pose.cpp:1
    @@ -223,32 +236,41 @@ NavigateToPoseNavigator::onPreempt(ActionT::Goal::ConstSharedPtr goal)
     }
     
     bool
    -NavigateToPoseNavigator::initializeGoalPose(ActionT::Goal::ConstSharedPtr goal)
    +NavigateToPoseNavigator::prepareGoalPose(
    +  ActionT::Goal::ConstSharedPtr goal,
    +  geometry_msgs::msg::PoseStamped & current_pose,
    +  geometry_msgs::msg::PoseStamped & goal_pose, std::string & error)
     {
    -  geometry_msgs::msg::PoseStamped current_pose;
       if (!nav2_util::getFreshPose(
           *feedback_utils_.tf, feedback_utils_.global_frame,
           feedback_utils_.robot_frame, clock_->now(),
           transform_staleness_threshold_, current_pose))
       {
    -    bt_action_server_->setInternalError(
    -      ActionT::Result::TF_ERROR,
    -      "Initial robot pose is not available.");
    +    error = "Initial robot pose is not available.";
         return false;
       }
     
    -  geometry_msgs::msg::PoseStamped goal_pose;
       if (!nav2_util::transformPoseInTargetFrame(
           goal->pose, goal_pose, *feedback_utils_.tf, feedback_utils_.global_frame,
           feedback_utils_.transform_tolerance))
       {
    -    bt_action_server_->setInternalError(
    -      ActionT::Result::TF_ERROR,
    -      "Failed to transform a goal pose provided with frame_id '" +
    -      goal->pose.header.frame_id +
    -      "' to the global frame '" +
    -      feedback_utils_.global_frame +
    -      "'.");
    +    error = "Failed to transform a goal pose provided with frame_id '" +
    +      goal->pose.header.frame_id + "' to the global frame '" +
    +      feedback_utils_.global_frame + "'.";
    +    return false;
    +  }
    +
    +  return true;
    +}
    +
    +bool
    +NavigateToPoseNavigator::initializeGoalPose(ActionT::Goal::ConstSharedPtr goal)
    +{
    +  geometry_msgs::msg::PoseStamped current_pose;
    +  geometry_msgs::msg::PoseStamped goal_pose;
    +  std::string error;
    +  if (!prepareGoalPose(goal, current_pose, goal_pose, error)) {
    +    bt_action_server_->setInternalError(ActionT::Result::TF_ERROR, error);
         return false;

    These should be run in quick succession.

    Why? A pending goal can wait a long time, right?

    IMO, the prepareGoalPose serves for two different purposes:

    goalReceived: asks whether to accept this goal at all. We can remove this, but we would end up accepting a bad goal.
    goalStarted: asks for the pose to use right now. I don't think we can remove this.

    SteveMacenski SteveMacenski commented on Nov 03, 2026 03:03 UTC
    Contributor

    https://claude.ai/share/7a9377a9-27ce-48fd-b301-cf33544088da try now. Apparently claude doesn't show you messages after a share link is created, unless manually told to update to include it all.

    LMK what you think. I expect you may take some of that chat and throw it into your own AI to continue it.

    mini-1235 mini-1235 commented on Nov 03, 2026 16:09 UTC
    Author

    Did a few iterations to address the issue while trying to keep the diff small (most of the diff in this PR now is from tests added by my agent), also confirmed that this still fixes the issue I reported. Please take another look!

    mini-1235 mini-1235 commented on Nov 03, 2026 17:07 UTC
    Author
    SteveMacenski SteveMacenski commented on code on Nov 03, 2026 18:39 UTC
    Code Review
    nav2_behavior_tree/include/nav2_behavior_tree/bt_action_server_impl.hpp:1
    @@ -445,12 +429,31 @@ void BtActionServer<ActionT, NodeT>::executeCallback()
           on_loop_callback_();
         };
     
    -  // Execute the BT that was previously created in the configure step
    -  nav2_behavior_tree::BtStatus rc = bt_->run(&tree_, on_loop, is_canceling, bt_loop_duration_);
    +  // Exceptions take the normal completion path so the result is sent and the navigator released
    +  nav2_behavior_tree::BtStatus rc = nav2_behavior_tree::BtStatus::FAILED;
    +  bool started = false;
    +  try {
    +    started = current_goal && loadBehaviorTree(current_goal->behavior_tree) &&
    +      (!on_goal_started_callback_ || on_goal_started_callback_(current_goal));
    +    if (!started) {
    +      if (internal_error_code_ == ActionT::Result::NONE) {
    +        setInternalError(ActionT::Result::UNKNOWN, "Goal failed to start.");
    +      }
    +    } else {
    +      // Execute the BT that was previously created in the configure step
    +      rc = bt_->run(&tree_, on_loop, is_canceling, bt_loop_duration_);
    +    }
    +  } catch (const std::exception & e) {

    I don't understand the try/catch here now. The load cannot throw and I don't think we allow any of the on event callbacks to throw either. Edit: Ah, is this so that the on completion callback is triggered in case the tree itself throws? I guess that makes sense :-)

    Also, does the started conditionals need to move til after the lambdas? I'm not sure why these moved. If we kept at top, then we wouldn't get down here to need the started variable at all.

    I get the attempt to compress it, but I think unless it fixes an async issue we should try to minimize the changes. This compressed alot into the try and started logic is harder to follow. Its not impossible or anything, just not seeing the reason to overcomplicate what is already pretty involved. Validating the goal's state and early exiting I think is the most clear so that the BT running stuff is clear

    SteveMacenski SteveMacenski commented on code on Nov 03, 2026 18:39 UTC
    Code Review
    nav2_behavior_tree/include/nav2_behavior_tree/bt_action_server_impl.hpp:1
    @@ -445,12 +429,31 @@ void BtActionServer<ActionT, NodeT>::executeCallback()
           on_loop_callback_();
         };
     
    -  // Execute the BT that was previously created in the configure step
    -  nav2_behavior_tree::BtStatus rc = bt_->run(&tree_, on_loop, is_canceling, bt_loop_duration_);
    +  // Exceptions take the normal completion path so the result is sent and the navigator released
    +  nav2_behavior_tree::BtStatus rc = nav2_behavior_tree::BtStatus::FAILED;
    +  bool started = false;
    +  try {
    +    started = current_goal && loadBehaviorTree(current_goal->behavior_tree) &&
    +      (!on_goal_started_callback_ || on_goal_started_callback_(current_goal));
    +    if (!started) {
    +      if (internal_error_code_ == ActionT::Result::NONE) {
    +        setInternalError(ActionT::Result::UNKNOWN, "Goal failed to start.");
    +      }
    +    } else {
    +      // Execute the BT that was previously created in the configure step
    +      rc = bt_->run(&tree_, on_loop, is_canceling, bt_loop_duration_);
    +    }
    +  } catch (const std::exception & e) {
    +    setInternalError(
    +      ActionT::Result::UNKNOWN, std::string("Exception during BT execution: ") + e.what());
    +    rc = nav2_behavior_tree::BtStatus::FAILED;
    +  }
     
       // Make sure that the Bt is not in a running state from a previous execution
       // note: if all the ControlNodes are implemented correctly, this is not needed.
    -  bt_->haltAllActions(tree_);
    +  if (started) {

    Why not always do?

    SteveMacenski SteveMacenski commented on code on Nov 03, 2026 18:41 UTC
    Code Review
    nav2_core/include/nav2_core/behavior_tree_navigator.hpp:1
    @@ -120,18 +120,16 @@ class NavigatorMuxer
       /**
        * @brief Start navigating with a given navigator
        * @param string Name of the navigator to start
    +   * @return bool If the navigator holds ownership; false if another navigator holds it
        */
    -  void startNavigating(nav2_core::NavigatorBase * navigator)
    +  bool startNavigating(nav2_core::NavigatorBase * navigator)
       {
         std::scoped_lock l(mutex_);
    -    if (current_navigator_ != nullptr) {
    -      RCLCPP_ERROR(
    -        rclcpp::get_logger("NavigatorMutex"),
    -        "Major error! Navigation requested while another navigation"
    -        " task is in progress! This likely occurred from an incorrect"
    -        "implementation of a navigator plugin.");
    +    if (current_navigator_ != nullptr && current_navigator_ != navigator) {

    Here and L157 using isNavigating do to the null check would make it more semantically understandable.

    SteveMacenski SteveMacenski commented on Nov 03, 2026 18:43 UTC
    Contributor

    Check the chat link, I asked it to check again and found a few more :cry: Some I think are not from this though or might be overblown.

    mini-1235 mini-1235 commented on code on Nov 15, 2026 17:56 UTC
    Code Review
    nav2_core/include/nav2_core/behavior_tree_navigator.hpp:1
    @@ -120,18 +120,16 @@ class NavigatorMuxer
       /**
        * @brief Start navigating with a given navigator
        * @param string Name of the navigator to start
    +   * @return bool If the navigator holds ownership; false if another navigator holds it
        */
    -  void startNavigating(nav2_core::NavigatorBase * navigator)
    +  bool startNavigating(nav2_core::NavigatorBase * navigator)
       {
         std::scoped_lock l(mutex_);
    -    if (current_navigator_ != nullptr) {
    -      RCLCPP_ERROR(
    -        rclcpp::get_logger("NavigatorMutex"),
    -        "Major error! Navigation requested while another navigation"
    -        " task is in progress! This likely occurred from an incorrect"
    -        "implementation of a navigator plugin.");
    +    if (current_navigator_ != nullptr && current_navigator_ != navigator) {

    It would deadlock since isNavigating takes the same mutex

    mini-1235 mini-1235 commented on Nov 16, 2026 09:35 UTC
    Author

    For completeness, I will respond to the five items in the shared link. But I think trying to keep the diff small while also fixing all the issues Claude raised is making it hard for me to iterate on this PR. On top of that, after taking a closer look, I don't think all the issues Claude raised are valid. There might also be many more pre-existing issues unrelated to #6279 that Claude could raise, including some I intentionally reverted earlier to make the review easier.

    I must also admit that in the later iterations (after the async issue), I let Claude lead most of the changes. I mainly reviewed its code and responses, iterated until they made sense to me, and then let it push. On the other hand, in the early stages of this PR, I spent a few hours understanding the issue and coming up with my own solution.

    1. NTP onPreempt failure now reports the previous goal’s waypoints with the wrong error code

    Earlier, I committed 3c3d8cb to address an issue Claude raised, but now it seems to be complaining it about another issue. Since this appears to predate #6279, I would prefer to just revert all the related changes from this PR.

    2. Accepting a same-BT preemption before validating it

    This predates #6279, and I had already reverted the related changes earlier to keep the PR easier to review.

    3. Cross-navigator preemption can still lose to a promoted goal, and is then rejected despite allow_navigator_preemption: true

    This seems like a real issue introduced by this PR. 1c99004 seems to fix it, but it also makes the diff larger, so I am not sure how to proceed here.

    4. Stranded pending goal keeps the muxer held (pre-existing, in SimpleActionServer)

    I am still not sure I understand this issue, even after reading through it multiple times.

    5. Exceptions outside the try still skip completion

    A non-std exception does skip completion, but that is also true on main, so again I think it is out of scope here.

    While I am still happy to help fix this regression, I have to admit that I am a bit lost in this PR and not sure how to proceed.

    Maybe I also need to rethink my personal workflow when working with AI agents. I have only been using them for a few months, so I am still figuring out what works best for me. If you have any suggestions, I would be happy to hear them

    SteveMacenski SteveMacenski commented on code on Nov 21, 2026 00:46 UTC
    Code Review
    nav2_core/include/nav2_core/behavior_tree_navigator.hpp:1
    @@ -120,18 +120,16 @@ class NavigatorMuxer
       /**
        * @brief Start navigating with a given navigator
        * @param string Name of the navigator to start
    +   * @return bool If the navigator holds ownership; false if another navigator holds it
        */
    -  void startNavigating(nav2_core::NavigatorBase * navigator)
    +  bool startNavigating(nav2_core::NavigatorBase * navigator)
       {
         std::scoped_lock l(mutex_);
    -    if (current_navigator_ != nullptr) {
    -      RCLCPP_ERROR(
    -        rclcpp::get_logger("NavigatorMutex"),
    -        "Major error! Navigation requested while another navigation"
    -        " task is in progress! This likely occurred from an incorrect"
    -        "implementation of a navigator plugin.");
    +    if (current_navigator_ != nullptr && current_navigator_ != navigator) {

    How about recursive_mutex then?

    SteveMacenski SteveMacenski commented on Nov 21, 2026 01:03 UTC
    Contributor

    Sorry for the delay, I had Josh starting in the office for onboarding as a maintainer this week so I was busy getting him up to speed. This is a pretty key priority since this is a major regression. Annoying, the US has a holiday on Thursday and then I'm traveling Friday for a couple of weeks so I'm going to have to follow up with you on this as I'm on-the-go.

    I'm aware that some of the Claude commentary is not valid / correct, but some of it is. That's more what I'm focused on. Don't take it as word-of-truth and I'm expecting all of them to be valid / resolved.

    This comment is answering your other components, the technical 1-5 analysis is in the comment below this one.

    While I am still happy to help fix this regression, I have to admit that I am a bit lost in this PR and not sure how to proceed. If you have any suggestions, I would be happy to hear them

    I can completely understand that, this is _very_ complicated. In general for something like this, I would probably not opt to use agents to implement since understanding the flow is pretty important to finding a viable solution & most agents are going to have problems with the context of this much code in this many different files/locations. I would probably use it to help me validate my solution and code, but not the actual understanding of the issue and my preliminary solution.

    I'm thinking maybe we should revert https://github.com/ros-navigation/navigation2/pull/6279 at least on Lyrical immediately, if not on Rolling as well. This is too big of a regression to let sit. I think it was a nice ergonomic improvement for @redvinaa 's needs but I think he would also agree that this is a big bug and needs to be solved before that work can be kept in.

    ---

    As for next steps, I'm wondering maybe if we should tackle this from another perspective. Lets pretend that we reverted #6279 so we're back to how things were before. How would we go about implementing it again knowing what we know now? Maybe we choose to go down a different path in a different location.

    Or if we think we can get this over the line with 1-2 more pushes, then I think this so far looks quite close to what I'd expect a solution at least down this direction would look like.

    SteveMacenski SteveMacenski commented on Nov 21, 2026 01:34 UTC
    Contributor

    With respect to your 1-5:

    1 & 2. The AI says we should call prepareGoalPose in the 2x navigators before we do initializeGoalPose(bt_action_server_->acceptPendingGoal());. It says basically to invert the ordering so that we validate the goal before we switch to it. But to actually hit it, the already-passed check would have to fail within a few milliseconds later. Highly unlikely.

    If we did this, then having initializeGoalPose also call prepareGoalPose would be unnecessary and redundant for this case - which I did not ask for or model in the AI to make this diff small and readable. Note that probably don't need to change some of the things like exceptions text / add excessive comments.

    --- a/nav2_bt_navigator/src/navigators/navigate_through_poses.cpp
    +++ b/nav2_bt_navigator/src/navigators/navigate_through_poses.cpp
    @@ -243,10 +243,20 @@ NavigateThroughPosesNavigator::onPreempt(ActionT::Goal::ConstSharedPtr goal)
         // accept the pending goal if the current goal is running the default BT file
    +    // Validate before accepting, since accepting aborts the current goal
    +    geometry_msgs::msg::PoseStamped current_pose;
    +    nav_msgs::msg::Goals goals;
    +    std::string error;
    +    if (!prepareGoalPoses(goal, current_pose, goals, error)) {
    +      RCLCPP_WARN(
    +        logger_,
    +        "Preemption request was rejected: %s For now, continuing to track the last goal "
    +        "until completion.", error.c_str());
    +      bt_action_server_->terminatePendingGoal();
    +      return;
    +    }
         if (!initializeGoalPoses(bt_action_server_->acceptPendingGoal())) {
    -      throw std::runtime_error(
    -        "Preemption request was rejected since the goal poses could not be "
    -        "transformed.");
    +      throw std::runtime_error("Failed to initialize the preempting goal.");
         }
       } else {
    @@ -296,6 +306,8 @@ NavigateThroughPosesNavigator::prepareGoalPoses(
     bool
     NavigateThroughPosesNavigator::initializeGoalPoses(ActionT::Goal::ConstSharedPtr goal)
     {
    +  // Never report a previous goal's waypoint statuses if initialization fails
    +  goal_initialized_ = false;
       geometry_msgs::msg::PoseStamped current_pose;
    
    --- a/nav2_bt_navigator/src/navigators/navigate_to_pose.cpp
    +++ b/nav2_bt_navigator/src/navigators/navigate_to_pose.cpp
    @@ -16,6 +16,7 @@
     #include <limits>
    +#include <stdexcept>
     #include "nav2_bt_navigator/navigators/navigate_to_pose.hpp"
    @@ -216,12 +217,19 @@ NavigateToPoseNavigator::onPreempt(ActionT::Goal::ConstSharedPtr goal)
         // accept the pending goal if the current goal is running the default BT file
    -    if (!initializeGoalPose(bt_action_server_->acceptPendingGoal())) {
    +    // Validate before accepting, since accepting aborts the current goal
    +    geometry_msgs::msg::PoseStamped current_pose, goal_pose;
    +    std::string error;
    +    if (!prepareGoalPose(goal, current_pose, goal_pose, error)) {
           RCLCPP_WARN(
             logger_,
    -        "Preemption request was rejected since the goal pose could not be "
    -        "transformed. For now, continuing to track the last goal until completion.");
    +        "Preemption request was rejected: %s For now, continuing to track the last goal "
    +        "until completion.", error.c_str());
           bt_action_server_->terminatePendingGoal();
    +      return;
    +    }
    +    if (!initializeGoalPose(bt_action_server_->acceptPendingGoal())) {
    +      throw std::runtime_error("Failed to initialize the preempting goal.");
         }
       } else {
    

    3. AI claims you fixed that, so we're good here.

    4. This is not introduced by this PR. However this would be the fix:

    --- a/nav2_ros_common/include/nav2_ros_common/simple_action_server.hpp
    +++ b/nav2_ros_common/include/nav2_ros_common/simple_action_server.hpp
    @@ void handle_accepted(const std::shared_ptr<rclcpp_action::ServerGoalHandle<ActionT>> handle)
         std::lock_guard<std::recursive_mutex> lock(update_mutex_);
         debug_msg("Receiving a new goal");
     
    -    if (is_active(current_handle_) || is_running()) {
    +    // A worker that already decided to exit will never pick up a pending goal
    +    if (is_active(current_handle_) || (is_running() && !worker_done_)) {
           debug_msg("An older goal is active, moving the new goal to a pending slot.");
     ...
           current_handle_ = handle;
     
           // Return quickly to avoid blocking the executor, so spin up a new thread
           debug_msg("Executing goal asynchronously.");
    +      worker_done_ = false;
           execution_future_ = std::async(
    @@ void work()
           } catch (std::exception & ex) {
             RCLCPP_ERROR(
               node_logging_interface_->get_logger(),
               "Action server failed while executing action callback: \"%s\"", ex.what());
    +        std::lock_guard<std::recursive_mutex> lock(update_mutex_);
             terminate_all();
             if (completion_callback_) {completion_callback_();}
    +        worker_done_ = true;
             return;
           }
    @@
           if (stop_execution_) {
             warn_msg("Stopping the thread per request.");
             terminate_all();
             if (completion_callback_) {completion_callback_();}
    +        worker_done_ = true;
             break;
           }
    @@
           } else {
             debug_msg("Done processing available goals.");
    +        worker_done_ = true;
             break;
           }
    @@
       std::future<void> execution_future_;
       bool stop_execution_{false};
    +  bool worker_done_{true};
    

    5. I think this is a theoretical issue, not a real one. No completion callback, nor halt all actions can throw. You can simply ignore this.

    ---

    I asked for a full clean review from an independent agent and came back with the same issues beyond the solutions above, so I think with this it should be good to go from the agent-review-hell unless you see more issues?

    After we agree on all of this, I will also spend the time with my own human brain to justify these changes to myself so we're not just trusting AI. I don't let the robots think for me, even if they're helpful. Making sure this is correct and in good developer taste is kind of my job :laughing:

    mergify[bot] mergify[bot] commented on Nov 24, 2026 21:02 UTC
    Bot

    This pull request is in conflict. Could you fix it @mini-1235?

    mini-1235 mini-1235 commented on Nov 29, 2026 15:11 UTC
    Author

    Sorry for the delay, I had Josh starting in the office for onboarding as a maintainer this week so I was busy getting him up to speed. This is a pretty key priority since this is a major regression. Annoying, the US has a holiday on Thursday and then I'm traveling Friday for a couple of weeks so I'm going to have to follow up with you on this as I'm on-the-go.

    Same here :( It is nearly the end of the year and I have a few deadlines to prioritize, so I can only work on big PRs like this one on weekends. Sorry about that.

    I am leaning toward reverting #6279 rather than continuing with this PR. Honestly, I don't think I have the time or the interest to keep iterating on it until we are both happy with the result.

    If I may make a couple of suggestions for the review process:

  • If Claude reviews the whole PR and has suggestions, it would be much easier for me if they were posted as inline comments, the way a human reviewer would. Long chat comments are really hard for me to follow and respond to. When I get those, I would rather just have my own agent respond, and then it turns into agent to agent, with me only reviewing at the end once both agents are satisfied.

  • I think it is important to define what should and shouldn't be fixed in a given PR. With human-only reviews, a reviewer might spot a few issues that predate the PR. But AI is very good at finding those, but it also sometimes flags issues that don't make sense, especially when it is only reading the code and the PR is this complicated. If I tried to address all of them, it would be very tiring, and I think the result would often be harder for the reviewer to follow as well.
  • I know these are quite subjective, and I am definitely not criticizing the workflow here. Honestly, I feel this PR has grown too complicated, and I am not confident in it. So I think the best path is to close this PR(if you agree), revert the original one, and let someone else pick up the original issue if they are interested

    Reviewers
    Assignees
    mini-1235 mini-1235
    Labels
    risk: low confidence: 81.7% 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: 86.6% (HIGH) · Higher = larger blast radius
    86.6%
    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: 81.7% · Lower = rushed or shallow review
    81.7%
    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: 15.9% · Safe to merge
    15.9%