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
39 changes: 35 additions & 4 deletions docs/config/fault-manager.rst
Original file line number Diff line number Diff line change
Expand Up @@ -840,8 +840,39 @@ Fields:
- ``keep`` (default) or ``drop``
- What happens to a new recording that cannot fit the storage quota.

These two fields are parsed and checked in this release. The rules do not change which recordings
are removed yet.
**What the rules do.** A new recording evicts only recordings whose priority is less than or equal to
its own, and evicts them in this order: lowest ``priority`` first, then the recordings whose faults are
all cleared, then healed, then active (any fault PREFAILED, PREPASSED or CONFIRMED), then the oldest. A
recording shared by several faults (a burst) ranks by its highest-priority fault, with each fault's
severity as it is stored now, so a fault that was reported again at a higher severity moves its
recordings up. The ranking reads the links as they are after the new recording and the per-fault cap
are applied. The quota is enforced when a new recording is stored: if the per-fault cap removes every
new row (possible only when the new recording is older than the stored ones, after a backward clock
step), nothing is evicted in that store.

A new recording that does not fit after every allowed eviction follows ``over_quota`` of its
highest-priority fault (``keep`` when faults of equal priority disagree). ``keep`` stores it over the
quota and logs a warning; ``keep`` also deletes the recordings it was allowed to evict. ``drop`` drops
the new recording alone and deletes nothing. The log line of a drop names the path, the size, the
quota and the reason.

**Open-time check.** When a fault whose rule says ``over_quota: drop`` confirms, and the recording
is predicted not to fit, the recording is not started. The prediction is the stored bytes, less what the
per-fault cap frees for that fault and what the fault's priority allows to evict, plus the bytes of
recordings that are closed but not stored yet, plus the buffered bytes times
``1 + duration_after_sec / duration_sec``. The term for recordings not stored yet is an estimate of their payload (container and metadata overhead
are not included), counted only while no stored row names them; the store still decides with the
measured size. A refused fault logs one INFO line and leaves
the ring buffer in place for the next fault. The prediction is an estimate: a recording that grows past
it in its post-fault window is dropped when it is stored.

**Invalid configuration.** While the retention configuration is invalid, the quota is a hard stop for
new recordings: a recording that does not fit after the per-fault cap is dropped, and nothing is
evicted for the quota. The open-time check runs for every fault. The per-fault cap and the removal of
a cleared fault's recording (``auto_cleanup``) work as without rules.

A failed attempt to open a recording keeps the ring buffer, so the next fault within ``duration_sec``
still gets its history.

**Resolution.** Each field of a fault's rule comes from the first level that sets it: its
``fault_codes.<CODE>`` entry, then the first label of ``pattern_order`` whose ``match`` covers the
Expand Down Expand Up @@ -881,8 +912,8 @@ empty list (``pattern_order: []``, leave the key out) fails while the node is bu
logs "Fault manager did not start" and exits with code 1. An empty key segment (``fault_codes..priority``
through ``-p``, or an empty YAML key) aborts inside ROS initialisation, before the fault manager runs.

