Files
move_base2/test/action_runner_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

504 lines
16 KiB
C++

/*********************************************************************
*
* move_base2 — kiểm ActionRunner: định tuyến theo actionType, vòng đời tick, và timeout tầng 1.
*
* Author: DuongTD
*********************************************************************/
#include <gtest/gtest.h>
#include <cstdlib>
#include <memory>
#include <string>
#include <vector>
#include <robot/node_handle.h>
#include <action_core/action_handler.h>
#include <move_base2/core/component_status.h>
#include <move_base2/runners/action_runner.h>
#include "fake_ports.h"
namespace
{
using action_core::ActionHandler;
using move_base2::ActionRunner;
using move_base2::ActionTick;
using move_base2::testing::FakeClockPort;
robot_protocol_msgs::Action makeAction(const std::string& type, const std::string& id = "a1")
{
robot_protocol_msgs::Action action;
action.actionType = type;
action.actionId = id;
return action;
}
/**
* @brief Handler viết hoàn toàn trong test.
*
* Sự tồn tại của nó là bài kiểm tra thật cho tính plugin: thêm một loại action mới mà không sửa
* file nào trong `src/` của gói.
*/
class ScriptedHandler final : public ActionHandler
{
public:
explicit ScriptedHandler(std::vector<std::string> types) : types_(std::move(types))
{
}
bool configure(const std::string& name, const action_core::ActionContext& /*ctx*/,
robot::NodeHandle& /*nh*/) override
{
name_ = name;
return configure_ok;
}
std::vector<std::string> supportedActionTypes() const override
{
return types_;
}
bool start(const robot_protocol_msgs::Action& action, const robot::Time& /*now*/) override
{
++start_count;
last_action_id = action.actionId;
return start_ok;
}
action_core::ActionTick update(const robot::Time& /*now*/) override
{
++update_count;
action_core::ActionTick tick;
if (ticks_after_cancel_left >= 0)
{
if (ticks_after_cancel_left-- > 0)
{
tick.status = action_core::ActionStatus::kRunning;
return tick;
}
tick.status = action_core::ActionStatus::kCancelled;
tick.message = "device safe";
return tick;
}
tick.status = next_status;
return tick;
}
void cancel() override
{
++cancel_count;
if (cancel_needs_ticks)
{
ticks_after_cancel_left = cancel_ticks;
next_status = action_core::ActionStatus::kRunning;
}
}
bool cancelNeedsTicks() const override
{
return cancel_needs_ticks;
}
void pause(const robot::Time& now) override
{
++pause_count;
last_pause_at = now;
}
void resume(const robot::Time& now) override
{
++resume_count;
last_resume_at = now;
}
bool configure_ok = true;
bool start_ok = true;
action_core::ActionStatus next_status = action_core::ActionStatus::kRunning;
/// Mô hình handler thiết bị: sau cancel() còn `cancel_ticks` lượt update() rồi mới kCancelled.
bool cancel_needs_ticks = false;
int cancel_ticks = 2;
int ticks_after_cancel_left = -1;
int start_count = 0;
int update_count = 0;
int cancel_count = 0;
int pause_count = 0;
int resume_count = 0;
robot::Time last_pause_at;
robot::Time last_resume_at;
std::string last_action_id;
private:
std::vector<std::string> types_;
std::string name_;
};
struct Rig
{
Rig()
{
runner.setClock(&clock);
}
bool load(const std::string& ns)
{
runner.setNamespace(ns);
robot::NodeHandle nh;
return runner.configure(nh);
}
FakeClockPort clock{1000.0};
ActionRunner runner;
};
// ------------------------------------------------------------------------------------------------
// Đăng ký thủ công — kiểm định tuyến và vòng đời mà không cần .so
// ------------------------------------------------------------------------------------------------
TEST(ActionRunner, RoutesByActionType)
{
Rig rig;
auto pick = std::make_shared<ScriptedHandler>(std::vector<std::string>{"pick"});
auto drop = std::make_shared<ScriptedHandler>(std::vector<std::string>{"drop"});
ASSERT_TRUE(rig.runner.registerHandler(pick));
ASSERT_TRUE(rig.runner.registerHandler(drop));
ASSERT_TRUE(rig.load("actions_empty"));
ASSERT_TRUE(rig.runner.start(makeAction("drop", "d7")));
EXPECT_EQ(drop->start_count, 1);
EXPECT_EQ(pick->start_count, 0);
EXPECT_EQ(drop->last_action_id, "d7");
}
TEST(ActionRunner, OneHandlerCanTakeSeveralTypes)
{
Rig rig;
auto handler = std::make_shared<ScriptedHandler>(std::vector<std::string>{"pick", "drop"});
ASSERT_TRUE(rig.runner.registerHandler(handler));
ASSERT_TRUE(rig.load("actions_empty"));
EXPECT_TRUE(rig.runner.start(makeAction("pick")));
EXPECT_TRUE(rig.runner.start(makeAction("drop")));
EXPECT_EQ(handler->start_count, 2);
}
TEST(ActionRunner, RejectsDuplicateActionType)
{
Rig rig;
ASSERT_TRUE(rig.runner.registerHandler(
std::make_shared<ScriptedHandler>(std::vector<std::string>{"pick"})));
// Hai handler cùng nhận một type thì định tuyến phụ thuộc thứ tự nạp — phải từ chối, không ghi đè.
EXPECT_FALSE(rig.runner.registerHandler(
std::make_shared<ScriptedHandler>(std::vector<std::string>{"pick"})));
}
TEST(ActionRunner, RejectsHandlerWithoutTypes)
{
Rig rig;
EXPECT_FALSE(rig.runner.registerHandler(std::make_shared<ScriptedHandler>(
std::vector<std::string>{})));
EXPECT_FALSE(rig.runner.registerHandler(nullptr));
}
TEST(ActionRunner, UnknownActionTypeFailsStart)
{
Rig rig;
ASSERT_TRUE(rig.runner.registerHandler(
std::make_shared<ScriptedHandler>(std::vector<std::string>{"pick"})));
ASSERT_TRUE(rig.load("actions_empty"));
EXPECT_FALSE(rig.runner.start(makeAction("charge")));
}
TEST(ActionRunner, EmptyActionTypeFailsStart)
{
Rig rig;
ASSERT_TRUE(rig.runner.registerHandler(
std::make_shared<ScriptedHandler>(std::vector<std::string>{"pick"})));
ASSERT_TRUE(rig.load("actions_empty"));
EXPECT_FALSE(rig.runner.start(makeAction("")));
}
TEST(ActionRunner, StartBeforeConfigureFails)
{
Rig rig;
ASSERT_TRUE(rig.runner.registerHandler(
std::make_shared<ScriptedHandler>(std::vector<std::string>{"pick"})));
EXPECT_FALSE(rig.runner.start(makeAction("pick")));
}
TEST(ActionRunner, HandlerRefusingStartIsReported)
{
Rig rig;
auto handler = std::make_shared<ScriptedHandler>(std::vector<std::string>{"pick"});
handler->start_ok = false;
ASSERT_TRUE(rig.runner.registerHandler(handler));
ASSERT_TRUE(rig.load("actions_empty"));
EXPECT_FALSE(rig.runner.start(makeAction("pick")));
// Không được tick tiếp sau khi start hỏng.
EXPECT_EQ(rig.runner.update().status, ActionTick::Status::kFailed);
EXPECT_EQ(handler->update_count, 0);
}
TEST(ActionRunner, UpdateWithoutActiveActionFailsInsteadOfCrashing)
{
Rig rig;
ASSERT_TRUE(rig.load("actions_empty"));
const ActionTick tick = rig.runner.update();
EXPECT_EQ(tick.status, ActionTick::Status::kFailed);
EXPECT_FALSE(tick.message.empty());
}
TEST(ActionRunner, TicksUntilHandlerFinishes)
{
Rig rig;
auto handler = std::make_shared<ScriptedHandler>(std::vector<std::string>{"pick"});
ASSERT_TRUE(rig.runner.registerHandler(handler));
ASSERT_TRUE(rig.load("actions_empty"));
ASSERT_TRUE(rig.runner.start(makeAction("pick")));
EXPECT_EQ(rig.runner.update().status, ActionTick::Status::kRunning);
EXPECT_EQ(rig.runner.update().status, ActionTick::Status::kRunning);
handler->next_status = action_core::ActionStatus::kSucceeded;
EXPECT_EQ(rig.runner.update().status, ActionTick::Status::kSucceeded);
// Sau khi kết thúc, action không còn active: tick thêm là lỗi thứ tự gọi, không phải kRunning.
EXPECT_EQ(rig.runner.update().status, ActionTick::Status::kFailed);
EXPECT_EQ(handler->update_count, 3);
}
TEST(ActionRunner, CancelReachesHandlerAndClearsActive)
{
Rig rig;
auto handler = std::make_shared<ScriptedHandler>(std::vector<std::string>{"pick"});
ASSERT_TRUE(rig.runner.registerHandler(handler));
ASSERT_TRUE(rig.load("actions_empty"));
ASSERT_TRUE(rig.runner.start(makeAction("pick")));
rig.runner.cancel();
EXPECT_EQ(handler->cancel_count, 1);
EXPECT_EQ(rig.runner.update().status, ActionTick::Status::kFailed);
}
TEST(ActionRunner, DeviceHandlerKeepsBeingTickedAfterCancelUntilItReportsCancelled)
{
// Pha 3 (2026-09-11): handler khai cancelNeedsTicks → runner GIỮ nó sau cancel(), tick tiếp tới
// khi trả kCancelled; hàng kAction = stopping trong lúc đó, idle khi xong.
Rig rig;
move_base2::ComponentStatusBoard board;
rig.runner.attachStatusBoard(&board);
auto handler = std::make_shared<ScriptedHandler>(std::vector<std::string>{"lift"});
handler->cancel_needs_ticks = true;
handler->cancel_ticks = 2;
ASSERT_TRUE(rig.runner.registerHandler(handler));
ASSERT_TRUE(rig.load("actions_empty"));
ASSERT_TRUE(rig.runner.start(makeAction("lift")));
EXPECT_EQ(board.phase(move_base2::Component::kAction), move_base2::ComponentPhase::kBusy);
rig.runner.cancel();
EXPECT_EQ(handler->cancel_count, 1);
EXPECT_EQ(board.phase(move_base2::Component::kAction), move_base2::ComponentPhase::kStopping);
EXPECT_EQ(rig.runner.update().status, ActionTick::Status::kRunning);
EXPECT_EQ(rig.runner.update().status, ActionTick::Status::kRunning);
EXPECT_EQ(board.phase(move_base2::Component::kAction), move_base2::ComponentPhase::kStopping);
const ActionTick done = rig.runner.update();
EXPECT_EQ(done.status, ActionTick::Status::kCancelled);
EXPECT_EQ(board.phase(move_base2::Component::kAction), move_base2::ComponentPhase::kIdle);
EXPECT_EQ(rig.runner.update().status, ActionTick::Status::kFailed) << "handler was released";
}
TEST(ActionRunner, PerceptionHandlerIsReleasedRightAwayOnCancel)
{
Rig rig;
move_base2::ComponentStatusBoard board;
rig.runner.attachStatusBoard(&board);
auto handler = std::make_shared<ScriptedHandler>(std::vector<std::string>{"detect"});
ASSERT_TRUE(rig.runner.registerHandler(handler));
ASSERT_TRUE(rig.load("actions_empty"));
ASSERT_TRUE(rig.runner.start(makeAction("detect")));
rig.runner.cancel();
EXPECT_EQ(board.phase(move_base2::Component::kAction), move_base2::ComponentPhase::kIdle);
EXPECT_EQ(rig.runner.update().status, ActionTick::Status::kFailed) << "no handler active";
}
TEST(ActionRunner, PauseAndResumeReachTheHandlerWithTheClockTime)
{
Rig rig;
move_base2::ComponentStatusBoard board;
rig.runner.attachStatusBoard(&board);
auto handler = std::make_shared<ScriptedHandler>(std::vector<std::string>{"pick"});
ASSERT_TRUE(rig.runner.registerHandler(handler));
ASSERT_TRUE(rig.load("actions_empty"));
ASSERT_TRUE(rig.runner.start(makeAction("pick")));
rig.clock.advance(1.0);
rig.runner.pause();
EXPECT_EQ(handler->pause_count, 1);
EXPECT_DOUBLE_EQ(handler->last_pause_at.toSec(), 1001.0);
EXPECT_EQ(board.phase(move_base2::Component::kAction), move_base2::ComponentPhase::kPaused);
rig.clock.advance(30.0);
rig.runner.resume();
EXPECT_EQ(handler->resume_count, 1);
EXPECT_DOUBLE_EQ(handler->last_resume_at.toSec(), 1031.0);
EXPECT_EQ(board.phase(move_base2::Component::kAction), move_base2::ComponentPhase::kBusy);
// Không có action đang chạy thì pause/resume không tới handler nào.
rig.runner.cancel();
rig.runner.pause();
rig.runner.resume();
EXPECT_EQ(handler->pause_count, 1);
EXPECT_EQ(handler->resume_count, 1);
}
TEST(ActionRunner, LoadedNoopHandlerDoesNotCountPausedTimeTowardsItsDuration)
{
// Handler thật (noop, duration 2 s): pause 30 s giữa chừng, resume, phải còn chạy tiếp đúng phần
// thời gian còn lại — không kết thúc sớm, không timeout oan.
Rig rig;
ASSERT_TRUE(rig.load("actions"));
ASSERT_TRUE(rig.runner.start(makeAction("wait", "w1"))); // duration: 2.0 s, timeout 10 s
rig.clock.advance(1.0);
EXPECT_EQ(rig.runner.update().status, ActionTick::Status::kRunning);
rig.runner.pause();
rig.clock.advance(30.0); // đứng chờ lâu hơn cả timeout 10 s
rig.runner.resume();
EXPECT_EQ(rig.runner.update().status, ActionTick::Status::kRunning)
<< "the 30 s pause must not count: 1 s of 2 s elapsed, and the 10 s timeout must not fire";
rig.clock.advance(1.0);
EXPECT_EQ(rig.runner.update().status, ActionTick::Status::kSucceeded);
}
TEST(ActionRunner, CancelWithoutActiveActionIsSafe)
{
Rig rig;
ASSERT_TRUE(rig.load("actions_empty"));
rig.runner.cancel();
SUCCEED();
}
TEST(ActionRunner, ConfigureRequiresClock)
{
ActionRunner runner; // không setClock
robot::NodeHandle nh;
EXPECT_FALSE(runner.configure(nh)) << "missing ClockPort means handlers have no timeout "
"reference";
}
TEST(ActionRunner, EmptyHandlerListIsValid)
{
// Hệ không có thiết bị nào: mọi mission đều nav-only, và ControlLoop::submit đã từ chối yêu cầu
// mang action ngay tại cửa.
Rig rig;
EXPECT_TRUE(rig.load("actions_empty"));
EXPECT_EQ(rig.runner.handlerCount(), 0u);
EXPECT_FALSE(rig.runner.start(makeAction("pick")));
}
// ------------------------------------------------------------------------------------------------
// Nạp thật qua Boost.DLL — đúng đường runtime đi
// ------------------------------------------------------------------------------------------------
TEST(ActionRunner, LoadsHandlerPluginFromConfig)
{
Rig rig;
ASSERT_TRUE(rig.load("actions"));
ASSERT_EQ(rig.runner.handlerCount(), 1u);
EXPECT_NE(rig.runner.find("wait"), nullptr);
EXPECT_NE(rig.runner.find("pick"), nullptr);
EXPECT_EQ(rig.runner.find("charge"), nullptr);
}
TEST(ActionRunner, LoadedHandlerRunsForConfiguredDuration)
{
Rig rig;
ASSERT_TRUE(rig.load("actions"));
ASSERT_TRUE(rig.runner.start(makeAction("wait", "w1"))); // duration: 2.0 s
rig.clock.advance(1.0);
EXPECT_EQ(rig.runner.update().status, ActionTick::Status::kRunning);
rig.clock.advance(1.0);
EXPECT_EQ(rig.runner.update().status, ActionTick::Status::kSucceeded);
}
TEST(ActionRunner, HandlerTimesOutOnItsOwnWithoutStateMachineHelp)
{
Rig rig;
ASSERT_TRUE(rig.load("actions_slow")); // hang: true, timeout 3 s
ASSERT_TRUE(rig.runner.start(makeAction("wait")));
rig.clock.advance(2.0);
ASSERT_EQ(rig.runner.update().status, ActionTick::Status::kRunning);
rig.clock.advance(1.5);
const ActionTick tick = rig.runner.update();
// Timeout TẦNG 1: handler tự chịu trách nhiệm, không dựa vào action_patience (mặc định tắt).
EXPECT_EQ(tick.status, ActionTick::Status::kFailed);
EXPECT_NE(tick.message.find("timeout"), std::string::npos);
}
TEST(ActionRunner, HangingHandlerWithoutTimeoutIsRejectedAtConfigure)
{
// Treo + tắt timeout = action chạy vĩnh viễn. Contract cấm, nên phải chặn lúc khởi động.
Rig rig;
EXPECT_FALSE(rig.load("actions_hang_forever"));
EXPECT_EQ(rig.runner.handlerCount(), 0u);
}
TEST(ActionRunner, MissingLibraryPathFailsConfigure)
{
Rig rig;
EXPECT_FALSE(rig.load("actions_missing_library"));
EXPECT_EQ(rig.runner.handlerCount(), 0u);
}
TEST(ActionRunner, HandlerWithTimeoutBelowDurationIsRejectedAtConfigure)
{
// Cấu hình khiến action LUÔN hỏng vì timeout — phải chặn lúc khởi động, không phải lúc chạy.
Rig rig;
EXPECT_FALSE(rig.load("actions_bad"));
EXPECT_EQ(rig.runner.handlerCount(), 0u);
}
TEST(ActionRunner, ConfigureTwiceRejected)
{
Rig rig;
ASSERT_TRUE(rig.load("actions"));
robot::NodeHandle nh;
EXPECT_FALSE(rig.runner.configure(nh));
}
} // namespace
int main(int argc, char** argv)
{
#ifdef MOVE_BASE2_TEST_CONFIG_DIR
setenv("PNKX_NAV_CORE_CONFIG_DIR", MOVE_BASE2_TEST_CONFIG_DIR, 0);
#endif
#ifdef MOVE_BASE2_TEST_LIBRARY_DIR
setenv("PNKX_NAV_CORE_LIBRARY_PATH", MOVE_BASE2_TEST_LIBRARY_DIR, 0);
#endif
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}