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
50 changes: 44 additions & 6 deletions docs/api/rest.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1968,6 +1968,7 @@ List all bulk-data items in a category for the entity.
"fault_codes": ["MOTOR_OVERHEAT", "MOTOR_STALL"],
"duration_sec": 6.0,
"format": "mcap",
"priority": 900,
"recording_id": "fault_MOTOR_OVERHEAT_1738664999000",
"storage_files": 1
}
Expand All @@ -1978,10 +1979,42 @@ List all bulk-data items in a category for the entity.
For ``rosbags``, the descriptor ``id`` is the recording id - the bag directory
name - and it is what the download URL takes. There is **one descriptor per
recording**, not one per fault: faults confirmed in one burst share a single
recording, and ``x-medkit.fault_codes`` lists every fault attached to it. A
recording therefore reports its size once. One fault code can appear on several
descriptors, one per occurrence it kept, told apart by ``creation_date``, which
is the time that recording was made.
recording, and ``x-medkit.fault_codes`` lists the attached faults this
entity's list includes. A recording therefore reports its size once. One fault
code can appear on several descriptors, one per occurrence it kept, told apart
by ``creation_date``, which is the time that recording was made.

``x-medkit.priority`` is the recording's retention priority: the highest
``priority`` of every fault attached to the recording, also the faults this
entity's list leaves out, from each fault's current severity (see Rosbag
Retention Rules in :doc:`/config/fault-manager`). It is ``0`` when the fault
manager runs without a valid retention configuration. A client that fetches the
most important recordings first sorts by ``priority``, then by
``creation_date``.

**Which entity lists a recording.** An entity lists a recording when one of its
fault sources is exactly a reporting source of one of the recording's faults. A
recording shared by faults of two apps is listed under both, and each list names
its own faults in ``x-medkit.fault_codes``. The fault manager's own App lists
every recording: its source is the fault manager's FQN, ``/fault_manager``, or
``<fault_manager.namespace>/fault_manager``. A Component or Function whose
sources include that FQN, such as the host Component of runtime discovery, lists
every recording too. In runtime discovery the fault manager node is an App like
every other node. In hybrid discovery it is an App no manifest declares, unless
``unmanifested_nodes: ignore`` hides it. In manifest-only discovery it exists
only when the manifest declares it.

**Which entity downloads a recording.** The download route and the
:ref:`manifest and file routes <rest-rosbag-recording-files>` serve a recording
to an entity whose sources include the fault manager's FQN, or when one of the
recording's faults passes the list's rule above or the rule of the entity's
fault route: every reporting source is one of the entity's sources or lies below
one at a ``/`` boundary (``plc`` does not cover ``plc_line1``). So every
recording the list shows and every ``bulk_data_uri`` the entity's faults
advertise downloads, and nothing else: a fault reported by two apps downloads
under both, and a fault reported by a node below the entity and by an outside
app downloads under that node's App and the outside app, not under the entity. A
fault-code URL also needs the requested fault in that scope.

``x-medkit.storage_files`` is how many storage files the recording is held in,
read from the recording's own metadata. A ``1`` is the normal case and says the
Expand Down Expand Up @@ -2319,8 +2352,13 @@ the file, and that answer carries ``Content-Range: bytes */<size>``.

**The listing is complete or refused.** ``GET
/api/v1/{entity-path}/bulk-data/rosbags`` answers ``503`` when the fault manager
cannot be read for any of the sources the entity covers. A ``200`` is a
complete list, so an empty ``items`` means there are no recordings.
cannot be read for any of the sources the entity covers, or for every recording
on the fault manager's own App. A ``200`` is a complete list, so an empty
``items`` means there are no recordings. A recording downloads under an entity,
also through the manifest and file routes, when the entity's sources include the
fault manager's node, which lists and downloads every recording, or when one of
its faults has a reporting source equal to one of the entity's sources, or has
every reporting source at or below the entity's sources at a ``/`` boundary.

