feat(move_base2): wait for a ready global costmap and replay maps in host order

- Replay static maps in arrival order instead of topic order, so a
  direction grid can no longer be replayed before its static map (F3).
- PlannerRunner checks every enabled global layer under the same lock as
  the snapshot; while not current it keeps the goal, reports
  waiting_for_costmap, logs the stale layers (throttled) and does not
  spend planner_patience or watchdog budget. After costmap_ready_timeout
  [s] (default 10, 0 = legacy behaviour) the attempt fails as before.
- Test fixture destroys the server before its fake ports; the control
  thread could call a destroyed port (race existed before this change).
This commit is contained in:
2026-11-04 11:14:15 +07:00
parent 7bfb3c362d
commit 6decd8db32
18 changed files with 446 additions and 31 deletions

View File

@@ -53,6 +53,9 @@ struct MoveBase2Config
*/
double planner_timeout = 5.0;
/// [s] Continuous global-costmap readiness wait; 0 disables the check (legacy behavior).
double costmap_ready_timeout = 10.0;
/**
* Watchdog (2026-09-11): thread riêng đọc bảng trạng thái thành phần, kết luận "treo" theo ngân
* sách từng hàng. `watchdog.planner_timeout` được chép từ @ref planner_timeout khi nạp.

View File

@@ -109,6 +109,9 @@ struct ControlLoopConfig
/// [s] Chu kỳ danh nghĩa, chỉ dùng cho dt của cycle ĐẦU TIÊN khi chưa có mốc thời gian trước đó.
double nominal_control_period = 0.05;
/// [s] Maximum continuous global-costmap wait; 0 disables the readiness check.
double costmap_ready_timeout = 10.0;
/// Công tắc log chẩn đoán. Xem `MoveBase2Config::debug_*` để biết từng nhóm in cái gì.
bool debug_state = true;
bool debug_plan = true;

View File

@@ -48,7 +48,8 @@ enum class ComponentPhase : std::uint8_t
kBusy, ///< Đang làm việc.
kStopping, ///< Đã được bảo dừng (preempt/cancel) nhưng chưa thoát.
kPaused, ///< Đã xác nhận tạm dừng (chỉ action, pha 3).
kHung ///< Watchdog kết luận: bận quá ngân sách mà không nhích (pha 4).
kHung, ///< Watchdog kết luận: bận quá ngân sách mà không nhích (pha 4).
kWaitingForCostmap ///< Retaining the request until global costmap data is ready.
};
const char* toString(Component component);

View File

@@ -28,6 +28,7 @@ enum class PlannerFeedback
{
kIdle, ///< Chưa có tin gì mới kể từ cycle trước.
kBusy, ///< Đang lập plan, chưa có kết quả.
kWaitingForCostmap, ///< Goal retained while the global costmap becomes current.
kPlanReady, ///< Có plan mới, không rỗng, sẵn sàng đẩy xuống controller.
kFailed ///< Lần lập plan gần nhất thất bại.
};
@@ -190,6 +191,7 @@ struct StateMachineInput
bool emergency = false;
PlannerFeedback planner = PlannerFeedback::kIdle;
bool planner_costmap_wait_finished = false;
ControllerFeedback controller = ControllerFeedback::kIdle;
RecoveryFeedback recovery = RecoveryFeedback::kIdle;
ActionFeedback action = ActionFeedback::kIdle;

View File

@@ -10,6 +10,7 @@
#define MOVE_BASE2_NAVIGATION_SERVER_H_
#include <atomic>
#include <cstdint>
#include <map>
#include <memory>
#include <mutex>
@@ -60,6 +61,8 @@ public:
/**
* @brief Nạp cấu hình và các cổng cho control loop.
* @warning Các cổng trong deps là non-owning: bên cấp phải giữ chúng sống tới khi control
* thread đã được dừng và join, kể cả khi dựa vào destructor của NavigationServer.
* @param[out] error Lý do không cấu hình được.
*/
bool configureLoop(const ControlLoopConfig& config, const ControlLoopDeps& deps,
@@ -423,6 +426,10 @@ private:
/// Bảo vệ dữ liệu sensor và footprint: host ghi từ thread của nó, control loop đọc.
mutable std::mutex data_mutex_;
/// Latest arrival order per stored static-map topic; guarded by data_mutex_.
std::map<std::string, std::uint64_t> static_map_sequences_;
std::uint64_t next_static_map_sequence_ = 0;
std::vector<robot_geometry_msgs::Point> footprint_;
bool footprint_pending_ = false;
std::map<std::string, robot_sensor_msgs::DepthCameraData::ConstPtr> depth_camera_data_;

View File

@@ -108,6 +108,12 @@ public:
/// @brief Có lượt lập plan nào đang chạy không.
virtual bool isPlanning() const = 0;
/// Configure the global readiness wait before accepting requests. Zero keeps legacy behavior.
virtual void setCostmapReadyTimeout(double /*seconds*/) {}
/// Atomically sample the wait and consume the completion event since the previous sample.
virtual bool costmapWaitState(bool& finished) { finished = false; return false; }
/**
* @brief Lấy kết quả nếu đã có. Không chặn.
*

View File

@@ -11,6 +11,7 @@
#define MOVE_BASE2_RUNNERS_PLANNER_RUNNER_H_
#include <condition_variable>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <functional>
@@ -38,6 +39,15 @@ class Costmap2DROBOT;
namespace move_base2
{
/// Decision for a continuous readiness wait. A zero timeout preserves legacy planning behavior.
enum class CostmapReadyDecision { kPlan, kWait, kTimeout };
inline CostmapReadyDecision costmapReadyDecision(bool ready, double elapsed, double timeout)
{
if (timeout == 0.0 || ready)
return CostmapReadyDecision::kPlan;
return elapsed >= timeout ? CostmapReadyDecision::kTimeout : CostmapReadyDecision::kWait;
}
/**
* @class PlannerRunner
* @brief Nạp và chạy global planner thế hệ 1 (`robot_nav_core::BaseGlobalPlanner`) qua Boost.DLL,
@@ -177,6 +187,8 @@ public:
const robot_protocol_msgs::Order* order, std::uint64_t tag) override;
bool isPlanning() const override;
void setCostmapReadyTimeout(double seconds) override;
bool costmapWaitState(bool& finished) override;
bool pollPlan(PlanResult& result) override;
@@ -268,6 +280,15 @@ private:
bool running_ = false; ///< Thread đang chạy plugin.
bool discard_ = false; ///< Lượt đang chạy đã bị huỷ — vứt kết quả khi nó về.
bool has_result_ = false;
double costmap_ready_timeout_ = 10.0; ///< [s], protected by mutex_.
bool waiting_for_costmap_ = false;
bool costmap_wait_finished_ = false;
// Written only by the planner thread; throttle a persistent outage across failed attempts.
bool costmap_wait_problem_active_ = false;
std::chrono::steady_clock::time_point last_costmap_wait_log_;
std::chrono::steady_clock::time_point last_costmap_timeout_log_;
std::string costmap_stale_names_;
bool costmap_stale_names_reserved_ = false;
robot_nav_core::BaseGlobalPlanner* active_ = nullptr; ///< Non-owning, trỏ vào @ref planners_.
/**

View File

@@ -49,6 +49,8 @@ const char* toString(ComponentPhase phase)
return "paused";
case ComponentPhase::kHung:
return "hung";
case ComponentPhase::kWaitingForCostmap:
return "waiting_for_costmap";
}
return "unknown";
}

View File

@@ -146,6 +146,7 @@ void readMoveBase2Fields(robot::NodeHandle& nh, MoveBase2Config& config)
readDouble(nh, "controller_frequency", config.controller_frequency);
readDouble(nh, "planner_frequency", config.planner_frequency);
readDouble(nh, "planner_timeout", config.planner_timeout);
readDouble(nh, "costmap_ready_timeout", config.costmap_ready_timeout);
readDouble(nh, "runtime_stats_period", config.runtime_stats_period);
readDouble(nh, "watchdog_period", config.watchdog.period);
readDouble(nh, "local_planner_call_budget", config.watchdog.local_planner_call_budget);
@@ -435,6 +436,11 @@ bool MoveBase2Config::validate(std::string& error) const
error = "planner_timeout is not finite [s]";
return false;
}
if (!std::isfinite(costmap_ready_timeout) || costmap_ready_timeout < 0.0)
{
error = "costmap_ready_timeout must be finite and >= 0 [s] (0 = legacy behavior)";
return false;
}
if (!watchdog.validate(error))
{
return false;
@@ -536,6 +542,8 @@ std::string MoveBase2Config::describe() const
out << " controller_frequency: " << controller_frequency << " Hz\n";
out << " planner_frequency: " << planner_frequency << " Hz\n";
out << " planner_timeout: " << planner_timeout << " s\n";
out << " costmap_ready_timeout: " << costmap_ready_timeout << " s"
<< (costmap_ready_timeout == 0.0 ? " (readiness check off)\n" : "\n");
out << " runtime_stats_period: " << runtime_stats_period << " s"
<< (runtime_stats_period > 0.0 ? "\n" : " (off)\n");
out << watchdog.describe();
@@ -582,6 +590,7 @@ void MoveBase2Config::fromLegacyNodeHandle(robot::NodeHandle& nh)
readDouble(nh, "controller_frequency", controller_frequency);
readDouble(nh, "planner_frequency", planner_frequency);
readDouble(nh, "costmap_ready_timeout", costmap_ready_timeout);
// Khoá này không có trong schema gen-1 — nó là công cụ chẩn đoán của move_base2. Vẫn đọc ở đây
// để bật được telemetry mà không phải chuyển cả cây config sang schema mới.
readDouble(nh, "runtime_stats_period", runtime_stats_period);
@@ -731,6 +740,7 @@ ControlLoopConfig MoveBase2Config::toControlLoopConfig() const
config.debug_plan = debug_plan;
config.debug_skip = debug_skip;
config.state_machine = state_machine;
config.costmap_ready_timeout = costmap_ready_timeout;
config.velocity = velocity;
config.nominal_control_period =
controller_frequency > 0.0 ? 1.0 / controller_frequency : 0.05; // [s]

View File

@@ -48,6 +48,8 @@ const char* toString(PlannerFeedback feedback)
return "idle";
case PlannerFeedback::kBusy:
return "busy";
case PlannerFeedback::kWaitingForCostmap:
return "waiting_for_costmap";
case PlannerFeedback::kPlanReady:
return "plan_ready";
case PlannerFeedback::kFailed:
@@ -96,6 +98,11 @@ const char* toString(RecoveryFeedback feedback)
bool ControlLoopConfig::validate(std::string& error) const
{
if (!std::isfinite(costmap_ready_timeout) || costmap_ready_timeout < 0.0)
{
error = "costmap_ready_timeout must be finite and >= 0 [s]";
return false;
}
if (!state_machine.validate(error))
{
return false;
@@ -239,6 +246,7 @@ bool ControlLoop::configure(const ControlLoopConfig& config, const ControlLoopDe
config_ = config;
deps_ = deps;
deps_.planner->setCostmapReadyTimeout(config_.costmap_ready_timeout);
// EnvMonitor (Test/docs/move_base2/ENV_MONITOR_PLAN.md) — bộ giám sát môi trường duy nhất từ 6/9/2026 (PathMonitor cũ đã
@@ -1035,6 +1043,9 @@ bool ControlLoop::step()
input.cancel_requested = cancel_requested_;
input.emergency = emergency_;
input.planner = planner_feedback_;
const bool planner_waiting = deps_.planner->costmapWaitState(input.planner_costmap_wait_finished);
if (planner_running_ && planner_waiting && planner_feedback_ == PlannerFeedback::kBusy)
input.planner = PlannerFeedback::kWaitingForCostmap;
input.controller = controller_feedback_;
input.recovery = recovery_feedback_;
input.action = action_feedback_;

View File

@@ -11,6 +11,7 @@
#include <move_base2/io/sensor_store_types.h>
#include <robot_sensor_ports/sensor_writer.h>
#include <algorithm>
#include <cmath>
#include <mission_adapters/mission_request.h>
@@ -181,23 +182,41 @@ void NavigationServer::attachCostmaps(robot_costmap_2d::LayeredCostmap* global,
// Phát lại static map đã nhận trước khi costmap tồn tại. Chỉ static map, cố ý: một laser scan cũ
// phát lại vào costmap là dựng vật cản ở chỗ robot có thể đã rời khỏi từ lâu — im lặng và nguy
// hiểm hơn hẳn việc chờ mẫu kế tiếp, vốn chỉ cách vài chục ms.
std::map<std::string, robot_nav_msgs::OccupancyGrid> maps;
using ReplayEntry = std::pair<std::uint64_t,
std::pair<std::string, robot_nav_msgs::OccupancyGrid>>;
std::vector<ReplayEntry> maps;
std::pair<std::string, robot_nav_msgs::OccupancyGrid> legacy_map;
bool has_legacy_map = false;
{
std::lock_guard<std::mutex> lock(data_mutex_);
maps = static_maps_;
maps.reserve(static_maps_.size());
for (const auto& entry : static_maps_)
{
maps.push_back({ static_map_sequences_.at(entry.first), entry });
}
// `map_save_`/`map_name_save_` là cặp biến PUBLIC của BaseNavigation mà host tự gán (đường bù
// của bản cũ cho đúng vấn đề này). Tôn trọng nó để host không phải sửa gì, nhưng không để nó
// ghi đè bản đã đi qua addStaticMap.
if (!map_name_save_.empty() && maps.find(map_name_save_) == maps.end())
if (!map_name_save_.empty() && static_maps_.find(map_name_save_) == static_maps_.end())
{
maps[map_name_save_] = map_save_;
legacy_map = { map_name_save_, map_save_ };
has_legacy_map = true;
}
}
// The static map must precede its direction grid: the app must resend the direction grid
// immediately after every static map. Replaying by topic name would reverse that order.
std::sort(maps.begin(), maps.end(), [](const ReplayEntry& a, const ReplayEntry& b) {
return a.first < b.first;
});
if (has_legacy_map)
{
sensors_.pushStaticMap(legacy_map.first, legacy_map.second);
}
for (const auto& entry : maps)
{
sensors_.pushStaticMap(entry.first, entry.second);
sensors_.pushStaticMap(entry.second.first, entry.second.second);
}
}
@@ -693,6 +712,7 @@ void NavigationServer::addStaticMap(const std::string& topic, robot_nav_msgs::Oc
{
std::lock_guard<std::mutex> lock(data_mutex_);
static_maps_[topic] = map;
static_map_sequences_[topic] = ++next_static_map_sequence_;
}
sensors_.pushStaticMap(topic, map);
}
@@ -825,6 +845,7 @@ bool NavigationServer::removeStaticMap(const std::string& topic)
sensor_store_.clearTopic(topic);
std::lock_guard<std::mutex> lock(data_mutex_);
static_map_sequences_.erase(topic);
return static_maps_.erase(topic) > 0;
}
@@ -866,6 +887,7 @@ bool NavigationServer::removeAllStaticMaps()
std::lock_guard<std::mutex> lock(data_mutex_);
static_maps_.clear();
static_map_sequences_.clear();
return true;
}
@@ -906,6 +928,7 @@ bool NavigationServer::removeAllData()
{
std::lock_guard<std::mutex> lock(data_mutex_);
static_maps_.clear();
static_map_sequences_.clear();
laser_scans_.clear();
point_clouds_.clear();
point_cloud2s_.clear();

View File

@@ -8,7 +8,9 @@
*********************************************************************/
#include <move_base2/runners/planner_runner.h>
#include <algorithm>
#include <cmath>
#include <chrono>
#include <exception>
#include <utility>
@@ -19,12 +21,51 @@
#include <robot/plugin_loader_helper.h>
#include <robot/robot.h>
#include <robot_costmap_2d/costmap_2d_robot.h>
#include <robot_costmap_2d/direction_field.h>
#include <robot_costmap_2d/layer.h>
#include <robot_costmap_2d/layered_costmap.h>
namespace move_base2
{
namespace
{
// Called with the master mutex held. Direction providers own a separate mutex, so their
// snapshot is the race-free equivalent of Layer::isCurrent() for those layers.
bool costmapReady(robot_costmap_2d::LayeredCostmap& costmap, std::string* stale_names)
{
const auto& layers = *costmap.getPlugins();
std::size_t providers = 0;
for (const auto& layer : layers)
if (layer && layer->isEnabled() &&
dynamic_cast<const robot_costmap_2d::DirectionFieldProvider*>(layer.get()))
++providers;
bool ready = true;
if (stale_names)
stale_names->clear();
for (const auto& layer : layers)
{
if (!layer || !layer->isEnabled())
continue;
const auto* provider = dynamic_cast<const robot_costmap_2d::DirectionFieldProvider*>(layer.get());
const bool current = provider
? providers == 1 && provider->directionSnapshot().state != robot_costmap_2d::DirectionFieldState::kPending
: layer->getType() != robot_costmap_2d::LayerType::DIRECTIONAL_LAYER && layer->isCurrent();
if (!current)
{
ready = false;
if (stale_names)
{
if (!stale_names->empty())
stale_names->append(", ");
stale_names->append(layer->getName());
}
}
}
return ready;
}
/// @brief Pose có dùng được để lập plan không — NaN/Inf lọt vào SBPL là hỏng ở tầng khó truy nhất.
bool isFinitePose(const robot_geometry_msgs::PoseStamped& pose)
{
@@ -430,6 +471,9 @@ bool PlannerRunner::swapPlanner(const std::string& planner_name)
// Thread chưa nhận: rút yêu cầu ra, kẻo nó chạy yêu cầu của planner cũ trên instance mới rồi
// vứt — tốn một lượt makePlan vô ích.
pending_ = false;
waiting_for_costmap_ = false;
if (status_board_ != nullptr)
status_board_->enter(Component::kGlobalPlanner, ComponentPhase::kIdle);
request_order_.reset();
}
else if (running_)
@@ -445,6 +489,7 @@ bool PlannerRunner::swapPlanner(const std::string& planner_name)
}
active_ = planner;
active_external_grid_ = external_grid ? &external_grid : nullptr;
cv_.notify_all();
}
active_name_ = planner_name;
@@ -510,6 +555,9 @@ bool PlannerRunner::startPlan(const robot_geometry_msgs::PoseStamped& start,
pending_ = true;
discard_ = false;
has_result_ = false;
waiting_for_costmap_ = costmap_lock_enabled_ && costmap_ready_timeout_ > 0.0;
if (waiting_for_costmap_ && status_board_ != nullptr)
status_board_->enter(Component::kGlobalPlanner, ComponentPhase::kWaitingForCostmap);
cv_.notify_one();
return true;
@@ -521,6 +569,20 @@ bool PlannerRunner::isPlanning() const
return pending_ || running_;
}
void PlannerRunner::setCostmapReadyTimeout(double seconds)
{
std::lock_guard<std::mutex> lock(mutex_);
costmap_ready_timeout_ = seconds;
}
bool PlannerRunner::costmapWaitState(bool& finished)
{
std::lock_guard<std::mutex> lock(mutex_);
finished = costmap_wait_finished_;
costmap_wait_finished_ = false;
return waiting_for_costmap_;
}
bool PlannerRunner::pollPlan(PlanResult& result)
{
std::lock_guard<std::mutex> lock(mutex_);
@@ -567,6 +629,9 @@ void PlannerRunner::cancelPlan()
// sẽ nhận job này NGAY SAU cancel, chạy trọn allocated_time cho một plan không ai cần (bắt được
// bằng test CancelPreemptsAPreemptablePlannerWithinMilliseconds, 2026-09-11).
pending_ = false;
waiting_for_costmap_ = false;
if (status_board_ != nullptr)
status_board_->enter(Component::kGlobalPlanner, ComponentPhase::kIdle);
request_order_.reset();
}
else if (pending_ || running_)
@@ -588,6 +653,7 @@ void PlannerRunner::cancelPlan()
// Kết quả đã nằm sẵn trong hộp thư cũng bỏ luôn: bên gọi vừa nói nó không còn cần plan này.
has_result_ = false;
handoff_.clear();
cv_.notify_all();
}
// ================================================================================================
@@ -617,15 +683,16 @@ void PlannerRunner::threadBody()
// control thread không bao giờ phải chờ một lượt lập plan.
robot_nav_core::BaseGlobalPlanner* planner = active_;
const ExternalGridSetter* external_grid = active_external_grid_;
running_planner_ = planner;
running_planner_ = nullptr;
const robot_geometry_msgs::PoseStamped start = request_start_;
const robot_geometry_msgs::PoseStamped goal = request_goal_;
const std::shared_ptr<robot_protocol_msgs::Order> order = request_order_;
const std::uint64_t tag = request_tag_;
const double ready_timeout = costmap_ready_timeout_;
pending_ = false;
running_ = true;
if (status_board_ != nullptr)
if (status_board_ != nullptr && !waiting_for_costmap_)
{
status_board_->enter(Component::kGlobalPlanner, ComponentPhase::kBusy);
}
@@ -634,10 +701,10 @@ void PlannerRunner::threadBody()
planning_.clear();
bool ok = false;
bool waited = false;
try
{
ScopedSection timer(stats_, section_make_plan_);
// Planner phải thấy một lưới ĐÔNG CỨNG suốt makePlan: LayeredCostmap::updateMap ghi lưới, và
// resizeMap REALLOC cả mảng, dưới Costmap2D::getMutex(). Hai cách đạt được điều đó:
//
@@ -650,32 +717,118 @@ void PlannerRunner::threadBody()
// đứng chờ hết lượt search; với SBPL cạn search trên map lớn là 6-14 s (đo 2026-09-17).
// Đây là đường rơi về khi tắt snapshot hoặc plugin không nhận lưới ngoài.
//
// Kiểm "costmap đã sẵn sàng" (P4, Test/docs/DIRECTION_ZONE_PLAN.md mục 7.3) chạy dưới CÙNG lần
// khoá đó, nên lưới planner đọc chính là lưới vừa được xác nhận current. Chưa current thì nhả
// khoá, chờ có hạn `costmap_ready_timeout` rồi kiểm lại; không gọi makePlan trên map dở dang.
//
// Lấy getCostmap() mỗi lượt, không cache — con trỏ đó có thể bị thay (bài học double-free của
// workspace). Với capability có mà snapshot TẮT, vẫn gọi setter với nullptr: xoá lưới ngoài
// còn sót từ cấu hình trước, để planner đọc lưới sống dưới khoá dài đúng như (b).
boost::unique_lock<robot_costmap_2d::Costmap2D::mutex_t> costmap_lock;
if (costmap_lock_enabled_)
using Clock = std::chrono::steady_clock;
Clock::time_point wait_started;
std::string& stale_names = costmap_stale_names_;
while (true)
{
boost::unique_lock<robot_costmap_2d::Costmap2D::mutex_t> costmap_lock;
const bool has_setter = external_grid != nullptr && static_cast<bool>(*external_grid);
if (has_setter && costmap_->isSnapshotEnabled())
const bool use_snapshot = costmap_lock_enabled_ && has_setter && costmap_->isSnapshotEnabled();
if (costmap_lock_enabled_)
costmap_lock = boost::unique_lock<robot_costmap_2d::Costmap2D::mutex_t>(
*costmap_->getCostmap()->getMutex());
// updateMap and StaticLayer callbacks use this same master mutex. For a snapshot, the
// recursive mutex remains held across both readiness and refreshSnapshot's copy. For a
// live grid it stays held through makePlan. Direction providers use their own snapshot lock.
if (costmap_lock_enabled_ && ready_timeout > 0.0 && !costmap_stale_names_reserved_)
{
std::size_t capacity = 0;
for (const auto& layer : *costmap_->getLayeredCostmap()->getPlugins())
if (layer) capacity += layer->getName().size() + 2;
stale_names.reserve(capacity);
costmap_stale_names_reserved_ = true;
}
const bool ready = !costmap_lock_enabled_ || ready_timeout == 0.0 ||
costmapReady(*costmap_->getLayeredCostmap(), &stale_names);
const auto now = Clock::now();
if (!ready && !waited)
{
waited = true;
wait_started = now;
if (!costmap_wait_problem_active_)
{
costmap_wait_problem_active_ = true;
last_costmap_wait_log_ = now;
robot::log_warning("[move_base2] PlannerRunner: waiting for global costmap; not current: %s\n",
stale_names.c_str());
}
}
const double elapsed = waited ? std::chrono::duration<double>(now - wait_started).count() : 0.0;
const CostmapReadyDecision decision = costmapReadyDecision(ready, elapsed, ready_timeout);
if (decision == CostmapReadyDecision::kTimeout)
{
if (last_costmap_timeout_log_ == Clock::time_point{} ||
std::chrono::duration<double>(now - last_costmap_timeout_log_).count() >= 5.0)
{
robot::log_error("[move_base2] PlannerRunner: global costmap readiness timed out after %.2f s; not current: %s\n",
elapsed, stale_names.c_str());
last_costmap_timeout_log_ = now;
}
break;
}
if (decision == CostmapReadyDecision::kWait)
{
if (std::chrono::duration<double>(now - last_costmap_wait_log_).count() >= 5.0)
{
robot::log_warning("[move_base2] PlannerRunner: still waiting for global costmap (%.2f s); not current: %s\n",
elapsed, stale_names.c_str());
last_costmap_wait_log_ = now;
}
costmap_lock.unlock();
lock.lock();
const double poll_seconds = std::min(0.05, ready_timeout - elapsed);
cv_.wait_for(lock, std::chrono::duration<double>(poll_seconds),
[this] { return shutdown_ || discard_; });
const bool cancelled = shutdown_ || discard_;
lock.unlock();
if (cancelled)
break;
continue;
}
if (use_snapshot)
{
costmap_->refreshSnapshot();
(*external_grid)(planner, costmap_->getCostmapForRead());
}
else
else if (costmap_lock_enabled_ && has_setter)
(*external_grid)(planner, nullptr);
lock.lock();
const bool cancelled = shutdown_ || discard_;
waiting_for_costmap_ = false;
costmap_wait_finished_ = costmap_wait_finished_ || waited;
if (!cancelled)
{
if (has_setter)
{
(*external_grid)(planner, nullptr);
}
costmap_lock = boost::unique_lock<robot_costmap_2d::Costmap2D::mutex_t>(
*(costmap_->getCostmap()->getMutex()));
running_planner_ = planner;
if (status_board_ != nullptr)
status_board_->enter(Component::kGlobalPlanner, ComponentPhase::kBusy);
}
lock.unlock();
if (cancelled)
break;
if (use_snapshot)
costmap_lock.unlock();
if (costmap_wait_problem_active_)
{
robot::log_info("[move_base2] PlannerRunner: global costmap is ready; planning resumes.\n");
costmap_wait_problem_active_ = false;
last_costmap_timeout_log_ = Clock::time_point{};
}
ScopedSection timer(stats_, section_make_plan_);
ok = (order != nullptr) ? planner->makePlan(*order, start, goal, planning_)
: planner->makePlan(start, goal, planning_);
break;
}
// Hai overload của interface gốc gộp lại: "có Order hay không" là một nhánh, không phải hai
// contract. Plugin nào không hiểu Order thì overload mặc định của nó tự lo.
ok = (order != nullptr) ? planner->makePlan(*order, start, goal, planning_)
: planner->makePlan(start, goal, planning_);
}
catch (const std::exception& ex)
{
@@ -701,6 +854,9 @@ void PlannerRunner::threadBody()
}
lock.lock();
if (waiting_for_costmap_ && waited)
costmap_wait_finished_ = true;
waiting_for_costmap_ = false;
running_ = false;
running_planner_ = nullptr;
if (status_board_ != nullptr)

