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>
This commit is contained in:
2026-09-12 22:07:34 +07:00
parent 7d00c5ab66
commit 8bc4895a60
41 changed files with 4751 additions and 95 deletions

View File

@@ -385,6 +385,181 @@ TEST(PlannerRunner, CancelledPlanProducesNoResult)
"nobody asks for anymore";
}
TEST(PlannerRunner, CancelPreemptsAPreemptablePlannerWithinMilliseconds)
{
// 2026-09-11: plugin implement robot_nav_core::Preemptable thì cancelPlan() cắt lượt đang chạy —
// thread rảnh trong vài ms thay vì 2 s. Đây là thứ làm CANCELLED/PAUSED nói thật mà không phải chờ.
Fixture fixture("TestPlannerSlowPreemptable");
ASSERT_TRUE(fixture.ok()) << fixture.error();
ASSERT_TRUE(fixture.runner_.startPlan(makePose(0.0, 0.0), makePose(2.0, 0.0), nullptr, 1));
std::this_thread::sleep_for(std::chrono::milliseconds(50));
ASSERT_TRUE(fixture.runner_.isPlanning());
const auto before = std::chrono::steady_clock::now();
fixture.runner_.cancelPlan();
int waited_ms = 0;
while (fixture.runner_.isPlanning() && waited_ms < 1000)
{
std::this_thread::sleep_for(std::chrono::milliseconds(1));
++waited_ms;
}
const double elapsed_ms =
std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - before).count();
EXPECT_FALSE(fixture.runner_.isPlanning());
EXPECT_LT(elapsed_ms, 200.0) << "preempt did not reach the planner; the thread ran to the end";
move_base2::PlanResult result;
EXPECT_FALSE(fixture.runner_.pollPlan(result)) << "a preempted attempt must not deliver a plan";
// Lượt kế phải khởi động được ngay và chạy bình thường (cờ preempt không dính sang lượt sau).
ASSERT_TRUE(fixture.runner_.startPlan(makePose(0.0, 0.0), makePose(1.0, 0.0), nullptr, 2));
EXPECT_TRUE(fixture.runner_.isPlanning());
fixture.runner_.cancelPlan();
for (int i = 0; i < 1000 && fixture.runner_.isPlanning(); ++i)
{
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
EXPECT_FALSE(fixture.runner_.isPlanning());
}
TEST(PlannerRunner, SwapWhileAPreemptablePlannerIsRunningCutsTheOldAttempt)
{
// Đổi profile (mission kế dùng planner khác) trong lúc lượt cũ chưa về: swapPlanner phải cắt
// instance ĐANG chạy, không chỉ đánh dấu vứt. Không cắt thì yêu cầu kế đứng ở kBusy tới hết
// allocated_time của lượt cũ (2 s ở đây, 10-30 s với SBPL thật).
Fixture fixture("TestPlannerSlowPreemptable");
ASSERT_TRUE(fixture.ok()) << fixture.error();
ASSERT_TRUE(fixture.runner_.startPlan(makePose(0.0, 0.0), makePose(2.0, 0.0), nullptr, 1));
std::this_thread::sleep_for(std::chrono::milliseconds(50));
ASSERT_TRUE(fixture.runner_.isPlanning());
const auto before = std::chrono::steady_clock::now();
ASSERT_TRUE(fixture.runner_.swapPlanner("TestPlannerOk"));
for (int i = 0; i < 1000 && fixture.runner_.isPlanning(); ++i)
{
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
const double elapsed_ms =
std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - before).count();
EXPECT_FALSE(fixture.runner_.isPlanning());
EXPECT_LT(elapsed_ms, 200.0) << "swapPlanner did not preempt the running instance";
move_base2::PlanResult result;
EXPECT_FALSE(fixture.runner_.pollPlan(result)) << "the old planner's attempt must be discarded";
EXPECT_EQ(fixture.runner_.activePlanner(), "TestPlannerOk");
// Planner mới chạy bình thường ngay sau đó.
ASSERT_TRUE(fixture.runner_.startPlan(makePose(0.0, 0.0), makePose(1.0, 0.0), nullptr, 2));
for (int i = 0; i < 10000 && fixture.runner_.isPlanning(); ++i)
{
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
ASSERT_TRUE(fixture.runner_.pollPlan(result));
EXPECT_TRUE(result.succeeded);
EXPECT_EQ(result.tag, 2U);
}
TEST(PlannerRunner, CancelAfterSwapPreemptsTheInstanceThatIsActuallyRunning)
{
// Thứ tự thật trong log 2026-09-11 (mission 2 đổi profile TRƯỚC khi accept_request gọi
// cancelPlan): active_ đã trỏ sang planner mới, nhưng thread vẫn ở trong makePlan của planner cũ.
// cancelPlan phải cắt đúng instance đang chạy, không phải active_.
Fixture fixture("TestPlannerSlowPreemptable");
ASSERT_TRUE(fixture.ok()) << fixture.error();
ASSERT_TRUE(fixture.runner_.startPlan(makePose(0.0, 0.0), makePose(2.0, 0.0), nullptr, 1));
std::this_thread::sleep_for(std::chrono::milliseconds(50));
ASSERT_TRUE(fixture.runner_.isPlanning());
// Đổi sang planner "ngoan" (stubborn — không Preemptable) để chứng minh cancel không nhìn active_:
// nếu cancel dynamic_cast trên active_ thì ra null và lượt Preemptable đang chạy KHÔNG bị cắt.
// Lưu ý: swapPlanner nay cũng preempt; để tách bạch, test này chỉ khẳng định tổng thể thread rảnh
// trong vài ms sau cặp swap+cancel, đúng như ControlLoop làm khi nhận goal mới.
ASSERT_TRUE(fixture.runner_.swapPlanner("TestPlannerSlowStubborn"));
fixture.runner_.cancelPlan();
int waited_ms = 0;
while (fixture.runner_.isPlanning() && waited_ms < 1000)
{
std::this_thread::sleep_for(std::chrono::milliseconds(1));
++waited_ms;
}
EXPECT_FALSE(fixture.runner_.isPlanning());
EXPECT_LT(waited_ms, 200) << "the running Preemptable instance was not the one preempted";
move_base2::PlanResult result;
EXPECT_FALSE(fixture.runner_.pollPlan(result));
}
TEST(PlannerRunner, SwapWhileTheJobIsQueuedButNotStartedDropsIt)
{
// Yêu cầu vừa được đặt, thread chưa kịp nhận: đổi planner phải rút yêu cầu đó ra, không để thread
// chạy yêu cầu của planner cũ trên instance mới rồi vứt.
Fixture fixture("TestPlannerSlowPreemptable");
ASSERT_TRUE(fixture.ok()) << fixture.error();
bool dropped_before_start = false;
for (int attempt = 0; attempt < 50 && !dropped_before_start; ++attempt)
{
ASSERT_TRUE(fixture.runner_.startPlan(makePose(0.0, 0.0), makePose(2.0, 0.0), nullptr, 1));
ASSERT_TRUE(fixture.runner_.swapPlanner("TestPlannerOk"));
// Cả hai nhánh (rút trước khi thread nhận / cắt sau khi nó nhận) đều phải rảnh trong vài ms.
int waited_ms = 0;
while (fixture.runner_.isPlanning() && waited_ms < 1000)
{
std::this_thread::sleep_for(std::chrono::milliseconds(1));
++waited_ms;
}
EXPECT_FALSE(fixture.runner_.isPlanning());
EXPECT_LT(waited_ms, 200);
move_base2::PlanResult result;
EXPECT_FALSE(fixture.runner_.pollPlan(result));
dropped_before_start = (waited_ms == 0);
ASSERT_TRUE(fixture.runner_.swapPlanner("TestPlannerSlowPreemptable"));
}
// Không ép nhánh "rút trước khi nhận" phải xảy ra (phụ thuộc scheduler), chỉ cần cả hai nhánh
// đều đúng.
SUCCEED();
}
TEST(PlannerRunner, DestructorPreemptsARunningPreemptablePlanner)
{
// Shutdown giữa một lượt search dài: destructor phải cắt lượt đó thay vì chờ hết allocated_time.
const auto before = std::chrono::steady_clock::now();
{
Fixture fixture("TestPlannerSlowPreemptable");
ASSERT_TRUE(fixture.ok()) << fixture.error();
ASSERT_TRUE(fixture.runner_.startPlan(makePose(0.0, 0.0), makePose(2.0, 0.0), nullptr, 1));
std::this_thread::sleep_for(std::chrono::milliseconds(50));
ASSERT_TRUE(fixture.runner_.isPlanning());
}
const double elapsed_ms =
std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - before).count();
EXPECT_LT(elapsed_ms, 500.0) << "destructor waited for the whole 2 s search";
}
TEST(PlannerRunner, CancelOnAStubbornPlannerFallsBackToDiscardingTheResult)
{
// Plugin cũ (không Preemptable): hành vi trước 2026-09-11 giữ nguyên — thread bận tới hết lượt,
// kết quả về bị vứt. isPlanning() phải nói thật suốt quãng đó.
Fixture fixture("TestPlannerSlowStubborn");
ASSERT_TRUE(fixture.ok()) << fixture.error();
ASSERT_TRUE(fixture.runner_.startPlan(makePose(0.0, 0.0), makePose(2.0, 0.0), nullptr, 1));
std::this_thread::sleep_for(std::chrono::milliseconds(50));
fixture.runner_.cancelPlan();
EXPECT_TRUE(fixture.runner_.isPlanning()) << "a stubborn planner cannot be cut short";
for (int i = 0; i < 2000 && fixture.runner_.isPlanning(); ++i)
{
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
EXPECT_FALSE(fixture.runner_.isPlanning());
move_base2::PlanResult result;
EXPECT_FALSE(fixture.runner_.pollPlan(result));
}
TEST(PlannerRunner, ResultCarriesBackTheTagItWasStartedWith)
{
Fixture fixture;