Software Updates
----------------
Expand Down
4 changes: 4 additions & 0 deletions docs/config/fault-manager.rst
Original file line number Diff line number Diff line change
Expand Up @@ -864,6 +864,10 @@ quota and logs a warning; ``keep`` also deletes the recordings it was allowed to
the new recording alone and deletes nothing. The log line of a drop names the path, the size, the
quota and the reason.

**The priority in the list.** ``~/list_rosbags`` and the gateway's ``GET .../bulk-data/rosbags``
show each recording's priority (``priorities``, ``x-medkit.priority``): the rank above, read when the
list is served. It is ``0`` without rules and while the configuration is invalid.

**Open-time check.** When a fault whose rule says ``over_quota: drop`` confirms, and the recording
is predicted not to fit, the recording is not started. The prediction is the stored bytes, less what the
per-fault cap frees for that fault and what the fault's priority allows to evict, plus the bytes of
Expand Down
4 changes: 2 additions & 2 deletions docs/requirements/specs/bulkdata.rst
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@ BulkData
The endpoint shall list all bulk-data items available in the addressed bulk-data category on the entity.

Returns BulkDataDescriptor array with id, name, mimetype, size, creation_date fields.
Includes ``x-medkit`` extensions with fault_code, duration_sec, format.
For ``rosbags``, includes ``x-medkit`` extensions with fault_codes, duration_sec, format,
recording_id and priority, the recording's retention priority.

.. req:: GET /{entity}/bulk-data/{category}/{bulk-data-id}
:id: REQ_INTEROP_073
Expand Down Expand Up @@ -54,4 +55,3 @@ BulkData

Returns 204 No Content on success. Supported for components and apps.
The ``rosbags`` category is managed by the fault manager and cannot be deleted.

