Files
sbpl_recovery/test/detour_path_recovery_test.cpp
duongtd ea79686eef 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>
2026-09-12 22:06:50 +07:00

731 lines
28 KiB
C++

/*********************************************************************
*
* Software License Agreement (BSD License)
*
* Kiểm DetourPathRecovery: chọn điểm nối, splice với plan cũ, thử-lại theo ứng viên, quy đổi frame
* qua TF, và các đường từ chối. Planner là plugin giả (TestLinePlanner) nạp qua đúng đường
* Boost.DLL mà runtime đi; costmap là placeholder — hai test seam `lock_costmap` và
* `costmap_frame_override` giữ cho không có dereference nào chạm vào nó.
*
* Author: DuongTD
*********************************************************************/
#include <gtest/gtest.h>
#include <chrono>
#include <cmath>
#include <cstdint>
#include <cstdlib>
#include <string>
#include <thread>
#include <vector>
#include <robot/node_handle.h>
#include <robot_costmap_2d/cost_values.h>
#include <robot_costmap_2d/costmap_2d.h>
#include <tf3/buffer_core.h>
#include <recovery_core/recovery_registry.h>
#include <sbpl_recovery/merge_grids.h>
namespace
{
using recovery_core::RecoveryBehavior;
using recovery_core::RecoveryContext;
using recovery_core::RecoveryGoal;
using recovery_core::RecoveryRegistry;
using recovery_core::RecoveryResult;
using recovery_core::RecoveryStatus;
using recovery_core::RecoveryTrigger;
/// Costmap placeholder: địa chỉ hợp lệ nhưng KHÔNG phải costmap — mọi đường dereference đã bị tắt
/// qua test seam. Cùng khuôn với planner_runner_test của move_base2.
robot_costmap_2d::Costmap2DROBOT* dummyCostmap()
{
static std::uintptr_t placeholder = 0;
return reinterpret_cast<robot_costmap_2d::Costmap2DROBOT*>(&placeholder);
}
class FakePoseProvider final : public recovery_core::PoseProvider
{
public:
bool ok = true;
robot_geometry_msgs::PoseStamped pose;
bool getRobotPose(robot_geometry_msgs::PoseStamped& out) const override
{
if (!ok)
{
return false;
}
out = pose;
return true;
}
};
/**
* @class BandCollisionChecker
* @brief Chặn một dải theo trục x: [from, to] không đặt được robot vào.
*
* Mô phỏng đúng tình huống sim: một vật cản nằm CHÍNH TRÊN tuyến, kéo dài vài mét — thứ khiến các
* ứng viên điểm nối chọn thuần theo khoảng cách đều rơi vào vùng cấm.
*/
class BandCollisionChecker final : public recovery_core::CollisionChecker
{
public:
void blockBand(double from_x, double to_x)
{
from_x_ = from_x;
to_x_ = to_x;
}
/// Vật cản THỨ HAI xa hơn trên tuyến — plan cũ không replan nên đuôi nó xuyên vật cản này mãi.
void blockSecondBand(double from_x, double to_x)
{
second_from_x_ = from_x;
second_to_x_ = to_x;
}
/// Dải "chưa quan sát": costmap local lăn theo robot nên đây là phần lớn tuyến phía trước.
void unknownBand(double from_x, double to_x)
{
unknown_from_x_ = from_x;
unknown_to_x_ = to_x;
}
/// Rìa lưới costmap: từ x này trở đi pose nằm NGOÀI lưới — quét phải dừng, không phải "chắn".
void outsideFrom(double from_x)
{
outside_from_x_ = from_x;
}
double footprintCost(double x, double y, double theta) const override
{
(void)y;
(void)theta;
++query_count_;
if ((x >= from_x_ && x <= to_x_) || (x >= second_from_x_ && x <= second_to_x_))
{
return -1.0;
}
return (x >= unknown_from_x_ && x <= unknown_to_x_) ? -3.0 : 0.0;
}
Placement classify(double x, double y, double theta) const override
{
if (x >= outside_from_x_)
{
return Placement::kOutside;
}
const double cost = footprintCost(x, y, theta);
if (cost >= 0.0)
{
return Placement::kFree;
}
return cost == -3.0 ? Placement::kUnknown : Placement::kBlocked;
}
std::size_t queryCount() const
{
return query_count_;
}
private:
double from_x_ = 1.0;
double to_x_ = 0.0; // dải rỗng: mặc định không chặn gì
double second_from_x_ = 1.0;
double second_to_x_ = 0.0; // dải thứ hai, mặc định rỗng
double unknown_from_x_ = 1.0;
double unknown_to_x_ = 0.0;
double outside_from_x_ = 1e9; // mặc định: lưới phủ hết
mutable std::size_t query_count_ = 0;
};
class FakePlanProvider final : public recovery_core::PlanProvider
{
public:
std::vector<robot_geometry_msgs::PoseStamped> plan;
bool getGlobalPlan(std::vector<robot_geometry_msgs::PoseStamped>& out) const override
{
if (plan.empty())
{
return false;
}
out = plan;
return true;
}
};
robot_geometry_msgs::PoseStamped makePose(const std::string& frame, double x, double y)
{
robot_geometry_msgs::PoseStamped pose;
pose.header.frame_id = frame;
pose.pose.position.x = x;
pose.pose.position.y = y;
pose.pose.orientation.w = 1.0;
return pose;
}
/// Plan thẳng dọc trục x: [from_x, to_x] bước @p step, y cố định.
std::vector<robot_geometry_msgs::PoseStamped> makeLinePlan(const std::string& frame, double from_x,
double to_x, double step, double y)
{
std::vector<robot_geometry_msgs::PoseStamped> plan;
for (double x = from_x; x <= to_x + 1e-9; x += step)
{
plan.push_back(makePose(frame, x, y));
}
return plan;
}
RecoveryBehavior* findBehavior(RecoveryRegistry& registry, const std::string& name)
{
for (std::size_t i = 0; i < registry.size(); ++i)
{
if (registry.nameAt(i) == name)
{
return registry.at(i);
}
}
return nullptr;
}
RecoveryGoal controllingGoal()
{
RecoveryGoal goal;
goal.trigger = RecoveryTrigger::kControllingFailed;
return goal;
}
/**
* Fixture: registry thật + plugin thật (nạp qua Boost.DLL) trên cổng giả. TF có sẵn một transform
* tĩnh map->odom (odom gốc tại (2, 1) trong map) cho các ca đổi frame.
*/
class DetourPathRecoveryTest : public ::testing::Test
{
protected:
void SetUp() override
{
tf3::TransformStampedMsg map_to_odom;
map_to_odom.header.frame_id = "map";
map_to_odom.child_frame_id = "odom";
map_to_odom.transform.translation.x = 2.0; // [m] p_map = p_odom + (2, 1)
map_to_odom.transform.translation.y = 1.0; // [m]
map_to_odom.transform.rotation.w = 1.0;
ASSERT_TRUE(tf_.setTransform(map_to_odom, "test", /*is_static=*/true));
ctx_.pose = &pose_;
ctx_.plan = &plan_;
// Tuyến tham chiếu để RỖNG mặc định: phần lớn test kiểm hình học trên plan hiện hành, và
// behavior phải tự quay về `plan` khi tham chiếu chưa có. Test nào cần thì tự nạp.
ctx_.reference_plan = &reference_plan_;
ctx_.collision = &collision_;
ctx_.local_costmap = dummyCostmap();
ctx_.tf = &tf_;
robot::NodeHandle nh;
ASSERT_TRUE(registry_.loadFromConfig(nh, "recovery", ctx_));
ASSERT_EQ(registry_.size(), 8u); // +detour_async, detour_slow (2026-09-11)
}
FakePoseProvider pose_;
FakePlanProvider plan_;
FakePlanProvider reference_plan_;
BandCollisionChecker collision_;
tf3::BufferCore tf_;
RecoveryContext ctx_;
RecoveryRegistry registry_;
robot::Time t0_{100, 0};
};
TEST_F(DetourPathRecoveryTest, StartRefusesWithoutAPlan)
{
RecoveryBehavior* detour = findBehavior(registry_, "detour");
ASSERT_NE(detour, nullptr);
pose_.pose = makePose("odom", 0.0, 0.0);
plan_.plan.clear(); // Không có plan thì không có gì để nối lại.
EXPECT_FALSE(detour->start(controllingGoal(), t0_));
}
TEST_F(DetourPathRecoveryTest, ReturnsThePlannedPathWithoutSplicing)
{
// Contract 2026-09-02: behavior lập LẠI CẢ ĐƯỜNG tới đích chặng và trả về NGUYÊN kết quả đó.
// Không còn điểm nối, không còn đoạn đuôi ghép vào — đó là hai nguồn sinh ra đường tự cắt.
RecoveryBehavior* detour = findBehavior(registry_, "detour");
ASSERT_NE(detour, nullptr);
// Plan cùng frame với costmap (odom): không cần quy đổi. Robot ở gốc, plan 0..5 m bước 0.5.
pose_.pose = makePose("odom", 0.0, 0.0);
plan_.plan = makeLinePlan("odom", 0.0, 5.0, 0.5, 0.0);
ASSERT_TRUE(detour->start(controllingGoal(), t0_));
const RecoveryResult result = detour->update(t0_);
ASSERT_EQ(result.status, RecoveryStatus::kSucceeded);
const robot_nav_msgs::Path* path = result.pathOut();
ASSERT_NE(path, nullptr);
EXPECT_EQ(path->header.frame_id, "odom");
// Đúng 5 pose của planner giả — KHÔNG có pose nào của plan cũ nối thêm vào.
ASSERT_EQ(path->poses.size(), 5u);
EXPECT_NEAR(path->poses.front().pose.position.x, 0.0, 1e-9); // xuất phát tại pose robot
EXPECT_NEAR(path->poses.back().pose.position.x, 5.0, 1e-9); // kết thúc tại ĐÍCH CHẶNG
EXPECT_NEAR(path->poses.back().pose.position.y, 0.0, 1e-9);
}
TEST_F(DetourPathRecoveryTest, FlakyPlannerRetriesTheSameGoal)
{
// Đích không đổi giữa các attempt — chỉ lượt planner được thử lại. Đổi đích giữa chừng là đổi
// bài toán đang giải, và chính việc "thử ứng viên khác" của bản cũ mới đẻ ra điểm nối sau lưng.
RecoveryBehavior* detour = findBehavior(registry_, "detour_flaky");
ASSERT_NE(detour, nullptr);
pose_.pose = makePose("odom", 0.0, 0.0);
plan_.plan = makeLinePlan("odom", 0.0, 5.0, 0.5, 0.0);
ASSERT_TRUE(detour->start(controllingGoal(), t0_));
// Hai lượt đầu bị planner giả từ chối, lượt ba thành công.
EXPECT_EQ(detour->update(t0_).status, RecoveryStatus::kRunning);
EXPECT_EQ(detour->update(t0_).status, RecoveryStatus::kRunning);
const RecoveryResult result = detour->update(t0_);
ASSERT_EQ(result.status, RecoveryStatus::kSucceeded);
const robot_nav_msgs::Path* path = result.pathOut();
ASSERT_NE(path, nullptr);
// Đích vẫn là đích chặng, y hệt lượt đầu.
EXPECT_NEAR(path->poses.back().pose.position.x, 5.0, 1e-9);
}
TEST_F(DetourPathRecoveryTest, FailsAfterAllAttempts)
{
RecoveryBehavior* detour = findBehavior(registry_, "detour_dead");
ASSERT_NE(detour, nullptr);
pose_.pose = makePose("odom", 0.0, 0.0);
plan_.plan = makeLinePlan("odom", 0.0, 5.0, 0.5, 0.0);
ASSERT_TRUE(detour->start(controllingGoal(), t0_));
EXPECT_EQ(detour->update(t0_).status, RecoveryStatus::kRunning);
EXPECT_EQ(detour->update(t0_).status, RecoveryStatus::kRunning);
EXPECT_EQ(detour->update(t0_).status, RecoveryStatus::kRunning);
// Hết attempts_per_run (3) lượt: kFailed để state machine chuyển behavior kế tiếp.
EXPECT_EQ(detour->update(t0_).status, RecoveryStatus::kFailed);
}
TEST_F(DetourPathRecoveryTest, ConvertsFramesThroughTf)
{
RecoveryBehavior* detour = findBehavior(registry_, "detour_map");
ASSERT_NE(detour, nullptr);
// Plan ở MAP, costmap ở ODOM (odom gốc tại map (2,1)). Robot đứng ở odom (0,0) = map (2,1).
pose_.pose = makePose("odom", 0.0, 0.0);
plan_.plan = makeLinePlan("map", 2.0, 7.0, 0.5, 1.0);
ASSERT_TRUE(detour->start(controllingGoal(), t0_));
const RecoveryResult result = detour->update(t0_);
ASSERT_EQ(result.status, RecoveryStatus::kSucceeded);
const robot_nav_msgs::Path* path = result.pathOut();
ASSERT_NE(path, nullptr);
// Kết quả phải nằm TRỌN trong frame của plan: đường (planner trả ở odom) đã được quy về map.
EXPECT_EQ(path->header.frame_id, "map");
ASSERT_EQ(path->poses.size(), 5u);
EXPECT_NEAR(path->poses.front().pose.position.x, 2.0, 1e-9); // robot tại map (2,1)
EXPECT_NEAR(path->poses.front().pose.position.y, 1.0, 1e-9);
EXPECT_NEAR(path->poses.back().pose.position.x, 7.0, 1e-9); // đích chặng, map x=7.0
EXPECT_NEAR(path->poses.back().pose.position.y, 1.0, 1e-9);
}
TEST_F(DetourPathRecoveryTest, TakesTheGoalFromTheReferenceRouteNotTheDriftedPlan)
{
// Contract 2026-08-05e, giữ nguyên sau khi bỏ detour: ĐÍCH lấy từ TUYẾN GỐC của chặng, không
// phải plan đang bám. Lấy từ plan đang bám thì mỗi lượt recovery lấy kết quả lượt trước làm mốc
// — sim đo tuyến bị ăn mòn dần và robot không bao giờ quay về tuyến order.
RecoveryBehavior* detour = findBehavior(registry_, "detour");
ASSERT_NE(detour, nullptr);
pose_.pose = makePose("odom", 0.0, 0.0);
// Plan ĐANG BÁM đã trôi sang y = 3.0 sau vài lượt detour trước đó.
plan_.plan = makeLinePlan("odom", 0.0, 6.0, 0.5, 3.0);
// Tuyến GỐC vẫn là tuyến order ở y = 0.0.
reference_plan_.plan = makeLinePlan("odom", 0.0, 6.0, 0.5, 0.0);
ASSERT_TRUE(detour->start(controllingGoal(), t0_));
const RecoveryResult result = detour->update(t0_);
ASSERT_EQ(result.status, RecoveryStatus::kSucceeded);
const robot_nav_msgs::Path* path = result.pathOut();
ASSERT_NE(path, nullptr);
// Đích phải là đích TUYẾN GỐC (y = 0), không phải plan đã trôi (y = 3): đó chính là thứ kéo
// robot trở lại tuyến fleet đã duyệt.
EXPECT_NEAR(path->poses.back().pose.position.y, 0.0, 1e-9);
EXPECT_NEAR(path->poses.back().pose.position.x, 6.0, 1e-9);
}
TEST_F(DetourPathRecoveryTest, FallsBackToTheCurrentPlanWhenNoReferenceRouteExists)
{
// Runtime chưa lập được plan nào (hoặc không cấp tuyến tham chiếu): vẫn phải vòng được, chỉ mất
// khả năng tự về tuyến. Im lặng bỏ cuộc thì tệ hơn nhiều.
RecoveryBehavior* detour = findBehavior(registry_, "detour");
ASSERT_NE(detour, nullptr);
pose_.pose = makePose("odom", 0.0, 0.0);
plan_.plan = makeLinePlan("odom", 0.0, 6.0, 0.5, 3.0);
reference_plan_.plan.clear(); // chưa có tuyến gốc
ASSERT_TRUE(detour->start(controllingGoal(), t0_));
const RecoveryResult result = detour->update(t0_);
ASSERT_EQ(result.status, RecoveryStatus::kSucceeded);
const robot_nav_msgs::Path* path = result.pathOut();
ASSERT_NE(path, nullptr);
EXPECT_NEAR(path->poses.back().pose.position.y, 3.0, 1e-9); // đuôi của plan đang bám
}
TEST_F(DetourPathRecoveryTest, PlannerSymbolMayDifferFromTheInstanceName)
{
// Đường mà runtime dùng để cho detour một instance SBPL riêng: `planner_name` là namespace param
// (`DetourOnlyTuning`, khai `points: 9`), `planner_symbol` là alias có thật trong .so.
// `libsbpl_lattice_planner` chỉ export một symbol, nên nếu hai thứ này bị buộc phải trùng nhau
// thì không thể có instance tuning riêng — đúng lỗi làm route path_blocked rỗng trên sim.
RecoveryBehavior* detour = findBehavior(registry_, "detour_alias");
ASSERT_NE(detour, nullptr) << "behavior bị loại lúc nạp: planner_symbol không resolve được";
pose_.pose = makePose("odom", 0.0, 0.0);
plan_.plan = makeLinePlan("odom", 0.0, 5.0, 0.5, 0.0);
ASSERT_TRUE(detour->start(controllingGoal(), t0_));
const RecoveryResult result = detour->update(t0_);
ASSERT_EQ(result.status, RecoveryStatus::kSucceeded);
const robot_nav_msgs::Path* path = result.pathOut();
ASSERT_NE(path, nullptr);
// Param đọc từ `DetourOnlyTuning`: đường 9 điểm (mặc định là 5), không nối đuôi gì thêm.
EXPECT_EQ(path->poses.size(), 9u);
EXPECT_NEAR(path->poses.back().pose.position.x, 5.0, 1e-9); // đích chặng
}
TEST_F(DetourPathRecoveryTest, RejectsDetoursThatStrayTooFarFromTheRoute)
{
// Guard lệch tuyến: order chỉ định tuyến, robot chỉ được rời khỏi nó trong hành lang fleet cho
// phép. Planner giả luôn phình 1.0 m, ngưỡng đặt 0.2 m -> mọi ứng viên bị loại, behavior kFailed
// để route chuyển sang cách xử lý khác.
RecoveryBehavior* detour = findBehavior(registry_, "detour_narrow");
ASSERT_NE(detour, nullptr);
pose_.pose = makePose("odom", 0.0, 0.0);
plan_.plan = makeLinePlan("odom", 0.0, 5.0, 0.5, 0.0);
ASSERT_TRUE(detour->start(controllingGoal(), t0_));
// Ba ứng viên, ứng viên nào cũng lập được đường nhưng đều vượt ngưỡng lệch.
EXPECT_EQ(detour->update(t0_).status, RecoveryStatus::kRunning);
EXPECT_EQ(detour->update(t0_).status, RecoveryStatus::kRunning);
EXPECT_EQ(detour->update(t0_).status, RecoveryStatus::kRunning);
EXPECT_EQ(detour->update(t0_).status, RecoveryStatus::kFailed);
}
TEST_F(DetourPathRecoveryTest, AcceptsDetoursInsideTheDeviationLimit)
{
// Cùng ngưỡng 0.2 m nhưng planner mặc định (`detour`) không phình: đường vòng nằm trên tuyến nên
// guard không được chặn nhầm.
RecoveryBehavior* detour = findBehavior(registry_, "detour");
ASSERT_NE(detour, nullptr);
pose_.pose = makePose("odom", 0.0, 0.0);
plan_.plan = makeLinePlan("odom", 0.0, 5.0, 0.5, 0.0);
ASSERT_TRUE(detour->start(controllingGoal(), t0_));
EXPECT_EQ(detour->update(t0_).status, RecoveryStatus::kSucceeded);
}
TEST_F(DetourPathRecoveryTest, FailsWhenPoseIsLostMidRun)
{
RecoveryBehavior* detour = findBehavior(registry_, "detour");
ASSERT_NE(detour, nullptr);
pose_.pose = makePose("odom", 0.0, 0.0);
plan_.plan = makeLinePlan("odom", 0.0, 5.0, 0.5, 0.0);
ASSERT_TRUE(detour->start(controllingGoal(), t0_));
// Mất pose giữa lượt: không được lập đường vòng bằng pose cũ.
pose_.ok = false;
EXPECT_EQ(detour->update(t0_).status, RecoveryStatus::kFailed);
}
TEST(DetourPathRecoveryNoTfTest, RefusesWhenFramesDifferWithoutTf)
{
// Registry riêng với context KHÔNG có TF: plan (map) khác frame costmap (odom) phải bị từ chối
// ngay tại start, kèm lý do — không đoán, không trộn frame.
FakePoseProvider pose;
FakePlanProvider plan;
RecoveryContext ctx;
ctx.pose = &pose;
ctx.plan = &plan;
ctx.local_costmap = dummyCostmap();
ctx.tf = nullptr;
robot::NodeHandle nh;
RecoveryRegistry registry;
ASSERT_TRUE(registry.loadFromConfig(nh, "recovery", ctx));
RecoveryBehavior* detour = findBehavior(registry, "detour_map");
ASSERT_NE(detour, nullptr);
pose.pose = makePose("odom", 0.0, 0.0);
plan.plan = makeLinePlan("map", 2.0, 7.0, 0.5, 1.0);
EXPECT_FALSE(detour->start(controllingGoal(), robot::Time{100, 0}));
}
} // namespace
// ================================================================================================
// merge_grids.h — ngữ nghĩa gộp lưới (thuần, lưới tay, không cần costmap sống)
// ================================================================================================
TEST(MergeGrids, CellMergeSemantics)
{
using robot_costmap_2d::FREE_SPACE;
using robot_costmap_2d::LETHAL_OBSTACLE;
using robot_costmap_2d::NO_INFORMATION;
// local chưa quét -> tin mắt rộng.
EXPECT_EQ(sbpl_recovery::mergeCellCost(LETHAL_OBSTACLE, NO_INFORMATION), LETHAL_OBSTACLE);
EXPECT_EQ(sbpl_recovery::mergeCellCost(FREE_SPACE, NO_INFORMATION), FREE_SPACE);
// global chưa biết nhưng local ĐÃ biết -> lấy local (max mù sẽ biến 255 thành "chắn").
EXPECT_EQ(sbpl_recovery::mergeCellCost(NO_INFORMATION, FREE_SPACE), FREE_SPACE);
EXPECT_EQ(sbpl_recovery::mergeCellCost(NO_INFORMATION, LETHAL_OBSTACLE), LETHAL_OBSTACLE);
// Cả hai đều biết -> một bên chắn là chắn; local FREE không xoá tường global.
EXPECT_EQ(sbpl_recovery::mergeCellCost(LETHAL_OBSTACLE, FREE_SPACE), LETHAL_OBSTACLE);
EXPECT_EQ(sbpl_recovery::mergeCellCost(FREE_SPACE, LETHAL_OBSTACLE), LETHAL_OBSTACLE);
EXPECT_EQ(sbpl_recovery::mergeCellCost(FREE_SPACE, FREE_SPACE), FREE_SPACE);
}
TEST(MergeGrids, OverlayWritesLocalWindowOntoGlobalBase)
{
using robot_costmap_2d::Costmap2D;
using robot_costmap_2d::FREE_SPACE;
using robot_costmap_2d::LETHAL_OBSTACLE;
using robot_costmap_2d::NO_INFORMATION;
// Nền global 10x10 @ 0.1 m, gốc (0,0): FREE, một bức tường tĩnh tại (0.55, 0.55).
Costmap2D merged(10, 10, 0.1, 0.0, 0.0, FREE_SPACE);
merged.setCost(5, 5, LETHAL_OBSTACLE);
// Cửa sổ local 4x4 @ 0.1 m, gốc (0.2, 0.2): một vật cản tươi, một cell FREE trùng tường global,
// phần còn lại chưa quét (NO_INFORMATION).
Costmap2D local(4, 4, 0.1, 0.2, 0.2, NO_INFORMATION);
local.setCost(1, 1, LETHAL_OBSTACLE); // (0.35, 0.35): vật cản sensor
local.setCost(3, 3, FREE_SPACE); // (0.55, 0.55): local nói sạch NGAY TRÊN tường global
sbpl_recovery::PlanarTransform2D identity;
sbpl_recovery::overlayLocalGrid(local, identity, merged);
unsigned int mx = 0;
unsigned int my = 0;
ASSERT_TRUE(merged.worldToMap(0.35, 0.35, mx, my));
EXPECT_EQ(merged.getCost(mx, my), LETHAL_OBSTACLE); // vật cản tươi được đè vào nền
ASSERT_TRUE(merged.worldToMap(0.55, 0.55, mx, my));
EXPECT_EQ(merged.getCost(mx, my), LETHAL_OBSTACLE); // tường global KHÔNG bị local FREE xoá
ASSERT_TRUE(merged.worldToMap(0.25, 0.25, mx, my));
EXPECT_EQ(merged.getCost(mx, my), FREE_SPACE); // local chưa quét -> giữ nền global
ASSERT_TRUE(merged.worldToMap(0.95, 0.95, mx, my));
EXPECT_EQ(merged.getCost(mx, my), FREE_SPACE); // ngoài cửa sổ local -> nền global nguyên vẹn
}
TEST(MergeGrids, OverlayTransformsLocalFrameIntoGridFrame)
{
using robot_costmap_2d::Costmap2D;
using robot_costmap_2d::FREE_SPACE;
using robot_costmap_2d::LETHAL_OBSTACLE;
using robot_costmap_2d::NO_INFORMATION;
Costmap2D merged(20, 20, 0.1, 0.0, 0.0, FREE_SPACE);
// Local frame (odom) lệch map: tịnh tiến (1.0, 0.5), quay 90 độ.
Costmap2D local(4, 4, 0.1, 0.0, 0.0, NO_INFORMATION);
local.setCost(2, 0, LETHAL_OBSTACLE); // tâm cell tại odom (0.25, 0.05)
sbpl_recovery::PlanarTransform2D odom_to_map;
odom_to_map.x = 1.0;
odom_to_map.y = 0.5;
odom_to_map.cos_yaw = 0.0;
odom_to_map.sin_yaw = 1.0; // yaw = +90 độ: (x, y) -> (-y, x)
sbpl_recovery::overlayLocalGrid(local, odom_to_map, merged);
// odom (0.25, 0.05) -> map (1.0 - 0.05, 0.5 + 0.25) = (0.95, 0.75).
unsigned int mx = 0;
unsigned int my = 0;
ASSERT_TRUE(merged.worldToMap(0.95, 0.75, mx, my));
EXPECT_EQ(merged.getCost(mx, my), LETHAL_OBSTACLE);
}
// ================================================================================================
// Đường bất đồng bộ (2026-09-11): makePlan trên worker thread, control thread chỉ poll; cancel()
// cắt được lượt đang chạy qua robot_nav_core::Preemptable.
// ================================================================================================
namespace
{
/// Poll update() tới khi status khác kRunning-"đang chạy", tối đa @p max_seconds.
RecoveryResult pumpUntilSettled(RecoveryBehavior* detour, const robot::Time& t0, double max_seconds,
int* ticks_out = nullptr)
{
const auto deadline = std::chrono::steady_clock::now() +
std::chrono::duration_cast<std::chrono::steady_clock::duration>(
std::chrono::duration<double>(max_seconds));
int ticks = 0;
RecoveryResult result;
while (std::chrono::steady_clock::now() < deadline)
{
result = detour->update(t0);
++ticks;
if (result.status != RecoveryStatus::kRunning)
{
break;
}
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
if (ticks_out != nullptr)
{
*ticks_out = ticks;
}
return result;
}
} // namespace
TEST_F(DetourPathRecoveryTest, AsyncUpdateNeverBlocksAndDeliversThePathLater)
{
RecoveryBehavior* detour = findBehavior(registry_, "detour_async");
ASSERT_NE(detour, nullptr);
pose_.pose = makePose("odom", 0.0, 0.0);
plan_.plan = makeLinePlan("odom", 0.0, 5.0, 0.5, 0.0);
ASSERT_TRUE(detour->start(controllingGoal(), t0_));
// Tick đầu khởi động worker và trả về NGAY — planner giả ngủ 300 ms, tick phải < 50 ms.
const auto before = std::chrono::steady_clock::now();
const RecoveryResult first = detour->update(t0_);
const double first_ms =
std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - before).count();
EXPECT_EQ(first.status, RecoveryStatus::kRunning);
EXPECT_LT(first_ms, 50.0) << "update() blocked inside makePlan";
int ticks = 0;
const RecoveryResult result = pumpUntilSettled(detour, t0_, 3.0, &ticks);
ASSERT_EQ(result.status, RecoveryStatus::kSucceeded);
EXPECT_GE(ticks, 2) << "the path must arrive on a later tick, not the first";
const robot_nav_msgs::Path* path = result.pathOut();
ASSERT_NE(path, nullptr);
ASSERT_EQ(path->poses.size(), 5u);
}
TEST_F(DetourPathRecoveryTest, CancelMidSearchReturnsQuicklyAndJoinsTheWorker)
{
RecoveryBehavior* detour = findBehavior(registry_, "detour_slow");
ASSERT_NE(detour, nullptr);
pose_.pose = makePose("odom", 0.0, 0.0);
plan_.plan = makeLinePlan("odom", 0.0, 5.0, 0.5, 0.0);
ASSERT_TRUE(detour->start(controllingGoal(), t0_));
ASSERT_EQ(detour->update(t0_).status, RecoveryStatus::kRunning);
std::this_thread::sleep_for(std::chrono::milliseconds(50)); // worker đang ở giữa 300 ms "search"
const auto before = std::chrono::steady_clock::now();
detour->cancel(); // → onCancelRequested(): preempt + join
const double cancel_ms =
std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - before).count();
EXPECT_LT(cancel_ms, 100.0) << "cancel must not wait for the fake 300 ms search to finish";
// Sau cancel behavior phải khởi động lại được ngay (worker cũ đã join), và lượt mới chạy bình thường.
ASSERT_TRUE(detour->start(controllingGoal(), t0_)) << "stale worker blocked a new run";
const RecoveryResult result = pumpUntilSettled(detour, t0_, 3.0);
EXPECT_EQ(result.status, RecoveryStatus::kSucceeded);
}
TEST_F(DetourPathRecoveryTest, CancelledSearchResultIsDiscarded)
{
RecoveryBehavior* detour = findBehavior(registry_, "detour_slow");
ASSERT_NE(detour, nullptr);
pose_.pose = makePose("odom", 0.0, 0.0);
plan_.plan = makeLinePlan("odom", 0.0, 5.0, 0.5, 0.0);
ASSERT_TRUE(detour->start(controllingGoal(), t0_));
ASSERT_EQ(detour->update(t0_).status, RecoveryStatus::kRunning);
detour->cancel();
// Tick sau cancel: base trả kCancelled (đường onCancel), không được là kSucceeded với path của
// lượt đã huỷ.
const RecoveryResult after = detour->update(t0_);
EXPECT_NE(after.status, RecoveryStatus::kSucceeded);
EXPECT_EQ(after.pathOut(), nullptr);
}
int main(int argc, char** argv)
{
#ifdef SBPL_RECOVERY_TEST_CONFIG_DIR
// Trỏ cây config vào bản test TRƯỚC khi bất kỳ NodeHandle nào được dựng.
setenv("PNKX_NAV_CORE_CONFIG_DIR", SBPL_RECOVERY_TEST_CONFIG_DIR, 1);
#endif
#ifdef SBPL_RECOVERY_TEST_LIBRARY_DIR
// PluginLoaderHelper chỉ ghép ".so" trong nhánh PNKX_NAV_CORE_LIBRARY_PATH — không đặt biến này
// thì `library_path: libsbpl_recovery` không resolve được khi LD_LIBRARY_PATH thiếu devel/lib.
// Cùng khuôn với bộ test của recovery_core.
setenv("PNKX_NAV_CORE_LIBRARY_PATH", SBPL_RECOVERY_TEST_LIBRARY_DIR, 0);
#endif
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
TEST_F(DetourPathRecoveryTest, RefusesToStartWhenAlreadyAtTheGoal)
{
// Lập đường tới chính chỗ đang đứng cho ra path một pose; tầng trên nhận rồi báo hỏng ngay chu
// kỳ sau. Từ chối ở onStart rẻ hơn, và không đốt attempts_per_run lượt planner.
RecoveryBehavior* detour = findBehavior(registry_, "detour");
ASSERT_NE(detour, nullptr);
pose_.pose = makePose("odom", 5.0, 0.0);
plan_.plan = makeLinePlan("odom", 0.0, 5.0, 0.5, 0.0); // đích chặng cũng ở x = 5.0
EXPECT_FALSE(detour->start(controllingGoal(), t0_));
}
TEST_F(DetourPathRecoveryTest, PlansFromTheRobotEvenWhenItDriftedFarOffTheRoute)
{
// Ca đã làm bản detour sinh vòng khép kín (sim 28/8, mission 8): robot lệch xa tuyến hơn ngưỡng
// quét nên con trỏ ứng viên tụt về đầu tuyến và điểm nối rơi ra SAU LƯNG. Không còn điểm nối thì
// ca đó không tồn tại — đường luôn bắt đầu tại robot và kết thúc tại đích chặng.
RecoveryBehavior* detour = findBehavior(registry_, "detour");
ASSERT_NE(detour, nullptr);
pose_.pose = makePose("odom", 3.0, 4.0); // lệch 4 m khỏi tuyến
plan_.plan = makeLinePlan("odom", 0.0, 6.0, 0.5, 0.0);
ASSERT_TRUE(detour->start(controllingGoal(), t0_));
const RecoveryResult result = detour->update(t0_);
ASSERT_EQ(result.status, RecoveryStatus::kSucceeded);
const robot_nav_msgs::Path* path = result.pathOut();
ASSERT_NE(path, nullptr);
EXPECT_NEAR(path->poses.front().pose.position.x, 3.0, 1e-9);
EXPECT_NEAR(path->poses.front().pose.position.y, 4.0, 1e-9);
EXPECT_NEAR(path->poses.back().pose.position.x, 6.0, 1e-9);
EXPECT_NEAR(path->poses.back().pose.position.y, 0.0, 1e-9);
}