Fix navigator state mutation before preemption validation #6646
Note that this is not directly related to the regression, but rather an issue I noticed with how pending goals are handled. For example:
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.
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 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>
</details>
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).
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 toinitializeGoalPoseto reject, checking ifbt_action_server_is actively processing a goal (or the muxer) and if so check on the request's fields like inonPreempt?
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
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.
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?
Should this be a required implementation? This is the only one that has a default implementation. I think this should be strictly required
What does this buy us?
Isn't on goal received still already run? This would mean we call it twice, no?
Similarly, what does this buy us if the muxer is working properly?
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.
Without this, every same-navigator preemption calls startNavigating while this navigator already owns the muxer. That logs a false "Major error".
Agreed. Will update today
Similar to https://github.com/ros-navigation/navigation2/pull/6646#discussion_r4425464819. Without this, stopNavigating would log a false "Major error".
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
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
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.
Check this is non-null
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.
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 (?)
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.
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.
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!
Failing test should be fixed by https://github.com/ros-navigation/navigation2/pull/6740
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
Why not always do?
Here and L157 using isNavigating do to the null check would make it more semantically understandable.
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.
It would deadlock since isNavigating takes the same mutex
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
How about recursive_mutex then?
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.
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:
This pull request is in conflict. Could you fix it @mini-1235?
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:
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
mini-1235
<!-- 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
goalReceivednow only validates the goal (TF lookups). It no longer changes the running BT'sblackboard or feedback. Reception-time TF validation from #6279 is kept.
New pure virtual
goalStartedhook onBehaviorTreeNavigator.BtActionServercalls it when agoal starts executing, including a pending goal promoted after the current one completes. It
initializes the blackboard.
NavigatorMuxer::startNavigatingis now atomic and returnsfalseif another navigator owns themuxer, instead of logging "Major error!" and taking it over.
Cross-navigator preemption (
allow_navigator_preemption) retriespreemptCurrentNavigator()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, soa 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:
goalStartedis pure virtual, so externalBehaviorTreeNavigatorplugins mustimplement 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 testfornav2_core,nav2_bt_navigatorandnav2_behavior_treepasses, excepttest_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 promotionalso 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
onPreemptaccepts first, so a late TF failure aborts the current goal, andNavigateThroughPosesthrows). This predates #6279.Follow-up PR:
NavigateThroughPosescan keep stale waypoints when a preemption fails. Thispredates #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 clutterI 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 -->
backport-*.