5 changes: 4 additions & 1 deletion scripts/check_cores_without_ros/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -201,9 +201,12 @@ class NoFaultTransport : public gw::FaultServiceTransport {
gw::FaultResult get_rosbag(const std::string & /*fault_code*/) override {
return none();
}
gw::FaultResult list_rosbags(const std::string & /*entity_fqn*/) override {
gw::FaultResult list_rosbags(const std::string & /*entity_fqn*/, bool /*all_recordings*/) override {
return none();
}
std::string fault_manager_fqn() const override {
return "/fault_manager";
}
bool wait_for_services(std::chrono::duration<double> /*timeout*/) override {
return false;
}
Expand Down
1 change: 1 addition & 0 deletions src/ros2_medkit_fault_manager/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ ros2 service call /fault_manager/clear_fault ros2_medkit_msgs/srv/ClearFault \
| `~/list_faults` | `ros2_medkit_msgs/srv/ListFaults` | Query faults with filtering |
| `~/clear_fault` | `ros2_medkit_msgs/srv/ClearFault` | Clear/acknowledge a fault |
| `~/get_snapshots` | `ros2_medkit_msgs/srv/GetSnapshots` | Get topic snapshots for a fault |
| `~/list_rosbags` | `ros2_medkit_msgs/srv/ListRosbags` | Rosbag rows of the faults an entity reported (`entity_fqn`), or every row with `all_recordings`; each row with its recording's retention priority (`priorities`) |

## Features

Expand Down
2 changes: 2 additions & 0 deletions src/ros2_medkit_fault_manager/design/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -593,6 +593,8 @@ Rosbag retention
ring buffer in place. The size is an estimate: a recording that grows past it in its post-roll is
dropped at the store.
- ``recording_priority``: the priority of a stored recording.
- ``recording_priorities``: the priority of each of several recordings, for ``ListRosbags``. One
read of the rosbag rows and one read per distinct fault code, however many recordings.
- ``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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,11 @@ class RosbagRetention {
/// @throws a storage failure
int64_t recording_priority(const std::string & recording_id);

/// recording_priority() of each of @p recording_ids, keyed by id. One read of the rosbag rows and
/// one read per distinct fault code, however many recordings.
/// @throws a storage failure
std::unordered_map<std::string, int64_t> recording_priorities(const std::vector<std::string> & recording_ids);

/// Whether a new recording for @p fault_code may start. Checked only in kDegraded and for a
/// fault whose rule says over_quota: drop. Refused when the storage, less what the cap and the
/// eviction would free, plus @p reserve_bytes is over the quota. A failed read admits it.
Expand Down
30 changes: 30 additions & 0 deletions src/ros2_medkit_fault_manager/src/core/rosbag_retention.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -511,6 +511,36 @@ int64_t RosbagRetention::recording_priority(const std::string & recording_id) {
return rank_of(*state, codes, cache).priority;
}

std::unordered_map<std::string, int64_t>
RosbagRetention::recording_priorities(const std::vector<std::string> & recording_ids) {
std::unordered_map<std::string, int64_t> priorities;
for (const auto & id : recording_ids) {
priorities.emplace(id, 0);
}
if (priorities.empty()) {
return priorities;
}
std::lock_guard<std::mutex> lock(mutex_);
const auto state = std::atomic_load(&state_);
if (state->mode != RetentionMode::kConfigured) {
return priorities;
}
std::unordered_map<std::string, std::vector<std::string>> codes_by_recording;
for (const auto & row : storage_.get_all_rosbag_files()) {
if (priorities.count(row.recording_id) != 0) {
codes_by_recording[row.recording_id].push_back(row.fault_code);
}
}
FactsCache cache;
for (auto & entry : priorities) {
const auto codes = codes_by_recording.find(entry.first);
if (codes != codes_by_recording.end()) {
entry.second = rank_of(*state, codes->second, cache).priority;
}
}
return priorities;
}

bool RosbagRetention::admits_new_recording(const std::string & fault_code, size_t reserve_bytes,
const std::vector<std::pair<std::string, size_t>> & pending) {
const auto state = std::atomic_load(&state_);
Expand Down
27 changes: 23 additions & 4 deletions src/ros2_medkit_fault_manager/src/fault_manager_node.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1238,18 +1238,23 @@ void FaultManagerNode::handle_get_rosbag(const std::shared_ptr<ros2_medkit_msgs:
void FaultManagerNode::handle_list_rosbags(
const std::shared_ptr<ros2_medkit_msgs::srv::ListRosbags::Request> & request,
const std::shared_ptr<ros2_medkit_msgs::srv::ListRosbags::Response> & response) {
RCLCPP_DEBUG(get_logger(), "ListRosbags request for entity: %s", request->entity_fqn.c_str());
RCLCPP_DEBUG(get_logger(), "ListRosbags request for entity: %s (all recordings: %s)", request->entity_fqn.c_str(),
request->all_recordings ? "true" : "false");

if (request->entity_fqn.empty()) {
if (!request->all_recordings && request->entity_fqn.empty()) {
response->success = false;
response->error_message = "entity_fqn cannot be empty";
return;
}

// Use batch storage API to get all rosbags for this entity
std::vector<RosbagFileInfo> rosbags = {};
try {
rosbags = storage_->list_rosbags_for_entity(request->entity_fqn);
if (request->all_recordings) {
rosbags = storage_->get_all_rosbag_files();
std::reverse(rosbags.begin(), rosbags.end()); // newest first, as the entity listing orders its rows
} else {
rosbags = storage_->list_rosbags_for_entity(request->entity_fqn);
}
} catch (const FaultStorage::IgnorableConnectionException & e) {
RCLCPP_WARN(get_logger(), "Failed to connect with the fault storage server: %s", e.what());
response->success = false;
Expand Down Expand Up @@ -1293,6 +1298,20 @@ void FaultManagerNode::handle_list_rosbags(
response->created_at_ns.push_back(info.created_at_ns);
}

// One retention call for the whole response: a per-recording read costs one storage transaction each.
try {
const auto priorities = rosbag_retention_->recording_priorities(response->recording_ids);
response->priorities.reserve(response->recording_ids.size());
for (const auto & recording_id : response->recording_ids) {
response->priorities.push_back(priorities.at(recording_id));
}
} catch (const std::exception & e) {
RCLCPP_WARN(get_logger(), "Failed to read the rosbag priorities: %s", e.what());
response->success = false;
response->error_message = storage_unavailable(e);
return;
}

response->success = true;
RCLCPP_DEBUG(get_logger(), "ListRosbags returned %zu rosbags for entity '%s'", response->fault_codes.size(),
request->entity_fqn.c_str());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -350,9 +350,10 @@ def get_rosbag(self, code='', recording_id=''):
request.recording_id = recording_id
return self._call(GetRosbag, 'get_rosbag', request)

def list_rosbags(self, entity=SOURCE_ID):
def list_rosbags(self, entity=SOURCE_ID, all_recordings=False):
request = ListRosbags.Request()
request.entity_fqn = entity
request.all_recordings = all_recordings
return self._call(ListRosbags, 'list_rosbags', request)

def _wait_for_subscription_count(self, reached, what):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -971,6 +971,10 @@ def test_degraded_quota_is_a_hard_stop(self):
with self.fm_run(**base, **{'snapshots.rosbag.auto_cleanup': False}) as fm:
self.assertIsNotNone(fm.wait_line(r'Invalid rosbag retention configuration'))
stored = {code: self.record(fm, code, 2) for code in ('DEG_A', 'DEG_B', 'DEG_C')}
listed = self.client.list_rosbags('', all_recordings=True)
self.assertTrue(listed.success, listed.error_message)
self.assertEqual(sorted(listed.fault_codes), ['DEG_A', 'DEG_B', 'DEG_C'])
self.assertEqual(list(listed.priorities), [0] * len(listed.fault_codes))
path, kept = self.record_growing(fm, 'DEG_NEW', 2)
self.assertFalse(kept)
self.assertFalse(os.path.exists(path))
Expand Down
111 changes: 111 additions & 0 deletions src/ros2_medkit_fault_manager/test/test_rosbag_retention.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,54 @@ class FailingPolicyReadStorage : public InMemoryFaultStorage {
bool fail_apply{false};
};

/// Counts every fault and rosbag read the retention can make.
class CountingReadStorage : public InMemoryFaultStorage {
public:
std::optional<fd::FaultRecord> get_fault(const std::string & fault_code) const override {
++reads;
return InMemoryFaultStorage::get_fault(fault_code);
}
bool contains(const std::string & fault_code) const override {
++reads;
return InMemoryFaultStorage::contains(fault_code);
}
std::vector<fd::FaultRecord> list_faults(bool filter_by_severity, uint8_t severity,
const std::vector<std::string> & statuses) const override {
++reads;
return InMemoryFaultStorage::list_faults(filter_by_severity, severity, statuses);
}
std::vector<fd::FaultRecord> get_all_faults() const override {
++reads;
return InMemoryFaultStorage::get_all_faults();
}
std::optional<RosbagFileInfo> get_rosbag_file(const std::string & fault_code) const override {
++reads;
return InMemoryFaultStorage::get_rosbag_file(fault_code);
}
std::vector<RosbagFileInfo> get_rosbag_files(const std::string & fault_code) const override {
++reads;
return InMemoryFaultStorage::get_rosbag_files(fault_code);
}
std::vector<RosbagFileInfo> get_rosbag_files_by_recording(const std::string & recording_id) const override {
++reads;
return InMemoryFaultStorage::get_rosbag_files_by_recording(recording_id);
}
size_t get_total_rosbag_storage_bytes() const override {
++reads;
return InMemoryFaultStorage::get_total_rosbag_storage_bytes();
}
std::vector<RosbagFileInfo> get_all_rosbag_files() const override {
++reads;
return InMemoryFaultStorage::get_all_rosbag_files();
}
std::vector<RosbagFileInfo> list_rosbags_for_entity(const std::string & entity_fqn) const override {
++reads;
return InMemoryFaultStorage::list_rosbags_for_entity(entity_fqn);
}

mutable size_t reads = 0;
};

/// Keeps every line it is given.
class CapturingLogSink : public ros2_medkit_fault_manager::core::LogSink {
public:
Expand Down Expand Up @@ -580,4 +628,67 @@ TEST_F(RosbagRetentionStore, PolicyReadFailureFallsBackToInsertAndCap) {
}
}

TEST(RosbagRetention, RecordingPrioritiesReadsDoNotGrowWithRecordings) {
// The read count is not observable outside the process: one list call must not cost one
// storage transaction per recording.
ros2_medkit_fault_manager::core::FlatParams params;
params["defaults.priority"] = int64_t{10};
params["severity.ERROR.priority"] = int64_t{50};
params["severity.CRITICAL.priority"] = int64_t{900};
auto parsed = RetentionPolicy::parse(params);
ASSERT_TRUE(parsed.errors.empty());
const auto policy = std::make_shared<const RetentionPolicy>(std::move(*parsed.policy));
const std::vector<std::pair<std::string, uint8_t>> faults = {
{"F_WARN", fd::severity::kWarn}, {"F_ERROR", fd::severity::kError}, {"F_CRITICAL", fd::severity::kCritical}};

// Every fault code is linked in both runs: recording 0 links all of them, the others one each.
const auto reads_for = [&](size_t recordings) {
CountingReadStorage storage;
for (const auto & fault : faults) {
storage.report_fault_event(fault.first, fd::ReportKind::kFailed, fault.second, "reads", "/node", 1000,
DebounceConfig{});
}
std::vector<RosbagFileInfo> rows;
std::vector<std::string> ids;
for (size_t i = 0; i < recordings; ++i) {
const std::string id = "fault_rec_" + std::to_string(i);
ids.push_back(id);
for (size_t f = 0; f < faults.size(); ++f) {
if (i == 0 || i % faults.size() == f) {
RosbagFileInfo row;
row.fault_code = faults[f].first;
row.file_path = "/bags/" + id;
row.recording_id = id;
row.format = "mcap";
row.size_bytes = 1024;
row.created_at_ns = static_cast<int64_t>(1000 + i);
rows.push_back(row);
}
}
}
seed_rosbag_rows(storage, rows);
RosbagRetention retention(storage, RosbagRetentionLimits{}, test_log_sink(), kLogger);
retention.set_policy(RetentionMode::kConfigured, policy);

storage.reads = 0;
const auto priorities = retention.recording_priorities(ids);
const size_t reads = storage.reads;

EXPECT_EQ(priorities.size(), ids.size());
for (const auto & id : ids) {
const auto found = priorities.find(id);
EXPECT_NE(found, priorities.end()) << id;
if (found != priorities.end()) {
EXPECT_EQ(found->second, retention.recording_priority(id)) << id;
}
}
return reads;
};

const size_t one = reads_for(1);
const size_t fifty = reads_for(50);
EXPECT_EQ(one, fifty) << "reads grow with the number of recordings";
EXPECT_GT(one, 0u);
}

} // namespace
10 changes: 10 additions & 0 deletions src/ros2_medkit_gateway/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1223,6 +1223,16 @@ download serves one storage file, verbatim, named `<recording_id>.<format>`
(`.mcap` or `.sqlite3`). It is not an archive and it does not include the bag's
`metadata.yaml`.

Each descriptor carries `x-medkit.priority`, the recording's retention priority:
the highest priority of every fault attached to it, from each fault's current
severity, and `0` without a valid retention configuration. A client sorts by
`priority`, then by `creation_date`. The fault manager's own App, and an entity
that hosts it, lists every recording. A recording downloads under an entity whose
sources include the fault manager's node, or when one of its faults has a
reporting source equal to one of the entity's sources (the list's rule) or has
every reporting source at or below the entity's sources at a `/` boundary (the
rule of the entity's fault route, which advertises the URL).

For a recording held in a single storage file, which is the normal case, the
descriptor `size` is that file's length and therefore the length of the
download. A recording that grew past `snapshots.rosbag.max_bag_size_mb` is split
Expand Down
Loading
Loading