Any other error does not stop the fault manager. It keeps running, records as before, does not use
the rules and reports the fault ``ROSBAG_RETENTION_CONFIG_INVALID`` (severity ``CRITICAL``, source the
Any other error does not stop the fault manager. It keeps running, does not use the rules (the quota
is then a hard stop for new recordings, see above) and reports the fault ``ROSBAG_RETENTION_CONFIG_INVALID`` (severity ``CRITICAL``, source the
fault manager node, description the errors). That fault starts no capture. Clearing it does not fix
the configuration: the next fault that confirms reports it again. A start with a valid configuration
(or none) clears it. If the fault storage is unreachable at start, the report or the clear is retried
Expand Down
13 changes: 9 additions & 4 deletions src/ros2_medkit_fault_manager/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -135,9 +135,14 @@ parameter list and recording lifecycle.

`snapshots.rosbag.retention.*` sets a `priority` (0-1000) and an `over_quota` choice (`keep` or `drop`)
per fault, from four levels: fault code, the first matching pattern of `pattern_order`, severity, defaults.
They are read at startup and validated; this release does not yet use them to choose which recordings go.
They are read at startup and validated. A new recording evicts only recordings of equal or lower priority,
lowest priority first, then cleared before healed before active, then oldest. A recording that still does not
fit follows `over_quota`: `keep` (default) stores it over the quota, `drop` drops it and deletes nothing.
A recording that is predicted not to fit is not started when its fault says `drop` (the ring buffer stays for
the next fault). With an invalid configuration the quota is a hard stop for new recordings and nothing is
evicted for it. Without any retention parameter the quota evicts the oldest recordings first.
A parameter the ROS YAML loader moved (found by reading each parameters file a second time) or that has too many key segments stops the node with exit code 1. Any other error keeps the node
recording as before and reports the fault `ROSBAG_RETENTION_CONFIG_INVALID`. See
running without the rules, with the quota as a hard stop for new recordings, and reports the fault `ROSBAG_RETENTION_CONFIG_INVALID`. See
`config/rosbag_retention.example.yaml` and `docs/config/fault-manager.rst`.

### Storage Backends
Expand Down Expand Up @@ -583,8 +588,8 @@ and some of them build an `rclcpp::Clock`.
`core::reclassify_stale_healed()` is the startup pass for stale HEALED rows;
- `core::FaultManagerCore`: `report`, `clear`, `list`, `get`, `list_for_entity`, `record_transition`
and `tick`. These calls run under one internal mutex.
- `core::RosbagRetention`: every rosbag retention decision (the per-fault cap, the storage quota,
the clear and the stale-row cleanup) on top of `FaultStorage::apply_rosbag_changes`. It returns
- `core::RosbagRetention`: every rosbag retention decision (the per-fault cap, the storage quota with
the retention rules, the open-time quota check, the clear and the stale-row cleanup) on top of `FaultStorage::apply_rosbag_changes`. It returns
the directories to remove and never removes one itself.

The core reaches the outside through four interfaces. The ROS adapter implements them.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,12 @@
# fault_codes.<CODE>, then the first label of pattern_order whose match covers the whole
# fault code, then severity.<SEVERITY> of the fault, then defaults, then the built-in value.
# Fields: priority (integer 0-1000, built-in 0) and over_quota (keep or drop, built-in keep).
# Any other key under retention is an error: the fault manager keeps running, records as before
# and reports the fault ROSBAG_RETENTION_CONFIG_INVALID. Retention values are read-only at runtime.
# A new recording evicts only recordings of equal or lower priority: lowest priority first, then
# cleared, healed, active, then oldest. If it still does not fit, keep stores it over the quota and
# drop discards it alone. With drop, a recording predicted not to fit is not started.
# Any other key under retention is an error: the fault manager keeps running without the rules, the
# quota becomes a hard stop for new recordings (nothing is evicted for it) and it reports the fault
# ROSBAG_RETENTION_CONFIG_INVALID. Retention values are read-only at runtime.
#
# Use with: ros2 run ros2_medkit_fault_manager fault_manager_node --ros-args --params-file <this file>
# The rules are read only when snapshots.rosbag.enabled is true.
Expand Down
45 changes: 43 additions & 2 deletions src/ros2_medkit_fault_manager/design/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -563,7 +563,31 @@ Rosbag retention
``max_bags_per_fault`` of 1), applies the per-fault cap in the same change set as the insert,
then the quota. One hold covers all three, so a clear finds the store either before its check
or after its quota step. A new row that loses the cap is not inserted, and its directory is
removed like any other the cap frees.
removed like any other the cap frees. Without rules (``RetentionMode::kUnconfigured``) the quota
evicts the oldest recordings first. With rules (``kConfigured``) the store decides everything
before it applies anything: it predicts the total after the insert and the cap (the sum per path
of the largest row, the storage's own rule), picks the recordings the new one may evict, and
applies the insert, the cap and the evictions only when it fits. A recording that does not fit
after every allowed eviction follows ``over_quota``: ``keep`` stores it over the limit,
``drop`` returns ``kDroppedOverQuota`` with nothing applied and the caller removes the bag.
The quota is enforced when a new recording is stored: if the per-fault cap removes every new
row (only when the new recording is older than the stored ones, after a backward clock step),
nothing is evicted in that store.
In degrade (``kDegraded``) there is no eviction for the quota: a new recording that does not
fit after the cap is dropped. A path the storage already holds (an upserted link) is never
dropped.
- ``admits_new_recording``: the open-time check. ``RosbagCapture`` asks it where a new recording
is about to start, before the ring buffer is flushed. It runs in degrade and for a fault whose
rule says ``over_quota: drop``. It refuses when the stored bytes, less what the cap frees for the
fault and what the fault's rank may evict, plus the payload bytes of recordings that are closed
but not stored yet (kept in memory by ``RosbagCapture``, so no file system walk) and the
estimated size of the recording (the buffered bytes times ``1 + duration_after_sec /
duration_sec``), exceed the quota. The pending term is an estimate of the payload without container
and metadata overhead, and the retention counts a pending recording only while no stored row
names its path. The store still decides with the measured size. A refusal leaves the
ring buffer in place. The size is an estimate: a recording that grows past it in its post-roll is
dropped at the store.
- ``recording_priority``: the priority of a stored recording.
- ``on_fault_cleared``: removes every row of a cleared fault. ``RosbagCapture`` decides whether a
clear removes recordings at all.
- ``forget_recording``: removes the rows of a recording whose directory is gone, for
Expand Down Expand Up @@ -593,7 +617,24 @@ re-reports. When the re-read of a FAILED report fails the core calls ``on_confir
reads that fault's status first. A successful clear of the own fault, or of a root cause that auto-clears it,
drops both. The timer is created cancelled and runs on the
executor thread only while something is pending: the flag, or the startup report or clear that the core
has not accepted yet. Nothing reads the policy yet.
has not accepted yet.

The node publishes the mode and the policy once, with ``RosbagRetention::set_policy``, after it builds
the retention and before capture starts. Each decision loads that snapshot once with ``std::atomic_load``
and uses it throughout.

The rank of a recording is read from the rows as they will be after the insert and the cap:

- priority: the highest ``priority`` of the faults it links, each resolved with the fault's severity as
stored now. A link whose fault the storage does not hold counts as severity INFO and cleared;
- ``over_quota``: that of its highest-priority fault, ``keep`` when faults of equal priority disagree;
- status: active when any linked fault is PREFAILED, PREPASSED or CONFIRMED, else healed when any is
HEALED, else cleared.

The eviction order is priority ascending, then cleared, healed, active, then oldest first. The
candidates are every stored recording except the new one and the paths the cap removes in the same
store, limited to a priority less than or equal to the new recording's. A read that only the rank
needs and that fails makes the store fall back to the insert and the cap alone, with ``quota_failed``.

Lock order: the caller's outer locks (the node's rosbag mutex on the inline store path, the core
mutex on the clear path), then the retention mutex, then the storage's own lock. Under the
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,16 @@
#pragma once

