feat: run detour planning on a worker thread so cancel doesn't block the control loop

DetourPathRecovery was the one recovery behavior that mattered for the
onCancelRequested() fix in recovery_core (commit 254c7fc): it calls
SBPLDetourPlanner::makePlan() synchronously from update(), which runs on
the control thread — cancel arriving mid-search had nothing to preempt it
with, and the control loop itself would stall for the remainder of
allocated_time.

- Moves the search to a per-attempt worker thread (startWorker/workerBody/
  planInto/finishAttempt/waitWorker/joinWorker/requestWorkerStop); update()
  only polls.
- onCancelRequested() (new override): preempts via
  robot_nav_core::Preemptable if the inner planner supports it (see
  Test/sbpl_lattice_planner), then waits up to cancel_join_timeout (0.2 s)
  and joins — cancel now actually blocks until the worker is gone, not
  just until a flag is set.
- onStart() joins a stale worker from a previous attempt before starting a
  new one; destructor joins too.
- async_planning param (default true) so tests can force the old
  synchronous path when they need deterministic single-thread timing.
- Uses RECOVERY_CORE_EXPORT_BEHAVIOR for the ABI version symbol.
- test/plugins/test_line_planner.cpp: added plan_delay (simulate a slow
  search) and made it Preemptable, exported as TestSlowPlanner, to drive
  the new worker-thread cancel tests.

Depends on recovery_core commit 254c7fc (onCancelRequested hook + ABI
macro) and Test/sbpl_lattice_planner commit 7456e99 (Preemptable pattern
this follows).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
2026-09-12 22:06:50 +07:00
parent 8f9326be04
commit ea79686eef
4 changed files with 400 additions and 19 deletions

View File

