From 77fd4efcd9bd7b5fd92e0f6f56352e569ca0128e Mon Sep 17 00:00:00 2001 From: Bartosz Burda Date: Tue, 1 Dec 2026 14:41:03 +0100 Subject: [PATCH] fault_manager: evict rosbag recordings by retention priority * feat(fault_manager): evict rosbag recordings by priority, honour over_quota, check the quota before a recording starts * docs(fault_manager): describe priority eviction, over_quota and the open-time quota check * fix(fault_manager): count closed recordings that are not stored yet in the open-time quota check * docs(fault_manager): an invalid retention configuration is a hard stop for the quota, pending recordings count in the check * fix(fault_manager): count a pending recording once in the open-time quota check * docs(fault_manager): the pending term of the open-time check is a payload estimate * test(fault_manager): pin the restore order, end the drop test's window by SIGTERM, make the failed open independent of the window --- docs/config/fault-manager.rst | 39 +- src/ros2_medkit_fault_manager/README.md | 13 +- .../config/rosbag_retention.example.yaml | 8 +- .../design/index.rst | 45 +- .../core/rosbag_retention.hpp | 76 +++ .../rosbag_capture.hpp | 20 + .../src/core/rosbag_retention.cpp | 469 +++++++++++++- .../src/fault_manager_node.cpp | 4 + .../src/rosbag_capture.cpp | 73 +++ .../test/integration/rosbag_fm_harness.py | 81 ++- .../integration/test_rosbag_quota.test.py | 607 +++++++++++++++++- .../integration/test_rosbag_quota_pg.test.py | 3 + .../test/test_rosbag_retention.cpp | 207 ++++++ .../test_rosbag_retention_priority.test.py | 214 ++++++ 14 files changed, 1823 insertions(+), 36 deletions(-) create mode 100644 src/ros2_medkit_integration_tests/test/features/test_rosbag_retention_priority.test.py diff --git a/docs/config/fault-manager.rst b/docs/config/fault-manager.rst index 26d78561b..70119d4de 100644 --- a/docs/config/fault-manager.rst +++ b/docs/config/fault-manager.rst @@ -840,8 +840,39 @@ Fields: - ``keep`` (default) or ``drop`` - What happens to a new recording that cannot fit the storage quota. -These two fields are parsed and checked in this release. The rules do not change which recordings -are removed yet. +**What the rules do.** A new recording evicts only recordings whose priority is less than or equal to +its own, and evicts them in this order: lowest ``priority`` first, then the recordings whose faults are +all cleared, then healed, then active (any fault PREFAILED, PREPASSED or CONFIRMED), then the oldest. A +recording shared by several faults (a burst) ranks by its highest-priority fault, with each fault's +severity as it is stored now, so a fault that was reported again at a higher severity moves its +recordings up. The ranking reads the links as they are after the new recording and the per-fault cap +are applied. The quota is enforced when a new recording is stored: if the per-fault cap removes every +new row (possible only when the new recording is older than the stored ones, after a backward clock +step), nothing is evicted in that store. + +A new recording that does not fit after every allowed eviction follows ``over_quota`` of its +highest-priority fault (``keep`` when faults of equal priority disagree). ``keep`` stores it over the +quota and logs a warning; ``keep`` also deletes the recordings it was allowed to evict. ``drop`` drops +the new recording alone and deletes nothing. The log line of a drop names the path, the size, the +quota and the reason. + +**Open-time check.** When a fault whose rule says ``over_quota: drop`` confirms, and the recording +is predicted not to fit, the recording is not started. The prediction is the stored bytes, less what the +per-fault cap frees for that fault and what the fault's priority allows to evict, plus the bytes of +recordings that are closed but not stored yet, plus the buffered bytes times +``1 + duration_after_sec / duration_sec``. The term for recordings not stored yet is an estimate of their payload (container and metadata overhead +are not included), counted only while no stored row names them; the store still decides with the +measured size. A refused fault logs one INFO line and leaves +the ring buffer in place for the next fault. The prediction is an estimate: a recording that grows past +it in its post-fault window is dropped when it is stored. + +**Invalid configuration.** While the retention configuration is invalid, the quota is a hard stop for +new recordings: a recording that does not fit after the per-fault cap is dropped, and nothing is +evicted for the quota. The open-time check runs for every fault. The per-fault cap and the removal of +a cleared fault's recording (``auto_cleanup``) work as without rules. + +A failed attempt to open a recording keeps the ring buffer, so the next fault within ``duration_sec`` +still gets its history. **Resolution.** Each field of a fault's rule comes from the first level that sets it: its ``fault_codes.`` entry, then the first label of ``pattern_order`` whose ``match`` covers the @@ -881,8 +912,8 @@ empty list (``pattern_order: []``, leave the key out) fails while the node is bu logs "Fault manager did not start" and exits with code 1. An empty key segment (``fault_codes..priority`` through ``-p``, or an empty YAML key) aborts inside ROS initialisation, before the fault manager runs. -Any other error does not stop the fault manager. It keeps running, records as before, does not use -the rules and reports the fault ``ROSBAG_RETENTION_CONFIG_INVALID`` (severity ``CRITICAL``, source the +Any other error does not stop the fault manager. It keeps running, does not use the rules (the quota +is then a hard stop for new recordings, see above) and reports the fault ``ROSBAG_RETENTION_CONFIG_INVALID`` (severity ``CRITICAL``, source the fault manager node, description the errors). That fault starts no capture. Clearing it does not fix the configuration: the next fault that confirms reports it again. A start with a valid configuration (or none) clears it. If the fault storage is unreachable at start, the report or the clear is retried diff --git a/src/ros2_medkit_fault_manager/README.md b/src/ros2_medkit_fault_manager/README.md index 6cdee3b2a..ba018bb92 100644 --- a/src/ros2_medkit_fault_manager/README.md +++ b/src/ros2_medkit_fault_manager/README.md @@ -135,9 +135,14 @@ parameter list and recording lifecycle. `snapshots.rosbag.retention.*` sets a `priority` (0-1000) and an `over_quota` choice (`keep` or `drop`) per fault, from four levels: fault code, the first matching pattern of `pattern_order`, severity, defaults. -They are read at startup and validated; this release does not yet use them to choose which recordings go. +They are read at startup and validated. A new recording evicts only recordings of equal or lower priority, +lowest priority first, then cleared before healed before active, then oldest. A recording that still does not +fit follows `over_quota`: `keep` (default) stores it over the quota, `drop` drops it and deletes nothing. +A recording that is predicted not to fit is not started when its fault says `drop` (the ring buffer stays for +the next fault). With an invalid configuration the quota is a hard stop for new recordings and nothing is +evicted for it. Without any retention parameter the quota evicts the oldest recordings first. A parameter the ROS YAML loader moved (found by reading each parameters file a second time) or that has too many key segments stops the node with exit code 1. Any other error keeps the node -recording as before and reports the fault `ROSBAG_RETENTION_CONFIG_INVALID`. See +running without the rules, with the quota as a hard stop for new recordings, and reports the fault `ROSBAG_RETENTION_CONFIG_INVALID`. See `config/rosbag_retention.example.yaml` and `docs/config/fault-manager.rst`. ### Storage Backends @@ -583,8 +588,8 @@ and some of them build an `rclcpp::Clock`. `core::reclassify_stale_healed()` is the startup pass for stale HEALED rows; - `core::FaultManagerCore`: `report`, `clear`, `list`, `get`, `list_for_entity`, `record_transition` and `tick`. These calls run under one internal mutex. -- `core::RosbagRetention`: every rosbag retention decision (the per-fault cap, the storage quota, - the clear and the stale-row cleanup) on top of `FaultStorage::apply_rosbag_changes`. It returns +- `core::RosbagRetention`: every rosbag retention decision (the per-fault cap, the storage quota with + the retention rules, the open-time quota check, the clear and the stale-row cleanup) on top of `FaultStorage::apply_rosbag_changes`. It returns the directories to remove and never removes one itself. The core reaches the outside through four interfaces. The ROS adapter implements them. diff --git a/src/ros2_medkit_fault_manager/config/rosbag_retention.example.yaml b/src/ros2_medkit_fault_manager/config/rosbag_retention.example.yaml index 3f53fe2c3..73776b54f 100644 --- a/src/ros2_medkit_fault_manager/config/rosbag_retention.example.yaml +++ b/src/ros2_medkit_fault_manager/config/rosbag_retention.example.yaml @@ -4,8 +4,12 @@ # fault_codes., then the first label of pattern_order whose match covers the whole # fault code, then severity. of the fault, then defaults, then the built-in value. # Fields: priority (integer 0-1000, built-in 0) and over_quota (keep or drop, built-in keep). -# Any other key under retention is an error: the fault manager keeps running, records as before -# and reports the fault ROSBAG_RETENTION_CONFIG_INVALID. Retention values are read-only at runtime. +# A new recording evicts only recordings of equal or lower priority: lowest priority first, then +# cleared, healed, active, then oldest. If it still does not fit, keep stores it over the quota and +# drop discards it alone. With drop, a recording predicted not to fit is not started. +# Any other key under retention is an error: the fault manager keeps running without the rules, the +# quota becomes a hard stop for new recordings (nothing is evicted for it) and it reports the fault +# ROSBAG_RETENTION_CONFIG_INVALID. Retention values are read-only at runtime. # # Use with: ros2 run ros2_medkit_fault_manager fault_manager_node --ros-args --params-file # The rules are read only when snapshots.rosbag.enabled is true. diff --git a/src/ros2_medkit_fault_manager/design/index.rst b/src/ros2_medkit_fault_manager/design/index.rst index 9487709c7..0537622cc 100644 --- a/src/ros2_medkit_fault_manager/design/index.rst +++ b/src/ros2_medkit_fault_manager/design/index.rst @@ -563,7 +563,31 @@ Rosbag retention ``max_bags_per_fault`` of 1), applies the per-fault cap in the same change set as the insert, then the quota. One hold covers all three, so a clear finds the store either before its check or after its quota step. A new row that loses the cap is not inserted, and its directory is - removed like any other the cap frees. + removed like any other the cap frees. Without rules (``RetentionMode::kUnconfigured``) the quota + evicts the oldest recordings first. With rules (``kConfigured``) the store decides everything + before it applies anything: it predicts the total after the insert and the cap (the sum per path + of the largest row, the storage's own rule), picks the recordings the new one may evict, and + applies the insert, the cap and the evictions only when it fits. A recording that does not fit + after every allowed eviction follows ``over_quota``: ``keep`` stores it over the limit, + ``drop`` returns ``kDroppedOverQuota`` with nothing applied and the caller removes the bag. + The quota is enforced when a new recording is stored: if the per-fault cap removes every new + row (only when the new recording is older than the stored ones, after a backward clock step), + nothing is evicted in that store. + In degrade (``kDegraded``) there is no eviction for the quota: a new recording that does not + fit after the cap is dropped. A path the storage already holds (an upserted link) is never + dropped. +- ``admits_new_recording``: the open-time check. ``RosbagCapture`` asks it where a new recording + is about to start, before the ring buffer is flushed. It runs in degrade and for a fault whose + rule says ``over_quota: drop``. It refuses when the stored bytes, less what the cap frees for the + fault and what the fault's rank may evict, plus the payload bytes of recordings that are closed + but not stored yet (kept in memory by ``RosbagCapture``, so no file system walk) and the + estimated size of the recording (the buffered bytes times ``1 + duration_after_sec / + duration_sec``), exceed the quota. The pending term is an estimate of the payload without container + and metadata overhead, and the retention counts a pending recording only while no stored row + names its path. The store still decides with the measured size. A refusal leaves the + ring buffer in place. The size is an estimate: a recording that grows past it in its post-roll is + dropped at the store. +- ``recording_priority``: the priority of a stored recording. - ``on_fault_cleared``: removes every row of a cleared fault. ``RosbagCapture`` decides whether a clear removes recordings at all. - ``forget_recording``: removes the rows of a recording whose directory is gone, for @@ -593,7 +617,24 @@ re-reports. When the re-read of a FAILED report fails the core calls ``on_confir reads that fault's status first. A successful clear of the own fault, or of a root cause that auto-clears it, drops both. The timer is created cancelled and runs on the executor thread only while something is pending: the flag, or the startup report or clear that the core -has not accepted yet. Nothing reads the policy yet. +has not accepted yet. + +The node publishes the mode and the policy once, with ``RosbagRetention::set_policy``, after it builds +the retention and before capture starts. Each decision loads that snapshot once with ``std::atomic_load`` +and uses it throughout. + +The rank of a recording is read from the rows as they will be after the insert and the cap: + +- priority: the highest ``priority`` of the faults it links, each resolved with the fault's severity as + stored now. A link whose fault the storage does not hold counts as severity INFO and cleared; +- ``over_quota``: that of its highest-priority fault, ``keep`` when faults of equal priority disagree; +- status: active when any linked fault is PREFAILED, PREPASSED or CONFIRMED, else healed when any is + HEALED, else cleared. + +The eviction order is priority ascending, then cleared, healed, active, then oldest first. The +candidates are every stored recording except the new one and the paths the cap removes in the same +store, limited to a priority less than or equal to the new recording's. A read that only the rank +needs and that fails makes the store fall back to the insert and the cap alone, with ``quota_failed``. Lock order: the caller's outer locks (the node's rosbag mutex on the inline store path, the core mutex on the clear path), then the retention mutex, then the storage's own lock. Under the 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 2c3eb5b69..71a700ef4 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 @@ -15,12 +15,16 @@ #pragma once #include +#include +#include #include #include #include +#include #include #include "ros2_medkit_fault_manager/core/log_sink.hpp" +#include "ros2_medkit_fault_manager/core/retention_policy.hpp" #include "ros2_medkit_fault_manager/fault_storage.hpp" namespace ros2_medkit_fault_manager::core { @@ -32,6 +36,19 @@ struct RosbagRetentionLimits { bool auto_cleanup{true}; ///< A cleared fault loses its recordings }; +/// How the quota treats a new recording. +enum class RetentionMode { + kUnconfigured, ///< No rules: the oldest recordings go first + kConfigured, ///< The rules rank the recordings + kDegraded, ///< The rules are invalid: the quota is a hard stop for new recordings, nothing is evicted for it +}; + +/// One immutable snapshot of the rules. Every decision loads it once. +struct RetentionPolicyState { + RetentionMode mode{RetentionMode::kUnconfigured}; + std::shared_ptr policy; ///< Null unless kConfigured +}; + /// Why a recording's directory is no longer named by any row. enum class RemovalReason { kCap, ///< The per-fault cap (max_bags_per_fault) @@ -51,10 +68,20 @@ enum class StoreResult { kStored, ///< The rows were applied. Also when the cap removed every new row. kAllFaultsCleared, ///< Every fault of the recording is cleared. Nothing was stored. kStoreFailed, ///< The cap read or the insert failed. Nothing was stored. + kDroppedOverQuota, ///< The recording does not fit the quota. Nothing was stored; the caller removes the bag. }; struct StoreOutcome { + enum class DropReason { + kNone, + kOverQuotaDrop, ///< over_quota: drop of the recording's rule + kDegradedQuota, ///< Invalid configuration: the quota is a hard stop + }; + StoreResult result{StoreResult::kStored}; + DropReason drop_reason{DropReason::kNone}; + size_t recording_bytes{0}; ///< Set with kDroppedOverQuota: size of the dropped recording + size_t limit_bytes{0}; ///< Set with kDroppedOverQuota: the quota /// The quota read or an eviction threw. The rows stay stored, and so do the evictions before it. bool quota_failed{false}; std::string error; ///< Exception text of the store failure or of the quota failure @@ -84,8 +111,26 @@ class RosbagRetention { RosbagRetention & operator=(RosbagRetention &&) = delete; ~RosbagRetention() = default; + /// Publish the rules. @p policy is null unless @p mode is kConfigured. Safe to call while + /// decisions run: each decision uses the snapshot it loaded. + void set_policy(RetentionMode mode, std::shared_ptr policy); + + /// Priority of a stored recording: the highest priority of the faults it is linked to, 0 + /// unless kConfigured. + /// @throws a storage failure + int64_t recording_priority(const std::string & recording_id); + + /// Whether a new recording for @p fault_code may start. Checked only in kDegraded and for a + /// fault whose rule says over_quota: drop. Refused when the storage, less what the cap and the + /// eviction would free, plus @p reserve_bytes is over the quota. A failed read admits it. + /// @p pending lists recordings closed but not stored yet (path, estimated bytes). Each counts only + /// while no stored row names its path, which is known only under the mutex. + bool admits_new_recording(const std::string & fault_code, size_t reserve_bytes, + const std::vector> & pending = {}); + /// Store the rows of one recording. In one hold of the mutex: drop the rows of faults the /// storage holds as cleared, apply the per-fault cap together with the insert, then the quota. + /// With rules the quota evicts by priority and may drop the new recording instead. /// Precondition: no stored row names the recording's path, except links that @p rows upsert. /// Precondition: every row carries `recording_id == rosbag_recording_id(file_path)`, not empty. /// Never throws. @@ -110,6 +155,36 @@ class RosbagRetention { std::vector unlink_paths; }; + struct FaultFacts; + struct RecordingRank; + struct QuotaDecision; + using FactsCache = std::unordered_map; + + /// The store without rules: quota eviction oldest first. + StoreOutcome store_oldest_first(const std::vector & rows); + + /// The store with rules (kConfigured) or in degrade (kDegraded). + StoreOutcome store_ranked(const std::vector & rows, const RetentionPolicyState & state); + + /// What the quota does with a new recording, decided before anything is applied. + /// @throws a failure of a read the decision needs + QuotaDecision decide_quota(const std::vector & rows, const RosbagChangeSet & changes, + const RetentionPolicyState & state); + + /// Apply @p changes of a store. Lists the directories no row names any more in @p outcome. + /// False, with kStoreFailed in @p outcome, when the apply throws. + bool apply_store(const std::vector & rows, const RosbagChangeSet & changes, + const std::unordered_map & recording_ids, StoreOutcome & outcome); + + /// Severity, rule and status of a fault as the storage holds it now. A fault the storage does + /// not hold counts as cleared with severity INFO. + /// @throws a storage failure + FaultFacts fault_facts(const RetentionPolicyState & state, const std::string & fault_code, FactsCache & cache); + + /// The rank of a recording from the faults its rows link. + RecordingRank rank_of(const RetentionPolicyState & state, const std::vector & fault_codes, + FactsCache & cache); + /// Whether a fault keeps its row: false only under auto_cleanup with a cap of exactly 1, for a /// fault the storage holds as cleared. A fault that cannot be read keeps its row. bool row_still_wanted(const std::string & fault_code); @@ -132,6 +207,7 @@ class RosbagRetention { const RosbagRetentionLimits limits_; LogSink & log_sink_; const std::string logger_name_; + std::shared_ptr state_; ///< Only through std::atomic_load / std::atomic_store std::mutex mutex_; }; diff --git a/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/rosbag_capture.hpp b/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/rosbag_capture.hpp index 628acfe71..3c8bbe3a8 100644 --- a/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/rosbag_capture.hpp +++ b/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/rosbag_capture.hpp @@ -274,6 +274,14 @@ class RosbagCapture { /// opened; on kIoError the partial bag has already been removed. FlushResult flush_to_bag(const std::string & fault_code); + /// Put @p messages back in front of what the buffer received meanwhile and apply the + /// buffer limits again. Takes buffer_mutex_. + void restore_buffer(std::deque messages); + + /// The open-time quota check for a new recording of @p fault_code. Reads the buffer size + /// under buffer_mutex_ and releases it before the retention is asked. + bool quota_admits_recording(const std::string & fault_code); + /// Open a fresh bag for @p fault_code: generate the path, create its parent /// directory and open active_writer_. Independent of the ring buffer, so a /// post-fault-only recording can use it with nothing buffered. @@ -332,6 +340,9 @@ class RosbagCapture { /// would terminate; the other runs on the capture pool, which would swallow it /// into a log with the bag already orphaned. /// + /// A recording the quota refused (core::StoreResult::kDroppedOverQuota) is removed here too, + /// and logged once the directory is gone. + /// /// @return True when the rows are durable. bool store_rows_or_discard_bag(std::vector rows, const std::string & bag_path); @@ -491,6 +502,15 @@ class RosbagCapture { /// the bag being closed. std::atomic recording_started_at_ns_{0}; + /// Payload bytes written to the open writer, reset when a writer opens. The open-time quota check + /// counts them for a recording that is closed but not stored yet. + std::atomic recording_bytes_{0}; + + /// Closed recordings the store worker has not finished, by directory, with their payload bytes. + /// A leaf lock: nothing else is taken under it. + std::mutex pending_mutex_; + std::map pending_bytes_; + /// When start() ran, on the monotonic clock. Bounds the buffered history a flush /// may claim: that history is measured on the wall clock (message timestamps are), /// so an NTP step or a VM resync between buffering a message and flushing it lands 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 d75737d3e..890458b1f 100644 --- a/src/ros2_medkit_fault_manager/src/core/rosbag_retention.cpp +++ b/src/ros2_medkit_fault_manager/src/core/rosbag_retention.cpp @@ -18,6 +18,8 @@ #include #include #include +#include +#include #include #include #include @@ -59,11 +61,112 @@ bool is_empty(const RosbagChangeSet & changes) { return changes.insert.empty() && changes.remove.empty() && changes.remove_recordings.empty(); } +constexpr int kStatusCleared = 0; +constexpr int kStatusHealed = 1; +constexpr int kStatusActive = 2; + +int status_rank(const std::optional & fault) { + if (!fault.has_value()) { + return kStatusCleared; + } + const std::string & status = fault->status; + if (status == fd::fault_status::kPrefailed || status == fd::fault_status::kPrepassed || + status == fd::fault_status::kConfirmed) { + return kStatusActive; + } + return status == fd::fault_status::kHealed ? kStatusHealed : kStatusCleared; +} + +/// The stored rows as they are after @p changes, ordered as the backends order them. +std::vector rows_after(std::vector rows, const RosbagChangeSet & changes) { + rows.erase(std::remove_if(rows.begin(), rows.end(), + [&changes](const RosbagFileInfo & row) { + const bool by_link = std::any_of( + changes.remove.begin(), changes.remove.end(), [&row](const RosbagLink & link) { + return link.fault_code == row.fault_code && link.file_path == row.file_path; + }); + const bool by_recording = + std::find(changes.remove_recordings.begin(), changes.remove_recordings.end(), + row.recording_id) != changes.remove_recordings.end(); + return by_link || by_recording; + }), + rows.end()); + for (const auto & in : changes.insert) { + auto same_link = std::find_if(rows.begin(), rows.end(), [&in](const RosbagFileInfo & row) { + return row.fault_code == in.fault_code && row.file_path == in.file_path; + }); + if (same_link != rows.end()) { + *same_link = in; + } else { + rows.push_back(in); + } + } + std::stable_sort(rows.begin(), rows.end(), [](const RosbagFileInfo & a, const RosbagFileInfo & b) { + return a.created_at_ns < b.created_at_ns; + }); + return rows; +} + +/// The storage's own rule: the largest row of a path counts, once. +std::map bytes_by_path(const std::vector & rows) { + std::map bytes; + for (const auto & row : rows) { + auto & largest = bytes[row.file_path]; + largest = std::max(largest, row.size_bytes); + } + return bytes; +} + +size_t total_bytes(const std::vector & rows) { + size_t total = 0; + for (const auto & entry : bytes_by_path(rows)) { + total += entry.second; + } + return total; +} + } // namespace +struct RosbagRetention::FaultFacts { + int64_t priority{0}; + OverQuota over_quota{OverQuota::kKeep}; + int status{kStatusCleared}; +}; + +struct RosbagRetention::RecordingRank { + int64_t priority{0}; + OverQuota over_quota{OverQuota::kKeep}; + int status{kStatusCleared}; +}; + +struct RosbagRetention::QuotaDecision { + bool drop{false}; + StoreOutcome::DropReason reason{StoreOutcome::DropReason::kNone}; + size_t recording_bytes{0}; + bool keep_over_limit{false}; ///< The recording stays over the quota after every allowed eviction + int64_t priority{0}; + struct Victim { + std::string recording_id; + std::string path; + }; + std::vector evict; ///< In eviction order +}; + RosbagRetention::RosbagRetention(FaultStorage & storage, RosbagRetentionLimits limits, LogSink & log_sink, std::string logger_name) - : storage_(storage), limits_(limits), log_sink_(log_sink), logger_name_(std::move(logger_name)) { + : storage_(storage) + , limits_(limits) + , log_sink_(log_sink) + , logger_name_(std::move(logger_name)) + , state_(std::make_shared()) { +} + +void RosbagRetention::set_policy(RetentionMode mode, std::shared_ptr policy) { + auto state = std::make_shared(); + state->mode = mode; + state->policy = mode == RetentionMode::kConfigured ? std::move(policy) : nullptr; + std::shared_ptr published = std::move(state); + std::atomic_store(&state_, std::move(published)); } StoreOutcome RosbagRetention::store(std::vector rows) { @@ -84,14 +187,19 @@ StoreOutcome RosbagRetention::store(std::vector rows) { return outcome; } + const auto state = std::atomic_load(&state_); + if (state->mode == RetentionMode::kUnconfigured) { + return store_oldest_first(rows); + } + return store_ranked(rows, *state); +} + +StoreOutcome RosbagRetention::store_oldest_first(const std::vector & rows) { + StoreOutcome outcome; RosbagChangeSet changes; std::unordered_map recording_ids; try { changes = cap_changes(rows, recording_ids); - if (!is_empty(changes)) { - outcome.unlink_paths = - freed(storage_.apply_rosbag_changes(changes).orphaned_paths, recording_ids, RemovalReason::kCap); - } } catch (const std::exception & e) { outcome.result = StoreResult::kStoreFailed; outcome.error = e.what(); @@ -101,16 +209,8 @@ StoreOutcome RosbagRetention::store(std::vector rows) { outcome.error = "unknown exception"; return outcome; } - - // A path the cap left without any new row has no row at all: nothing else names a new recording. - std::set inserted_paths; - for (const auto & row : changes.insert) { - inserted_paths.insert(row.file_path); - } - for (const auto & row : rows) { - if (inserted_paths.count(row.file_path) == 0) { - append_unique(outcome.unlink_paths, freed({row.file_path}, recording_ids, RemovalReason::kCap)); - } + if (!apply_store(rows, changes, recording_ids, outcome)) { + return outcome; } const std::string & bag_path = rows.front().file_path; @@ -145,6 +245,345 @@ StoreOutcome RosbagRetention::store(std::vector rows) { return outcome; } +bool RosbagRetention::apply_store(const std::vector & rows, const RosbagChangeSet & changes, + const std::unordered_map & recording_ids, + StoreOutcome & outcome) { + try { + if (!is_empty(changes)) { + outcome.unlink_paths = + freed(storage_.apply_rosbag_changes(changes).orphaned_paths, recording_ids, RemovalReason::kCap); + } + } catch (const std::exception & e) { + outcome.result = StoreResult::kStoreFailed; + outcome.error = e.what(); + return false; + } catch (...) { + outcome.result = StoreResult::kStoreFailed; + outcome.error = "unknown exception"; + return false; + } + + // A path the cap left without any new row has no row at all: nothing else names a new recording. + std::set inserted_paths; + for (const auto & row : changes.insert) { + inserted_paths.insert(row.file_path); + } + for (const auto & row : rows) { + if (inserted_paths.count(row.file_path) == 0) { + append_unique(outcome.unlink_paths, freed({row.file_path}, recording_ids, RemovalReason::kCap)); + } + } + return true; +} + +StoreOutcome RosbagRetention::store_ranked(const std::vector & rows, + const RetentionPolicyState & state) { + StoreOutcome outcome; + RosbagChangeSet changes; + std::unordered_map recording_ids; + try { + changes = cap_changes(rows, recording_ids); + } catch (const std::exception & e) { + outcome.result = StoreResult::kStoreFailed; + outcome.error = e.what(); + return outcome; + } catch (...) { + outcome.result = StoreResult::kStoreFailed; + outcome.error = "unknown exception"; + return outcome; + } + + const std::string & bag_path = rows.front().file_path; + // Decided before anything is applied. A failed read falls back to the insert and the cap alone, + // and is reported once those are applied. + QuotaDecision decision; + std::string read_error; + try { + decision = decide_quota(rows, changes, state); + } catch (const std::exception & e) { + decision = QuotaDecision{}; + read_error = e.what(); + } catch (...) { + decision = QuotaDecision{}; + read_error = "unknown exception"; + } + + if (decision.drop) { + outcome.result = StoreResult::kDroppedOverQuota; + outcome.drop_reason = decision.reason; + outcome.recording_bytes = decision.recording_bytes; + outcome.limit_bytes = limits_.max_total_bytes; + return outcome; + } + + if (!apply_store(rows, changes, recording_ids, outcome)) { + return outcome; + } + if (!read_error.empty()) { + outcome.quota_failed = true; + outcome.error = read_error; + logf(log_sink_, LogLevel::kWarn, logger_name_, "Failed to enforce the rosbag storage limit after storing '%s': %s", + bag_path.c_str(), read_error.c_str()); + } + + try { + for (const auto & victim : decision.evict) { + RosbagChangeSet eviction; + eviction.remove_recordings.push_back(victim.recording_id); + const std::unordered_map ids{{victim.path, victim.recording_id}}; + append_unique(outcome.unlink_paths, + freed(storage_.apply_rosbag_changes(eviction).orphaned_paths, ids, RemovalReason::kQuota)); + } + } catch (const std::exception & e) { + outcome.quota_failed = true; + outcome.error = e.what(); + logf(log_sink_, LogLevel::kWarn, logger_name_, "Failed to enforce the rosbag storage limit after storing '%s': %s", + bag_path.c_str(), e.what()); + return outcome; + } catch (...) { + outcome.quota_failed = true; + outcome.error = "unknown exception"; + logf(log_sink_, LogLevel::kWarn, logger_name_, + "Failed to enforce the rosbag storage limit after storing '%s': unknown exception", bag_path.c_str()); + return outcome; + } + if (decision.keep_over_limit) { + logf(log_sink_, LogLevel::kWarn, logger_name_, + "Recording '%s' (priority %lld) still exceeds snapshots.rosbag.max_total_storage_mb (%zu MB) after every " + "recording it may evict was removed; it is kept (over_quota: keep), and the storage stays over the limit", + rows.front().recording_id.c_str(), static_cast(decision.priority), + limits_.max_total_bytes / (1024 * 1024)); + } + return outcome; +} + +RosbagRetention::QuotaDecision RosbagRetention::decide_quota(const std::vector & rows, + const RosbagChangeSet & changes, + const RetentionPolicyState & state) { + QuotaDecision decision; + const size_t limit = limits_.max_total_bytes; + const std::string & bag_path = rows.front().file_path; + + // The total after the store never exceeds the total now plus the new recording. + size_t new_bytes = 0; + for (const auto & row : rows) { + new_bytes = std::max(new_bytes, row.size_bytes); + } + if (storage_.get_total_rosbag_storage_bytes() + new_bytes <= limit) { + return decision; + } + + const auto stored = storage_.get_all_rosbag_files(); + const auto after = rows_after(stored, changes); + const auto sizes = bytes_by_path(after); + size_t predicted = 0; + for (const auto & entry : sizes) { + predicted += entry.second; + } + if (predicted <= limit) { + return decision; + } + const bool kept_by_cap = sizes.count(bag_path) != 0; + if (!kept_by_cap) { + return decision; // the cap removed every new row: nothing is stored to make room for + } + // A path the storage already holds is an upserted link: dropping it would orphan a stored row. + const bool upserted = std::any_of(stored.begin(), stored.end(), [&bag_path](const RosbagFileInfo & row) { + return row.file_path == bag_path; + }); + decision.recording_bytes = sizes.at(bag_path); + + if (state.mode == RetentionMode::kDegraded) { + if (!upserted) { + decision.drop = true; + decision.reason = StoreOutcome::DropReason::kDegradedQuota; + } + return decision; + } + + struct Candidate { + std::string path; + std::string recording_id; + size_t bytes{0}; + size_t age{0}; + RecordingRank rank; + }; + std::vector candidates; + std::map index_by_path; + std::map> codes_by_path; + for (const auto & row : after) { + if (index_by_path.emplace(row.file_path, candidates.size()).second) { + candidates.push_back({row.file_path, row.recording_id, sizes.at(row.file_path), candidates.size(), {}}); + } + codes_by_path[row.file_path].push_back(row.fault_code); + } + + FactsCache cache; + const RecordingRank fresh = rank_of(state, codes_by_path.at(bag_path), cache); + decision.priority = fresh.priority; + std::vector allowed; + for (auto & candidate : candidates) { + if (candidate.path == bag_path) { + continue; + } + candidate.rank = rank_of(state, codes_by_path.at(candidate.path), cache); + if (candidate.rank.priority <= fresh.priority) { + allowed.push_back(candidate); + } + } + std::sort(allowed.begin(), allowed.end(), [](const Candidate & a, const Candidate & b) { + return std::tie(a.rank.priority, a.rank.status, a.age) < std::tie(b.rank.priority, b.rank.status, b.age); + }); + + size_t remaining = predicted; + size_t chosen = 0; + while (chosen < allowed.size() && remaining > limit) { + remaining -= std::min(remaining, allowed[chosen].bytes); + ++chosen; + } + const bool fits = remaining <= limit; + if (!fits) { + chosen = allowed.size(); + if (!upserted && fresh.over_quota == OverQuota::kDrop) { + decision.drop = true; + decision.reason = StoreOutcome::DropReason::kOverQuotaDrop; + return decision; + } + decision.keep_over_limit = true; + } + for (size_t i = 0; i < chosen; ++i) { + decision.evict.push_back({allowed[i].recording_id, allowed[i].path}); + } + return decision; +} + +RosbagRetention::FaultFacts RosbagRetention::fault_facts(const RetentionPolicyState & state, + const std::string & fault_code, FactsCache & cache) { + const auto known = cache.find(fault_code); + if (known != cache.end()) { + return known->second; + } + const auto fault = storage_.get_fault(fault_code); + FaultFacts facts; + const ResolvedRule rule = state.policy->resolve(fault_code, fault.has_value() ? fault->severity : uint8_t{0}); + facts.priority = rule.priority; + facts.over_quota = rule.over_quota; + facts.status = status_rank(fault); + cache.emplace(fault_code, facts); + return facts; +} + +RosbagRetention::RecordingRank RosbagRetention::rank_of(const RetentionPolicyState & state, + const std::vector & fault_codes, + FactsCache & cache) { + RecordingRank rank; + bool first = true; + for (const auto & code : fault_codes) { + const FaultFacts facts = fault_facts(state, code, cache); + rank.status = std::max(rank.status, facts.status); + if (first || facts.priority > rank.priority) { + rank.priority = facts.priority; + rank.over_quota = facts.over_quota; + first = false; + } else if (facts.priority == rank.priority && facts.over_quota == OverQuota::kKeep) { + rank.over_quota = OverQuota::kKeep; // on a tie keeping data is the safer side + } + } + return rank; +} + +int64_t RosbagRetention::recording_priority(const std::string & recording_id) { + std::lock_guard lock(mutex_); + const auto state = std::atomic_load(&state_); + if (state->mode != RetentionMode::kConfigured) { + return 0; + } + std::vector codes; + for (const auto & row : storage_.get_rosbag_files_by_recording(recording_id)) { + codes.push_back(row.fault_code); + } + FactsCache cache; + return rank_of(*state, codes, cache).priority; +} + +bool RosbagRetention::admits_new_recording(const std::string & fault_code, size_t reserve_bytes, + const std::vector> & pending) { + const auto state = std::atomic_load(&state_); + if (state->mode == RetentionMode::kUnconfigured) { + return true; + } + std::lock_guard lock(mutex_); + try { + FactsCache cache; + int64_t priority = 0; + if (state->mode == RetentionMode::kConfigured) { + const FaultFacts own = fault_facts(*state, fault_code, cache); + if (own.over_quota == OverQuota::kKeep) { + return true; + } + priority = own.priority; + } + + // One more recording of this fault: the cap removes the same links as for a real store. + RosbagFileInfo probe; + probe.fault_code = fault_code; + probe.file_path = ""; + probe.recording_id = probe.file_path; + probe.created_at_ns = std::numeric_limits::max(); + std::unordered_map recording_ids; + RosbagChangeSet cap = cap_changes({probe}, recording_ids); + cap.insert.clear(); + const auto stored = storage_.get_all_rosbag_files(); + const auto after = rows_after(stored, cap); + const size_t stored_bytes = total_bytes(stored); + const size_t after_cap = total_bytes(after); + + size_t evictable = 0; + if (state->mode == RetentionMode::kConfigured) { + const auto sizes = bytes_by_path(after); + std::map> codes_by_path; + for (const auto & row : after) { + codes_by_path[row.file_path].push_back(row.fault_code); + } + for (const auto & entry : codes_by_path) { + if (rank_of(*state, entry.second, cache).priority <= priority) { + evictable += sizes.at(entry.first); + } + } + } + + const size_t limit = limits_.max_total_bytes; + const size_t kept = after_cap - evictable; + std::set stored_paths; + for (const auto & row : stored) { + stored_paths.insert(row.file_path); + } + size_t needed = reserve_bytes; + for (const auto & entry : pending) { + if (stored_paths.count(entry.first) == 0) { + needed += entry.second; + } + } + if (kept + needed <= limit) { + return true; + } + logf(log_sink_, LogLevel::kInfo, logger_name_, + "Not recording fault '%s': it needs up to %zu bytes (buffered history and post-fault window) and " + "only %zu of snapshots.rosbag.max_total_storage_mb (%zu MB) can be had (stored %zu bytes, freed by the cap " + "%zu, evictable %zu); the buffered history stays for the next fault", + fault_code.c_str(), needed, limit > kept ? limit - kept : size_t{0}, limit / (1024 * 1024), stored_bytes, + stored_bytes - after_cap, evictable); + return false; + } catch (const std::exception & e) { + logf(log_sink_, LogLevel::kWarn, logger_name_, "Could not check the rosbag quota before recording '%s': %s", + fault_code.c_str(), e.what()); + } catch (...) { + logf(log_sink_, LogLevel::kWarn, logger_name_, + "Could not check the rosbag quota before recording '%s': unknown exception", fault_code.c_str()); + } + return true; +} + std::vector RosbagRetention::evict_over_quota(size_t max_bytes, const std::string & keep_recording_id) { std::lock_guard lock(mutex_); Eviction eviction; 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 1f22c89d3..20d0d3f10 100644 --- a/src/ros2_medkit_fault_manager/src/fault_manager_node.cpp +++ b/src/ros2_medkit_fault_manager/src/fault_manager_node.cpp @@ -249,6 +249,10 @@ FaultManagerNode::FaultManagerNode(const rclcpp::NodeOptions & options) : Node(" retention_limits.auto_cleanup = config_.snapshots_rosbag_auto_cleanup; rosbag_retention_ = std::make_shared(*storage_, retention_limits, log_sink_, config_.logger_name); + rosbag_retention_->set_policy(retention_degraded_ ? core::RetentionMode::kDegraded + : retention_policy_ != nullptr ? core::RetentionMode::kConfigured + : core::RetentionMode::kUnconfigured, + retention_policy_); // Runs after the override files are loaded, so a code with its own healing_enabled: true keeps // its HEALED status. Each flipped fault is audited, or the audit log's verify() would not see it. diff --git a/src/ros2_medkit_fault_manager/src/rosbag_capture.cpp b/src/ros2_medkit_fault_manager/src/rosbag_capture.cpp index 6c905200d..41a7d7971 100644 --- a/src/ros2_medkit_fault_manager/src/rosbag_capture.cpp +++ b/src/ros2_medkit_fault_manager/src/rosbag_capture.cpp @@ -25,6 +25,7 @@ #include #include #include +#include #include #include #include @@ -448,6 +449,10 @@ void RosbagCapture::store_worker_loop() { store_busy_ = true; lock.unlock(); store_closed_recording(recording); + { + std::lock_guard plock(pending_mutex_); + pending_bytes_.erase(recording.bag_path); + } lock.lock(); store_busy_ = false; store_cv_.notify_all(); @@ -553,6 +558,11 @@ void RosbagCapture::on_fault_confirmed(const std::string & fault_code) { return; } + // A recording the store would drop anyway must not take the history the next fault needs. + if (!quota_admits_recording(fault_code)) { + return; + } + RCLCPP_INFO(node_->get_logger(), "RosbagCapture: fault '%s' confirmed, flushing buffer to bag", fault_code.c_str()); // In "entity" mode, narrow the broadly-buffered messages to the faulting node's @@ -888,6 +898,7 @@ void RosbagCapture::message_callback(const std::string & topic, const std::strin auto bag_msg = create_bag_message(topic, timestamp_ns, msg->get_rcl_serialized_message(), node_->get_logger()); if (bag_msg) { active_writer_->write(bag_msg); + recording_bytes_ += msg->size(); } // Memory is automatically cleaned up by RAII when bag_msg goes out of scope } catch (const std::exception & e) { @@ -1241,6 +1252,7 @@ std::optional RosbagCapture::open_bag_writer(const std::string & fa std::lock_guard wlock(writer_mutex_); active_writer_ = std::move(writer); created_topics_.clear(); + recording_bytes_.store(0); return bag_path; } catch (const std::exception & e) { @@ -1257,6 +1269,36 @@ std::optional RosbagCapture::open_bag_writer(const std::string & fa } } +void RosbagCapture::restore_buffer(std::deque messages) { + { + std::lock_guard lock(buffer_mutex_); + for (const auto & message : messages) { + buffer_bytes_ += message.serialized_data->size(); + } + messages.insert(messages.end(), std::make_move_iterator(message_buffer_.begin()), + std::make_move_iterator(message_buffer_.end())); + message_buffer_ = std::move(messages); + } + prune_buffer(); +} + +bool RosbagCapture::quota_admits_recording(const std::string & fault_code) { + size_t buffered_bytes = 0; + { + std::lock_guard lock(buffer_mutex_); + buffered_bytes = buffer_bytes_; + } + // Recordings closed but not stored yet: the retention counts those it does not hold yet. + std::vector> pending; + { + std::lock_guard lock(pending_mutex_); + pending.assign(pending_bytes_.begin(), pending_bytes_.end()); + } + const double window = config_.duration_sec > 0.0 ? config_.duration_after_sec / config_.duration_sec : 0.0; + const auto reserve = static_cast(static_cast(buffered_bytes) * (1.0 + std::max(0.0, window))); + return retention_->admits_new_recording(fault_code, reserve, pending); +} + RosbagCapture::FlushResult RosbagCapture::flush_to_bag(const std::string & fault_code) { // Copy buffer under lock, then release to avoid holding mutex during IO std::deque messages_to_write; @@ -1275,6 +1317,8 @@ RosbagCapture::FlushResult RosbagCapture::flush_to_bag(const std::string & fault auto opened = open_bag_writer(fault_code); if (!opened) { + // The next fault within duration_sec needs this history. + restore_buffer(std::move(messages_to_write)); return {FlushStatus::kIoError, ""}; } const std::string bag_path = *opened; @@ -1317,6 +1361,7 @@ RosbagCapture::FlushResult RosbagCapture::flush_to_bag(const std::string & fault node_->get_logger()); if (bag_msg) { active_writer_->write(bag_msg); + recording_bytes_ += msg.serialized_data->size(); if (msg_count == 0) { first_written_ns = msg.timestamp_ns; } @@ -1537,6 +1582,26 @@ bool RosbagCapture::store_rows_or_discard_bag(std::vector rows, return false; } + if (outcome.result == core::StoreResult::kDroppedOverQuota) { + const char * reason = outcome.drop_reason == core::StoreOutcome::DropReason::kDegradedQuota + ? "the retention configuration is invalid, so the quota is a hard stop" + : "over_quota is drop"; + std::error_code ec; + std::filesystem::remove_all(bag_path, ec); + if (ec) { + RCLCPP_WARN(node_->get_logger(), + "Recording '%s' (%zu bytes) does not fit snapshots.rosbag.max_total_storage_mb (%zu bytes): %s. " + "It could not be removed (%s); the directory stays, unreachable and uncounted", + bag_path.c_str(), outcome.recording_bytes, outcome.limit_bytes, reason, ec.message().c_str()); + } else { + RCLCPP_WARN(node_->get_logger(), + "Recording '%s' (%zu bytes) dropped, it does not fit snapshots.rosbag.max_total_storage_mb " + "(%zu bytes): %s", + bag_path.c_str(), outcome.recording_bytes, outcome.limit_bytes, reason); + } + return false; + } + if (outcome.result == core::StoreResult::kStoreFailed) { // Without a row nothing can ever reach this bag: retrieval is keyed by fault // code, and quota accounting enumerates rows, so a kept directory would sit @@ -1629,6 +1694,12 @@ void RosbagCapture::finalize_post_fault_recording() { std::lock_guard wlock(writer_mutex_); closing_writer = std::move(active_writer_); created_topics_.clear(); + { + // Taken after the last write, which needs this lock, and registered under the lock that + // cleared the guard: a confirmation that sees the guard down also sees this recording. + std::lock_guard plock(pending_mutex_); + pending_bytes_[bag_path] = recording_bytes_.exchange(0); + } // Measured here, with the writer already out of reach of message_callback, and // not further down: closing the bag flushes it and writes metadata.yaml, and // the size walk recurses the directory. Both are the fault manager's own time @@ -1679,6 +1750,8 @@ void RosbagCapture::finalize_post_fault_recording() { // and the capture subscriptions for as long as it takes, so the rest is the store // worker's. The row is stored only after the manifest is written, so a recording // is never listed before its manifest exists. + RCLCPP_DEBUG(node_->get_logger(), "Post-fault window of '%s' closed, recording '%s' waits for the store", + fault_code.c_str(), bag_path.c_str()); ClosedRecording recording; recording.bag_path = std::move(bag_path); recording.fault_code = std::move(fault_code); diff --git a/src/ros2_medkit_fault_manager/test/integration/rosbag_fm_harness.py b/src/ros2_medkit_fault_manager/test/integration/rosbag_fm_harness.py index ceb039c0a..ecd92c054 100644 --- a/src/ros2_medkit_fault_manager/test/integration/rosbag_fm_harness.py +++ b/src/ros2_medkit_fault_manager/test/integration/rosbag_fm_harness.py @@ -47,6 +47,10 @@ MIB = 1024 * 1024 KIB = 1024 PAYLOAD_TOPIC = '/pin/payload' +SEVERITY_INFO = 0 +SEVERITY_WARN = 1 +SEVERITY_ERROR = 2 +SEVERITY_CRITICAL = 3 SOURCE_ID = '/pin_node' FM_NODE = 'fault_manager' QOS_MATCH_PARAM = 'snapshots.rosbag.qos_match' @@ -302,11 +306,11 @@ def _call(self, srv_type, name, request): raise AssertionError(f'{name} did not answer\n' + self.failure_context()) return answer - def report(self, code): + def report(self, code, severity=SEVERITY_ERROR): request = ReportFault.Request() request.fault_code = code request.event_type = ReportFault.Request.EVENT_FAILED - request.severity = 2 + request.severity = severity request.description = 'pin' request.source_id = SOURCE_ID return self._call(ReportFault, 'report_fault', request) @@ -423,6 +427,7 @@ def __init__(self, client, period_sec=0.01, size=1024): self._client = client self._period = period_sec self._size = size + self.published = 0 self._stop = threading.Event() self._thread = threading.Thread(target=self._run, daemon=True) @@ -431,6 +436,7 @@ def _run(self): msg.data = list(os.urandom(self._size)) while not self._stop.wait(self._period): self._client.publisher.publish(msg) + self.published += 1 def __enter__(self): self._thread.start() @@ -441,6 +447,11 @@ def __exit__(self, *exc): self._thread.join(timeout=10) +def rules(flat): + """Return the retention parameters of `flat`, which are relative to the retention prefix.""" + return {f'snapshots.rosbag.retention.{key}': value for key, value in flat.items()} + + def poll(predicate, timeout=None, interval=0.05): """Return True once `predicate()` is true, False at the deadline.""" deadline = time.monotonic() + (EVENT_TIMEOUT_SEC if timeout is None else timeout) @@ -575,21 +586,26 @@ def check_size(self, path, mib): f'{path} holds {actual} bytes, expected {payload}' f' plus at most {SIZE_SLACK}') - def record(self, fm, code, mib, burst=()): + def record(self, fm, code, mib, burst=(), severities=None, reports=1): """ Publish `mib` MiB, confirm `code` and `burst`, and return the bag path. - The `burst` faults confirm inside the post-fault window of `code`. + The `burst` faults confirm inside the post-fault window of `code`. `severities` maps a + fault code to its severity; the others report ERROR. `code` is reported `reports` times. """ + severities = severities or {} mark = fm.mark() self.client.publish_bytes(int(mib * MIB) // MESSAGE_SIZE, MESSAGE_SIZE) - self.assertTrue(self.client.report(code).accepted) + for _ in range(reports): + self.assertTrue( + self.client.report(code, severities.get(code, SEVERITY_ERROR)).accepted) if burst: self.assertIsNotNone( fm.wait_line(r'Recording [\d.]+s more after fault confirmation', since=mark), 'the post-fault window never opened:\n' + fm.output()[-3000:]) for other in burst: - self.assertTrue(self.client.report(other).accepted) + self.assertTrue( + self.client.report(other, severities.get(other, SEVERITY_ERROR)).accepted) self.assertIsNotNone( fm.wait_line(f"Fault '{other}' confirmed during post-fault recording", since=mark), @@ -601,6 +617,42 @@ def record(self, fm, code, mib, burst=()): self.check_size(path, mib) return path + def record_growing(self, fm, code, post_mib, others=(), severities=None, buffer_kib=128, + during_window=None): + """ + Confirm `code` on a small ring buffer, then publish `post_mib` MiB in its post-roll. + + The buffer passes the open-time check; the recording grows past it afterwards. The `others` + confirm inside the window. `during_window(path)` runs with the recording's directory once + the window is open. Return (path, stored): stored is False when the store dropped the + recording. + """ + severities = severities or {} + known = set(bag_dirs(self.storage)) + mark = fm.mark() + self.client.publish_bytes(max(1, buffer_kib * KIB // MESSAGE_SIZE), MESSAGE_SIZE) + self.assertTrue(self.client.report(code, severities.get(code, SEVERITY_ERROR)).accepted) + self.assertIsNotNone( + fm.wait_line(r'Recording [\d.]+s more after fault confirmation', since=mark), + 'the post-fault window never opened:\n' + fm.output()[-3000:]) + if during_window is not None: + fresh = [name for name in bag_dirs(self.storage) + if name not in known and f'fault_{code}_' in name] + self.assertEqual(len(fresh), 1, fresh) + during_window(os.path.join(self.storage, fresh[0])) + for other in others: + self.assertTrue( + self.client.report(other, severities.get(other, SEVERITY_ERROR)).accepted) + self.assertIsNotNone( + fm.wait_line(f"Fault '{other}' confirmed during post-fault recording", since=mark), + f'{other} did not land inside the window:\n' + fm.output()[-3000:]) + self.client.publish_bytes(int(post_mib * MIB) // MESSAGE_SIZE, MESSAGE_SIZE) + outcome = fm.wait_line( + rf"Bag file completed: (\S*fault_{code}_\d+)|Recording '(\S*fault_{code}_\d+)' " + rf'\(\d+ bytes\) dropped', since=mark) + self.assertIsNotNone(outcome, f'no outcome for {code}:\n' + fm.output()[-3000:]) + return outcome.group(1) or outcome.group(2), outcome.group(1) is not None + def assert_recording_present(self, code, path): self.assertTrue(os.path.isdir(path), f'{path} is gone') self.assertIn(path, self.row_paths(code), f'{code} has no row for {path}') @@ -626,3 +678,20 @@ def check_quota_evicts_oldest_first(self): self.assertLessEqual(storage_bytes(self.storage), quota_mib * MIB) self.assertEqual(sorted(bag_dirs(self.storage)), sorted(os.path.basename(paths[code]) for code in order[2:])) + + def check_critical_evicts_lower_priority(self): + """Check that a CRITICAL recording evicts the WARN ones before an older ERROR one.""" + severities = {'ERR_OLD': SEVERITY_ERROR, 'WARN_A': SEVERITY_WARN, 'WARN_B': SEVERITY_WARN, + 'CRIT_A': SEVERITY_CRITICAL} + with self.fm_run(**{'snapshots.rosbag.max_bags_per_fault': 0, + 'snapshots.rosbag.max_total_storage_mb': 7, + **rules({'severity.WARN.priority': 10, 'severity.ERROR.priority': 50, + 'severity.CRITICAL.priority': 100})}) as fm: + paths = {code: self.record(fm, code, 2, severities=severities) + for code in ('ERR_OLD', 'WARN_A', 'WARN_B')} + critical = self.record(fm, 'CRIT_A', 4, severities=severities) + for code in ('WARN_A', 'WARN_B'): + self.assert_recording_gone(code, paths[code]) + self.assert_recording_present('ERR_OLD', paths['ERR_OLD']) + self.assert_recording_present('CRIT_A', critical) + self.assertLessEqual(storage_bytes(self.storage), 7 * MIB) diff --git a/src/ros2_medkit_fault_manager/test/integration/test_rosbag_quota.test.py b/src/ros2_medkit_fault_manager/test/integration/test_rosbag_quota.test.py index 172b14298..fb3482a92 100644 --- a/src/ros2_medkit_fault_manager/test/integration/test_rosbag_quota.test.py +++ b/src/ros2_medkit_fault_manager/test/integration/test_rosbag_quota.test.py @@ -25,7 +25,9 @@ import pathlib import re import shutil +import signal import sys +import time from launch import LaunchDescription import launch_testing @@ -35,19 +37,22 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) from rosbag_fm_harness import ( # noqa: E402 - bag_dirs, FM_NODE, MESSAGE_SIZE, MIB, poll, RetentionCase, sqlite_exec, Ticker, + bag_dirs, dir_size, FM_NODE, MESSAGE_SIZE, MIB, poll, RetentionCase, rules, + SEVERITY_CRITICAL, SEVERITY_ERROR, SEVERITY_WARN, SIZE_SLACK, sqlite_exec, storage_bytes, + Ticker, ) RACE_REPETITIONS = 50 DISCARDED_BEFORE_STORE = 'Bag file discarded (all its faults cleared before it was stored)' FUTURE_NS = 4_000_000_000 * 1_000_000_000 SLOW_REMOVAL_FILES = 20000 +VICTIM_FILES = 60000 CLEARED_REMOVAL = r'Recording removed: (\S+) \(fault cleared\)' -def make_slow_to_remove(path): +def make_slow_to_remove(path, files=SLOW_REMOVAL_FILES): """Fill `path` with empty files, so its removal outlasts the reading of one log line.""" - for index in range(SLOW_REMOVAL_FILES): + for index in range(files): with open(os.path.join(path, f'pad_{index}'), 'w'): pass @@ -255,6 +260,25 @@ def test_store_failures(self): self.assert_recording_present('STORE_B', second) self.assert_recording_present('STORE_A', first) + with self.subTest('iv: with rules, an eviction fails on the second chosen recording'): + self.new_scratch() + with self.fm_run(**{'snapshots.rosbag.max_bags_per_fault': 0, + 'snapshots.rosbag.max_total_storage_mb': 4, + **rules({'defaults.priority': 10})}) as fm: + paths = {code: self.record(fm, code, 1) + for code in ('STORE_A', 'STORE_B', 'STORE_C')} + self._trigger('fail_delete', 'DELETE', 'STORE_B') + mark = fm.mark() + big = self.record(fm, 'STORE_D', 3) + self.assertIsNotNone( + fm.wait_line(r'Failed to enforce the rosbag storage limit after storing ' + r"'\S*fault_STORE_D_\d+'", since=mark), + fm.output()[-3000:]) + self.assert_recording_gone('STORE_A', paths['STORE_A']) + self.assert_recording_present('STORE_B', paths['STORE_B']) + self.assert_recording_present('STORE_C', paths['STORE_C']) + self.assert_recording_present('STORE_D', big) + def _race(self, **overrides): """Confirm and clear fault after fault; none may keep a row or a directory.""" discarded = 0 @@ -503,3 +527,580 @@ def test_stale_rows(self): self.assertFalse(served.success) self.assertIn('not found on disk', served.error_message) self.assertEqual(self.stored_rows(), []) + + def test_critical_evicts_lower_priority(self): + self.check_critical_evicts_lower_priority() + + def test_new_never_evicts_higher(self): + """A new recording evicts equal or lower priority only, the older one first.""" + quota = {'snapshots.rosbag.max_bags_per_fault': 0, + 'snapshots.rosbag.max_total_storage_mb': 7, + 'snapshots.rosbag.duration_after_sec': 3.0} + severities = {code: SEVERITY_CRITICAL for code in ('CRIT_A', 'CRIT_B', 'CRIT_C')} + severities.update({code: SEVERITY_WARN for code in ('WARN_A', 'WARN_B', 'WARN_C')}) + priorities = rules({'severity.WARN.priority': 10, 'severity.CRITICAL.priority': 100}) + + with self.subTest('equal priority goes, higher stays'): + with self.fm_run(**quota, **priorities) as fm: + crit_a = self.record(fm, 'CRIT_A', 2, severities=severities) + warn_a = self.record(fm, 'WARN_A', 2, severities=severities) + crit_b = self.record(fm, 'CRIT_B', 2, severities=severities) + warn_b = self.record(fm, 'WARN_B', 2, severities=severities) + self.assert_recording_gone('WARN_A', warn_a) + self.assert_recording_present('CRIT_A', crit_a) + self.assert_recording_present('CRIT_B', crit_b) + self.assert_recording_present('WARN_B', warn_b) + + for over_quota in ('keep', 'drop'): + with self.subTest(f'only higher left, new does not fit: {over_quota}'): + self.new_scratch() + params = {**quota, **priorities, + **rules({'severity.WARN.over_quota': over_quota})} + with self.fm_run(**params) as fm: + crit = {code: self.record(fm, code, 2, severities=severities) + for code in ('CRIT_A', 'CRIT_B', 'CRIT_C')} + mark = fm.mark() + path, stored = self.record_growing(fm, 'WARN_A', 2, severities=severities) + for code, bag in crit.items(): + self.assert_recording_present(code, bag) + if over_quota == 'keep': + self.assertTrue(stored) + self.assert_recording_present('WARN_A', path) + self.assertIsNotNone( + fm.wait_line(r'still exceeds snapshots\.rosbag\.max_total_storage_mb ' + r'\(7 MB\)', since=mark), fm.output()[-3000:]) + else: + self.assertFalse(stored) + self.assertFalse(os.path.exists(path)) + self.assertEqual(self.row_paths('WARN_A'), []) + + def test_status_order_when_configured(self): + """Same priority: cleared, then healed, then active. Priority outranks status.""" + quota = {'snapshots.rosbag.max_bags_per_fault': 0, + 'snapshots.rosbag.max_total_storage_mb': 7, + 'snapshots.rosbag.auto_cleanup': False, + 'healing_enabled': True, + 'healing_threshold': 0} + + def fill(fm): + paths = {'ACTIVE': self.record(fm, 'ACTIVE', 2), + 'HEALED': self.record(fm, 'HEALED', 2), + 'CLEARED': self.record(fm, 'CLEARED', 2)} + self.assertTrue(self.client.report_passed('HEALED').accepted) + self.assertTrue(self.client.clear('CLEARED').success) + self.assertEqual(self.client.get_fault('HEALED').fault.status, 'HEALED') + return paths + + with self.subTest('with rules'): + with self.fm_run(**quota, **rules({'defaults.priority': 10})) as fm: + paths = fill(fm) + self.record(fm, 'NEW_1', 2) + self.assert_recording_gone('CLEARED', paths['CLEARED']) + self.assert_recording_present('HEALED', paths['HEALED']) + self.record(fm, 'NEW_2', 2) + self.assert_recording_gone('HEALED', paths['HEALED']) + self.assert_recording_present('ACTIVE', paths['ACTIVE']) + self.record(fm, 'NEW_3', 2) + self.assert_recording_gone('ACTIVE', paths['ACTIVE']) + + with self.subTest('lower priority goes before a higher priority one that is cleared'): + self.new_scratch() + severities = {'HIGH_CLEARED': SEVERITY_ERROR, 'LOW_ACTIVE': SEVERITY_WARN, + 'MID_ACTIVE': SEVERITY_ERROR, 'NEW': SEVERITY_CRITICAL} + with self.fm_run(**quota, **rules({'severity.WARN.priority': 10, + 'severity.ERROR.priority': 50, + 'severity.CRITICAL.priority': 100})) as fm: + high = self.record(fm, 'HIGH_CLEARED', 2, severities=severities) + low = self.record(fm, 'LOW_ACTIVE', 2, severities=severities) + mid = self.record(fm, 'MID_ACTIVE', 2, severities=severities) + self.assertTrue(self.client.clear('HIGH_CLEARED').success) + self.record(fm, 'NEW', 2, severities=severities) + self.assert_recording_gone('LOW_ACTIVE', low) + self.assert_recording_present('HIGH_CLEARED', high) + self.assert_recording_present('MID_ACTIVE', mid) + + with self.subTest('without rules: oldest first'): + self.new_scratch() + with self.fm_run(**quota) as fm: + paths = fill(fm) + self.record(fm, 'NEW_1', 2) + self.assert_recording_gone('ACTIVE', paths['ACTIVE']) + self.assert_recording_present('CLEARED', paths['CLEARED']) + self.assert_recording_present('HEALED', paths['HEALED']) + + def test_prefailed_counts_as_active(self): + """A recording whose fault is PREFAILED outlasts a newer cleared one.""" + with self.fm_run(**{'snapshots.rosbag.max_bags_per_fault': 0, + 'snapshots.rosbag.max_total_storage_mb': 7, + 'snapshots.rosbag.auto_cleanup': False, + 'confirmation_threshold': -3, + **rules({'defaults.priority': 10})}) as fm: + pending = self.record(fm, 'PENDING', 2, reports=3) + cleared = self.record(fm, 'CLEARED_NEWER', 2, reports=3) + self.record(fm, 'ACTIVE_FILL', 2, reports=3) + # A cleared fault that fails once again starts over at PREFAILED. + self.assertTrue(self.client.clear('PENDING').success) + self.assertTrue(self.client.report('PENDING').accepted) + self.assertEqual(self.client.get_fault('PENDING').fault.status, 'PREFAILED') + self.assertTrue(self.client.clear('CLEARED_NEWER').success) + self.record(fm, 'NEW', 2, reports=3) + self.assert_recording_gone('CLEARED_NEWER', cleared) + self.assert_recording_present('PENDING', pending) + + def test_escalation_moves_recordings(self): + """A fault reported again at a higher severity ranks by the severity it has now.""" + severities = {'RISEN': SEVERITY_WARN, 'OTHER_A': SEVERITY_WARN, 'OTHER_B': SEVERITY_WARN, + 'NEW': SEVERITY_ERROR} + with self.fm_run(**{'snapshots.rosbag.max_bags_per_fault': 0, + 'snapshots.rosbag.max_total_storage_mb': 7, + **rules({'severity.WARN.priority': 10, 'severity.ERROR.priority': 50, + 'severity.CRITICAL.priority': 100})}) as fm: + risen = self.record(fm, 'RISEN', 2, severities=severities) + other_a = self.record(fm, 'OTHER_A', 2, severities=severities) + other_b = self.record(fm, 'OTHER_B', 2, severities=severities) + self.assertTrue(self.client.report('RISEN', SEVERITY_CRITICAL).accepted) + self.assertEqual(self.client.get_fault('RISEN').fault.severity, SEVERITY_CRITICAL) + self.record(fm, 'NEW', 2, severities=severities) + self.assert_recording_present('RISEN', risen) + self.assert_recording_gone('OTHER_A', other_a) + self.assert_recording_present('OTHER_B', other_b) + + def test_shared_recording_takes_max_priority(self): + """A burst recording ranks as its most important fault, by the links left after the cap.""" + severities = {'WARN_X': SEVERITY_WARN, 'CRIT_X': SEVERITY_CRITICAL, + 'FILL_A': SEVERITY_WARN, 'FILL_B': SEVERITY_WARN, 'ERR_NEW': SEVERITY_ERROR, + 'ERR_LATE': SEVERITY_ERROR} + with self.fm_run(**{'snapshots.rosbag.max_bags_per_fault': 1, + 'snapshots.rosbag.auto_cleanup': False, + 'snapshots.rosbag.max_total_storage_mb': 7, + 'snapshots.rosbag.duration_after_sec': 3.0, + **rules({'severity.WARN.priority': 10, 'severity.ERROR.priority': 50, + 'severity.CRITICAL.priority': 100})}) as fm: + burst = self.record(fm, 'WARN_X', 2, burst=('CRIT_X',), severities=severities) + fill_a = self.record(fm, 'FILL_A', 2, severities=severities) + fill_b = self.record(fm, 'FILL_B', 2, severities=severities) + + self.record(fm, 'ERR_NEW', 2, severities=severities) + self.assert_recording_present('WARN_X', burst) + self.assert_recording_gone('FILL_A', fill_a) + + # The cap removes the CRITICAL fault's link to the burst; the WARN fault's stays. + self.assertTrue(self.client.clear('CRIT_X').success) + crit_new = self.record(fm, 'CRIT_X', 0.5, severities=severities) + self.assertNotIn(('CRIT_X', burst), self.stored_rows()) + self.assertIn(('WARN_X', burst), self.stored_rows()) + self.assert_recording_present('CRIT_X', crit_new) + + self.record(fm, 'ERR_LATE', 2, severities=severities) + self.assert_recording_gone('WARN_X', burst) + self.assert_recording_present('FILL_B', fill_b) + self.assert_recording_present('CRIT_X', crit_new) + + def test_shared_recording_ranks_after_the_cap_of_the_same_store(self): + """The cap of the store that needs the eviction already counts: the burst ranks as WARN.""" + severities = {'WARN_X': SEVERITY_WARN, 'CRIT_X': SEVERITY_CRITICAL, + 'ERR_FILL': SEVERITY_ERROR} + with self.fm_run(**{'snapshots.rosbag.max_bags_per_fault': 1, + 'snapshots.rosbag.auto_cleanup': False, + 'snapshots.rosbag.max_total_storage_mb': 7, + 'snapshots.rosbag.duration_after_sec': 3.0, + **rules({'severity.WARN.priority': 10, 'severity.ERROR.priority': 50, + 'severity.CRITICAL.priority': 100})}) as fm: + burst = self.record(fm, 'WARN_X', 2, burst=('CRIT_X',), severities=severities) + fill = self.record(fm, 'ERR_FILL', 2, severities=severities) + self.assertTrue(self.client.clear('CRIT_X').success) + # The cap removes CRIT_X's link to the burst in this store, and 7.5 MiB needs room. + fresh = self.record(fm, 'CRIT_X', 3.5, severities=severities) + self.assert_recording_gone('WARN_X', burst) + self.assert_recording_present('ERR_FILL', fill) + self.assert_recording_present('CRIT_X', fresh) + + def test_shared_recording_mixed_status_counts_active(self): + """A burst recording with one cleared and one active fault ranks as active.""" + with self.fm_run(**{'snapshots.rosbag.max_bags_per_fault': 0, + 'snapshots.rosbag.auto_cleanup': False, + 'snapshots.rosbag.max_total_storage_mb': 7, + 'snapshots.rosbag.duration_after_sec': 3.0, + **rules({'defaults.priority': 10})}) as fm: + burst = self.record(fm, 'MIX_A', 2, burst=('MIX_B',)) + plain = self.record(fm, 'MIX_PLAIN', 2) + active = self.record(fm, 'MIX_ACTIVE', 2) + self.assertTrue(self.client.clear('MIX_A').success) + self.assertTrue(self.client.clear('MIX_PLAIN').success) + self.record(fm, 'MIX_NEW', 2) + self.assert_recording_gone('MIX_PLAIN', plain) + self.assert_recording_present('MIX_A', burst) + self.assert_recording_present('MIX_B', burst) + self.assert_recording_present('MIX_ACTIVE', active) + + def test_burst_over_quota_from_highest_priority(self): + """The fault with the highest priority decides whether a burst that cannot fit is kept.""" + base = {'snapshots.rosbag.max_bags_per_fault': 0, + 'snapshots.rosbag.max_total_storage_mb': 3, + 'snapshots.rosbag.duration_after_sec': 5.0} + cases = { + 'a: WARN drop, CRITICAL keep: kept': ( + {'severity.WARN.priority': 10, 'severity.WARN.over_quota': 'drop', + 'severity.CRITICAL.priority': 100, 'severity.CRITICAL.over_quota': 'keep'}, + {'BURST_P': SEVERITY_WARN, 'BURST_Q': SEVERITY_CRITICAL}, True), + 'b: WARN keep, CRITICAL drop: dropped': ( + {'severity.WARN.priority': 10, 'severity.WARN.over_quota': 'keep', + 'severity.CRITICAL.priority': 100, 'severity.CRITICAL.over_quota': 'drop'}, + {'BURST_P': SEVERITY_WARN, 'BURST_Q': SEVERITY_CRITICAL}, False), + 'c: same priority, one keep: kept': ( + {'fault_codes.BURST_P.priority': 50, 'fault_codes.BURST_P.over_quota': 'drop', + 'fault_codes.BURST_Q.priority': 50, 'fault_codes.BURST_Q.over_quota': 'keep'}, + {}, True), + } + for name, (flat, severities, kept) in cases.items(): + with self.subTest(name): + self.new_scratch() + with self.fm_run(**base, **rules(flat)) as fm: + path, stored = self.record_growing(fm, 'BURST_P', 4, others=('BURST_Q',), + severities=severities) + self.assertEqual(stored, kept, fm.output()[-3000:]) + if kept: + self.assert_recording_present('BURST_P', path) + self.assert_recording_present('BURST_Q', path) + else: + self.assertFalse(os.path.exists(path)) + self.assertEqual(self.stored_rows(), []) + + def test_over_quota_from_most_specific_level(self): + """A fault code's own over_quota beats the severity's.""" + with self.fm_run(**{'snapshots.rosbag.max_bags_per_fault': 0, + 'snapshots.rosbag.max_total_storage_mb': 3, + 'snapshots.rosbag.duration_after_sec': 3.0, + **rules({'severity.ERROR.over_quota': 'keep', + 'fault_codes.LEVEL_DROP.over_quota': 'drop'})}) as fm: + kept, kept_stored = self.record_growing(fm, 'LEVEL_KEEP', 4) + self.assertTrue(kept_stored) + dropped, dropped_stored = self.record_growing(fm, 'LEVEL_DROP', 4) + self.assertFalse(dropped_stored) + self.assertFalse(os.path.exists(dropped)) + self.assert_recording_present('LEVEL_KEEP', kept) + self.assertEqual(self.row_paths('LEVEL_DROP'), []) + + def test_oversized_kept_over_quota(self): + """With keep, lower recordings go, a higher one stays and the new one exceeds the quota.""" + severities = {'LOW_A': SEVERITY_WARN, 'LOW_B': SEVERITY_WARN, 'BIG': SEVERITY_CRITICAL} + with self.fm_run(**{'snapshots.rosbag.max_bags_per_fault': 0, + 'snapshots.rosbag.max_total_storage_mb': 5, + **rules({'fault_codes.HIGH.priority': 500, + 'severity.WARN.priority': 10, + 'severity.CRITICAL.priority': 100, + 'severity.CRITICAL.over_quota': 'keep'})}) as fm: + high = self.record(fm, 'HIGH', 1) + lows = {code: self.record(fm, code, 1, severities=severities) + for code in ('LOW_A', 'LOW_B')} + mark = fm.mark() + big = self.record(fm, 'BIG', 5, severities=severities) + self.assertIsNotNone( + fm.wait_line(r'Recording .* \(priority 100\) still exceeds ' + r'snapshots\.rosbag\.max_total_storage_mb \(5 MB\)', since=mark), + 'no warning for the oversized recording:\n' + fm.output()[-3000:]) + for code, path in lows.items(): + self.assert_recording_gone(code, path) + self.assert_recording_present('HIGH', high) + self.assert_recording_present('BIG', big) + self.assertGreater(storage_bytes(self.storage), 5 * MIB) + + def test_oversized_drops_only_itself(self): + """With drop, a recording that outgrows the quota in its post-roll is dropped alone.""" + severities = {'OLD_A': SEVERITY_WARN, 'OLD_B': SEVERITY_WARN, 'GROWS': SEVERITY_CRITICAL} + params = {'snapshots.rosbag.max_bags_per_fault': 0, + 'snapshots.rosbag.max_total_storage_mb': 5, + **rules({'severity.WARN.priority': 10, 'severity.CRITICAL.priority': 100, + 'severity.CRITICAL.over_quota': 'drop'})} + with self.fm_run(**params) as fm: + olds = {code: self.record(fm, code, 1, severities=severities) + for code in ('OLD_A', 'OLD_B')} + + # The window outlasts the test: it ends when the test stops the process. + with self.fm_run(**params, **{'snapshots.rosbag.duration_after_sec': 600.0}) as fm: + known = set(bag_dirs(self.storage)) + mark = fm.mark() + self.client.publish_bytes(1, MESSAGE_SIZE) + self.assertTrue(self.client.report('GROWS', SEVERITY_CRITICAL).accepted) + self.assertIsNotNone( + fm.wait_line(r'Recording [\d.]+s more after fault confirmation', since=mark), + fm.output()[-3000:]) + fresh = [name for name in bag_dirs(self.storage) if name not in known] + self.assertEqual(len(fresh), 1, fresh) + path = os.path.join(self.storage, fresh[0]) + make_slow_to_remove(path) + self.client.publish_bytes(7 * MIB // MESSAGE_SIZE, MESSAGE_SIZE) + self.assertTrue(poll(lambda: dir_size(path) >= 5 * MIB), 'the recording did not grow') + fm.proc.send_signal(signal.SIGTERM) + dropped = r"Recording '\S+' \(\d+ bytes\) dropped" + self.assertIsNotNone(fm.wait_line(dropped, since=mark), fm.output()[-3000:]) + self.assertFalse(os.path.exists(path), f'{path} was still on disk at its log line') + self.assertEqual(fm.wait_exit(), 0, fm.output()[-3000:]) + self.assertEqual(fm.count_lines(dropped, since=mark), 1) + self.assertEqual(fm.count_lines(r'Not recording fault', since=mark), 0) + self.assertEqual(self.row_paths('GROWS'), []) + for code, old in olds.items(): + self.assertTrue(os.path.isdir(old), f'{old} is gone') + self.assertEqual(self.row_paths(code), [old]) + + @staticmethod + def drain_pipe(fifo): + """Read a pipe without blocking. True once its writer has sent data and closed.""" + descriptor = os.open(fifo, os.O_RDONLY | os.O_NONBLOCK) + received = [] + + def finished(): + while True: + try: + chunk = os.read(descriptor, 65536) + except BlockingIOError: + return False + if not chunk: + return bool(received) + received.append(chunk) + + try: + return poll(finished) + finally: + os.close(descriptor) + + def test_refused_open_counts_pending_recordings(self): + """A recording closed but not stored yet still takes room from the next one.""" + params = {'snapshots.rosbag.max_bags_per_fault': 0, + 'snapshots.rosbag.max_total_storage_mb': 5, + 'snapshots.rosbag.duration_after_sec': 3.0, + **rules({'fault_codes.PEND.priority': 100, + 'fault_codes.PEND_DROP.over_quota': 'drop'})} + + with self.subTest('the store has not started'): + with self.fm_run(**params) as fm: + mark = fm.mark() + self.client.publish_bytes(3 * MIB // MESSAGE_SIZE, MESSAGE_SIZE) + self.assertTrue(self.client.report('PEND').accepted) + self.assertIsNotNone( + fm.wait_line(r'Recording [\d.]+s more after fault confirmation', since=mark), + fm.output()[-3000:]) + # The store worker blocks when it writes the manifest, until a reader opens it. + fifo = os.path.join(self.storage, bag_dirs(self.storage)[0], + '.manifest.json.tmp') + os.mkfifo(fifo) + try: + self.assertIsNotNone( + fm.wait_line(r"Post-fault window of 'PEND' closed", since=mark), + fm.output()[-3000:]) + mark = fm.mark() + self.client.publish_bytes(3 * MIB // MESSAGE_SIZE, MESSAGE_SIZE) + self.assertTrue(self.client.report('PEND_DROP').accepted) + self.assertIsNotNone( + fm.wait_line(r"Not recording fault 'PEND_DROP'", since=mark), + fm.output()[-3000:]) + self.assertEqual(len(bag_dirs(self.storage)), 1) + finally: + released = self.drain_pipe(fifo) + self.assertTrue(released, 'the store worker never wrote the manifest') + self.assertIsNotNone(fm.wait_line(r'Bag file completed: \S*fault_PEND_\d+'), + fm.output()[-3000:]) + + with self.subTest('the store has written its rows and still removes its victim'): + self.new_scratch() + with self.fm_run(**params) as fm: + victim = self.record(fm, 'PEND_VICTIM', 2) + make_slow_to_remove(victim, VICTIM_FILES) + mark = fm.mark() + self.client.publish_bytes(3 * MIB // MESSAGE_SIZE, MESSAGE_SIZE) + self.assertTrue(self.client.report('PEND').accepted) + self.assertTrue( + poll(lambda: any(code == 'PEND' for code, _ in self.stored_rows())), + fm.output()[-3000:]) + # The row is stored, its victim is still being removed and PEND is not logged yet. + self.assertTrue(os.path.exists(victim), 'the victim was already removed') + mark = fm.mark() + self.client.publish_bytes(1 * MIB // MESSAGE_SIZE, MESSAGE_SIZE) + self.assertTrue(self.client.report('PEND_DROP').accepted) + done = fm.wait_line(r'Bag file completed: (\S*fault_PEND_DROP_\d+)', since=mark) + self.assertIsNotNone(done, fm.output()[-3000:]) + self.assertEqual(fm.count_lines(r"Not recording fault 'PEND_DROP'", since=mark), 0) + + def test_open_check_counts_the_post_roll(self): + """The estimate adds the post-fault window: a buffer that fits alone is refused.""" + with self.fm_run(**{'snapshots.rosbag.max_total_storage_mb': 5, + 'snapshots.rosbag.duration_sec': 10.0, + 'snapshots.rosbag.duration_after_sec': 10.0, + **rules({'fault_codes.WINDOWED.over_quota': 'drop'})}) as fm: + mark = fm.mark() + self.client.publish_bytes(3 * MIB // MESSAGE_SIZE, MESSAGE_SIZE) + self.assertTrue(self.client.report('WINDOWED').accepted) + self.assertIsNotNone(fm.wait_line(r"Not recording fault 'WINDOWED'", since=mark), + fm.output()[-3000:]) + self.assertEqual(bag_dirs(self.storage), []) + + def test_refused_open_keeps_history(self): + """A recording the quota cannot take is not started and its history serves the next.""" + with self.fm_run(**{'snapshots.rosbag.max_total_storage_mb': 5, + **rules({'fault_codes.HELD.priority': 50, + 'fault_codes.REFUSED.over_quota': 'drop', + 'fault_codes.ADMITTED.over_quota': 'drop'})}) as fm: + held = self.record(fm, 'HELD', 2) + mark = fm.mark() + self.client.publish_bytes(4 * MIB // MESSAGE_SIZE, MESSAGE_SIZE) + self.assertTrue(self.client.report('REFUSED').accepted) + self.assertIsNotNone(fm.wait_line(r"Not recording fault 'REFUSED'", since=mark), + fm.output()[-3000:]) + self.assertEqual(bag_dirs(self.storage), [os.path.basename(held)]) + self.assertEqual(self.row_paths('REFUSED'), []) + + mark = fm.mark() + self.assertTrue(self.client.clear('HELD').success) + self.assertIsNotNone( + fm.wait_line(r"Auto-cleanup: deleted bag file for fault 'HELD'", since=mark), + fm.output()[-3000:]) + mark = fm.mark() + self.assertTrue(self.client.report('ADMITTED').accepted) + done = fm.wait_line(r'Bag file created: (\S*fault_ADMITTED_\d+)', since=mark) + self.assertIsNotNone(done, fm.output()[-3000:]) + self.check_size(done.group(1), 4) + + def test_degraded_quota_is_a_hard_stop(self): + """An invalid retention configuration: nothing is evicted for the quota.""" + invalid = rules({'defaults.priority': -5}) + base = {'snapshots.rosbag.max_bags_per_fault': 1, + 'snapshots.rosbag.max_total_storage_mb': 7, + 'snapshots.rosbag.duration_after_sec': 3.0, **invalid} + + with self.subTest('the quota drops a new recording, the cap frees a repeating fault'): + with self.fm_run(**base, **{'snapshots.rosbag.auto_cleanup': False}) as fm: + self.assertIsNotNone(fm.wait_line(r'Invalid rosbag retention configuration')) + stored = {code: self.record(fm, code, 2) for code in ('DEG_A', 'DEG_B', 'DEG_C')} + path, kept = self.record_growing(fm, 'DEG_NEW', 2) + self.assertFalse(kept) + self.assertFalse(os.path.exists(path)) + for code, bag in stored.items(): + self.assert_recording_present(code, bag) + self.assertEqual(fm.count_lines(r'Deleted old bag'), 0) + + self.assertTrue(self.client.clear('DEG_A').success) + again = self.record(fm, 'DEG_A', 2) + self.assert_recording_gone('DEG_A', stored['DEG_A']) + self.assert_recording_present('DEG_A', again) + self.assert_recording_present('DEG_B', stored['DEG_B']) + self.assert_recording_present('DEG_C', stored['DEG_C']) + + with self.subTest('a clear removes the recording, the open-time check refuses'): + self.new_scratch() + with self.fm_run(**base, **{'snapshots.rosbag.auto_cleanup': True}) as fm: + stored = {code: self.record(fm, code, 2) for code in ('DEG_A', 'DEG_B', 'DEG_C')} + mark = fm.mark() + self.client.publish_bytes(4 * MIB // MESSAGE_SIZE, MESSAGE_SIZE) + self.assertTrue(self.client.report('DEG_REFUSED').accepted) + self.assertIsNotNone( + fm.wait_line(r"Not recording fault 'DEG_REFUSED'", since=mark), + fm.output()[-3000:]) + self.assertEqual(sorted(bag_dirs(self.storage)), + sorted(os.path.basename(p) for p in stored.values())) + + mark = fm.mark() + self.assertTrue(self.client.clear('DEG_B').success) + self.assertIsNotNone( + fm.wait_line(r"Auto-cleanup: deleted bag file for fault 'DEG_B'", since=mark), + fm.output()[-3000:]) + self.assert_recording_gone('DEG_B', stored['DEG_B']) + self.assert_recording_present('DEG_A', stored['DEG_A']) + + @staticmethod + def message_times_ns(bag_path): + import rosbag2_py + reader = rosbag2_py.SequentialReader() + reader.open(rosbag2_py.StorageOptions(uri=bag_path, storage_id='mcap'), + rosbag2_py.ConverterOptions('', '')) + times = [] + while reader.has_next(): + times.append(reader.read_next()[2]) + return times + + def make_open_fail(self, code): + """Make an open of a bag for `code` try every name and fail, without growing setup.""" + os.makedirs(self.storage, exist_ok=True) + self.addCleanup(os.chmod, self.storage, 0o755) + os.chmod(self.storage, 0o555) + probe = os.path.join(self.storage, 'probe') + try: + os.mkdir(probe) + except PermissionError: + return + # A process that ignores permissions: claim every name the open can reach instead, + # always keeping a few seconds of names ahead of the clock. + os.rmdir(probe) + os.chmod(self.storage, 0o755) + stamp = int(time.time() * 1000) - 5 + + def claim_ahead(): + nonlocal stamp + if stamp >= int(time.time() * 1000) + 3000: + return True + for _ in range(500): + os.mkdir(os.path.join(self.storage, f'fault_{code}_{stamp}.claim')) + stamp += 1 + return False + + self.assertTrue(poll(claim_ahead), 'the names were claimed slower than time passes') + + def test_failed_open_keeps_history(self): + """A bag that cannot be opened keeps the ring buffer for the next fault.""" + duration_sec = 3.0 + period_sec = 0.0005 + slack_ns = int(0.5e9) + with self.fm_run(**{'snapshots.rosbag.duration_sec': duration_sec}) as fm, \ + Ticker(self.client, period_sec) as ticker: + self.assertTrue(poll(lambda: ticker.published >= int(duration_sec / period_sec)), + 'the ticker did not fill the ring buffer') + + # The open of the first bag tries every name and fails, with messages arriving. + self.make_open_fail('OPEN_A') + failed_at = time.time_ns() + published = ticker.published + mark = fm.mark() + self.assertTrue(self.client.report('OPEN_A').accepted) + self.assertIsNotNone( + fm.wait_line(r"Failed to create bag file for fault 'OPEN_A'", since=mark), + fm.output()[-3000:]) + os.chmod(self.storage, 0o755) + self.assertGreater(ticker.published, published, 'nothing arrived during the open') + # Counting messages gives a lower bound on the time that passes, at any pace. + later = ticker.published + int((slack_ns / 1e9 + 0.5) / period_sec) + self.assertTrue(poll(lambda: ticker.published >= later)) + + requested_ns = time.time_ns() + mark = fm.mark() + self.assertTrue(self.client.report('OPEN_B').accepted) + done = fm.wait_line(r'Bag file created: (\S*fault_OPEN_B_\d+)', since=mark) + self.assertIsNotNone(done, fm.output()[-3000:]) + oldest = min(self.message_times_ns(done.group(1))) + # Only a restore puts a message from before the failed open into this bag, and the + # restored ones are pruned by age like the rest. + self.assertLess(oldest, failed_at) + self.assertGreaterEqual(oldest, requested_ns - int(duration_sec * 1e9) - slack_ns) + + def test_failed_open_restores_within_the_buffer_limit(self): + """The restored buffer obeys max_buffer_mb together with what arrived meanwhile.""" + with self.fm_run(**{'snapshots.rosbag.max_buffer_mb': 2}) as fm: + ticker = Ticker(self.client, 0.001, MESSAGE_SIZE) + with ticker: + self.assertTrue(poll(lambda: ticker.published >= 100)) + self.make_open_fail('LIMIT_A') + published = ticker.published + mark = fm.mark() + self.assertTrue(self.client.report('LIMIT_A').accepted) + self.assertIsNotNone( + fm.wait_line(r"Failed to create bag file for fault 'LIMIT_A'", since=mark), + fm.output()[-3000:]) + os.chmod(self.storage, 0o755) + self.assertGreater(ticker.published, published, 'nothing arrived during the open') + + mark = fm.mark() + self.assertTrue(self.client.report('LIMIT_B').accepted) + done = fm.wait_line(r'Bag file created: (\S*fault_LIMIT_B_\d+)', since=mark) + self.assertIsNotNone(done, fm.output()[-3000:]) + size = dir_size(done.group(1)) + self.assertLessEqual(size, 2 * MIB + SIZE_SLACK, + 'the restored buffer outgrew its limit') + self.assertGreaterEqual(size, 1.8 * MIB, 'the buffer was not restored') diff --git a/src/ros2_medkit_fault_manager/test/integration/test_rosbag_quota_pg.test.py b/src/ros2_medkit_fault_manager/test/integration/test_rosbag_quota_pg.test.py index 2fb7587b1..f6cf3d76b 100644 --- a/src/ros2_medkit_fault_manager/test/integration/test_rosbag_quota_pg.test.py +++ b/src/ros2_medkit_fault_manager/test/integration/test_rosbag_quota_pg.test.py @@ -79,6 +79,9 @@ def stored_rows(self): def test_quota_evicts_oldest_first(self): self.check_quota_evicts_oldest_first() + def test_critical_evicts_lower_priority(self): + self.check_critical_evicts_lower_priority() + def test_clear_removes_the_row_and_the_directory(self): with self.fm_run() as fm: bag = self.record(fm, 'PG_A', 1) diff --git a/src/ros2_medkit_fault_manager/test/test_rosbag_retention.cpp b/src/ros2_medkit_fault_manager/test/test_rosbag_retention.cpp index e9392dd13..dcb4aa5b0 100644 --- a/src/ros2_medkit_fault_manager/test/test_rosbag_retention.cpp +++ b/src/ros2_medkit_fault_manager/test/test_rosbag_retention.cpp @@ -21,12 +21,14 @@ #include #include #include +#include #include #include #include #include #include +#include "ros2_medkit_fault_manager/core/retention_policy.hpp" #include "ros2_medkit_fault_manager/core/rosbag_retention.hpp" #include "ros2_medkit_fault_manager/fault_storage.hpp" #include "ros2_medkit_fault_manager/sqlite_fault_storage.hpp" @@ -42,6 +44,8 @@ using ros2_medkit_fault_manager::RosbagChangeSet; using ros2_medkit_fault_manager::RosbagFileInfo; using ros2_medkit_fault_manager::SqliteFaultStorage; using ros2_medkit_fault_manager::core::RemovalReason; +using ros2_medkit_fault_manager::core::RetentionMode; +using ros2_medkit_fault_manager::core::RetentionPolicy; using ros2_medkit_fault_manager::core::RosbagRetention; using ros2_medkit_fault_manager::core::RosbagRetentionLimits; using ros2_medkit_fault_manager::core::StoreResult; @@ -153,6 +157,74 @@ class FailingEvictionStorage : public InMemoryFaultStorage { std::string failing_recording_; }; +/// Storage whose reads the quota decision needs fail on demand. +class FailingPolicyReadStorage : public InMemoryFaultStorage { + public: + enum class Fail { kNone, kFault, kAllRows, kTotal }; + + std::optional get_fault(const std::string & fault_code) const override { + if (fail == Fail::kFault) { + throw std::runtime_error("fault read failed"); + } + return InMemoryFaultStorage::get_fault(fault_code); + } + + std::vector get_all_rosbag_files() const override { + if (fail == Fail::kAllRows) { + throw std::runtime_error("all rows read failed"); + } + return InMemoryFaultStorage::get_all_rosbag_files(); + } + + size_t get_total_rosbag_storage_bytes() const override { + if (fail == Fail::kTotal) { + throw std::runtime_error("total read failed"); + } + return InMemoryFaultStorage::get_total_rosbag_storage_bytes(); + } + + RosbagApplyResult apply_rosbag_changes(const RosbagChangeSet & changes) override { + if (fail_apply) { + throw std::runtime_error("apply failed"); + } + return InMemoryFaultStorage::apply_rosbag_changes(changes); + } + + Fail fail{Fail::kNone}; + bool fail_apply{false}; +}; + +/// Keeps every line it is given. +class CapturingLogSink : public ros2_medkit_fault_manager::core::LogSink { + public: + void log(ros2_medkit_fault_manager::core::LogLevel /*level*/, const std::string & /*logger*/, + const std::string & message) override { + std::lock_guard lock(mutex_); + lines.push_back(message); + } + + bool has(const std::string & text) { + std::lock_guard lock(mutex_); + return std::any_of(lines.begin(), lines.end(), [&text](const std::string & line) { + return line.find(text) != std::string::npos; + }); + } + + std::vector lines; + + private: + std::mutex mutex_; +}; + +std::shared_ptr policy_with_over_quota(const std::string & over_quota) { + ros2_medkit_fault_manager::core::FlatParams params; + params["defaults.priority"] = int64_t{10}; + params["defaults.over_quota"] = over_quota; + auto parsed = RetentionPolicy::parse(params); + EXPECT_TRUE(parsed.errors.empty()); + return std::make_shared(std::move(*parsed.policy)); +} + class RosbagRetentionStore : public ::testing::Test { protected: void SetUp() override { @@ -373,4 +445,139 @@ TEST_F(RosbagRetentionStore, AutoCleanupCountsRemovedRows) { EXPECT_TRUE(none.unlink_paths.empty()); } +TEST_F(RosbagRetentionStore, PredictedTotalMatchesStoredTotal) { + // The oldest recording Z is the only one the quota may evict. At a limit equal to the total the + // store leaves it alone; one byte lower, the prediction is over and Z goes. Either way the + // storage then holds exactly the total worked out by hand. + struct Case { + const char * name; + size_t cap; + std::vector seeded; + std::vector incoming; + size_t total; + }; + const auto z = row("Z", "fault_Z_1000", 1000, 400); + const std::vector cases{ + {"plain new recording", 0, {z}, {row("N", "fault_N_5000", 5000, 300)}, 700}, + {"upserted link that grows", + 0, + {z, row("U", "fault_U_2000", 2000, 300)}, + {row("U", "fault_U_2000", 6000, 500)}, + 900}, + {"upserted link that shrinks under a larger sibling row", + 0, + {z, row("U", "fault_U_2000", 2000, 500), row("V", "fault_U_2000", 2500, 500)}, + {row("U", "fault_U_2000", 6000, 300)}, + 900}, + {"upserted link that shrinks", + 0, + {z, row("U", "fault_U_2000", 2000, 500)}, + {row("U", "fault_U_2000", 6000, 300)}, + 700}, + {"the cap removes a path's last link", + 1, + {z, row("O", "fault_O_2000", 2000, 300)}, + {row("O", "fault_O_6000", 6000, 200)}, + 600}, + {"the cap removes the largest row of a path another fault links", + 1, + {z, row("O", "fault_S_2000", 2000, 500), row("P", "fault_S_2000", 2500, 300)}, + {row("O", "fault_O_6000", 6000, 200)}, + 900}, + }; + for (const auto & c : cases) { + for (const bool at_limit : {true, false}) { + SCOPED_TRACE(std::string(c.name) + (at_limit ? ": limit equals the total" : ": limit is one byte lower")); + InMemoryFaultStorage storage; + seed_rosbag_rows(storage, c.seeded); + RosbagRetention retention(storage, limits(c.cap, at_limit ? c.total : c.total - 1), test_log_sink(), kLogger); + retention.set_policy(RetentionMode::kConfigured, policy_with_over_quota("drop")); + + const auto outcome = retention.store(c.incoming); + + EXPECT_EQ(outcome.result, StoreResult::kStored); + EXPECT_FALSE(outcome.quota_failed) << outcome.error; + EXPECT_EQ(listed(outcome.unlink_paths, z.file_path), !at_limit); + EXPECT_EQ(storage.get_total_rosbag_storage_bytes(), at_limit ? c.total : c.total - z.size_bytes); + } + } + + // An upserted link is never dropped, also under drop and over the quota. + InMemoryFaultStorage storage; + seed_rosbag_rows(storage, {z, row("U", "fault_U_2000", 2000, 300)}); + RosbagRetention retention(storage, limits(0, 600), test_log_sink(), kLogger); + retention.set_policy(RetentionMode::kConfigured, policy_with_over_quota("drop")); + const auto outcome = retention.store({row("U", "fault_U_2000", 6000, 900)}); + EXPECT_EQ(outcome.result, StoreResult::kStored); + EXPECT_EQ(storage.get_total_rosbag_storage_bytes(), 900u); + EXPECT_TRUE(listed(outcome.unlink_paths, z.file_path)); +} + +TEST_F(RosbagRetentionStore, PolicyReadFailureFallsBackToInsertAndCap) { + using Fail = FailingPolicyReadStorage::Fail; + for (const auto fail : {Fail::kFault, Fail::kAllRows, Fail::kTotal}) { + SCOPED_TRACE(static_cast(fail)); + FailingPolicyReadStorage storage; + const auto stored = row("Z", "fault_Z_1000", 1000, 500); + seed_rosbag_rows(storage, {stored}); + RosbagRetention retention(storage, limits(0, 600), test_log_sink(), kLogger); + retention.set_policy(RetentionMode::kConfigured, policy_with_over_quota("drop")); + storage.fail = fail; + const auto fresh = row("N", "fault_N_2000", 2000, 500); + + const auto outcome = retention.store({fresh}); + + EXPECT_EQ(outcome.result, StoreResult::kStored); + EXPECT_TRUE(outcome.quota_failed); + EXPECT_NE(outcome.error.find("read failed"), std::string::npos) << outcome.error; + EXPECT_TRUE(outcome.unlink_paths.empty()); + storage.fail = Fail::kNone; + EXPECT_EQ(storage.get_rosbag_files("N").size(), 1u) << "the rows were not stored"; + EXPECT_EQ(storage.get_rosbag_files("Z").size(), 1u) << "a recording was evicted without a decision"; + } + + // The fallback applies the cap with the insert: the stored row of the same fault goes. The cap + // leaves the total under the quota, so only the total and the all-rows read are needed. + { + for (const auto fail : {Fail::kAllRows, Fail::kTotal}) { + SCOPED_TRACE(static_cast(fail)); + FailingPolicyReadStorage storage; + const auto old_row = row("Z", "fault_Z_1000", 1000, 500); + seed_rosbag_rows(storage, {old_row}); + RosbagRetention retention(storage, limits(1, 600), test_log_sink(), kLogger); + retention.set_policy(RetentionMode::kConfigured, policy_with_over_quota("drop")); + storage.fail = fail; + const auto fresh = row("Z", "fault_Z_2000", 2000, 500); + + const auto outcome = retention.store({fresh}); + + EXPECT_EQ(outcome.result, StoreResult::kStored); + EXPECT_TRUE(outcome.quota_failed); + EXPECT_TRUE(listed(outcome.unlink_paths, old_row.file_path)) << "the cap did not free the old recording"; + storage.fail = Fail::kNone; + const auto rows = storage.get_rosbag_files("Z"); + ASSERT_EQ(rows.size(), 1u); + EXPECT_EQ(rows[0].file_path, fresh.file_path); + } + } + + // A failing apply is a store failure, and only that is logged. + { + FailingPolicyReadStorage storage; + seed_rosbag_rows(storage, {row("Z", "fault_Z_1000", 1000, 500)}); + CapturingLogSink sink; + RosbagRetention retention(storage, limits(0, 600), sink, kLogger); + retention.set_policy(RetentionMode::kConfigured, policy_with_over_quota("drop")); + storage.fail = FailingPolicyReadStorage::Fail::kTotal; + storage.fail_apply = true; + + const auto outcome = retention.store({row("N", "fault_N_2000", 2000, 500)}); + + EXPECT_EQ(outcome.result, StoreResult::kStoreFailed); + EXPECT_FALSE(outcome.quota_failed); + EXPECT_NE(outcome.error.find("apply failed"), std::string::npos) << outcome.error; + EXPECT_FALSE(sink.has("Failed to enforce the rosbag storage limit")) << "a store that failed claimed a fallback"; + } +} + } // namespace diff --git a/src/ros2_medkit_integration_tests/test/features/test_rosbag_retention_priority.test.py b/src/ros2_medkit_integration_tests/test/features/test_rosbag_retention_priority.test.py new file mode 100644 index 000000000..f0d616ee1 --- /dev/null +++ b/src/ros2_medkit_integration_tests/test/features/test_rosbag_retention_priority.test.py @@ -0,0 +1,214 @@ +#!/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. + +"""Rosbag retention by priority, seen through the gateway's bulk-data list. + +The fault manager runs with severity rules and a quota of a few recordings. An ERROR and a WARN +recording fill it, a CRITICAL fault arrives and the WARN recording is evicted, not the older ERROR +one. A fault whose rule says ``over_quota: drop`` is refused when it cannot fit and is not listed. +The result is read from ``GET /apps//bulk-data/rosbags``. +""" + +import os +import re +import shutil +import tempfile +import time +import unittest + +import launch_testing +import rclpy +from rclpy.duration import Duration +from rclpy.node import Node +from rclpy.qos import HistoryPolicy, QoSProfile, ReliabilityPolicy +from ros2_medkit_msgs.msg import Fault +from ros2_medkit_msgs.srv import ReportFault + +from ros2_medkit_test_utils.constants import ALLOWED_EXIT_CODES +from ros2_medkit_test_utils.gateway_test_case import GatewayTestCase +from ros2_medkit_test_utils.launch_helpers import create_test_launch + +from std_msgs.msg import UInt8MultiArray + +PAYLOAD_TOPIC = '/e2e/retention_payload' +APP_ENDPOINT = '/apps/lidar_sensor' +SOURCE_FQN = '/perception/lidar/lidar_sensor' +LIDAR_OWN_FAULT = 'LIDAR_CALIBRATION_REQUIRED' +MESSAGE_BYTES = 128 * 1024 +MIB = 1024 * 1024 +QUOTA_MB = 3 + +ROSBAG_STORAGE_PATH = tempfile.mkdtemp(prefix='rosbag_e2e_retention_') + + +def generate_test_description(): + return create_test_launch( + demo_nodes=['lidar_sensor'], + # Healthy lidar: the test reports every fault itself. + lidar_faulty=False, + fault_manager=True, + fault_manager_params={ + 'confirmation_threshold': -1, + 'snapshots.rosbag.duration_sec': 60.0, + 'snapshots.rosbag.duration_after_sec': 2.0, + 'snapshots.rosbag.include_topics': [PAYLOAD_TOPIC], + 'snapshots.rosbag.format': 'mcap', + 'snapshots.rosbag.storage_path': ROSBAG_STORAGE_PATH, + 'snapshots.rosbag.max_bags_per_fault': 0, + 'snapshots.rosbag.max_total_storage_mb': QUOTA_MB, + 'snapshots.rosbag.retention.severity.WARN.priority': 10, + 'snapshots.rosbag.retention.severity.ERROR.priority': 50, + 'snapshots.rosbag.retention.severity.CRITICAL.priority': 100, + 'snapshots.rosbag.retention.fault_codes.E2E_DROP.over_quota': 'drop', + 'snapshots.rosbag.retention.fault_codes.E2E_GROWS.over_quota': 'drop', + }, + ) + + +class TestRosbagRetentionPriority(GatewayTestCase): + """A CRITICAL recording evicts WARN ones; a refused recording is not listed.""" + + MIN_EXPECTED_APPS = 1 + REQUIRED_APPS = {'lidar_sensor'} + + @classmethod + def setUpClass(cls): + # The publisher exists before the gateway wait: the explicit-topic capture only retries + # type discovery for a short time after startup. + rclpy.init() + cls.driver = Node('retention_priority_driver') + qos = QoSProfile(reliability=ReliabilityPolicy.RELIABLE, history=HistoryPolicy.KEEP_LAST, + depth=500) + cls.payload_pub = cls.driver.create_publisher(UInt8MultiArray, PAYLOAD_TOPIC, qos) + cls.report_client = cls.driver.create_client( + ReportFault, '/fault_manager/report_fault') + super().setUpClass() + assert cls.report_client.wait_for_service(timeout_sec=20.0), \ + 'report_fault service not available' + deadline = time.time() + 15.0 + while (not cls.driver.get_subscriptions_info_by_topic(PAYLOAD_TOPIC) + and time.time() < deadline): + rclpy.spin_once(cls.driver, timeout_sec=0.2) + assert cls.driver.get_subscriptions_info_by_topic(PAYLOAD_TOPIC), \ + 'fault_manager never subscribed to the payload topic' + + @classmethod + def tearDownClass(cls): + cls.driver.destroy_node() + rclpy.shutdown() + super().tearDownClass() + + def _publish(self, mib): + for _ in range(int(mib * MIB) // MESSAGE_BYTES): + msg = UInt8MultiArray() + msg.data = list(os.urandom(MESSAGE_BYTES)) + self.payload_pub.publish(msg) + self.assertTrue(self.payload_pub.wait_for_all_acked(Duration(seconds=30)), + 'the payload was not acknowledged by the fault manager') + + def _report(self, fault_code, severity): + request = ReportFault.Request() + request.fault_code = fault_code + request.event_type = ReportFault.Request.EVENT_FAILED + request.severity = severity + request.description = 'retention e2e' + request.source_id = SOURCE_FQN + future = self.report_client.call_async(request) + rclpy.spin_until_future_complete(self.driver, future, timeout_sec=10.0) + self.assertIsNotNone(future.result(), 'report_fault call timed out') + self.assertTrue(future.result().accepted) + + def _listed_faults(self): + listing = self.get_json(f'{APP_ENDPOINT}/bulk-data/rosbags') + return {code for item in listing.get('items', []) + for code in item.get('x-medkit', {}).get('fault_codes', [])} + + def _wait_listed(self, predicate, what): + self.poll_endpoint_until( + f'{APP_ENDPOINT}/bulk-data/rosbags', + lambda listing: predicate({ + code for item in listing.get('items', []) + for code in item.get('x-medkit', {}).get('fault_codes', [])}), + timeout=30.0) + self.assertTrue(predicate(self._listed_faults()), what) + + def test_01_critical_evicts_the_lowest_priority_recording(self): + """A CRITICAL recording evicts the WARN one, not the older ERROR one. + + @verifies REQ_INTEROP_072 + """ + # The demo node reports a fault of its own at startup. Its listing means the faults + # below meet an idle capture. + self._wait_listed(lambda faults: LIDAR_OWN_FAULT in faults, + 'the demo node recording never finished') + self._publish(1) + self._report('E2E_ERROR', Fault.SEVERITY_ERROR) + self._wait_listed(lambda faults: 'E2E_ERROR' in faults, 'ERROR was not recorded') + self._publish(1) + self._report('E2E_WARN', Fault.SEVERITY_WARN) + self._wait_listed(lambda faults: {'E2E_ERROR', 'E2E_WARN'} <= faults, + 'WARN was not recorded') + + self._publish(1.5) + self._report('E2E_CRITICAL', Fault.SEVERITY_CRITICAL) + self._wait_listed(lambda faults: 'E2E_CRITICAL' in faults and 'E2E_WARN' not in faults, + 'the WARN recording was not evicted for the CRITICAL one') + listed = self._listed_faults() + self.assertIn('E2E_ERROR', listed, 'the older, more important recording was evicted') + self.assertNotIn('E2E_WARN', listed) + + def test_02_a_recording_that_outgrows_the_quota_is_dropped_at_the_store(self, proc_output): + """A drop recording that passed the open-time check is dropped when it is stored. + + @verifies REQ_INTEROP_072 + """ + self._publish(0.125) + self._report('E2E_GROWS', Fault.SEVERITY_WARN) + proc_output.assertWaitFor( + "fault 'E2E_GROWS' confirmed, flushing buffer to bag", timeout=30) + self._publish(2) + proc_output.assertWaitFor( + re.compile(r"fault_E2E_GROWS_\d+' \(\d+ bytes\) dropped"), timeout=30) + listed = self._listed_faults() + self.assertNotIn('E2E_GROWS', listed) + self.assertIn('E2E_CRITICAL', listed) + self.assertIn('E2E_ERROR', listed) + + def test_03_a_refused_recording_is_not_listed(self, proc_output): + """A recording that cannot fit under over_quota drop is refused and not listed. + + @verifies REQ_INTEROP_072 + """ + self._publish(3.5) + self._report('E2E_DROP', Fault.SEVERITY_WARN) + proc_output.assertWaitFor("Not recording fault 'E2E_DROP'", timeout=30) + listed = self._listed_faults() + self.assertNotIn('E2E_DROP', listed) + self.assertIn('E2E_CRITICAL', listed) + self.assertIn('E2E_ERROR', listed) + + +@launch_testing.post_shutdown_test() +class TestShutdown(unittest.TestCase): + """Post-shutdown checks.""" + + def test_exit_codes(self, proc_info): + """Gateway and fault manager exit cleanly.""" + launch_testing.asserts.assertExitCodes( + proc_info, allowable_exit_codes=ALLOWED_EXIT_CODES) + + def test_cleanup_temp_directory(self): + """Remove this run's bag storage.""" + shutil.rmtree(ROSBAG_STORAGE_PATH, ignore_errors=True)