feat: preempt a running search via robot_nav_core::Preemptable + sbpl abort flag

- Implements Preemptable::preempt() (atomic store), checked between the up
  to 3 internal ARA* runs a single makePlan() can do (free_start_heading
  retry, realign) — the runs now share one time budget instead of each
  getting the full allocated_time, and a preempt between runs stops the
  next one from starting (kMinReplanBudget floor so a preempt right at the
  edge still gets a minimal attempt).
- Probes for the vendored sbpl's abort flag at runtime via
  dlsym(RTLD_DEFAULT, "sbpl_abort_flag_abi_version") before touching
  set_abort_flag() — logs an error if the header advertises the flag but
  the loaded .so doesn't (header/lib version mismatch), a warning if built
  against an sbpl without the flag at all (falls back to the old
  run-to-allocated_time behaviour, no crash).
- primitive_filename now resolves relative to PNKX_NAV_CORE_CONFIG_DIR
  instead of only working from one dev machine's absolute path.
- CMakeLists.txt: target_include_directories(... BEFORE PRIVATE
  ${SBPL_INCLUDE_DIRS}) so this package's own sbpl header wins over a
  same-named one pulled in transitively (apt ros-noetic-sbpl in
  /opt/ros/noetic/include has no abort flag and was winning silently);
  configure-time check for SBPL_HAS_ABORT_FLAG in the resolved header with
  a loud warning if missing.

Depends on Test/sbpl commit bd89924 (the abort flag itself) and
pnkx_nav_core commit 2b0993b (robot_nav_core::Preemptable header).

Measured on the dev machine (2026-09-12, apt ros-noetic-sbpl removed,
rebuilt): "preempted after N ms" with N in the tens of ms instead of
running to allocated_time (was up to 9 s). Full numbers:
Test/move_base2/docs/PLAN_LIFECYCLE_CANCEL_PAUSE_RESUME.md section 6.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
2026-09-12 22:06:30 +07:00
parent 9c1667eb3c
commit 7456e99372
3 changed files with 172 additions and 6 deletions

View File

