Files
move_base2/test/walking_skeleton_test.cpp
duongtd 8bc4895a60 feat: lifecycle contract — cancel/pause must reach true quiescence before reporting done
Root cause (from a C++ host log, 2026-09-11): cancel during PLANNING only set
a discard flag on the planner thread, which ran to allocated_time before
CANCELLED could be reported; a queued next mission landed on a still-busy
planner and timed out too. Same class of bug existed for pause, recovery, and
implicitly for a legitimate ABORTED read while a component was still
unwinding. Full audit, decisions, and phased design in
docs/PLAN_LIFECYCLE_CANCEL_PAUSE_RESUME.md; old-vs-new behaviour per state in
docs/LIFECYCLE_BEHAVIOUR_MATRIX.md.

Runtime quiescence, not just "command sent":
- kPausing (new state) mirrors kCancelling: PAUSED/CANCELLED is only entered
  once planner and recovery are idle, the action reports terminal, and the
  robot is stopped per odometry (robot_stopped, stopped_measured_linear/
  angular_eps) — not merely "the command we sent was zero". settle_timeout
  bounds the wait; exceeding it still finishes but logs an ungated error
  naming which component was still busy, so a plugin that doesn't honour
  cancel/pause is visible instead of silently swallowed.
- PlannerRunner::running_planner_ (new): the instance the planner thread is
  actually inside makePlan() with, tracked separately from active_ — active_
  can already point at a different instance after swapPlanner() while the
  old attempt is still running. cancelPlan(), swapPlanner() (when a job is
  running_ or only pending_ and not yet picked up), and the destructor all
  preempt through this pointer now; the old code preempted through active_
  and could silently preempt the wrong (idle) instance after a profile swap.
- ComponentStatusBoard + per-component ComponentPhase (idle/busy/stopping/
  paused/hung), read by PlannerRunner, RecoveryRunner, ActionRunner and
  ControlLoop instead of ad hoc bools — this is what makes "did everything
  actually stop" answerable at all, and what the new Watchdog thread reads
  to flag a component busy-without-progress as hung (logged once at the
  edge) without the control loop needing to detect its own stall.
- Resume: PLANNING replans from the current pose. CONTROLLING re-issues
  setPlan() with the plan already in hand (decided: setPlan again, not a
  fresh plan) — the local planner needs nothing else since it already runs
  once per control cycle; a fresh plan on resume was considered and
  rejected as unnecessary work for a plan that's still valid.
- Command-to-zero on cancel/pause stays immediate (no deceleration ramp) —
  existing VelocityArbiter behaviour, left as is per a scoped decision.

Depends on: Test/sbpl (bd89924), pnkx_nav_core (2b0993b, robot_nav_core::
Preemptable + component_status_probe.h), Test/sbpl_lattice_planner (7456e99),
Test/recovery_core (254c7fc, onCancelRequested + ABI guard), Test/
sbpl_recovery (ea79686, worker-thread cancel), Test/action_core (669c3f7,
pause/resume + kCancelled), Test/dock_pattern_action (cc1ea74).

Verified: 13 gtest binaries / 528 tests, 0 failures. Runtime on the dev
machine (Gazebo + real ROS host + VDA5050 over MQTT), 6 scenarios — cancel
during PLANNING, pause/resume during PLANNING and CONTROLLING (incl.
submit-while-still-winding-down), pause-then-cancel during PLANNING and
CONTROLLING: no ABORTED/RECOVERING in any run, preempt lands within
hundredths of a millisecond of entering CANCELLING/PAUSING, PAUSED/CANCELLED
only reported once the robot is actually stopped per odometry. Full numbers
in the plan doc section 6.

Excluded from this commit (pre-existing, unrelated):
config/runtime/recovery_behaviors_params.yaml (allocated_time 1.0->2.0,
SBPLDetourPlanner tuning predating this work).

Not yet done (see plan doc "Trạng thái"): config tuning (phase 0, pending
per a scoping decision); runtime scenarios for cancel mid-detour and a 30 s
pause mid-action; commit to rb_ws is a separate step, not done here.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-12 22:07:34 +07:00