@@ -21,12 +21,17 @@
*********************************************************************/
#include <algorithm>
#include <atomic>
#include <chrono>
#include <cmath>
#include <condition_variable>
#include <cstddef>
#include <functional>
#include <limits>
#include <memory>
#include <mutex>
#include <string>
#include <thread>
#include <vector>
#include <boost/dll/alias.hpp>
@@ -41,10 +46,12 @@
#include <robot_costmap_2d/costmap_2d.h>
#include <robot_costmap_2d/costmap_2d_robot.h>
#include <robot_nav_core/base_global_planner.h>
#include <robot_nav_core/preemptable.h>
#include <robot_tf3_geometry_msgs/tf3_geometry_msgs.h>
#include <tf3/buffer_core.h>
#include <recovery_core/adapters/costmap_collision_checker.h>
#include <recovery_core/recovery_abi.h>
#include <recovery_core/recovery_behavior.h>
#include <sbpl_recovery/merge_grids.h>
@@ -216,6 +223,40 @@ public:
return recovery_core::RecoveryOutputType::kPath;
}
~DetourPathRecovery() override
{
// Worker có thể còn chạy nếu lượt bị huỷ mà planner không preempt được: cắt rồi join — huỷ
// object trong lúc worker còn đụng member là use-after-free.
requestWorkerStop();
joinWorker();
}
/**
* @brief Hook đồng bộ khi bị huỷ (recovery_core, 2026-09-11): cắt lượt makePlan đang chạy.
*
* Chạy trên control thread. `preempt()` trên planner (nếu nó là Preemptable) làm ARA* thoát trong
* vài ms; đợi worker tối đa `cancel_join_timeout` rồi join. Quá trần = planner không tuân preempt
* (libsbpl cũ, hoặc plugin khác) — log LỖI, không tắt được; worker được join ở onStart kế/dtor.
*/
void onCancelRequested() override
{
if (!workerRunning())
{
return;
}
requestWorkerStop();
if (!waitWorker(cancel_join_timeout_))
{
robot::log_error("[sbpl_recovery] '%s': planner '%s' did not return %.2f s after preempt — "
"the cancelled search keeps running in the background (does the planner "
"implement robot_nav_core::Preemptable, and does libsbpl have the abort "
"flag?).",
name().c_str(), planner_name_.c_str(), cancel_join_timeout_);
return;
}
joinWorker();
}
protected:
bool onConfigure(robot::NodeHandle& nh) override
{
@@ -233,6 +274,12 @@ protected:
// này không còn nối vào tuyến cũ nữa. Để nguyên trong YAML thì vô hại (không ai đọc), nhưng
// nên dọn để khỏi có người chỉnh rồi chờ hiệu ứng không bao giờ tới.
nh.param("attempts_per_run", attempts_per_run_, kDefaultAttemptsPerRun);
// [s] Trần đợi worker thoát khi bị cancel/pause. Với planner preempt được là vài ms; đặt đủ dư.
nh.param("cancel_join_timeout", cancel_join_timeout_, 0.2);
// true (mặc định): makePlan chạy trên worker thread, control thread không kẹt. false: chạy
// đồng bộ trong onUpdate như trước 2026-09-11 — chỉ cho planner giả tức thì trong unit test,
// hoặc đường lùi khi cần tái hiện hành vi cũ.
nh.param("async_planning", async_planning_, true);
nh.param("max_deviation", max_deviation_, 0.0);
// "reference" | "current". Xem @ref rejoin_on_ và RecoveryContext::reference_plan.
nh.param("rejoin_on", rejoin_on_, std::string("reference"));
@@ -444,12 +491,47 @@ protected:
return false;
}
// Worker của lượt trước (bị huỷ mà planner không preempt được) phải xong trước khi lập lại:
// nó còn đụng merged_grid_/planner_. Join có trần; quá trần thì từ chối khởi động thay vì đua.
if (workerRunning())
{
requestWorkerStop();
if (!waitWorker(cancel_join_timeout_))
{
robot::log_error("[sbpl_recovery] '%s': previous planning worker still running after "
"%.2f s — refusing to start a new run on top of it.",
name().c_str(), cancel_join_timeout_);
return false;
}
joinWorker();
}
attempt_ = 0;
return true;
}
/**
* @brief Một tick. Từ 2026-09-11 lượt makePlan chạy trên WORKER THREAD: control thread chỉ chuẩn
* bị (pose, đích, lưới gộp), khởi động, rồi mỗi tick poll — không bao giờ kẹt trong SBPL,
* nên cancel/pause của host tới được ngay cycle kế. Hợp lệ với THREADING.md: behavior họ
* kPath không phát vận tốc, bất biến "chỉ control thread phát cmd_vel" không bị chạm.
*/
recovery_core::RecoveryResult onUpdate(const robot::Time& now, double /*dt*/) override
{
// --- Worker đang chạy: poll --------------------------------------------------------------
if (workerRunning())
{
if (!workerDone())
{
return recovery_core::RecoveryResult::Running()
.withProgress(progressNow(), remainingNow())
.withMessage("planning attempt " + std::to_string(attempt_ + 1) + "/" +
std::to_string(attempts_per_run_) + " in progress");
}
joinWorker();
return finishAttempt(now);
}
if (attempt_ >= static_cast<std::size_t>(attempts_per_run_))
{
return recovery_core::RecoveryResult::Failed()
@@ -458,6 +540,7 @@ protected:
std::to_string(attempts_per_run_) + " attempt(s)");
}
// --- Chuẩn bị một attempt trên control thread ------------------------------------------
// Pose lấy TƯƠI mỗi lượt thử: behavior trước đó trong route (rotate/back_up) có thể đã dời
// robot; và mất pose giữa chừng phải kết thúc lượt, không dùng pose cũ.
robot_geometry_msgs::PoseStamped start;
@@ -467,25 +550,81 @@ protected:
}
robot_geometry_msgs::PoseStamped goal;
std::vector<robot_geometry_msgs::PoseStamped> detour;
bool planned = false;
try
{
goal = toFrame(goal_in_plan_, costmap_frame_);
}
catch (const std::exception& ex)
{
robot::log_warning("[sbpl_recovery] '%s': attempt %zu/%d: goal frame conversion threw: %s",
name().c_str(), attempt_ + 1, attempts_per_run_, ex.what());
++attempt_;
return recovery_core::RecoveryResult::Running()
.withProgress(progressNow(), remainingNow())
.withMessage("goal could not be expressed in the costmap frame");
}
if (merged_active_)
{
// Lưới gộp: chụp lại bản TƯƠI trước từng attempt (mutex chỉ bị giữ trong lúc copy), rồi
// SBPL search trên bản chụp — KHÔNG giữ mutex costmap nào, map update không bị bỏ đói dù
// attempt thua đốt trọn allocated_time. Chụp trên control thread; worker chỉ đọc.
if (!buildMergedGrid())
{
return recovery_core::RecoveryResult::Failed()
.withMessage("could not rebuild the merged grid (TF/costmap unavailable)");
}
set_external_grid_(planner_.get(), &merged_grid_);
}
if (!async_planning_)
{
// Đường đồng bộ: cùng thân với worker nhưng chạy ngay trên thread này.
worker_start_ = start;
worker_goal_ = goal;
worker_detour_.clear();
worker_stop_.store(false, std::memory_order_relaxed);
planInto(worker_planned_, worker_detour_);
return finishAttempt(now);
}
startWorker(start, goal);
return recovery_core::RecoveryResult::Running()
.withProgress(progressNow(), remainingNow())
.withMessage("planning attempt " + std::to_string(attempt_ + 1) + "/" +
std::to_string(attempts_per_run_) + " started");
}
private:
// ================================================================================================
// Worker thread cho một attempt (2026-09-11)
// ================================================================================================
void startWorker(const robot_geometry_msgs::PoseStamped& start,
const robot_geometry_msgs::PoseStamped& goal)
{
worker_start_ = start;
worker_goal_ = goal;
worker_detour_.clear();
worker_planned_ = false;
worker_stop_.store(false, std::memory_order_relaxed);
{
std::lock_guard<std::mutex> lock(worker_mutex_);
worker_done_ = false;
}
worker_running_ = true;
worker_ = std::thread(&DetourPathRecovery::workerBody, this);
}
/// @brief Một lượt makePlan với đúng giao thức khoá cũ. Dùng chung cho worker và đường đồng bộ.
void planInto(bool& planned_out, std::vector<robot_geometry_msgs::PoseStamped>& detour_out)
{
bool planned = false;
try
{
if (merged_active_)
{
// Lưới gộp: chụp lại bản TƯƠI trước từng attempt (mutex chỉ bị giữ trong lúc copy), rồi
// SBPL search trên bản chụp — KHÔNG giữ mutex costmap nào, map update không bị bỏ đói dù
// attempt thua đốt trọn allocated_time.
if (!buildMergedGrid())
{
return recovery_core::RecoveryResult::Failed()
.withMessage("could not rebuild the merged grid (TF/costmap unavailable)");
}
set_external_grid_(planner_.get(), &merged_grid_);
planned = planner_->makePlan(start, goal, detour);
planned = planner_->makePlan(worker_start_, worker_goal_, detour_out);
}
// Cùng giao thức khoá với PlannerRunner/gen-1: map-update thread ghi lưới dưới mutex này,
// planner đọc lưới sống thì phải giữ nó. Chỉ unit test với costmap placeholder được tắt.
@@ -494,19 +633,83 @@ protected:
robot_costmap_2d::Costmap2DROBOT* costmap = chosenCostmap();
boost::unique_lock<robot_costmap_2d::Costmap2D::mutex_t> lock(
*(costmap->getCostmap()->getMutex()));
planned = planner_->makePlan(start, goal, detour);
planned = planner_->makePlan(worker_start_, worker_goal_, detour_out);
}
else
{
planned = planner_->makePlan(start, goal, detour);
planned = planner_->makePlan(worker_start_, worker_goal_, detour_out);
}
}
catch (const std::exception& ex)
{
// Exception thoát khỏi thân thread là std::terminate — bắt ở đây, báo như một attempt hỏng.
robot::log_warning("[sbpl_recovery] '%s': attempt %zu/%d threw: %s", name().c_str(),
attempt_ + 1, attempts_per_run_, ex.what());
planned = false;
}
catch (...)
{
robot::log_warning("[sbpl_recovery] '%s': attempt %zu/%d threw an unknown exception",
name().c_str(), attempt_ + 1, attempts_per_run_);
planned = false;
}
// Lượt bị cắt thì kết quả (nếu có) không phải thứ ai yêu cầu.
planned_out = planned && !worker_stop_.load(std::memory_order_relaxed);
}
void workerBody()
{
planInto(worker_planned_, worker_detour_);
{
std::lock_guard<std::mutex> lock(worker_mutex_);
worker_done_ = true;
}
worker_cv_.notify_all();
}
bool workerRunning() const
{
return worker_running_;
}
bool workerDone()
{
std::lock_guard<std::mutex> lock(worker_mutex_);
return worker_done_;
}
/// @return true nếu worker đã xong trong @p seconds.
bool waitWorker(double seconds)
{
std::unique_lock<std::mutex> lock(worker_mutex_);
return worker_cv_.wait_for(lock, std::chrono::duration<double>(seconds),
[this] { return worker_done_; });
}
void joinWorker()
{
if (worker_.joinable())
{
worker_.join();
}
worker_running_ = false;
}
/// @brief Cắt lượt đang chạy: preempt planner (nếu hỗ trợ) + cờ vứt kết quả.
void requestWorkerStop()
{
worker_stop_.store(true, std::memory_order_relaxed);
if (auto* p = dynamic_cast<robot_nav_core::Preemptable*>(planner_.get()))
{
p->preempt();
}
}
/// @brief Phần sau makePlan (guard lệch tuyến, đổi frame, nộp path) — chạy trên control thread.
recovery_core::RecoveryResult finishAttempt(const robot::Time& now)
{
const bool planned = worker_planned_;
std::vector<robot_geometry_msgs::PoseStamped>& detour = worker_detour_;
if (planned && !detour.empty() && max_deviation_ > 0.0)
{
@@ -593,7 +796,6 @@ protected:
std::to_string(attempts_per_run_) + " failed");
}
private:
robot_costmap_2d::Costmap2DROBOT* chosenCostmap() const
{
return use_global_costmap_ ? ctx().global_costmap : ctx().local_costmap;
@@ -913,8 +1115,21 @@ private:
std::string costmap_frame_;
std::size_t attempt_ = 0;
// --- Worker thread của một attempt (2026-09-11) ---------------------------------------------
double cancel_join_timeout_ = 0.2; ///< [s] trần đợi worker thoát sau preempt.
bool async_planning_ = true; ///< false = makePlan đồng bộ trong onUpdate (test/đường lùi).
std::thread worker_;
bool worker_running_ = false; ///< chỉ control thread đọc/ghi.
std::mutex worker_mutex_;
std::condition_variable worker_cv_;
bool worker_done_ = false; ///< dưới worker_mutex_.
std::atomic<bool> worker_stop_{false};
robot_geometry_msgs::PoseStamped worker_start_;
robot_geometry_msgs::PoseStamped worker_goal_;
std::vector<robot_geometry_msgs::PoseStamped> worker_detour_; ///< worker ghi, control đọc sau join.
bool worker_planned_ = false; ///< như trên.
};
} // namespace sbpl_recovery
BOOST_DLL_ALIAS(sbpl_recovery::DetourPathRecovery::create, DetourPathRecovery)
RECOVERY_CORE_EXPORT_BEHAVIOR(sbpl_recovery::DetourPathRecovery::create, DetourPathRecovery)