@@ -38,6 +38,9 @@
#include <sbpl_lattice_planner/sbpl_lattice_planner.h>
#include <cmath>
#include <cstdlib>
#include <dlfcn.h>
#include <unistd.h>
#include <robot_nav_msgs/Path.h>
@@ -114,6 +117,37 @@ bool SBPLLatticePlanner::initialize(std::string name, robot_costmap_2d::Costmap2
private_nh.param("primitive_filename",primitive_filename_,string(""));
private_nh.param("force_scratch_limit",force_scratch_limit_,500);
// Đường dẫn TƯƠNG ĐỐI của file mprim được giải theo cây config đang chạy (2026-09-11), cùng thứ
// tự NodeHandle dùng: PNKX_NAV_CORE_CONFIG_DIR rồi PNKX_NAV_CORE_DIR/config. Trước đây YAML phải
// ghi đường dẫn tuyệt đối — máy dev chép sang robot là gãy (`/home/duongtd/rl_ws/...`).
if (!primitive_filename_.empty() && primitive_filename_[0] != '/' &&
access(primitive_filename_.c_str(), R_OK) != 0)
{
std::vector<std::string> candidates;
if (const char* cfg = std::getenv("PNKX_NAV_CORE_CONFIG_DIR"))
candidates.push_back(std::string(cfg) + "/" + primitive_filename_);
if (const char* root = std::getenv("PNKX_NAV_CORE_DIR"))
candidates.push_back(std::string(root) + "/config/" + primitive_filename_);
bool resolved = false;
for (const std::string& c : candidates)
{
if (access(c.c_str(), R_OK) == 0)
{
robot::log_info("[sbpl_lattice_planner] primitive_filename '%s' resolved to '%s'",
primitive_filename_.c_str(), c.c_str());
primitive_filename_ = c;
resolved = true;
break;
}
}
if (!resolved)
{
robot::log_error("[sbpl_lattice_planner] primitive_filename '%s' is relative and was not "
"found under PNKX_NAV_CORE_CONFIG_DIR or PNKX_NAV_CORE_DIR/config",
primitive_filename_.c_str());
}
}
double nominalvel_mpersecs, timetoturn45degsinplace_secs;
private_nh.param("nominalvel_mpersecs", nominalvel_mpersecs, 0.4);
private_nh.param("timetoturn45degsinplace_secs", timetoturn45degsinplace_secs, 0.6);
@@ -242,6 +276,35 @@ bool SBPLLatticePlanner::initialize(std::string name, robot_costmap_2d::Costmap2
exit(1);
}
// Preempt (2026-09-11) cần libsbpl có abort flag. Header nói có (SBPL_HAS_ABORT_FLAG) chưa đủ:
// .so nạp lúc chạy có thể là bản cũ (ros-noetic-sbpl 2020 ở /opt/ros) — layout SBPLPlanner khác,
// chạm vào set_abort_flag() là ghi đè member đầu của ARAPlanner. Probe symbol trước, không có thì
// TUYỆT ĐỐI không đụng cờ và nói to: cancel sẽ không cắt được lượt đang chạy.
sbpl_abort_supported_ = false;
#ifdef SBPL_HAS_ABORT_FLAG
{
using ProbeFn = int (*)();
void* sym = dlsym(RTLD_DEFAULT, "sbpl_abort_flag_abi_version");
if (sym != nullptr && reinterpret_cast<ProbeFn>(sym)() == SBPL_ABORT_FLAG_ABI_VERSION)
{
sbpl_abort_supported_ = true;
planner_->set_abort_flag(&preempt_);
robot::log_info("[sbpl_lattice_planner] libsbpl abort flag: supported — cancel/pause can "
"interrupt a running search");
}
else
{
robot::log_error("[sbpl_lattice_planner] compiled against an sbpl header with abort flag "
"but the loaded libsbpl.so has no sbpl_abort_flag_abi_version (old library "
"on the load path?) — preempt DISABLED, a cancelled search runs to "
"allocated_time. Fix the install so one libsbpl is used.");
}
}
#else
robot::log_warning("[sbpl_lattice_planner] built against an sbpl without abort flag — "
"cancel/pause cannot interrupt a running search (runs to allocated_time)");
#endif
robot::log_info("[sbpl_lattice_planner] Initialized successfully");
// plan_pub_ = private_nh.advertise<nav_msgs::Path>("plan", 1);
// stats_publisher_ = private_nh.advertise<sbpl_lattice_planner::SBPLLatticePlannerStats>("sbpl_lattice_planner_stats", 1);
@@ -299,6 +362,10 @@ bool SBPLLatticePlanner::makePlan(const robot_geometry_msgs::PoseStamped& start,
return false;
}
// Mỗi lượt bắt đầu với cờ preempt SẠCH: một preempt nhắm vào lượt trước không được giết lượt này
// (contract robot_nav_core::Preemptable). Cờ đã gắn vào planner_ ở initialize() nếu libsbpl hỗ trợ.
preempt_.store(false, std::memory_order_relaxed);
// Lưới cell đang có hiệu lực: bản chụp ngoài (detour trên lưới gộp) hoặc lưới sống. Footprint,
// inflation và frame vẫn thuộc costmap sống — lưới ngoài bắt buộc cùng kích thước với nó.
const robot_costmap_2d::Costmap2D* grid = activeGrid();
@@ -448,20 +515,38 @@ bool SBPLLatticePlanner::makePlan(const robot_geometry_msgs::PoseStamped& start,
robot::log_debug("[sbpl_lattice_planner] run planner");
const robot::Time plan_started = robot::Time::now();
// NGÂN SÁCH CHUNG (2026-09-11): `allocated_time` là trần của CẢ lượt makePlan, không phải của
// từng lượt replan nội bộ. Trước đây ba lượt (free heading → heading thật → căn lại heading) mỗi
// lượt được cấp lại nguyên allocated_time, trần thật là 3x — 30 s với config 10 s, và
// PlannerRunner giữ costmap mutex suốt chừng ấy. Lượt sau chỉ chạy khi còn >= kMinReplanBudget.
constexpr double kMinReplanBudget = 0.5; // [s] dưới mức này một lượt ARA* không kịp ra gì
const auto budget_left = [&]() {
return allocated_time_ - (robot::Time::now() - plan_started).toSec();
};
vector<int> solution_stateIDs;
int solution_cost;
try{
int ret = planner_->replan(allocated_time_, &solution_stateIDs, &solution_cost);
if(!ret && start_heading_overridden){
if(preempt_.load(std::memory_order_relaxed)){
robot::log_info("[sbpl_lattice_planner] preempted after %.0f ms (first search)",
(robot::Time::now() - plan_started).toSec() * 1000.0);
return false;
}
if(!ret && start_heading_overridden && budget_left() >= kMinReplanBudget){
// Heading giả định có thể không khả thi (vd hướng tới goal đâm thẳng vào tường
// ngay tại cell xuất phát) — thử lại MỘT lần với heading thật trước khi bỏ cuộc.
robot::log_warning("[sbpl_lattice_planner] no solution with free start heading, "
"retrying with actual robot heading");
"retrying with actual robot heading (%.2f s left)", budget_left());
int sid = env_->SetStart(start.pose.position.x - grid->getOriginX(),
start.pose.position.y - grid->getOriginY(),
theta_start_actual);
if(sid >= 0 && planner_->set_start(sid) != 0){
ret = planner_->replan(allocated_time_, &solution_stateIDs, &solution_cost);
ret = planner_->replan(budget_left(), &solution_stateIDs, &solution_cost);
}
if(preempt_.load(std::memory_order_relaxed)){
robot::log_info("[sbpl_lattice_planner] preempted after %.0f ms (heading retry)",
(robot::Time::now() - plan_started).toSec() * 1000.0);
return false;
}
}
if(ret)
@@ -546,8 +631,19 @@ bool SBPLLatticePlanner::makePlan(const robot_geometry_msgs::PoseStamped& start,
scanned += std::hypot(sbpl_path[i + 1].x - sbpl_path[i].x,
sbpl_path[i + 1].y - sbpl_path[i].y);
}
if(preempt_.load(std::memory_order_relaxed)){
robot::log_info("[sbpl_lattice_planner] preempted after %.0f ms (before realign)",
(robot::Time::now() - plan_started).toSec() * 1000.0);
return false;
}
if(budget_left() < kMinReplanBudget){
robot::log_debug("[sbpl_lattice_planner] initial segment curved (dev %.2f rad) but only "
"%.2f s of the budget left — keeping the first path", max_dev, budget_left());
}
else{
robot::log_debug("[sbpl_lattice_planner] initial segment curved (dev %.2f rad), "
"replanning with start heading realigned to %.2f", max_dev, theta_realign);
"replanning with start heading realigned to %.2f (%.2f s left)",
max_dev, theta_realign, budget_left());
try{
int sid = env_->SetStart(start.pose.position.x - grid->getOriginX(),
start.pose.position.y - grid->getOriginY(),
@@ -555,18 +651,24 @@ bool SBPLLatticePlanner::makePlan(const robot_geometry_msgs::PoseStamped& start,
vector<int> realigned_ids;
int realigned_cost;
if(sid >= 0 && planner_->set_start(sid) != 0 &&
planner_->replan(allocated_time_, &realigned_ids, &realigned_cost)){
planner_->replan(budget_left(), &realigned_ids, &realigned_cost)){
vector<EnvNAVXYTHETALAT3Dpt_t> realigned_path;
env_->ConvertStateIDPathintoXYThetaPath(&realigned_ids, &realigned_path);
if(!realigned_path.empty()){
sbpl_path = realigned_path;
}
}
if(preempt_.load(std::memory_order_relaxed)){
robot::log_info("[sbpl_lattice_planner] preempted after %.0f ms (realign)",
(robot::Time::now() - plan_started).toSec() * 1000.0);
return false;
}
}
catch(SBPL_Exception *e){
// giữ path đầu tiên — cong nhưng vẫn hợp lệ, không được trả thất bại ở đây
robot::log_warning("[sbpl_lattice_planner] realigned replan failed, keeping first path");
}
} // budget_left() >= kMinReplanBudget
}
}
@@ -694,6 +796,13 @@ void setExternalGridOn(robot_nav_core::BaseGlobalPlanner* planner,
}
}
void SBPLLatticePlanner::preempt()
{
// Từ thread khác: một store, không lock. ARA* đọc cờ này qua set_abort_flag (nếu libsbpl hỗ trợ);
// makePlan đọc nó giữa các lượt replan nội bộ. Không log ở đây — chạy trên control thread.
preempt_.store(true, std::memory_order_relaxed);
}
};
// Alias cho Boost.DLL (nếu muốn dùng boost::dll::import_alias)