2116 lines
79 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/*********************************************************************
*
* Software License Agreement (BSD License)
*
* move_base2 — test bộ khung chạy end-to-end với thành phần giả.
*
* Đây là test chứng minh contract giữa các cổng đã khớp: nhận yêu cầu, đi qua đủ state, gọi đúng
* cổng, phát đúng lệnh vận tốc, và báo kết quả đúng một lần.
*
* Author: DuongTD
*********************************************************************/
#include <gtest/gtest.h>
#include <algorithm>
#include <string>
#include <vector>
#include <move_base2/control_loop.h>
#include "fake_ports.h"
using move_base2::ControlLoop;
using move_base2::ControlLoopConfig;
using move_base2::ControlLoopDeps;
using move_base2::MotionProfile;
using move_base2::NavigationRequest;
using move_base2::NavigationState;
using move_base2::RecoveryTrigger;
using move_base2::testing::ActionScript;
using move_base2::testing::ControllerScript;
using move_base2::testing::FakeActionPort;
using move_base2::testing::FakeClockPort;
using move_base2::testing::FakeControllerPort;
using move_base2::testing::FakeCostmapStatusPort;
using move_base2::testing::FakeMissionPort;
using move_base2::testing::FakeEnvironmentPort;
using move_base2::testing::FakePlannerPort;
using move_base2::testing::FakePosePort;
using move_base2::testing::FakeRecoveryPort;
using move_base2::testing::PlannerScript;
using move_base2::testing::RecoveryScript;
namespace
{
constexpr double kControlPeriod = 0.05; ///< [s]
ControlLoopConfig baseConfig()
{
ControlLoopConfig config;
config.state_machine.planner_patience = 0.5; // [s]
config.state_machine.controller_patience = 0.5; // [s]
config.state_machine.oscillation_timeout = 0.0; // tắt
config.state_machine.oscillation_distance = 0.5; // [m]
config.state_machine.max_planning_retries = -1;
config.state_machine.recovery_behavior_count = 2;
config.state_machine.recovery_enabled = true;
config.velocity.max_vel_x = 0.5; // [m/s]
config.velocity.min_vel_x = -0.2; // [m/s]
config.velocity.max_vel_theta = 1.0; // [rad/s]
config.velocity.max_accel_x = 100.0; // [m/s^2] lớn để test tập trung vào state, không vào ramp
config.velocity.max_accel_theta = 100.0; // [rad/s^2]
config.nominal_control_period = kControlPeriod;
config.position.global_planner_name = "FakeGlobalPlanner";
config.position.local_planner_name = "FakeLocalPlanner";
config.docking = config.position;
config.docking.local_planner_name = "FakeDockPlanner";
config.go_straight = config.position;
config.go_straight.local_planner_name = "FakeStraightPlanner";
config.rotate = config.position;
config.rotate.local_planner_name = "FakeRotatePlanner";
return config;
}
NavigationRequest makeRequest(double goal_x, std::uint64_t sequence_id = 0)
{
NavigationRequest request;
request.profile = MotionProfile::kPosition;
request.goal.header.frame_id = "map";
request.goal.pose.position.x = goal_x;
request.goal.pose.orientation.w = 1.0;
request.mission_sequence_id = sequence_id;
return request;
}
/// @brief Gắn @p count action tên "act_<i>" vào yêu cầu — kiểm được thứ tự tới ActionPort (D8).
NavigationRequest withActions(NavigationRequest request, std::size_t count)
{
for (std::size_t i = 0; i < count; ++i)
{
robot_protocol_msgs::Action action;
action.actionType = "act_" + std::to_string(i);
request.actions.push_back(action);
}
return request;
}
/// @brief Yêu cầu chỉ-có-action (D8): has_goal = false, goal để mặc định — không được validate.
NavigationRequest makeActionOnlyRequest(std::size_t count, std::uint64_t sequence_id = 0)
{
NavigationRequest request;
request.has_goal = false;
request.mission_sequence_id = sequence_id;
return withActions(request, count);
}
/**
* @class Fixture
* @brief Dựng sẵn control loop nối với toàn bộ cổng giả.
*/
class Fixture
{
public:
explicit Fixture(const ControlLoopConfig& config = baseConfig()) : recovery_(2)
{
pose_.setPosition(0.0, 0.0);
deps_.clock = &clock_;
deps_.pose = &pose_;
deps_.planner = &planner_;
deps_.controller = &controller_;
deps_.recovery = &recovery_;
deps_.mission = &mission_;
deps_.action = &action_;
deps_.costmap_status = &costmap_status_;
deps_.environment = &environment_;
deps_.components = &components_;
planner_.attachStatusBoard(&components_);
recovery_.attachStatusBoard(&components_);
action_.attachStatusBoard(&components_);
std::string error;
EXPECT_TRUE(loop_.configure(config, deps_, error)) << error;
}
/// @brief Chạy tối đa @p max_cycles cycle, ghi lại chuỗi state (đã nén lặp liên tiếp).
void run(std::size_t max_cycles = 200)
{
for (std::size_t i = 0; i < max_cycles; ++i)
{
record();
if (!loop_.step())
{
record();
return;
}
clock_.advance(kControlPeriod);
}
hit_limit_ = true;
}
/// @brief Chạy đúng một cycle và ghi lại state sau cycle đó.
void stepOnce()
{
loop_.step();
clock_.advance(kControlPeriod);
record();
}
const std::vector<std::string>& states() const
{
return states_;
}
bool hitLimit() const
{
return hit_limit_;
}
ControlLoop loop_;
FakeClockPort clock_;
FakePosePort pose_;
FakePlannerPort planner_;
FakeControllerPort controller_;
FakeRecoveryPort recovery_;
FakeMissionPort mission_;
FakeActionPort action_;
FakeCostmapStatusPort costmap_status_;
FakeEnvironmentPort environment_;
move_base2::ComponentStatusBoard components_;
ControlLoopDeps deps_;
private:
void record()
{
const std::string name = move_base2::toString(loop_.state());
if (states_.empty() || states_.back() != name)
{
states_.push_back(name);
}
}
std::vector<std::string> states_;
bool hit_limit_ = false;
};
std::string join(const std::vector<std::string>& items)
{
std::string out = "[";
for (std::size_t i = 0; i < items.size(); ++i)
{
out += items[i];
if (i + 1 < items.size())
{
out += ", ";
}
}
return out + "]";
}
} // namespace
// ================================================================================================
// Cấu hình và cửa vào
// ================================================================================================
TEST(ControlLoop, RefusesToConfigureWithMissingPorts)
{
ControlLoop loop;
ControlLoopDeps deps; // toàn null
std::string error;
EXPECT_FALSE(loop.configure(baseConfig(), deps, error));
EXPECT_NE(error.find("port"), std::string::npos);
EXPECT_FALSE(loop.initialized());
}
TEST(ControlLoop, RefusesToConfigureWithInvalidVelocityLimits)
{
Fixture fixture;
ControlLoopConfig bad = baseConfig();
bad.velocity.max_vel_x = -1.0;
ControlLoop loop;
std::string error;
EXPECT_FALSE(loop.configure(bad, fixture.deps_, error));
}
TEST(ControlLoop, RefusesToConfigureWithoutPositionPlanner)
{
Fixture fixture;
ControlLoopConfig bad = baseConfig();
bad.position.local_planner_name.clear();
ControlLoop loop;
std::string error;
EXPECT_FALSE(loop.configure(bad, fixture.deps_, error));
EXPECT_NE(error.find("position"), std::string::npos);
}
TEST(ControlLoop, RejectsGoalWithInvalidQuaternion)
{
Fixture fixture;
NavigationRequest request = makeRequest(3.0);
request.goal.pose.orientation.w = 0.0; // norm = 0
std::string reason;
EXPECT_FALSE(fixture.loop_.submit(request, reason));
EXPECT_NE(reason.find("quaternion"), std::string::npos);
}
TEST(ControlLoop, RejectsGoalWithNonFiniteCoordinates)
{
Fixture fixture;
NavigationRequest request = makeRequest(3.0);
request.goal.pose.position.x = std::numeric_limits<double>::quiet_NaN();
std::string reason;
EXPECT_FALSE(fixture.loop_.submit(request, reason));
}
TEST(ControlLoop, RejectsRequestWhenLocalPlannerCannotBeLoaded)
{
Fixture fixture;
fixture.controller_.setSwapSucceeds(false);
std::string reason;
EXPECT_FALSE(fixture.loop_.submit(makeRequest(3.0), reason));
EXPECT_NE(reason.find("local planner"), std::string::npos);
}
TEST(ControlLoop, RejectsRequestWhenGlobalPlannerCannotBeLoaded)
{
Fixture fixture;
fixture.planner_.setSwapSucceeds(false);
std::string reason;
EXPECT_FALSE(fixture.loop_.submit(makeRequest(3.0), reason));
EXPECT_NE(reason.find("global planner"), std::string::npos);
}
TEST(ControlLoop, ProfileSelectsItsOwnLocalPlanner)
{
Fixture fixture;
NavigationRequest docking = makeRequest(1.0);
docking.profile = MotionProfile::kDocking;
docking.marker = "dock_a";
std::string reason;
ASSERT_TRUE(fixture.loop_.submit(docking, reason)) << reason;
EXPECT_EQ(fixture.controller_.activeController(), "FakeDockPlanner");
// Marker phải tới port TRƯỚC khi swap — planner đọc maker_name trong initialize().
EXPECT_EQ(fixture.controller_.lastDockingMarker(), "dock_a");
NavigationRequest rotate = makeRequest(1.0);
rotate.profile = MotionProfile::kRotate;
ASSERT_TRUE(fixture.loop_.submit(rotate, reason)) << reason;
EXPECT_EQ(fixture.controller_.activeController(), "FakeRotatePlanner");
}
TEST(ControlLoop, DockingMarkerProfileOverridesBothPlannersAndFallsBackToDefault)
{
ControlLoopConfig config = baseConfig();
config.docking_marker_profiles["trolley"].global_planner_name = "FakeTrolleyGlobalPlanner";
config.docking_marker_profiles["trolley"].local_planner_name = "FakeTrolleyLocalPlanner";
Fixture fixture(config);
NavigationRequest trolley = makeRequest(1.0);
trolley.profile = MotionProfile::kDocking;
trolley.marker = "trolley";
std::string reason;
ASSERT_TRUE(fixture.loop_.submit(trolley, reason)) << reason;
EXPECT_EQ(fixture.planner_.activePlanner(), "FakeTrolleyGlobalPlanner");
EXPECT_EQ(fixture.controller_.activeController(), "FakeTrolleyLocalPlanner");
NavigationRequest unconfigured = makeRequest(1.0);
unconfigured.profile = MotionProfile::kDocking;
unconfigured.marker = "charger";
ASSERT_TRUE(fixture.loop_.submit(unconfigured, reason)) << reason;
EXPECT_EQ(fixture.planner_.activePlanner(), "FakeGlobalPlanner");
EXPECT_EQ(fixture.controller_.activeController(), "FakeDockPlanner");
}
TEST(ControlLoop, AllowsGoalFrameStyleDockingWithoutMarker)
{
// Marker là tuỳ chọn từ 2026-09-06: docking chạy bằng goal_frame đã quy về pose tuyệt đối, local
// planner không đọc `maker_name`. Request không marker phải được nhận, không phải bị từ chối.
ControlLoopConfig config = baseConfig();
Fixture fixture(config);
NavigationRequest docking = makeRequest(1.0);
docking.profile = MotionProfile::kDocking;
std::string reason;
EXPECT_TRUE(fixture.loop_.submit(docking, reason)) << reason;
EXPECT_TRUE(fixture.controller_.lastDockingMarker().empty());
}
TEST(ControlLoop, RejectsDockingRequestWhenMarkerIsUnknown)
{
Fixture fixture;
fixture.controller_.setDockingMarkerSucceeds(false); // marker không có trong maker_sources
NavigationRequest docking = makeRequest(1.0);
docking.profile = MotionProfile::kDocking;
docking.marker = "tram_la";
std::string reason;
EXPECT_FALSE(fixture.loop_.submit(docking, reason));
EXPECT_NE(reason.find("tram_la"), std::string::npos) << reason;
}
// ================================================================================================
// Đường đi thuận lợi
// ================================================================================================
TEST(ControlLoop, HappyPathReachesSucceededAndReportsOnce)
{
Fixture fixture;
fixture.planner_.setScript({PlannerScript::kOk});
fixture.controller_.setScript({ControllerScript::kOk, ControllerScript::kOk,
ControllerScript::kOk, ControllerScript::kGoalReached});
std::string reason;
ASSERT_TRUE(fixture.loop_.submit(makeRequest(3.0, 42), reason)) << reason;
fixture.run();
EXPECT_FALSE(fixture.hitLimit());
EXPECT_EQ(fixture.states(), (std::vector<std::string>{"IDLE", "PLANNING", "CONTROLLING",
"SUCCEEDED"}))
<< join(fixture.states());
EXPECT_STREQ(fixture.loop_.lastOutcome(), "SUCCEEDED");
EXPECT_EQ(fixture.loop_.outcomeReportCount(), 1u);
EXPECT_EQ(fixture.mission_.reportCountFor(42), 1u)
<< "each leg may report its outcome exactly once";
}
TEST(ControlLoop, DirectGoalWithoutMissionIdDoesNotTouchMissionLayer)
{
Fixture fixture;
fixture.controller_.setScript({ControllerScript::kOk, ControllerScript::kGoalReached});
std::string reason;
ASSERT_TRUE(fixture.loop_.submit(makeRequest(3.0, 0), reason)) << reason;
fixture.run();
EXPECT_EQ(fixture.loop_.outcomeReportCount(), 1u);
EXPECT_TRUE(fixture.mission_.reports().empty())
<< "a direct goal belongs to no mission so nothing is reported to the mission layer";
}
TEST(ControlLoop, ControllerCommandIsPublishedWhileControlling)
{
Fixture fixture;
fixture.controller_.setNominalSpeed(0.3);
fixture.controller_.setScript({ControllerScript::kOk});
std::string reason;
ASSERT_TRUE(fixture.loop_.submit(makeRequest(3.0), reason)) << reason;
fixture.loop_.step(); // IDLE -> PLANNING (lập plan trong cycle này)
fixture.clock_.advance(kControlPeriod);
fixture.loop_.step(); // PLANNING -> CONTROLLING, chạy controller ngay
ASSERT_EQ(fixture.loop_.state(), NavigationState::kControlling);
EXPECT_NEAR(fixture.loop_.lastCommand().linear.x, 0.3, 1e-9);
}
TEST(ControlLoop, OrderIsForwardedToThePlanner)
{
Fixture fixture;
NavigationRequest request = makeRequest(3.0);
request.order = std::make_shared<robot_protocol_msgs::Order>();
std::string reason;
ASSERT_TRUE(fixture.loop_.submit(request, reason)) << reason;
fixture.loop_.step();
EXPECT_TRUE(fixture.planner_.sawOrder());
}
// ================================================================================================
// Bất biến an toàn
// ================================================================================================
TEST(ControlLoop, NoVelocityIsEmittedOutsideControllingAndRecovering)
{
Fixture fixture;
fixture.controller_.setScript({ControllerScript::kOk, ControllerScript::kOk,
ControllerScript::kGoalReached});
std::string reason;
ASSERT_TRUE(fixture.loop_.submit(makeRequest(3.0), reason)) << reason;
for (int i = 0; i < 50; ++i)
{
const bool running = fixture.loop_.step();
const NavigationState state = fixture.loop_.state();
if (move_base2::mustBeStopped(state))
{
ASSERT_DOUBLE_EQ(fixture.loop_.lastCommand().linear.x, 0.0)
<< "state " << move_base2::toString(state) << " at cycle " << i;
ASSERT_DOUBLE_EQ(fixture.loop_.lastCommand().angular.z, 0.0)
<< "state " << move_base2::toString(state) << " at cycle " << i;
}
if (!running)
{
break;
}
fixture.clock_.advance(kControlPeriod);
}
}
TEST(ControlLoop, NaNFromControllerIsBlockedByArbiter)
{
Fixture fixture;
fixture.controller_.setScript({ControllerScript::kNaN});
std::string reason;
ASSERT_TRUE(fixture.loop_.submit(makeRequest(3.0), reason)) << reason;
fixture.loop_.step();
fixture.clock_.advance(kControlPeriod);
fixture.loop_.step(); // CONTROLLING, controller trả NaN
EXPECT_DOUBLE_EQ(fixture.loop_.lastCommand().linear.x, 0.0);
EXPECT_GT(fixture.loop_.arbiter().nonFiniteRejections(), 0u);
}
TEST(ControlLoop, OverspeedCommandIsClampedNotPassedThrough)
{
Fixture fixture;
fixture.controller_.setScript({ControllerScript::kTooFast});
std::string reason;
ASSERT_TRUE(fixture.loop_.submit(makeRequest(3.0), reason)) << reason;
fixture.loop_.step();
fixture.clock_.advance(kControlPeriod);
fixture.loop_.step();
EXPECT_DOUBLE_EQ(fixture.loop_.lastCommand().linear.x, 0.5);
EXPECT_DOUBLE_EQ(fixture.loop_.lastCommand().angular.z, 1.0);
EXPECT_GT(fixture.loop_.arbiter().velocityClamps(), 0u);
}
TEST(ControlLoop, EmptyPlanIsTreatedAsFailureNotAsAValidPlan)
{
// Fake cố ý vi phạm contract (trả true kèm plan rỗng) để kiểm guard của bên gọi: plan rỗng lọt
// xuống sẽ thành front()/back() trên vector rỗng ở tầng dưới.
Fixture fixture;
fixture.planner_.setScript({PlannerScript::kEmpty});
std::string reason;
ASSERT_TRUE(fixture.loop_.submit(makeRequest(3.0), reason)) << reason;
fixture.run();
EXPECT_EQ(fixture.controller_.setPlanCount(), 0u) << "an empty plan must not be pushed down to "
"the controller";
EXPECT_STREQ(fixture.loop_.lastOutcome(), "FAILED");
}
TEST(ControlLoop, LostPoseStopsTheRobotImmediately)
{
Fixture fixture;
fixture.controller_.setScript({ControllerScript::kOk});
std::string reason;
ASSERT_TRUE(fixture.loop_.submit(makeRequest(3.0), reason)) << reason;
fixture.loop_.step();
fixture.clock_.advance(kControlPeriod);
fixture.loop_.step();
ASSERT_GT(fixture.loop_.lastCommand().linear.x, 0.0);
fixture.pose_.setAvailable(false);
fixture.clock_.advance(kControlPeriod);
fixture.loop_.step();
EXPECT_DOUBLE_EQ(fixture.loop_.lastCommand().linear.x, 0.0)
<< "losing TF must stop the robot immediately, not keep going on a stale pose";
}
// ================================================================================================
// Recovery
// ================================================================================================
TEST(ControlLoop, PrimaryPlannerFailureUsesBackupBeforeRecovery)
{
ControlLoopConfig config = baseConfig();
config.backup_global_planner_name = "FakeBackupGlobalPlanner";
// 0 nghĩa là không retry planner hiện tại. Backup vẫn phải có đúng một lượt riêng trước recovery.
config.state_machine.max_planning_retries = 0;
Fixture fixture(config);
fixture.planner_.setScript({PlannerScript::kFail, PlannerScript::kOk});
fixture.controller_.setScript({ControllerScript::kOk, ControllerScript::kGoalReached});
std::string reason;
NavigationRequest request = makeRequest(3.0, 71);
request.order = std::make_shared<robot_protocol_msgs::Order>();
ASSERT_TRUE(fixture.loop_.submit(request, reason)) << reason;
fixture.run();
EXPECT_FALSE(fixture.hitLimit());
EXPECT_EQ(fixture.planner_.activePlanner(), "FakeBackupGlobalPlanner");
EXPECT_EQ(fixture.planner_.makePlanCount(), 2u);
EXPECT_EQ(fixture.planner_.orderHistory(), (std::vector<bool>{true, false}));
EXPECT_EQ(fixture.recovery_.startCount(), 0u);
EXPECT_EQ(fixture.states(),
(std::vector<std::string>{"IDLE", "PLANNING", "CONTROLLING", "SUCCEEDED"}))
<< join(fixture.states());
}
TEST(ControlLoop, BackupPlannerFailureEscalatesToRecovery)
{
ControlLoopConfig config = baseConfig();
config.backup_global_planner_name = "FakeBackupGlobalPlanner";
config.state_machine.max_planning_retries = 0;
Fixture fixture(config);
fixture.planner_.setScript({PlannerScript::kFail, PlannerScript::kFail});
fixture.recovery_.setScript({RecoveryScript::kRunning});
std::string reason;
ASSERT_TRUE(fixture.loop_.submit(makeRequest(3.0, 72), reason)) << reason;
for (int i = 0; i < 20 && fixture.loop_.state() != NavigationState::kRecovering; ++i)
{
fixture.stepOnce();
}
EXPECT_EQ(fixture.planner_.activePlanner(), "FakeBackupGlobalPlanner");
EXPECT_EQ(fixture.planner_.makePlanCount(), 2u);
EXPECT_EQ(fixture.loop_.state(), NavigationState::kRecovering);
EXPECT_EQ(fixture.recovery_.startCount(), 1u);
EXPECT_EQ(fixture.recovery_.lastTrigger(), RecoveryTrigger::kPlanningFailed);
}
TEST(ControlLoop, PlannerFailureDrivesRecoveryThenSucceeds)
{
// Kịch bản thật: planner bế tắc cho tới khi recovery gỡ được thế, sau đó lập plan bình thường.
// Lật kịch bản planner ngay khi quan sát thấy RECOVERING, thay vì đếm trước số cycle — đếm trước
// làm test phụ thuộc vào đúng thời điểm hết kiên nhẫn, thứ không phải là thứ đang được kiểm.
Fixture fixture;
fixture.planner_.setScript({PlannerScript::kFail});
fixture.controller_.setScript({ControllerScript::kOk, ControllerScript::kGoalReached});
fixture.recovery_.setScript({RecoveryScript::kRunning, RecoveryScript::kSucceeded});
std::string reason;
ASSERT_TRUE(fixture.loop_.submit(makeRequest(3.0, 7), reason)) << reason;
bool planner_unblocked = false;
std::vector<std::string> states;
for (int i = 0; i < 200; ++i)
{
const std::string name = move_base2::toString(fixture.loop_.state());
if (states.empty() || states.back() != name)
{
states.push_back(name);
}
if (!planner_unblocked && fixture.loop_.state() == NavigationState::kRecovering)
{
fixture.planner_.setScript({PlannerScript::kOk});
planner_unblocked = true;
}
if (!fixture.loop_.step())
{
states.push_back(move_base2::toString(fixture.loop_.state()));
break;
}
fixture.clock_.advance(kControlPeriod);
}
EXPECT_TRUE(planner_unblocked) << "never entered recovery";
EXPECT_EQ(states, (std::vector<std::string>{"IDLE", "PLANNING", "RECOVERING", "PLANNING",
"CONTROLLING", "SUCCEEDED"}))
<< join(states);
EXPECT_EQ(fixture.recovery_.startCount(), 1u);
EXPECT_EQ(fixture.recovery_.lastStartIndex(), 0u);
EXPECT_EQ(fixture.recovery_.lastTrigger(), RecoveryTrigger::kPlanningFailed);
EXPECT_EQ(fixture.mission_.reportCountFor(7), 1u);
}
TEST(ControlLoop, AllRecoveriesExhaustedEndsInAbortedWithSingleReport)
{
Fixture fixture;
fixture.planner_.setScript({PlannerScript::kFail}); // luôn hỏng
fixture.recovery_.setScript({RecoveryScript::kSucceeded});
std::string reason;
ASSERT_TRUE(fixture.loop_.submit(makeRequest(3.0, 9), reason)) << reason;
fixture.run();
EXPECT_FALSE(fixture.hitLimit());
EXPECT_EQ(fixture.states(),
(std::vector<std::string>{"IDLE", "PLANNING", "RECOVERING", "PLANNING", "RECOVERING",
"PLANNING", "ABORTED"}))
<< join(fixture.states());
EXPECT_EQ(fixture.recovery_.startedIndices(), (std::vector<std::size_t>{0u, 1u}))
<< "behaviors must run one after another, the first one must not repeat";
EXPECT_STREQ(fixture.loop_.lastOutcome(), "FAILED");
EXPECT_EQ(fixture.loop_.outcomeReportCount(), 1u);
EXPECT_EQ(fixture.mission_.reportCountFor(9), 1u);
}
TEST(ControlLoop, RecoveryRefusingToStartMovesOnToTheNextBehavior)
{
Fixture fixture;
fixture.planner_.setScript({PlannerScript::kFail});
fixture.recovery_.setStartSucceeds(false);
std::string reason;
ASSERT_TRUE(fixture.loop_.submit(makeRequest(3.0), reason)) << reason;
fixture.run();
EXPECT_EQ(fixture.recovery_.startedIndices(), (std::vector<std::size_t>{0u, 1u}));
EXPECT_EQ(fixture.recovery_.updateCount(), 0u)
<< "a behavior that never started successfully must not be ticked";
EXPECT_STREQ(fixture.loop_.lastOutcome(), "FAILED");
}
TEST(ControlLoop, RecoveryVelocityGoesThroughArbiterWithOneHandoverCycle)
{
Fixture fixture;
fixture.planner_.setScript({PlannerScript::kFail});
fixture.recovery_.setScript({RecoveryScript::kRunning, RecoveryScript::kRunning,
RecoveryScript::kSucceeded});
fixture.recovery_.setRecoveryVelocity(true, -0.15); // [m/s], âm = lùi
fixture.controller_.setScript({ControllerScript::kOk});
std::string reason;
ASSERT_TRUE(fixture.loop_.submit(makeRequest(3.0), reason)) << reason;
bool saw_reverse = false;
for (int i = 0; i < 60; ++i)
{
const bool running = fixture.loop_.step();
if (fixture.loop_.state() == NavigationState::kRecovering &&
fixture.loop_.lastCommand().linear.x < -1e-6)
{
saw_reverse = true;
EXPECT_GE(fixture.loop_.lastCommand().linear.x, -0.2) << "the reverse command must stay "
"within the limit";
}
if (!running)
{
break;
}
fixture.clock_.advance(kControlPeriod);
}
EXPECT_TRUE(saw_reverse) << "recovery published a velocity but the command never reached the "
"output";
}
TEST(ControlLoop, RecoveryDisabledAbortsOnFirstFailure)
{
ControlLoopConfig config = baseConfig();
config.state_machine.recovery_enabled = false;
config.state_machine.recovery_behavior_count = 0;
Fixture fixture(config);
fixture.planner_.setScript({PlannerScript::kFail});
std::string reason;
ASSERT_TRUE(fixture.loop_.submit(makeRequest(3.0), reason)) << reason;
fixture.run();
EXPECT_EQ(fixture.recovery_.startCount(), 0u);
EXPECT_EQ(fixture.states(), (std::vector<std::string>{"IDLE", "PLANNING", "ABORTED"}))
<< join(fixture.states());
}
// ================================================================================================
// Pause / cancel
// ================================================================================================
TEST(ControlLoop, CancelWhileControllingStopsAndReportsCancelled)
{
Fixture fixture;
fixture.controller_.setScript({ControllerScript::kOk});
std::string reason;
ASSERT_TRUE(fixture.loop_.submit(makeRequest(3.0, 5), reason)) << reason;
fixture.loop_.step();
fixture.clock_.advance(kControlPeriod);
fixture.loop_.step();
ASSERT_EQ(fixture.loop_.state(), NavigationState::kControlling);
ASSERT_GT(fixture.loop_.lastCommand().linear.x, 0.0);
fixture.loop_.requestCancel();
int cycles_to_zero = 0;
for (int i = 0; i < 10; ++i)
{
fixture.clock_.advance(kControlPeriod);
const bool running = fixture.loop_.step();
++cycles_to_zero;
if (!running)
{
break;
}
}
EXPECT_LE(cycles_to_zero, 2) << "cmd_vel must reach 0 within 2 cycles after a cancel";
EXPECT_DOUBLE_EQ(fixture.loop_.lastCommand().linear.x, 0.0);
EXPECT_EQ(fixture.loop_.state(), NavigationState::kCancelled);
EXPECT_STREQ(fixture.loop_.lastOutcome(), "CANCELLED");
EXPECT_EQ(fixture.mission_.reportCountFor(5), 1u);
}
TEST(ControlLoop, CancelDuringRecoveryStopsTheBehavior)
{
Fixture fixture;
fixture.planner_.setScript({PlannerScript::kFail});
fixture.recovery_.setScript({RecoveryScript::kRunning});
fixture.recovery_.setRecoveryVelocity(true, -0.15);
std::string reason;
ASSERT_TRUE(fixture.loop_.submit(makeRequest(3.0), reason)) << reason;
for (int i = 0; i < 40 && fixture.loop_.state() != NavigationState::kRecovering; ++i)
{
fixture.loop_.step();
fixture.clock_.advance(kControlPeriod);
}
ASSERT_EQ(fixture.loop_.state(), NavigationState::kRecovering);
fixture.loop_.requestCancel();
fixture.loop_.step();
fixture.clock_.advance(kControlPeriod);
EXPECT_EQ(fixture.recovery_.cancelCount(), 1u);
EXPECT_DOUBLE_EQ(fixture.loop_.lastCommand().linear.x, 0.0);
fixture.loop_.step();
EXPECT_EQ(fixture.loop_.state(), NavigationState::kCancelled);
}
TEST(ControlLoop, PauseAndResumeMidControlling)
{
Fixture fixture;
fixture.controller_.setScript({ControllerScript::kOk});
std::string reason;
ASSERT_TRUE(fixture.loop_.submit(makeRequest(3.0), reason)) << reason;
fixture.loop_.step();
fixture.clock_.advance(kControlPeriod);
fixture.loop_.step();
ASSERT_EQ(fixture.loop_.state(), NavigationState::kControlling);
fixture.loop_.requestPause();
fixture.clock_.advance(kControlPeriod);
fixture.loop_.step();
EXPECT_EQ(fixture.loop_.state(), NavigationState::kPausing);
EXPECT_DOUBLE_EQ(fixture.loop_.lastCommand().linear.x, 0.0);
fixture.clock_.advance(kControlPeriod);
fixture.loop_.step();
EXPECT_EQ(fixture.loop_.state(), NavigationState::kPaused);
// Dừng lâu rồi tiếp tục: không được vì thế mà rơi vào recovery.
fixture.clock_.advance(30.0);
fixture.loop_.requestResume();
fixture.loop_.step();
EXPECT_EQ(fixture.loop_.state(), NavigationState::kControlling);
EXPECT_GT(fixture.loop_.lastCommand().linear.x, 0.0);
}
TEST(ControlLoop, ResumeMidControllingReappliesThePlanToTheController)
{
// Local planner giữ warm-start/slew theo thời gian; sau 30 s đứng yên phải nạp lại plan để
// plugin reset theo pose hiện tại (2026-09-11).
Fixture fixture;
fixture.controller_.setScript({ControllerScript::kOk});
std::string reason;
ASSERT_TRUE(fixture.loop_.submit(makeRequest(3.0), reason)) << reason;
fixture.loop_.step();
fixture.clock_.advance(kControlPeriod);
fixture.loop_.step();
ASSERT_EQ(fixture.loop_.state(), NavigationState::kControlling);
const std::size_t set_plan_before = fixture.controller_.setPlanCount();
ASSERT_EQ(set_plan_before, 1u);
fixture.loop_.requestPause();
fixture.clock_.advance(kControlPeriod);
fixture.loop_.step();
fixture.clock_.advance(kControlPeriod);
fixture.loop_.step();
ASSERT_EQ(fixture.loop_.state(), NavigationState::kPaused);
EXPECT_EQ(fixture.controller_.setPlanCount(), set_plan_before) << "pause must not touch the plan";
fixture.clock_.advance(30.0);
fixture.loop_.requestResume();
fixture.loop_.step();
EXPECT_EQ(fixture.loop_.state(), NavigationState::kControlling);
EXPECT_EQ(fixture.controller_.setPlanCount(), set_plan_before + 1)
<< "resume from CONTROLLING must call setPlan() again so the plugin resets its warm start";
EXPECT_GT(fixture.loop_.lastCommand().linear.x, 0.0);
}
// ================================================================================================
// Cancel phải dừng THẬT (2026-09-11): CANCELLED chỉ khi thread planner rảnh và odom về 0.
// Tái hiện log: cancel lúc SBPL đang chạy → host thấy CANCELLED sau 33 ms → gửi goal kế →
// startPlan() bị từ chối vì thread còn bận → bị coi là hỏng → recovery → ABORTED.
// ================================================================================================
namespace
{
/// Fixture với planner "chậm" (10 cycle) và KHÔNG preempt được — đúng SBPL trước pha 2.
ControlLoopConfig busyPlannerConfig()
{
ControlLoopConfig config = baseConfig();
config.state_machine.planner_patience = 5.0; // [s] đủ dài để kBusy không bị patience cắt
config.state_machine.max_planning_retries = 0; // như config trên máy chạy log
config.state_machine.settle_timeout = 2.0; // [s]
return config;
}
constexpr std::size_t kSlowPlannerCycles = 10;
/// Đưa fixture tới PLANNING với một lượt lập plan đang bay, chưa có kết quả.
void driveToPlanningInFlight(Fixture& fixture, std::uint64_t mission_id)
{
fixture.planner_.setLatencyCycles(kSlowPlannerCycles);
fixture.planner_.setCancelKeepsBusy(true);
std::string reason;
ASSERT_TRUE(fixture.loop_.submit(makeRequest(3.0, mission_id), reason)) << reason;
fixture.loop_.step(); // accept → PLANNING, startPlan()
fixture.clock_.advance(kControlPeriod);
fixture.loop_.step(); // pollPlan: chưa có
fixture.clock_.advance(kControlPeriod);
ASSERT_EQ(fixture.loop_.state(), NavigationState::kPlanning);
ASSERT_TRUE(fixture.planner_.isPlanning());
}
} // namespace
TEST(ControlLoop, CancelWhilePlannerStaysBusyHoldsCancellingUntilTheThreadIsIdle)
{
Fixture fixture(busyPlannerConfig());
driveToPlanningInFlight(fixture, 7);
// reset() lúc configure và accept_request đều gọi cancelPlan() (dọn lượt cũ) — đếm tương đối.
const std::size_t cancels_before = fixture.planner_.cancelCount();
fixture.loop_.requestCancel();
fixture.loop_.step();
fixture.clock_.advance(kControlPeriod);
ASSERT_EQ(fixture.loop_.state(), NavigationState::kCancelling);
EXPECT_EQ(fixture.planner_.cancelCount(), cancels_before + 1);
EXPECT_TRUE(fixture.planner_.isPlanning()) << "the fake models a planner that cannot be preempted";
// Chừng nào thread còn bận: giữ CANCELLING, lệnh = 0, KHÔNG báo kết quả. Cycle mà thread rảnh
// (pollPlan thấy lượt cũ xong) cũng chính là cycle CANCELLED — không chậm thêm vòng nào.
std::size_t cycles_held = 0;
for (; cycles_held < 50; ++cycles_held)
{
const bool busy_before = fixture.planner_.isPlanning();
fixture.loop_.step();
fixture.clock_.advance(kControlPeriod);
EXPECT_DOUBLE_EQ(fixture.loop_.lastCommand().linear.x, 0.0);
if (fixture.loop_.state() == NavigationState::kCancelled)
{
EXPECT_TRUE(busy_before) << "must not finish before the very cycle the thread frees";
EXPECT_FALSE(fixture.planner_.isPlanning());
break;
}
EXPECT_EQ(fixture.loop_.state(), NavigationState::kCancelling) << "cycle " << cycles_held;
EXPECT_TRUE(fixture.planner_.isPlanning()) << "held CANCELLING although the thread is idle";
EXPECT_EQ(fixture.mission_.reportCountFor(7), 0u) << "CANCELLED reported while planner busy";
}
EXPECT_GE(cycles_held, 3u) << "the fake planner should have stayed busy for several cycles";
EXPECT_LT(cycles_held, 50u) << "never reached CANCELLED";
EXPECT_EQ(fixture.loop_.state(), NavigationState::kCancelled);
EXPECT_STREQ(fixture.loop_.lastOutcome(), "CANCELLED");
EXPECT_EQ(fixture.mission_.reportCountFor(7), 1u);
}
TEST(ControlLoop, GoalSentRightAfterCancelWaitsForTheBusyPlannerInsteadOfFailing)
{
// Đúng chuỗi sự kiện trong log: cancel mission 3, mission 4 tới 0.2 s sau. Không được có
// RECOVERING/ABORTED; mission 4 phải tới CONTROLLING sau khi thread rảnh.
Fixture fixture(busyPlannerConfig());
driveToPlanningInFlight(fixture, 3);
fixture.loop_.requestCancel();
fixture.loop_.step();
fixture.clock_.advance(kControlPeriod);
ASSERT_EQ(fixture.loop_.state(), NavigationState::kCancelling);
// Host không đợi PREEMPTED (hành vi cũ của khung chương trình): gửi goal kế ngay.
std::string reason;
ASSERT_TRUE(fixture.loop_.submit(makeRequest(5.0, 4), reason)) << reason;
const std::size_t make_plan_before = fixture.planner_.makePlanCount();
bool saw_recovering = false;
bool saw_aborted = false;
bool reached_controlling = false;
for (int i = 0; i < 60 && !reached_controlling; ++i)
{
fixture.loop_.step();
fixture.clock_.advance(kControlPeriod);
const NavigationState s = fixture.loop_.state();
saw_recovering = saw_recovering || s == NavigationState::kRecovering;
saw_aborted = saw_aborted || s == NavigationState::kAborted;
reached_controlling = s == NavigationState::kControlling;
}
EXPECT_FALSE(saw_recovering) << "a busy planner thread was treated as a failed planning attempt";
EXPECT_FALSE(saw_aborted);
EXPECT_TRUE(reached_controlling);
EXPECT_EQ(fixture.planner_.makePlanCount(), make_plan_before + 1)
<< "exactly one new planning attempt once the thread was free";
EXPECT_EQ(fixture.mission_.reportCountFor(3), 1u) << "mission 3 reported once (CANCELLED)";
EXPECT_EQ(fixture.mission_.reportCountFor(4), 0u) << "mission 4 is still running";
}
TEST(ControlLoop, PauseWhilePlanningThenResumeWaitsForTheBusyPlanner)
{
// pause lúc PLANNING đi cùng đường cancelPlan(); resume → PLANNING → startPlan() bị từ chối →
// phải là kBusy, không phải kFailed.
Fixture fixture(busyPlannerConfig());
driveToPlanningInFlight(fixture, 8);
fixture.loop_.requestPause();
fixture.loop_.step();
fixture.clock_.advance(kControlPeriod);
ASSERT_EQ(fixture.loop_.state(), NavigationState::kPausing)
<< "planner thread still busy: PAUSED must not be reported yet";
ASSERT_TRUE(fixture.planner_.isPlanning());
fixture.loop_.requestResume();
bool saw_recovering = false;
bool reached_controlling = false;
for (int i = 0; i < 60 && !reached_controlling; ++i)
{
fixture.loop_.step();
fixture.clock_.advance(kControlPeriod);
saw_recovering = saw_recovering || fixture.loop_.state() == NavigationState::kRecovering;
reached_controlling = fixture.loop_.state() == NavigationState::kControlling;
}
EXPECT_FALSE(saw_recovering);
EXPECT_TRUE(reached_controlling);
EXPECT_EQ(fixture.mission_.reportCountFor(8), 0u);
}
TEST(ControlLoop, NewGoalPreemptingABusyPlannerWaitsInsteadOfFailing)
{
// MissionManager::submit() tự huỷ mission đang chạy — không cần cancel vẫn dính cùng đường.
Fixture fixture(busyPlannerConfig());
driveToPlanningInFlight(fixture, 11);
std::string reason;
ASSERT_TRUE(fixture.loop_.submit(makeRequest(6.0, 12), reason)) << reason;
bool saw_recovering = false;
bool reached_controlling = false;
for (int i = 0; i < 60 && !reached_controlling; ++i)
{
fixture.loop_.step();
fixture.clock_.advance(kControlPeriod);
saw_recovering = saw_recovering || fixture.loop_.state() == NavigationState::kRecovering;
reached_controlling = fixture.loop_.state() == NavigationState::kControlling;
}
EXPECT_FALSE(saw_recovering);
EXPECT_TRUE(reached_controlling);
EXPECT_EQ(fixture.mission_.reportCountFor(11), 1u) << "mission 11 reported once (PREEMPTED)";
EXPECT_EQ(fixture.mission_.reportCountFor(12), 0u);
}
TEST(ControlLoop, BusyPlannerStillCountsAgainstPlannerPatience)
{
// kBusy không phải vé miễn phí: plugin treo thật thì planner_patience vẫn phải leo thang.
ControlLoopConfig config = busyPlannerConfig();
config.state_machine.planner_patience = 0.2; // [s] = 4 cycle
Fixture fixture(config);
fixture.planner_.setLatencyCycles(100); // treo "vĩnh viễn" so với patience
fixture.planner_.setCancelKeepsBusy(true);
std::string reason;
ASSERT_TRUE(fixture.loop_.submit(makeRequest(3.0, 20), reason)) << reason;
fixture.loop_.step();
fixture.clock_.advance(kControlPeriod);
fixture.loop_.step();
fixture.clock_.advance(kControlPeriod);
// Goal kế chen ngang (preempt) trong lúc thread treo: chờ bằng kBusy tối đa planner_patience rồi
// mới recovery. Dùng preempt thay vì cancel để không phải đợi settle_timeout ở đây.
ASSERT_TRUE(fixture.loop_.submit(makeRequest(5.0, 21), reason)) << reason;
bool saw_recovering = false;
for (int i = 0; i < 30 && !saw_recovering; ++i)
{
fixture.loop_.step();
fixture.clock_.advance(kControlPeriod);
saw_recovering = fixture.loop_.state() == NavigationState::kRecovering;
}
EXPECT_TRUE(saw_recovering) << "a planner that never returns must still hit planner_patience";
}
TEST(ControlLoop, CancelSettleTimeoutFinishesCancelledEvenIfThePlannerNeverFrees)
{
ControlLoopConfig config = busyPlannerConfig();
config.state_machine.settle_timeout = 0.2; // [s] = 4 cycle
Fixture fixture(config);
fixture.planner_.setLatencyCycles(1000);
fixture.planner_.setCancelKeepsBusy(true);
std::string reason;
ASSERT_TRUE(fixture.loop_.submit(makeRequest(3.0, 30), reason)) << reason;
fixture.loop_.step();
fixture.clock_.advance(kControlPeriod);
fixture.loop_.step();
fixture.clock_.advance(kControlPeriod);
fixture.loop_.requestCancel();
std::size_t cycles = 0;
bool running = true;
while (running && cycles < 20)
{
running = fixture.loop_.step();
fixture.clock_.advance(kControlPeriod);
++cycles;
}
EXPECT_FALSE(running);
EXPECT_EQ(fixture.loop_.state(), NavigationState::kCancelled);
EXPECT_TRUE(fixture.planner_.isPlanning()) << "the thread is still busy — settle timeout fired";
EXPECT_GE(cycles, 4u);
EXPECT_LE(cycles, 7u) << "CANCELLED must arrive right after settle_timeout";
EXPECT_EQ(fixture.mission_.reportCountFor(30), 1u);
}
TEST(ControlLoop, CancellingWaitsForMeasuredVelocityToReadZero)
{
// Lệnh về 0 ngay cycle đầu, nhưng odom còn 0.3 m/s (driver đang giảm tốc) → chưa CANCELLED.
Fixture fixture;
fixture.controller_.setScript({ControllerScript::kOk});
std::string reason;
ASSERT_TRUE(fixture.loop_.submit(makeRequest(3.0, 40), reason)) << reason;
fixture.loop_.step();
fixture.clock_.advance(kControlPeriod);
fixture.loop_.step();
ASSERT_EQ(fixture.loop_.state(), NavigationState::kControlling);
fixture.controller_.setOdometry(0.3);
fixture.loop_.requestCancel();
fixture.clock_.advance(kControlPeriod);
fixture.loop_.step();
ASSERT_EQ(fixture.loop_.state(), NavigationState::kCancelling);
EXPECT_DOUBLE_EQ(fixture.loop_.lastCommand().linear.x, 0.0);
for (int i = 0; i < 5; ++i)
{
fixture.clock_.advance(kControlPeriod);
fixture.loop_.step();
EXPECT_EQ(fixture.loop_.state(), NavigationState::kCancelling) << "cycle " << i;
}
EXPECT_EQ(fixture.mission_.reportCountFor(40), 0u);
fixture.controller_.setOdometry(0.0);
fixture.clock_.advance(kControlPeriod);
fixture.loop_.step();
EXPECT_EQ(fixture.loop_.state(), NavigationState::kCancelled);
EXPECT_EQ(fixture.mission_.reportCountFor(40), 1u);
}
TEST(ControlLoop, PauseWhilePlannerBusyHoldsPausingUntilTheThreadIsIdle)
{
// PAUSED nói thật (2026-09-11): pause nhận trong 1 cycle (lệnh 0), nhưng PAUSED chỉ khi thread
// planner đã nhả — cùng cơ chế với CANCELLING.
Fixture fixture(busyPlannerConfig());
driveToPlanningInFlight(fixture, 50);
fixture.loop_.requestPause();
fixture.loop_.step();
fixture.clock_.advance(kControlPeriod);
ASSERT_EQ(fixture.loop_.state(), NavigationState::kPausing);
EXPECT_DOUBLE_EQ(fixture.loop_.lastCommand().linear.x, 0.0);
EXPECT_EQ(fixture.components_.phase(move_base2::Component::kGlobalPlanner),
move_base2::ComponentPhase::kStopping)
<< "the fake planner reports 'stopping' after a cancel it cannot honour";
std::size_t held = 0;
for (; held < 50; ++held)
{
fixture.loop_.step();
fixture.clock_.advance(kControlPeriod);
if (fixture.loop_.state() == NavigationState::kPaused)
{
break;
}
EXPECT_EQ(fixture.loop_.state(), NavigationState::kPausing) << "cycle " << held;
EXPECT_TRUE(fixture.planner_.isPlanning());
}
EXPECT_GE(held, 3u);
EXPECT_EQ(fixture.loop_.state(), NavigationState::kPaused);
EXPECT_FALSE(fixture.planner_.isPlanning());
EXPECT_EQ(fixture.components_.phase(move_base2::Component::kGlobalPlanner),
move_base2::ComponentPhase::kIdle);
}
TEST(ControlLoop, CancellingWaitsForARecoveryWorkerReportedThroughTheStatusBoard)
{
// Recovery có worker thread (detour, pha 2): cancel() không kết thúc được ngay → hàng kRecovery
// giữ 'stopping' → CANCELLING phải chờ, dù cổng planner đã rảnh và lệnh đã 0.
Fixture fixture;
fixture.planner_.setScript({PlannerScript::kFail});
fixture.recovery_.setScript({RecoveryScript::kRunning});
fixture.recovery_.setCancelKeepsBusy(true);
std::string reason;
ASSERT_TRUE(fixture.loop_.submit(makeRequest(3.0, 60), reason)) << reason;
for (int i = 0; i < 40 && fixture.loop_.state() != NavigationState::kRecovering; ++i)
{
fixture.loop_.step();
fixture.clock_.advance(kControlPeriod);
}
ASSERT_EQ(fixture.loop_.state(), NavigationState::kRecovering);
fixture.loop_.requestCancel();
fixture.loop_.step();
fixture.clock_.advance(kControlPeriod);
ASSERT_EQ(fixture.loop_.state(), NavigationState::kCancelling);
ASSERT_TRUE(fixture.recovery_.stopping());
for (int i = 0; i < 5; ++i)
{
fixture.loop_.step();
fixture.clock_.advance(kControlPeriod);
EXPECT_EQ(fixture.loop_.state(), NavigationState::kCancelling) << "cycle " << i;
}
EXPECT_EQ(fixture.mission_.reportCountFor(60), 0u);
fixture.recovery_.settleCancel(); // worker giả đã thoát
fixture.loop_.step();
EXPECT_EQ(fixture.loop_.state(), NavigationState::kCancelled);
EXPECT_EQ(fixture.mission_.reportCountFor(60), 1u);
}
TEST(ControlLoop, StatusBoardTracksLocalPlannerAndControlLoopHeartbeat)
{
Fixture fixture;
fixture.controller_.setScript({ControllerScript::kOk});
const std::uint64_t before =
fixture.components_.at(move_base2::Component::kControlLoop).progress_ticks.load();
std::string reason;
ASSERT_TRUE(fixture.loop_.submit(makeRequest(3.0), reason)) << reason;
fixture.loop_.step();
fixture.clock_.advance(kControlPeriod);
fixture.loop_.step();
ASSERT_EQ(fixture.loop_.state(), NavigationState::kControlling);
// Heartbeat nhích mỗi step(); local planner về idle sau mỗi lượt gọi (không để "bận" treo).
EXPECT_GE(fixture.components_.at(move_base2::Component::kControlLoop).progress_ticks.load(),
before + 2);
EXPECT_EQ(fixture.components_.phase(move_base2::Component::kLocalPlanner),
move_base2::ComponentPhase::kIdle);
EXPECT_GT(fixture.components_.at(move_base2::Component::kLocalPlanner).progress_ticks.load(), 0u)
<< "computeVelocityCommands must have been bracketed busy/idle at least once";
}
TEST(ControlLoop, MeasuredVelocityIsIgnoredWhenTheEpsSwitchesAreZero)
{
ControlLoopConfig config = baseConfig();
config.state_machine.stopped_measured_linear_eps = 0.0;
config.state_machine.stopped_measured_angular_eps = 0.0;
Fixture fixture(config);
fixture.controller_.setScript({ControllerScript::kOk});
std::string reason;
ASSERT_TRUE(fixture.loop_.submit(makeRequest(3.0, 41), reason)) << reason;
fixture.loop_.step();
fixture.clock_.advance(kControlPeriod);
fixture.loop_.step();
ASSERT_EQ(fixture.loop_.state(), NavigationState::kControlling);
fixture.controller_.setOdometry(0.3); // odom nói còn chạy — nhưng công tắc tắt
fixture.loop_.requestCancel();
fixture.clock_.advance(kControlPeriod);
fixture.loop_.step();
fixture.clock_.advance(kControlPeriod);
fixture.loop_.step();
EXPECT_EQ(fixture.loop_.state(), NavigationState::kCancelled)
<< "with eps = 0 'stopped' is judged from the issued command, as before 2026-09-11";
}
// ================================================================================================
// Nhiều chặng liên tiếp
// ================================================================================================
TEST(ControlLoop, ThreeSequentialMissionLegsEachReportedExactlyOnce)
{
Fixture fixture;
for (std::uint64_t leg = 1; leg <= 3; ++leg)
{
fixture.planner_.setScript({PlannerScript::kOk});
fixture.controller_.setScript({ControllerScript::kOk, ControllerScript::kGoalReached});
std::string reason;
ASSERT_TRUE(fixture.loop_.submit(makeRequest(static_cast<double>(leg), leg), reason)) << reason;
for (int i = 0; i < 50; ++i)
{
const bool running = fixture.loop_.step();
fixture.clock_.advance(kControlPeriod);
if (!running)
{
break;
}
}
ASSERT_EQ(fixture.loop_.state(), NavigationState::kSucceeded) << "leg " << leg;
ASSERT_EQ(fixture.mission_.reportCountFor(leg), 1u) << "leg " << leg;
}
EXPECT_EQ(fixture.loop_.outcomeReportCount(), 3u);
EXPECT_EQ(fixture.mission_.reports().size(), 3u);
}
// ================================================================================================
// Action của mission (D8)
// ================================================================================================
TEST(ControlLoopActions, ActionOnlyMissionNeverTouchesPlannerOrController)
{
Fixture fixture;
fixture.action_.setScript({ActionScript::kRunning, ActionScript::kSucceeded,
ActionScript::kRunning, ActionScript::kSucceeded});
std::string reason;
ASSERT_TRUE(fixture.loop_.submit(makeActionOnlyRequest(2, 7), reason)) << reason;
fixture.run();
ASSERT_FALSE(fixture.hitLimit()) << join(fixture.states());
EXPECT_EQ(fixture.states(),
(std::vector<std::string>{"IDLE", "EXECUTING_ACTIONS", "SUCCEEDED"}))
<< join(fixture.states());
// Không một lời gọi nào tới planner/controller — và vì thế không một lệnh vận tốc nào khác 0.
EXPECT_EQ(fixture.planner_.makePlanCount(), 0u);
EXPECT_EQ(fixture.controller_.computeCount(), 0u);
EXPECT_EQ(fixture.loop_.lastCommand().linear.x, 0.0);
EXPECT_EQ(fixture.loop_.lastCommand().angular.z, 0.0);
// Hai action tới port nguyên vẹn, đúng thứ tự; kết quả báo đúng một lần sau action cuối.
EXPECT_EQ(fixture.action_.startedActionTypes(),
(std::vector<std::string>{"act_0", "act_1"}));
EXPECT_EQ(fixture.mission_.reportCountFor(7), 1u);
}
TEST(ControlLoopActions, MissionWithGoalRunsActionsAfterGoalReached)
{
Fixture fixture;
fixture.planner_.setScript({PlannerScript::kOk});
fixture.controller_.setScript({ControllerScript::kOk, ControllerScript::kGoalReached});
fixture.action_.setScript({ActionScript::kRunning, ActionScript::kSucceeded});
std::string reason;
ASSERT_TRUE(fixture.loop_.submit(withActions(makeRequest(2.0, 11), 1), reason)) << reason;
fixture.run();
ASSERT_FALSE(fixture.hitLimit()) << join(fixture.states());
EXPECT_EQ(fixture.states(),
(std::vector<std::string>{"IDLE", "PLANNING", "CONTROLLING", "EXECUTING_ACTIONS",
"SUCCEEDED"}))
<< join(fixture.states());
EXPECT_EQ(fixture.action_.startedActionTypes(), (std::vector<std::string>{"act_0"}));
EXPECT_EQ(fixture.mission_.reportCountFor(11), 1u);
}
TEST(ControlLoopActions, ActionFailureAbortsAndReportsOnce)
{
Fixture fixture;
fixture.action_.setScript({ActionScript::kRunning, ActionScript::kFailed});
std::string reason;
ASSERT_TRUE(fixture.loop_.submit(makeActionOnlyRequest(1, 13), reason)) << reason;
fixture.run();
ASSERT_FALSE(fixture.hitLimit()) << join(fixture.states());
EXPECT_EQ(fixture.loop_.state(), NavigationState::kAborted);
EXPECT_EQ(fixture.mission_.reportCountFor(13), 1u);
EXPECT_EQ(fixture.recovery_.startCount(), 0u) << "a failed action must not drag recovery in";
}
TEST(ControlLoopActions, PauseAndResumeAreForwardedToTheActionPort)
{
// Pha 3 (2026-09-11): handler có timeout riêng phải biết pause để dịch mốc; không báo thì 20 s
// đứng chờ bị tính vào timeout dò 15 s → kFailed → ABORTED oan ngay sau resume.
Fixture fixture;
fixture.action_.setScript({ActionScript::kRunning});
std::string reason;
ASSERT_TRUE(fixture.loop_.submit(makeActionOnlyRequest(1, 14), reason)) << reason;
fixture.stepOnce();
fixture.stepOnce();
ASSERT_EQ(fixture.loop_.state(), NavigationState::kExecutingActions);
const std::size_t updates_before_pause = fixture.action_.updateCount();
fixture.loop_.requestPause();
fixture.stepOnce();
EXPECT_EQ(fixture.action_.pauseCount(), 1u);
EXPECT_EQ(fixture.action_.cancelCount(), 0u) << "pause must not cancel the action";
fixture.stepOnce(); // hàng kAction = paused → quiescent
EXPECT_EQ(fixture.loop_.state(), NavigationState::kPaused);
EXPECT_EQ(fixture.action_.updateCount(), updates_before_pause) << "no ticks while paused";
fixture.clock_.advance(30.0);
fixture.loop_.requestResume();
fixture.stepOnce();
EXPECT_EQ(fixture.action_.resumeCount(), 1u);
EXPECT_EQ(fixture.loop_.state(), NavigationState::kExecutingActions);
EXPECT_GT(fixture.action_.updateCount(), updates_before_pause) << "ticking resumed";
EXPECT_EQ(fixture.action_.startCount(), 1u) << "the action must not be restarted";
}
TEST(ControlLoopActions, CancelWaitsForADeviceHandlerToReportCancelled)
{
// Handler thiết bị cần 3 tick sau cancel() để về vị trí an toàn: CANCELLING tick tiếp, không
// cấp vận tốc, và CANCELLED chỉ được báo sau tick kCancelled.
Fixture fixture;
fixture.action_.setScript({ActionScript::kRunning});
fixture.action_.setCancelNeedsTicks(3);
std::string reason;
ASSERT_TRUE(fixture.loop_.submit(makeActionOnlyRequest(1, 15), reason)) << reason;
fixture.stepOnce();
fixture.stepOnce();
ASSERT_EQ(fixture.loop_.state(), NavigationState::kExecutingActions);
fixture.loop_.requestCancel();
fixture.stepOnce();
ASSERT_EQ(fixture.loop_.state(), NavigationState::kCancelling);
EXPECT_EQ(fixture.action_.cancelCount(), 1u);
EXPECT_EQ(fixture.components_.phase(move_base2::Component::kAction),
move_base2::ComponentPhase::kStopping);
std::size_t held = 0;
for (; held < 10; ++held)
{
if (fixture.loop_.state() == NavigationState::kCancelled)
{
break;
}
EXPECT_EQ(fixture.loop_.state(), NavigationState::kCancelling) << "cycle " << held;
EXPECT_DOUBLE_EQ(fixture.loop_.lastCommand().linear.x, 0.0);
EXPECT_EQ(fixture.mission_.reportCountFor(15), 0u) << "CANCELLED reported before the device was safe";
fixture.stepOnce();
}
EXPECT_GE(held, 3u) << "the handler asked for 3 ticks after cancel";
EXPECT_EQ(fixture.loop_.state(), NavigationState::kCancelled);
EXPECT_EQ(fixture.mission_.reportCountFor(15), 1u);
EXPECT_EQ(fixture.components_.phase(move_base2::Component::kAction),
move_base2::ComponentPhase::kIdle);
}
TEST(ControlLoopActions, SubmitRejectsActionRequestWhenActionPortMissing)
{
Fixture fixture;
ControlLoop bare_loop;
ControlLoopDeps deps = fixture.deps_;
deps.action = nullptr;
std::string error;
ASSERT_TRUE(bare_loop.configure(baseConfig(), deps, error)) << error;
std::string reason;
EXPECT_FALSE(bare_loop.submit(makeActionOnlyRequest(1), reason));
EXPECT_NE(reason.find("action port"), std::string::npos) << reason;
// Không goal lẫn action thì bị từ chối bất kể có port hay không.
EXPECT_FALSE(fixture.loop_.submit(makeActionOnlyRequest(0), reason));
EXPECT_NE(reason.find("neither goal nor action"), std::string::npos) << reason;
}
// ================================================================================================
// Lập plan bất đồng bộ (kBusy)
//
// Global planner nặng mất hàng trăm ms, control loop chạy 20 Hz và là thread duy nhất phát cmd_vel.
// Các test dưới đây khoá lại điều kiện để tách được hai nhịp đó mà state machine không phải đoán.
// ================================================================================================
TEST(ControlLoopAsyncPlanner, StaysInPlanningWhileThePlannerIsStillWorking)
{
Fixture fixture;
fixture.planner_.setLatencyCycles(3);
fixture.controller_.setScript({ControllerScript::kOk});
std::string reason;
ASSERT_TRUE(fixture.loop_.submit(makeRequest(3.0), reason)) << reason;
fixture.stepOnce(); // IDLE -> PLANNING, kick lượt lập plan
ASSERT_EQ(fixture.loop_.state(), NavigationState::kPlanning);
for (int i = 0; i < 3; ++i)
{
fixture.stepOnce();
EXPECT_EQ(fixture.loop_.state(), NavigationState::kPlanning)
<< "left PLANNING while the planner was still computing, cycle " << i;
}
fixture.stepOnce();
EXPECT_EQ(fixture.loop_.state(), NavigationState::kControlling);
}
TEST(ControlLoopAsyncPlanner, DoesNotRestartAPlanThatIsAlreadyRunning)
{
// `start_planner` là tín hiệu MỨC, bật lại mỗi cycle chừng nào còn ở PLANNING. Kick lại một lượt
// đang chạy sẽ làm mất toàn bộ thời gian đã bỏ ra cho nó.
Fixture fixture;
fixture.planner_.setLatencyCycles(4);
std::string reason;
ASSERT_TRUE(fixture.loop_.submit(makeRequest(3.0), reason)) << reason;
for (int i = 0; i < 4; ++i)
{
fixture.stepOnce();
}
EXPECT_EQ(fixture.planner_.makePlanCount(), 1u)
<< "the planning attempt was restarted every cycle";
}
TEST(ControlLoopAsyncPlanner, PlannerPatienceStillFiresWhileThePlannerIsBusy)
{
// Đây là thứ DUY NHẤT phát hiện được thread planner treo. Ở chế độ đồng bộ, planner treo làm
// treo luôn control loop nên còn dễ thấy; ở chế độ bất đồng bộ nó im lặng hoàn toàn.
ControlLoopConfig config = baseConfig();
config.state_machine.planner_patience = 0.2; // [s] = 4 cycle
config.state_machine.max_planning_retries = -1;
Fixture fixture(config);
fixture.planner_.setLatencyCycles(1000); // không bao giờ xong
std::string reason;
ASSERT_TRUE(fixture.loop_.submit(makeRequest(3.0), reason)) << reason;
for (int i = 0; i < 20; ++i)
{
fixture.stepOnce();
}
// Planner treo vĩnh viễn thì đường đi đúng là: hết kiên nhẫn -> recovery -> thử lại -> hết
// recovery -> ABORTED. Điều phải khoá lại là nó KHÔNG đứng im ở PLANNING.
EXPECT_NE(std::find(fixture.states().begin(), fixture.states().end(), "RECOVERING"),
fixture.states().end())
<< "the planner hung and nobody escalated — the robot would sit in PLANNING forever: "
<< join(fixture.states());
EXPECT_EQ(fixture.loop_.state(), NavigationState::kAborted) << join(fixture.states());
}
TEST(ControlLoopAsyncPlanner, KeepsFollowingTheOldPlanWhileReplanningInBackground)
{
// Chính là lý do tồn tại của cả mô hình: lập lại plan không được làm gián đoạn việc bám plan cũ.
ControlLoopConfig config = baseConfig();
config.state_machine.controller_patience = 100.0; // [s] không cho controller hết kiên nhẫn
Fixture fixture(config);
fixture.controller_.setNominalSpeed(0.3); // [m/s]
fixture.controller_.setScript({ControllerScript::kOk});
std::string reason;
ASSERT_TRUE(fixture.loop_.submit(makeRequest(3.0), reason)) << reason;
fixture.stepOnce(); // PLANNING
fixture.stepOnce(); // -> CONTROLLING
ASSERT_EQ(fixture.loop_.state(), NavigationState::kControlling);
for (int i = 0; i < 5; ++i)
{
fixture.stepOnce();
EXPECT_EQ(fixture.loop_.state(), NavigationState::kControlling);
EXPECT_NEAR(fixture.loop_.lastCommand().linear.x, 0.3, 1e-9)
<< "cmd_vel was interrupted while replanning, cycle " << i;
}
}
TEST(ControlLoopAsyncPlanner, BackgroundReplanSwapsThePlanWithoutLeavingControlling)
{
// Contract 2026-08-04: `planner_frequency` là cơ chế thay plan duy nhất trong lúc chạy — plan
// mới được lập nền theo nhịp và thay ngay trong kControlling, không đổi state, không dừng robot.
ControlLoopConfig config = baseConfig();
config.planner_frequency = 2.0; // [Hz] -> chu kỳ 0.5 s = 10 cycle @ kControlPeriod 0.05 s
Fixture fx(config);
std::string reason;
ASSERT_TRUE(fx.loop_.submit(makeRequest(5.0), reason)) << reason;
// 1.5 s: lượt plan đầu (kPlanning) + ít nhất 2 nhịp replan nền.
for (int i = 0; i < 30; ++i)
{
fx.stepOnce();
}
EXPECT_EQ(fx.loop_.state(), NavigationState::kControlling);
EXPECT_GE(fx.planner_.makePlanCount(), 3u); // 1 lượt đầu + >= 2 replan nền
EXPECT_GE(fx.controller_.setPlanCount(), 3u); // mỗi plan mới đều tới controller
EXPECT_EQ(join(fx.states()), "[PLANNING, CONTROLLING]") << "replan nền không được đổi state";
}
TEST(ControlLoopAsyncPlanner, BackgroundReplanFailureKeepsTheCurrentPlanAndSkipsBackup)
{
// Replan nền hỏng thì plan cũ vẫn hiệu lực: không recovery, và nhất là KHÔNG kích backup
// planner — một lượt replan hụt mà đổi hẳn sang SBPL là mất quỹ đạo Order cho phần còn lại.
ControlLoopConfig config = baseConfig();
config.planner_frequency = 2.0; // [Hz]
config.backup_global_planner_name = "FakeBackupPlanner";
Fixture fx(config);
// Lượt đầu thành công; mọi lượt sau (toàn replan nền) đều fail.
fx.planner_.setScript({PlannerScript::kOk, PlannerScript::kFail});
std::string reason;
ASSERT_TRUE(fx.loop_.submit(makeRequest(5.0), reason)) << reason;
for (int i = 0; i < 30; ++i)
{
fx.stepOnce();
}
EXPECT_EQ(fx.loop_.state(), NavigationState::kControlling);
EXPECT_GE(fx.planner_.makePlanCount(), 2u); // replan nền có chạy thật và có fail thật
EXPECT_EQ(fx.planner_.activePlanner(), "FakeGlobalPlanner");
EXPECT_EQ(fx.planner_.swapCount(), 1u) << "backup planner must not be engaged by a background "
"replan failure";
}
TEST(ControlLoopAsyncPlanner, CancelWhilePlanningCancelsTheRunningPlan)
{
// Không huỷ thì lượt đang bay vẫn về và chiếm chỗ hộp thư, rồi bị nhận nhầm cho yêu cầu kế tiếp.
Fixture fixture;
fixture.planner_.setLatencyCycles(100);
std::string reason;
ASSERT_TRUE(fixture.loop_.submit(makeRequest(3.0), reason)) << reason;
fixture.stepOnce();
ASSERT_EQ(fixture.loop_.state(), NavigationState::kPlanning);
ASSERT_TRUE(fixture.planner_.isPlanning());
fixture.loop_.requestCancel();
fixture.stepOnce();
EXPECT_GE(fixture.planner_.cancelCount(), 1u);
EXPECT_FALSE(fixture.planner_.isPlanning());
}
TEST(ControlLoopAsyncPlanner, AcceptingANewRequestCancelsAnInFlightPlan)
{
Fixture fixture;
fixture.planner_.setLatencyCycles(100);
std::string reason;
ASSERT_TRUE(fixture.loop_.submit(makeRequest(3.0), reason)) << reason;
fixture.stepOnce();
ASSERT_TRUE(fixture.planner_.isPlanning());
const std::size_t before = fixture.planner_.cancelCount();
fixture.loop_.requestCancel();
fixture.stepOnce();
fixture.stepOnce();
ASSERT_TRUE(fixture.loop_.submit(makeRequest(5.0), reason)) << reason;
fixture.stepOnce();
EXPECT_GT(fixture.planner_.cancelCount(), before)
<< "a new request did not cancel the planning attempt of the old goal";
}
TEST(ControlLoopAsyncPlanner, FailureToStartAPlanIsTreatedAsAFailedAttempt)
{
// Không khởi động được mà im lặng thì state machine đứng ở PLANNING vô hạn: không có kFailed để
// đếm lượt, không có kPlanReady để đi tiếp.
ControlLoopConfig config = baseConfig();
config.state_machine.max_planning_retries = 2;
Fixture fixture(config);
fixture.planner_.setSwapSucceeds(true);
fixture.planner_.setScript({PlannerScript::kFail});
std::string reason;
ASSERT_TRUE(fixture.loop_.submit(makeRequest(3.0), reason)) << reason;
fixture.run();
EXPECT_FALSE(fixture.hitLimit()) << join(fixture.states());
EXPECT_NE(std::find(fixture.states().begin(), fixture.states().end(), "RECOVERING"),
fixture.states().end())
<< join(fixture.states());
}
// ================================================================================================
// Preempt — goal mới thay goal cũ NGAY
//
// Bấm goal mới nghĩa là goal cũ không còn muốn nữa. Xếp hàng chờ robot đi hết chặng cũ là hành vi
// không ai mong đợi, và mission layer cũng đã chốt "preempt ngay" (Q1, Phase 2).
// ================================================================================================
TEST(ControlLoopPreempt, NewGoalWhileControllingReplansImmediately)
{
Fixture fixture;
fixture.controller_.setScript({ControllerScript::kOk});
std::string reason;
ASSERT_TRUE(fixture.loop_.submit(makeRequest(3.0), reason)) << reason;
fixture.stepOnce(); // IDLE -> PLANNING
fixture.stepOnce(); // -> CONTROLLING
ASSERT_EQ(fixture.loop_.state(), NavigationState::kControlling);
const std::size_t plans_before = fixture.planner_.makePlanCount();
ASSERT_TRUE(fixture.loop_.submit(makeRequest(9.0), reason)) << reason;
fixture.stepOnce();
EXPECT_EQ(fixture.loop_.state(), NavigationState::kPlanning)
<< "the new goal was queued instead of replacing the old one right away";
EXPECT_GT(fixture.planner_.makePlanCount(), plans_before) << "did not replan for the new goal";
}
TEST(ControlLoopPreempt, NewGoalWhilePlanningReplansImmediately)
{
Fixture fixture;
fixture.planner_.setLatencyCycles(50); // plan cũ còn lâu mới xong
std::string reason;
ASSERT_TRUE(fixture.loop_.submit(makeRequest(3.0), reason)) << reason;
fixture.stepOnce();
ASSERT_EQ(fixture.loop_.state(), NavigationState::kPlanning);
ASSERT_TRUE(fixture.loop_.submit(makeRequest(9.0), reason)) << reason;
fixture.stepOnce();
EXPECT_EQ(fixture.loop_.state(), NavigationState::kPlanning);
EXPECT_GE(fixture.planner_.cancelCount(), 1u) << "the planning attempt for the old goal was not "
"cancelled";
}
TEST(ControlLoopPreempt, OldMissionIsReportedPreemptedExactlyOnceUnderItsOwnId)
{
// Bất biến quan trọng nhất: báo kết quả ĐÚNG MỘT LẦN và ĐÚNG ID. Preempt báo kết quả chặng cũ và
// nhận chặng mới trong cùng một cycle — dùng nhầm id thì mission layer mất dấu cả hai chặng.
Fixture fixture;
fixture.controller_.setScript({ControllerScript::kOk});
std::string reason;
ASSERT_TRUE(fixture.loop_.submit(makeRequest(3.0, 11), reason)) << reason;
fixture.stepOnce();
fixture.stepOnce();
ASSERT_EQ(fixture.loop_.state(), NavigationState::kControlling);
ASSERT_TRUE(fixture.loop_.submit(makeRequest(9.0, 22), reason)) << reason;
fixture.stepOnce();
EXPECT_EQ(fixture.mission_.reportCountFor(11), 1u) << "the preempted leg was not reported "
"exactly once";
EXPECT_EQ(fixture.mission_.reportCountFor(22), 0u) << "the NEW leg got its outcome reported the "
"moment it was accepted";
}
TEST(ControlLoopPreempt, PreemptedGoalStillFinishesTheNewOne)
{
// Preempt không được để lại trạng thái nửa vời: chặng mới phải chạy tới cùng như bình thường.
Fixture fixture;
fixture.controller_.setScript({ControllerScript::kOk, ControllerScript::kOk,
ControllerScript::kGoalReached});
std::string reason;
ASSERT_TRUE(fixture.loop_.submit(makeRequest(3.0, 11), reason)) << reason;
fixture.stepOnce();
fixture.stepOnce();
ASSERT_TRUE(fixture.loop_.submit(makeRequest(9.0, 22), reason)) << reason;
fixture.run();
EXPECT_FALSE(fixture.hitLimit()) << join(fixture.states());
EXPECT_STREQ(fixture.loop_.lastOutcome(), "SUCCEEDED");
EXPECT_EQ(fixture.mission_.reportCountFor(22), 1u);
}
TEST(ControlLoopPreempt, NewGoalDuringRecoveryCancelsTheRunningBehavior)
{
ControlLoopConfig config = baseConfig();
config.state_machine.planner_patience = 0.05; // [s] vào recovery nhanh
Fixture fixture(config);
fixture.planner_.setScript({PlannerScript::kFail});
fixture.recovery_.setScript({RecoveryScript::kRunning});
std::string reason;
ASSERT_TRUE(fixture.loop_.submit(makeRequest(3.0), reason)) << reason;
for (int i = 0; i < 6 && fixture.loop_.state() != NavigationState::kRecovering; ++i)
{
fixture.stepOnce();
}
ASSERT_EQ(fixture.loop_.state(), NavigationState::kRecovering) << join(fixture.states());
fixture.planner_.setScript({PlannerScript::kOk});
ASSERT_TRUE(fixture.loop_.submit(makeRequest(9.0), reason)) << reason;
fixture.stepOnce();
EXPECT_EQ(fixture.loop_.state(), NavigationState::kPlanning);
EXPECT_GE(fixture.recovery_.cancelCount(), 1u) << "the running behavior was not told to stop";
}
// ================================================================================================
// Guard "không đi mù" — dữ liệu quan sát của costmap quá hạn
// ================================================================================================
//
// move_base thế hệ 1 có đúng guard này (`move_base.cpp:2720`) và move_base2 trước đây KHÔNG có:
// costmap hết hạn nghĩa là robot đang tránh vật cản trên một bản đồ của quá khứ.
TEST(StaleCostmap, BlocksWheelsWhileControlling)
{
Fixture fixture;
fixture.planner_.setScript({ PlannerScript::kOk });
fixture.controller_.setScript(std::vector<ControllerScript>(50, ControllerScript::kOk));
std::string error;
ASSERT_TRUE(fixture.loop_.submit(makeRequest(2.0), error)) << error;
// Chạy tới khi đang bám plan và thực sự có lệnh khác 0.
for (int i = 0; i < 20 && fixture.loop_.state() != NavigationState::kControlling; ++i)
{
fixture.loop_.step();
}
ASSERT_EQ(fixture.loop_.state(), NavigationState::kControlling);
fixture.loop_.step();
ASSERT_GT(std::abs(fixture.loop_.lastCommand().linear.x), 0.0) << "no command to block yet";
const std::size_t controller_calls_before = fixture.controller_.computeCount();
fixture.costmap_status_.setCurrent(false);
fixture.loop_.step();
EXPECT_DOUBLE_EQ(fixture.loop_.lastCommand().linear.x, 0.0) << "sensor data is stale yet it kept "
"driving";
EXPECT_DOUBLE_EQ(fixture.loop_.lastCommand().angular.z, 0.0);
EXPECT_EQ(fixture.controller_.computeCount(), controller_calls_before)
<< "the controller must not compute a command on stale data";
EXPECT_EQ(fixture.loop_.state(), NavigationState::kControlling)
<< "the guard only blocks the wheels, it does not change state — exactly like the old "
"version";
}
TEST(StaleCostmap, ResumesWhenSensorDataBecomesCurrentAgain)
{
Fixture fixture;
fixture.planner_.setScript({ PlannerScript::kOk });
fixture.controller_.setScript(std::vector<ControllerScript>(50, ControllerScript::kOk));
std::string error;
ASSERT_TRUE(fixture.loop_.submit(makeRequest(2.0), error)) << error;
for (int i = 0; i < 20 && fixture.loop_.state() != NavigationState::kControlling; ++i)
{
fixture.loop_.step();
}
ASSERT_EQ(fixture.loop_.state(), NavigationState::kControlling);
fixture.costmap_status_.setCurrent(false);
fixture.loop_.step();
ASSERT_DOUBLE_EQ(fixture.loop_.lastCommand().linear.x, 0.0);
fixture.costmap_status_.setCurrent(true);
fixture.loop_.step();
EXPECT_GT(std::abs(fixture.loop_.lastCommand().linear.x), 0.0)
<< "sensors are fresh again yet the robot stays still";
}
TEST(StaleCostmap, DisabledByConfigLetsTheRobotDrive)
{
ControlLoopConfig config = baseConfig();
config.require_current_costmap = false;
Fixture fixture(config);
fixture.planner_.setScript({ PlannerScript::kOk });
fixture.controller_.setScript(std::vector<ControllerScript>(50, ControllerScript::kOk));
std::string error;
ASSERT_TRUE(fixture.loop_.submit(makeRequest(2.0), error)) << error;
for (int i = 0; i < 20 && fixture.loop_.state() != NavigationState::kControlling; ++i)
{
fixture.loop_.step();
}
ASSERT_EQ(fixture.loop_.state(), NavigationState::kControlling);
fixture.costmap_status_.setCurrent(false);
fixture.loop_.step();
EXPECT_GT(std::abs(fixture.loop_.lastCommand().linear.x), 0.0)
<< "the guard is disabled by config yet it still blocked";
}
TEST(StaleCostmap, NullPortMeansNoGuard)
{
// Đường đi của mọi test cổng-giả có sẵn: không ai bơm costmap_status thì lõi coi là còn hạn.
Fixture fixture;
fixture.deps_.costmap_status = nullptr;
std::string error;
ASSERT_TRUE(fixture.loop_.configure(baseConfig(), fixture.deps_, error)) << error;
fixture.planner_.setScript({ PlannerScript::kOk });
fixture.controller_.setScript(std::vector<ControllerScript>(50, ControllerScript::kOk));
ASSERT_TRUE(fixture.loop_.submit(makeRequest(2.0), error)) << error;
for (int i = 0; i < 20 && fixture.loop_.state() != NavigationState::kControlling; ++i)
{
fixture.loop_.step();
}
ASSERT_EQ(fixture.loop_.state(), NavigationState::kControlling);
fixture.costmap_status_.setCurrent(false); // không ai hỏi nó cả
fixture.loop_.step();
EXPECT_GT(std::abs(fixture.loop_.lastCommand().linear.x), 0.0);
EXPECT_EQ(fixture.costmap_status_.queryCount(), 0u) << "the port was detached yet the core still "
"asked it";
}
// ================================================================================================
// Trợ giúp chung cho các ca có mission (submit + kiểm nhận).
// ================================================================================================
namespace
{
/// @brief Nộp yêu cầu và trả true nếu lõi nhận — gọn hơn việc mỗi ca tự khai biến `reason`.
bool submitOk(Fixture& fixture, const NavigationRequest& request)
{
std::string reason;
const bool accepted = fixture.loop_.submit(request, reason);
EXPECT_TRUE(accepted) << reason;
return accepted;
}
} // namespace
int main(int argc, char** argv)
{
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
// =================================================================================================
// EnvMonitor kContact — phanh theo quỹ đạo thật, cờ collision, leo thang khi route khoá (P4, 2026-09-05).
// PathMonitor cũ (4 phép đo, PathCheckPort) đã xoá 6/9/2026 — xem Test/ENV_MONITOR_PLAN.md §4.19.
// =================================================================================================
namespace
{
void driveToControlling(Fixture& fixture)
{
fixture.planner_.setScript({ PlannerScript::kOk });
fixture.controller_.setScript(std::vector<ControllerScript>(60, ControllerScript::kOk));
fixture.recovery_.setScript(std::vector<RecoveryScript>(20, RecoveryScript::kRunning));
ASSERT_TRUE(submitOk(fixture, makeRequest(3.0)));
for (int i = 0; i < 8; ++i)
{
fixture.stepOnce(); // qua ramp gia tốc của trọng tài để lệnh ổn định
}
ASSERT_EQ(fixture.loop_.state(), NavigationState::kControlling);
ASSERT_GT(fixture.loop_.lastCommand().linear.x, 0.0);
}
} // namespace
namespace
{
/// @brief P4 (5/9): guard cũ tắt hẳn, kContact của EnvMonitor phanh thật và giơ cờ collision.
ControlLoopConfig envContactConfig()
{
ControlLoopConfig config = baseConfig();
config.state_machine.recovery_routes.planning_failed = { 0 };
config.state_machine.recovery_routes.controlling_failed = { 0 };
config.state_machine.recovery_routes.oscillation = { 0 };
config.state_machine.recovery_routes.path_blocked = { 1 };
config.state_machine.recovery_routes.collision = { 1 };
config.env_monitor.enabled = true;
config.env_monitor.stall.action = "log";
config.env_monitor.unreachable.action = "log";
config.env_monitor.contact.action = "recover";
config.env_monitor.contact.apply_command = true;
config.env_monitor.contact.confirm_cycles = 2;
config.env_monitor.contact.trigger_static_time = 0.3; // [s] = 6 cycle, đủ ngắn cho test
config.env_monitor.contact.clean_start_margin = 0.2; // [m]
config.env_sampling.check_period = 0.01; // [s] < chu kỳ 0.05 -> tick nặng mỗi cycle
return config;
}
} // namespace
TEST(WalkingSkeletonEnvContact, BrakesAfterConfirmThenRaisesCollisionAfterStaticTime)
{
Fixture fixture(envContactConfig());
driveToControlling(fixture);
// Tiếp xúc 0.10 m trên quỹ đạo, trong clean_start_margin: cycle 1 đếm, cycle 2 phanh -> lệnh 0.
fixture.environment_.setContact(true, 0.10);
fixture.stepOnce();
fixture.stepOnce();
EXPECT_DOUBLE_EQ(fixture.loop_.lastCommand().linear.x, 0.0);
EXPECT_DOUBLE_EQ(fixture.loop_.lastCommand().angular.z, 0.0);
EXPECT_EQ(fixture.loop_.state(), NavigationState::kControlling) << "phanh nhưng chưa giơ cờ";
// Kề mũi đứng yên đủ trigger_static_time -> cờ collision -> route collision.
int held = 0;
for (int i = 0; i < 12 && fixture.loop_.state() == NavigationState::kControlling; ++i)
{
fixture.stepOnce();
EXPECT_DOUBLE_EQ(fixture.loop_.lastCommand().linear.x, 0.0) << "cycle " << i;
++held;
}
EXPECT_EQ(fixture.loop_.state(), NavigationState::kRecovering);
EXPECT_EQ(fixture.recovery_.lastTrigger(), RecoveryTrigger::kCollision);
EXPECT_GE(held, 4) << "cờ phải chờ đủ trigger_static_time, không nổ cùng nhịp với phanh";
}
TEST(WalkingSkeletonEnvContact, HeldWithTheRouteSpentEscalatesToControllingFailed)
{
// Cùng chuỗi bắt buộc như guard cũ: cạn route collision -> khoá -> brake giữ 0 nhưng controller
// phải bị báo no_valid_command -> controller_patience -> controlling_failed. Không có bước này
// robot đứng chết vô hạn với controller "ổn".
Fixture fixture(envContactConfig());
driveToControlling(fixture);
fixture.recovery_.setScript({ RecoveryScript::kFailed });
fixture.environment_.setContact(true, 0.10);
for (int i = 0; i < 12 && fixture.loop_.state() == NavigationState::kControlling; ++i)
{
fixture.stepOnce();
}
ASSERT_EQ(fixture.loop_.state(), NavigationState::kRecovering);
ASSERT_EQ(fixture.recovery_.lastTrigger(), RecoveryTrigger::kCollision);
for (int i = 0; i < 4 && fixture.loop_.state() == NavigationState::kRecovering; ++i)
{
fixture.stepOnce();
}
ASSERT_EQ(fixture.loop_.state(), NavigationState::kControlling)
<< "detour thất bại phải quay về kControlling với route collision đã cạn";
// onRecoveryFinished xoá chuỗi phanh: tối đa confirm_cycles cycle lệnh có thể khác 0 rồi phanh lại.
bool escalated = false;
int nonzero_after_settle = 0;
for (int i = 0; i < 60 && !escalated; ++i)
{
fixture.stepOnce();
if (i >= 3 && fixture.loop_.lastCommand().linear.x != 0.0)
{
++nonzero_after_settle;
}
escalated = fixture.loop_.state() == NavigationState::kRecovering &&
fixture.recovery_.lastTrigger() == RecoveryTrigger::kControllingFailed;
}
EXPECT_TRUE(escalated) << "EnvMonitor held the robot but nothing escalated";
EXPECT_EQ(nonzero_after_settle, 0) << "brake must hold once re-confirmed";
}
TEST(WalkingSkeletonEnvContact, DetourFromContactThatDidNotMoveTheRobotArmsTheStandDown)
{
// Run 6/9 16:30 (đám đông): người đứng 7 cm trước mũi -> cờ collision -> detour -> chạm lại ngay -> cờ -> detour ...
// 4 lần rồi ABORT, vì stand-down không được vũ trang (trigger đọc ở cycle tick là mặc định). Chuỗi đúng: sau
// detour do cờ collision mà robot không dịch, chạm lại thì kContact ĐỨNG RA — không phanh, không cờ thứ hai.
Fixture fixture(envContactConfig());
driveToControlling(fixture);
std::vector<robot_geometry_msgs::PoseStamped> detour{ makeRequest(0.0).goal, makeRequest(3.0).goal };
fixture.recovery_.setScript({ RecoveryScript::kSucceeded });
fixture.recovery_.setSucceedWithPath(detour);
fixture.environment_.setContact(true, 0.10);
for (int i = 0; i < 12 && fixture.loop_.state() == NavigationState::kControlling; ++i)
{
fixture.stepOnce();
}
ASSERT_EQ(fixture.loop_.state(), NavigationState::kRecovering);
ASSERT_EQ(fixture.recovery_.lastTrigger(), RecoveryTrigger::kCollision);
for (int i = 0; i < 4 && fixture.loop_.state() == NavigationState::kRecovering; ++i)
{
fixture.stepOnce();
}
ASSERT_EQ(fixture.loop_.state(), NavigationState::kControlling);
// Vẫn chạm 0.10 m, robot (pose giả) không dịch: không được có RECOVERING thứ hai trong 1.5 s, và lệnh phải
// được trả về controller (đứng ra = không phanh).
int recovering_again = 0;
double max_cmd = 0.0;
for (int i = 0; i < 30; ++i)
{
fixture.stepOnce();
if (fixture.loop_.state() == NavigationState::kRecovering)
{
++recovering_again;
}
max_cmd = std::max(max_cmd, fixture.loop_.lastCommand().linear.x);
}
EXPECT_EQ(0, recovering_again) << "cờ collision nổ lại từ chính chỗ vừa detour";
EXPECT_GT(max_cmd, 0.0) << "stand-down phải nhường lệnh cho controller";
}
TEST(WalkingSkeletonEnvContact, ContactBeyondTheStoppingDistanceCapsSpeedWithoutBraking)
{
Fixture fixture(envContactConfig());
driveToControlling(fixture);
const double v_free = fixture.loop_.lastCommand().linear.x;
ASSERT_GT(v_free, 0.27);
// 2.0 m phía trước: bao sqrt(2·0.35·1.7) = 1.09 m/s > lệnh -> không đổi, không phanh.
fixture.environment_.setContact(true, 2.0);
for (int i = 0; i < 6; ++i)
{
fixture.stepOnce();
}
EXPECT_DOUBLE_EQ(fixture.loop_.lastCommand().linear.x, v_free);
EXPECT_EQ(fixture.loop_.state(), NavigationState::kControlling);
// 0.40 m: bao sqrt(2·0.35·(0.40 − margin 0.2 − dư 0.1)) = 0.265 m/s. Lệnh bị kẹp xuống đúng bao và GIỮ ở đó:
// quãng phanh ở tốc độ đã kẹp = 0.10 m -> còn 0.30 m > margin -> không phải "sắp chạm", không phanh, không cờ.
fixture.environment_.setContact(true, 0.40);
for (int i = 0; i < 8; ++i)
{
fixture.stepOnce();
EXPECT_NEAR(fixture.loop_.lastCommand().linear.x, std::sqrt(2.0 * 0.35 * 0.10), 1e-3) << "cycle " << i;
}
EXPECT_EQ(fixture.loop_.state(), NavigationState::kControlling);
}
// ---------------------------------------------------------------------------------------------
// Phép đo 4 — "planner đòi đi mà robot không tiến"
// ---------------------------------------------------------------------------------------------
namespace
{
/// Pose giả đứng yên tại gốc trong khi controller kOk vẫn phát v > 0 — đúng định nghĩa kẹt.
void runStalled(Fixture& fixture, int max_cycles)
{
fixture.controller_.setScript(std::vector<ControllerScript>(400, ControllerScript::kOk));
for (int i = 0; i < max_cycles && fixture.loop_.state() == NavigationState::kControlling; ++i)
{
fixture.stepOnce();
}
}
} // namespace