From c70b26262290c47bdca488b30994c341f541442f Mon Sep 17 00:00:00 2001 From: Bartosz Burda Date: Tue, 1 Dec 2026 14:41:08 +0100 Subject: [PATCH] fault_manager: run and drop captures by retention priority * feat(fault_manager): run and drop captures by retention priority * fix(fault_manager): one policy snapshot per capture queue decision * docs(fault_manager): the capture queue's FIFO fallback and the lock-free policy methods --- docs/config/fault-manager.rst | 24 +- docs/tutorials/snapshots.rst | 4 +- src/ros2_medkit_fault_manager/CMakeLists.txt | 5 + src/ros2_medkit_fault_manager/README.md | 6 +- .../design/index.rst | 29 +- .../capture_thread_pool.hpp | 70 ++++- .../core/fault_manager_core.hpp | 2 +- .../core/rosbag_retention.hpp | 12 +- .../src/capture_thread_pool.cpp | 158 +++++++++-- .../src/core/rosbag_retention.cpp | 23 ++ .../src/fault_manager_node.cpp | 34 +-- .../test_capture_queue_priority.test.py | 264 ++++++++++++++++++ .../test/test_capture_thread_pool.cpp | 181 ++++++++++++ 13 files changed, 744 insertions(+), 68 deletions(-) create mode 100644 src/ros2_medkit_fault_manager/test/integration/test_capture_queue_priority.test.py diff --git a/docs/config/fault-manager.rst b/docs/config/fault-manager.rst index ea86e11a9..3951fc3b5 100644 --- a/docs/config/fault-manager.rst +++ b/docs/config/fault-manager.rst @@ -542,7 +542,11 @@ Basic Snapshot Settings the range is clamped to the nearest end with a warning). * - ``snapshots.capture_queue_full_policy`` - ``reject_newest`` - - Policy when the queue is full: ``reject_newest`` or ``drop_oldest``. + - Which capture a full queue drops among the captures with the lowest priority, the new one + included: ``reject_newest`` the newest (the new capture when it ties), ``drop_oldest`` the + oldest. Each drop logs one WARN with the fault code and the priority. Without valid retention + rules every priority is ``0``, so ``reject_newest`` drops the new capture and ``drop_oldest`` + the oldest waiting one. See the capture queue under Rosbag Retention Rules. Rosbag Recording ~~~~~~~~~~~~~~~~ @@ -908,7 +912,7 @@ Fields: - Meaning * - ``priority`` - integer 0-1000, default ``0`` - - Rank of the fault's recordings. + - Rank of the fault's recordings and of its captures waiting in the capture queue. * - ``over_quota`` - ``keep`` (default) or ``drop`` - What happens to a new recording that cannot fit the storage quota. @@ -1085,6 +1089,22 @@ or unreadable file is a failed measurement. The fault manager logs one WARN at s line ends with ``source=test-capacity`` instead of ``source=filesystem``. It is not a parameter and cannot be set over the API. Never set it on a robot. +**The capture queue.** A capture waits in the queue (``snapshots.capture_queue_depth``) until a capture +worker is free. Its priority is the ``priority`` of its fault's rule, resolved with the fault's severity +as it is stored when a worker picks a capture and when a full queue drops one: a fault reported again, +while its capture waits, at a severity whose rule has a higher priority moves up (a priority need not +follow the severity). A free worker runs the waiting capture with the highest priority, the oldest first +among equal priorities. The order is strict and has no aging: a low-priority capture can wait as long as +captures of a higher priority keep arriving. A full queue drops the capture with the +lowest priority, the new one included; among equal lowest priorities ``capture_queue_full_policy`` +decides: ``reject_newest`` drops the newest (the new capture when it ties), ``drop_oldest`` the oldest. +When the waiting captures keep changing while their priorities are read (three reads in a row), that one +pick or drop uses arrival order and ``capture_queue_full_policy`` alone and logs a DEBUG line. +Each dropped capture logs one WARN, not throttled: ``Capture queue full (): dropped the +[pending ]capture of '' (priority )``. A fault that cannot be read counts as priority ``0``. +Without valid rules (none, or an invalid configuration) every priority is ``0``: the queue runs oldest +first and the policy alone decides the drop. + **The priority in the list.** ``~/list_rosbags`` and the gateway's ``GET .../bulk-data/rosbags`` show each recording's priority (``priorities``, ``x-medkit.priority``): the rank above, read when the list is served. It is ``0`` without rules and while the configuration is invalid. diff --git a/docs/tutorials/snapshots.rst b/docs/tutorials/snapshots.rst index 7d1b8ea4d..b5e341db0 100644 --- a/docs/tutorials/snapshots.rst +++ b/docs/tutorials/snapshots.rst @@ -157,7 +157,9 @@ Configure snapshot capture via fault manager parameters: - Max pending captures before the full-queue policy applies (>= 1). * - ``snapshots.capture_queue_full_policy`` - ``reject_newest`` - - Policy when the queue is full: ``reject_newest`` or ``drop_oldest``. + - Which capture a full queue drops among those with the lowest retention priority: + ``reject_newest`` (the newest) or ``drop_oldest`` (the oldest). Without retention rules + every priority is equal. Advanced Configuration ---------------------- diff --git a/src/ros2_medkit_fault_manager/CMakeLists.txt b/src/ros2_medkit_fault_manager/CMakeLists.txt index 2552c117b..c3f4011ff 100644 --- a/src/ros2_medkit_fault_manager/CMakeLists.txt +++ b/src/ros2_medkit_fault_manager/CMakeLists.txt @@ -320,6 +320,11 @@ endif() medkit_add_launch_test(test_rosbag_storage_availability test/integration/test_rosbag_storage_availability.test.py TIMEOUT 300 LABELS "integration") + # The capture queue by retention priority: the pick order, the full-queue drop and its WARN, without + # rules and with an invalid configuration. + medkit_add_launch_test(test_capture_queue_priority test/integration/test_capture_queue_priority.test.py + TIMEOUT 300 LABELS "integration") + if(POSTGRES_SUPPORT) medkit_add_launch_test(test_rosbag_quota_pg test/integration/test_rosbag_quota_pg.test.py TIMEOUT 300 LABELS "integration") diff --git a/src/ros2_medkit_fault_manager/README.md b/src/ros2_medkit_fault_manager/README.md index 44b18a9a4..69e53d057 100644 --- a/src/ros2_medkit_fault_manager/README.md +++ b/src/ros2_medkit_fault_manager/README.md @@ -81,7 +81,7 @@ Snapshots capture topic data when faults are confirmed for post-mortem debugging Each confirm also writes a **freeze-frame**: a single compact JSON object mapping every captured topic to its value at confirmation time, keyed by fault code. It differs from per-topic snapshots in two ways: snapshots are deleted when the fault is cleared, while the freeze-frame is retained across `clear_fault` (once the snapshots are gone, `~/get_fault` serves the retained frame so the confirmed-state record stays available after acknowledgement); and a re-confirm that captures nothing (e.g. source publishers down) never overwrites an existing non-empty frame. A fault code with no configured capture set gets no freeze-frame row; a configured capture that samples nothing on its first run records an empty `{}` frame. Freeze-frame storage is bounded by the number of distinct fault codes (one row per code, replaced in place) and rows are never evicted. -Under a fault storm, captures are bounded by a worker pool (`capture_pool_size`) draining a bounded queue (`capture_queue_depth`); excess captures are dropped per `capture_queue_full_policy` and logged (throttled). The pool is shared and is created when snapshots **or** rosbag is enabled, so these parameters bound both. `capture_pool_size` parallelizes freeze-frame snapshot capture only - rosbag stays single-writer regardless of pool size, and correlated faults confirming inside one post-roll window share a single recording. +Under a fault storm, captures are bounded by a worker pool (`capture_pool_size`) draining a bounded queue (`capture_queue_depth`). A free worker runs the waiting capture with the highest retention priority, oldest first among equals; a full queue drops the capture with the lowest priority, the new one included, and `capture_queue_full_policy` decides among equal priorities. Each drop logs one WARN with the fault code and the priority. Without valid retention rules every priority is 0: oldest first, and the policy alone decides the drop. The pool is shared and is created when snapshots **or** rosbag is enabled, so these parameters bound both. `capture_pool_size` parallelizes freeze-frame snapshot capture only - rosbag stays single-writer regardless of pool size, and correlated faults confirming inside one post-roll window share a single recording. That single-writer property also shapes what each fault of a burst gets. Nothing is buffered while a post-fault window is open (messages go straight into the open bag), and the flush that opened that bag already emptied the ring buffer, so a fault confirming right _after_ the window closes has no pre-fault history available. What a confirmation gets is decided by the buffer, so a fault arriving before any captured topic has published lands the same way. It gets a **post-fault-only bag**: its own recording holding just its `duration_after_sec` window, entered through the same post-roll state machine, so later faults of the burst attach to it normally. With `duration_after_sec: 0` there is no window to record into and such a fault gets no bag; if the bag cannot be written at all, no recording is opened and no metadata row is stored. The `duration_sec` on a stored bag is the span the recording was open rather than the configured windows, so a post-fault-only bag usually reports roughly `duration_after_sec` where a full one reports its buffered history too. It is a recording span, not a content span: a window during which nothing was published still reports the seconds it covered. It can also exceed `duration_sec + duration_after_sec`, because the ring buffer is pruned only when a message arrives - a topic that stops publishing keeps its last window buffered until the next confirmation flushes it, which is deliberate for a black box. See `docs/config/fault-manager.rst` for the full lifecycle. @@ -97,7 +97,7 @@ That single-writer property also shapes what each fault of a burst gets. Nothing | `snapshots.max_per_fault` | int | `10` | Max snapshots retained per fault. | | `snapshots.capture_pool_size` | int | `2` | Max concurrent capture threads under a fault storm (>= 1). Parallelizes snapshot capture only; rosbag stays single-writer. | | `snapshots.capture_queue_depth` | int | `16` | Max pending captures before the full-queue policy applies (>= 1). | -| `snapshots.capture_queue_full_policy` | string | `reject_newest` | Policy when the queue is full: `reject_newest` or `drop_oldest`. | +| `snapshots.capture_queue_full_policy` | string | `reject_newest` | Drop of a full queue among the lowest priorities: `reject_newest` (the newest) or `drop_oldest` (the oldest). | **Topic Resolution Priority:** @@ -174,6 +174,8 @@ periodic job with no priority limit. A new recording below the floor with nothin delete is not started. `over_quota: keep` does not keep a recording below the floor. The floor is a target, not a reservation: other writers can change the free space between two measurements. With PostgreSQL on the same disk it is also its headroom. +A capture waiting in the capture queue has its fault's priority, read with the fault's current severity when a +worker picks a capture and when a full queue drops one: the highest runs first, the lowest is dropped first. A new recording evicts only recordings of equal or lower priority, lowest priority first, then cleared before healed before active, then a recording `keep_first` protects after the others, then oldest. A recording that still does not fit follows `over_quota`: `keep` (default) stores it over the quota, `drop` drops it and diff --git a/src/ros2_medkit_fault_manager/design/index.rst b/src/ros2_medkit_fault_manager/design/index.rst index 5b52c5418..7ecd75e7b 100644 --- a/src/ros2_medkit_fault_manager/design/index.rst +++ b/src/ros2_medkit_fault_manager/design/index.rst @@ -65,7 +65,8 @@ The following diagram shows the relationships between the main components of the +shutdown() +dropped_captures() : uint64_t -workers_ : vector - -queue_ : deque + -queue_ : deque + -priority_of_ : PriorityFn } enum QueueFullPolicy { @@ -201,8 +202,21 @@ Main Components 5. **CaptureThreadPool** - Bounded worker pool for snapshot capture Under a fault storm the node enqueues capture jobs into a bounded ``CaptureThreadPool`` (``pool_size`` workers draining a ``queue_depth``-bounded queue) rather than spawning one - thread per fault. The full-queue policy (``reject_newest``/``drop_oldest``) bounds memory, - and the destructor joins the pool before rosbag teardown. + thread per fault. The bounded queue bounds memory, and the destructor joins the pool before + rosbag teardown. + + Each job's priority comes from ``RosbagRetention::capture_priorities``, read when a worker picks + a job and when a full queue chooses its victim: one call per decision with every code it + compares, so one decision uses one policy snapshot. A worker runs the highest priority, + FIFO among equals. A full queue drops the lowest, the incoming job included; the full-queue policy + (``reject_newest``/``drop_oldest``) picks the newest or the oldest among equal lowest priorities. + ``EnqueueOutcome`` names the dropped code and the priority the decision used; the node logs one + WARN per drop, not throttled. The reads run outside the queue mutex on a copy of the pending + jobs. Each job carries a unique sequence number, and a decision applies only when the pending + jobs are unchanged after the read; else the read repeats, and after ``kMaxPriorityReads`` (3) + that decision is FIFO with one DEBUG line. ``enqueue`` runs in the core's capture hook, so its + reads run under the core mutex, like the storage writes of a report; a worker's reads hold no + core lock. Without valid rules every priority is 0: FIFO and the policy alone. 6. **FaultManagerCore** - ROS-free report, clear, list, get and tick logic (``core/fault_manager_core.hpp``) @@ -564,7 +578,8 @@ It is the only write of the rosbag rows. The retention below makes every decisio Rosbag retention """""""""""""""" -``core::RosbagRetention`` holds every rosbag retention decision, each under one retention mutex: +``core::RosbagRetention`` holds every rosbag retention decision, each under one retention mutex +except ``capture_priorities``: - ``store``: drops the rows of codes whose delete generation moved since they joined the recording (see below) and of faults the storage holds as cleared with a deleting clear @@ -652,6 +667,12 @@ Rosbag retention - ``has_space_candidate(priority_limit)``: the same choice without the removal, for the open-time floor check. A failed read answers true and logs nothing. - ``fault_priority(fault_code)``: the priority of the fault's rule, 0 unless ``kConfigured``. +- ``capture_priorities(fault_codes)``: the priorities of captures in the capture queue, without the + retention mutex, so a capture pick does not wait behind a store, a floor pass or a sweep that + holds it during its storage calls. It loads the policy snapshot once with ``std::atomic_load``, + reads each fault with one ``get_fault`` and resolves its rule with the fault's severity. 0 unless + ``kConfigured``, for a fault that cannot be read and for one that does not exist. It logs nothing + and never throws. **Delete generation.** A recording closes on the executor and is stored later on the store worker, so a fault can heal or be cleared, and fail again, between the two. The status at the store then diff --git a/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/capture_thread_pool.hpp b/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/capture_thread_pool.hpp index 76e70c078..a1bc9b5b8 100644 --- a/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/capture_thread_pool.hpp +++ b/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/capture_thread_pool.hpp @@ -30,41 +30,61 @@ namespace ros2_medkit_fault_manager { -/// Policy applied when the bounded pending queue is full. +/// Victim of a full queue among the jobs that tie for the lowest priority. enum class QueueFullPolicy { - kRejectNewest, ///< Drop the incoming job. - kDropOldest ///< Evict the oldest pending job, queue the incoming one. + kRejectNewest, ///< The newest: the incoming job when it ties. + kDropOldest ///< The oldest. }; /// Result of an enqueue attempt. enum class EnqueueResult { kAccepted, ///< Queued; will run. - kDroppedNewest, ///< Queue full (reject_newest): incoming dropped. - kEvictedOldest, ///< Queue full (drop_oldest): oldest evicted, incoming queued. + kDroppedNewest, ///< Queue full: the incoming job was the one to drop. + kEvictedOldest, ///< Queue full: a pending job was dropped (evicted_code), the incoming one queued. kRejectedShuttingDown ///< Pool is shutting down: not queued, will not run. }; struct EnqueueOutcome { EnqueueResult result; std::optional evicted_code; ///< Set only for kEvictedOldest. + int64_t dropped_priority{0}; ///< kDroppedNewest, kEvictedOldest: priority the drop decided with. }; /// Bounded worker pool that runs fault-capture jobs off the service thread. /// /// Caps concurrent in-flight captures at pool_size and bounds pending work at -/// queue_depth with a configurable full-queue policy, giving peak memory and -/// thread count a hard upper bound under a fault storm. See issue #441. +/// queue_depth, giving peak memory and thread count a hard upper bound under a +/// fault storm. See issue #441. +/// +/// A worker runs the pending job with the highest priority, FIFO among equals. A full queue drops +/// the job with the lowest priority, the incoming one included; full_policy breaks a tie. +/// Priorities are read when a job is picked and when a victim is chosen, outside the queue mutex. +/// A decision applies only if the pending jobs did not change during the read, else it reads +/// again; after kMaxPriorityReads it is FIFO, logged at DEBUG. +/// +/// enqueue() runs in the core's capture hook, so its reads run under the core mutex. A worker's +/// reads run with no core lock. priority_of must never acquire the core mutex. class CaptureThreadPool { public: + /// Priorities of the captures of @p fault_codes, in order. Higher runs first and is dropped last. + /// One call per decision, with every code it compares: one policy generation per decision. + using PriorityFn = std::function(const std::vector & fault_codes)>; + + /// Reads of one decision before it falls back to FIFO. + static constexpr int kMaxPriorityReads = 3; + /// @param pool_size Number of worker threads (clamped to >= 1). /// @param queue_depth Max pending jobs (clamped to >= 1). - /// @param full_policy Behavior when the pending queue is full. + /// @param full_policy Victim among equal lowest priorities when the pending queue is full. /// @param log Sink for worker-side capture failures. Must outlive the pool. /// @param capture_fn Invoked per job on a worker thread. Must be thread-safe /// for pool_size concurrent calls. Exceptions are caught and logged. /// @param logger_name Logger name of the lines written to @p log. + /// @param priority_of Thread-safe. A throw or a result of another size counts as every priority 0. + /// Empty: every priority is 0 (FIFO). CaptureThreadPool(std::size_t pool_size, std::size_t queue_depth, QueueFullPolicy full_policy, core::LogSink & log, - std::function capture_fn, std::string logger_name = "fault_manager"); + std::function capture_fn, std::string logger_name = "fault_manager", + PriorityFn priority_of = {}); ~CaptureThreadPool(); CaptureThreadPool(const CaptureThreadPool &) = delete; @@ -72,14 +92,15 @@ class CaptureThreadPool { CaptureThreadPool(CaptureThreadPool &&) = delete; CaptureThreadPool & operator=(CaptureThreadPool &&) = delete; - /// Enqueue a capture job. Non-blocking. Thread-safe. + /// Enqueue a capture job. Thread-safe. On a full queue it calls priority_of, which in the node + /// reads the storage under the core mutex; it waits for that read. EnqueueOutcome enqueue(const std::string & fault_code); /// Stop accepting work, let in-flight jobs finish, discard pending, join all /// workers. Idempotent and noexcept. Called by the destructor. void shutdown() noexcept; - /// Lifetime total of storm drops (kDroppedNewest + kEvictedOldest). + /// Lifetime total of full-queue drops (kDroppedNewest + kEvictedOldest). uint64_t dropped_captures() const { return dropped_captures_.load(); } @@ -88,17 +109,42 @@ class CaptureThreadPool { std::size_t pending_size() const; private: + struct Job { + uint64_t seq; ///< Unique per enqueue: tells a job from a later one of the same code + std::string code; + }; + void worker_loop(); + /// Wait for a pending job and move the code of the one with the highest priority into @p code. + /// Expects @p lock held; holds it again on return. False once the pool stops. + bool take_next(std::unique_lock & lock, std::string & code); + + /// Drop the lowest of the full queue and @p fault_code. @p priorities are those of queue_, in + /// order. Expects queue_mutex_ held. + EnqueueOutcome drop_lowest(const std::string & fault_code, const std::vector & priorities, + int64_t incoming_priority); + + /// Whether queue_ still holds exactly @p seen. Expects queue_mutex_ held. + bool unchanged(const std::vector & seen) const; + + /// priority_of_ of the codes of @p jobs, then of @p incoming when given, in one call. Every + /// priority is 0 without a function, after a throw or for a result of another size. Called + /// without queue_mutex_. + std::vector priorities_of(const std::vector & jobs, const std::string * incoming) const; + const std::size_t queue_depth_; const QueueFullPolicy full_policy_; core::LogSink & log_; std::string logger_name_; std::function capture_fn_; + /// Never reset: an enqueue() can be reading priorities while shutdown() runs. + const PriorityFn priority_of_; mutable std::mutex queue_mutex_; std::condition_variable cv_; - std::deque queue_; + std::deque queue_; + uint64_t next_seq_{0}; bool stop_{false}; std::atomic dropped_captures_{0}; diff --git a/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/core/fault_manager_core.hpp b/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/core/fault_manager_core.hpp index afff61ec2..92f2c6a5c 100644 --- a/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/core/fault_manager_core.hpp +++ b/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/core/fault_manager_core.hpp @@ -55,7 +55,7 @@ enum class CaptureEnqueue { kNone, ///< No capture is configured; nothing was queued. kAccepted, ///< Queued. kDroppedNewest, ///< Queue full: the request was dropped. - kEvictedOldest, ///< Queue full: the oldest pending request was evicted and this one queued. + kEvictedOldest, ///< Queue full: a pending request (evicted_code) was evicted and this one queued. kShuttingDown ///< The capture pool is stopping; nothing was queued. }; diff --git a/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/core/rosbag_retention.hpp b/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/core/rosbag_retention.hpp index ba41e7175..52b47d47d 100644 --- a/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/core/rosbag_retention.hpp +++ b/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/core/rosbag_retention.hpp @@ -138,8 +138,10 @@ struct SweepOutcome { /// Every rosbag retention decision of the fault manager, on FaultStorage::apply_rosbag_changes(). /// -/// Each public method holds one mutex for its whole decision. Lock order: the caller's outer -/// locks -> this mutex -> the storage's own lock. Under it only storage calls and logging run: +/// Each public method holds one mutex for its whole decision, except set_policy(), which publishes +/// the policy snapshot with std::atomic_store, and capture_priorities(), which reads it: neither +/// takes the mutex. Lock order: the caller's outer locks -> this mutex -> the storage's own lock. +/// Under it only storage calls and logging run: /// no other lock and no file system call. Nothing here unlinks a file or logs a removal. Each /// method returns the directories the caller removes, with the reason it logs after each removal. class RosbagRetention { @@ -256,6 +258,12 @@ class RosbagRetention { /// @throws a storage failure int64_t fault_priority(const std::string & fault_code); + /// Priorities of captures of @p fault_codes in the capture queue, in order: the priority of the + /// rule of each fault as the storage holds it now, all from one policy snapshot. 0 unless + /// kConfigured, and for a fault that cannot be read or does not exist. Takes no mutex but the + /// storage's own and logs nothing. Empty only when the result cannot be allocated. + std::vector capture_priorities(const std::vector & fault_codes) noexcept; + private: struct Eviction { std::vector unlink_paths; diff --git a/src/ros2_medkit_fault_manager/src/capture_thread_pool.cpp b/src/ros2_medkit_fault_manager/src/capture_thread_pool.cpp index 8662855ce..2de611686 100644 --- a/src/ros2_medkit_fault_manager/src/capture_thread_pool.cpp +++ b/src/ros2_medkit_fault_manager/src/capture_thread_pool.cpp @@ -14,6 +14,8 @@ #include "ros2_medkit_fault_manager/capture_thread_pool.hpp" +#include +#include #include #include @@ -21,15 +23,15 @@ namespace ros2_medkit_fault_manager { CaptureThreadPool::CaptureThreadPool(std::size_t pool_size, std::size_t queue_depth, QueueFullPolicy full_policy, core::LogSink & log, std::function capture_fn, - std::string logger_name) + std::string logger_name, PriorityFn priority_of) : queue_depth_(queue_depth == 0 ? 1 : queue_depth) , full_policy_(full_policy) , log_(log) , logger_name_(std::move(logger_name)) - , capture_fn_(std::move(capture_fn)) { - // Defensive clamp: this is a public class. Callers (the node) validate to >= 1, - // but a stray 0 must not UB. With 0 workers nothing drains the queue; with - // queue_depth 0 + kDropOldest, enqueue() would call front() on an empty deque. + , capture_fn_(std::move(capture_fn)) + , priority_of_(std::move(priority_of)) { + // Defensive clamp: this is a public class. Callers (the node) validate to >= 1. + // With 0 workers nothing drains the queue; with queue_depth 0 nothing is queued. // queue_depth_ is clamped in the initializer above. const std::size_t worker_count = pool_size == 0 ? 1 : pool_size; workers_.reserve(worker_count); @@ -45,27 +47,96 @@ CaptureThreadPool::~CaptureThreadPool() { } EnqueueOutcome CaptureThreadPool::enqueue(const std::string & fault_code) { - std::lock_guard lock(queue_mutex_); - if (stop_) { - return {EnqueueResult::kRejectedShuttingDown, std::nullopt}; + std::unique_lock lock(queue_mutex_); + for (int read = 0;; ++read) { + if (stop_) { + return {EnqueueResult::kRejectedShuttingDown, std::nullopt}; + } + if (queue_.size() < queue_depth_) { + queue_.push_back({next_seq_++, fault_code}); + cv_.notify_one(); + return {EnqueueResult::kAccepted, std::nullopt}; + } + if (!priority_of_) { + return drop_lowest(fault_code, std::vector(queue_.size(), 0), 0); + } + if (read == kMaxPriorityReads) { + break; + } + const std::vector seen(queue_.begin(), queue_.end()); + lock.unlock(); + std::vector priorities = priorities_of(seen, &fault_code); + lock.lock(); + if (unchanged(seen)) { + const int64_t incoming_priority = priorities.back(); + priorities.pop_back(); + return drop_lowest(fault_code, priorities, incoming_priority); + } } - if (queue_.size() < queue_depth_) { - queue_.push_back(fault_code); - cv_.notify_one(); - return {EnqueueResult::kAccepted, std::nullopt}; + EnqueueOutcome outcome = drop_lowest(fault_code, std::vector(queue_.size(), 0), 0); + lock.unlock(); + core::logf(log_, core::LogLevel::kDebug, logger_name_, + "Capture queue changed during %d priority reads; full-queue drop for '%s' decided FIFO", kMaxPriorityReads, + fault_code.c_str()); + return outcome; +} + +EnqueueOutcome CaptureThreadPool::drop_lowest(const std::string & fault_code, const std::vector & priorities, + int64_t incoming_priority) { + int64_t lowest = incoming_priority; + for (const int64_t p : priorities) { + lowest = std::min(lowest, p); } - // Queue full. - if (full_policy_ == QueueFullPolicy::kRejectNewest) { - dropped_captures_.fetch_add(1, std::memory_order_relaxed); - return {EnqueueResult::kDroppedNewest, std::nullopt}; + // The candidates in age order are the pending jobs, then the incoming one. + std::optional victim; + if (full_policy_ == QueueFullPolicy::kDropOldest) { + const auto first = std::find(priorities.begin(), priorities.end(), lowest); + if (first != priorities.end()) { + victim = static_cast(first - priorities.begin()); + } + } else if (incoming_priority != lowest) { + const auto last = std::find(priorities.rbegin(), priorities.rend(), lowest); + victim = static_cast(priorities.rend() - last) - 1; } - // kDropOldest: evict the oldest pending job. - std::string evicted = std::move(queue_.front()); - queue_.pop_front(); - queue_.push_back(fault_code); dropped_captures_.fetch_add(1, std::memory_order_relaxed); + if (!victim) { + return {EnqueueResult::kDroppedNewest, std::nullopt, incoming_priority}; + } + const auto evicted_job = queue_.begin() + static_cast(*victim); + std::string evicted = std::move(evicted_job->code); + queue_.erase(evicted_job); + queue_.push_back({next_seq_++, fault_code}); cv_.notify_one(); - return {EnqueueResult::kEvictedOldest, std::move(evicted)}; + return {EnqueueResult::kEvictedOldest, std::move(evicted), lowest}; +} + +bool CaptureThreadPool::unchanged(const std::vector & seen) const { + return std::equal(queue_.begin(), queue_.end(), seen.begin(), seen.end(), [](const Job & now, const Job & then) { + return now.seq == then.seq; + }); +} + +std::vector CaptureThreadPool::priorities_of(const std::vector & jobs, + const std::string * incoming) const { + std::vector codes; + codes.reserve(jobs.size() + 1); + for (const auto & job : jobs) { + codes.push_back(job.code); + } + if (incoming != nullptr) { + codes.push_back(*incoming); + } + if (priority_of_) { + try { + std::vector read = priority_of_(codes); + if (read.size() == codes.size()) { + return read; + } + } catch (...) { + // A failed read counts as every priority 0. + } + } + return std::vector(codes.size(), 0); } void CaptureThreadPool::shutdown() noexcept { @@ -101,19 +172,50 @@ std::size_t CaptureThreadPool::pending_size() const { return queue_.size(); } +bool CaptureThreadPool::take_next(std::unique_lock & lock, std::string & code) { + for (int read = 0;; ++read) { + cv_.wait(lock, [this] { + return stop_ || !queue_.empty(); + }); + if (stop_) { + return false; // check stop BEFORE dispatch -> pending discarded, not drained + } + const bool choice = queue_.size() > 1 && static_cast(priority_of_); + if (choice && read < kMaxPriorityReads) { + const std::vector seen(queue_.begin(), queue_.end()); + lock.unlock(); + const std::vector priorities = priorities_of(seen, nullptr); + lock.lock(); + if (!unchanged(seen)) { + continue; + } + // max_element returns the first of equal maxima: FIFO among equal priorities. + const auto highest = std::max_element(priorities.begin(), priorities.end()); + const auto picked = queue_.begin() + (highest - priorities.begin()); + code = std::move(picked->code); + queue_.erase(picked); + return true; + } + code = std::move(queue_.front().code); + queue_.pop_front(); + if (choice) { + lock.unlock(); + core::logf(log_, core::LogLevel::kDebug, logger_name_, + "Capture queue changed during %d priority reads; picked '%s' FIFO", kMaxPriorityReads, code.c_str()); + lock.lock(); + } + return true; + } +} + void CaptureThreadPool::worker_loop() { for (;;) { std::string job; { std::unique_lock lock(queue_mutex_); - cv_.wait(lock, [this] { - return stop_ || !queue_.empty(); - }); - if (stop_) { - return; // check stop BEFORE dispatch -> pending discarded, not drained + if (!take_next(lock, job)) { + return; } - job = std::move(queue_.front()); - queue_.pop_front(); } // release lock BEFORE running the (multi-second) job try { if (capture_fn_) { diff --git a/src/ros2_medkit_fault_manager/src/core/rosbag_retention.cpp b/src/ros2_medkit_fault_manager/src/core/rosbag_retention.cpp index 869c0c687..b8e821bf0 100644 --- a/src/ros2_medkit_fault_manager/src/core/rosbag_retention.cpp +++ b/src/ros2_medkit_fault_manager/src/core/rosbag_retention.cpp @@ -1101,6 +1101,29 @@ int64_t RosbagRetention::fault_priority(const std::string & fault_code) { return fault_facts(*state, fault_code, cache).priority; } +std::vector RosbagRetention::capture_priorities(const std::vector & fault_codes) noexcept { + try { + std::vector priorities(fault_codes.size(), 0); + const auto state = std::atomic_load(&state_); + if (state->mode != RetentionMode::kConfigured || !state->policy) { + return priorities; + } + for (std::size_t i = 0; i < fault_codes.size(); ++i) { + try { + const std::optional fault = storage_.get_fault(fault_codes[i]); + if (fault) { + priorities[i] = state->policy->resolve(fault_codes[i], fault->severity).priority; + } + } catch (...) { + // A fault that cannot be read keeps priority 0. + } + } + return priorities; + } catch (...) { + return {}; + } +} + bool RosbagRetention::clear_deletes(const RetentionPolicyState & state, const std::string & fault_code, FactsCache & cache) { if (state.mode != RetentionMode::kConfigured) { diff --git a/src/ros2_medkit_fault_manager/src/fault_manager_node.cpp b/src/ros2_medkit_fault_manager/src/fault_manager_node.cpp index 84a6fe922..e233c7182 100644 --- a/src/ros2_medkit_fault_manager/src/fault_manager_node.cpp +++ b/src/ros2_medkit_fault_manager/src/fault_manager_node.cpp @@ -404,6 +404,7 @@ FaultManagerNode::FaultManagerNode(const rclcpp::NodeOptions & options) : Node(" // pool_size concurrent calls the pool contract allows. Serialize just the rosbag // leg under this mutex; snapshot capture is independent and stays parallel. auto rosbag_mutex = std::make_shared(); + auto retention = rosbag_retention_; capture_pool_ = std::make_unique( static_cast(capture_pool_size_), static_cast(capture_queue_depth_), capture_queue_full_policy_, log_sink_, @@ -416,7 +417,10 @@ FaultManagerNode::FaultManagerNode(const rclcpp::NodeOptions & options) : Node(" bag->on_fault_confirmed(fault_code); } }, - config_.logger_name); + config_.logger_name, + [retention](const std::vector & fault_codes) { + return retention->capture_priorities(fault_codes); + }); } // Created cancelled: it runs only while an own-fault action is pending. @@ -518,27 +522,25 @@ core::CaptureResult FaultManagerNode::enqueue_capture(const std::string & fault_ return {}; } const EnqueueOutcome outcome = capture_pool_->enqueue(fault_code); - // RCLCPP_WARN_THROTTLE needs a non-const Clock lvalue (Humble/Lyrical compat); mirror - // rosbag_capture.cpp's local-copy pattern. The counter is cast to unsigned long long for %llu - // to avoid -Wuseless-cast (uint64_t == unsigned long on LP64). - rclcpp::Clock throttle_clock(*get_clock()); + // Every drop is a lost recording: one WARN each, not throttled. + const char * policy = capture_queue_full_policy_ == QueueFullPolicy::kRejectNewest ? "reject_newest" : "drop_oldest"; switch (outcome.result) { case EnqueueResult::kAccepted: return {core::CaptureEnqueue::kAccepted, {}}; case EnqueueResult::kEvictedOldest: - RCLCPP_WARN_THROTTLE(get_logger(), throttle_clock, 2000, - "Capture queue full (drop_oldest): evicted pending '%s' for '%s' " - "(pool=%d, queue=%d, total_dropped=%llu)", - outcome.evicted_code ? outcome.evicted_code->c_str() : "?", fault_code.c_str(), - capture_pool_size_, capture_queue_depth_, - static_cast(capture_pool_->dropped_captures())); + RCLCPP_WARN(get_logger(), + "Capture queue full (%s): dropped the pending capture of '%s' (priority %lld) for '%s' " + "(pool=%d, queue=%d, total_dropped=%llu)", + policy, outcome.evicted_code ? outcome.evicted_code->c_str() : "?", + static_cast(outcome.dropped_priority), fault_code.c_str(), capture_pool_size_, + capture_queue_depth_, static_cast(capture_pool_->dropped_captures())); return {core::CaptureEnqueue::kEvictedOldest, outcome.evicted_code.value_or(std::string{})}; case EnqueueResult::kDroppedNewest: - RCLCPP_WARN_THROTTLE(get_logger(), throttle_clock, 2000, - "Capture queue full (reject_newest): dropped capture for '%s' " - "(pool=%d, queue=%d, total_dropped=%llu)", - fault_code.c_str(), capture_pool_size_, capture_queue_depth_, - static_cast(capture_pool_->dropped_captures())); + RCLCPP_WARN(get_logger(), + "Capture queue full (%s): dropped the capture of '%s' (priority %lld) " + "(pool=%d, queue=%d, total_dropped=%llu)", + policy, fault_code.c_str(), static_cast(outcome.dropped_priority), capture_pool_size_, + capture_queue_depth_, static_cast(capture_pool_->dropped_captures())); return {core::CaptureEnqueue::kDroppedNewest, {}}; case EnqueueResult::kRejectedShuttingDown: RCLCPP_DEBUG(get_logger(), "Capture pool shutting down; skipped capture for '%s'", fault_code.c_str()); diff --git a/src/ros2_medkit_fault_manager/test/integration/test_capture_queue_priority.test.py b/src/ros2_medkit_fault_manager/test/integration/test_capture_queue_priority.test.py new file mode 100644 index 000000000..48ecf31cd --- /dev/null +++ b/src/ros2_medkit_fault_manager/test/integration/test_capture_queue_priority.test.py @@ -0,0 +1,264 @@ +#!/usr/bin/env python3 +# Copyright 2026 bburda +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +The capture queue by retention priority, against a real fault_manager_node on a SQLite file. + +One capture worker and two queue slots. A blocker capture holds the worker: its snapshot waits for +a message on a topic the test publishes. The test queues captures behind it, releases it, and reads +the capture order and the drops from the log lines. +""" + +import os +import pathlib +import re +import sys + +from launch import LaunchDescription +import launch_testing +import launch_testing.actions +import launch_testing.util +from rclpy.qos import HistoryPolicy, QoSProfile, ReliabilityPolicy + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) + +from rosbag_fm_harness import ( # noqa: E402 + EVENT_TIMEOUT_SEC, poll, RetentionCase, rules, SEVERITY_CRITICAL, SEVERITY_ERROR, + SEVERITY_INFO, SEVERITY_WARN, +) +from std_msgs.msg import UInt8MultiArray # noqa: E402 +import yaml # noqa: E402 + +# Only the blocker's snapshot samples this topic; the other captures have no snapshot topic. +GATE_TOPIC = '/pin/gate' +BLOCKER = 'BLOCKER' +# Reported once the first queued capture runs. It has the lowest priority, so it runs last. +SENTINEL = 'SENTINEL' +# The rosbag leg of every capture logs this line when it starts. +CAPTURE = "RosbagCapture: fault '{}' confirmed, flushing buffer to bag" +CAPTURE_RE = re.compile(CAPTURE.format(r'(\w+)')) +QUEUED_CAPTURE = CAPTURE.format(rf'(?!{BLOCKER}\b)\w+') +DROP_RE = re.compile(r'\[WARN\].*Capture queue full \((?:reject_newest|drop_oldest)\): ' + r"dropped the (?:pending )?capture of '(\w+)' \(priority (-?\d+)\)") +POLICIES = ('reject_newest', 'drop_oldest') +SEVERITY_PRIORITIES = { + 'severity.CRITICAL.priority': 900, 'severity.ERROR.priority': 600, + 'severity.WARN.priority': 300, 'severity.INFO.priority': 5, + f'fault_codes.{SENTINEL}.priority': 0, +} + + +def generate_test_description(): + return LaunchDescription([launch_testing.util.KeepAliveProc(), + launch_testing.actions.ReadyToTest()]), {} + + +class TestCaptureQueuePriority(RetentionCase): + + def setUp(self): + super().setUp() + qos = QoSProfile(reliability=ReliabilityPolicy.RELIABLE, history=HistoryPolicy.KEEP_LAST, + depth=10) + self.gate = self.client.node.create_publisher(UInt8MultiArray, GATE_TOPIC, qos) + self.addCleanup(self.client.node.destroy_publisher, self.gate) + + def write_yaml(self, name, tree): + path = os.path.join(os.path.dirname(self.db), name) + with open(path, 'w') as handle: + yaml.safe_dump(tree, handle) + return path + + def queue_run(self, policy, retention=None, params_file=None): + """Start a fault manager with one capture worker and two queue slots.""" + snapshots = self.write_yaml('snapshots.yaml', {'fault_specific': {BLOCKER: [GATE_TOPIC]}}) + return self.fm_run(params_file=params_file, **{ + 'snapshots.capture_pool_size': 1, + 'snapshots.capture_queue_depth': 2, + 'snapshots.capture_queue_full_policy': policy, + 'snapshots.background_capture': False, + 'snapshots.entity_default': False, + 'snapshots.timeout_sec': EVENT_TIMEOUT_SEC, + 'snapshots.config_file': snapshots, + **(retention or {})}) + + def hold_worker(self, fm): + """Start the blocker capture; return the log index once it waits on the gate topic.""" + self.assertTrue(poll(lambda: self.gate.get_subscription_count() == 0), + 'a subscriber stayed on ' + GATE_TOPIC) + mark = fm.mark() + self.assertTrue(self.client.report(BLOCKER).accepted) + self.assertIsNotNone( + fm.wait_line(f"Capturing snapshots for fault '{BLOCKER}'", since=mark), + fm.output()[-3000:]) + self.assertTrue(poll(lambda: self.gate.get_subscription_count() > 0), + 'the blocker capture never subscribed to ' + GATE_TOPIC) + return mark + + def report(self, code, severity): + self.assertTrue(self.client.report(code, severity).accepted) + + def assert_released_order(self, fm, mark, expected): + """Release the blocker; check that the queued captures run as `expected`, then nothing.""" + self.gate.publish(UInt8MultiArray(data=[1])) + self.assertIsNotNone(fm.wait_line(QUEUED_CAPTURE, since=mark), fm.output()[-3000:]) + # A slot is free now. A dropped capture still queued would run before the sentinel. + self.report(SENTINEL, SEVERITY_INFO) + self.assertIsNotNone(fm.wait_line(re.escape(CAPTURE.format(SENTINEL)), since=mark), + fm.output()[-3000:]) + order = [match.group(1) for match in map(CAPTURE_RE.search, + fm.lines_between(mark, fm.mark())) if match] + self.assertEqual(order, [BLOCKER, *expected, SENTINEL], fm.output()[-3000:]) + + def assert_drops(self, fm, mark, expected): + """ + Check one WARN per dropped capture: `expected` lists (code, priority) in order. + + Call after assert_released_order(): a drop is logged before its report returns, so before + the sentinel's capture. + """ + drops = [(match.group(1), int(match.group(2))) + for match in map(DROP_RE.search, fm.lines_between(mark, fm.mark())) if match] + self.assertEqual(drops, list(expected), fm.output()[-3000:]) + + def test_escalation_moves_a_waiting_capture_up(self): + """A WARN capture queued behind an ERROR one runs first once its fault is CRITICAL.""" + with self.queue_run('reject_newest', rules(SEVERITY_PRIORITIES)) as fm: + self.assert_rules_valid(fm) + mark = self.hold_worker(fm) + self.report('B', SEVERITY_ERROR) + self.report('A', SEVERITY_WARN) + self.report('A', SEVERITY_CRITICAL) + self.assertEqual(self.client.get_fault('A').fault.severity, SEVERITY_CRITICAL) + self.assert_released_order(fm, mark, ['A', 'B']) + self.assert_drops(fm, mark, []) + + def test_full_queue_drops_the_lowest(self): + """WARN A and INFO C wait, ERROR B arrives: C is dropped under either policy.""" + for policy in POLICIES: + with self.subTest(policy): + self.new_scratch() + with self.queue_run(policy, rules(SEVERITY_PRIORITIES)) as fm: + self.assert_rules_valid(fm) + mark = self.hold_worker(fm) + self.report('A', SEVERITY_WARN) + self.report('C', SEVERITY_INFO) + self.report('B', SEVERITY_ERROR) + self.assert_released_order(fm, mark, ['B', 'A']) + self.assert_drops(fm, mark, [('C', 5)]) + + def test_the_incoming_one_is_the_lowest(self): + """WARN A and ERROR B wait, INFO C arrives: C is dropped under either policy.""" + for policy in POLICIES: + with self.subTest(policy): + self.new_scratch() + with self.queue_run(policy, rules(SEVERITY_PRIORITIES)) as fm: + self.assert_rules_valid(fm) + mark = self.hold_worker(fm) + self.report('A', SEVERITY_WARN) + self.report('B', SEVERITY_ERROR) + self.report('C', SEVERITY_INFO) + self.assert_released_order(fm, mark, ['B', 'A']) + self.assert_drops(fm, mark, [('C', 5)]) + + def test_ties_follow_the_policy(self): + """Three WARN captures and a full queue: the policy picks among the equal priorities.""" + for policy, dropped, kept in (('reject_newest', 'W3', ['W1', 'W2']), + ('drop_oldest', 'W1', ['W2', 'W3'])): + with self.subTest(policy): + self.new_scratch() + with self.queue_run(policy, rules(SEVERITY_PRIORITIES)) as fm: + self.assert_rules_valid(fm) + mark = self.hold_worker(fm) + for code in ('W1', 'W2', 'W3'): + self.report(code, SEVERITY_WARN) + self.assert_released_order(fm, mark, kept) + self.assert_drops(fm, mark, [(dropped, 300)]) + + def check_fifo(self, fm, policy): + """INFO A and CRITICAL B wait, ERROR C arrives: FIFO and `policy`, every priority 0.""" + mark = self.hold_worker(fm) + self.report('A', SEVERITY_INFO) + self.report('B', SEVERITY_CRITICAL) + self.report('C', SEVERITY_ERROR) + dropped, kept = ('A', ['B', 'C']) if policy == 'drop_oldest' else ('C', ['A', 'B']) + self.assert_released_order(fm, mark, kept) + self.assert_drops(fm, mark, [(dropped, 0)]) + + def test_without_rules(self): + """No retention parameter: the queue is FIFO with today's full-queue policy.""" + for policy in POLICIES: + with self.subTest(policy): + self.new_scratch() + with self.queue_run(policy) as fm: + self.assertNotIn('Rosbag retention rules: ', fm.output()) + self.assertNotIn('Invalid rosbag retention configuration', fm.output()) + self.check_fifo(fm, policy) + + def test_invalid_configuration(self): + """Severity priorities beside an invalid value: FIFO with today's full-queue policy.""" + retention = {'severity': {'CRITICAL': {'priority': 900}, 'ERROR': {'priority': 600}, + 'WARN': {'priority': 300}, 'INFO': {'priority': 5}}, + 'defaults': {'on_healed': 'remove'}} + for policy in POLICIES: + with self.subTest(policy): + self.new_scratch() + params = self.write_yaml('retention.yaml', {'fault_manager': {'ros__parameters': { + 'snapshots': {'rosbag': {'retention': retention}}}}}) + with self.queue_run(policy, params_file=params) as fm: + self.assertIsNotNone(fm.wait_line(r'Invalid rosbag retention configuration'), + fm.output()[-3000:]) + self.check_fifo(fm, policy) + + def test_back_to_back_drops_are_each_logged(self): + """Drops one right after the other: one WARN per dropped capture, with its priority.""" + with self.subTest('the incoming capture is dropped'): + with self.queue_run('reject_newest', rules(SEVERITY_PRIORITIES)) as fm: + self.assert_rules_valid(fm) + mark = self.hold_worker(fm) + self.report('A', SEVERITY_WARN) + self.report('B', SEVERITY_WARN) + for code in ('C1', 'C2', 'C3'): + self.report(code, SEVERITY_INFO) + expected = [('C1', 5), ('C2', 5), ('C3', 5)] + self.assert_released_order(fm, mark, ['A', 'B']) + self.assert_drops(fm, mark, expected) + + with self.subTest('a pending capture is dropped'): + self.new_scratch() + with self.queue_run('drop_oldest', rules(SEVERITY_PRIORITIES)) as fm: + self.assert_rules_valid(fm) + mark = self.hold_worker(fm) + self.report('L1', SEVERITY_INFO) + self.report('L2', SEVERITY_INFO) + self.report('H1', SEVERITY_ERROR) + self.report('H2', SEVERITY_ERROR) + expected = [('L1', 5), ('L2', 5)] + self.assert_released_order(fm, mark, ['H1', 'H2']) + self.assert_drops(fm, mark, expected) + + def test_escalation_at_victim_time(self): + """INFO A escalated to CRITICAL while it waits: a full queue drops WARN B instead.""" + for policy in POLICIES: + with self.subTest(policy): + self.new_scratch() + with self.queue_run(policy, rules(SEVERITY_PRIORITIES)) as fm: + self.assert_rules_valid(fm) + mark = self.hold_worker(fm) + self.report('A', SEVERITY_INFO) + self.report('B', SEVERITY_WARN) + self.report('A', SEVERITY_CRITICAL) + self.report('C', SEVERITY_ERROR) + self.assert_released_order(fm, mark, ['A', 'C']) + self.assert_drops(fm, mark, [('B', 300)]) diff --git a/src/ros2_medkit_fault_manager/test/test_capture_thread_pool.cpp b/src/ros2_medkit_fault_manager/test/test_capture_thread_pool.cpp index defba8395..83715865c 100644 --- a/src/ros2_medkit_fault_manager/test/test_capture_thread_pool.cpp +++ b/src/ros2_medkit_fault_manager/test/test_capture_thread_pool.cpp @@ -16,9 +16,13 @@ #include #include +#include #include #include +#include #include +#include +#include #include #include #include @@ -32,6 +36,7 @@ #include "ros2_medkit_fault_manager/ros2/ros_log_sink.hpp" using ros2_medkit_fault_manager::CaptureThreadPool; +using ros2_medkit_fault_manager::EnqueueOutcome; using ros2_medkit_fault_manager::EnqueueResult; using ros2_medkit_fault_manager::QueueFullPolicy; @@ -350,3 +355,179 @@ TEST_F(CaptureThreadPoolTest, ReleasesCaptureFnAfterShutdown) { EXPECT_TRUE(weak.expired()); // capture_fn released after join -> ref dropped } } + +// The lock is not observable from outside the process. A priority read that blocks holds no queue +// mutex: pending_size() from another thread returns, for the full-queue read and for the pick. +TEST(CaptureThreadPool, PriorityReadsRunOutsideTheQueueMutex) { + constexpr auto kDeadline = std::chrono::seconds(30); + std::mutex m; + std::condition_variable cv; + bool armed = false; + bool entered = false; + bool released = false; + auto priority_of = [&](const std::vector & codes) { + std::unique_lock lock(m); + if (armed) { + armed = false; + entered = true; + cv.notify_all(); + cv.wait(lock, [&] { + return released; + }); + } + return std::vector(codes.size(), 0); + }; + const auto arm = [&] { + std::lock_guard lock(m); + armed = true; + entered = false; + released = false; + }; + const auto wait_entered = [&] { + std::unique_lock lock(m); + return cv.wait_for(lock, kDeadline, [&] { + return entered; + }); + }; + const auto release = [&] { + { + std::lock_guard lock(m); + released = true; + } + cv.notify_all(); + }; + + GatedCallback gc; + CaptureThreadPool pool(1, 2, QueueFullPolicy::kRejectNewest, test_logger(), gc.fn(), "test", priority_of); + pool.enqueue("blk"); + gc.wait_until_active(1); + EXPECT_EQ(pool.enqueue("p1").result, EnqueueResult::kAccepted); + EXPECT_EQ(pool.enqueue("p2").result, EnqueueResult::kAccepted); + + // The full-queue read of enqueue(). + arm(); + EnqueueOutcome outcome{EnqueueResult::kAccepted, std::nullopt}; + std::thread producer([&] { + outcome = pool.enqueue("p3"); + }); + const bool read_at_enqueue = wait_entered(); + auto pending = std::async(std::launch::async, [&] { + return pool.pending_size(); + }); + const bool returned = pending.wait_for(kDeadline) == std::future_status::ready; + release(); + producer.join(); + ASSERT_TRUE(read_at_enqueue) << "enqueue() on a full queue read no priority"; + EXPECT_TRUE(returned) << "pending_size() waited for the priority read of enqueue()"; + EXPECT_EQ(pending.get(), 2u); + EXPECT_EQ(outcome.result, EnqueueResult::kDroppedNewest); + + // The read of the pick, on the worker. + arm(); + gc.release(); + ASSERT_TRUE(wait_entered()); + pending = std::async(std::launch::async, [&] { + return pool.pending_size(); + }); + const bool returned_at_pick = pending.wait_for(kDeadline) == std::future_status::ready; + release(); + EXPECT_TRUE(returned_at_pick) << "pending_size() waited for the priority read of the pick"; + EXPECT_EQ(pending.get(), 2u); + gc.wait_until_started(3); + pool.shutdown(); + const std::vector expected{"blk", "p1", "p2"}; + EXPECT_EQ(gc.started(), expected); +} + +// One drop decision and one pick decision: each reads every code it compares in one call, so one +// decision never mixes two policy generations. +TEST(CaptureThreadPool, OneDecisionReadsPrioritiesInOneCall) { + std::mutex m; + std::vector> calls; + auto priority_of = [&](const std::vector & codes) { + std::lock_guard lock(m); + calls.push_back(codes); + return std::vector(codes.size(), 0); + }; + GatedCallback gc; + CaptureThreadPool pool(1, 2, QueueFullPolicy::kRejectNewest, test_logger(), gc.fn(), "test", priority_of); + pool.enqueue("blk"); + gc.wait_until_active(1); + EXPECT_EQ(pool.enqueue("p1").result, EnqueueResult::kAccepted); + EXPECT_EQ(pool.enqueue("p2").result, EnqueueResult::kAccepted); + EXPECT_EQ(pool.enqueue("p3").result, EnqueueResult::kDroppedNewest); + gc.release(); + gc.wait_until_started(3); + pool.shutdown(); + const std::vector> expected{{"p1", "p2", "p3"}, {"p1", "p2"}}; + std::lock_guard lock(m); + EXPECT_EQ(calls, expected); +} + +// Two workers read the priorities of the same pending jobs at once and take the mutex back one +// after the other. The second sees that the first took a job and reads again: every job runs once. +TEST(CaptureThreadPool, ATakenJobIsNeitherRunTwiceNorLost) { + constexpr auto kDeadline = std::chrono::seconds(30); + std::mutex m; + std::condition_variable cv; + bool armed = false; + bool released = false; + std::vector> held; + // The last pending job has the highest priority, so a stale pick points past the shrunk queue. + auto priority_of = [&](const std::vector & codes) { + std::unique_lock lock(m); + if (armed) { + held.push_back(codes); + cv.notify_all(); + cv.wait(lock, [&] { + return released; + }); + } + std::vector priorities; + priorities.reserve(codes.size()); + for (const auto & code : codes) { + priorities.push_back(code == "c" ? 5 : 1); + } + return priorities; + }; + GatedCallback gc; + CaptureThreadPool pool(2, 8, QueueFullPolicy::kRejectNewest, test_logger(), gc.fn(), "test", priority_of); + pool.enqueue("blk0"); + pool.enqueue("blk1"); + gc.wait_until_active(2); + for (const char * code : {"a", "b", "c"}) { + EXPECT_EQ(pool.enqueue(code).result, EnqueueResult::kAccepted); + } + { + std::lock_guard lock(m); + armed = true; + } + gc.release(); + bool both_held = false; + { + std::unique_lock lock(m); + both_held = cv.wait_for(lock, kDeadline, [&] { + return held.size() == 2; + }); + armed = false; + released = true; + } + cv.notify_all(); + ASSERT_TRUE(both_held) << "the two workers were not inside the priority read together"; + const std::vector pending{"a", "b", "c"}; + EXPECT_EQ(held[0], pending); + EXPECT_EQ(held[1], pending); + + const auto deadline = std::chrono::steady_clock::now() + kDeadline; + while (gc.started().size() < 5 && std::chrono::steady_clock::now() < deadline) { + std::this_thread::yield(); + } + pool.shutdown(); + std::map runs; + for (const auto & code : gc.started()) { + ++runs[code]; + } + const std::map expected{{"a", 1}, {"b", 1}, {"blk0", 1}, {"blk1", 1}, {"c", 1}}; + EXPECT_EQ(runs, expected); + EXPECT_EQ(pool.dropped_captures(), 0u); +}