From 383a04fe297b369d9c9af26f14752f0a21be251f Mon Sep 17 00:00:00 2001 From: duongtd Date: Thu, 13 Aug 2026 15:01:48 +0700 Subject: [PATCH] Report why an action failed instead of a bare "action failed" FrameSamplerActionHandler already builds a precise reason for each way it can fail: too few samples, detection too scattered, could not publish the output frame, raw frame never appeared. All four reached the log as the same four words, because control_loop read the tick, kept only the status, and dropped the message, while the state machine passed a hard-coded string to finish(). Three field runs in a row could not be diagnosed for that reason: the detector was healthy, the host confirmed pallet_raw was published and resolvable, and the only thing navigation said was "action failed". The handler message now travels through StateMachineInput into the terminal reason, so it reaches the host feedback as well as the log, and control_loop logs it directly - as an error when the action fails, as info when it succeeds, where it carries the sample count worth comparing against the next failure. StateMachineOutput::reason is a const char* and enter() stores the pointer rather than copying, so the composed string lives in a StateMachine member. Building it in a local would return a pointer into destroyed memory - every other reason in that class is a string literal, so nothing had hit this before. Two tests cover it: the message reaches the reason, and the reason survives the StateMachineInput that carried it. Config in this tree follows the same split as the robot: per-marker dock_anchor and footprint_dock in maker_sources.yaml, detect handlers separated into detect_charger and detect_pallet. --- config/runtime/action_handlers_params.yaml | 2 +- config/runtime/compound_actions_params.yaml | 6 +- config/runtime/costmap_common_params.yaml | 4 +- config/runtime/maker_sources.yaml | 8 +- config/runtime/move_base_common_params.yaml | 8 +- .../runtime/stanley_local_planner_params.yaml | 123 ++++++++++++++++++ include/move_base2/control_loop.h | 4 + include/move_base2/core/state_machine.h | 22 ++++ src/control_loop.cpp | 19 +++ src/state_machine.cpp | 11 +- test/state_machine_test.cpp | 42 ++++++ 11 files changed, 234 insertions(+), 15 deletions(-) diff --git a/config/runtime/action_handlers_params.yaml b/config/runtime/action_handlers_params.yaml index 99325cc..6582345 100644 --- a/config/runtime/action_handlers_params.yaml +++ b/config/runtime/action_handlers_params.yaml @@ -70,7 +70,7 @@ actions: simulated_parent_frame: base_link simulated_offset_x: -1.0 # [m] ► Chỉnh: chỉ có nghĩa khi use_simulated_goal: true. simulated_offset_y: 0.0 # [m] Đặt theo vị trí vật thể giả trong world Gazebo. - simulated_offset_yaw: 0.05 # [rad] + simulated_offset_yaw: -0.09 # [rad] # [s] Chờ robot đứng hẳn trước khi lấy mẫu — pose lúc vừa dừng còn dao động cơ khí. # ► Chỉnh: TĂNG nếu robot nặng/treo mềm và mẫu đầu bị lệch. GIẢM để rút ngắn chu kỳ dock. diff --git a/config/runtime/compound_actions_params.yaml b/config/runtime/compound_actions_params.yaml index a4fcc68..fadee61 100644 --- a/config/runtime/compound_actions_params.yaml +++ b/config/runtime/compound_actions_params.yaml @@ -64,18 +64,18 @@ vda5050_src: # LÚC ĐÓ — lúc adapter sinh chặng thì robot còn chưa tới nơi. # ► Chỉnh: [m] âm = lùi. Đặt đủ dài để càng nâng ra hẳn khỏi khe kệ trước khi robot xoay; # quá ngắn thì kệ quệt vào giá, quá dài thì tốn thời gian và có thể lùi vào lối đi chung. - - {move: -0.5, profile: go_straight} + # - {move: -0.5, profile: go_straight} dockTo: steps: - {action: DetectPallet} - - {move_to: dock_target, profile: docking, marker: trolley} + - {move_to: dock_target, profile: docking, marker: pallet} - {action: LiftFork} # Lùi ra khỏi khe kệ. Quãng đường tương đối được quy ra pose tuyệt đối tại `submit`, từ pose # LÚC ĐÓ — lúc adapter sinh chặng thì robot còn chưa tới nơi. # ► Chỉnh: [m] âm = lùi. Đặt đủ dài để càng nâng ra hẳn khỏi khe kệ trước khi robot xoay; # quá ngắn thì kệ quệt vào giá, quá dài thì tốn thời gian và có thể lùi vào lối đi chung. - - {move: -0.5, profile: go_straight} + # - {move: -0.5, profile: go_straight} # --- UnDockFromStation: lùi ra khỏi trạm -------------------------------------------------------- # Trước đây action này chạy phía host bằng `moveStraightTo`, một entry point đã bị gỡ vì nó đẩy diff --git a/config/runtime/costmap_common_params.yaml b/config/runtime/costmap_common_params.yaml index b975c63..30fb35e 100755 --- a/config/runtime/costmap_common_params.yaml +++ b/config/runtime/costmap_common_params.yaml @@ -21,8 +21,8 @@ virtual_walls_map: lethal_cost_threshold: 100 obstacles: - observation_sources: b_scan pc_marking pc_clearing pc_r_marking pc_r_clearing - # f_scan_marking: f_scan_marking f_scan_clearing + observation_sources: + # f_scan_marking: f_scan_marking f_scan_clearing b_scan pc_marking pc_clearing pc_r_marking pc_r_clearing # topic: /f_scan # data_type: LaserScan # clearing: false diff --git a/config/runtime/maker_sources.yaml b/config/runtime/maker_sources.yaml index 0794fbd..38883ed 100644 --- a/config/runtime/maker_sources.yaml +++ b/config/runtime/maker_sources.yaml @@ -60,27 +60,27 @@ maker_sources: trolley charger dock_station pallet docking_marker_profiles: trolley: global_planner: DockPlanner - local_planner: HybridLocalPlanner + local_planner: StanleyDockingLocalPlanner # Goal ở trọng tâm xe trolley (robot chui gầm) → cộng extent tâm→mặt từ footprint_dock. dock_anchor: center footprint_dock: [[0.583,-0.48],[0.583,0.48],[-0.583,0.48],[-0.583,-0.48]] charger: global_planner: TwoPointsPlanner - local_planner: HybridLocalPlanner + local_planner: StanleyDockingLocalPlanner # Goal teach ngay tâm mặt trạm sạc. Chỉ có tác dụng nếu đổi sang DockPlanner. dock_anchor: face footprint_dock: [[0.583,-0.48],[0.583,0.48],[-0.583,0.48],[-0.583,-0.48]] dock_station: global_planner: TwoPointsPlanner - local_planner: HybridLocalPlanner + local_planner: StanleyDockingLocalPlanner dock_anchor: center footprint_dock: [[0.583,-0.48],[0.583,0.48],[-0.583,0.48],[-0.583,-0.48]] pallet: global_planner: DockPlanner - local_planner: HybridLocalPlanner + local_planner: StanleyDockingLocalPlanner # Goal teach ở tâm mặt pallet → dock không đóng góp khoảng dừng, footprint_dock bị bỏ qua. dock_anchor: face footprint_dock: [[0.9,-0.8],[0.9,0.8],[-0.9,0.8],[-0.9,-0.8]] diff --git a/config/runtime/move_base_common_params.yaml b/config/runtime/move_base_common_params.yaml index 4a96eb8..7fcc2fd 100644 --- a/config/runtime/move_base_common_params.yaml +++ b/config/runtime/move_base_common_params.yaml @@ -24,14 +24,16 @@ position: global_planner: CustomPlanner # vật chất hoá tuyến NURBS từ edge của VDA5050 Order. # MÙ VẬT CẢN theo thiết kế — nó là route materializer, không # phải search planner. Chỉ có bản makePlan(Order, ...). - local_planner: PriestLocalPlanner + local_planner: StanleyLocalPlanner docking: # goal_frame đã được ControlLoop quy thành pose tuyệt đối. DockPlanner dùng đúng contract # makePlan(start, goal, plan), còn CustomPlanner chỉ xử lý makePlan(Order, start, goal, plan). # đây là config default sẽ được dùng nếu config theo từng maker docking ở file maker_sources.yaml bị bỏ trống global_planner: DockPlanner - local_planner: HybridLocalPlanner + # StanleyDockingLocalPlanner = CUNG libstanley_local_planner voi profile position, + # chi khac alias -> doc block config rieng (tolerance chat, toc do dock cham). + local_planner: StanleyDockingLocalPlanner go_straight: global_planner: TwoPointsPlanner @@ -157,7 +159,7 @@ oscillation_distance: 0.5 # `steering` là đổi nghĩa cho CẢ recovery, nên chỉ đổi khi robot thật sự là bicycle VÀ route # recovery đã bỏ/thay hành vi xoay tại chỗ (bicycle không xoay tại chỗ được). # Riêng việc chạy được bicycle thì `max_vel_theta` bên dưới đã đủ: 1.5708 không còn bị cắt. -command_semantics: twist +command_semantics: steering # [m/s] Trần tốc độ tiến (semantics `steering`: tốc độ bánh steer). Phải > max_vel_x của local # planner đang chạy — stanley 0.50, pnkx 1.2. diff --git a/config/runtime/stanley_local_planner_params.yaml b/config/runtime/stanley_local_planner_params.yaml index 114c6ff..2417432 100644 --- a/config/runtime/stanley_local_planner_params.yaml +++ b/config/runtime/stanley_local_planner_params.yaml @@ -175,5 +175,128 @@ StanleyLocalPlanner: # lines silently eat each other - never rely on it). # 3 produces >1800 lines/min at 30 Hz - field debugging only +# ============================================================================== +# PROFILE DOCKING (docking_planner_name / docking.local_planner tro vao day). +# CUNG code voi StanleyLocalPlanner (mot factory, hai BOOST_DLL_ALIAS) — chi khac +# config. YAML namespace KHONG ke thua: block nay phai lap lai DU moi key, thieu +# key nao la key do roi ve default trong struct C++, KHONG roi ve block tren. +# Giai thich chi tiet tung tham so: xem block StanleyLocalPlanner o tren. +# Khac biet docking (danh dau # DOCKING:): +# - toc do thap (leg dock ~1.7 m, do chinh xac quan trong hon thoi gian) +# - tolerance chat (xy 0.015 / yaw 0.010 thay vi 0.030 / 0.020) +# ============================================================================== StanleyDockingLocalPlanner: library_path: libstanley_local_planner + + # ================= Robot limits ================= + max_vel_x: 0.30 # [m/s] DOCKING: tran thap — leg dock ngan, uu tien chinh xac + min_vel_x: -0.20 # [m/s] DOCKING: lui cham khi vao pallet + wheel_base: 0.0 # [m] 0 = derive from TF front_axle_frame -> rear_axle_frame + front_axle_frame: "steer_link" + rear_axle_frame: "base_link" + + steer_limit_standstill: 1.5708 # [rad] + steer_limit_at_max_vel: 0.5000 # [rad] + align_steer_angle: 1.5708 # [rad] + min_steer_angle: 0.20 # [rad] + max_steer_rate: 1.00 # [rad/s] + + steer_zero_offset: 0.0 # [rad] SIM: khong co zero servo + + # ================= Goal tolerance ================= + xy_goal_tolerance: 0.015 # [m] DOCKING: 0.030 -> 0.015 (log 13/08: dung sat mep 0.024) + yaw_goal_tolerance: 0.010 # [rad] DOCKING: 0.020 -> 0.010 (yaw 0.02 x 1.2 m pallet = 2.4 cm mui cang) + goal_sq_dist_tol: 0.05 # [m^2] + + # ================= Control law (Stanley) ================= + path_yaw_mode: "tangent" + control_gain_e: 2.0 + control_gain_d: 1.5 + gain_cte_weight: 0.8 + gain_heading_weight: 0.5 + gain_min: 0.5 + gain_max: 1.8 + soft_min_vel: 0.20 # [m/s] + alpha_gain: 0.0 + near_goal_heading_gain: 4.0 # DOCKING 13/08: het pivot cuoi — dong not ~0.03 rad heading tren 0.2 m thang chot (yaw-rate ~ v*tan(delta)/L sup o toc bo; gain thuong chi dong 0.005-0.015 rad). Chi an ngoai curve mode. Robot lac duoi cuoi thi giam 3.0. + curve_gain_e_bonus: 0.0 # DOCKING 13/08: 4x heading gain nhan reference lead 0.23 rad dau chang thanh slam full-lock -90, robot xoay tai cho ~2 s truoc khi lan banh. ff da ganh cua; bo bonus de vao cua bang ff + gain 2.0. Neu giua cua e tang lai thi thu 1.0. + tangent_window_pts: 1 # DOCKING 13/08: cua so 3 diem o SAT DAU path lech het ve phia truoc (chord 0..5 = 0.25 m cong) -> reference lead 0.23 thay vi 0.125 rad. Path dock la duong giai tich, 1 chord/5cm du sach. Path rang cua thi tra ve 3. + heading_preview: 0.10 # [m] GIU 0.10. Trial 0.20 (13/08 run C) FAIL: ff doc kappa truoc 0.2 m nen tat som giua cua -> understeer, e max 0.071, th_e o dich 0.097. Combo tot nhat da do: align_to_path_start true + preview 0.10 (run B: max 0.031-0.033, mean 0.012-0.015). + curve_feedforward_gain: 1.0 + + # ================= Heading bias ================= + # DOCKING: OFF co chu dich — leg dock lui + cong + ngan, estimator khong du mau + # de hoc (instance nay KHONG thua huong bias instance position da hoc). + heading_bias_mode: "off" + heading_bias_tau: 30.0 # [s] + heading_bias_min_vel: 0.45 # [m/s] + heading_bias_clamp: 0.05 # [rad] + heading_bias_min_samples: 60 # [cycles] + + # ================= Steering bias ================= + steer_bias_gain: 0.0 # DOCKING + SIM: OFF (leg qua ngan de tich phan co nghia) + steer_bias_clamp: 0.05 # [rad] + steer_bias_decay: 0.9999 + steer_bias_min_vel: 0.30 # [m/s] + steer_bias_max_heading_err: 0.10 # [rad] + + # ================= Plan window / lookahead ================= + max_global_plan_lookahead_dist: 3.0 # [m] + min_lookahead: 0.50 # [m] + min_lookahead_near_goal: 0.40 # [m] + dyn_lookahead_gain: 2.50 # [m/(m/s)] + near_goal_freeze_dist: 0.50 # [m] + max_advance_dist: 0.20 # [m] + max_back_dist: 0.10 # [m] + + # ================= Curvature ================= + high_curvature: 0.30 # [1/m] + mid_curvature: 0.20 # [1/m] + low_curvature: 0.10 # [1/m] + straight_confirm_steps: 110 + + # ================= Speed profile ================= + speed_base: 0.20 # [m/s] DOCKING: 0.30 -> 0.20 + curve_max_speed: 0.20 # [m/s] DOCKING: cua dock R~1 m, di cham + min_drive_speed: 0.07 # [m/s] + accel_distance: 2.00 # [m] + decel_min: 0.05 # [m/s per cycle] + decel_max: 0.10 # [m/s per cycle] + collision_horizon_factor: 2.0 + goal_decel_limit: 0.40 # [m/s^2] + min_approach_speed: 0.05 # [m/s] DOCKING: 0.06 -> 0.05, bo cham vao tolerance chat hon + + # ================= Align / phase ================= + align_to_path_start: true # DOCKING: pivot ve dung heading POSE DAU path. Da thu false 13/08 (run C, kem preview 0.20): khong bam — giu true. + # khong phai heading reference cua control law (nearest + preview + # 0.10 m, trung binh 3 diem) — tren cua K~1.4 reference do di truoc + # diem dau path ~0.14 rad + align_pivot_toward_curve: true # DOCKING 13/08: pivot do banh ve PHIA cua sap toi (ff pose 0 < -0.30 rad -> -90). Truoc do do +90 roi phai quet 2.6-3.1 rad tai cho ~2.4 s truoc khi lan banh. ROBOT THAT: kiem tra drive nhan lenh -90 truoc khi bat. + heading_eps: 0.010 # [rad] DOCKING: 0.020 -> 0.010. Path dock vao cua K~1.4 ngay + # pose 0; align dung o 0.0185 rad la mang san 1 do lech vao cua + # (sim 13/08: e vot 0.034 m ngay sau align) + steer_eps: 0.020 # [rad] + heading_align_tol: 0.050 # [rad] + near_goal_dist: 1.00 # [m] + steer_realign_off: 0.503 # [rad] + steer_realign_on: 0.080 # [rad] DOCKING: 0.150 -> 0.080. Steer quet 2.6 rad tu pivot sang + # goc cua mat ~2.2 s; tha drive khi con lech 0.111 rad la chay + # voi banh lai chua toi noi — cho settle gan hon roi moi tha + steering_active: 0.094 # [rad] + segment_transition_threshold: 0.010 # [m] + segment_end_ratio: 0.05 + xy_reached_gate_factor: 3.0 + + # ================= TF guard ================= + tf_lookup_at_pose_stamp: true + transform_tolerance: 0.20 # [s] + max_plan_tf_jump_rate: 1.50 # [m/s] SIM (robot that: 0.60) + max_plan_tf_jump_abs: 1.00 # [m] + max_plan_tf_yaw_jump: 0.20 # [rad] + tf_reject_window_cycles: 30 + tf_reject_ratio: 0.5 + + # ================= Debug ================= + debug_tf: false + debug_offset: true + debug_level: 2 diff --git a/include/move_base2/control_loop.h b/include/move_base2/control_loop.h index c91b59f..24bb0ee 100644 --- a/include/move_base2/control_loop.h +++ b/include/move_base2/control_loop.h @@ -430,6 +430,10 @@ private: RecoveryFeedback recovery_feedback_ = RecoveryFeedback::kIdle; ActionFeedback action_feedback_ = ActionFeedback::kIdle; + /// Lý do action handler đưa ra cho lần tick vừa rồi; chỉ giữ khi tick đó HỎNG, xem + /// @ref StateMachineInput::action_message. + std::string action_message_; + std::vector latest_plan_; /// Tuyến tham chiếu của chặng — xem @ref orderPlan. Chỉ ghi từ kết quả của PlannerRunner. std::vector order_plan_; diff --git a/include/move_base2/core/state_machine.h b/include/move_base2/core/state_machine.h index de896d7..3dbb550 100644 --- a/include/move_base2/core/state_machine.h +++ b/include/move_base2/core/state_machine.h @@ -153,6 +153,18 @@ struct StateMachineInput RecoveryFeedback recovery = RecoveryFeedback::kIdle; ActionFeedback action = ActionFeedback::kIdle; + /** + * Lý do action handler đưa ra cho lần tick vừa rồi; rỗng = handler không nói gì. + * + * Chỉ đọc khi @ref action là `kFailed`, và chỉ để ghép vào lý do kết thúc. Không có nó thì mọi + * kiểu hỏng của action đều hiện ra ngoài là đúng một chuỗi `"action failed"` — handler dò frame + * phân biệt được "thiếu mẫu", "dò ra nhưng tản quá", "không publish được" và "frame không bao giờ + * xuất hiện", bốn nguyên nhân với bốn cách xử lý khác nhau, mà người đọc log không thấy cái nào. + * + * Đây là chuỗi cho NGƯỜI đọc, không phải mã lỗi: state machine không rẽ nhánh theo nó. + */ + std::string action_message; + /** * Lấy được pose robot hay không. * @@ -401,6 +413,16 @@ private: std::size_t recovery_index_ = 0; RecoveryTrigger active_recovery_trigger_ = RecoveryTrigger::kPlanningFailed; + /** + * Kho giữ lý do action hỏng sau khi ghép với @ref StateMachineInput::action_message. + * + * @ref StateMachineOutput::reason là `const char*` và chỉ lưu CON TRỎ, không sao chép. Mọi lý do + * khác trong lớp này là string literal nên sống suốt chương trình; riêng lý do này được dựng lúc + * chạy, nên phải sống ít nhất bằng object — dựng nó trong một biến cục bộ là trả về con trỏ tới + * bộ nhớ đã huỷ. + */ + std::string action_failure_reason_; + /** * State đã leo thang vào recovery — quyết định đường quay về khi behavior kết thúc (contract * 2026-08-04b): từ kControlling thì bám tiếp plan cũ, từ kPlanning (mất pose lúc lập plan) thì diff --git a/src/control_loop.cpp b/src/control_loop.cpp index 23f1efc..a5d248d 100644 --- a/src/control_loop.cpp +++ b/src/control_loop.cpp @@ -253,6 +253,7 @@ void ControlLoop::reset() controller_feedback_ = ControllerFeedback::kIdle; recovery_feedback_ = RecoveryFeedback::kIdle; action_feedback_ = ActionFeedback::kIdle; + action_message_.clear(); latest_plan_.clear(); planner_running_ = false; @@ -809,6 +810,7 @@ bool ControlLoop::step() input.controller = controller_feedback_; input.recovery = recovery_feedback_; input.action = action_feedback_; + input.action_message = action_message_; input.pose_available = pose_available; input.costmap_current = !costmap_stale; input.robot_stopped = arbiter_.stopped(); @@ -845,6 +847,7 @@ bool ControlLoop::step() controller_feedback_ = ControllerFeedback::kIdle; recovery_feedback_ = RecoveryFeedback::kIdle; action_feedback_ = ActionFeedback::kIdle; + action_message_.clear(); // --- 3. Thi hành output --------------------------------------------------------------------- // Nhãn của yêu cầu SẮP bị thay. Preempt bật cả `report_outcome` lẫn `accept_request` trong cùng @@ -1025,11 +1028,27 @@ bool ControlLoop::step() break; case ActionTick::Status::kSucceeded: action_feedback_ = ActionFeedback::kSucceeded; + // Log ở mức info: một action chạy xong là sự kiện hiếm, và câu này mang theo số mẫu / frame + // đã ghi — thứ cần đối chiếu khi lần sau nó hỏng. + if (!tick.message.empty()) + { + robot::log_info("[move_base2] %s\n", tick.message.c_str()); + } break; case ActionTick::Status::kFailed: action_feedback_ = ActionFeedback::kFailed; + // Handler đã dựng sẵn lý do cụ thể ("thiếu mẫu", "tản quá", "không publish được"). Trước + // đây chuỗi đó dừng ngay tại đây và ra ngoài chỉ còn "action failed" — ba lần chạy hiện + // trường liên tiếp không truy được nguyên nhân chính vì thế. + if (!tick.message.empty()) + { + robot::log_error("[move_base2] %s\n", tick.message.c_str()); + } break; } + // Giữ lại cho lần dựng StateMachineInput ngay sau đó; xoá khi status khác kFailed để lý do cũ + // không bám sang một action khác. + action_message_ = (tick.status == ActionTick::Status::kFailed) ? tick.message : std::string(); } // --- 3.5 Guard "không đi mù" ----------------------------------------------------------------- diff --git a/src/state_machine.cpp b/src/state_machine.cpp index 14fee95..948b21e 100644 --- a/src/state_machine.cpp +++ b/src/state_machine.cpp @@ -785,8 +785,15 @@ StateMachineOutput StateMachine::update(const StateMachineInput& in) // Action hỏng không có đường recovery: recovery behavior là công cụ phục hồi NAVIGATION // (dọn costmap, lùi, xoay), không giúp gì được một thiết bị đang hỏng. Kết thúc tường minh // để mission layer quyết định làm gì với phần còn lại của order. - finish(NavigationState::kAborted, NavigationOutcome::kFailed, in.now, "action failed", - out); + // + // Mang theo lý do của handler: nó đi tiếp ra host qua feedback, nên đây là chỗ duy nhất + // người vận hành thấy được action nào hỏng vì cái gì. + // Giữ trong member: `out.reason` chỉ lưu con trỏ (xem @ref action_failure_reason_). + action_failure_reason_ = in.action_message.empty() + ? std::string("action failed") + : "action failed: " + in.action_message; + finish(NavigationState::kAborted, NavigationOutcome::kFailed, in.now, + action_failure_reason_.c_str(), out); break; } diff --git a/test/state_machine_test.cpp b/test/state_machine_test.cpp index d639ca0..e008f8e 100644 --- a/test/state_machine_test.cpp +++ b/test/state_machine_test.cpp @@ -1282,6 +1282,48 @@ TEST(StateMachineActions, ActionFailureAbortsWithoutRecovery) EXPECT_TRUE(out.report_outcome); EXPECT_EQ(out.outcome, NavigationOutcome::kFailed); EXPECT_FALSE(out.start_recovery) << "recovery repairs navigation, it cannot rescue an action"; + EXPECT_STREQ(out.reason, "action failed") + << "handler im lặng thì vẫn phải có lý do chung, không được rỗng"; +} + +TEST(StateMachineActions, ActionFailureReasonCarriesTheHandlerMessage) +{ + // Handler dò frame phân biệt được "thiếu mẫu", "tản quá", "không publish được" và "frame không + // xuất hiện". Không mang chuỗi đó ra ngoài thì cả bốn hiện lên log y hệt nhau — đã mất ba lần + // chạy hiện trường liên tiếp vì không truy được nguyên nhân. + Driver driver; + ASSERT_EQ(driver.tick(requestWithActions(1, /*has_goal=*/false)).state, + NavigationState::kExecutingActions); + + StateMachineInput failed = actionFb(ActionFeedback::kFailed); + failed.action_message = "action 'detect': only 12 sample(s) of 'pallet_raw', need 20"; + + const StateMachineOutput out = driver.tick(failed); + ASSERT_EQ(out.state, NavigationState::kAborted); + EXPECT_STREQ(out.reason, + "action failed: action 'detect': only 12 sample(s) of 'pallet_raw', need 20"); +} + +TEST(StateMachineActions, ActionFailureReasonOutlivesTheInputThatCarriedIt) +{ + // `StateMachineOutput::reason` là `const char*` và chỉ lưu CON TRỎ. Lý do này được ghép lúc chạy + // chứ không phải string literal, nên nếu nó nằm trong biến cục bộ hay trong chính `in` thì con trỏ + // treo ngay khi lời gọi kết thúc — hỏng im lặng, sanitizer mới thấy. + Driver driver; + ASSERT_EQ(driver.tick(requestWithActions(1, /*has_goal=*/false)).state, + NavigationState::kExecutingActions); + + StateMachineOutput out; + { + StateMachineInput failed = actionFb(ActionFeedback::kFailed); + failed.action_message = "action 'detect': detection unstable (spread xy=0.041 m)"; + out = driver.tick(failed); + // `failed` bị huỷ ở đây, kéo theo buffer của action_message. + } + + ASSERT_EQ(out.state, NavigationState::kAborted); + EXPECT_STREQ(out.reason, + "action failed: action 'detect': detection unstable (spread xy=0.041 m)"); } TEST(StateMachineActions, CancelDuringActionCancelsPortAndEndsCancelled)