#include <cstddef>
#include <cstdint>
#include <memory>
#include <mutex>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>

#include "ros2_medkit_fault_manager/core/log_sink.hpp"
#include "ros2_medkit_fault_manager/core/retention_policy.hpp"
#include "ros2_medkit_fault_manager/fault_storage.hpp"

namespace ros2_medkit_fault_manager::core {
Expand All @@ -32,6 +36,19 @@ struct RosbagRetentionLimits {
bool auto_cleanup{true}; ///< A cleared fault loses its recordings
};

/// How the quota treats a new recording.
enum class RetentionMode {
kUnconfigured, ///< No rules: the oldest recordings go first
kConfigured, ///< The rules rank the recordings
kDegraded, ///< The rules are invalid: the quota is a hard stop for new recordings, nothing is evicted for it
};

/// One immutable snapshot of the rules. Every decision loads it once.
struct RetentionPolicyState {
RetentionMode mode{RetentionMode::kUnconfigured};
std::shared_ptr<const RetentionPolicy> policy; ///< Null unless kConfigured
};

/// Why a recording's directory is no longer named by any row.
enum class RemovalReason {
kCap, ///< The per-fault cap (max_bags_per_fault)
Expand All @@ -51,10 +68,20 @@ enum class StoreResult {
kStored, ///< The rows were applied. Also when the cap removed every new row.
kAllFaultsCleared, ///< Every fault of the recording is cleared. Nothing was stored.
kStoreFailed, ///< The cap read or the insert failed. Nothing was stored.
kDroppedOverQuota, ///< The recording does not fit the quota. Nothing was stored; the caller removes the bag.
};

struct StoreOutcome {
enum class DropReason {
kNone,
kOverQuotaDrop, ///< over_quota: drop of the recording's rule
kDegradedQuota, ///< Invalid configuration: the quota is a hard stop
};

StoreResult result{StoreResult::kStored};
DropReason drop_reason{DropReason::kNone};
size_t recording_bytes{0}; ///< Set with kDroppedOverQuota: size of the dropped recording
size_t limit_bytes{0}; ///< Set with kDroppedOverQuota: the quota
/// The quota read or an eviction threw. The rows stay stored, and so do the evictions before it.
bool quota_failed{false};
std::string error; ///< Exception text of the store failure or of the quota failure
Expand Down Expand Up @@ -84,8 +111,26 @@ class RosbagRetention {
RosbagRetention & operator=(RosbagRetention &&) = delete;
~RosbagRetention() = default;

/// Publish the rules. @p policy is null unless @p mode is kConfigured. Safe to call while
/// decisions run: each decision uses the snapshot it loaded.
void set_policy(RetentionMode mode, std::shared_ptr<const RetentionPolicy> policy);

/// Priority of a stored recording: the highest priority of the faults it is linked to, 0
/// unless kConfigured.
/// @throws a storage failure
int64_t recording_priority(const std::string & recording_id);

/// Whether a new recording for @p fault_code may start. Checked only in kDegraded and for a
/// fault whose rule says over_quota: drop. Refused when the storage, less what the cap and the
/// eviction would free, plus @p reserve_bytes is over the quota. A failed read admits it.
/// @p pending lists recordings closed but not stored yet (path, estimated bytes). Each counts only
/// while no stored row names its path, which is known only under the mutex.
bool admits_new_recording(const std::string & fault_code, size_t reserve_bytes,
const std::vector<std::pair<std::string, size_t>> & pending = {});

/// Store the rows of one recording. In one hold of the mutex: drop the rows of faults the
/// storage holds as cleared, apply the per-fault cap together with the insert, then the quota.
/// With rules the quota evicts by priority and may drop the new recording instead.
/// Precondition: no stored row names the recording's path, except links that @p rows upsert.
/// Precondition: every row carries `recording_id == rosbag_recording_id(file_path)`, not empty.
/// Never throws.
Expand All @@ -110,6 +155,36 @@ class RosbagRetention {
std::vector<FreedRecording> unlink_paths;
};

struct FaultFacts;
struct RecordingRank;
struct QuotaDecision;
using FactsCache = std::unordered_map<std::string, FaultFacts>;

/// The store without rules: quota eviction oldest first.
StoreOutcome store_oldest_first(const std::vector<RosbagFileInfo> & rows);

/// The store with rules (kConfigured) or in degrade (kDegraded).
StoreOutcome store_ranked(const std::vector<RosbagFileInfo> & rows, const RetentionPolicyState & state);

/// What the quota does with a new recording, decided before anything is applied.
/// @throws a failure of a read the decision needs
QuotaDecision decide_quota(const std::vector<RosbagFileInfo> & rows, const RosbagChangeSet & changes,
const RetentionPolicyState & state);

/// Apply @p changes of a store. Lists the directories no row names any more in @p outcome.
/// False, with kStoreFailed in @p outcome, when the apply throws.
bool apply_store(const std::vector<RosbagFileInfo> & rows, const RosbagChangeSet & changes,
const std::unordered_map<std::string, std::string> & recording_ids, StoreOutcome & outcome);

/// Severity, rule and status of a fault as the storage holds it now. A fault the storage does
/// not hold counts as cleared with severity INFO.
/// @throws a storage failure
FaultFacts fault_facts(const RetentionPolicyState & state, const std::string & fault_code, FactsCache & cache);

/// The rank of a recording from the faults its rows link.
RecordingRank rank_of(const RetentionPolicyState & state, const std::vector<std::string> & fault_codes,
FactsCache & cache);

/// Whether a fault keeps its row: false only under auto_cleanup with a cap of exactly 1, for a
/// fault the storage holds as cleared. A fault that cannot be read keeps its row.
bool row_still_wanted(const std::string & fault_code);
Expand All @@ -132,6 +207,7 @@ class RosbagRetention {
const RosbagRetentionLimits limits_;
LogSink & log_sink_;
const std::string logger_name_;
std::shared_ptr<const RetentionPolicyState> state_; ///< Only through std::atomic_load / std::atomic_store
std::mutex mutex_;
};

Expand Down
Loading
Loading