From 7f381ec5263c70aa4007eb865e126acee12c2475 Mon Sep 17 00:00:00 2001 From: Bartosz Burda Date: Tue, 1 Dec 2026 14:41:02 +0100 Subject: [PATCH] fault_manager: make all rosbag retention decisions in one component * test(fault_manager): pin that a shutdown inside a post-roll removes the recording its cap replaced * feat(fault_manager): make every rosbag retention decision in one component * fix(fault_manager): log each recording removal after it happened * fix(fault_manager): remove and log every recording through one helper * fix(fault_manager): log a removal only when something was removed --- src/ros2_medkit_fault_manager/CMakeLists.txt | 6 + src/ros2_medkit_fault_manager/README.md | 6 +- .../design/index.rst | 60 ++- .../core/rosbag_retention.hpp | 138 +++++++ .../fault_manager_node.hpp | 10 + .../fault_storage.hpp | 88 +--- .../postgres_fault_storage.hpp | 17 - .../retention_worker.hpp | 87 ++++ .../rosbag_capture.hpp | 74 ++-- .../sqlite_fault_storage.hpp | 23 +- .../src/core/fault_manager_startup.cpp | 6 - .../src/core/rosbag_retention.cpp | 330 +++++++++++++++ .../src/fault_manager_node.cpp | 21 +- .../src/fault_storage.cpp | 161 +------- .../src/postgres_fault_storage.cpp | 217 ---------- .../src/retention_worker.cpp | 161 ++++++++ .../src/rosbag_capture.cpp | 207 +++------- .../src/sqlite_fault_storage.cpp | 266 +------------ .../integration/test_rosbag_quota.test.py | 174 +++++++- .../integration/test_rosbag_quota_pg.test.py | 7 +- .../test/test_fault_manager.cpp | 65 +-- .../test/test_postgres_storage.cpp | 205 +++------- .../test/test_rosbag_capture.cpp | 263 ++++++------ .../test/test_rosbag_retention.cpp | 376 ++++++++++++++++++ .../test/test_rosbag_rows.hpp | 65 +++ .../test/test_rosbag_storage_parity.cpp | 349 +++++++++++----- .../test/test_sqlite_storage.cpp | 218 ++++------ 27 files changed, 2071 insertions(+), 1529 deletions(-) create mode 100644 src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/core/rosbag_retention.hpp create mode 100644 src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/retention_worker.hpp create mode 100644 src/ros2_medkit_fault_manager/src/core/rosbag_retention.cpp create mode 100644 src/ros2_medkit_fault_manager/src/retention_worker.cpp create mode 100644 src/ros2_medkit_fault_manager/test/test_rosbag_retention.cpp create mode 100644 src/ros2_medkit_fault_manager/test/test_rosbag_rows.hpp diff --git a/src/ros2_medkit_fault_manager/CMakeLists.txt b/src/ros2_medkit_fault_manager/CMakeLists.txt index b82f4e734..38933c6a6 100644 --- a/src/ros2_medkit_fault_manager/CMakeLists.txt +++ b/src/ros2_medkit_fault_manager/CMakeLists.txt @@ -124,6 +124,7 @@ set(FAULT_MANAGER_FILES src/capture_thread_pool.cpp src/fault_manager_node.cpp src/pending_topic_watcher.cpp + src/retention_worker.cpp src/snapshot_capture.cpp src/rosbag_capture.cpp src/ros2/fault_msg_conversions.cpp @@ -220,6 +221,11 @@ endif() target_link_libraries(test_rosbag_storage_parity fault_manager_lib) medkit_target_dependencies(test_rosbag_storage_parity rclcpp ros2_medkit_msgs) + # Rosbag retention decisions under failing and gated storage. Creates no ROS node. + medkit_add_gtest(test_rosbag_retention test/test_rosbag_retention.cpp) + target_link_libraries(test_rosbag_retention fault_manager_lib) + medkit_test_needs_no_domain(test_rosbag_retention) + # Fault audit log tests (hash chain, verify, rotation, reopen) medkit_add_gtest(test_fault_audit_log test/test_fault_audit_log.cpp) target_link_libraries(test_fault_audit_log fault_manager_lib) diff --git a/src/ros2_medkit_fault_manager/README.md b/src/ros2_medkit_fault_manager/README.md index 47d2cc55e..34906d479 100644 --- a/src/ros2_medkit_fault_manager/README.md +++ b/src/ros2_medkit_fault_manager/README.md @@ -574,6 +574,9 @@ 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 + the directories to remove and never removes one itself. The core reaches the outside through four interfaces. The ROS adapter implements them. @@ -597,7 +600,8 @@ The core returns `ros2_medkit::fault_detection` values (`FaultRecord`, `FaultEve nanosecond times. **ROS adapter** (`fault_manager_lib` and `fault_manager_node`): the services, the `FaultEvent` -publisher, wall timers that call `tick`, the capture thread pool, snapshot and rosbag capture. It +publisher, wall timers that call `tick`, the capture thread pool, snapshot and rosbag capture, and +the `RetentionWorker` thread that removes the directories of cleared and stale recordings. It implements the four interfaces: `ros2::RosEventSink`, `ros2::RosCaptureHooks`, `ros2::SystemWallClock` and `ros2::RosLogSink`. It converts between the core values and the messages in `ros2/fault_msg_conversions.hpp`. diff --git a/src/ros2_medkit_fault_manager/design/index.rst b/src/ros2_medkit_fault_manager/design/index.rst index cce9b5cfc..e473718ff 100644 --- a/src/ros2_medkit_fault_manager/design/index.rst +++ b/src/ros2_medkit_fault_manager/design/index.rst @@ -552,4 +552,62 @@ inserted row's recording id. The call throws ``std::invalid_argument`` before it With that rule, applying a set twice leaves the same rows and the second call returns no orphaned paths. -Production code does not call it yet. The six existing rosbag mutators keep serving the node. +It is the only write of the rosbag rows. The retention below makes every decision on top of it. + +Rosbag retention +"""""""""""""""" + +``core::RosbagRetention`` holds every rosbag retention decision, each under one retention mutex: + +- ``store``: drops the rows of faults the storage holds as cleared (``auto_cleanup`` with a + ``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. +- ``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 + ``GetRosbag`` and ``ListRosbags``. The node builds the retention also with rosbag capture off, + so this cleanup runs then too. + +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 +retention mutex only storage calls and logging run. No other lock is taken and no file system +call runs. + +The retention never unlinks and logs no removal. Each call returns the directories no row names +any more, each with its recording id and the reason it was freed. Which thread removes them +depends on the path: + +- Store (the store worker, or the capture pool when there is no post-fault window): the store's + own thread removes the cap victims, a new recording that lost the cap and the quota evictions, + once the retention mutex is released and before "Bag file created" or "Bag file completed" is + logged. The executor never runs a store. A bag that never got a row is discarded on the same + thread. +- Clear and stale rows (the executor): the rows go inside the service call. The node's + ``RetentionWorker``, one thread with a FIFO queue, removes the directories, so the clear service + returns before a large bag is removed. + +Every path removes a directory through ``RetentionWorker::remove_recording()``, which logs the +removal after it succeeded. No line announces a removal that has not happened yet: + +- a cap victim: ``Recording removed: (max_bags_per_fault)``; +- a recording of a cleared fault: ``Recording removed: (fault cleared)``; +- a quota eviction: ``Deleted old bag '' to enforce storage limit``; +- a stale row: no line, because its directory was already missing; +- a removal that failed: a WARN with the path, the reason and the error. + +A removal that found no directory removed nothing and logs no line. + +A clear logs ``Auto-cleanup: deleted bag file for fault ''`` once, after the lines of its +recordings, when all of them are gone. It logs it at once when a sibling of the burst still holds +the bag. + +The node shuts down in this order: the capture pool, then ``RosbagCapture::stop()``, which +finalizes an open post-fault window and stores it, then ``RetentionWorker::drain_and_stop()``, +which runs the removals the clear and stale-row paths posted. A ``RosbagCapture`` constructed +without a retention builds its own, with an inline worker that removes on the clearing thread. + +All fault manager service callbacks run on one executor thread (``rclcpp::spin`` in +``main.cpp``). A change to a multi-threaded executor must revisit which retention decisions need +the core mutex. 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 new file mode 100644 index 000000000..2c3eb5b69 --- /dev/null +++ b/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/core/rosbag_retention.hpp @@ -0,0 +1,138 @@ +// 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. + +#pragma once + +#include +#include +#include +#include +#include + +#include "ros2_medkit_fault_manager/core/log_sink.hpp" +#include "ros2_medkit_fault_manager/fault_storage.hpp" + +namespace ros2_medkit_fault_manager::core { + +/// Retention settings of the rosbag recordings (`snapshots.rosbag.*`). +struct RosbagRetentionLimits { + size_t max_bags_per_fault{1}; ///< Recordings kept per fault code, 0 = unlimited + size_t max_total_bytes{500ULL * 1024 * 1024}; ///< Quota over every recording + bool auto_cleanup{true}; ///< A cleared fault loses its recordings +}; + +/// Why a recording's directory is no longer named by any row. +enum class RemovalReason { + kCap, ///< The per-fault cap (max_bags_per_fault) + kQuota, ///< The quota (max_total_storage_mb) + kCleared, ///< The fault was cleared (auto_cleanup) + kStale, ///< The directory was already missing +}; + +/// A directory no row names any more: the caller removes it and logs the removal. +struct FreedRecording { + std::string path; + std::string recording_id; + RemovalReason reason{RemovalReason::kCap}; +}; + +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. +}; + +struct StoreOutcome { + StoreResult result{StoreResult::kStored}; + /// 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 + /// Directories no row names any more, each path once. Never the path of a recording that + /// kAllFaultsCleared or kStoreFailed left without rows: the caller discards that one. + std::vector unlink_paths; +}; + +struct RemovalOutcome { + size_t removed_rows{0}; + std::vector unlink_paths; ///< Directories no row names any more, each path once +}; + +/// Every rosbag retention decision of the fault manager, on FaultStorage::apply_rosbag_changes(). +/// +/// Each public method holds one mutex for its whole decision. Lock order: the caller's outer +/// locks -> this mutex -> the storage's own lock. Under it only storage calls and logging run: +/// no other lock and no file system call. Nothing here unlinks a file or logs a removal. Each +/// method returns the directories the caller removes, with the reason it logs after each removal. +class RosbagRetention { + public: + RosbagRetention(FaultStorage & storage, RosbagRetentionLimits limits, LogSink & log_sink, std::string logger_name); + + RosbagRetention(const RosbagRetention &) = delete; + RosbagRetention & operator=(const RosbagRetention &) = delete; + RosbagRetention(RosbagRetention &&) = delete; + RosbagRetention & operator=(RosbagRetention &&) = delete; + ~RosbagRetention() = default; + + /// 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. + /// 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. + StoreOutcome store(std::vector rows); + + /// Evict whole recordings, oldest first, until the total is at or under @p max_bytes. Never + /// evicts @p keep_recording_id. + /// @throws the first storage failure; the evictions before it stay applied + /// @return The paths to unlink, in eviction order + std::vector evict_over_quota(size_t max_bytes, const std::string & keep_recording_id = {}); + + /// Remove every row of @p fault_code. The caller decides whether a clear removes recordings. + /// @throws the storage failure; no row changed then + RemovalOutcome on_fault_cleared(const std::string & fault_code); + + /// Remove every row of a recording whose directory is gone. + /// @throws the storage failure; no row changed then + RemovalOutcome forget_recording(const std::string & recording_id); + + private: + struct Eviction { + std::vector unlink_paths; + }; + + /// 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); + + /// The insert and the per-fault cap removals of @p rows, as one change set. Fills + /// @p recording_ids with the recording id of every path it read or was given. + /// @throws a failure of the cap read + RosbagChangeSet cap_changes(const std::vector & rows, + std::unordered_map & recording_ids); + + /// Quota eviction. @p out holds what was applied, also when this throws. + void evict(size_t max_bytes, const std::string & keep_recording_id, Eviction & out); + + /// Apply @p changes and count @p rows as removed. Each freed path takes its recording id from + /// @p rows and the reason @p reason. + RemovalOutcome remove(const std::vector & rows, const RosbagChangeSet & changes, + RemovalReason reason); + + FaultStorage & storage_; + const RosbagRetentionLimits limits_; + LogSink & log_sink_; + const std::string logger_name_; + std::mutex mutex_; +}; + +} // namespace ros2_medkit_fault_manager::core diff --git a/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/fault_manager_node.hpp b/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/fault_manager_node.hpp index fa1f61e17..eae7abf8c 100644 --- a/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/fault_manager_node.hpp +++ b/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/fault_manager_node.hpp @@ -25,9 +25,11 @@ #include "ros2_medkit_fault_manager/capture_thread_pool.hpp" #include "ros2_medkit_fault_manager/core/fault_manager_config.hpp" #include "ros2_medkit_fault_manager/core/fault_manager_core.hpp" +#include "ros2_medkit_fault_manager/core/rosbag_retention.hpp" #include "ros2_medkit_fault_manager/correlation/correlation_engine.hpp" #include "ros2_medkit_fault_manager/fault_audit_log.hpp" #include "ros2_medkit_fault_manager/fault_storage.hpp" +#include "ros2_medkit_fault_manager/retention_worker.hpp" #include "ros2_medkit_fault_manager/ros2/ros_capture_hooks.hpp" #include "ros2_medkit_fault_manager/ros2/ros_event_sink.hpp" #include "ros2_medkit_fault_manager/ros2/ros_log_sink.hpp" @@ -223,6 +225,14 @@ class FaultManagerNode : public rclcpp::Node { /// shared_ptr to allow safe capture-by-value in the pool's capture jobs. std::shared_ptr snapshot_capture_; + /// Removes the directories a clear or a stale-row cleanup frees, off the executor. Drained at shutdown + /// after rosbag_capture_->stop(). + std::shared_ptr retention_worker_; + + /// Rosbag retention decisions. Built also with rosbag capture off: the stale-row cleanup of + /// GetRosbag and ListRosbags runs then too. + std::shared_ptr rosbag_retention_; + /// Rosbag capture for time-window recording (nullptr if disabled). /// shared_ptr to allow safe capture-by-value in the pool's capture jobs. std::shared_ptr rosbag_capture_; diff --git a/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/fault_storage.hpp b/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/fault_storage.hpp index 56d185398..84d32fcc6 100644 --- a/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/fault_storage.hpp +++ b/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/fault_storage.hpp @@ -295,20 +295,6 @@ class FaultStorage { virtual void set_max_snapshots_per_fault(size_t /*max_count*/) { } - /// Cap on RECORDINGS retained per fault code (0 = unlimited). - /// - /// Enforced inside store_rosbag_file(s), atomically with the insert: past the cap - /// the fault's OLDEST recordings lose their row, and a bag whose last referencing - /// row goes is unlinked once the store is durable. - /// - /// Keep-newest, the same direction as set_max_snapshots_per_fault. The two caps - /// differ in unit, not in policy: that one evicts whole capture SETS, this one - /// evicts RECORDINGS. A bag is evidence about a machine you are about to inspect, - /// so the recent one wins; and keep-newest at 1 is exactly the pre-#620 - /// behaviour, which is what makes the default a no-op. - virtual void set_max_rosbags_per_fault(size_t /*max_count*/) { - } - /// Whether acknowledging a fault keeps the value snapshots it captured. /// /// Off by default, which is the historical behaviour: clear_fault deletes them. @@ -398,30 +384,8 @@ class FaultStorage { /// @return The retained near-miss entries in chronological order virtual std::vector get_near_misses(const std::string & fault_code) const = 0; - /// Store rosbag file metadata for a fault - /// @param info The rosbag file info to store (replaces any existing entry for fault_code) - virtual void store_rosbag_file(const RosbagFileInfo & info) = 0; - - /// Store one row per fault of a burst that shares a recording. - /// - /// Implementations MUST be all-or-nothing. The caller treats a throw as "no row - /// was written" and discards the recording, so a batch that stored some rows and - /// then threw would leave those rows naming a bag that has just been removed: - /// unreadable for good, and still charged against the storage quota, which sums - /// rows. Both in-tree backends satisfy this - SQLite through a transaction, the - /// in-memory one by publishing the whole batch at once. - /// - /// The default below does NOT satisfy it and exists only so a backend that cannot - /// fail per row keeps compiling. Override it in anything that can. - /// - /// @param infos The rows to store (typically all pointing at one file_path) - virtual void store_rosbag_files(const std::vector & infos) { - for (const auto & info : infos) { - store_rosbag_file(info); - } - } - - /// Apply a set of rosbag row changes in one transaction. + /// Apply a set of rosbag row changes in one transaction. The only write of the rosbag rows; + /// core::RosbagRetention makes every retention decision on top of it. /// /// - All or nothing: when anything throws, no row has changed. /// - Applies no per-fault cap. @@ -451,35 +415,6 @@ class FaultStorage { /// start from a recording id and need the faults behind it. virtual std::vector get_rosbag_files_by_recording(const std::string & recording_id) const = 0; - /// Delete one whole recording: every fault's link to it, and the bag. This is the - /// right unit for quota eviction and for a bag that has vanished from disk - both - /// are facts about the recording, not about one fault that happens to reference it. - /// @return number of rows removed - virtual size_t delete_rosbag_recording(const std::string & recording_id) = 0; - - /// Delete rosbag file record and the actual file for a fault. Faults from one - /// burst can share a recording; the file is unlinked only with the last record - /// that references it. - /// @param fault_code The fault code to delete rosbag for - /// @return true if record was deleted, false if not found - virtual bool delete_rosbag_file(const std::string & fault_code) = 0; - - /// Delete the records of several faults (typically the whole burst behind one - /// recording). Backends with real transactions (SQLite) remove the rows - /// atomically and unlink the file only after the commit, so a crash mid-delete - /// never leaves a row pointing at a removed bag. Default: plain loop. - /// @param fault_codes The fault codes to delete rosbag records for - /// @return Number of records actually deleted - virtual size_t delete_rosbag_files(const std::vector & fault_codes) { - size_t deleted = 0; - for (const auto & code : fault_codes) { - if (delete_rosbag_file(code)) { - ++deleted; - } - } - return deleted; - } - /// Get total size of all stored rosbag files in bytes, counting a shared /// recording once regardless of how many faults reference it /// @return Total size in bytes @@ -558,21 +493,13 @@ class InMemoryFaultStorage : public FaultStorage { void store_freeze_frame(const FreezeFrameData & frame) override; std::optional get_freeze_frame(const std::string & fault_code) const override; - void set_max_rosbags_per_fault(size_t max_count) override; - size_t set_max_near_misses_per_fault(size_t max_count) override; std::vector get_near_misses(const std::string & fault_code) const override; - void store_rosbag_file(const RosbagFileInfo & info) override; - /// All-or-nothing, as the base class requires: the batch is built beside the live - /// map and swapped in, so a throw leaves the store exactly as it was. - void store_rosbag_files(const std::vector & infos) override; RosbagApplyResult apply_rosbag_changes(const RosbagChangeSet & changes) override; std::optional get_rosbag_file(const std::string & fault_code) const override; std::vector get_rosbag_files(const std::string & fault_code) const override; std::vector get_rosbag_files_by_recording(const std::string & recording_id) const override; - bool delete_rosbag_file(const std::string & fault_code) override; - size_t delete_rosbag_recording(const std::string & recording_id) override; size_t get_total_rosbag_storage_bytes() const override; std::vector get_all_rosbag_files() const override; std::vector list_rosbags_for_entity(const std::string & entity_fqn) const override; @@ -588,13 +515,6 @@ class InMemoryFaultStorage : public FaultStorage { void record_near_miss(const FaultState & state, const DebounceConfig & config, uint8_t severity, const std::string & source_id, int64_t timestamp_ns); - /// Whether a fault other than @p fault_code still references @p file_path. - /// One recording can back several faults of the same burst, so the bag must - /// only be unlinked once the last of them is gone. Caller holds mutex_. - - /// Whether any row at all still references @p file_path. Caller holds mutex_. - bool path_referenced(const std::string & file_path) const; - mutable std::mutex mutex_; std::map faults_; std::vector snapshots_; @@ -614,10 +534,6 @@ class InMemoryFaultStorage : public FaultStorage { }; std::vector rosbag_files_; uint64_t rosbag_seq_{0}; - /// Defaults to 1, the pre-#620 behaviour: a new recording replaces the old one. - /// A backend constructed directly (tests, embedders) therefore behaves exactly as - /// it always did until someone opts into a history. 0 = unlimited. - size_t max_rosbags_per_fault_{1}; std::map> near_misses_; ///< fault_code -> series (retained across clear) DebounceConfig config_; size_t max_snapshots_per_fault_{0}; ///< 0 = unlimited diff --git a/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/postgres_fault_storage.hpp b/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/postgres_fault_storage.hpp index 78e231029..05037154c 100644 --- a/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/postgres_fault_storage.hpp +++ b/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/postgres_fault_storage.hpp @@ -83,8 +83,6 @@ class PgFaultStorage : public FaultStorage { void set_retain_snapshots_on_clear(bool retain) override; bool retains_snapshots_on_clear() const override; - void set_max_rosbags_per_fault(size_t max_count) override; - void store_snapshot(const SnapshotData & snapshot) override; void store_snapshots(const std::vector & snapshots) override; std::vector get_snapshots(const std::string & fault_code, @@ -96,15 +94,10 @@ class PgFaultStorage : public FaultStorage { size_t set_max_near_misses_per_fault(size_t max_count) override; std::vector get_near_misses(const std::string & fault_code) const override; - void store_rosbag_file(const RosbagFileInfo & info) override; - void store_rosbag_files(const std::vector & infos) override; RosbagApplyResult apply_rosbag_changes(const RosbagChangeSet & changes) override; std::optional get_rosbag_file(const std::string & fault_code) const override; std::vector get_rosbag_files(const std::string & fault_code) const override; std::vector get_rosbag_files_by_recording(const std::string & recording_id) const override; - bool delete_rosbag_file(const std::string & fault_code) override; - size_t delete_rosbag_recording(const std::string & recording_id) override; - size_t delete_rosbag_files(const std::vector & fault_codes) override; size_t get_total_rosbag_storage_bytes() const override; std::vector get_all_rosbag_files() const override; std::vector list_rosbags_for_entity(const std::string & entity_fqn) const override; @@ -144,13 +137,6 @@ class PgFaultStorage : public FaultStorage { /// Drop the connection and start the backoff after a failed round. Caller holds mutex_. void fail_round(const std::string & error) const; - /// Whether any fault at all still references @p file_path. Caller holds mutex_. - bool path_referenced(const std::string & file_path) const; - - /// store_rosbag_file body without taking mutex_. Caller holds mutex_ and - /// manages transaction scope. Returns replaced bag path if applicable. - std::vector store_rosbag_file_locked(const RosbagFileInfo & info, pqxx::work & tx); - /// report_fault_event body without taking mutex_ or opening a transaction. Caller holds mutex_ /// and supplies the transaction, so the fault row and any near-miss row commit together. bool report_fault_event_locked(const std::string & fault_code, fd::ReportKind kind, uint8_t severity, @@ -198,9 +184,6 @@ class PgFaultStorage : public FaultStorage { size_t max_snapshots_per_fault_{0}; ///< 0 = unlimited size_t max_near_misses_per_fault_{0}; ///< 0 = unlimited bool retain_snapshots_on_clear_{false}; - /// Defaults to 1, the pre-#620 behaviour: a new recording replaces the old one. - /// 0 = unlimited, bounded only by max_total_storage_mb. - size_t max_rosbags_per_fault_{1}; int max_retries_{1}; ///< Attempts after the first one. Must be >= 0. unsigned reconnection_delay_{500}; }; diff --git a/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/retention_worker.hpp b/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/retention_worker.hpp new file mode 100644 index 000000000..db5911df4 --- /dev/null +++ b/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/retention_worker.hpp @@ -0,0 +1,87 @@ +// 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. + +#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/rosbag_retention.hpp" + +namespace ros2_medkit_fault_manager { + +/// Runs the file system work that follows a rosbag row change, such as removing a directory +/// no row names any more. +/// +/// kThread: one thread runs the posted jobs in FIFO order. kInline: post() runs the job at once +/// on the calling thread. In both modes a job that throws is logged as an ERROR, and every job +/// ends with the DEBUG line `retention job done: `. post() after drain_and_stop() logs a +/// WARN and drops the job. +class RetentionWorker { + public: + enum class Mode { kThread, kInline }; + + RetentionWorker(core::LogSink & log_sink, std::string logger_name, Mode mode); + /// Runs drain_and_stop(). + ~RetentionWorker(); + + RetentionWorker(const RetentionWorker &) = delete; + RetentionWorker & operator=(const RetentionWorker &) = delete; + RetentionWorker(RetentionWorker &&) = delete; + RetentionWorker & operator=(RetentionWorker &&) = delete; + + void post(std::string kind, std::function job); + + /// Remove the directory of @p recording on the calling thread, then log the removal with its + /// reason: `Recording removed: (max_bags_per_fault)` or `(fault cleared)`, or main's + /// `Deleted old bag '' to enforce storage limit` for the quota. No line when nothing was + /// removed, and none for a stale row. A failure logs a WARN with the path, the reason and the + /// error. + /// @return true when the directory is gone + bool remove_recording(const core::FreedRecording & recording); + + /// Post one job that runs remove_recording() for each of @p recordings. Posts nothing when + /// @p recordings is empty. + void post_removals(std::string kind, std::vector recordings); + + /// Run every job posted so far, then stop the thread. Idempotent. + void drain_and_stop(); + + private: + struct Job { + std::string kind; + std::function run; + }; + + void thread_loop(); + void run_job(const Job & job); + + core::LogSink & log_sink_; + const std::string logger_name_; + const Mode mode_; + std::mutex mutex_; + std::condition_variable cv_; + std::deque queue_; + bool stopping_{false}; + std::thread thread_; +}; + +} // namespace ros2_medkit_fault_manager 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 f380a8503..628acfe71 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 @@ -31,7 +31,10 @@ #include #include +#include "ros2_medkit_fault_manager/core/rosbag_retention.hpp" #include "ros2_medkit_fault_manager/fault_storage.hpp" +#include "ros2_medkit_fault_manager/retention_worker.hpp" +#include "ros2_medkit_fault_manager/ros2/ros_log_sink.hpp" #include "ros2_medkit_fault_manager/snapshot_capture.hpp" namespace ros2_medkit_fault_manager { @@ -75,7 +78,8 @@ class RosbagCapture { /// backend unavailable without depending on which plugins CI happens to install. using StorageProbeFn = std::function(const std::string & format)>; - /// Create rosbag capture + /// Create rosbag capture with its own retention, limited by @p config, and an inline worker: + /// every unlink runs on the thread whose call caused it. /// @param node ROS 2 node for creating subscriptions and timers /// @param storage Fault storage for persisting bag file metadata /// @param config Rosbag configuration @@ -84,6 +88,14 @@ class RosbagCapture { RosbagCapture(rclcpp::Node * node, FaultStorage * storage, const RosbagConfig & config, const SnapshotConfig & snapshot_config, StorageProbeFn storage_probe = {}); + /// Create rosbag capture on a retention and a worker the caller owns, as the fault manager + /// node does. The caller drains @p retention_worker after stop(). + /// @param retention Retention decisions over @p storage + /// @param retention_worker Removes the directories a clear frees + RosbagCapture(rclcpp::Node * node, FaultStorage * storage, const RosbagConfig & config, + const SnapshotConfig & snapshot_config, std::shared_ptr retention, + std::shared_ptr retention_worker, StorageProbeFn storage_probe = {}); + ~RosbagCapture(); // Non-copyable, non-movable @@ -140,18 +152,6 @@ class RosbagCapture { /// auto-excluded from broad-mode capture. Static + public so it is directly testable. static bool is_high_bandwidth_topic(const std::string & topic); - /// Delete oldest bags from @p storage until its accounted total fits @p max_bytes. - /// A bag shared by a burst of correlated faults is evicted as one unit: every row - /// referencing it goes together and its bytes are freed once, so the running total - /// tracks what is really on disk instead of drifting below it. - /// @p keep_recording_id, when set, is never evicted: the recording that was just - /// stored must not be the one its own quota sweep deletes, even when it alone is - /// over @p max_bytes. - /// @return Paths of the evicted bags, oldest first. - /// Static + public so the quota arithmetic is testable without a live recording. - static std::vector evict_bags_over_quota(FaultStorage * storage, size_t max_bytes, - const std::string & keep_recording_id = ""); - /// Suffix of the directory that reserves a bag path while its writer opens. static constexpr const char * kBagPathClaimSuffix = ".claim"; @@ -177,10 +177,10 @@ class RosbagCapture { /// derived origin above zero, which span_sec_since() reserves for "never started" and /// reports as a duration of 0. /// - /// Static + public for the same reason as the quota arithmetic above: a wall-clock - /// step cannot be produced through this class's own API, and in ordinary operation the - /// oldest buffered message is always younger than the capture, so the bound never - /// engages and nothing driving the capture can exercise it. + /// Static + public because a wall-clock step cannot be produced through this class's + /// own API, and in ordinary operation the oldest buffered message is always younger + /// than the capture, so the bound never engages and nothing driving the capture can + /// exercise it. static int64_t bounded_history_ns(int64_t now_wall_ns, int64_t oldest_msg_wall_ns, int64_t now_steady_ns, int64_t capture_started_steady_ns); /// Build the single path component naming a fault's bag directory. @@ -227,6 +227,9 @@ class RosbagCapture { std::string bag_path; ///< Set only when status == kOk. }; + /// The constructor body both constructors share: storage backend resolution and the start. + void init(StorageProbeFn storage_probe); + /// Initialize subscriptions for configured topics void init_subscriptions(); @@ -286,9 +289,6 @@ class RosbagCapture { /// Calculate total size of a bag directory size_t calculate_bag_size(const std::string & bag_path) const; - /// Enforce storage limits by deleting oldest bags, never @p keep_recording_id - void enforce_storage_limits(const std::string & keep_recording_id); - /// Write manifest.json into a closed recording. Logs and carries on when it cannot. void write_manifest(const std::string & bag_path, int64_t created_at_ns); @@ -321,33 +321,27 @@ class RosbagCapture { /// rows, so a directory with no row is unreachable, uncounted, and can never be /// evicted to make room. /// - /// The discard covers a failure of the store and nothing else. Quota enforcement - /// runs afterwards under its own handler: by then the rows are committed, so a - /// failing eviction says nothing about this bag, and removing the directory there - /// would strand the rows just written - unreadable for good, and still charged - /// against max_total_storage_mb. + /// The decisions are core::RosbagRetention::store(). The bag is discarded here when + /// every fault of it is cleared or the store failed, and nothing else. A failed quota + /// keeps it: by then the rows are committed, and removing the directory would strand + /// them - unreadable for good, and still charged against max_total_storage_mb. The + /// directories the store freed are removed here, before the caller logs the stored + /// bag, and each removal is logged once it is done. /// /// Never throws. One caller runs on the store worker, where an escaping exception /// would terminate; the other runs on the capture pool, which would swallow it /// into a log with the bag already orphaned. /// - /// Rows of faults the store reports cleared are dropped first (row_still_wanted()), - /// and with none left the bag is discarded. - /// /// @return True when the rows are durable. bool store_rows_or_discard_bag(std::vector rows, const std::string & bag_path); - /// Whether the fault still gets a row: false only under auto_cleanup with no history, - /// for a fault the store holds as cleared. Called under clear_rows_mutex_. - bool row_still_wanted(const std::string & code); - /// Whether the operator asked this fault code to keep a recording history. /// /// A cap of exactly 1 is the pre-#620 single-recording behaviour, where /// auto_cleanup deleting the recording on acknowledgement is right. Anything /// else - including 0, which means unlimited - is a history someone configured, - /// and acknowledgement must not be what takes it away. Both places that act on - /// auto_cleanup ask this, or the two disagree about the same fault: one keeps + /// and acknowledgement must not be what takes it away. The store applies the same + /// rule (core::RosbagRetention), or the two disagree about the same fault: one keeps /// the rows and the other deletes the bag out from under them. bool keeps_history() const { return config_.max_bags_per_fault != 1; @@ -426,6 +420,11 @@ class RosbagCapture { RosbagConfig config_; SnapshotConfig snapshot_config_; + /// Log sink of the retention and the worker this capture builds itself; null otherwise. + std::unique_ptr own_log_sink_; + std::shared_ptr retention_; + std::shared_ptr retention_worker_; + /// Ring buffer for messages mutable std::mutex buffer_mutex_; std::deque message_buffer_; @@ -542,13 +541,10 @@ class RosbagCapture { /// Store worker. Owned by the capture and joined in the destructor. The queue is /// FIFO, so the quota sweeps run in the order the recordings closed. It takes no - /// other lock of this class, so it adds nothing to the lock order above. + /// other lock of this class, so it adds nothing to the lock order above. The + /// retention's mutex is taken with no lock of this class held. std::mutex store_mutex_; std::condition_variable store_cv_; - /// Orders storing a recording's rows against on_fault_cleared()'s delete: held for - /// the cleared check plus the insert, and for the delete. Hashing stays outside it. - /// Only storage calls run under it, so it is innermost in the lock order. - std::mutex clear_rows_mutex_; std::deque store_queue_; bool store_busy_{false}; bool store_stopping_{false}; diff --git a/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/sqlite_fault_storage.hpp b/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/sqlite_fault_storage.hpp index b69e829b8..303d74bc9 100644 --- a/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/sqlite_fault_storage.hpp +++ b/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/sqlite_fault_storage.hpp @@ -69,8 +69,6 @@ class SqliteFaultStorage : public FaultStorage { void set_retain_snapshots_on_clear(bool retain) override; bool retains_snapshots_on_clear() const override; - void set_max_rosbags_per_fault(size_t max_count) override; - void store_snapshot(const SnapshotData & snapshot) override; void store_snapshots(const std::vector & snapshots) override; std::vector get_snapshots(const std::string & fault_code, @@ -83,15 +81,10 @@ class SqliteFaultStorage : public FaultStorage { size_t set_max_near_misses_per_fault(size_t max_count) override; std::vector get_near_misses(const std::string & fault_code) const override; - void store_rosbag_file(const RosbagFileInfo & info) override; - void store_rosbag_files(const std::vector & infos) override; RosbagApplyResult apply_rosbag_changes(const RosbagChangeSet & changes) override; std::optional get_rosbag_file(const std::string & fault_code) const override; std::vector get_rosbag_files(const std::string & fault_code) const override; std::vector get_rosbag_files_by_recording(const std::string & recording_id) const override; - bool delete_rosbag_file(const std::string & fault_code) override; - size_t delete_rosbag_recording(const std::string & recording_id) override; - size_t delete_rosbag_files(const std::vector & fault_codes) override; size_t get_total_rosbag_storage_bytes() const override; std::vector get_all_rosbag_files() const override; std::vector list_rosbags_for_entity(const std::string & entity_fqn) const override; @@ -123,20 +116,9 @@ class SqliteFaultStorage : public FaultStorage { /// C++ through rosbag_recording_id() so the basename rule has one implementation. void migrate_rosbag_files_add_recording_id(); - /// Whether a fault other than @p fault_code still references @p file_path. - /// One recording can back several faults of the same burst, so the bag must - /// only be unlinked once the last of them is gone. Caller holds mutex_. - - /// Whether any fault at all still references @p file_path. Caller holds mutex_. + /// Whether any row at all still references @p file_path. Caller holds mutex_. bool path_referenced(const std::string & file_path) const; - /// store_rosbag_file body without taking mutex_. Caller holds mutex_ and - /// unlinks the returned replaced-bag path once the row change is durable. - /// @return file_paths whose last row for this fault the per-fault cap evicted. - /// The caller unlinks each only after the commit, and only if path_referenced() - /// still says nobody holds it. - std::vector store_rosbag_file_locked(const RosbagFileInfo & info); - /// report_fault_event body without taking mutex_ or opening a transaction. Caller holds mutex_ /// and wraps the call, so the fault row and any near-miss row commit together. bool report_fault_event_locked(const std::string & fault_code, fd::ReportKind kind, uint8_t severity, @@ -173,9 +155,6 @@ class SqliteFaultStorage : public FaultStorage { size_t max_snapshots_per_fault_{0}; ///< 0 = unlimited size_t max_near_misses_per_fault_{0}; ///< 0 = unlimited bool retain_snapshots_on_clear_{false}; - /// Defaults to 1, the pre-#620 behaviour: a new recording replaces the old one. - /// 0 = unlimited, bounded only by max_total_storage_mb. - size_t max_rosbags_per_fault_{1}; }; } // namespace ros2_medkit_fault_manager diff --git a/src/ros2_medkit_fault_manager/src/core/fault_manager_startup.cpp b/src/ros2_medkit_fault_manager/src/core/fault_manager_startup.cpp index a2f73b250..a3bcb3aee 100644 --- a/src/ros2_medkit_fault_manager/src/core/fault_manager_startup.cpp +++ b/src/ros2_medkit_fault_manager/src/core/fault_manager_startup.cpp @@ -230,12 +230,6 @@ CoreParts build_core_parts(const FaultManagerConfig & config, LogSink & sink) { // Independent of the cap: max_per_fault 0 means unlimited. parts.storage->set_retain_snapshots_on_clear(config.snapshots_retain_on_clear); - if (config.snapshots_rosbag_enabled) { - // The cap lives in the storage backend: it has to be atomic with the insert, and the unlink - // has to happen after the backend's commit. - parts.storage->set_max_rosbags_per_fault(static_cast(config.snapshots_rosbag_max_bags_per_fault)); - } - // Applying the near-miss bound also trims a series an earlier run left over it, which deletes // history for good. Unreachable storage skips the trim; the bound still applies to new entries. size_t evicted_near_misses = 0; diff --git a/src/ros2_medkit_fault_manager/src/core/rosbag_retention.cpp b/src/ros2_medkit_fault_manager/src/core/rosbag_retention.cpp new file mode 100644 index 000000000..d75737d3e --- /dev/null +++ b/src/ros2_medkit_fault_manager/src/core/rosbag_retention.cpp @@ -0,0 +1,330 @@ +// 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. + +#include "ros2_medkit_fault_manager/core/rosbag_retention.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace ros2_medkit_fault_manager::core { + +namespace { + +/// Append @p freed to @p out, skipping a path already listed. +void append_unique(std::vector & out, const std::vector & freed) { + for (const auto & entry : freed) { + const bool listed = std::any_of(out.begin(), out.end(), [&entry](const FreedRecording & known) { + return known.path == entry.path; + }); + if (!listed) { + out.push_back(entry); + } + } +} + +/// The freed recordings of @p paths, each with its recording id from @p recording_ids. +std::vector freed(const std::vector & paths, + const std::unordered_map & recording_ids, + RemovalReason reason) { + std::vector out; + out.reserve(paths.size()); + for (const auto & path : paths) { + const auto known = recording_ids.find(path); + const std::string id = + known != recording_ids.end() && !known->second.empty() ? known->second : rosbag_recording_id(path); + out.push_back({path, id, reason}); + } + return out; +} + +bool is_empty(const RosbagChangeSet & changes) { + return changes.insert.empty() && changes.remove.empty() && changes.remove_recordings.empty(); +} + +} // namespace + +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)) { +} + +StoreOutcome RosbagRetention::store(std::vector rows) { + for ([[maybe_unused]] const auto & row : rows) { + assert(!row.recording_id.empty() && row.recording_id == rosbag_recording_id(row.file_path)); + } + std::lock_guard lock(mutex_); + StoreOutcome outcome; + + // A clear either shows here as cleared, or its removal waits for this mutex and takes the rows. + rows.erase(std::remove_if(rows.begin(), rows.end(), + [this](const RosbagFileInfo & row) { + return !row_still_wanted(row.fault_code); + }), + rows.end()); + if (rows.empty()) { + outcome.result = StoreResult::kAllFaultsCleared; + return 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(); + return outcome; + } catch (...) { + outcome.result = StoreResult::kStoreFailed; + 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)); + } + } + + const std::string & bag_path = rows.front().file_path; + const std::string & keep_recording_id = rows.front().recording_id; + Eviction eviction; + try { + try { + evict(limits_.max_total_bytes, keep_recording_id, eviction); + } catch (...) { + append_unique(outcome.unlink_paths, eviction.unlink_paths); + throw; + } + append_unique(outcome.unlink_paths, eviction.unlink_paths); + // Everything older is gone by now, so what is left over the quota is the kept recording alone. + if (!keep_recording_id.empty() && storage_.get_total_rosbag_storage_bytes() > limits_.max_total_bytes) { + logf(log_sink_, LogLevel::kWarn, logger_name_, + "Recording '%s' alone exceeds snapshots.rosbag.max_total_storage_mb (%zu MB); it is kept, and the " + "storage stays over the limit until a newer recording replaces it", + keep_recording_id.c_str(), limits_.max_total_bytes / (1024 * 1024)); + } + } 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()); + } 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; +} + +std::vector RosbagRetention::evict_over_quota(size_t max_bytes, const std::string & keep_recording_id) { + std::lock_guard lock(mutex_); + Eviction eviction; + evict(max_bytes, keep_recording_id, eviction); + std::vector paths; + paths.reserve(eviction.unlink_paths.size()); + for (const auto & entry : eviction.unlink_paths) { + paths.push_back(entry.path); + } + return paths; +} + +RemovalOutcome RosbagRetention::on_fault_cleared(const std::string & fault_code) { + std::lock_guard lock(mutex_); + const auto rows = storage_.get_rosbag_files(fault_code); + RosbagChangeSet changes; + for (const auto & row : rows) { + changes.remove.push_back({row.fault_code, row.file_path}); + } + return remove(rows, changes, RemovalReason::kCleared); +} + +RemovalOutcome RosbagRetention::forget_recording(const std::string & recording_id) { + // An empty id names rows whose backfill did not finish, not one recording. + if (recording_id.empty()) { + return {}; + } + std::lock_guard lock(mutex_); + const auto rows = storage_.get_rosbag_files_by_recording(recording_id); + RosbagChangeSet changes; + changes.remove_recordings.push_back(recording_id); + return remove(rows, changes, RemovalReason::kStale); +} + +bool RosbagRetention::row_still_wanted(const std::string & fault_code) { + // Without auto_cleanup, or with a history configured, a cleared fault keeps its recording. + if (!limits_.auto_cleanup || limits_.max_bags_per_fault != 1) { + return true; + } + std::optional fault; + try { + fault = storage_.get_fault(fault_code); + } catch (const std::exception & e) { + logf(log_sink_, LogLevel::kWarn, logger_name_, + "Could not read fault '%s' before storing its bag, keeping its row: %s", fault_code.c_str(), e.what()); + return true; + } catch (...) { + logf(log_sink_, LogLevel::kWarn, logger_name_, + "Could not read fault '%s' before storing its bag, keeping its row: unknown exception", fault_code.c_str()); + return true; + } + // Absent is not cleared: only a fault the storage holds AND reports as cleared loses its row. + return !fault.has_value() || fault->status != fd::fault_status::kCleared; +} + +RosbagChangeSet RosbagRetention::cap_changes(const std::vector & rows, + std::unordered_map & recording_ids) { + for (const auto & row : rows) { + recording_ids.emplace(row.file_path, row.recording_id); + } + RosbagChangeSet changes; + const size_t cap = limits_.max_bags_per_fault; + if (cap == 0) { + changes.insert = rows; + return changes; + } + + // One candidate per link, ordered as the backends order rows: created_at_ns, then insertion. + // A stored row ranks by its place in the read; a new row ranks after every stored one; a row + // that upserts a stored link keeps the stored rank. + struct Candidate { + int64_t created_at_ns; + size_t rank; + std::string file_path; + bool stored; + bool incoming; + }; + std::set> dropped; + std::set done; + for (const auto & first : rows) { + const std::string & code = first.fault_code; + if (!done.insert(code).second) { + continue; + } + const auto stored = storage_.get_rosbag_files(code); // newest first + std::vector candidates; + size_t rank = 0; + for (auto it = stored.rbegin(); it != stored.rend(); ++it) { + recording_ids.emplace(it->file_path, it->recording_id); + candidates.push_back({it->created_at_ns, rank++, it->file_path, true, false}); + } + for (const auto & row : rows) { + if (row.fault_code != code) { + continue; + } + auto same_link = std::find_if(candidates.begin(), candidates.end(), [&row](const Candidate & c) { + return c.file_path == row.file_path; + }); + if (same_link != candidates.end()) { + same_link->created_at_ns = row.created_at_ns; + same_link->incoming = true; + } else { + candidates.push_back({row.created_at_ns, rank++, row.file_path, false, true}); + } + } + if (candidates.size() <= cap) { + continue; + } + std::sort(candidates.begin(), candidates.end(), [](const Candidate & a, const Candidate & b) { + return std::tie(a.created_at_ns, a.rank) > std::tie(b.created_at_ns, b.rank); // newest first + }); + for (size_t i = cap; i < candidates.size(); ++i) { + if (candidates[i].stored) { + changes.remove.push_back({code, candidates[i].file_path}); + } + if (candidates[i].incoming) { + dropped.emplace(code, candidates[i].file_path); + } + } + } + + for (const auto & row : rows) { + if (dropped.count({row.fault_code, row.file_path}) == 0) { + changes.insert.push_back(row); + } + } + return changes; +} + +void RosbagRetention::evict(size_t max_bytes, const std::string & keep_recording_id, Eviction & out) { + size_t current_bytes = storage_.get_total_rosbag_storage_bytes(); + if (current_bytes <= max_bytes) { + return; + } + + // Rows are links: a burst shares one recording and one fault holds several. Group them back + // into bags, so a shared bag is evicted whole and its bytes are freed once. + std::vector paths_oldest_first; + std::unordered_map recording_by_path; + std::unordered_map bytes_by_path; + for (const auto & row : storage_.get_all_rosbag_files()) { + // The rows arrive oldest first, so a path's first row gives the recording's age. + if (recording_by_path.emplace(row.file_path, row.recording_id).second) { + paths_oldest_first.push_back(row.file_path); + } + // The storage counts the largest row per path. + auto & bytes = bytes_by_path[row.file_path]; + bytes = std::max(bytes, row.size_bytes); + } + + for (const auto & path : paths_oldest_first) { + if (current_bytes <= max_bytes) { + break; + } + if (!keep_recording_id.empty() && recording_by_path[path] == keep_recording_id) { + continue; + } + // By recording, not by fault code: a fault's newer recordings must stay. + RosbagChangeSet changes; + changes.remove_recordings.push_back(recording_by_path[path]); + append_unique(out.unlink_paths, freed(storage_.apply_rosbag_changes(changes).orphaned_paths, recording_by_path, + RemovalReason::kQuota)); + // Saturate: the quota must never be met by underflow. + current_bytes -= std::min(current_bytes, bytes_by_path[path]); + } +} + +RemovalOutcome RosbagRetention::remove(const std::vector & rows, const RosbagChangeSet & changes, + RemovalReason reason) { + RemovalOutcome outcome; + if (rows.empty()) { + return outcome; + } + std::unordered_map recording_ids; + for (const auto & row : rows) { + recording_ids.emplace(row.file_path, row.recording_id); + } + outcome.unlink_paths = freed(storage_.apply_rosbag_changes(changes).orphaned_paths, recording_ids, reason); + outcome.removed_rows = rows.size(); + return outcome; +} + +} // namespace ros2_medkit_fault_manager::core 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 3ea975413..7b598e322 100644 --- a/src/ros2_medkit_fault_manager/src/fault_manager_node.cpp +++ b/src/ros2_medkit_fault_manager/src/fault_manager_node.cpp @@ -134,6 +134,14 @@ FaultManagerNode::FaultManagerNode(const rclcpp::NodeOptions & options) : Node(" wall_clock_, log_sink_); storage_ = &core_->storage(); + retention_worker_ = std::make_shared(log_sink_, config_.logger_name, RetentionWorker::Mode::kThread); + core::RosbagRetentionLimits retention_limits; + retention_limits.max_bags_per_fault = static_cast(config_.snapshots_rosbag_max_bags_per_fault); + retention_limits.max_total_bytes = static_cast(config_.snapshots_rosbag_max_total_storage_mb) * 1024 * 1024; + retention_limits.auto_cleanup = config_.snapshots_rosbag_auto_cleanup; + rosbag_retention_ = + std::make_shared(*storage_, retention_limits, log_sink_, config_.logger_name); + // 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. core::reclassify_stale_healed(*storage_, core_->fault_code_resolver(), core_->global_debounce(), @@ -203,7 +211,8 @@ FaultManagerNode::FaultManagerNode(const rclcpp::NodeOptions & options) : Node(" // Initialize rosbag capture if enabled if (snapshot_config.rosbag.enabled) { - rosbag_capture_ = std::make_shared(this, storage_, snapshot_config.rosbag, snapshot_config); + rosbag_capture_ = std::make_shared(this, storage_, snapshot_config.rosbag, snapshot_config, + rosbag_retention_, retention_worker_); // The recapture cooldown gates the capture job as a whole, bags included, so it // puts a floor under how often a history can actually grow: a fault that @@ -282,6 +291,10 @@ FaultManagerNode::~FaultManagerNode() { if (rosbag_capture_) { rosbag_capture_->stop(); } + // Last: runs the directory removals the clear and stale-row paths posted before exit. + if (retention_worker_) { + retention_worker_->drain_and_stop(); + } // Close the chain with a "logging deactivated" marker. Best-effort and appended // directly (recorded even in confirmed_only mode); a failure here must not throw @@ -865,7 +878,8 @@ void FaultManagerNode::handle_get_rosbag(const std::shared_ptrdelete_rosbag_recording(rosbag_info->recording_id); + auto removal = rosbag_retention_->forget_recording(rosbag_info->recording_id); + retention_worker_->post_removals("forget", std::move(removal.unlink_paths)); } catch (const FaultStorage::IgnorableConnectionException & e) { RCLCPP_WARN(get_logger(), "Failed to connect with the fault storage server: %s", e.what()); return; @@ -915,7 +929,8 @@ void FaultManagerNode::handle_list_rosbags( // by fault code would instead take that fault's healthy recordings with it. if (reaped.insert(info.recording_id).second) { try { - storage_->delete_rosbag_recording(info.recording_id); + auto removal = rosbag_retention_->forget_recording(info.recording_id); + retention_worker_->post_removals("forget", std::move(removal.unlink_paths)); } catch (const FaultStorage::IgnorableConnectionException & e) { RCLCPP_WARN(get_logger(), "Failed to connect with the fault storage server: %s", e.what()); response->success = false; diff --git a/src/ros2_medkit_fault_manager/src/fault_storage.cpp b/src/ros2_medkit_fault_manager/src/fault_storage.cpp index 24461f123..1144ddc7f 100644 --- a/src/ros2_medkit_fault_manager/src/fault_storage.cpp +++ b/src/ros2_medkit_fault_manager/src/fault_storage.cpp @@ -390,7 +390,7 @@ void InMemoryFaultStorage::store_snapshots(const std::vector & sna const std::string fault_code = snapshots.front().fault_code; - // Built beside the live vector and swapped in, the shape store_rosbag_files + // Built beside the live vector and swapped in, the shape apply_rosbag_changes // uses: a capture is all-or-nothing, so a throw partway must not leave half of // it stored. auto updated = snapshots_; @@ -564,99 +564,6 @@ void check_rosbag_change_set(const RosbagChangeSet & changes) { } } -void InMemoryFaultStorage::set_max_rosbags_per_fault(size_t max_count) { - std::lock_guard lock(mutex_); - max_rosbags_per_fault_ = max_count; -} - -void InMemoryFaultStorage::store_rosbag_file(const RosbagFileInfo & info) { - // Through the batch path deliberately: with a per-fault cap a single store is - // insert + trim, and both must publish together. - store_rosbag_files({info}); -} - -void InMemoryFaultStorage::store_rosbag_files(const std::vector & infos) { - if (infos.empty()) { - return; - } - std::lock_guard lock(mutex_); - - // Built beside the live vector and swapped in, because swap cannot throw. The - // caller reads a throw here as "no row was written" and removes the recording, so - // a batch that stored half a burst and then threw would leave those rows naming a - // bag that is gone. Copying costs one allocation per stored recording, not per - // message. std::vector::swap is noexcept for the default allocator, exactly as - // std::map::swap was. - auto updated = rosbag_files_; - uint64_t next_seq = rosbag_seq_; - std::set evicted; - - for (const auto & in : infos) { - RosbagFileInfo row = in; - if (row.recording_id.empty()) { - row.recording_id = rosbag_recording_id(row.file_path); - } - - // Upsert on the (fault, recording) LINK - the same grain as the SQLite unique - // index. Re-storing the same link refreshes it; a link to a different recording - // appends, which is the feature. - auto it = std::find_if(updated.begin(), updated.end(), [&row](const RosbagRow & r) { - return r.info.fault_code == row.fault_code && r.info.file_path == row.file_path; - }); - if (it != updated.end()) { - it->info = row; - } else { - updated.push_back(RosbagRow{row, ++next_seq}); - } - - if (max_rosbags_per_fault_ == 0) { - continue; - } - - // Keep the newest N recordings of this fault, oldest evicted first - the same - // direction as evict_bags_over_quota, so the two eviction owners never need a - // tiebreak. At N = 1 this is the pre-#620 behaviour exactly. - std::vector mine; - for (size_t i = 0; i < updated.size(); ++i) { - if (updated[i].info.fault_code == row.fault_code) { - mine.push_back(i); - } - } - if (mine.size() <= max_rosbags_per_fault_) { - continue; - } - std::sort(mine.begin(), mine.end(), [&updated](size_t a, size_t b) { - return std::tie(updated[a].info.created_at_ns, updated[a].seq) < - std::tie(updated[b].info.created_at_ns, updated[b].seq); - }); - std::vector doomed(mine.begin(), - mine.begin() + static_cast(mine.size() - max_rosbags_per_fault_)); - std::sort(doomed.rbegin(), doomed.rend()); // descending, so erase stays valid - for (size_t idx : doomed) { - evicted.insert(updated[idx].info.file_path); - updated.erase(updated.begin() + static_cast(idx)); - } - } - - rosbag_files_.swap(updated); - rosbag_seq_ = next_seq; - - // Unlinked only once every row is in, the way the SQLite backend unlinks after its - // COMMIT: a throw above must leave the old rows pointing at bags that still exist. - // Referencing is decided on the finished batch, not on the state before it - two - // faults of one burst can share the bag being evicted, and checking row by row - // beforehand would find it still held by a sibling that a later iteration then - // evicts, leaking the directory. - for (const auto & path : evicted) { - if (path_referenced(path)) { - continue; - } - std::error_code ec; - std::filesystem::remove_all(path, ec); - // Ignore errors - file may already be deleted - } -} - RosbagApplyResult InMemoryFaultStorage::apply_rosbag_changes(const RosbagChangeSet & changes) { check_rosbag_change_set(changes); std::lock_guard lock(mutex_); @@ -773,72 +680,6 @@ InMemoryFaultStorage::get_rosbag_files_by_recording(const std::string & recordin return result; } -bool InMemoryFaultStorage::delete_rosbag_file(const std::string & fault_code) { - std::lock_guard lock(mutex_); - - // ALL recordings of this fault. Used by auto_cleanup on clear, where dropping the - // fault's whole black-box history is the intent. - std::set touched; - const size_t before = rosbag_files_.size(); - for (auto it = rosbag_files_.begin(); it != rosbag_files_.end();) { - if (it->info.fault_code == fault_code) { - touched.insert(it->info.file_path); - it = rosbag_files_.erase(it); - } else { - ++it; - } - } - if (rosbag_files_.size() == before) { - return false; - } - - for (const auto & path : touched) { - if (path_referenced(path)) { - continue; // a sibling fault of the burst still holds it - } - std::error_code ec; - std::filesystem::remove_all(path, ec); - // Ignore errors - file may already be deleted - } - return true; -} - -size_t InMemoryFaultStorage::delete_rosbag_recording(const std::string & recording_id) { - // Mirrors SqliteFaultStorage: an empty id addresses a set, not a recording. - if (recording_id.empty()) { - return 0; - } - - std::lock_guard lock(mutex_); - - std::set touched; - size_t removed = 0; - for (auto it = rosbag_files_.begin(); it != rosbag_files_.end();) { - if (it->info.recording_id == recording_id) { - touched.insert(it->info.file_path); - it = rosbag_files_.erase(it); - ++removed; - } else { - ++it; - } - } - - for (const auto & path : touched) { - if (path_referenced(path)) { - continue; - } - std::error_code ec; - std::filesystem::remove_all(path, ec); - } - return removed; -} - -bool InMemoryFaultStorage::path_referenced(const std::string & file_path) const { - return std::any_of(rosbag_files_.begin(), rosbag_files_.end(), [&](const RosbagRow & row) { - return row.info.file_path == file_path; - }); -} - size_t InMemoryFaultStorage::get_total_rosbag_storage_bytes() const { std::lock_guard lock(mutex_); diff --git a/src/ros2_medkit_fault_manager/src/postgres_fault_storage.cpp b/src/ros2_medkit_fault_manager/src/postgres_fault_storage.cpp index fa53b6c64..081683414 100644 --- a/src/ros2_medkit_fault_manager/src/postgres_fault_storage.cpp +++ b/src/ros2_medkit_fault_manager/src/postgres_fault_storage.cpp @@ -1106,57 +1106,6 @@ std::vector PgFaultStorage::get_near_misses(const std::string & }); } -void PgFaultStorage::set_max_rosbags_per_fault(size_t max_count) { - std::lock_guard lock(mutex_); - max_rosbags_per_fault_ = max_count; -} - -void PgFaultStorage::store_rosbag_file(const RosbagFileInfo & info) { - // Routed through the batch path deliberately: with a per-fault cap a single - // store is insert + trim, i.e. several statements that must share one - // transaction and one post-commit unlink pass. - store_rosbag_files({info}); -} - -void PgFaultStorage::store_rosbag_files(const std::vector & infos) { - if (infos.empty()) { - return; - } - std::lock_guard lock(mutex_); - - // One transaction for the whole burst: a crash mid-store must not leave some - // faults of the shared recording without their lookup row. Evicted bags are - // unlinked only after COMMIT - a ROLLBACK (PostgreSQL transaction abort) resurrects the rows, which must keep - // pointing at bags that still exist. - const std::vector evicted = run_in_transaction("store_rosbag_files", [&](pqxx::work & tx) { - std::vector paths; - for (const auto & info : infos) { - auto evicted_paths = store_rosbag_file_locked(info, tx); - paths.insert(paths.end(), std::make_move_iterator(evicted_paths.begin()), - std::make_move_iterator(evicted_paths.end())); - } - return paths; - }); - - // Referencing is re-checked on the committed state, not on the state each - // eviction saw: two faults of one burst can link the same bag, and a row-by-row - // check inside the loop would find it still held by a sibling that a later - // iteration then evicts, leaking the directory. - const std::set unique_paths(evicted.begin(), evicted.end()); - for (const auto & path : unique_paths) { - try { - if (path_referenced(path)) { - continue; - } - } catch (const std::exception & e) { - continue; // The rows are already committed, so keep the directory. - } - - std::error_code ec; - std::filesystem::remove_all(path, ec); - } -} - RosbagApplyResult PgFaultStorage::apply_rosbag_changes(const RosbagChangeSet & changes) { check_rosbag_change_set(changes); std::lock_guard lock(mutex_); @@ -1204,50 +1153,6 @@ RosbagApplyResult PgFaultStorage::apply_rosbag_changes(const RosbagChangeSet & c return result; } -std::vector PgFaultStorage::store_rosbag_file_locked(const RosbagFileInfo & info, pqxx::work & tx) { - RosbagFileInfo row = info; - if (row.recording_id.empty()) { - row.recording_id = rosbag_recording_id(row.file_path); - } - - // Upserts on idx_rosbag_files_fault_path, i.e. on the (fault, recording) link. - // Re-storing the SAME link refreshes it; a link to a DIFFERENT recording is a new - // row now, which is the feature. Nothing is unlinked here - byte lifetime is the - // cap's business below, and the caller's, after the commit. - // - // ON CONFLICT DO UPDATE keeps the row's identity, so a refresh does not move the - // link to the end of the id order. Every read below breaks created_at_ns ties by - // id, and the in-memory backend keeps its sequence number across a refresh, so a - // delete-and-reinsert would put the two backends in a different order for a - // re-stored row inside a tie group. - execute(tx, - "INSERT INTO rosbag_files " - "(fault_code, recording_id, file_path, format, duration_sec, size_bytes, created_at_ns) " - "VALUES ($1, $2, $3, $4, $5, $6, $7) " - "ON CONFLICT (fault_code, file_path) DO UPDATE SET " - "recording_id = EXCLUDED.recording_id, format = EXCLUDED.format, " - "duration_sec = EXCLUDED.duration_sec, size_bytes = EXCLUDED.size_bytes, " - "created_at_ns = EXCLUDED.created_at_ns", - row.fault_code, row.recording_id, row.file_path, row.format, row.duration_sec, - static_cast(row.size_bytes), row.created_at_ns); - - if (max_rosbags_per_fault_ == 0) { - return {}; // unlimited per fault; only the global byte quota bounds this - } - - auto res = - execute(tx, - "DELETE FROM rosbag_files WHERE fault_code = $1 AND id NOT IN " - "(SELECT id FROM rosbag_files WHERE fault_code = $1 ORDER BY created_at_ns DESC, id DESC LIMIT $2) " - "RETURNING file_path", - row.fault_code, static_cast(max_rosbags_per_fault_)); - - std::set evicted; - for (const auto & r : res) { - evicted.insert(r["file_path"].as()); - } - return {evicted.begin(), evicted.end()}; -} namespace { /// Shared projection so every rosbag read decodes the same column order. @@ -1302,42 +1207,6 @@ std::vector PgFaultStorage::get_rosbag_files_by_recording(const }); } -size_t PgFaultStorage::delete_rosbag_recording(const std::string & recording_id) { - // An empty id is not a recording that happens to be unnamed, it is a row whose - // backfill did not finish. Matching on it would take every such row of every - // fault with one DELETE, and evict_bags_over_quota calls this with whatever the - // row held. - if (recording_id.empty()) { - return 0; - } - - std::lock_guard lock(mutex_); - - auto outcome = - run_in_transaction("delete_rosbag_recording", [&](pqxx::work & tx) -> std::pair, size_t> { - // DELETE ... RETURNING reads and deletes the rows in one statement. - auto res = execute(tx, "DELETE FROM rosbag_files WHERE recording_id = $1 RETURNING file_path", recording_id); - std::set paths; - for (const auto & r : res) { - paths.insert(r["file_path"].as()); - } - return {paths, static_cast(res.affected_rows())}; - }); - - for (const auto & path : outcome.first) { - try { - if (path_referenced(path)) { - continue; // another recording writes into the same directory - leave it - } - } catch (const std::exception & e) { - continue; // The rows are already committed, so keep the directory. - } - std::error_code ec; - std::filesystem::remove_all(path, ec); - } - return outcome.second; -} - std::optional PgFaultStorage::get_rosbag_file(const std::string & fault_code) const { std::lock_guard lock(mutex_); @@ -1358,92 +1227,6 @@ std::optional PgFaultStorage::get_rosbag_file(const std::string }); } -bool PgFaultStorage::delete_rosbag_file(const std::string & fault_code) { - std::lock_guard lock(mutex_); - - auto outcome = - run_in_transaction("delete_rosbag_file", [&](pqxx::work & tx) -> std::pair, bool> { - // Row first, file after. Deleting the bag before its row would, on a failed - // DELETE, leave a surviving row pointing at a directory that is gone - - // unreadable for good, and still charged against the storage quota, which sums - // rows. This way the worst case is an orphaned directory instead. - auto res = execute(tx, "DELETE FROM rosbag_files WHERE fault_code = $1 RETURNING file_path", fault_code); - // Every path, not the first one: a fault holds as many recordings as its cap - // allows, and reading one row would unlink one bag and leak the rest - rows gone, - // directories left behind, uncounted by a quota that sums rows. - std::set paths; - for (const auto & r : res) { - paths.insert(r["file_path"].as()); - } - return {paths, res.affected_rows() > 0}; - }); - - for (const auto & path : outcome.first) { - try { - if (path_referenced(path)) { - continue; - } - } catch (const std::exception & e) { - continue; // The rows are already committed, so keep the directory. - } - std::error_code ec; - std::filesystem::remove_all(path, ec); - // Ignore errors - file may already be deleted - } - - return outcome.second; -} - -size_t PgFaultStorage::delete_rosbag_files(const std::vector & fault_codes) { - if (fault_codes.empty()) { - return 0; - } - std::lock_guard lock(mutex_); - - // Rows go first, in one transaction, and the files only after the commit: a - // crash mid-delete leaves at worst an orphaned directory, never a row whose - // bag is already gone. - auto outcome = - run_in_transaction("delete_rosbag_files", [&](pqxx::work & tx) -> std::pair, size_t> { - std::set paths; - size_t deleted = 0; - for (const auto & code : fault_codes) { - // RETURNING gives every path this code held, not just the first: one fault - // code can name several recordings now, and the sweep must be able to - // reclaim every one of their bags. - auto res = execute(tx, "DELETE FROM rosbag_files WHERE fault_code = $1 RETURNING file_path", code); - for (const auto & r : res) { - paths.insert(r["file_path"].as()); - } - if (res.affected_rows() > 0) { - ++deleted; - } - } - return {paths, deleted}; - }); - - for (const auto & path : outcome.first) { - try { - if (path_referenced(path)) { - continue; - } - } catch (const std::exception & e) { - continue; // The rows are already committed, so keep the directory. - } - std::error_code ec; - std::filesystem::remove_all(path, ec); - // Ignore errors - file may already be deleted - } - return outcome.second; -} - -bool PgFaultStorage::path_referenced(const std::string & file_path) const { - return run_in_transaction("path_referenced", [&](pqxx::work & tx) { - auto res = execute(tx, "SELECT COUNT(*) AS n FROM rosbag_files WHERE file_path = $1", file_path); - return !res.empty() && res[0]["n"].as() > 0; - }); -} - size_t PgFaultStorage::get_total_rosbag_storage_bytes() const { std::lock_guard lock(mutex_); diff --git a/src/ros2_medkit_fault_manager/src/retention_worker.cpp b/src/ros2_medkit_fault_manager/src/retention_worker.cpp new file mode 100644 index 000000000..8d5b3c866 --- /dev/null +++ b/src/ros2_medkit_fault_manager/src/retention_worker.cpp @@ -0,0 +1,161 @@ +// 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. + +#include "ros2_medkit_fault_manager/retention_worker.hpp" + +#include +#include +#include + +namespace ros2_medkit_fault_manager { + +namespace { + +/// Why a recording went, as its log lines name it. +const char * removal_reason_name(core::RemovalReason reason) { + switch (reason) { + case core::RemovalReason::kCap: + return "max_bags_per_fault"; + case core::RemovalReason::kQuota: + return "max_total_storage_mb"; + case core::RemovalReason::kCleared: + return "fault cleared"; + case core::RemovalReason::kStale: + return "directory missing"; + } + return "unknown"; +} + +} // namespace + +RetentionWorker::RetentionWorker(core::LogSink & log_sink, std::string logger_name, Mode mode) + : log_sink_(log_sink), logger_name_(std::move(logger_name)), mode_(mode) { + if (mode_ == Mode::kThread) { + thread_ = std::thread([this]() { + thread_loop(); + }); + } +} + +RetentionWorker::~RetentionWorker() { + // A destructor must not throw, and join() can. + try { + drain_and_stop(); + } catch (...) { + } +} + +void RetentionWorker::post(std::string kind, std::function job) { + Job entry{std::move(kind), std::move(job)}; + { + std::lock_guard lock(mutex_); + if (stopping_) { + core::logf(log_sink_, core::LogLevel::kWarn, logger_name_, "Retention worker stopped, dropped job: %s", + entry.kind.c_str()); + return; + } + if (mode_ == Mode::kThread) { + queue_.push_back(std::move(entry)); + cv_.notify_one(); + return; + } + } + run_job(entry); +} + +void RetentionWorker::drain_and_stop() { + std::thread worker; + { + std::lock_guard lock(mutex_); + stopping_ = true; + worker = std::move(thread_); + } + cv_.notify_all(); + if (worker.joinable()) { + worker.join(); + } +} + +void RetentionWorker::thread_loop() { + std::unique_lock lock(mutex_); + while (true) { + cv_.wait(lock, [this]() { + return !queue_.empty() || stopping_; + }); + if (queue_.empty()) { + return; + } + Job job = std::move(queue_.front()); + queue_.pop_front(); + lock.unlock(); + run_job(job); + lock.lock(); + } +} + +void RetentionWorker::run_job(const Job & job) { + try { + job.run(); + } catch (const std::exception & e) { + core::logf(log_sink_, core::LogLevel::kError, logger_name_, "Retention job failed: %s: %s", job.kind.c_str(), + e.what()); + } catch (...) { + core::logf(log_sink_, core::LogLevel::kError, logger_name_, "Retention job failed: %s: unknown exception", + job.kind.c_str()); + } + core::logf(log_sink_, core::LogLevel::kDebug, logger_name_, "retention job done: %s", job.kind.c_str()); +} + +bool RetentionWorker::remove_recording(const core::FreedRecording & recording) { + std::error_code ec; + const auto removed = std::filesystem::remove_all(recording.path, ec); + if (ec) { + core::logf(log_sink_, core::LogLevel::kWarn, logger_name_, "Failed to remove recording '%s' (%s): %s", + recording.path.c_str(), removal_reason_name(recording.reason), ec.message().c_str()); + return false; + } + if (removed == 0) { + // The directory was already missing: nothing was removed. + return true; + } + switch (recording.reason) { + case core::RemovalReason::kQuota: + core::logf(log_sink_, core::LogLevel::kInfo, logger_name_, "Deleted old bag '%s' to enforce storage limit", + recording.path.c_str()); + break; + case core::RemovalReason::kStale: + // A stale row is reaped because its directory went missing. + break; + case core::RemovalReason::kCap: + case core::RemovalReason::kCleared: + core::logf(log_sink_, core::LogLevel::kInfo, logger_name_, "Recording removed: %s (%s)", + recording.recording_id.c_str(), removal_reason_name(recording.reason)); + break; + } + return true; +} + +void RetentionWorker::post_removals(std::string kind, std::vector recordings) { + if (recordings.empty()) { + return; + } + // The job runs on this worker, so the worker outlives it. + post(std::move(kind), [this, recordings = std::move(recordings)]() { + for (const auto & recording : recordings) { + remove_recording(recording); + } + }); +} + +} // namespace ros2_medkit_fault_manager diff --git a/src/ros2_medkit_fault_manager/src/rosbag_capture.cpp b/src/ros2_medkit_fault_manager/src/rosbag_capture.cpp index fb3be1d36..6c905200d 100644 --- a/src/ros2_medkit_fault_manager/src/rosbag_capture.cpp +++ b/src/ros2_medkit_fault_manager/src/rosbag_capture.cpp @@ -33,7 +33,6 @@ #include #include #include -#include #include #include "ros2_medkit_fault_manager/core/recording_manifest.hpp" @@ -237,6 +236,39 @@ RosbagCapture::RosbagCapture(rclcpp::Node * node, FaultStorage * storage, const throw std::invalid_argument("RosbagCapture requires a valid storage pointer"); } + core::RosbagRetentionLimits limits; + limits.max_bags_per_fault = config_.max_bags_per_fault; + limits.max_total_bytes = config_.max_total_storage_mb * 1024 * 1024; + limits.auto_cleanup = config_.auto_cleanup; + own_log_sink_ = std::make_unique(); + const std::string logger_name = node_->get_logger().get_name(); + retention_ = std::make_shared(*storage_, limits, *own_log_sink_, logger_name); + retention_worker_ = std::make_shared(*own_log_sink_, logger_name, RetentionWorker::Mode::kInline); + init(std::move(storage_probe)); +} + +RosbagCapture::RosbagCapture(rclcpp::Node * node, FaultStorage * storage, const RosbagConfig & config, + const SnapshotConfig & snapshot_config, std::shared_ptr retention, + std::shared_ptr retention_worker, StorageProbeFn storage_probe) + : node_(node) + , storage_(storage) + , config_(config) + , snapshot_config_(snapshot_config) + , retention_(std::move(retention)) + , retention_worker_(std::move(retention_worker)) { + if (!node_) { + throw std::invalid_argument("RosbagCapture requires a valid node pointer"); + } + if (!storage_) { + throw std::invalid_argument("RosbagCapture requires a valid storage pointer"); + } + if (!retention_ || !retention_worker_) { + throw std::invalid_argument("RosbagCapture requires a retention and a retention worker"); + } + init(std::move(storage_probe)); +} + +void RosbagCapture::init(StorageProbeFn storage_probe) { storage_probe_ = storage_probe ? std::move(storage_probe) : [this](const std::string & f) { return default_storage_probe(f); }; @@ -673,13 +705,30 @@ void RosbagCapture::on_fault_cleared(const std::string & fault_code) { } } - // Delete the bag file for this fault. Called from the clear service, where a throw terminates the process. - // Under clear_rows_mutex_: a row the store worker is inserting lands before this delete, never after. + // Called from the clear service, where a throw terminates the process. The retention orders this + // removal against a store in progress. The directories go on the retention worker: one line per + // removed recording, then one line for the fault once all of them are gone. try { - std::lock_guard rows_lock(clear_rows_mutex_); - if (storage_->delete_rosbag_file(fault_code)) { + auto removal = retention_->on_fault_cleared(fault_code); + if (removal.removed_rows == 0) { + return; + } + if (removal.unlink_paths.empty()) { + // A sibling of the burst still names the bag: the rows are gone and no directory is. RCLCPP_INFO(node_->get_logger(), "Auto-cleanup: deleted bag file for fault '%s'", fault_code.c_str()); + return; } + // The job runs on the worker, so the worker outlives it. + retention_worker_->post("clear", [worker = retention_worker_.get(), logger = node_->get_logger(), fault_code, + freed = std::move(removal.unlink_paths)]() { + bool removed_all = true; + for (const auto & recording : freed) { + removed_all = worker->remove_recording(recording) && removed_all; + } + if (removed_all) { + RCLCPP_INFO(logger, "Auto-cleanup: deleted bag file for fault '%s'", fault_code.c_str()); + } + }); } catch (const std::exception & e) { RCLCPP_WARN(node_->get_logger(), "Auto-cleanup of the bag for fault '%s' failed: %s", fault_code.c_str(), e.what()); } @@ -1438,57 +1487,6 @@ size_t RosbagCapture::calculate_bag_size(const std::string & bag_path) const { return total_size; } -std::vector RosbagCapture::evict_bags_over_quota(FaultStorage * storage, size_t max_bytes, - const std::string & keep_recording_id) { - size_t current_bytes = storage->get_total_rosbag_storage_bytes(); - if (current_bytes <= max_bytes) { - return {}; - } - - // get_all_rosbag_files() is one row per (fault, recording) link: a burst of - // correlated faults shares one recording, and one fault can hold several. Group - // the rows back into bags first: deleting a single row of a shared bag leaves the - // directory on disk (a sibling still points at it), so freeing its bytes per row - // would drop the running total below the real one and stop the eviction while the - // quota is still blown. - std::vector paths_oldest_first; - std::unordered_map recording_by_path; - std::unordered_map bytes_by_path; - for (const auto & bag : storage->get_all_rosbag_files()) { - // First row for this path decides its position in the oldest-first order; the - // rows arrive sorted, so that is the recording's own age. - if (recording_by_path.emplace(bag.file_path, bag.recording_id).second) { - paths_oldest_first.push_back(bag.file_path); - } - // Mirror the storage accounting, which takes the largest row per path. - auto & bytes = bytes_by_path[bag.file_path]; - bytes = std::max(bytes, bag.size_bytes); - } - - std::vector evicted; - for (const auto & path : paths_oldest_first) { - if (current_bytes <= max_bytes) { - break; - } - if (!keep_recording_id.empty() && recording_by_path[path] == keep_recording_id) { - continue; - } - - // By RECORDING, not by fault code. The unit being evicted is a bag, and a - // fault can now hold several: deleting by code would take this fault's other, - // newer recordings with it, and their directories would never be unlinked - // because their paths were never collected - invisible to the quota from then - // on. One call per bag, so the SQLite backend still removes the whole burst's - // rows in one transaction and unlinks after the commit. - storage->delete_rosbag_recording(recording_by_path[path]); - // Saturate rather than wrap: the quota must never be satisfied by underflow. - current_bytes -= std::min(current_bytes, bytes_by_path[path]); - evicted.push_back(path); - } - - return evicted; -} - int64_t RosbagCapture::bounded_history_ns(int64_t now_wall_ns, int64_t oldest_msg_wall_ns, int64_t now_steady_ns, int64_t capture_started_steady_ns) { // Saturating, not wrapping. Signed overflow is undefined, and this is a public @@ -1512,20 +1510,6 @@ int64_t RosbagCapture::bounded_history_ns(int64_t now_wall_ns, int64_t oldest_ms return std::clamp(difference(now_wall_ns, oldest_msg_wall_ns), 0, uptime_ns); } -void RosbagCapture::enforce_storage_limits(const std::string & keep_recording_id) { - const size_t max_bytes = config_.max_total_storage_mb * 1024 * 1024; - for (const auto & path : evict_bags_over_quota(storage_, max_bytes, keep_recording_id)) { - RCLCPP_INFO(node_->get_logger(), "Deleted old bag '%s' to enforce storage limit", path.c_str()); - } - // Everything older is gone by now, so what is left over the quota is the kept recording alone. - if (!keep_recording_id.empty() && storage_->get_total_rosbag_storage_bytes() > max_bytes) { - RCLCPP_WARN(node_->get_logger(), - "Recording '%s' alone exceeds snapshots.rosbag.max_total_storage_mb (%zu MB); it is kept, and the " - "storage stays over the limit until a newer recording replaces it", - keep_recording_id.c_str(), config_.max_total_storage_mb); - } -} - void RosbagCapture::write_manifest(const std::string & bag_path, int64_t created_at_ns) { try { if (const auto error = core::write_recording_manifest(bag_path, created_at_ns)) { @@ -1536,65 +1520,14 @@ void RosbagCapture::write_manifest(const std::string & bag_path, int64_t created } } -bool RosbagCapture::row_still_wanted(const std::string & code) { - // Same rule as on_fault_cleared: without auto_cleanup, or with a history - // configured, a cleared fault keeps its black box. Checking only auto_cleanup - // here let an acknowledgement arriving during the post-roll drop every row and - // delete the bag, while on_fault_cleared had just decided to keep it. - if (!config_.auto_cleanup || keeps_history()) { - return true; - } - // A throw terminates the store worker's process. A store that cannot answer keeps - // the row: the bag stays referenced. - std::optional fault; - try { - fault = storage_->get_fault(code); - } catch (const std::exception & e) { - RCLCPP_WARN(node_->get_logger(), "Could not read fault '%s' before storing its bag, keeping its row: %s", - code.c_str(), e.what()); - return true; - } - // Absent is not cleared. A caller driving the capture directly, or a fault the - // store never saw, must keep its row - only a fault the store still holds AND - // reports as cleared loses one. - return !fault.has_value() || fault->status != fd::fault_status::kCleared; -} - bool RosbagCapture::store_rows_or_discard_bag(std::vector rows, const std::string & bag_path) { - // Reported rather than logged inside the handler, because a handler cannot throw - // here and building the message is the one part that could. - const char * store_error = nullptr; - std::string store_error_text; - { - // A fault cleared meanwhile gets no row. The store is asked, not a flag captured - // earlier: on_fault_cleared() drops a code from the recording state only when the - // guard was published at the moment the clear arrived. The check and the insert - // hold clear_rows_mutex_, which on_fault_cleared() holds for its delete, and the - // store marks a fault cleared before on_fault_cleared() runs. So a clear either - // shows here as cleared, or its delete runs after the insert and takes the row. - std::lock_guard lock(clear_rows_mutex_); - rows.erase(std::remove_if(rows.begin(), rows.end(), - [this](const RosbagFileInfo & row) { - return !row_still_wanted(row.fault_code); - }), - rows.end()); - if (!rows.empty()) { - try { - storage_->store_rosbag_files(rows); - } catch (const std::exception & e) { - store_error_text = e.what(); - store_error = store_error_text.c_str(); - } catch (...) { - // The storage interface promises nothing about what a backend throws, and this - // function is called from a path that reaches ~RosbagCapture through stop(). - // An escape there terminates the process during shutdown. - store_error_text = "unknown exception"; - store_error = store_error_text.c_str(); - } - } + auto outcome = retention_->store(std::move(rows)); + // On this thread, with the retention mutex released, and before the caller logs the stored bag. + for (const auto & recording : outcome.unlink_paths) { + retention_worker_->remove_recording(recording); } - if (rows.empty()) { + if (outcome.result == core::StoreResult::kAllFaultsCleared) { // Every fault of the recording was cleared before its row was stored; nothing // references the bag, so it goes the way auto-cleanup would have taken it. std::error_code ec; @@ -1604,7 +1537,7 @@ bool RosbagCapture::store_rows_or_discard_bag(std::vector rows, return false; } - if (store_error != nullptr) { + 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 // on disk unreachable and uncounted, and the next full storage would not even @@ -1617,30 +1550,16 @@ bool RosbagCapture::store_rows_or_discard_bag(std::vector rows, RCLCPP_WARN(node_->get_logger(), "Failed to store rosbag metadata for '%s' (%s), and the bag could not be removed either (%s); " "it is now unreachable and uncounted on disk", - bag_path.c_str(), store_error, ec.message().c_str()); + bag_path.c_str(), outcome.error.c_str(), ec.message().c_str()); } else { RCLCPP_WARN(node_->get_logger(), "Failed to store rosbag metadata for '%s' (%s); discarded the bag, nothing could reference it", - bag_path.c_str(), store_error); + bag_path.c_str(), outcome.error.c_str()); } return false; } - // Separate handler, and deliberately outside the discard above. store_rosbag_files() - // commits before it returns, so from here the rows are durable: eviction sweeps the - // whole store and a failure here says nothing about this bag. Removing the directory - // on that failure would strand the rows just written - unreadable for good, and still - // charged against max_total_storage_mb, which sums rows. A missed sweep costs a late - // quota, and the next capture runs it again. - try { - enforce_storage_limits(rows.empty() ? std::string() : rows.front().recording_id); - } catch (const std::exception & e) { - RCLCPP_WARN(node_->get_logger(), "Failed to enforce the rosbag storage limit after storing '%s': %s", - bag_path.c_str(), e.what()); - } catch (...) { - RCLCPP_WARN(node_->get_logger(), "Failed to enforce the rosbag storage limit after storing '%s': unknown exception", - bag_path.c_str()); - } + // A failed quota leaves the rows stored, so the bag stays: the retention has logged it. return true; } diff --git a/src/ros2_medkit_fault_manager/src/sqlite_fault_storage.cpp b/src/ros2_medkit_fault_manager/src/sqlite_fault_storage.cpp index 8ec07d758..35166f7a6 100644 --- a/src/ros2_medkit_fault_manager/src/sqlite_fault_storage.cpp +++ b/src/ros2_medkit_fault_manager/src/sqlite_fault_storage.cpp @@ -512,8 +512,8 @@ void SqliteFaultStorage::migrate_rosbag_files_add_recording_id() { update.bind_text(1, rosbag_recording_id(file_path)); update.bind_int64(2, row_id); // A dropped result here (SQLITE_BUSY, SQLITE_FULL) would leave the row with an - // empty recording_id while COMMIT still reported success, and an empty id is - // what delete_rosbag_recording refuses to act on. + // empty recording_id while COMMIT still reported success, and a removal by + // recording id matches no row with an empty id. if (update.step() != SQLITE_DONE) { throw std::runtime_error(std::string("Failed to backfill recording_id: ") + sqlite3_errmsg(db_)); } @@ -1422,55 +1422,6 @@ void SqliteFaultStorage::exec_or_throw(const char * sql) { } } -void SqliteFaultStorage::set_max_rosbags_per_fault(size_t max_count) { - std::lock_guard lock(mutex_); - max_rosbags_per_fault_ = max_count; -} - -void SqliteFaultStorage::store_rosbag_file(const RosbagFileInfo & info) { - // Routed through the batch path deliberately: with a per-fault cap a single - // store is insert + trim, i.e. several statements that must share one - // transaction and one post-commit unlink pass. - store_rosbag_files({info}); -} - -void SqliteFaultStorage::store_rosbag_files(const std::vector & infos) { - if (infos.empty()) { - return; - } - std::lock_guard lock(mutex_); - - // One transaction for the whole burst: a crash mid-store must not leave some - // faults of the shared recording without their lookup row. Evicted bags are - // unlinked only after COMMIT - a ROLLBACK resurrects the rows, which must keep - // pointing at bags that still exist. - std::vector evicted; - exec_or_throw("BEGIN IMMEDIATE"); - try { - for (const auto & info : infos) { - auto paths = store_rosbag_file_locked(info); - evicted.insert(evicted.end(), std::make_move_iterator(paths.begin()), std::make_move_iterator(paths.end())); - } - exec_or_throw("COMMIT"); - } catch (...) { - sqlite3_exec(db_, "ROLLBACK", nullptr, nullptr, nullptr); - throw; - } - - // Referencing is re-checked on the committed state, not on the state each - // eviction saw: two faults of one burst can link the same bag, and a row-by-row - // check inside the loop would find it still held by a sibling that a later - // iteration then evicts, leaking the directory. - std::set unique_paths(evicted.begin(), evicted.end()); - for (const auto & path : unique_paths) { - if (path_referenced(path)) { - continue; - } - std::error_code ec; - std::filesystem::remove_all(path, ec); - } -} - RosbagApplyResult SqliteFaultStorage::apply_rosbag_changes(const RosbagChangeSet & changes) { check_rosbag_change_set(changes); std::lock_guard lock(mutex_); @@ -1543,81 +1494,6 @@ RosbagApplyResult SqliteFaultStorage::apply_rosbag_changes(const RosbagChangeSet return result; } -std::vector SqliteFaultStorage::store_rosbag_file_locked(const RosbagFileInfo & info) { - RosbagFileInfo row = info; - if (row.recording_id.empty()) { - row.recording_id = rosbag_recording_id(row.file_path); - } - - // Upserts on idx_rosbag_files_fault_path, i.e. on the (fault, recording) link. - // Re-storing the SAME link refreshes it; a link to a DIFFERENT recording is a new - // row now, which is the feature. Nothing is unlinked here - byte lifetime is the - // cap's business below, and the caller's, after the commit. - // - // ON CONFLICT DO UPDATE, not INSERT OR REPLACE: the latter deletes the row and - // inserts a fresh one, so a refresh silently moves the link to the end of the id - // order. Every read below breaks created_at_ns ties by id, and the in-memory - // backend keeps its sequence number across a refresh, so REPLACE would put the - // two backends in a different order for a re-stored row inside a tie group. - SqliteStatement stmt(db_, - "INSERT INTO rosbag_files " - "(fault_code, recording_id, file_path, format, duration_sec, size_bytes, created_at_ns) " - "VALUES (?, ?, ?, ?, ?, ?, ?) " - "ON CONFLICT(fault_code, file_path) DO UPDATE SET " - "recording_id = excluded.recording_id, format = excluded.format, " - "duration_sec = excluded.duration_sec, size_bytes = excluded.size_bytes, " - "created_at_ns = excluded.created_at_ns"); - - stmt.bind_text(1, row.fault_code); - stmt.bind_text(2, row.recording_id); - stmt.bind_text(3, row.file_path); - stmt.bind_text(4, row.format); - // Bind duration_sec as a double using sqlite3_bind_double directly - if (sqlite3_bind_double(stmt.get(), 5, row.duration_sec) != SQLITE_OK) { - throw std::runtime_error(std::string("Failed to bind duration_sec: ") + sqlite3_errmsg(db_)); - } - stmt.bind_int64(6, static_cast(row.size_bytes)); - stmt.bind_int64(7, row.created_at_ns); - - if (stmt.step() != SQLITE_DONE) { - throw std::runtime_error(std::string("Failed to store rosbag file: ") + sqlite3_errmsg(db_)); - } - - if (max_rosbags_per_fault_ == 0) { - return {}; // unlimited per fault; only the global byte quota bounds this - } - - // Keep the newest N recordings of this fault. Oldest-first eviction, the same - // direction as evict_bags_over_quota, so the two eviction owners never need a - // tiebreak. At N = 1 this reproduces the pre-#620 behaviour exactly: the new - // recording replaces the old and the old bag is unlinked. - const char * const doomed_sql = - "FROM rosbag_files WHERE fault_code = ?1 AND id NOT IN " - "(SELECT id FROM rosbag_files WHERE fault_code = ?1 " - " ORDER BY created_at_ns DESC, id DESC LIMIT ?2)"; - - std::vector evicted; - { - SqliteStatement select(db_, (std::string("SELECT DISTINCT file_path ") + doomed_sql).c_str()); - select.bind_text(1, row.fault_code); - select.bind_int64(2, static_cast(max_rosbags_per_fault_)); - while (select.step() == SQLITE_ROW) { - evicted.push_back(select.column_text(0)); - } - } - if (evicted.empty()) { - return {}; - } - - SqliteStatement del(db_, (std::string("DELETE ") + doomed_sql).c_str()); - del.bind_text(1, row.fault_code); - del.bind_int64(2, static_cast(max_rosbags_per_fault_)); - if (del.step() != SQLITE_DONE) { - throw std::runtime_error(std::string("Failed to trim rosbag rows: ") + sqlite3_errmsg(db_)); - } - return evicted; -} - namespace { /// Shared projection so every rosbag read decodes the same column order. @@ -1668,54 +1544,6 @@ std::vector SqliteFaultStorage::get_rosbag_files_by_recording(co return result; } -size_t SqliteFaultStorage::delete_rosbag_recording(const std::string & recording_id) { - // An empty id is not a recording that happens to be unnamed, it is a row whose - // backfill did not finish. Matching on it would take every such row of every - // fault with one DELETE, and evict_bags_over_quota calls this with whatever the - // row held. - if (recording_id.empty()) { - return 0; - } - - std::lock_guard lock(mutex_); - - std::set paths; - { - SqliteStatement select(db_, "SELECT DISTINCT file_path FROM rosbag_files WHERE recording_id = ?"); - select.bind_text(1, recording_id); - while (select.step() == SQLITE_ROW) { - paths.insert(select.column_text(0)); - } - } - if (paths.empty()) { - return 0; - } - - size_t removed = 0; - exec_or_throw("BEGIN IMMEDIATE"); - try { - SqliteStatement del(db_, "DELETE FROM rosbag_files WHERE recording_id = ?"); - del.bind_text(1, recording_id); - if (del.step() != SQLITE_DONE) { - throw std::runtime_error(std::string("Failed to delete rosbag recording: ") + sqlite3_errmsg(db_)); - } - removed = static_cast(sqlite3_changes(db_)); - exec_or_throw("COMMIT"); - } catch (...) { - sqlite3_exec(db_, "ROLLBACK", nullptr, nullptr, nullptr); - throw; - } - - for (const auto & path : paths) { - if (path_referenced(path)) { - continue; // another recording writes into the same directory - leave it - } - std::error_code ec; - std::filesystem::remove_all(path, ec); - } - return removed; -} - std::optional SqliteFaultStorage::get_rosbag_file(const std::string & fault_code) const { std::lock_guard lock(mutex_); @@ -1746,96 +1574,6 @@ std::optional SqliteFaultStorage::get_rosbag_file(const std::str return info; } -bool SqliteFaultStorage::delete_rosbag_file(const std::string & fault_code) { - std::lock_guard lock(mutex_); - - // Every path, not the first one: a fault holds as many recordings as its cap - // allows, and stepping once would unlink one bag and leak the rest - rows gone, - // directories left behind, uncounted by a quota that sums rows. - std::set paths; - { - SqliteStatement select_stmt(db_, "SELECT file_path FROM rosbag_files WHERE fault_code = ?"); - select_stmt.bind_text(1, fault_code); - while (select_stmt.step() == SQLITE_ROW) { - paths.insert(select_stmt.column_text(0)); - } - } - - // Row first, file after, exactly as delete_rosbag_files() does it. The step() - // below throws on a busy, full or unwritable database; with the unlink already - // done, that would leave a surviving row pointing at a bag that is gone - - // unreadable for good, and still charged against the storage quota, which sums - // rows. This way the worst case is an orphaned directory instead. - SqliteStatement delete_stmt(db_, "DELETE FROM rosbag_files WHERE fault_code = ?"); - delete_stmt.bind_text(1, fault_code); - - if (delete_stmt.step() != SQLITE_DONE) { - throw std::runtime_error(std::string("Failed to delete rosbag file record: ") + sqlite3_errmsg(db_)); - } - - const bool deleted = sqlite3_changes(db_) > 0; - - // Unlink only once no fault references the bag any more. These rows are already - // gone, so path_referenced() sees exactly the siblings of a shared recording. - for (const auto & path : paths) { - if (!path_referenced(path)) { - std::error_code ec; - std::filesystem::remove_all(path, ec); - // Ignore errors - file may already be deleted - } - } - - return deleted; -} - -size_t SqliteFaultStorage::delete_rosbag_files(const std::vector & fault_codes) { - if (fault_codes.empty()) { - return 0; - } - std::lock_guard lock(mutex_); - - // Rows go first, in one transaction, and the file only after the commit: a - // crash mid-delete leaves at worst an orphaned directory, never a row whose - // bag is already gone. - std::set paths; - size_t deleted = 0; - exec_or_throw("BEGIN IMMEDIATE"); - try { - for (const auto & code : fault_codes) { - { - // while, not if: one fault code can name several recordings now, and the - // sweep must be able to reclaim every one of their bags. - SqliteStatement select_stmt(db_, "SELECT file_path FROM rosbag_files WHERE fault_code = ?"); - select_stmt.bind_text(1, code); - while (select_stmt.step() == SQLITE_ROW) { - paths.insert(select_stmt.column_text(0)); - } - } - SqliteStatement delete_stmt(db_, "DELETE FROM rosbag_files WHERE fault_code = ?"); - delete_stmt.bind_text(1, code); - if (delete_stmt.step() != SQLITE_DONE) { - throw std::runtime_error(std::string("Failed to delete rosbag file record: ") + sqlite3_errmsg(db_)); - } - if (sqlite3_changes(db_) > 0) { - ++deleted; - } - } - exec_or_throw("COMMIT"); - } catch (...) { - sqlite3_exec(db_, "ROLLBACK", nullptr, nullptr, nullptr); - throw; - } - - for (const auto & path : paths) { - if (!path_referenced(path)) { - std::error_code ec; - std::filesystem::remove_all(path, ec); - // Ignore errors - file may already be deleted - } - } - return deleted; -} - bool SqliteFaultStorage::path_referenced(const std::string & file_path) const { SqliteStatement stmt(db_, "SELECT COUNT(*) FROM rosbag_files WHERE file_path = ?"); stmt.bind_text(1, file_path); 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 e8d2d4d5f..172b14298 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 @@ -23,6 +23,7 @@ import os import pathlib +import re import shutil import sys @@ -34,12 +35,21 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) from rosbag_fm_harness import ( # noqa: E402 - bag_dirs, MIB, poll, RetentionCase, sqlite_exec, Ticker, + bag_dirs, FM_NODE, MESSAGE_SIZE, MIB, poll, RetentionCase, sqlite_exec, 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 +CLEARED_REMOVAL = r'Recording removed: (\S+) \(fault cleared\)' + + +def make_slow_to_remove(path): + """Fill `path` with empty files, so its removal outlasts the reading of one log line.""" + for index in range(SLOW_REMOVAL_FILES): + with open(os.path.join(path, f'pad_{index}'), 'w'): + pass def generate_test_description(): @@ -299,6 +309,32 @@ def test_shutdown_during_post_roll(self): self.assertTrue(os.path.isdir(served.file_path)) self.assertEqual([code for code, _ in self.stored_rows()], ['SHUT_A']) + def test_shutdown_finalizes_a_cap_victim(self): + """SIGTERM inside a post-roll stores the recording and removes the one its cap replaced.""" + params = {'snapshots.rosbag.max_bags_per_fault': 1, 'snapshots.rosbag.auto_cleanup': False} + with self.fm_run(**params) as fm: + first = self.record(fm, 'SHUT_CAP', 1) + with self.fm_run(**{**params, 'snapshots.rosbag.duration_after_sec': 30.0}) as fm: + self.assertTrue(self.client.clear('SHUT_CAP').success) + mark = fm.mark() + self.client.publish_bytes(8, 128 * 1024) + self.assertTrue(self.client.report('SHUT_CAP').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:]) + self.assertEqual(fm.terminate(), 0, fm.output()[-3000:]) + self.assertFalse(os.path.exists(first), f'{first} outlived the row the cap removed') + dirs = bag_dirs(self.storage) + self.assertEqual(len(dirs), 1, f'expected only the replacement, found {dirs}') + replacement = os.path.join(self.storage, dirs[0]) + with self.fm_run(**params): + served = self.client.get_rosbag('SHUT_CAP') + self.assertTrue(served.success, served.error_message) + self.assertEqual(served.file_path, replacement) + self.assertTrue(os.path.isdir(replacement)) + self.assertEqual(self.stored_rows(), [('SHUT_CAP', replacement)]) + self.assertFalse(os.path.exists(first)) + def test_shutdown_right_after_clear(self): """SIGTERM as soon as ClearFault returns leaves no directory and a clean exit.""" with self.fm_run() as fm: @@ -308,6 +344,142 @@ def test_shutdown_right_after_clear(self): self.assertFalse(os.path.exists(bag)) self.assertEqual(bag_dirs(self.storage), []) + def test_shutdown_drains_queued_removals(self): + """SIGTERM with clear removals still queued runs them all before the exit.""" + with self.fm_run() as fm: + bags = [self.record(fm, 'DRAIN_A', 1), self.record(fm, 'DRAIN_B', 1)] + for bag in bags: + make_slow_to_remove(bag) + self.assertTrue(self.client.clear('DRAIN_A').success) + self.assertTrue(self.client.clear('DRAIN_B').success) + self.assertEqual(fm.terminate(), 0, fm.output()[-3000:]) + output = fm.output() + for bag in bags: + self.assertFalse(os.path.exists(bag), + f'{bag} outlived the shutdown:\n{output[-4000:]}') + self.assertEqual(bag_dirs(self.storage), []) + + def test_no_removal_line_for_a_missing_directory(self): + """A clear whose directory is already gone logs no removal of it.""" + with self.fm_run(**{'snapshots.rosbag.max_bags_per_fault': 1, + 'snapshots.rosbag.auto_cleanup': True}) as fm: + bag = self.record(fm, 'GONE_DIR', 1) + shutil.rmtree(bag) + mark = fm.mark() + self.assertTrue(self.client.clear('GONE_DIR').success) + self.assertIsNotNone( + fm.wait_line(r"Auto-cleanup: deleted bag file for fault 'GONE_DIR'", since=mark), + fm.output()[-3000:]) + removed = f'Recording removed: {os.path.basename(bag)} ' + self.assertEqual(fm.count_lines(re.escape(removed), since=mark), 0, + fm.output()[-3000:]) + + def test_removals_are_logged(self): + """Each removal of a recording is logged after its directory is gone.""" + with self.subTest('a: a cap victim, before the recording that replaced it'): + self.new_scratch() + with self.fm_run(**{'snapshots.rosbag.auto_cleanup': False}) as fm: + first = self.record(fm, 'LOG_CAP', 1) + self.assertTrue(self.client.clear('LOG_CAP').success) + make_slow_to_remove(first) + mark = self.start_store(fm, 'LOG_CAP', 1) + removed = (f'Recording removed: {os.path.basename(first)} ' + f'(max_bags_per_fault)') + self.assertIsNotNone(fm.wait_line(re.escape(removed), since=mark), + fm.output()[-3000:]) + self.assertFalse(os.path.exists(first), f'{first} is still on disk') + self.assert_logged_before(fm, removed, 'LOG_CAP', mark) + + with self.subTest('b: a quota eviction, before the recording that caused it'): + self.new_scratch() + with self.fm_run(**{'snapshots.rosbag.max_bags_per_fault': 0, + 'snapshots.rosbag.max_total_storage_mb': 3}) as fm: + evicted = self.record(fm, 'LOG_QUOTA_A', 2) + make_slow_to_remove(evicted) + mark = self.start_store(fm, 'LOG_QUOTA_B', 2) + line = f"[{FM_NODE}]: Deleted old bag '{evicted}' to enforce storage limit" + self.assertIsNotNone(fm.wait_line(re.escape(line), since=mark), + fm.output()[-3000:]) + self.assertFalse(os.path.exists(evicted), f'{evicted} is still on disk') + self.assert_logged_before(fm, line, 'LOG_QUOTA_B', mark) + + with self.subTest('c: a clear'): + self.new_scratch() + with self.fm_run() as fm: + bag = self.record(fm, 'LOG_CLEAR', 1) + mark = fm.mark() + self.assertTrue(self.client.clear('LOG_CLEAR').success) + self.assertIsNotNone( + fm.wait_line(r"Auto-cleanup: deleted bag file for fault 'LOG_CLEAR'", + since=mark), + fm.output()[-3000:]) + self.assertFalse(os.path.exists(bag), f'{bag} is still on disk') + + with self.subTest('d: a clear of a fault with two recordings'): + self.new_scratch() + with self.fm_run(**{'snapshots.rosbag.max_bags_per_fault': 0, + 'snapshots.rosbag.auto_cleanup': False}) as fm: + bags = [self.record(fm, 'LOG_TWO', 1)] + self.assertTrue(self.client.clear('LOG_TWO').success) + bags.append(self.record(fm, 'LOG_TWO', 1)) + self.assertEqual(sorted(self.row_paths('LOG_TWO')), sorted(bags)) + by_id = {os.path.basename(bag): bag for bag in bags} + for bag in bags: + make_slow_to_remove(bag) + with self.fm_run(**{'snapshots.rosbag.max_bags_per_fault': 1, + 'snapshots.rosbag.auto_cleanup': True}) as fm: + mark = fm.mark() + self.assertTrue(self.client.clear('LOG_TWO').success) + seen = [] + for _ in bags: + others = ''.join(f'(?!{re.escape(done)} )' for done in seen) + match = fm.wait_line(r'Recording removed: ' + others + + r'(\S+) \(fault cleared\)', since=mark) + self.assertIsNotNone(match, fm.output()[-3000:]) + self.assertIn(match.group(1), by_id) + self.assertFalse(os.path.exists(by_id[match.group(1)]), + f'{by_id[match.group(1)]} is still on disk') + seen.append(match.group(1)) + auto = r"Auto-cleanup: deleted bag file for fault 'LOG_TWO'" + self.assertIsNotNone(fm.wait_line(auto, since=mark), fm.output()[-3000:]) + self.assertEqual(fm.count_lines(CLEARED_REMOVAL, since=mark), 2) + self.assertEqual(fm.count_lines(auto, since=mark), 1) + output = fm.output() + for recording_id in seen: + self.assertLess( + output.index(f'Recording removed: {recording_id} (fault cleared)'), + output.index("Auto-cleanup: deleted bag file for fault 'LOG_TWO'"), + 'the fault was logged before the removal of its recording') + + with self.subTest('e: a clear removes on the worker, after its reply'): + self.new_scratch() + with self.fm_run() as fm: + bag = self.record(fm, 'LOG_WORKER', 1) + make_slow_to_remove(bag) + mark = fm.mark() + self.assertTrue(self.client.clear('LOG_WORKER').success) + self.assertTrue(os.path.isdir(bag), + 'the clear removed the directory before its reply') + removed = f'Recording removed: {os.path.basename(bag)} (fault cleared)' + self.assertIsNotNone(fm.wait_line(re.escape(removed), since=mark), + fm.output()[-3000:]) + self.assertFalse(os.path.exists(bag), f'{bag} is still on disk') + + def start_store(self, fm, code, mib): + """Publish `mib` MiB and confirm `code` without waiting for the bag; return a mark.""" + mark = fm.mark() + self.client.publish_bytes(int(mib * MIB) // MESSAGE_SIZE, MESSAGE_SIZE) + self.assertTrue(self.client.report(code).accepted) + return mark + + def assert_logged_before(self, fm, removal, code, mark): + """Wait for the bag of `code` and check `removal` was logged before it.""" + done = fm.wait_line(rf'Bag file (?:created|completed): \S*fault_{code}_\d+', since=mark) + self.assertIsNotNone(done, f'no recording for {code}:\n' + fm.output()[-3000:]) + output = fm.output() + self.assertLess(output.index(removal), output.index(done.group(0)), + 'the recording was logged before the removal it caused') + def test_stale_rows(self): """A row whose directory is gone is reaped on the next listing, with rosbag on or off.""" with self.subTest('rosbag off on the next run'): 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 9dc827288..2fb7587b1 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 @@ -83,7 +83,12 @@ def test_clear_removes_the_row_and_the_directory(self): with self.fm_run() as fm: bag = self.record(fm, 'PG_A', 1) self.assert_recording_present('PG_A', bag) + mark = fm.mark() self.assertTrue(self.client.clear('PG_A').success) - self.assert_recording_gone('PG_A', bag) self.assertEqual(self.stored_rows(), []) + # The line is logged once the directory is removed. + self.assertIsNotNone( + fm.wait_line(r"Auto-cleanup: deleted bag file for fault 'PG_A'", since=mark), + fm.output()[-3000:]) + self.assert_recording_gone('PG_A', bag) self.assertEqual(bag_dirs(self.storage), []) diff --git a/src/ros2_medkit_fault_manager/test/test_fault_manager.cpp b/src/ros2_medkit_fault_manager/test/test_fault_manager.cpp index 7050e1d16..615531a0d 100644 --- a/src/ros2_medkit_fault_manager/test/test_fault_manager.cpp +++ b/src/ros2_medkit_fault_manager/test/test_fault_manager.cpp @@ -48,6 +48,7 @@ #include "ros2_medkit_msgs/srv/list_rosbags.hpp" #include "ros2_medkit_msgs/srv/report_fault.hpp" #include "test_log_sink.hpp" +#include "test_rosbag_rows.hpp" using ros2_medkit_fault_manager::clamp_debounce_counter; using ros2_medkit_fault_manager::compute_debounce_status; @@ -1676,7 +1677,7 @@ TEST_F(FaultEventPublishingTest, GetFaultReportsARecordingsServedBytesNotItsFoot ASSERT_GT(bag.footprint, bag.served) << "metadata.yaml did not land, so there is nothing to tell apart"; ASSERT_TRUE(call_report_fault("SERVED_BYTES_FAULT", Fault::SEVERITY_ERROR, "/test_node")); - fault_manager_->get_storage_for_test().store_rosbag_file(bag.row_for("SERVED_BYTES_FAULT")); + seed_rosbag_rows(fault_manager_->get_storage_for_test(), {bag.row_for("SERVED_BYTES_FAULT")}); auto response = call_get_fault("SERVED_BYTES_FAULT"); ASSERT_TRUE(response.has_value()); @@ -1708,7 +1709,7 @@ TEST_F(FaultEventPublishingTest, EveryRosbagServiceReportsTheServedBytes) { ASSERT_TRUE(call_report_fault("ALL_SERVICES_FAULT", Fault::SEVERITY_ERROR, "/test_node")); const auto row = bag.row_for("ALL_SERVICES_FAULT"); - fault_manager_->get_storage_for_test().store_rosbag_file(row); + seed_rosbag_rows(fault_manager_->get_storage_for_test(), {row}); const std::string ns = test_node_->get_namespace(); @@ -1769,7 +1770,7 @@ TEST_F(FaultEventPublishingTest, GetSnapshotsDoesNotAdvertiseARouteThatWasRemove ReportedBag bag("no_download_url"); ASSERT_TRUE(call_report_fault("NO_URL_FAULT", Fault::SEVERITY_ERROR, "/test_node")); - fault_manager_->get_storage_for_test().store_rosbag_file(bag.row_for("NO_URL_FAULT")); + seed_rosbag_rows(fault_manager_->get_storage_for_test(), {bag.row_for("NO_URL_FAULT")}); auto client = test_node_->create_client(std::string(test_node_->get_namespace()) + "/fault_manager/get_snapshots"); @@ -2039,64 +2040,6 @@ TEST(InMemoryFreezeFrameTest, SurvivesClearFault) { EXPECT_EQ(retrieved->data, frame.data); } -// --- InMemoryFaultStorage shared-rosbag re-store tests --- -// A fault re-confirming stores a row with a new path; the old bag must be -// unlinked only when no sibling fault of the burst still references it. - -TEST(InMemoryRosbagRestoreTest, RestoreWithNewPathUnlinksTheOldExclusiveBag) { - InMemoryFaultStorage storage; - - const auto old_path = (std::filesystem::temp_directory_path() / "medkit_restore_exclusive_bag").string(); - std::filesystem::create_directories(old_path); - - ros2_medkit_fault_manager::RosbagFileInfo info; - info.fault_code = "X"; - info.file_path = old_path; - info.format = "mcap"; - info.duration_sec = 5.0; - info.size_bytes = 100; - info.created_at_ns = 1000; - storage.store_rosbag_file(info); - - info.file_path = old_path + "_new"; - storage.store_rosbag_file(info); - - EXPECT_FALSE(std::filesystem::exists(old_path)) << "nobody references the old bag, it must be unlinked"; - auto row = storage.get_rosbag_file("X"); - ASSERT_TRUE(row.has_value()); - EXPECT_EQ(row->file_path, old_path + "_new"); -} - -TEST(InMemoryRosbagRestoreTest, RestoreWithNewPathKeepsTheBagASiblingStillReferences) { - InMemoryFaultStorage storage; - - const auto shared_path = (std::filesystem::temp_directory_path() / "medkit_restore_shared_bag").string(); - std::filesystem::create_directories(shared_path); - - ros2_medkit_fault_manager::RosbagFileInfo info; - info.file_path = shared_path; - info.format = "mcap"; - info.duration_sec = 5.0; - info.size_bytes = 100; - info.created_at_ns = 1000; - info.fault_code = "X"; - storage.store_rosbag_file(info); - info.fault_code = "Y"; - storage.store_rosbag_file(info); - - info.fault_code = "X"; - info.file_path = shared_path + "_new"; - storage.store_rosbag_file(info); - - EXPECT_TRUE(std::filesystem::exists(shared_path)) << "the sibling fault still owns the shared bag"; - auto sibling = storage.get_rosbag_file("Y"); - ASSERT_TRUE(sibling.has_value()); - EXPECT_EQ(sibling->file_path, shared_path); - - std::error_code ec; - std::filesystem::remove_all(shared_path, ec); -} - // ============================================================================= // Snapshot recapture cooldown test // ============================================================================= diff --git a/src/ros2_medkit_fault_manager/test/test_postgres_storage.cpp b/src/ros2_medkit_fault_manager/test/test_postgres_storage.cpp index d3bdb419e..18fc4e45a 100644 --- a/src/ros2_medkit_fault_manager/test/test_postgres_storage.cpp +++ b/src/ros2_medkit_fault_manager/test/test_postgres_storage.cpp @@ -47,14 +47,18 @@ #include "rclcpp/rclcpp.hpp" #include "rcutils/logging.h" +#include "ros2_medkit_fault_manager/core/rosbag_retention.hpp" #include "ros2_medkit_fault_manager/postgres_fault_storage.hpp" #include "ros2_medkit_msgs/msg/fault.hpp" #include "ros2_medkit_msgs/srv/report_fault.hpp" #include "test_log_sink.hpp" +#include "test_rosbag_rows.hpp" using ros2_medkit_fault_manager::DebounceConfig; using ros2_medkit_fault_manager::PgFaultStorage; using ros2_medkit_fault_manager::RosbagFileInfo; +using ros2_medkit_fault_manager::core::RosbagRetention; +using ros2_medkit_fault_manager::core::RosbagRetentionLimits; using ros2_medkit_msgs::msg::Fault; using ros2_medkit_msgs::srv::ReportFault; @@ -1696,61 +1700,9 @@ RosbagFileInfo make_rosbag(const std::string & code, const std::string & path, i } } // namespace -TEST_F(PgFaultStorageTest, OneFaultKeepsSeveralRecordingsWhenTheCapAllows) { - storage_->set_max_rosbags_per_fault(3); - storage_->store_rosbag_file(make_rosbag("FLAP", "/bags/fault_FLAP_100", 100)); - storage_->store_rosbag_file(make_rosbag("FLAP", "/bags/fault_FLAP_200", 200)); - - const auto rows = storage_->get_rosbag_files("FLAP"); - ASSERT_EQ(rows.size(), 2u) << "the second recording must not replace the first"; - EXPECT_EQ(rows[0].recording_id, "fault_FLAP_200") << "newest first"; - EXPECT_EQ(rows[1].recording_id, "fault_FLAP_100"); - - // get_rosbag_file is "the newest", deterministically. - const auto newest = storage_->get_rosbag_file("FLAP"); - ASSERT_TRUE(newest.has_value()); - EXPECT_EQ(newest->recording_id, "fault_FLAP_200"); -} - -TEST_F(PgFaultStorageTest, CapKeepsTheNewestAndUnlinksTheEvictedBag) { - const auto dir_a = temp_root_ / "fault_CAP_100"; - const auto dir_b = temp_root_ / "fault_CAP_200"; - std::filesystem::create_directories(dir_a); - std::filesystem::create_directories(dir_b); - - storage_->set_max_rosbags_per_fault(1); - storage_->store_rosbag_file(make_rosbag("CAP", dir_a.string(), 100)); - storage_->store_rosbag_file(make_rosbag("CAP", dir_b.string(), 200)); - - const auto rows = storage_->get_rosbag_files("CAP"); - ASSERT_EQ(rows.size(), 1u) << "cap 1 is the historical behaviour: one recording per fault"; - EXPECT_EQ(rows[0].file_path, dir_b.string()); - EXPECT_FALSE(std::filesystem::exists(dir_a)) << "the evicted bag must be unlinked"; - EXPECT_TRUE(std::filesystem::exists(dir_b)); -} - -TEST_F(PgFaultStorageTest, EvictingOneFaultsLinkKeepsABagASiblingStillReferences) { - // A burst shares one recording. Evicting it for one fault must not take the bytes - // the other fault still points at. - const auto shared = temp_root_ / "fault_SHARED_100"; - const auto later = temp_root_ / "fault_A_200"; - std::filesystem::create_directories(shared); - std::filesystem::create_directories(later); - - storage_->set_max_rosbags_per_fault(1); - storage_->store_rosbag_files({make_rosbag("A", shared.string(), 100), make_rosbag("B", shared.string(), 100)}); - // A re-confirms with its own new bag, so A's link to the shared one is evicted. - storage_->store_rosbag_file(make_rosbag("A", later.string(), 200)); - - EXPECT_TRUE(std::filesystem::exists(shared)) << "B still references it"; - const auto b_rows = storage_->get_rosbag_files("B"); - ASSERT_EQ(b_rows.size(), 1u); - EXPECT_EQ(b_rows[0].file_path, shared.string()); -} - TEST_F(PgFaultStorageTest, RecordingLookupReturnsEveryFaultOfTheBurst) { - storage_->store_rosbag_files({make_rosbag("A", "/bags/fault_A_100", 100), make_rosbag("B", "/bags/fault_A_100", 100), - make_rosbag("C", "/bags/fault_A_100", 100)}); + seed_rosbag_rows(*storage_, {make_rosbag("A", "/bags/fault_A_100", 100), make_rosbag("B", "/bags/fault_A_100", 100), + make_rosbag("C", "/bags/fault_A_100", 100)}); const auto rows = storage_->get_rosbag_files_by_recording("fault_A_100"); ASSERT_EQ(rows.size(), 3u) << "the download authorizes against this set"; @@ -1762,28 +1714,34 @@ TEST_F(PgFaultStorageTest, RecordingLookupReturnsEveryFaultOfTheBurst) { TEST_F(PgFaultStorageTest, DeleteRecordingRemovesEveryLinkAndTheBag) { const auto dir = temp_root_ / "fault_A_100"; std::filesystem::create_directories(dir); - storage_->store_rosbag_files({make_rosbag("A", dir.string(), 100), make_rosbag("B", dir.string(), 100)}); + seed_rosbag_rows(*storage_, {make_rosbag("A", dir.string(), 100), make_rosbag("B", dir.string(), 100)}); + RosbagRetention retention(*storage_, RosbagRetentionLimits{}, test_log_sink(), "test_postgres_storage"); - EXPECT_EQ(storage_->delete_rosbag_recording("fault_A_100"), 2u); + const auto removal = retention.forget_recording("fault_A_100"); + expect_unlinkable(removal.unlink_paths); + EXPECT_EQ(removal.removed_rows, 2u); EXPECT_TRUE(storage_->get_rosbag_files("A").empty()); EXPECT_TRUE(storage_->get_rosbag_files("B").empty()); - EXPECT_FALSE(std::filesystem::exists(dir)); + EXPECT_TRUE(listed(removal.unlink_paths, dir.string())); } TEST_F(PgFaultStorageTest, DeletingAFaultDropsAllItsRecordings) { - storage_->set_max_rosbags_per_fault(0); - storage_->store_rosbag_file(make_rosbag("A", "/bags/fault_A_100", 100)); - storage_->store_rosbag_file(make_rosbag("A", "/bags/fault_A_200", 200)); - - EXPECT_TRUE(storage_->delete_rosbag_file("A")); + std::filesystem::create_directories(temp_root_ / "fault_A_100"); + std::filesystem::create_directories(temp_root_ / "fault_A_200"); + seed_rosbag_rows(*storage_, {make_rosbag("A", (temp_root_ / "fault_A_100").string(), 100)}); + seed_rosbag_rows(*storage_, {make_rosbag("A", (temp_root_ / "fault_A_200").string(), 200)}); + RosbagRetention retention(*storage_, RosbagRetentionLimits{}, test_log_sink(), "test_postgres_storage"); + + const auto removal = retention.on_fault_cleared("A"); + expect_unlinkable(removal.unlink_paths); + EXPECT_EQ(removal.removed_rows, 2u); EXPECT_TRUE(storage_->get_rosbag_files("A").empty()) << "auto_cleanup drops the fault's whole history"; } TEST_F(PgFaultStorageTest, SharedRecordingStillCountsOnceTowardsStorageWithSeveralRecordings) { - storage_->set_max_rosbags_per_fault(0); - storage_->store_rosbag_files( - {make_rosbag("A", "/bags/fault_A_100", 100, 4096), make_rosbag("B", "/bags/fault_A_100", 100, 4096)}); - storage_->store_rosbag_file(make_rosbag("A", "/bags/fault_A_200", 200, 1024)); + seed_rosbag_rows( + *storage_, {make_rosbag("A", "/bags/fault_A_100", 100, 4096), make_rosbag("B", "/bags/fault_A_100", 100, 4096)}); + seed_rosbag_rows(*storage_, {make_rosbag("A", "/bags/fault_A_200", 200, 1024)}); EXPECT_EQ(storage_->get_total_rosbag_storage_bytes(), 4096u + 1024u) << "bytes belong to file_path, not to the row"; } @@ -2079,7 +2037,7 @@ TEST_F(PgFaultStorageTest, ListRosbagsForEntityFiltersCorrectly) { info1.duration_sec = 5.0; info1.size_bytes = 1024; info1.created_at_ns = clock.now().nanoseconds(); - storage_->store_rosbag_file(info1); + seed_rosbag_rows(*storage_, {info1}); RosbagFileInfo info2; info2.fault_code = "ENTITY_FAULT_2"; @@ -2088,7 +2046,7 @@ TEST_F(PgFaultStorageTest, ListRosbagsForEntityFiltersCorrectly) { info2.duration_sec = 3.0; info2.size_bytes = 512; info2.created_at_ns = clock.now().nanoseconds(); - storage_->store_rosbag_file(info2); + seed_rosbag_rows(*storage_, {info2}); // Get rosbags for motor entity auto rosbags = storage_->list_rosbags_for_entity("/powertrain/motor"); @@ -2108,15 +2066,15 @@ TEST_F(PgFaultStorageTest, ListRosbagsForEntityFiltersCorrectly) { TEST_F(PgFaultStorageTest, AFailingRowDeleteKeepsTheBagOnDisk) { using ros2_medkit_fault_manager::RosbagFileInfo; - // delete_rosbag_file() has to survive a DELETE that throws - a lock timeout, a - // full disk, a read-only standby - without having already unlinked the bag. A - // surviving row whose directory is gone fails every later retrieval and keeps its - // bytes charged against the quota, which sums rows. + // A clear has to survive a DELETE that throws - a lock timeout, a full disk, a read-only + // standby - without the bag being unlinked. A surviving row whose directory is gone fails + // every later retrieval and keeps its bytes charged against the quota, which sums rows. + // The storage primitive never unlinks, and the retention hands over nothing on a throw. const auto bag_dir = temp_root_ / "failing_delete_bag"; std::filesystem::create_directories(bag_dir); { std::ofstream(bag_dir / "payload.mcap") << "data"; } - storage_->store_rosbag_file(make_rosbag("DELETE_FAILS", bag_dir.string(), 1000, 4)); + seed_rosbag_rows(*storage_, {make_rosbag("DELETE_FAILS", bag_dir.string(), 1000, 4)}); // Make the DELETE, and only the DELETE, fail. A dropped or renamed table would // take the whole statement with it, and the ordering under test is between the @@ -2128,7 +2086,8 @@ TEST_F(PgFaultStorageTest, AFailingRowDeleteKeepsTheBagOnDisk) { "CREATE TRIGGER block_rosbag_delete BEFORE DELETE ON rosbag_files " "FOR EACH ROW EXECUTE PROCEDURE block_rosbag_delete()"); - EXPECT_THROW(storage_->delete_rosbag_file("DELETE_FAILS"), std::runtime_error); + RosbagRetention retention(*storage_, RosbagRetentionLimits{}, test_log_sink(), "test_postgres_storage"); + EXPECT_THROW(retention.on_fault_cleared("DELETE_FAILS"), std::runtime_error); exec_raw("DROP TRIGGER block_rosbag_delete ON rosbag_files"); @@ -2148,7 +2107,7 @@ TEST_F(PgFaultStorageTest, GetAllRosbagFilesReturnsSortedByCreatedAt) { info1.duration_sec = 1.0; info1.size_bytes = 100; info1.created_at_ns = 1000; - storage_->store_rosbag_file(info1); + seed_rosbag_rows(*storage_, {info1}); RosbagFileInfo info2; info2.fault_code = "FAULT_B"; @@ -2157,7 +2116,7 @@ TEST_F(PgFaultStorageTest, GetAllRosbagFilesReturnsSortedByCreatedAt) { info2.duration_sec = 2.0; info2.size_bytes = 200; info2.created_at_ns = 2000; - storage_->store_rosbag_file(info2); + seed_rosbag_rows(*storage_, {info2}); auto all_rosbags = storage_->get_all_rosbag_files(); ASSERT_EQ(all_rosbags.size(), 2u); @@ -2184,17 +2143,22 @@ TEST_F(PgFaultStorageTest, SharedRosbagSurvivesUntilTheLastFaultIsDeleted) { info.duration_sec = 5.0; info.size_bytes = 4096; info.created_at_ns = 1000; - storage_->store_rosbag_file(info); + seed_rosbag_rows(*storage_, {info}); info.fault_code = "CORRELATED"; - storage_->store_rosbag_file(info); + seed_rosbag_rows(*storage_, {info}); + RosbagRetention retention(*storage_, RosbagRetentionLimits{}, test_log_sink(), "test_postgres_storage"); - EXPECT_TRUE(storage_->delete_rosbag_file("CORRELATED")); - EXPECT_TRUE(std::filesystem::exists(bag_path)); + const auto correlated = retention.on_fault_cleared("CORRELATED"); + expect_unlinkable(correlated.unlink_paths); + EXPECT_GT(correlated.removed_rows, 0u); + EXPECT_FALSE(listed(correlated.unlink_paths, bag_path)); EXPECT_TRUE(storage_->get_rosbag_file("ROOT_CAUSE").has_value()); - EXPECT_TRUE(storage_->delete_rosbag_file("ROOT_CAUSE")); - EXPECT_FALSE(std::filesystem::exists(bag_path)); + const auto root = retention.on_fault_cleared("ROOT_CAUSE"); + expect_unlinkable(root.unlink_paths); + EXPECT_GT(root.removed_rows, 0u); + EXPECT_TRUE(listed(root.unlink_paths, bag_path)); } TEST_F(PgFaultStorageTest, SharedRosbagCountsOnceTowardsStorageTotal) { @@ -2212,7 +2176,7 @@ TEST_F(PgFaultStorageTest, SharedRosbagCountsOnceTowardsStorageTotal) { info.duration_sec = 5.0; info.size_bytes = bytes; info.created_at_ns = 1000; - storage_->store_rosbag_file(info); + seed_rosbag_rows(*storage_, {info}); }; store("BIG_FIRST", "/tmp/shared_a.mcap", 1000); @@ -2224,60 +2188,6 @@ TEST_F(PgFaultStorageTest, SharedRosbagCountsOnceTowardsStorageTotal) { EXPECT_EQ(storage_->get_total_rosbag_storage_bytes(), 1000u + 800u + 500u); } -// Re-store guard: a fault re-confirming stores a row with a new path, and the -// old bag must be unlinked only when no sibling fault still references it. - -TEST_F(PgFaultStorageTest, RestoreWithNewPathUnlinksTheOldExclusiveBag) { - using ros2_medkit_fault_manager::RosbagFileInfo; - - const auto old_path = (temp_root_ / "_exclusive_bag").string(); - std::filesystem::create_directories(old_path); - - RosbagFileInfo info; - info.fault_code = "X"; - info.file_path = old_path; - info.format = "mcap"; - info.duration_sec = 5.0; - info.size_bytes = 100; - info.created_at_ns = 1000; - storage_->store_rosbag_file(info); - - info.file_path = old_path + "_new"; - storage_->store_rosbag_file(info); - - EXPECT_FALSE(std::filesystem::exists(old_path)) << "nobody references the old bag, it must be unlinked"; - auto row = storage_->get_rosbag_file("X"); - ASSERT_TRUE(row.has_value()); - EXPECT_EQ(row->file_path, old_path + "_new"); -} - -TEST_F(PgFaultStorageTest, RestoreWithNewPathKeepsTheBagASiblingStillReferences) { - using ros2_medkit_fault_manager::RosbagFileInfo; - - const auto shared_path = (temp_root_ / "_shared_bag").string(); - std::filesystem::create_directories(shared_path); - - RosbagFileInfo info; - info.file_path = shared_path; - info.format = "mcap"; - info.duration_sec = 5.0; - info.size_bytes = 100; - info.created_at_ns = 1000; - info.fault_code = "X"; - storage_->store_rosbag_file(info); - info.fault_code = "Y"; - storage_->store_rosbag_file(info); - - info.fault_code = "X"; - info.file_path = shared_path + "_new"; - storage_->store_rosbag_file(info); - - EXPECT_TRUE(std::filesystem::exists(shared_path)) << "the sibling fault still owns the shared bag"; - auto sibling = storage_->get_rosbag_file("Y"); - ASSERT_TRUE(sibling.has_value()); - EXPECT_EQ(sibling->file_path, shared_path); -} - // Burst-level batch operations (one PostgreSQL transaction per burst). TEST_F(PgFaultStorageTest, BulkStoreRegistersEveryFaultOfTheBurst) { @@ -2295,7 +2205,7 @@ TEST_F(PgFaultStorageTest, BulkStoreRegistersEveryFaultOfTheBurst) { info.fault_code = code; rows.push_back(info); } - storage_->store_rosbag_files(rows); + seed_rosbag_rows(*storage_, rows); for (const char * code : {"ROOT_CAUSE", "CORRELATED_A", "CORRELATED_B"}) { auto row = storage_->get_rosbag_file(code); @@ -2322,17 +2232,26 @@ TEST_F(PgFaultStorageTest, BulkDeleteRemovesTheBurstAndUnlinksTheBagOnce) { info.fault_code = code; rows.push_back(info); } - storage_->store_rosbag_files(rows); + seed_rosbag_rows(*storage_, rows); + RosbagRetention retention(*storage_, RosbagRetentionLimits{}, test_log_sink(), "test_postgres_storage"); // A partial delete leaves the bag on disk for the remaining fault. - EXPECT_EQ(storage_->delete_rosbag_files({"CORRELATED_A", "CORRELATED_B", "NEVER_STORED"}), 2u); - EXPECT_TRUE(std::filesystem::exists(bag_path)); + size_t codes_deleted = 0; + for (const char * code : {"CORRELATED_A", "CORRELATED_B", "NEVER_STORED"}) { + const auto removal = retention.on_fault_cleared(code); + expect_unlinkable(removal.unlink_paths); + EXPECT_FALSE(listed(removal.unlink_paths, bag_path)) << code; + codes_deleted += removal.removed_rows > 0 ? 1 : 0; + } + EXPECT_EQ(codes_deleted, 2u); EXPECT_TRUE(storage_->get_rosbag_file("ROOT_CAUSE").has_value()); EXPECT_FALSE(storage_->get_rosbag_file("CORRELATED_A").has_value()); // The last reference going away unlinks the directory. - EXPECT_EQ(storage_->delete_rosbag_files({"ROOT_CAUSE"}), 1u); - EXPECT_FALSE(std::filesystem::exists(bag_path)); + const auto root = retention.on_fault_cleared("ROOT_CAUSE"); + expect_unlinkable(root.unlink_paths); + EXPECT_EQ(root.removed_rows, 1u); + EXPECT_EQ(paths_of(root.unlink_paths), std::vector{bag_path}); EXPECT_EQ(storage_->get_total_rosbag_storage_bytes(), 0u); } diff --git a/src/ros2_medkit_fault_manager/test/test_rosbag_capture.cpp b/src/ros2_medkit_fault_manager/test/test_rosbag_capture.cpp index 6f86b69bf..12e8087c6 100644 --- a/src/ros2_medkit_fault_manager/test/test_rosbag_capture.cpp +++ b/src/ros2_medkit_fault_manager/test/test_rosbag_capture.cpp @@ -51,12 +51,18 @@ #include "ros2_medkit_msgs/msg/fault.hpp" #include "ros2_medkit_msgs/srv/report_fault.hpp" #include "test_log_sink.hpp" +#include "test_rosbag_rows.hpp" using ros2_medkit_fault_manager::FaultStorage; using ros2_medkit_fault_manager::InMemoryFaultStorage; +using ros2_medkit_fault_manager::RetentionWorker; +using ros2_medkit_fault_manager::RosbagApplyResult; using ros2_medkit_fault_manager::RosbagCapture; +using ros2_medkit_fault_manager::RosbagChangeSet; using ros2_medkit_fault_manager::RosbagConfig; using ros2_medkit_fault_manager::SnapshotConfig; +using ros2_medkit_fault_manager::core::RosbagRetention; +using ros2_medkit_fault_manager::core::RosbagRetentionLimits; namespace { @@ -958,7 +964,7 @@ TEST_F(RosbagCaptureTest, SharedBagTotalTakesTheLargestRowPerPath) { info.duration_sec = 5.0; info.size_bytes = bytes; info.created_at_ns = 1000; - storage_->store_rosbag_file(info); + seed_rosbag_rows(*storage_, {info}); }; store("AAA_BIG", "/tmp/shared_bag_a", 4096); @@ -986,7 +992,7 @@ TEST_F(RosbagCaptureTest, EvictionFreesASharedBagOnceAndKeepsTheQuotaHonest) { shared.created_at_ns = 1000; for (const char * code : {"ROOT_CAUSE", "CORRELATED_A", "CORRELATED_B"}) { shared.fault_code = code; - storage_->store_rosbag_file(shared); + seed_rosbag_rows(*storage_, {shared}); } ros2_medkit_fault_manager::RosbagFileInfo solo; @@ -996,24 +1002,26 @@ TEST_F(RosbagCaptureTest, EvictionFreesASharedBagOnceAndKeepsTheQuotaHonest) { solo.duration_sec = 5.0; solo.size_bytes = 600; solo.created_at_ns = 2000; - storage_->store_rosbag_file(solo); + seed_rosbag_rows(*storage_, {solo}); ASSERT_EQ(storage_->get_total_rosbag_storage_bytes(), 1600u); - auto evicted = RosbagCapture::evict_bags_over_quota(storage_.get(), 1000); + RosbagRetention retention(*storage_, RosbagRetentionLimits{}, test_log_sink(), "test_rosbag_capture"); + auto evicted = retention.evict_over_quota(1000); + expect_unlinkable(evicted); // The oldest bag goes as a unit, taking all three of its rows with it, and the // freed bytes match what actually left the disk. EXPECT_EQ(evicted, std::vector{shared_path}); EXPECT_EQ(storage_->get_total_rosbag_storage_bytes(), 600u); - EXPECT_FALSE(std::filesystem::exists(shared_path)); + EXPECT_TRUE(listed(evicted, shared_path)); EXPECT_FALSE(storage_->get_rosbag_file("ROOT_CAUSE").has_value()); EXPECT_FALSE(storage_->get_rosbag_file("CORRELATED_A").has_value()); EXPECT_FALSE(storage_->get_rosbag_file("CORRELATED_B").has_value()); // The newer bag fits under the quota and must survive. EXPECT_TRUE(storage_->get_rosbag_file("UNRELATED").has_value()); - EXPECT_TRUE(std::filesystem::exists(solo_path)); + EXPECT_FALSE(listed(evicted, solo_path)); } TEST_F(RosbagCaptureTest, EvictionKeepsGoingWhenTheSharedBagIsNotEnough) { @@ -1035,10 +1043,10 @@ TEST_F(RosbagCaptureTest, EvictionKeepsGoingWhenTheSharedBagIsNotEnough) { shared.created_at_ns = 1000; shared.fault_code = "ROOT_CAUSE"; shared.size_bytes = 500; - storage_->store_rosbag_file(shared); + seed_rosbag_rows(*storage_, {shared}); shared.fault_code = "CORRELATED_A"; shared.size_bytes = 400; - storage_->store_rosbag_file(shared); + seed_rosbag_rows(*storage_, {shared}); ros2_medkit_fault_manager::RosbagFileInfo solo; solo.fault_code = "UNRELATED"; @@ -1047,16 +1055,18 @@ TEST_F(RosbagCaptureTest, EvictionKeepsGoingWhenTheSharedBagIsNotEnough) { solo.duration_sec = 5.0; solo.size_bytes = 400; solo.created_at_ns = 2000; - storage_->store_rosbag_file(solo); + seed_rosbag_rows(*storage_, {solo}); ASSERT_EQ(storage_->get_total_rosbag_storage_bytes(), 900u); - auto evicted = RosbagCapture::evict_bags_over_quota(storage_.get(), 300); + RosbagRetention retention(*storage_, RosbagRetentionLimits{}, test_log_sink(), "test_rosbag_capture"); + auto evicted = retention.evict_over_quota(300); + expect_unlinkable(evicted); EXPECT_EQ(evicted, (std::vector{shared_path, solo_path})); EXPECT_EQ(storage_->get_total_rosbag_storage_bytes(), 0u); - EXPECT_FALSE(std::filesystem::exists(shared_path)); - EXPECT_FALSE(std::filesystem::exists(solo_path)); + EXPECT_TRUE(listed(evicted, shared_path)); + EXPECT_TRUE(listed(evicted, solo_path)); } // @verifies REQ_INTEROP_088 @@ -1074,7 +1084,7 @@ TEST_F(RosbagCaptureTest, EvictionNeverDeletesTheRecordingJustStored) { older.format = "mcap"; older.size_bytes = 300; older.created_at_ns = 1000; - storage_->store_rosbag_file(older); + seed_rosbag_rows(*storage_, {older}); ros2_medkit_fault_manager::RosbagFileInfo newest; newest.fault_code = "NEWEST"; @@ -1082,13 +1092,15 @@ TEST_F(RosbagCaptureTest, EvictionNeverDeletesTheRecordingJustStored) { newest.format = "mcap"; newest.size_bytes = 2000; newest.created_at_ns = 2000; - storage_->store_rosbag_file(newest); + seed_rosbag_rows(*storage_, {newest}); - auto evicted = RosbagCapture::evict_bags_over_quota(storage_.get(), 1000, "fault_NEWEST_2000"); + RosbagRetention retention(*storage_, RosbagRetentionLimits{}, test_log_sink(), "test_rosbag_capture"); + auto evicted = retention.evict_over_quota(1000, "fault_NEWEST_2000"); + expect_unlinkable(evicted); EXPECT_EQ(evicted, std::vector{older_path}); - EXPECT_FALSE(std::filesystem::exists(older_path)); - EXPECT_TRUE(std::filesystem::exists(newest_path)); + EXPECT_TRUE(listed(evicted, older_path)); + EXPECT_FALSE(listed(evicted, newest_path)); ASSERT_TRUE(storage_->get_rosbag_file("NEWEST").has_value()); // Still over the quota: that is the state the caller warns about. EXPECT_EQ(storage_->get_total_rosbag_storage_bytes(), 2000u); @@ -1108,7 +1120,7 @@ TEST_F(RosbagCaptureTest, EvictionSkipsTheKeptRecordingWhereverItSorts) { kept.format = "mcap"; kept.size_bytes = 900; kept.created_at_ns = 1000; - storage_->store_rosbag_file(kept); + seed_rosbag_rows(*storage_, {kept}); ros2_medkit_fault_manager::RosbagFileInfo later; later.fault_code = "LATER"; @@ -1116,12 +1128,14 @@ TEST_F(RosbagCaptureTest, EvictionSkipsTheKeptRecordingWhereverItSorts) { later.format = "mcap"; later.size_bytes = 900; later.created_at_ns = 2000; - storage_->store_rosbag_file(later); + seed_rosbag_rows(*storage_, {later}); - auto evicted = RosbagCapture::evict_bags_over_quota(storage_.get(), 1000, "fault_KEPT_1000"); + RosbagRetention retention(*storage_, RosbagRetentionLimits{}, test_log_sink(), "test_rosbag_capture"); + auto evicted = retention.evict_over_quota(1000, "fault_KEPT_1000"); + expect_unlinkable(evicted); EXPECT_EQ(evicted, std::vector{later_path}); - EXPECT_TRUE(std::filesystem::exists(kept_path)); + EXPECT_FALSE(listed(evicted, kept_path)); EXPECT_EQ(storage_->get_total_rosbag_storage_bytes(), 900u); } @@ -1232,53 +1246,6 @@ TEST_F(RosbagCaptureTest, TheDerivedOriginStaysPositiveOnALowUptimeMachine) { EXPECT_GT(now_steady - history, 0) << "the recording's origin is non-positive, so its duration reports as zero"; } -TEST_F(RosbagCaptureTest, ABatchStoreUnlinksASharedReplacedBagExactlyOnce) { - // The in-memory backend now publishes a batch in one step rather than row by row, - // because the caller reads a throw as "nothing was stored" and removes the - // recording. The replaced-bag rule has to survive that rewrite: two faults of one - // burst can share the bag being replaced, and whether it is still referenced has - // to be judged on the finished batch. Judged row by row beforehand, each row sees - // its sibling still pointing at the old bag and neither unlinks it. - using ros2_medkit_fault_manager::RosbagFileInfo; - - const auto old_bag = temp_dir_ / "shared_old_bag"; - const auto new_bag = temp_dir_ / "shared_new_bag"; - std::filesystem::create_directories(old_bag); - std::filesystem::create_directories(new_bag); - - RosbagFileInfo shared; - shared.file_path = old_bag.string(); - shared.format = "mcap"; - shared.duration_sec = 1.0; - shared.size_bytes = 10; - shared.created_at_ns = 1000; - shared.fault_code = "SHARED_A"; - storage_->store_rosbag_file(shared); - shared.fault_code = "SHARED_B"; - storage_->store_rosbag_file(shared); - ASSERT_TRUE(std::filesystem::exists(old_bag)); - - RosbagFileInfo moved = shared; - moved.file_path = new_bag.string(); - moved.created_at_ns = 2000; - std::vector rows; - rows.reserve(2); - moved.fault_code = "SHARED_A"; - rows.push_back(moved); - moved.fault_code = "SHARED_B"; - rows.push_back(moved); - storage_->store_rosbag_files(rows); - - EXPECT_FALSE(std::filesystem::exists(old_bag)) << "the replaced bag leaked: nothing references it any more"; - EXPECT_TRUE(std::filesystem::exists(new_bag)) << "the bag the batch points at was removed"; - auto row_a = storage_->get_rosbag_file("SHARED_A"); - auto row_b = storage_->get_rosbag_file("SHARED_B"); - ASSERT_TRUE(row_a.has_value()); - ASSERT_TRUE(row_b.has_value()); - EXPECT_EQ(row_a->file_path, new_bag.string()); - EXPECT_EQ(row_b->file_path, new_bag.string()); -} - TEST_F(RosbagCaptureTest, TheHistoryBoundHoldsForClockValuesFarApart) { // A public entry point taking two clocks it does not control. The pair below would // overflow a signed subtraction, which is undefined - the result has to stay inside @@ -1308,19 +1275,15 @@ TEST_F(RosbagCaptureTest, NoStartTimeYieldsNoClaimedHistory) { // Integration tests (simplified without actual message publishing) -/// Storage whose rosbag metadata writes fail, the way a full, read-only or busy +/// Storage whose rosbag row inserts fail, the way a full, read-only or busy /// SQLite database does at finalize time - that is, after the bag itself has /// already been created on disk. class RosbagMetadataFailingStorage : public InMemoryFaultStorage { public: - void store_rosbag_files(const std::vector & /*infos*/) override { - ++store_attempts; - throw std::runtime_error("metadata store unavailable"); - } - - // Both entry points, or the double silently stops failing for whichever call the - // code under test happens to use - the immediate path used the single-row one. - void store_rosbag_file(const ros2_medkit_fault_manager::RosbagFileInfo & /*info*/) override { + RosbagApplyResult apply_rosbag_changes(const RosbagChangeSet & changes) override { + if (changes.insert.empty()) { + return InMemoryFaultStorage::apply_rosbag_changes(changes); + } ++store_attempts; throw std::runtime_error("metadata store unavailable"); } @@ -1333,11 +1296,14 @@ class RosbagMetadataFailingStorage : public InMemoryFaultStorage { /// Storage whose metadata writes SUCCEED and whose quota sweep then fails, the way /// a busy or full SQLite database does on the eviction transaction's BEGIN IMMEDIATE. /// The distinction from the double above is the whole point: by the time the sweep -/// runs, store_rosbag_files() has committed, so the rows of the finished recording -/// are durable and the bag they name must survive the failure. +/// runs, the insert has committed, so the rows of the finished recording are durable +/// and the bag they name must survive the failure. class RosbagQuotaSweepFailingStorage : public InMemoryFaultStorage { public: - size_t delete_rosbag_recording(const std::string & /*recording_id*/) override { + RosbagApplyResult apply_rosbag_changes(const RosbagChangeSet & changes) override { + if (changes.remove_recordings.empty()) { + return InMemoryFaultStorage::apply_rosbag_changes(changes); + } ++sweep_attempts; throw std::runtime_error("quota sweep unavailable"); } @@ -1350,7 +1316,10 @@ class RosbagQuotaSweepFailingStorage : public InMemoryFaultStorage { /// through stop(), where an escape terminates the process. class RosbagNonStandardThrowStorage : public InMemoryFaultStorage { public: - void store_rosbag_files(const std::vector & /*infos*/) override { + RosbagApplyResult apply_rosbag_changes(const RosbagChangeSet & changes) override { + if (changes.insert.empty()) { + return InMemoryFaultStorage::apply_rosbag_changes(changes); + } ++store_attempts; throw 42; // NOLINT(hicpp-exception-baseclass) - deliberately not a std::exception } @@ -1383,7 +1352,10 @@ class RosbagFaultLookupFailingStorage : public InMemoryFaultStorage { /// Storage whose bag cleanup fails, as the PostgreSQL backend does while its server is down. class RosbagCleanupFailingStorage : public InMemoryFaultStorage { public: - bool delete_rosbag_file(const std::string & /*fault_code*/) override { + RosbagApplyResult apply_rosbag_changes(const RosbagChangeSet & changes) override { + if (changes.remove.empty() && changes.remove_recordings.empty()) { + return InMemoryFaultStorage::apply_rosbag_changes(changes); + } ++delete_attempts; throw FaultStorage::IgnorableConnectionException("database unreachable"); } @@ -1395,12 +1367,17 @@ class RosbagCleanupFailingStorage : public InMemoryFaultStorage { /// disk. The finalise reaches it after it has released post_fault_timer_mutex_, so it /// widens - deterministically, and without a hook in production code - the window in /// which a boundary confirmation has already published its own recording while the -/// outgoing finalise is still running. +/// outgoing finalise is still running. The delay is far above scheduling jitter, so a +/// span that waited for it shows in duration_sec even under load. class SlowMetadataStorage : public InMemoryFaultStorage { public: - void store_rosbag_files(const std::vector & infos) override { - std::this_thread::sleep_for(std::chrono::milliseconds(400)); - InMemoryFaultStorage::store_rosbag_files(infos); + static constexpr std::chrono::milliseconds kInsertDelay{3000}; + + RosbagApplyResult apply_rosbag_changes(const RosbagChangeSet & changes) override { + if (!changes.insert.empty()) { + std::this_thread::sleep_for(kInsertDelay); + } + return InMemoryFaultStorage::apply_rosbag_changes(changes); } }; @@ -1409,17 +1386,17 @@ class SlowMetadataStorage : public InMemoryFaultStorage { /// bag path it was handed, so the test can look at the directory while the store waits. class GatedMetadataStorage : public InMemoryFaultStorage { public: - void store_rosbag_files(const std::vector & infos) override { - { + RosbagApplyResult apply_rosbag_changes(const RosbagChangeSet & changes) override { + if (!changes.insert.empty()) { std::unique_lock lock(gate_mutex); - bag_path = infos.empty() ? std::string() : infos.front().file_path; + bag_path = changes.insert.front().file_path; entered = true; gate_cv.notify_all(); gate_cv.wait_for(lock, std::chrono::seconds(30), [this]() { return released; }); } - InMemoryFaultStorage::store_rosbag_files(infos); + return InMemoryFaultStorage::apply_rosbag_changes(changes); } void release() { @@ -1466,11 +1443,11 @@ class RosbagCaptureIntegrationTest : public RosbagCaptureTest { } } - /// Spin until the post-roll finalises and @p fault_code has its metadata row. - bool wait_for_row(const std::string & fault_code, std::chrono::milliseconds timeout) { + /// Spin until the post-roll finalises and @p fault_code has its metadata row in @p storage. + bool wait_for_row(const FaultStorage & storage, const std::string & fault_code, std::chrono::milliseconds timeout) { auto deadline = std::chrono::steady_clock::now() + timeout; while (std::chrono::steady_clock::now() < deadline) { - if (storage_->get_rosbag_file(fault_code).has_value()) { + if (storage.get_rosbag_file(fault_code).has_value()) { return true; } spin_for(std::chrono::milliseconds(100)); @@ -1478,6 +1455,10 @@ class RosbagCaptureIntegrationTest : public RosbagCaptureTest { return false; } + bool wait_for_row(const std::string & fault_code, std::chrono::milliseconds timeout) { + return wait_for_row(*storage_, fault_code, timeout); + } + /// Publish on @p pub for @p duration, spinning so the capture receives it. void publish_for(const rclcpp::Publisher::SharedPtr & pub, std::chrono::milliseconds duration) { @@ -1587,14 +1568,13 @@ TEST_F(RosbagCaptureIntegrationTest, AcknowledgingKeepsAHistoryTheOperatorConfig rosbag_config.duration_after_sec = 0.0; rosbag_config.auto_cleanup = true; rosbag_config.max_bags_per_fault = 3; - storage.set_max_rosbags_per_fault(rosbag_config.max_bags_per_fault); auto snapshot_config = create_snapshot_config(); RosbagCapture capture(node_.get(), &storage, rosbag_config, snapshot_config); capture.start(); fill_buffer("/keep_history_probe"); + // No post-fault window: the row is stored before on_fault_confirmed() returns. capture.on_fault_confirmed("KEEPS_HISTORY"); - spin_for(std::chrono::milliseconds(300)); ASSERT_FALSE(storage.get_rosbag_files("KEEPS_HISTORY").empty()) << "nothing was recorded to keep"; const auto before = storage.get_rosbag_files("KEEPS_HISTORY").size(); @@ -1618,7 +1598,6 @@ TEST_F(RosbagCaptureIntegrationTest, AcknowledgingDuringThePostRollKeepsAConfigu rosbag_config.duration_after_sec = 0.3; // still open when the clear lands rosbag_config.auto_cleanup = true; rosbag_config.max_bags_per_fault = 3; - storage.set_max_rosbags_per_fault(rosbag_config.max_bags_per_fault); rclcpp::Clock clock; storage.report_fault_event("ACK_MID_ROLL", fd::ReportKind::kFailed, ros2_medkit_msgs::msg::Fault::SEVERITY_ERROR, @@ -1636,7 +1615,7 @@ TEST_F(RosbagCaptureIntegrationTest, AcknowledgingDuringThePostRollKeepsAConfigu ASSERT_TRUE(storage.clear_fault("ACK_MID_ROLL")); capture.on_fault_cleared("ACK_MID_ROLL"); - spin_for(std::chrono::milliseconds(900)); // past the post-roll and the finalize + EXPECT_TRUE(wait_for_row(storage, "ACK_MID_ROLL", std::chrono::milliseconds(8000))); capture.wait_for_stored_recordings(); EXPECT_FALSE(storage.get_rosbag_files("ACK_MID_ROLL").empty()) @@ -1793,6 +1772,46 @@ TEST_F(RosbagCaptureIntegrationTest, AClearWhileTheRowIsStoredTakesTheRowWithIt) capture.stop(); } +TEST_F(RosbagCaptureIntegrationTest, ClearLeavesTheUnlinkToTheWorker) { + // The clear runs on the fault manager's executor. Its rows go inside the call; the + // directory, which can be large, goes on the retention worker. + auto rosbag_config = create_rosbag_config(); + rosbag_config.duration_after_sec = 0.0; // stored inside on_fault_confirmed() + auto snapshot_config = create_snapshot_config(); + auto worker = + std::make_shared(test_log_sink(), "test_rosbag_capture", RetentionWorker::Mode::kThread); + auto retention = + std::make_shared(*storage_, RosbagRetentionLimits{}, test_log_sink(), "test_rosbag_capture"); + RosbagCapture capture(node_.get(), storage_.get(), rosbag_config, snapshot_config, retention, worker); + + // Declared after the capture: a failed assertion destroys it first, which releases the job. + std::promise unblock; + worker->post("block", [blocked = unblock.get_future().share()]() { + blocked.wait(); + }); + + capture.start(); + fill_buffer("/clear_on_worker_probe"); + capture.on_fault_confirmed("CLEARED_ON_WORKER"); + const auto row = storage_->get_rosbag_file("CLEARED_ON_WORKER"); + ASSERT_TRUE(row.has_value()) << "fill_buffer() buffered nothing, so no recording was stored"; + + capture.on_fault_cleared("CLEARED_ON_WORKER"); + EXPECT_FALSE(storage_->get_rosbag_file("CLEARED_ON_WORKER").has_value()) << "the clear left its row"; + EXPECT_TRUE(std::filesystem::exists(row->file_path)) << "the clear removed the directory on its own thread"; + + unblock.set_value(); + std::promise barrier; + auto reached = barrier.get_future(); + worker->post("barrier", [&barrier]() { + barrier.set_value(); + }); + ASSERT_EQ(reached.wait_for(std::chrono::seconds(10)), std::future_status::ready) << "the worker is stuck"; + EXPECT_FALSE(std::filesystem::exists(row->file_path)) << "the worker did not remove the directory"; + + capture.stop(); +} + TEST_F(RosbagCaptureIntegrationTest, FaultConfirmedDuringPostRollGetsTheSameBag) { // Correlated faults arrive in a burst. The one that confirms while the first // fault's post-roll is still running used to be skipped outright and ended up @@ -1909,12 +1928,24 @@ TEST_F(RosbagCaptureIntegrationTest, PostRollKeepsTheRowWhenTheFaultCannotBeRead TEST_F(RosbagCaptureIntegrationTest, ClearSurvivesAFailingBagCleanup) { RosbagCleanupFailingStorage storage; + // A row to remove, so the clear reaches the failing removal. + const auto bag_dir = temp_dir_ / "fault_UNREACHABLE_1000"; + std::filesystem::create_directories(bag_dir); + ros2_medkit_fault_manager::RosbagFileInfo row; + row.fault_code = "UNREACHABLE"; + row.file_path = bag_dir.string(); + row.format = "mcap"; + row.size_bytes = 1; + row.created_at_ns = 1000; + seed_rosbag_rows(storage, {row}); auto rosbag_config = create_rosbag_config(); auto snapshot_config = create_snapshot_config(); RosbagCapture capture(node_.get(), &storage, rosbag_config, snapshot_config); EXPECT_NO_THROW(capture.on_fault_cleared("UNREACHABLE")); EXPECT_EQ(storage.delete_attempts, 1u) << "the cleanup never reached the store"; + EXPECT_TRUE(storage.get_rosbag_file("UNREACHABLE").has_value()) << "the failed removal took the row"; + EXPECT_TRUE(std::filesystem::exists(bag_dir)) << "the failed removal took the directory"; } TEST_F(RosbagCaptureIntegrationTest, PrimaryClearedDuringPostRollLeavesTheBagToItsAttachedFault) { @@ -2527,9 +2558,20 @@ TEST_F(RosbagCaptureIntegrationTest, ABoundaryRecordingKeepsItsScopeWhileTheOldF spin_for(std::chrono::milliseconds(50)); } - ASSERT_TRUE(wait_for_row("SCOPE_RACE_B", std::chrono::milliseconds(12000))); + // A's recording also holds a row for B, which attached to it. The row under test is B's own + // bag, stored after A's slow insert and then its own. + const auto own_bag = [](const auto & row) { + return row.has_value() && + std::filesystem::path(row->file_path).filename().string().rfind("fault_SCOPE_RACE_B_", 0) == 0; + }; + const auto deadline = std::chrono::steady_clock::now() + + scaled(std::chrono::milliseconds(12000) + 2 * SlowMetadataStorage::kInsertDelay); auto row_b = storage_->get_rosbag_file("SCOPE_RACE_B"); - ASSERT_TRUE(row_b.has_value()); + while (!own_bag(row_b) && std::chrono::steady_clock::now() < deadline) { + spin_for(std::chrono::milliseconds(100)); + row_b = storage_->get_rosbag_file("SCOPE_RACE_B"); + } + ASSERT_TRUE(own_bag(row_b)) << "the row of B's own recording was never stored"; size_t b_recordings = 0; for (const auto & entry : std::filesystem::directory_iterator(temp_dir_)) { if (entry.path().filename().string().rfind("fault_SCOPE_RACE_B_", 0) == 0) { @@ -2542,18 +2584,10 @@ TEST_F(RosbagCaptureIntegrationTest, ABoundaryRecordingKeepsItsScopeWhileTheOldF EXPECT_FALSE(bag_has_topic(row_b->file_path, "/scope_race_a")) << "the finalise of the previous recording cleared B's entity filter, and B recorded everything"; - // Read this for what it is. The storage double delays store_rosbag_files() by - // 400 ms, and the measurement has always been taken before that call - so this - // does NOT discriminate the change that moved it, and the commit that added it - // would pass with that change reverted. What it does pin is that the measurement - // never DRIFTS past the metadata write, which is a plausible future regression. - // - // The part that change really moved - the bag close and the directory size walk - - // has no falsifying test. Both cost tens of milliseconds on a bag this size, and - // reaching a margin a test could assert without becoming a timing flake would need - // a bag of about a hundred megabytes or a directory of tens of thousands of files. - // That is stated rather than papered over. - EXPECT_LT(row_b->duration_sec, rosbag_config.duration_after_sec + 0.3) + // design/index.rst, "Honest durations": the span ends at the handover, so it never covers A's slow store. + // The bag close takes milliseconds here and is not pinned. + const double half_delay_sec = std::chrono::duration(SlowMetadataStorage::kInsertDelay).count() / 2; + EXPECT_LT(row_b->duration_sec, rosbag_config.duration_after_sec + half_delay_sec) << "duration_sec includes finalisation work rather than the span the recording was open"; capture.stop(); @@ -2692,7 +2726,7 @@ TEST_F(RosbagCaptureIntegrationTest, MetadataStoreFailureDiscardsTheBagInsteadOf TEST_F(RosbagCaptureIntegrationTest, AFailingQuotaSweepKeepsTheBagItJustStored) { // The mirror image of the test above, and the case its double cannot reach. The - // sweep runs AFTER store_rosbag_files() has committed, so a failure there says + // sweep runs AFTER the insert has committed, so a failure there says // nothing about this recording. Discarding the bag then strands the rows just // written: unreadable for good, because retrieval is keyed by fault code, and // still charged against max_total_storage_mb, which sums rows - the very pressure @@ -2714,13 +2748,14 @@ TEST_F(RosbagCaptureIntegrationTest, AFailingQuotaSweepKeepsTheBagItJustStored) older.format = "mcap"; older.size_bytes = 1; older.created_at_ns = 1000; - sweep_failing_storage.store_rosbag_file(older); + seed_rosbag_rows(sweep_failing_storage, {older}); RosbagCapture capture(node_.get(), &sweep_failing_storage, rosbag_config, snapshot_config); capture.start(); fill_buffer("/sweep_failure_probe"); capture.on_fault_confirmed("SWEEP_FAILS"); - spin_for(std::chrono::milliseconds(1200)); // past the window, finalise ran + EXPECT_TRUE(wait_for_row(sweep_failing_storage, "SWEEP_FAILS", std::chrono::milliseconds(8000))); + // The sweep runs in the same store as the insert, which this waits out. capture.wait_for_stored_recordings(); auto row = sweep_failing_storage.get_rosbag_file("SWEEP_FAILS"); diff --git a/src/ros2_medkit_fault_manager/test/test_rosbag_retention.cpp b/src/ros2_medkit_fault_manager/test/test_rosbag_retention.cpp new file mode 100644 index 000000000..e9392dd13 --- /dev/null +++ b/src/ros2_medkit_fault_manager/test/test_rosbag_retention.cpp @@ -0,0 +1,376 @@ +// 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. + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#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" +#include "test_log_sink.hpp" +#include "test_rosbag_rows.hpp" + +namespace { + +using ros2_medkit_fault_manager::DebounceConfig; +using ros2_medkit_fault_manager::InMemoryFaultStorage; +using ros2_medkit_fault_manager::RosbagApplyResult; +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::RosbagRetention; +using ros2_medkit_fault_manager::core::RosbagRetentionLimits; +using ros2_medkit_fault_manager::core::StoreResult; + +constexpr const char * kLogger = "test_rosbag_retention"; +constexpr uint8_t kSeverityError = 2; + +/// SQLite storage whose fault read holds at a gate after the real read has returned. +class GatedFaultReadStorage : public SqliteFaultStorage { + public: + using SqliteFaultStorage::SqliteFaultStorage; + + std::optional get_fault(const std::string & fault_code) const override { + auto fault = SqliteFaultStorage::get_fault(fault_code); + std::unique_lock lock(gate_mutex_); + if (armed_) { + entered_ = true; + gate_cv_.notify_all(); + gate_cv_.wait_for(lock, std::chrono::seconds(30), [this]() { + return released_; + }); + } + return fault; + } + + void arm() { + std::lock_guard lock(gate_mutex_); + armed_ = true; + } + + bool wait_entered(std::chrono::milliseconds timeout) const { + std::unique_lock lock(gate_mutex_); + return gate_cv_.wait_for(lock, timeout, [this]() { + return entered_; + }); + } + + void release() { + std::lock_guard lock(gate_mutex_); + released_ = true; + gate_cv_.notify_all(); + } + + private: + mutable std::mutex gate_mutex_; + mutable std::condition_variable gate_cv_; + bool armed_{false}; + mutable bool entered_{false}; + bool released_{false}; +}; + +/// Opens the gate when the test ends, so a failed assertion cannot leave a store waiting. +class GateRelease { + public: + explicit GateRelease(GatedFaultReadStorage & storage) : storage_(storage) { + } + ~GateRelease() { + storage_.release(); + } + GateRelease(const GateRelease &) = delete; + GateRelease & operator=(const GateRelease &) = delete; + GateRelease(GateRelease &&) = delete; + GateRelease & operator=(GateRelease &&) = delete; + + private: + GatedFaultReadStorage & storage_; +}; + +/// Storage whose per-fault rosbag read fails. +class FailingCapReadStorage : public InMemoryFaultStorage { + public: + std::vector get_rosbag_files(const std::string & /*fault_code*/) const override { + ++reads; + throw std::runtime_error("cap read failed"); + } + + mutable size_t reads = 0; +}; + +/// Storage whose rosbag total fails. +class FailingQuotaReadStorage : public InMemoryFaultStorage { + public: + size_t get_total_rosbag_storage_bytes() const override { + ++reads; + throw std::runtime_error("quota read failed"); + } + + mutable size_t reads = 0; +}; + +/// Storage whose removal of one recording fails. +class FailingEvictionStorage : public InMemoryFaultStorage { + public: + explicit FailingEvictionStorage(std::string failing_recording) : failing_recording_(std::move(failing_recording)) { + } + + RosbagApplyResult apply_rosbag_changes(const RosbagChangeSet & changes) override { + const auto & ids = changes.remove_recordings; + if (std::find(ids.begin(), ids.end(), failing_recording_) != ids.end()) { + ++failures; + throw std::runtime_error("eviction failed"); + } + return InMemoryFaultStorage::apply_rosbag_changes(changes); + } + + size_t failures = 0; + + private: + std::string failing_recording_; +}; + +class RosbagRetentionStore : public ::testing::Test { + protected: + void SetUp() override { + dir_ = std::filesystem::temp_directory_path() / + ("medkit_retention_" + std::to_string(reinterpret_cast(this))); + std::filesystem::remove_all(dir_); + std::filesystem::create_directories(dir_); + } + + void TearDown() override { + std::error_code ec; + std::filesystem::remove_all(dir_, ec); + } + + RosbagFileInfo row(const std::string & code, const std::string & bag_name, int64_t created_ns, + size_t size_bytes = 1024) { + const auto path = dir_ / bag_name; + std::filesystem::create_directories(path); + std::ofstream(path / "metadata.yaml") << "version: 9\n"; + RosbagFileInfo info; + info.fault_code = code; + info.file_path = path.string(); + info.recording_id = bag_name; + info.format = "mcap"; + info.duration_sec = 1.0; + info.size_bytes = size_bytes; + info.created_at_ns = created_ns; + return info; + } + + static RosbagRetentionLimits limits(size_t max_bags_per_fault, size_t max_total_bytes = 500ULL * 1024 * 1024) { + RosbagRetentionLimits limits; + limits.max_bags_per_fault = max_bags_per_fault; + limits.max_total_bytes = max_total_bytes; + return limits; + } + + std::filesystem::path dir_; +}; + +TEST_F(RosbagRetentionStore, ClearBlocksWhileTheStoreChecks) { + // A clear either shows as cleared in the store's check, or its removal runs after the insert + // and takes the row. The gate holds the store between the check and the insert. + GatedFaultReadStorage storage((dir_ / "faults.db").string(), test_log_sink()); + storage.report_fault_event("CLEAR_RACE", fd::ReportKind::kFailed, kSeverityError, "race", "/node", 1000, + DebounceConfig{}); + // auto_cleanup on and a cap of 1: the store reads the fault before it inserts. + RosbagRetention retention(storage, limits(1), test_log_sink(), kLogger); + const auto bag = row("CLEAR_RACE", "fault_CLEAR_RACE_1", 1000); + + storage.arm(); + auto stored = std::async(std::launch::async, [&retention, &bag]() { + return retention.store({bag}); + }); + std::future cleared; + GateRelease release(storage); + ASSERT_TRUE(storage.wait_entered(std::chrono::seconds(10))) << "the store never read the fault"; + + // The read returned "not cleared". The clear marks the fault first, as the core does. + ASSERT_TRUE(storage.clear_fault("CLEAR_RACE")); + cleared = std::async(std::launch::async, [&retention]() { + return retention.on_fault_cleared("CLEAR_RACE"); + }); + // Bounded negative wait: a clear blocked on the retention mutex gives no sign of it, so the + // test can only see that it has not returned within the window. + EXPECT_EQ(cleared.wait_for(std::chrono::milliseconds(500)), std::future_status::timeout) + << "the clear ran while the store was between its check and its insert"; + + storage.release(); + const auto store_outcome = stored.get(); + const auto removal = cleared.get(); + EXPECT_EQ(store_outcome.result, StoreResult::kStored); + EXPECT_TRUE(storage.get_rosbag_files("CLEAR_RACE").empty()) << "a cleared fault kept its row"; + EXPECT_EQ(removal.removed_rows, 1u); + expect_unlinkable(removal.unlink_paths); + EXPECT_TRUE(listed(removal.unlink_paths, bag.file_path)) << "the clear did not hand over the directory"; +} + +TEST_F(RosbagRetentionStore, NoCapReadWhenTheCapIsZero) { + FailingCapReadStorage storage; + RosbagRetention retention(storage, limits(0), test_log_sink(), kLogger); + const auto bag = row("NO_CAP", "fault_NO_CAP_1", 1000); + + const auto outcome = retention.store({bag}); + + EXPECT_EQ(outcome.result, StoreResult::kStored) << outcome.error; + EXPECT_EQ(storage.reads, 0u) << "a cap of 0 read the fault's recordings"; + EXPECT_TRUE(storage.get_rosbag_file("NO_CAP").has_value()); + EXPECT_TRUE(outcome.unlink_paths.empty()); +} + +TEST_F(RosbagRetentionStore, FailingCapReadIsAStoreFailure) { + FailingCapReadStorage storage; + RosbagRetention retention(storage, limits(1), test_log_sink(), kLogger); + const auto bag = row("CAP_READ", "fault_CAP_READ_1", 1000); + + const auto outcome = retention.store({bag}); + + EXPECT_EQ(outcome.result, StoreResult::kStoreFailed); + EXPECT_EQ(storage.reads, 1u) << "a failed cap read is not retried"; + EXPECT_NE(outcome.error.find("cap read failed"), std::string::npos) << outcome.error; + EXPECT_FALSE(storage.get_rosbag_file("CAP_READ").has_value()); + EXPECT_TRUE(outcome.unlink_paths.empty()) << "the caller discards the bag, not the worker"; +} + +TEST_F(RosbagRetentionStore, FailingQuotaReadKeepsTheBag) { + FailingQuotaReadStorage storage; + RosbagRetention retention(storage, limits(1), test_log_sink(), kLogger); + const auto bag = row("QUOTA_READ", "fault_QUOTA_READ_1", 1000); + + const auto outcome = retention.store({bag}); + + EXPECT_EQ(outcome.result, StoreResult::kStored); + EXPECT_TRUE(outcome.quota_failed); + EXPECT_EQ(storage.reads, 1u); + EXPECT_NE(outcome.error.find("quota read failed"), std::string::npos) << outcome.error; + EXPECT_TRUE(storage.get_rosbag_file("QUOTA_READ").has_value()) << "a failed quota took the stored row"; + EXPECT_TRUE(outcome.unlink_paths.empty()); +} + +TEST_F(RosbagRetentionStore, EvictionStopsAtTheFirstFailure) { + FailingEvictionStorage storage("fault_O2_2000"); + const auto o1 = row("O1", "fault_O1_1000", 1000, 500); + const auto o2 = row("O2", "fault_O2_2000", 2000, 500); + seed_rosbag_rows(storage, {o1, o2}); + RosbagRetention retention(storage, limits(0, 600), test_log_sink(), kLogger); + const auto fresh = row("NEW", "fault_NEW_3000", 3000, 500); + + const auto outcome = retention.store({fresh}); + + EXPECT_EQ(outcome.result, StoreResult::kStored); + EXPECT_TRUE(outcome.quota_failed); + EXPECT_NE(outcome.error.find("eviction failed"), std::string::npos) << outcome.error; + EXPECT_EQ(storage.failures, 1u); + expect_unlinkable(outcome.unlink_paths); + EXPECT_TRUE(storage.get_rosbag_files("O1").empty()) << "the eviction before the failure was undone"; + EXPECT_TRUE(listed(outcome.unlink_paths, o1.file_path)); + EXPECT_EQ(storage.get_rosbag_files("O2").size(), 1u); + EXPECT_FALSE(listed(outcome.unlink_paths, o2.file_path)); + EXPECT_EQ(storage.get_rosbag_files("NEW").size(), 1u); + EXPECT_FALSE(listed(outcome.unlink_paths, fresh.file_path)); +} + +TEST_F(RosbagRetentionStore, QuotaRunsWhenTheCapRemovedEveryNewRow) { + InMemoryFaultStorage storage; + const auto other = row("OTHER", "fault_OTHER_1000", 1000, 500); + const auto newer = row("CAPPED", "fault_CAPPED_9000", 9000, 500); + seed_rosbag_rows(storage, {other, newer}); + RosbagRetention retention(storage, limits(1, 600), test_log_sink(), kLogger); + // Older than the stored recording, so it loses the cap of 1. + const auto loser = row("CAPPED", "fault_CAPPED_2000", 2000, 500); + + const auto outcome = retention.store({loser}); + + EXPECT_EQ(outcome.result, StoreResult::kStored); + EXPECT_FALSE(outcome.quota_failed) << outcome.error; + const auto capped = storage.get_rosbag_files("CAPPED"); + ASSERT_EQ(capped.size(), 1u); + EXPECT_EQ(capped[0].file_path, newer.file_path); + expect_unlinkable(outcome.unlink_paths); + EXPECT_TRUE(listed(outcome.unlink_paths, loser.file_path)) << "no row names the new recording"; + EXPECT_TRUE(storage.get_rosbag_files("OTHER").empty()) << "the quota did not run"; + EXPECT_TRUE(listed(outcome.unlink_paths, other.file_path)); + EXPECT_FALSE(listed(outcome.unlink_paths, newer.file_path)); + // Each freed directory carries the reason its removal is logged with. + for (const auto & recording : outcome.unlink_paths) { + if (recording.path == loser.file_path) { + EXPECT_EQ(recording.reason, RemovalReason::kCap); + EXPECT_EQ(recording.recording_id, "fault_CAPPED_2000"); + } else { + EXPECT_EQ(recording.reason, RemovalReason::kQuota); + EXPECT_EQ(recording.recording_id, "fault_OTHER_1000"); + } + } +} + +TEST_F(RosbagRetentionStore, QuotaStopsAtTheLimit) { + InMemoryFaultStorage storage; + const auto o1 = row("O1", "fault_O1_1000", 1000, 300); + const auto o2 = row("O2", "fault_O2_2000", 2000, 300); + seed_rosbag_rows(storage, {o1, o2}); + RosbagRetention retention(storage, limits(0, 1000), test_log_sink(), kLogger); + + // 300 + 300 + 400 is the limit exactly. + const auto at_limit = retention.store({row("N1", "fault_N1_3000", 3000, 400)}); + EXPECT_EQ(at_limit.result, StoreResult::kStored); + EXPECT_TRUE(at_limit.unlink_paths.empty()) << "a total equal to the limit evicted a recording"; + EXPECT_EQ(storage.get_rosbag_files("O1").size(), 1u); + + // 1300 is over: O1 goes, and the eviction stops at the limit with O2 still stored. + const auto over = retention.store({row("N2", "fault_N2_4000", 4000, 300)}); + EXPECT_EQ(over.result, StoreResult::kStored); + expect_unlinkable(over.unlink_paths); + EXPECT_EQ(paths_of(over.unlink_paths), std::vector{o1.file_path}); + EXPECT_TRUE(storage.get_rosbag_files("O1").empty()); + EXPECT_EQ(storage.get_rosbag_files("O2").size(), 1u) << "the eviction went past the limit"; +} + +TEST_F(RosbagRetentionStore, AutoCleanupCountsRemovedRows) { + InMemoryFaultStorage storage; + const auto own = row("CLEARED", "fault_CLEARED_1000", 1000); + auto shared = row("CLEARED", "fault_SHARED_2000", 2000); + seed_rosbag_rows(storage, {own, shared}); + shared.fault_code = "SIBLING"; + seed_rosbag_rows(storage, {shared}); + RosbagRetention retention(storage, limits(1), test_log_sink(), kLogger); + + const auto removal = retention.on_fault_cleared("CLEARED"); + EXPECT_EQ(removal.removed_rows, 2u); + expect_unlinkable(removal.unlink_paths); + EXPECT_EQ(paths_of(removal.unlink_paths), std::vector{own.file_path}) + << "SIBLING still names the shared bag"; + EXPECT_TRUE(storage.get_rosbag_files("CLEARED").empty()); + EXPECT_EQ(storage.get_rosbag_files("SIBLING").size(), 1u); + + const auto none = retention.on_fault_cleared("NEVER_RECORDED"); + EXPECT_EQ(none.removed_rows, 0u); + EXPECT_TRUE(none.unlink_paths.empty()); +} + +} // namespace diff --git a/src/ros2_medkit_fault_manager/test/test_rosbag_rows.hpp b/src/ros2_medkit_fault_manager/test/test_rosbag_rows.hpp new file mode 100644 index 000000000..87b353f0c --- /dev/null +++ b/src/ros2_medkit_fault_manager/test/test_rosbag_rows.hpp @@ -0,0 +1,65 @@ +// 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. + +#pragma once + +#include + +#include +#include +#include +#include +#include + +#include "ros2_medkit_fault_manager/core/rosbag_retention.hpp" +#include "ros2_medkit_fault_manager/fault_storage.hpp" + +/// Store rosbag rows as they are, through the storage primitive: no cap, no quota, no unlink. +inline void seed_rosbag_rows(ros2_medkit_fault_manager::FaultStorage & storage, + std::vector rows) { + ros2_medkit_fault_manager::RosbagChangeSet changes; + changes.insert = std::move(rows); + storage.apply_rosbag_changes(changes); +} + +/// The paths one retention call hands over: each still exists when the call returns, and is +/// listed once. +inline void expect_unlinkable(const std::vector & paths) { + for (const auto & path : paths) { + EXPECT_TRUE(std::filesystem::exists(path)) << path << " was removed before the caller could"; + EXPECT_EQ(std::count(paths.begin(), paths.end(), path), 1) << path << " is listed more than once"; + } +} + +inline bool listed(const std::vector & paths, const std::string & path) { + return std::find(paths.begin(), paths.end(), path) != paths.end(); +} + +inline std::vector paths_of(const std::vector & freed) { + std::vector paths; + paths.reserve(freed.size()); + for (const auto & recording : freed) { + paths.push_back(recording.path); + } + return paths; +} + +inline void expect_unlinkable(const std::vector & freed) { + expect_unlinkable(paths_of(freed)); +} + +inline bool listed(const std::vector & freed, + const std::string & path) { + return listed(paths_of(freed), path); +} diff --git a/src/ros2_medkit_fault_manager/test/test_rosbag_storage_parity.cpp b/src/ros2_medkit_fault_manager/test/test_rosbag_storage_parity.cpp index cb5c2f854..0a65faafa 100644 --- a/src/ros2_medkit_fault_manager/test/test_rosbag_storage_parity.cpp +++ b/src/ros2_medkit_fault_manager/test/test_rosbag_storage_parity.cpp @@ -43,6 +43,7 @@ #endif #include "rclcpp/rclcpp.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" #ifdef POSTGRES_SUPPORT @@ -51,6 +52,7 @@ #include "ros2_medkit_msgs/msg/fault.hpp" #include "ros2_medkit_msgs/srv/report_fault.hpp" #include "test_log_sink.hpp" +#include "test_rosbag_rows.hpp" namespace { @@ -63,6 +65,9 @@ using ros2_medkit_fault_manager::RosbagFileInfo; using ros2_medkit_fault_manager::RosbagLink; using ros2_medkit_fault_manager::SnapshotData; using ros2_medkit_fault_manager::SqliteFaultStorage; +using ros2_medkit_fault_manager::core::RosbagRetention; +using ros2_medkit_fault_manager::core::RosbagRetentionLimits; +using ros2_medkit_fault_manager::core::StoreResult; #ifdef POSTGRES_SUPPORT using ros2_medkit_fault_manager::PgFaultStorage; #endif @@ -186,12 +191,46 @@ class RosbagRetentionParityTest : public ::testing::Test { } void TearDown() override { + retention_.reset(); storage_.reset(); BackendFactory::cleanup(dir_); std::error_code ec; std::filesystem::remove_all(dir_, ec); } + static RosbagRetentionLimits cap(size_t max_bags_per_fault) { + RosbagRetentionLimits limits; + limits.max_bags_per_fault = max_bags_per_fault; + return limits; + } + + /// The retention every store() below goes through, over this backend. + void use_retention(RosbagRetentionLimits limits) { + retention_ = std::make_unique(*storage_, limits, test_log_sink(), "rosbag_retention_parity"); + } + + /// Store one recording through the retention and keep the paths it hands over. + void store(std::vector rows) { + const auto outcome = retention_->store(std::move(rows)); + EXPECT_EQ(outcome.result, StoreResult::kStored) << outcome.error; + hand_over(outcome.unlink_paths); + } + + /// Keep the paths of one retention call. Each is listed once across the whole test. + void hand_over(const std::vector & freed) { + const auto paths = paths_of(freed); + expect_unlinkable(paths); + for (const auto & path : paths) { + EXPECT_FALSE(unlinked(path)) << path << " was handed over twice"; + unlink_paths_.push_back(path); + } + } + + /// Whether a retention call of this test handed @p path over for removal. + bool unlinked(const std::string & path) const { + return listed(unlink_paths_, path); + } + /// Create a real bag directory so unlink behaviour is observable, not just row state. /// Bags are directories on disk, which is what both backends remove. std::string make_bag(const std::string & name) { @@ -215,6 +254,8 @@ class RosbagRetentionParityTest : public ::testing::Test { std::filesystem::path dir_; std::unique_ptr storage_; + std::unique_ptr retention_; + std::vector unlink_paths_; }; #ifdef POSTGRES_SUPPORT @@ -229,9 +270,8 @@ TYPED_TEST_SUITE(RosbagRetentionParityTest, Backends); TYPED_TEST(RosbagRetentionParityTest, RecordingIdIsTheBasenameOfEveryStoredRow) { // The gateway addresses a recording by this string and the fault_manager resolves it // back to rows, so a backend that stored anything else would break the URL silently. - this->storage_->set_max_rosbags_per_fault(0); - this->storage_->store_rosbag_file(this->row("BASENAME", "fault_BASENAME_1", 1000)); - this->storage_->store_rosbag_file(this->row("BASENAME", "fault_BASENAME_2", 2000)); + seed_rosbag_rows(*this->storage_, {this->row("BASENAME", "fault_BASENAME_1", 1000)}); + seed_rosbag_rows(*this->storage_, {this->row("BASENAME", "fault_BASENAME_2", 2000)}); const auto rows = this->storage_->get_rosbag_files("BASENAME"); ASSERT_EQ(rows.size(), 2u); @@ -243,10 +283,9 @@ TYPED_TEST(RosbagRetentionParityTest, RecordingIdIsTheBasenameOfEveryStoredRow) TYPED_TEST(RosbagRetentionParityTest, RecordingIdIsDerivedWhenTheCallerLeftItEmpty) { // rosbag_capture fills it, but the interface is public and embedders re-store rows. // A row with no recording_id is unaddressable, so neither backend may store one. - this->storage_->set_max_rosbags_per_fault(0); auto info = this->row("DERIVED", "fault_DERIVED_1", 1000); info.recording_id.clear(); - this->storage_->store_rosbag_file(info); + seed_rosbag_rows(*this->storage_, {info}); const auto rows = this->storage_->get_rosbag_files("DERIVED"); ASSERT_EQ(rows.size(), 1u); @@ -255,46 +294,46 @@ TYPED_TEST(RosbagRetentionParityTest, RecordingIdIsDerivedWhenTheCallerLeftItEmp TYPED_TEST(RosbagRetentionParityTest, SeveralRecordingsForOneFaultSurviveUnderACap) { // The feature itself: this is exactly what the schema made impossible before. - this->storage_->set_max_rosbags_per_fault(3); - this->storage_->store_rosbag_file(this->row("FLAP", "fault_FLAP_1", 1000)); - this->storage_->store_rosbag_file(this->row("FLAP", "fault_FLAP_2", 2000)); - this->storage_->store_rosbag_file(this->row("FLAP", "fault_FLAP_3", 3000)); + this->use_retention(this->cap(3)); + this->store({this->row("FLAP", "fault_FLAP_1", 1000)}); + this->store({this->row("FLAP", "fault_FLAP_2", 2000)}); + this->store({this->row("FLAP", "fault_FLAP_3", 3000)}); const auto rows = this->storage_->get_rosbag_files("FLAP"); ASSERT_EQ(rows.size(), 3u); EXPECT_EQ(rows[0].recording_id, "fault_FLAP_3") << "newest first"; EXPECT_EQ(rows[2].recording_id, "fault_FLAP_1"); for (const auto & r : rows) { - EXPECT_TRUE(std::filesystem::exists(r.file_path)); + EXPECT_FALSE(this->unlinked(r.file_path)); } } TYPED_TEST(RosbagRetentionParityTest, CapKeepsTheNewestAndUnlinksTheEvicted) { - this->storage_->set_max_rosbags_per_fault(2); + this->use_retention(this->cap(2)); const auto oldest = this->row("CAP", "fault_CAP_1", 1000); - this->storage_->store_rosbag_file(oldest); - this->storage_->store_rosbag_file(this->row("CAP", "fault_CAP_2", 2000)); - this->storage_->store_rosbag_file(this->row("CAP", "fault_CAP_3", 3000)); + this->store({oldest}); + this->store({this->row("CAP", "fault_CAP_2", 2000)}); + this->store({this->row("CAP", "fault_CAP_3", 3000)}); const auto rows = this->storage_->get_rosbag_files("CAP"); ASSERT_EQ(rows.size(), 2u); EXPECT_EQ(rows[0].recording_id, "fault_CAP_3"); EXPECT_EQ(rows[1].recording_id, "fault_CAP_2"); - EXPECT_FALSE(std::filesystem::exists(oldest.file_path)) << "the evicted bag must not outlive its last row"; + EXPECT_TRUE(this->unlinked(oldest.file_path)) << "the evicted bag must not outlive its last row"; } TYPED_TEST(RosbagRetentionParityTest, ACapOfOneReproducesThePreviousBehaviourExactly) { // The shipped default. Landing at parity is what makes any regression report about // the plumbing rather than about the retention policy. - this->storage_->set_max_rosbags_per_fault(1); + this->use_retention(this->cap(1)); const auto first = this->row("ONE", "fault_ONE_1", 1000); - this->storage_->store_rosbag_file(first); - this->storage_->store_rosbag_file(this->row("ONE", "fault_ONE_2", 2000)); + this->store({first}); + this->store({this->row("ONE", "fault_ONE_2", 2000)}); const auto rows = this->storage_->get_rosbag_files("ONE"); ASSERT_EQ(rows.size(), 1u); EXPECT_EQ(rows[0].recording_id, "fault_ONE_2"); - EXPECT_FALSE(std::filesystem::exists(first.file_path)); + EXPECT_TRUE(this->unlinked(first.file_path)); const auto newest = this->storage_->get_rosbag_file("ONE"); ASSERT_TRUE(newest.has_value()); @@ -302,20 +341,22 @@ TYPED_TEST(RosbagRetentionParityTest, ACapOfOneReproducesThePreviousBehaviourExa } TYPED_TEST(RosbagRetentionParityTest, ACapOfOneIsTheDefaultWithoutConfiguringAnything) { - // A backend constructed directly - tests, embedders - must not silently start - // accumulating recordings just because the cap became configurable. + // A retention built without configuring anything - tests, embedders - must not silently + // start accumulating recordings just because the cap became configurable. + EXPECT_EQ(RosbagRetentionLimits{}.max_bags_per_fault, 1u); + this->use_retention(RosbagRetentionLimits{}); const auto first = this->row("DEFAULT", "fault_DEFAULT_1", 1000); - this->storage_->store_rosbag_file(first); - this->storage_->store_rosbag_file(this->row("DEFAULT", "fault_DEFAULT_2", 2000)); + this->store({first}); + this->store({this->row("DEFAULT", "fault_DEFAULT_2", 2000)}); EXPECT_EQ(this->storage_->get_rosbag_files("DEFAULT").size(), 1u); - EXPECT_FALSE(std::filesystem::exists(first.file_path)); + EXPECT_TRUE(this->unlinked(first.file_path)); } TYPED_TEST(RosbagRetentionParityTest, ZeroMeansUnlimited) { - this->storage_->set_max_rosbags_per_fault(0); + this->use_retention(this->cap(0)); for (int i = 1; i <= 6; ++i) { - this->storage_->store_rosbag_file(this->row("UNBOUNDED", "fault_UNBOUNDED_" + std::to_string(i), i * 1000)); + this->store({this->row("UNBOUNDED", "fault_UNBOUNDED_" + std::to_string(i), i * 1000)}); } EXPECT_EQ(this->storage_->get_rosbag_files("UNBOUNDED").size(), 6u); } @@ -323,18 +364,18 @@ TYPED_TEST(RosbagRetentionParityTest, ZeroMeansUnlimited) { TYPED_TEST(RosbagRetentionParityTest, ReStoringTheSamePathIsAnUpsertNotASecondRecording) { // Uniqueness is on (fault_code, file_path). Re-storing the same bag - a restart // replaying its rows, say - must update in place, not consume a cap slot. - this->storage_->set_max_rosbags_per_fault(3); + this->use_retention(this->cap(3)); auto info = this->row("UPSERT", "fault_UPSERT_1", 1000); - this->storage_->store_rosbag_file(info); + this->store({info}); info.size_bytes = 4096; info.duration_sec = 9.0; - this->storage_->store_rosbag_file(info); + this->store({info}); const auto rows = this->storage_->get_rosbag_files("UPSERT"); ASSERT_EQ(rows.size(), 1u); EXPECT_EQ(rows[0].size_bytes, 4096u); EXPECT_DOUBLE_EQ(rows[0].duration_sec, 9.0); - EXPECT_TRUE(std::filesystem::exists(rows[0].file_path)) << "an upsert must not unlink the bag it just updated"; + EXPECT_FALSE(this->unlinked(rows[0].file_path)) << "an upsert must not unlink the bag it just updated"; } TYPED_TEST(RosbagRetentionParityTest, RefreshingALinkDoesNotMoveItWithinATieGroup) { @@ -342,13 +383,12 @@ TYPED_TEST(RosbagRetentionParityTest, RefreshingALinkDoesNotMoveItWithinATieGrou // refresh must not renumber the row. SQLite's INSERT OR REPLACE would: it deletes // and re-inserts, handing the row a fresh id and silently promoting it past rows // it was stored before. - this->storage_->set_max_rosbags_per_fault(0); auto first = this->row("REFRESH", "fault_REFRESH_1", 5000); - this->storage_->store_rosbag_file(first); - this->storage_->store_rosbag_file(this->row("REFRESH", "fault_REFRESH_2", 5000)); + seed_rosbag_rows(*this->storage_, {first}); + seed_rosbag_rows(*this->storage_, {this->row("REFRESH", "fault_REFRESH_2", 5000)}); first.size_bytes = 8192; - this->storage_->store_rosbag_file(first); + seed_rosbag_rows(*this->storage_, {first}); const auto rows = this->storage_->get_rosbag_files("REFRESH"); ASSERT_EQ(rows.size(), 2u); @@ -362,9 +402,8 @@ TYPED_TEST(RosbagRetentionParityTest, NewestFirstIsStableWhenAWholeBurstSharesAT // rather than exotic. SQLite breaks them by id; the in-memory backend needs its own // sequence counter to agree. Without it the two orders diverge only sometimes, // which is a flaky test rather than an honest failure. - this->storage_->set_max_rosbags_per_fault(0); for (int i = 1; i <= 4; ++i) { - this->storage_->store_rosbag_file(this->row("TIE", "fault_TIE_" + std::to_string(i), 7000)); + seed_rosbag_rows(*this->storage_, {this->row("TIE", "fault_TIE_" + std::to_string(i), 7000)}); } const auto rows = this->storage_->get_rosbag_files("TIE"); @@ -378,31 +417,31 @@ TYPED_TEST(RosbagRetentionParityTest, NewestFirstIsStableWhenAWholeBurstSharesAT TYPED_TEST(RosbagRetentionParityTest, ACapTieIsBrokenByInsertionOrderNotArbitrarily) { // The same tie, now deciding which bag gets deleted. Whichever row wins, both // backends must agree, and the survivor's bag must be the one still on disk. - this->storage_->set_max_rosbags_per_fault(1); + this->use_retention(this->cap(1)); const auto first = this->row("TIECAP", "fault_TIECAP_1", 7000); - this->storage_->store_rosbag_file(first); + this->store({first}); const auto second = this->row("TIECAP", "fault_TIECAP_2", 7000); - this->storage_->store_rosbag_file(second); + this->store({second}); const auto rows = this->storage_->get_rosbag_files("TIECAP"); ASSERT_EQ(rows.size(), 1u); EXPECT_EQ(rows[0].recording_id, "fault_TIECAP_2"); - EXPECT_TRUE(std::filesystem::exists(second.file_path)); - EXPECT_FALSE(std::filesystem::exists(first.file_path)); + EXPECT_FALSE(this->unlinked(second.file_path)); + EXPECT_TRUE(this->unlinked(first.file_path)); } TYPED_TEST(RosbagRetentionParityTest, ABurstRecordingSurvivesWhileASiblingRowReferencesIt) { // One bag, several faults. The cap evicts A's link but B still holds the bytes. - this->storage_->set_max_rosbags_per_fault(1); + this->use_retention(this->cap(1)); auto shared = this->row("BURST_A", "fault_BURST_1", 1000); - this->storage_->store_rosbag_file(shared); + this->store({shared}); shared.fault_code = "BURST_B"; - this->storage_->store_rosbag_file(shared); + this->store({shared}); const auto shared_path = shared.file_path; - this->storage_->store_rosbag_file(this->row("BURST_A", "fault_BURST_2", 2000)); + this->store({this->row("BURST_A", "fault_BURST_2", 2000)}); - EXPECT_TRUE(std::filesystem::exists(shared_path)) << "the sibling fault still owns the shared bag"; + EXPECT_FALSE(this->unlinked(shared_path)) << "the sibling fault still owns the shared bag"; const auto sibling = this->storage_->get_rosbag_files("BURST_B"); ASSERT_EQ(sibling.size(), 1u); EXPECT_EQ(sibling[0].file_path, shared_path); @@ -411,13 +450,12 @@ TYPED_TEST(RosbagRetentionParityTest, ABurstRecordingSurvivesWhileASiblingRowRef TYPED_TEST(RosbagRetentionParityTest, RecordingLookupReturnsEveryFaultOfTheBurst) { // This is what the gateway authorizes against: the union of faults attached to a // recording. Missing one would 404 a download the entity is entitled to. - this->storage_->set_max_rosbags_per_fault(0); auto shared = this->row("LOOKUP_A", "fault_LOOKUP_1", 1000); - this->storage_->store_rosbag_file(shared); + seed_rosbag_rows(*this->storage_, {shared}); shared.fault_code = "LOOKUP_B"; - this->storage_->store_rosbag_file(shared); + seed_rosbag_rows(*this->storage_, {shared}); shared.fault_code = "LOOKUP_C"; - this->storage_->store_rosbag_file(shared); + seed_rosbag_rows(*this->storage_, {shared}); const auto rows = this->storage_->get_rosbag_files_by_recording("fault_LOOKUP_1"); ASSERT_EQ(rows.size(), 3u); @@ -439,52 +477,57 @@ TYPED_TEST(RosbagRetentionParityTest, AnUnknownRecordingLooksUpEmptyRatherThanTh } TYPED_TEST(RosbagRetentionParityTest, DeletingARecordingRemovesEveryLinkAndTheBag) { - // What the quota sweep calls. Deleting by fault code here would wipe the whole - // history of every fault the bag touched. - this->storage_->set_max_rosbags_per_fault(0); + // Removal by recording, as the stale-row cleanup does. Deleting by fault code here would + // wipe the whole history of every fault the bag touched. auto shared = this->row("DELREC_A", "fault_DELREC_1", 1000); - this->storage_->store_rosbag_file(shared); + seed_rosbag_rows(*this->storage_, {shared}); shared.fault_code = "DELREC_B"; - this->storage_->store_rosbag_file(shared); + seed_rosbag_rows(*this->storage_, {shared}); const auto kept = this->row("DELREC_A", "fault_DELREC_2", 2000); - this->storage_->store_rosbag_file(kept); + seed_rosbag_rows(*this->storage_, {kept}); + this->use_retention(RosbagRetentionLimits{}); - EXPECT_EQ(this->storage_->delete_rosbag_recording("fault_DELREC_1"), 2u); - EXPECT_FALSE(std::filesystem::exists(shared.file_path)); + const auto removal = this->retention_->forget_recording("fault_DELREC_1"); + this->hand_over(removal.unlink_paths); + EXPECT_EQ(removal.removed_rows, 2u); + EXPECT_TRUE(this->unlinked(shared.file_path)); EXPECT_TRUE(this->storage_->get_rosbag_files("DELREC_B").empty()); const auto survivors = this->storage_->get_rosbag_files("DELREC_A"); ASSERT_EQ(survivors.size(), 1u) << "the other fault's other recording is untouched"; EXPECT_EQ(survivors[0].recording_id, "fault_DELREC_2"); - EXPECT_TRUE(std::filesystem::exists(kept.file_path)); + EXPECT_FALSE(this->unlinked(kept.file_path)); - EXPECT_EQ(this->storage_->delete_rosbag_recording("fault_DELREC_1"), 0u); + const auto again = this->retention_->forget_recording("fault_DELREC_1"); + this->hand_over(again.unlink_paths); + EXPECT_EQ(again.removed_rows, 0u); } TYPED_TEST(RosbagRetentionParityTest, DeletingAFaultDropsAllItsRecordings) { - this->storage_->set_max_rosbags_per_fault(0); const auto a = this->row("DELALL", "fault_DELALL_1", 1000); const auto b = this->row("DELALL", "fault_DELALL_2", 2000); - this->storage_->store_rosbag_file(a); - this->storage_->store_rosbag_file(b); + seed_rosbag_rows(*this->storage_, {a}); + seed_rosbag_rows(*this->storage_, {b}); + this->use_retention(RosbagRetentionLimits{}); - EXPECT_TRUE(this->storage_->delete_rosbag_file("DELALL")); + const auto removal = this->retention_->on_fault_cleared("DELALL"); + this->hand_over(removal.unlink_paths); + EXPECT_EQ(removal.removed_rows, 2u); EXPECT_TRUE(this->storage_->get_rosbag_files("DELALL").empty()); - EXPECT_FALSE(std::filesystem::exists(a.file_path)); - EXPECT_FALSE(std::filesystem::exists(b.file_path)); + EXPECT_TRUE(this->unlinked(a.file_path)); + EXPECT_TRUE(this->unlinked(b.file_path)); } TYPED_TEST(RosbagRetentionParityTest, ASharedBagCountsOnceTowardsStorageAcrossSeveralRecordings) { // The quota sums bytes per path, not per row. N recordings per fault multiplies the // rows, so a per-row sum would over-report and evict healthy bags under no pressure. - this->storage_->set_max_rosbags_per_fault(0); auto shared = this->row("QUOTA_A", "fault_QUOTA_1", 1000); - this->storage_->store_rosbag_file(shared); + seed_rosbag_rows(*this->storage_, {shared}); shared.fault_code = "QUOTA_B"; - this->storage_->store_rosbag_file(shared); + seed_rosbag_rows(*this->storage_, {shared}); shared.fault_code = "QUOTA_C"; - this->storage_->store_rosbag_file(shared); - this->storage_->store_rosbag_file(this->row("QUOTA_A", "fault_QUOTA_2", 2000)); + seed_rosbag_rows(*this->storage_, {shared}); + seed_rosbag_rows(*this->storage_, {this->row("QUOTA_A", "fault_QUOTA_2", 2000)}); EXPECT_EQ(this->storage_->get_total_rosbag_storage_bytes(), 2048u) << "two distinct bags of 1024, counted once each"; } @@ -492,10 +535,9 @@ TYPED_TEST(RosbagRetentionParityTest, ASharedBagCountsOnceTowardsStorageAcrossSe TYPED_TEST(RosbagRetentionParityTest, GetAllRosbagFilesListsEveryRecordingOldestFirst) { // The quota sweep walks this list and evicts from the front, so the extra rows this // change introduces have to appear here in a defined order. - this->storage_->set_max_rosbags_per_fault(0); - this->storage_->store_rosbag_file(this->row("ALL_A", "fault_ALL_1", 3000)); - this->storage_->store_rosbag_file(this->row("ALL_A", "fault_ALL_2", 1000)); - this->storage_->store_rosbag_file(this->row("ALL_B", "fault_ALL_3", 2000)); + seed_rosbag_rows(*this->storage_, {this->row("ALL_A", "fault_ALL_1", 3000)}); + seed_rosbag_rows(*this->storage_, {this->row("ALL_A", "fault_ALL_2", 1000)}); + seed_rosbag_rows(*this->storage_, {this->row("ALL_B", "fault_ALL_3", 2000)}); const auto rows = this->storage_->get_all_rosbag_files(); ASSERT_EQ(rows.size(), 3u); @@ -504,14 +546,132 @@ TYPED_TEST(RosbagRetentionParityTest, GetAllRosbagFilesListsEveryRecordingOldest EXPECT_EQ(rows[2].recording_id, "fault_ALL_1"); } +TYPED_TEST(RosbagRetentionParityTest, OneFaultKeepsSeveralRecordingsWhenTheCapAllows) { + this->use_retention(this->cap(3)); + this->store({this->row("FLAP", "fault_FLAP_100", 100)}); + this->store({this->row("FLAP", "fault_FLAP_200", 200)}); + + const auto rows = this->storage_->get_rosbag_files("FLAP"); + ASSERT_EQ(rows.size(), 2u) << "the second recording must not replace the first"; + EXPECT_EQ(rows[0].recording_id, "fault_FLAP_200") << "newest first"; + EXPECT_EQ(rows[1].recording_id, "fault_FLAP_100"); + + // get_rosbag_file is "the newest", deterministically. + const auto newest = this->storage_->get_rosbag_file("FLAP"); + ASSERT_TRUE(newest.has_value()); + EXPECT_EQ(newest->recording_id, "fault_FLAP_200"); +} + +TYPED_TEST(RosbagRetentionParityTest, CapKeepsTheNewestAndUnlinksTheEvictedBag) { + this->use_retention(this->cap(1)); + const auto a = this->row("CAP", "fault_CAP_100", 100); + const auto b = this->row("CAP", "fault_CAP_200", 200); + this->store({a}); + this->store({b}); + + const auto rows = this->storage_->get_rosbag_files("CAP"); + ASSERT_EQ(rows.size(), 1u) << "cap 1 is the historical behaviour: one recording per fault"; + EXPECT_EQ(rows[0].file_path, b.file_path); + EXPECT_TRUE(this->unlinked(a.file_path)) << "the evicted bag must be unlinked"; + EXPECT_FALSE(this->unlinked(b.file_path)); +} + +TYPED_TEST(RosbagRetentionParityTest, EvictingOneFaultsLinkKeepsABagASiblingStillReferences) { + // A burst shares one recording. Evicting it for one fault must not take the bytes + // the other fault still points at. + this->use_retention(this->cap(1)); + auto shared_b = this->row("B", "fault_SHARED_100", 100); + auto shared_a = shared_b; + shared_a.fault_code = "A"; + this->store({shared_a, shared_b}); + // A re-confirms with its own new bag, so A's link to the shared one is evicted. + this->store({this->row("A", "fault_A_200", 200)}); + + EXPECT_FALSE(this->unlinked(shared_b.file_path)) << "B still references it"; + const auto b_rows = this->storage_->get_rosbag_files("B"); + ASSERT_EQ(b_rows.size(), 1u); + EXPECT_EQ(b_rows[0].file_path, shared_b.file_path); +} + +// Re-store guard: a fault re-confirming stores a row with a new path, and the +// old bag must be unlinked only when no sibling fault still references it. + +TYPED_TEST(RosbagRetentionParityTest, RestoreWithNewPathUnlinksTheOldExclusiveBag) { + this->use_retention(RosbagRetentionLimits{}); + const auto old_bag = this->row("X", "exclusive_bag", 1000); + this->store({old_bag}); + + auto info = old_bag; + info.file_path = this->make_bag("exclusive_bag_new"); + info.recording_id = rosbag_recording_id(info.file_path); + this->store({info}); + + EXPECT_TRUE(this->unlinked(old_bag.file_path)) << "nobody references the old bag, it must be unlinked"; + auto row = this->storage_->get_rosbag_file("X"); + ASSERT_TRUE(row.has_value()); + EXPECT_EQ(row->file_path, info.file_path); +} + +TYPED_TEST(RosbagRetentionParityTest, RestoreWithNewPathKeepsTheBagASiblingStillReferences) { + this->use_retention(RosbagRetentionLimits{}); + auto info = this->row("X", "shared_bag", 1000); + const auto shared_path = info.file_path; + this->store({info}); + info.fault_code = "Y"; + this->store({info}); + + info.fault_code = "X"; + info.file_path = this->make_bag("shared_bag_new"); + info.recording_id = rosbag_recording_id(info.file_path); + this->store({info}); + + EXPECT_FALSE(this->unlinked(shared_path)) << "the sibling fault still owns the shared bag"; + auto sibling = this->storage_->get_rosbag_file("Y"); + ASSERT_TRUE(sibling.has_value()); + EXPECT_EQ(sibling->file_path, shared_path); +} + +TYPED_TEST(RosbagRetentionParityTest, ABatchStoreUnlinksASharedReplacedBagExactlyOnce) { + // Two faults of one burst can share the bag being replaced, and whether it is still + // referenced has to be judged on the finished batch. Judged row by row beforehand, + // each row sees its sibling still pointing at the old bag and neither unlinks it. + this->use_retention(RosbagRetentionLimits{}); + auto shared = this->row("SHARED_A", "shared_old_bag", 1000); + const auto old_bag = shared.file_path; + this->store({shared}); + shared.fault_code = "SHARED_B"; + this->store({shared}); + ASSERT_FALSE(this->unlinked(old_bag)); + + auto moved = shared; + moved.file_path = this->make_bag("shared_new_bag"); + moved.recording_id = rosbag_recording_id(moved.file_path); + moved.created_at_ns = 2000; + std::vector rows; + rows.reserve(2); + moved.fault_code = "SHARED_A"; + rows.push_back(moved); + moved.fault_code = "SHARED_B"; + rows.push_back(moved); + this->store(rows); + + EXPECT_TRUE(this->unlinked(old_bag)) << "the replaced bag leaked: nothing references it any more"; + EXPECT_FALSE(this->unlinked(moved.file_path)) << "the bag the batch points at was removed"; + auto row_a = this->storage_->get_rosbag_file("SHARED_A"); + auto row_b = this->storage_->get_rosbag_file("SHARED_B"); + ASSERT_TRUE(row_a.has_value()); + ASSERT_TRUE(row_b.has_value()); + EXPECT_EQ(row_a->file_path, moved.file_path); + EXPECT_EQ(row_b->file_path, moved.file_path); +} + // apply_rosbag_changes: the one write primitive. Same body over every backend. TYPED_TEST(RosbagRetentionParityTest, ApplyTwiceIsIdempotent) { const auto a = this->row("TWICE_A", "fault_TWICE_1", 1000); const auto b = this->row("TWICE_B", "fault_TWICE_2", 2000); - this->storage_->set_max_rosbags_per_fault(0); - this->storage_->store_rosbag_file(a); - this->storage_->store_rosbag_file(b); + seed_rosbag_rows(*this->storage_, {a}); + seed_rosbag_rows(*this->storage_, {b}); RosbagChangeSet set; set.insert.push_back(this->row("TWICE_C", "fault_TWICE_3", 3000)); @@ -536,11 +696,10 @@ TYPED_TEST(RosbagRetentionParityTest, ApplyTwiceIsIdempotent) { } TYPED_TEST(RosbagRetentionParityTest, OrphanedPathOnlyWhenLastLinkRemoved) { - this->storage_->set_max_rosbags_per_fault(0); auto shared = this->row("ORPHAN_A", "fault_ORPHAN_1", 1000); - this->storage_->store_rosbag_file(shared); + seed_rosbag_rows(*this->storage_, {shared}); shared.fault_code = "ORPHAN_B"; - this->storage_->store_rosbag_file(shared); + seed_rosbag_rows(*this->storage_, {shared}); RosbagChangeSet first; first.remove.push_back({"ORPHAN_A", shared.file_path}); @@ -561,9 +720,8 @@ TYPED_TEST(RosbagRetentionParityTest, OrphanedPathOnlyWhenLastLinkRemoved) { } TYPED_TEST(RosbagRetentionParityTest, ASetThatMovesTheLastLinkToAnotherFaultOrphansNothing) { - this->storage_->set_max_rosbags_per_fault(0); const auto old_link = this->row("MOVE_A", "fault_MOVE_1", 1000); - this->storage_->store_rosbag_file(old_link); + seed_rosbag_rows(*this->storage_, {old_link}); RosbagChangeSet set; set.remove.push_back({"MOVE_A", old_link.file_path}); @@ -577,7 +735,6 @@ TYPED_TEST(RosbagRetentionParityTest, ASetThatMovesTheLastLinkToAnotherFaultOrph } TYPED_TEST(RosbagRetentionParityTest, UpsertOnLinkKeepsOneRow) { - this->storage_->set_max_rosbags_per_fault(0); auto info = this->row("APPLY_UPSERT", "fault_APPLY_UPSERT_1", 1000); const auto sibling = this->row("APPLY_UPSERT", "fault_APPLY_UPSERT_2", 1000); @@ -621,13 +778,12 @@ TYPED_TEST(RosbagRetentionParityTest, UpsertOnLinkKeepsOneRow) { } TYPED_TEST(RosbagRetentionParityTest, RemoveRecordingsRemovesEveryLink) { - this->storage_->set_max_rosbags_per_fault(0); auto burst = this->row("RECS_A", "fault_RECS_1", 1000); - this->storage_->store_rosbag_file(burst); + seed_rosbag_rows(*this->storage_, {burst}); burst.fault_code = "RECS_B"; - this->storage_->store_rosbag_file(burst); + seed_rosbag_rows(*this->storage_, {burst}); const auto other = this->row("RECS_A", "fault_RECS_2", 2000); - this->storage_->store_rosbag_file(other); + seed_rosbag_rows(*this->storage_, {other}); RosbagChangeSet set; set.remove_recordings = {"fault_RECS_1", "fault_RECS_1", "fault_RECS_UNKNOWN", ""}; @@ -641,11 +797,10 @@ TYPED_TEST(RosbagRetentionParityTest, RemoveRecordingsRemovesEveryLink) { } TYPED_TEST(RosbagRetentionParityTest, ApplyNeverUnlinks) { - this->storage_->set_max_rosbags_per_fault(0); const auto a = this->row("KEEP_A", "fault_KEEP_1", 1000); const auto b = this->row("KEEP_B", "fault_KEEP_2", 2000); - this->storage_->store_rosbag_file(a); - this->storage_->store_rosbag_file(b); + seed_rosbag_rows(*this->storage_, {a}); + seed_rosbag_rows(*this->storage_, {b}); RosbagChangeSet set; set.remove.push_back({"KEEP_A", a.file_path}); @@ -659,7 +814,6 @@ TYPED_TEST(RosbagRetentionParityTest, ApplyNeverUnlinks) { } TYPED_TEST(RosbagRetentionParityTest, ApplyAppliesNoCap) { - this->storage_->set_max_rosbags_per_fault(1); RosbagChangeSet set; for (int i = 1; i <= 3; ++i) { set.insert.push_back(this->row("NOCAP", "fault_NOCAP_" + std::to_string(i), i * 1000)); @@ -671,9 +825,8 @@ TYPED_TEST(RosbagRetentionParityTest, ApplyAppliesNoCap) { } TYPED_TEST(RosbagRetentionParityTest, RejectsInsertAndRemoveOfTheSameLink) { - this->storage_->set_max_rosbags_per_fault(0); const auto kept = this->row("REJECT_A", "fault_REJECT_1", 1000); - this->storage_->store_rosbag_file(kept); + seed_rosbag_rows(*this->storage_, {kept}); const auto before = this->storage_->get_all_rosbag_files(); auto fresh = this->row("REJECT_B", "fault_REJECT_2", 2000); @@ -707,9 +860,8 @@ class RosbagApplyAtomicityTest : public RosbagRetentionParityTest {}; TYPED_TEST_SUITE(RosbagApplyAtomicityTest, SqlBackends); TYPED_TEST(RosbagApplyAtomicityTest, ApplyIsAtomicOnInsertFailure) { - this->storage_->set_max_rosbags_per_fault(0); const auto a = this->row("ATOM_A", "fault_ATOM_1", 1000); - this->storage_->store_rosbag_file(a); + seed_rosbag_rows(*this->storage_, {a}); BackendFactory::add_failing_trigger(this->dir_, "INSERT", "ATOM_FAIL"); RosbagChangeSet set; @@ -725,11 +877,10 @@ TYPED_TEST(RosbagApplyAtomicityTest, ApplyIsAtomicOnInsertFailure) { } TYPED_TEST(RosbagApplyAtomicityTest, ApplyIsAtomicOnDeleteFailure) { - this->storage_->set_max_rosbags_per_fault(0); const auto a = this->row("ATOM_A", "fault_ATOM_1", 1000); const auto failing = this->row("ATOM_FAIL", "fault_ATOM_2", 2000); - this->storage_->store_rosbag_file(a); - this->storage_->store_rosbag_file(failing); + seed_rosbag_rows(*this->storage_, {a}); + seed_rosbag_rows(*this->storage_, {failing}); BackendFactory::add_failing_trigger(this->dir_, "DELETE", "ATOM_FAIL"); RosbagChangeSet set; diff --git a/src/ros2_medkit_fault_manager/test/test_sqlite_storage.cpp b/src/ros2_medkit_fault_manager/test/test_sqlite_storage.cpp index 509f1a3ea..d2a26ecce 100644 --- a/src/ros2_medkit_fault_manager/test/test_sqlite_storage.cpp +++ b/src/ros2_medkit_fault_manager/test/test_sqlite_storage.cpp @@ -26,14 +26,18 @@ #include #include "rclcpp/rclcpp.hpp" +#include "ros2_medkit_fault_manager/core/rosbag_retention.hpp" #include "ros2_medkit_fault_manager/sqlite_fault_storage.hpp" #include "ros2_medkit_msgs/msg/fault.hpp" #include "ros2_medkit_msgs/srv/report_fault.hpp" #include "test_log_sink.hpp" +#include "test_rosbag_rows.hpp" using ros2_medkit_fault_manager::DebounceConfig; using ros2_medkit_fault_manager::RosbagFileInfo; using ros2_medkit_fault_manager::SqliteFaultStorage; +using ros2_medkit_fault_manager::core::RosbagRetention; +using ros2_medkit_fault_manager::core::RosbagRetentionLimits; using ros2_medkit_msgs::msg::Fault; using ros2_medkit_msgs::srv::ReportFault; @@ -1058,7 +1062,7 @@ TEST_F(SqliteFaultStorageTest, LegacyUniqueConstraintIsRebuiltAwayAndRecordingId TEST_F(SqliteFaultStorageTest, ReopeningAMigratedDatabaseIsANoOp) { // The migration runs on every open, so it has to be idempotent - a second and // third open must not rebuild again, lose rows or re-backfill. - storage_->store_rosbag_file(make_rosbag("A", "/bags/fault_A_100", 100)); + seed_rosbag_rows(*storage_, {make_rosbag("A", "/bags/fault_A_100", 100)}); const auto before = storage_->get_all_rosbag_files(); for (int i = 0; i < 2; ++i) { @@ -1071,63 +1075,9 @@ TEST_F(SqliteFaultStorageTest, ReopeningAMigratedDatabaseIsANoOp) { } } -TEST_F(SqliteFaultStorageTest, OneFaultKeepsSeveralRecordingsWhenTheCapAllows) { - storage_->set_max_rosbags_per_fault(3); - storage_->store_rosbag_file(make_rosbag("FLAP", "/bags/fault_FLAP_100", 100)); - storage_->store_rosbag_file(make_rosbag("FLAP", "/bags/fault_FLAP_200", 200)); - - const auto rows = storage_->get_rosbag_files("FLAP"); - ASSERT_EQ(rows.size(), 2u) << "the second recording must not replace the first"; - EXPECT_EQ(rows[0].recording_id, "fault_FLAP_200") << "newest first"; - EXPECT_EQ(rows[1].recording_id, "fault_FLAP_100"); - - // get_rosbag_file is "the newest", deterministically. - const auto newest = storage_->get_rosbag_file("FLAP"); - ASSERT_TRUE(newest.has_value()); - EXPECT_EQ(newest->recording_id, "fault_FLAP_200"); -} - -TEST_F(SqliteFaultStorageTest, CapKeepsTheNewestAndUnlinksTheEvictedBag) { - const auto bags = temp_db_path_.parent_path() / (temp_db_path_.stem().string() + "_bags"); - const auto dir_a = bags / "fault_CAP_100"; - const auto dir_b = bags / "fault_CAP_200"; - std::filesystem::create_directories(dir_a); - std::filesystem::create_directories(dir_b); - - storage_->set_max_rosbags_per_fault(1); - storage_->store_rosbag_file(make_rosbag("CAP", dir_a.string(), 100)); - storage_->store_rosbag_file(make_rosbag("CAP", dir_b.string(), 200)); - - const auto rows = storage_->get_rosbag_files("CAP"); - ASSERT_EQ(rows.size(), 1u) << "cap 1 is the historical behaviour: one recording per fault"; - EXPECT_EQ(rows[0].file_path, dir_b.string()); - EXPECT_FALSE(std::filesystem::exists(dir_a)) << "the evicted bag must be unlinked"; - EXPECT_TRUE(std::filesystem::exists(dir_b)); -} - -TEST_F(SqliteFaultStorageTest, EvictingOneFaultsLinkKeepsABagASiblingStillReferences) { - // A burst shares one recording. Evicting it for one fault must not take the bytes - // the other fault still points at. - const auto bags = temp_db_path_.parent_path() / (temp_db_path_.stem().string() + "_bags"); - const auto shared = bags / "fault_SHARED_100"; - const auto later = bags / "fault_A_200"; - std::filesystem::create_directories(shared); - std::filesystem::create_directories(later); - - storage_->set_max_rosbags_per_fault(1); - storage_->store_rosbag_files({make_rosbag("A", shared.string(), 100), make_rosbag("B", shared.string(), 100)}); - // A re-confirms with its own new bag, so A's link to the shared one is evicted. - storage_->store_rosbag_file(make_rosbag("A", later.string(), 200)); - - EXPECT_TRUE(std::filesystem::exists(shared)) << "B still references it"; - const auto b_rows = storage_->get_rosbag_files("B"); - ASSERT_EQ(b_rows.size(), 1u); - EXPECT_EQ(b_rows[0].file_path, shared.string()); -} - TEST_F(SqliteFaultStorageTest, RecordingLookupReturnsEveryFaultOfTheBurst) { - storage_->store_rosbag_files({make_rosbag("A", "/bags/fault_A_100", 100), make_rosbag("B", "/bags/fault_A_100", 100), - make_rosbag("C", "/bags/fault_A_100", 100)}); + seed_rosbag_rows(*storage_, {make_rosbag("A", "/bags/fault_A_100", 100), make_rosbag("B", "/bags/fault_A_100", 100), + make_rosbag("C", "/bags/fault_A_100", 100)}); const auto rows = storage_->get_rosbag_files_by_recording("fault_A_100"); ASSERT_EQ(rows.size(), 3u) << "the download authorizes against this set"; @@ -1140,28 +1090,37 @@ TEST_F(SqliteFaultStorageTest, DeleteRecordingRemovesEveryLinkAndTheBag) { const auto bags = temp_db_path_.parent_path() / (temp_db_path_.stem().string() + "_bags"); const auto dir = bags / "fault_A_100"; std::filesystem::create_directories(dir); - storage_->store_rosbag_files({make_rosbag("A", dir.string(), 100), make_rosbag("B", dir.string(), 100)}); + seed_rosbag_rows(*storage_, {make_rosbag("A", dir.string(), 100), make_rosbag("B", dir.string(), 100)}); + RosbagRetention retention(*storage_, RosbagRetentionLimits{}, test_log_sink(), "test_sqlite_storage"); - EXPECT_EQ(storage_->delete_rosbag_recording("fault_A_100"), 2u); + const auto removal = retention.forget_recording("fault_A_100"); + expect_unlinkable(removal.unlink_paths); + EXPECT_EQ(removal.removed_rows, 2u); EXPECT_TRUE(storage_->get_rosbag_files("A").empty()); EXPECT_TRUE(storage_->get_rosbag_files("B").empty()); - EXPECT_FALSE(std::filesystem::exists(dir)); + EXPECT_TRUE(listed(removal.unlink_paths, dir.string())); + std::filesystem::remove_all(bags); } TEST_F(SqliteFaultStorageTest, DeletingAFaultDropsAllItsRecordings) { - storage_->set_max_rosbags_per_fault(0); - storage_->store_rosbag_file(make_rosbag("A", "/bags/fault_A_100", 100)); - storage_->store_rosbag_file(make_rosbag("A", "/bags/fault_A_200", 200)); - - EXPECT_TRUE(storage_->delete_rosbag_file("A")); + const auto bags = temp_db_path_.parent_path() / (temp_db_path_.stem().string() + "_bags"); + std::filesystem::create_directories(bags / "fault_A_100"); + std::filesystem::create_directories(bags / "fault_A_200"); + seed_rosbag_rows(*storage_, {make_rosbag("A", (bags / "fault_A_100").string(), 100)}); + seed_rosbag_rows(*storage_, {make_rosbag("A", (bags / "fault_A_200").string(), 200)}); + RosbagRetention retention(*storage_, RosbagRetentionLimits{}, test_log_sink(), "test_sqlite_storage"); + + const auto removal = retention.on_fault_cleared("A"); + expect_unlinkable(removal.unlink_paths); + EXPECT_EQ(removal.removed_rows, 2u); EXPECT_TRUE(storage_->get_rosbag_files("A").empty()) << "auto_cleanup drops the fault's whole history"; + std::filesystem::remove_all(bags); } TEST_F(SqliteFaultStorageTest, SharedRecordingStillCountsOnceTowardsStorageWithSeveralRecordings) { - storage_->set_max_rosbags_per_fault(0); - storage_->store_rosbag_files( - {make_rosbag("A", "/bags/fault_A_100", 100, 4096), make_rosbag("B", "/bags/fault_A_100", 100, 4096)}); - storage_->store_rosbag_file(make_rosbag("A", "/bags/fault_A_200", 200, 1024)); + seed_rosbag_rows( + *storage_, {make_rosbag("A", "/bags/fault_A_100", 100, 4096), make_rosbag("B", "/bags/fault_A_100", 100, 4096)}); + seed_rosbag_rows(*storage_, {make_rosbag("A", "/bags/fault_A_200", 200, 1024)}); EXPECT_EQ(storage_->get_total_rosbag_storage_bytes(), 4096u + 1024u) << "bytes belong to file_path, not to the row"; } @@ -1457,7 +1416,7 @@ TEST_F(SqliteFaultStorageTest, ListRosbagsForEntityFiltersCorrectly) { info1.duration_sec = 5.0; info1.size_bytes = 1024; info1.created_at_ns = clock.now().nanoseconds(); - storage_->store_rosbag_file(info1); + seed_rosbag_rows(*storage_, {info1}); RosbagFileInfo info2; info2.fault_code = "ENTITY_FAULT_2"; @@ -1466,7 +1425,7 @@ TEST_F(SqliteFaultStorageTest, ListRosbagsForEntityFiltersCorrectly) { info2.duration_sec = 3.0; info2.size_bytes = 512; info2.created_at_ns = clock.now().nanoseconds(); - storage_->store_rosbag_file(info2); + seed_rosbag_rows(*storage_, {info2}); // Get rosbags for motor entity auto rosbags = storage_->list_rosbags_for_entity("/powertrain/motor"); @@ -1486,11 +1445,10 @@ TEST_F(SqliteFaultStorageTest, ListRosbagsForEntityFiltersCorrectly) { TEST_F(SqliteFaultStorageTest, AFailingRowDeleteKeepsTheBagOnDisk) { using ros2_medkit_fault_manager::RosbagFileInfo; - // delete_rosbag_file() has to survive a DELETE that throws - a busy, full or - // read-only database - without having already unlinked the bag. A surviving row - // whose directory is gone fails every later retrieval and keeps its bytes charged - // against the quota, which sums rows. The batch sibling states this invariant in - // its own comment; this pins it for the single-row path too. + // A clear has to survive a DELETE that throws - a busy, full or read-only database - + // without the bag being unlinked. A surviving row whose directory is gone fails every + // later retrieval and keeps its bytes charged against the quota, which sums rows. The + // storage primitive never unlinks, and the retention hands over nothing on a throw. const auto bag_dir = std::filesystem::temp_directory_path() / "test_failing_delete_bag"; std::filesystem::create_directories(bag_dir); { std::ofstream(bag_dir / "payload.mcap") << "data"; } @@ -1502,7 +1460,7 @@ TEST_F(SqliteFaultStorageTest, AFailingRowDeleteKeepsTheBagOnDisk) { info.duration_sec = 1.0; info.size_bytes = 4; info.created_at_ns = 1000; - storage_->store_rosbag_file(info); + seed_rosbag_rows(*storage_, {info}); // Make the DELETE, and only the DELETE, fail. A dropped or renamed table would // take the preceding SELECT with it, and the unlink under test comes after that. @@ -1515,7 +1473,8 @@ TEST_F(SqliteFaultStorageTest, AFailingRowDeleteKeepsTheBagOnDisk) { SQLITE_OK); sqlite3_close(raw); - EXPECT_THROW(storage_->delete_rosbag_file("DELETE_FAILS"), std::runtime_error); + RosbagRetention retention(*storage_, RosbagRetentionLimits{}, test_log_sink(), "test_sqlite_storage"); + EXPECT_THROW(retention.on_fault_cleared("DELETE_FAILS"), std::runtime_error); EXPECT_TRUE(storage_->get_rosbag_file("DELETE_FAILS").has_value()) << "the DELETE failed, so its row must remain"; EXPECT_TRUE(std::filesystem::exists(bag_dir)) @@ -1536,7 +1495,7 @@ TEST_F(SqliteFaultStorageTest, GetAllRosbagFilesReturnsSortedByCreatedAt) { info1.duration_sec = 1.0; info1.size_bytes = 100; info1.created_at_ns = 1000; - storage_->store_rosbag_file(info1); + seed_rosbag_rows(*storage_, {info1}); RosbagFileInfo info2; info2.fault_code = "FAULT_B"; @@ -1545,7 +1504,7 @@ TEST_F(SqliteFaultStorageTest, GetAllRosbagFilesReturnsSortedByCreatedAt) { info2.duration_sec = 2.0; info2.size_bytes = 200; info2.created_at_ns = 2000; - storage_->store_rosbag_file(info2); + seed_rosbag_rows(*storage_, {info2}); auto all_rosbags = storage_->get_all_rosbag_files(); ASSERT_EQ(all_rosbags.size(), 2u); @@ -1572,17 +1531,23 @@ TEST_F(SqliteFaultStorageTest, SharedRosbagSurvivesUntilTheLastFaultIsDeleted) { info.duration_sec = 5.0; info.size_bytes = 4096; info.created_at_ns = 1000; - storage_->store_rosbag_file(info); + seed_rosbag_rows(*storage_, {info}); info.fault_code = "CORRELATED"; - storage_->store_rosbag_file(info); + seed_rosbag_rows(*storage_, {info}); + RosbagRetention retention(*storage_, RosbagRetentionLimits{}, test_log_sink(), "test_sqlite_storage"); - EXPECT_TRUE(storage_->delete_rosbag_file("CORRELATED")); - EXPECT_TRUE(std::filesystem::exists(bag_path)); + const auto correlated = retention.on_fault_cleared("CORRELATED"); + expect_unlinkable(correlated.unlink_paths); + EXPECT_GT(correlated.removed_rows, 0u); + EXPECT_FALSE(listed(correlated.unlink_paths, bag_path)); EXPECT_TRUE(storage_->get_rosbag_file("ROOT_CAUSE").has_value()); - EXPECT_TRUE(storage_->delete_rosbag_file("ROOT_CAUSE")); - EXPECT_FALSE(std::filesystem::exists(bag_path)); + const auto root = retention.on_fault_cleared("ROOT_CAUSE"); + expect_unlinkable(root.unlink_paths); + EXPECT_GT(root.removed_rows, 0u); + EXPECT_TRUE(listed(root.unlink_paths, bag_path)); + std::filesystem::remove_all(bag_path); } TEST_F(SqliteFaultStorageTest, SharedRosbagCountsOnceTowardsStorageTotal) { @@ -1600,7 +1565,7 @@ TEST_F(SqliteFaultStorageTest, SharedRosbagCountsOnceTowardsStorageTotal) { info.duration_sec = 5.0; info.size_bytes = bytes; info.created_at_ns = 1000; - storage_->store_rosbag_file(info); + seed_rosbag_rows(*storage_, {info}); }; store("BIG_FIRST", "/tmp/shared_a.mcap", 1000); @@ -1612,63 +1577,6 @@ TEST_F(SqliteFaultStorageTest, SharedRosbagCountsOnceTowardsStorageTotal) { EXPECT_EQ(storage_->get_total_rosbag_storage_bytes(), 1000u + 800u + 500u); } -// Re-store guard: a fault re-confirming stores a row with a new path, and the -// old bag must be unlinked only when no sibling fault still references it. - -TEST_F(SqliteFaultStorageTest, RestoreWithNewPathUnlinksTheOldExclusiveBag) { - using ros2_medkit_fault_manager::RosbagFileInfo; - - const auto old_path = temp_db_path_.string() + "_exclusive_bag"; - std::filesystem::create_directories(old_path); - - RosbagFileInfo info; - info.fault_code = "X"; - info.file_path = old_path; - info.format = "mcap"; - info.duration_sec = 5.0; - info.size_bytes = 100; - info.created_at_ns = 1000; - storage_->store_rosbag_file(info); - - info.file_path = old_path + "_new"; - storage_->store_rosbag_file(info); - - EXPECT_FALSE(std::filesystem::exists(old_path)) << "nobody references the old bag, it must be unlinked"; - auto row = storage_->get_rosbag_file("X"); - ASSERT_TRUE(row.has_value()); - EXPECT_EQ(row->file_path, old_path + "_new"); -} - -TEST_F(SqliteFaultStorageTest, RestoreWithNewPathKeepsTheBagASiblingStillReferences) { - using ros2_medkit_fault_manager::RosbagFileInfo; - - const auto shared_path = temp_db_path_.string() + "_shared_bag"; - std::filesystem::create_directories(shared_path); - - RosbagFileInfo info; - info.file_path = shared_path; - info.format = "mcap"; - info.duration_sec = 5.0; - info.size_bytes = 100; - info.created_at_ns = 1000; - info.fault_code = "X"; - storage_->store_rosbag_file(info); - info.fault_code = "Y"; - storage_->store_rosbag_file(info); - - info.fault_code = "X"; - info.file_path = shared_path + "_new"; - storage_->store_rosbag_file(info); - - EXPECT_TRUE(std::filesystem::exists(shared_path)) << "the sibling fault still owns the shared bag"; - auto sibling = storage_->get_rosbag_file("Y"); - ASSERT_TRUE(sibling.has_value()); - EXPECT_EQ(sibling->file_path, shared_path); - - std::error_code ec; - std::filesystem::remove_all(shared_path, ec); -} - // Burst-level batch operations (one SQLite transaction per burst). TEST_F(SqliteFaultStorageTest, BulkStoreRegistersEveryFaultOfTheBurst) { @@ -1686,7 +1594,7 @@ TEST_F(SqliteFaultStorageTest, BulkStoreRegistersEveryFaultOfTheBurst) { info.fault_code = code; rows.push_back(info); } - storage_->store_rosbag_files(rows); + seed_rosbag_rows(*storage_, rows); for (const char * code : {"ROOT_CAUSE", "CORRELATED_A", "CORRELATED_B"}) { auto row = storage_->get_rosbag_file(code); @@ -1713,18 +1621,28 @@ TEST_F(SqliteFaultStorageTest, BulkDeleteRemovesTheBurstAndUnlinksTheBagOnce) { info.fault_code = code; rows.push_back(info); } - storage_->store_rosbag_files(rows); + seed_rosbag_rows(*storage_, rows); + RosbagRetention retention(*storage_, RosbagRetentionLimits{}, test_log_sink(), "test_sqlite_storage"); // A partial delete leaves the bag on disk for the remaining fault. - EXPECT_EQ(storage_->delete_rosbag_files({"CORRELATED_A", "CORRELATED_B", "NEVER_STORED"}), 2u); - EXPECT_TRUE(std::filesystem::exists(bag_path)); + size_t codes_deleted = 0; + for (const char * code : {"CORRELATED_A", "CORRELATED_B", "NEVER_STORED"}) { + const auto removal = retention.on_fault_cleared(code); + expect_unlinkable(removal.unlink_paths); + EXPECT_FALSE(listed(removal.unlink_paths, bag_path)) << code; + codes_deleted += removal.removed_rows > 0 ? 1 : 0; + } + EXPECT_EQ(codes_deleted, 2u); EXPECT_TRUE(storage_->get_rosbag_file("ROOT_CAUSE").has_value()); EXPECT_FALSE(storage_->get_rosbag_file("CORRELATED_A").has_value()); // The last reference going away unlinks the directory. - EXPECT_EQ(storage_->delete_rosbag_files({"ROOT_CAUSE"}), 1u); - EXPECT_FALSE(std::filesystem::exists(bag_path)); + const auto root = retention.on_fault_cleared("ROOT_CAUSE"); + expect_unlinkable(root.unlink_paths); + EXPECT_EQ(root.removed_rows, 1u); + EXPECT_EQ(paths_of(root.unlink_paths), std::vector{bag_path}); EXPECT_EQ(storage_->get_total_rosbag_storage_bytes(), 0u); + std::filesystem::remove_all(bag_path); } // =============================================================================