Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions src/ros2_medkit_fault_manager/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down
6 changes: 5 additions & 1 deletion src/ros2_medkit_fault_manager/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand All @@ -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`.
Expand Down
60 changes: 59 additions & 1 deletion src/ros2_medkit_fault_manager/design/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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: <recording_id> (max_bags_per_fault)``;
- a recording of a cleared fault: ``Recording removed: <recording_id> (fault cleared)``;
- a quota eviction: ``Deleted old bag '<path>' 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 '<code>'`` 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.
Original file line number Diff line number Diff line change
@@ -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 <cstddef>
#include <mutex>
#include <string>
#include <unordered_map>
#include <vector>

#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<FreedRecording> unlink_paths;
};

struct RemovalOutcome {
size_t removed_rows{0};
std::vector<FreedRecording> 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<RosbagFileInfo> 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<std::string> 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<FreedRecording> 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<RosbagFileInfo> & rows,
std::unordered_map<std::string, std::string> & 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<RosbagFileInfo> & 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
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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<SnapshotCapture> 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<RetentionWorker> 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<core::RosbagRetention> 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<RosbagCapture> rosbag_capture_;
Expand Down
Loading
Loading