View File

@@ -540,6 +540,13 @@ StateMachineOutput StateMachine::update(const StateMachineInput& in)
break;
}
// Waiting for input is not planning time and must not consume the retry budget.
// The completion event also covers a wait which began and ended between control cycles.
if (in.planner_costmap_wait_finished || in.planner == PlannerFeedback::kWaitingForCostmap)
last_valid_plan_ = in.now;
if (in.planner == PlannerFeedback::kWaitingForCostmap)
break;
if (in.planner == PlannerFeedback::kPlanReady)
{
out.apply_plan = true;

View File

@@ -94,7 +94,8 @@ TEST(ComponentStatusBoard, EveryComponentAndPhaseHasAName)
EXPECT_NE(name, "unknown");
}
for (const ComponentPhase p : {ComponentPhase::kIdle, ComponentPhase::kBusy, ComponentPhase::kStopping,
ComponentPhase::kPaused, ComponentPhase::kHung})
ComponentPhase::kPaused, ComponentPhase::kHung,
ComponentPhase::kWaitingForCostmap})
{
const std::string name = move_base2::toString(p);
EXPECT_FALSE(name.empty());

View File

@@ -11,6 +11,7 @@
#include <gtest/gtest.h>
#include <cstdlib>
#include <limits>
#include <string>
#include <robot/node_handle.h>
@@ -55,6 +56,35 @@ TEST(MoveBase2Config, DefaultsAreValid)
EXPECT_TRUE(config.validate(error)) << error;
}
TEST(MoveBase2Config, CostmapReadyTimeoutValidation)
{
MoveBase2Config config = minimalValid();
std::string error;
EXPECT_DOUBLE_EQ(config.costmap_ready_timeout, 10.0);
EXPECT_DOUBLE_EQ(config.toControlLoopConfig().costmap_ready_timeout, 10.0);
EXPECT_NE(config.describe().find("costmap_ready_timeout"), std::string::npos);
config.costmap_ready_timeout = 0.0;
EXPECT_TRUE(config.validate(error));
for (double invalid : {-1.0, std::numeric_limits<double>::infinity(),
std::numeric_limits<double>::quiet_NaN()})
{
config.costmap_ready_timeout = invalid;
EXPECT_FALSE(config.validate(error));
EXPECT_NE(error.find("costmap_ready_timeout"), std::string::npos);
}
}
TEST(MoveBase2Config, ReadsCostmapReadyTimeout)
{
robot::NodeHandle root;
robot::NodeHandle nh(root, "costmap_ready_timeout_test");
nh.setParam("costmap_ready_timeout", 3.5);
MoveBase2Config config;
config.fromNodeHandle(nh);
EXPECT_DOUBLE_EQ(config.costmap_ready_timeout, 3.5);
EXPECT_DOUBLE_EQ(config.toControlLoopConfig().costmap_ready_timeout, 3.5);
}
TEST(MoveBase2Config, CancelSettleKeysFallBackToDefaultsWhenAbsent)
{
// Cây config cũ (trước 2026-09-11) không có ba khoá này: phải giữ default BẬT (2 s, 0.02) chứ

View File

@@ -13,6 +13,7 @@
#include <chrono>
#include <cmath>
#include <cstddef>
#include <future>
#include <limits>
#include <string>
#include <thread>
@@ -195,7 +196,6 @@ public:
server_.attachCostmaps(&global_, &local_);
}
NavigationServer server_;
FakeClockPort clock_;
FakePosePort pose_;
FakePlannerPort planner_;
@@ -208,6 +208,10 @@ public:
robot_costmap_2d::LayeredCostmap global_;
robot_costmap_2d::LayeredCostmap local_;
// The server joins its control thread in its destructor. Declare it last so all borrowed
// ports, status data and costmaps outlive that join.
NavigationServer server_;
};
} // namespace
@@ -611,6 +615,74 @@ TEST(NavigationServerSensors, StaticMapReceivedBeforeAttachIsReplayed)
EXPECT_EQ(static_layer->records()[0].topic, "/map");
}
TEST(CostmapReadyDecision, ReadyWaitTimeoutAndLegacy)
{
using move_base2::CostmapReadyDecision;
using move_base2::costmapReadyDecision;
EXPECT_EQ(costmapReadyDecision(false, 0.0, 10.0), CostmapReadyDecision::kWait);
EXPECT_EQ(costmapReadyDecision(false, 9.99, 10.0), CostmapReadyDecision::kWait);
EXPECT_EQ(costmapReadyDecision(false, 10.0, 10.0), CostmapReadyDecision::kTimeout);
EXPECT_EQ(costmapReadyDecision(true, 3.0, 10.0), CostmapReadyDecision::kPlan);
EXPECT_EQ(costmapReadyDecision(false, 0.0, 0.0), CostmapReadyDecision::kPlan);
}
TEST(NavigationServerSensors, ReplayUsesLatestArrivalOrder)
{
Fixture fixture;
fixture.configure();
const robot_nav_msgs::OccupancyGrid grid;
fixture.server_.addStaticMap("/map", grid);
fixture.server_.addStaticMap("/direction_map", grid);
SpyPtr layer = attachSpy(fixture.global_, LayerType::STATIC_LAYER, "replay_spy");
fixture.attachCostmaps();
ASSERT_EQ(layer->count(), 2U);
EXPECT_EQ(layer->records()[0].topic, "/map");
EXPECT_EQ(layer->records()[1].topic, "/direction_map");
// The live pushes are followed by a second replay after both latest arrivals.
fixture.server_.addStaticMap("/map", grid);
fixture.server_.addStaticMap("/direction_map", grid);
fixture.attachCostmaps();
ASSERT_EQ(layer->count(), 6U);
EXPECT_EQ(layer->records()[4].topic, "/map");
EXPECT_EQ(layer->records()[5].topic, "/direction_map");
}
TEST(NavigationServerSensors, ReplayForgetsErasedAndClearedSequences)
{
Fixture fixture;
fixture.configure();
const robot_nav_msgs::OccupancyGrid grid;
fixture.server_.addStaticMap("/map", grid);
fixture.server_.addStaticMap("/direction_map", grid);
ASSERT_TRUE(fixture.server_.removeStaticMap("/map"));
fixture.server_.addStaticMap("/map", grid);
SpyPtr layer = attachSpy(fixture.global_, LayerType::STATIC_LAYER, "replay_spy");
fixture.attachCostmaps();
ASSERT_EQ(layer->count(), 2U);
EXPECT_EQ(layer->records()[0].topic, "/direction_map");
EXPECT_EQ(layer->records()[1].topic, "/map");
ASSERT_TRUE(fixture.server_.removeAllStaticMaps());
fixture.server_.addStaticMap("/direction_map", grid);
const std::size_t before_clear_replay = layer->count();
fixture.attachCostmaps();
ASSERT_EQ(layer->count(), before_clear_replay + 1U);
EXPECT_EQ(layer->records()[before_clear_replay].topic, "/direction_map");
ASSERT_TRUE(fixture.server_.removeAllData());
fixture.server_.addStaticMap("/map", grid);
fixture.server_.addStaticMap("/direction_map", grid);
fixture.server_.map_name_save_ = "/legacy";
const std::size_t before_replay = layer->count();
fixture.attachCostmaps();
ASSERT_EQ(layer->count(), before_replay + 3U);
EXPECT_EQ(layer->records()[before_replay].topic, "/legacy");
EXPECT_EQ(layer->records()[before_replay + 1].topic, "/map");
EXPECT_EQ(layer->records()[before_replay + 2].topic, "/direction_map");
}
TEST(NavigationServerSensors, LegacyMapSavePublicMemberIsAlsoReplayed)
{
// `map_save_`/`map_name_save_` là biến PUBLIC của BaseNavigation mà host tự gán
@@ -1203,12 +1275,33 @@ TEST(NavigationServerControlThread, SecondStartIsRefusedAndStopIsIdempotent)
TEST(NavigationServerControlThread, DestructorStopsTheThread)
{
// Thread chạm loop_, runtime_ và sensors_ mỗi cycle; huỷ chúng khi thread còn sống là hỏng ở chỗ
// không truy được.
Fixture fixture;
fixture.configure();
ASSERT_TRUE(fixture.server_.startControlThread(100.0));
SUCCEED(); // destructor của fixture phải join, không treo
// Wait until a real cycle has begun; fixture destruction must join before its borrowed ports die.
class SignallingClock final : public move_base2::ClockPort
{
public:
explicit SignallingClock(std::promise<void>& started) : started_(started) {}
robot::Time now() const override
{
if (!signalled_.exchange(true))
started_.set_value();
return robot::Time(kClockStart);
}
private:
std::promise<void>& started_;
mutable std::atomic<bool> signalled_{false};
};
std::promise<void> started;
auto first_cycle = started.get_future();
SignallingClock clock(started);
{
Fixture fixture;
fixture.deps_.clock = &clock;
fixture.configure();
ASSERT_TRUE(fixture.server_.startControlThread(100.0));
ASSERT_EQ(first_cycle.wait_for(std::chrono::seconds(2)), std::future_status::ready);
}
}
// ================================================================================================

View File

@@ -393,6 +393,31 @@ TEST(StateMachinePlanning, PlannerPatienceEscalatesToRecovery)
EXPECT_TRUE(out.stop_planner);
}
TEST(StateMachinePlanning, CostmapWaitDoesNotSpendPatienceOrRetries)
{
StateMachineConfig config = baseConfig();
config.max_planning_retries = 0;
Driver driver(config);
StateMachineInput request;
request.has_pending_request = true;
ASSERT_EQ(driver.tick(request).state, NavigationState::kPlanning);
StateMachineInput waiting;
waiting.planner = PlannerFeedback::kWaitingForCostmap;
for (int i = 0; i < 20; ++i)
{
driver.advance(0.6);
EXPECT_EQ(driver.tick(waiting).state, NavigationState::kPlanning);
}
StateMachineInput busy;
busy.planner = PlannerFeedback::kBusy;
busy.planner_costmap_wait_finished = true;
driver.advance(0.6);
EXPECT_EQ(driver.tick(busy).state, NavigationState::kPlanning);
driver.advance(0.6);
EXPECT_EQ(driver.tick(StateMachineInput()).state, NavigationState::kPlanning);
EXPECT_EQ(driver.tick(plannerFailed()).state, NavigationState::kRecovering);
}
TEST(StateMachinePlanning, MaxRetriesEscalatesBeforePatienceExpires)
{
StateMachineConfig config = baseConfig();

View File

@@ -72,6 +72,20 @@ TEST(Watchdog, IdleRowsAreNeverHung)
EXPECT_FALSE(dog.anyHung()) << "idle for a long time is not 'hung'";
}
TEST(Watchdog, WaitingForCostmapDoesNotConsumePlannerBudget)
{
ComponentStatusBoard board;
Watchdog dog;
std::string error;
WatchdogConfig c = fastConfig();
c.period = 0.0;
ASSERT_TRUE(dog.start(&board, c, error)) << error;
board.enter(Component::kGlobalPlanner, ComponentPhase::kWaitingForCostmap);
sleepMs(80);
dog.checkOnce();
EXPECT_FALSE(dog.hung(Component::kGlobalPlanner));
}
TEST(Watchdog, BusyWithoutProgressBecomesHungAndRecoversOnProgress)
{
ComponentStatusBoard board;