From 97fc47333e9c1065f65eab4a3da7c7809ad11b03 Mon Sep 17 00:00:00 2001 From: Bartosz Burda Date: Tue, 1 Dec 2026 14:41:05 +0100 Subject: [PATCH] fault_manager: max_bags and keep_first per rosbag retention rule * feat(fault_manager): max_bags and keep_first per rosbag retention rule * fix(fault_manager): one warning per unreadable fault * fix(fault_manager): one line for an unreadable fault over the quota; cooldown warning counts rule caps --- docs/config/fault-manager.rst | 60 ++- docs/tutorials/snapshots.rst | 18 +- src/ros2_medkit_fault_manager/CMakeLists.txt | 4 + src/ros2_medkit_fault_manager/README.md | 15 +- .../config/rosbag_retention.example.yaml | 17 +- .../config/snapshots.yaml | 6 +- .../design/index.rst | 35 +- .../core/retention_policy.hpp | 12 +- .../core/rosbag_retention.hpp | 54 ++- .../retention_worker.hpp | 2 +- .../rosbag_capture.hpp | 12 - .../src/core/retention_policy.cpp | 74 +++- .../src/core/rosbag_retention.cpp | 247 +++++++++--- .../src/fault_manager_node.cpp | 8 + .../src/retention_worker.cpp | 2 +- .../src/rosbag_capture.cpp | 15 +- .../test/integration/rosbag_fm_harness.py | 47 +++ .../integration/test_retention_config.test.py | 13 +- .../integration/test_rosbag_max_bags.test.py | 350 ++++++++++++++++++ .../integration/test_rosbag_quota.test.py | 3 +- .../integration/test_rosbag_quota_pg.test.py | 3 + .../test/test_retention_policy.cpp | 62 +++- .../test/test_rosbag_retention.cpp | 33 ++ 23 files changed, 952 insertions(+), 140 deletions(-) create mode 100644 src/ros2_medkit_fault_manager/test/integration/test_rosbag_max_bags.test.py diff --git a/docs/config/fault-manager.rst b/docs/config/fault-manager.rst index 5534e5c8c..a976a73ea 100644 --- a/docs/config/fault-manager.rst +++ b/docs/config/fault-manager.rst @@ -655,14 +655,16 @@ Capture continuous rosbag recordings around fault events. unlinked, so the default reproduces the historical behaviour exactly: a new recording replaces the previous one. ``0`` means unlimited, bounded only by ``max_total_storage_mb``. ``3`` is a reasonable value for a fault - that flaps - see the note below before raising it. + that flaps - see the note below before raising it. A retention rule's + ``max_bags`` replaces it for the fault codes the rule covers (see Rosbag + Retention Rules below). * - ``rosbag.auto_cleanup`` - ``true`` - Delete a fault's bags when the fault is cleared. A recording shared by a - burst survives until the last fault referencing it clears. Has no effect - once ``max_bags_per_fault`` is anything other than ``1``: a history someone - configured must not be what an acknowledgement takes away, so the cap - governs retention there instead. + burst survives until the last fault referencing it clears. Deletes only + for a fault whose cap is exactly ``1`` (its rule's ``max_bags``, else + ``max_bags_per_fault``): a history someone configured must not be what + an acknowledgement takes away, so the cap governs retention there instead. .. note:: @@ -683,7 +685,9 @@ Capture continuous rosbag recordings around fault events. a fault that returns sooner than the cooldown keeps ONE recording however high this cap is. That is the fast-flapping fault the cap exists for, so lower the cooldown when you raise the cap. The fault manager logs a warning at startup - when the two are configured against each other. + when the two are configured against each other: a cooldown above 0 with + ``max_bags_per_fault`` or, with a valid retention configuration, a rule's + ``max_bags`` other than 1 (the line names one such rule). .. _rosbag-recording-lifecycle: @@ -784,8 +788,9 @@ arrival prunes the whole buffer by age. Rosbag Retention Rules ~~~~~~~~~~~~~~~~~~~~~~ -The parameters under ``snapshots.rosbag.retention.`` set a rule per fault: a ``priority`` and an -``over_quota`` choice. They are read at startup, validated and logged. They are read only while +The parameters under ``snapshots.rosbag.retention.`` set a rule per fault: a ``priority``, an +``over_quota`` choice, a ``max_bags`` cap and ``keep_first``. They are read at startup, validated and +logged. They are read only while rosbag capture is on (``snapshots.rosbag.enabled: true``); with it off, the fault manager warns once and ignores them. Without any ``snapshots.rosbag.retention.*`` parameter the fault manager behaves as before. An example file is ``config/rosbag_retention.example.yaml``. @@ -805,6 +810,8 @@ before. An example file is ``config/rosbag_retention.example.yaml``. fault_codes: MOTOR-STALL: priority: 900 + max_bags: 5 + keep_first: true patterns: gnss_fix: match: 'GNSS\.FIX_LOST' @@ -847,10 +854,34 @@ Fields: * - ``over_quota`` - ``keep`` (default) or ``drop`` - What happens to a new recording that cannot fit the storage quota. + * - ``max_bags`` + - integer ``0`` or more, default ``rosbag.max_bags_per_fault`` + - Recordings kept per fault code. ``0`` means no cap, only the quota applies. + * - ``keep_first`` + - ``true`` or ``false`` (default) + - With a ``max_bags`` of 2 or more, keep the first recording plus the ``max_bags - 1`` newest. + Ignored with a warning when ``max_bags`` is below 2. + +**The cap per fault code.** When a recording is stored, each of its fault codes keeps at most its rule's +``max_bags`` recordings, resolved with the fault's severity as it is stored now. Over the cap the +oldest recording of the code is removed. With ``keep_first`` and a ``max_bags`` of 2 or more the first +recording is never removed by the cap: the code keeps it plus the ``max_bags - 1`` newest, and the +second oldest goes. "First" is the oldest recording of the fault code still stored: once the quota has +removed it, the next oldest is first. ``keep_first`` with a ``max_bags`` of 0 or 1 is ignored, and each +store of that fault code logs a warning. A fault that cannot be read when a recording is stored keeps +all its recordings in that store, with a warning; the next store decides again. A fault that is +reported again at a higher severity takes the cap of the higher severity. + +**The clear.** With ``rosbag.auto_cleanup: true`` a clear deletes the fault's recordings only when its +``max_bags`` is 1. ``max_bags: 3`` on a rule keeps the history of that fault also when +``max_bags_per_fault`` is 1, and ``max_bags: 1`` deletes it also when ``max_bags_per_fault`` is 3. **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 +all cleared, then healed, then active (any fault PREFAILED, PREPASSED or CONFIRMED); inside one +priority and status, a recording that ``keep_first`` protects goes after the others; then the oldest. +A recording is protected when it is the first recording of at least one of its fault codes whose rule +has ``keep_first`` with a ``max_bags`` of 2 or more. Priority and status still go before protection. 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 @@ -870,7 +901,8 @@ 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 +per-fault cap frees for that fault (with that fault code's ``max_bags`` and ``keep_first``; the codes +that join the recording later are not known yet) 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 @@ -881,7 +913,8 @@ 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 cleared fault's recording (``auto_cleanup``) work as without rules, with ``max_bags_per_fault`` for +every fault code. A failed attempt to open a recording keeps the ring buffer, so the next fault within ``duration_sec`` still gets its history. @@ -912,8 +945,9 @@ A file the fault manager cannot read is reported with a warning and skipped. **Errors.** The fault manager reports every error it finds: -- a value of the wrong type (``priority: 5.0`` is a double, not an integer), ``priority`` outside 0-1000, - ``over_quota`` other than ``keep`` or ``drop``; +- a value of the wrong type (``priority: 5.0`` is a double, not an integer, ``max_bags: "3"`` is a + string, ``keep_first: "yes"`` is a string, not a boolean), ``priority`` outside 0-1000, ``max_bags`` + below 0, ``over_quota`` other than ``keep`` or ``drop``; - an unknown severity name, an unknown field or an unknown key under the prefix; - ``match`` outside ``patterns``, a pattern without ``match``, a ``match`` that is not a valid regular expression; - a pattern missing from ``pattern_order``, a label in ``pattern_order`` that names no pattern, or twice. diff --git a/docs/tutorials/snapshots.rst b/docs/tutorials/snapshots.rst index 4747e8552..e09bafe62 100644 --- a/docs/tutorials/snapshots.rst +++ b/docs/tutorials/snapshots.rst @@ -55,8 +55,9 @@ configuration always overrides the zero-config fallback when present. across all of it, and only those. The rosbag recording is not covered by that setting. A clear deletes the recording under ``snapshots.rosbag.auto_cleanup``, unless that is off or - ``snapshots.rosbag.max_bags_per_fault`` keeps a history. The cap then governs - retention, except at ``0`` (unlimited), where only + ``snapshots.rosbag.max_bags_per_fault`` keeps a history. A retention rule's + ``max_bags`` replaces ``max_bags_per_fault`` for the faults it covers. The cap + then governs retention, except at ``0`` (unlimited), where only ``snapshots.rosbag.max_total_storage_mb`` bounds it. Quick Start @@ -505,7 +506,8 @@ style recording. This continuously buffers messages in memory and flushes them to a bag file when a fault is confirmed. The recording is deleted when the fault is cleared, unless ``snapshots.rosbag.auto_cleanup`` is off or ``snapshots.rosbag.max_bags_per_fault`` keeps a history, which takes over the -retention decision. +retention decision. A retention rule's ``max_bags`` replaces +``max_bags_per_fault`` for the faults it covers. **Key differences from JSON snapshots:** @@ -646,9 +648,10 @@ Rosbag Configuration Options - Automatically delete a fault's bag when it is cleared. A recording shared by a burst of faults is deleted when the last fault referencing it clears. Set to ``false`` to retain bags for manual analysis. Has no - effect once ``max_bags_per_fault`` is anything other than ``1``: a - history someone configured must not be what an acknowledgement takes - away, so the cap governs retention there instead. + effect for a fault whose cap is anything other than ``1`` (its retention + rule's ``max_bags``, else ``max_bags_per_fault``): a history someone + configured must not be what an acknowledgement takes away, so the cap + governs retention there instead. * - ``snapshots.rosbag.lazy_start`` - ``false`` - Controls when the ring buffer starts recording. See diagram below. @@ -675,7 +678,8 @@ Rosbag Configuration Options chasing. This is a fairness knob rather than a depth knob: ``max_total_storage_mb`` is the real disk bound, and a high value lets one flapping fault consume the budget and evict every other fault's - recording. + recording. A retention rule's ``max_bags`` replaces it for the faults + the rule covers. Bursts and the Window Boundary ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/src/ros2_medkit_fault_manager/CMakeLists.txt b/src/ros2_medkit_fault_manager/CMakeLists.txt index 9adc62548..dae901663 100644 --- a/src/ros2_medkit_fault_manager/CMakeLists.txt +++ b/src/ros2_medkit_fault_manager/CMakeLists.txt @@ -295,6 +295,10 @@ endif() medkit_add_launch_test(test_rosbag_quota test/integration/test_rosbag_quota.test.py TIMEOUT 600 LABELS "integration") + # max_bags and keep_first per retention rule: the cap, the clear and the eviction order. + medkit_add_launch_test(test_rosbag_max_bags test/integration/test_rosbag_max_bags.test.py TIMEOUT 600 + LABELS "integration") + if(POSTGRES_SUPPORT) medkit_add_launch_test(test_rosbag_quota_pg test/integration/test_rosbag_quota_pg.test.py TIMEOUT 300 LABELS "integration") diff --git a/src/ros2_medkit_fault_manager/README.md b/src/ros2_medkit_fault_manager/README.md index 0a87df8da..f426c7653 100644 --- a/src/ros2_medkit_fault_manager/README.md +++ b/src/ros2_medkit_fault_manager/README.md @@ -134,11 +134,16 @@ parameter list and recording lifecycle. #### Rosbag Retention Rules -`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. 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. +`snapshots.rosbag.retention.*` sets a `priority` (0-1000), an `over_quota` choice (`keep` or `drop`), a +`max_bags` cap and `keep_first` per fault, from four levels: fault code, the first matching pattern of +`pattern_order`, severity, defaults. They are read at startup and validated. Each fault code keeps at most its +rule's `max_bags` recordings (`max_bags_per_fault` when no level sets it, `0` = no cap); with `keep_first` and a +`max_bags` of 2 or more the first recording stays and the second oldest goes. "First" is the oldest recording of +the fault code still stored. With `auto_cleanup`, a clear deletes a fault's recordings only when its `max_bags` +is 1. A new recording evicts only recordings of equal or lower priority, lowest priority first, then cleared +before healed before active, then a recording `keep_first` protects after the others, 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. diff --git a/src/ros2_medkit_fault_manager/config/rosbag_retention.example.yaml b/src/ros2_medkit_fault_manager/config/rosbag_retention.example.yaml index 73776b54f..299413bfd 100644 --- a/src/ros2_medkit_fault_manager/config/rosbag_retention.example.yaml +++ b/src/ros2_medkit_fault_manager/config/rosbag_retention.example.yaml @@ -3,10 +3,18 @@ # A field of a fault's rule comes from the first level that sets it: # fault_codes., then the first label of pattern_order whose match covers the whole # fault code, then severity. of the fault, then defaults, then the built-in value. -# Fields: priority (integer 0-1000, built-in 0) and over_quota (keep or drop, built-in keep). +# Fields: priority (integer 0-1000, built-in 0), over_quota (keep or drop, built-in keep), +# max_bags (integer 0 or more, built-in snapshots.rosbag.max_bags_per_fault) and keep_first (true or +# false, built-in false). +# max_bags is the number of recordings kept per fault code, 0 = no cap. Over the cap the oldest +# recording goes; with keep_first and a max_bags of 2 or more the first recording stays and the +# second oldest goes. "First" is the oldest recording of the fault code still stored. keep_first +# with a max_bags below 2 is ignored with a warning. A clear deletes the fault's recordings when +# snapshots.rosbag.auto_cleanup is true and its max_bags is 1. # 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. +# cleared, healed, active; inside that, a recording kept by keep_first after the others, then +# oldest first. 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. @@ -28,10 +36,13 @@ fault_manager: CRITICAL: priority: 100 over_quota: keep + max_bags: 5 fault_codes: # A fault code has no dot here. Hyphens are allowed. MOTOR-STALL: priority: 900 + max_bags: 10 + keep_first: true DEBUG_NOISE: priority: 0 over_quota: drop diff --git a/src/ros2_medkit_fault_manager/config/snapshots.yaml b/src/ros2_medkit_fault_manager/config/snapshots.yaml index 2eba501c9..701e2ac0e 100644 --- a/src/ros2_medkit_fault_manager/config/snapshots.yaml +++ b/src/ros2_medkit_fault_manager/config/snapshots.yaml @@ -180,6 +180,7 @@ rosbag: # Think of this as fairness rather than depth: the disk is bounded by # max_total_storage_mb either way, and a high value lets one flapping fault consume # the budget and evict every other fault's recording. + # A retention rule's max_bags (snapshots.rosbag.retention) replaces it for its faults. max_bags_per_fault: 1 # Maximum in-memory ring buffer size in MB (default: 256) @@ -195,8 +196,9 @@ rosbag: # Auto-cleanup bag files when fault is cleared (default: true) # When true, bag files are deleted when ClearFault is called # When false, bag files persist until manually deleted or storage limit hit - # No effect once max_bags_per_fault is anything other than 1: a configured - # history governs retention instead, and an acknowledgement leaves it alone + # No effect for a fault whose cap is anything other than 1 (its retention rule's + # max_bags, else max_bags_per_fault): a configured history governs retention + # instead, and an acknowledgement leaves it alone auto_cleanup: true # ============================================================================= diff --git a/src/ros2_medkit_fault_manager/design/index.rst b/src/ros2_medkit_fault_manager/design/index.rst index 8a35f6771..abbb7e887 100644 --- a/src/ros2_medkit_fault_manager/design/index.rst +++ b/src/ros2_medkit_fault_manager/design/index.rst @@ -565,10 +565,19 @@ 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, + ``max_bags`` 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. Without rules (``RetentionMode::kUnconfigured``) the quota + or after its quota step. One store reads each distinct fault once (``fault_facts``, a cache per + decision) and uses that read for the clear default, the cap and the rank. + The cap of a fault code is its rule's ``max_bags`` in ``kConfigured``, resolved with the fault's + current severity, and ``max_bags_per_fault`` otherwise. ``0`` means no cap. With ``keep_first`` + and a cap of 2 or more the first link of the code (the oldest stored link, in the backends' order + ``created_at_ns`` then insertion, read before the change) is never a cap loser, so an incoming row + that upserts it does not make another link first. ``keep_first`` with a cap below 2 is ignored, with + one warning per fault code and store. A fault that cannot be read is not capped in that store and + keeps its row, with one warning per fault and store, also when the clear default read it first. A + new row that loses the cap is not inserted, and its directory is 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 @@ -591,12 +600,18 @@ Rosbag retention 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. + dropped at the store. What the cap frees is computed with the triggering fault code's ``max_bags`` + and ``keep_first``: the codes that join the recording later are not known when it opens. +- ``deletes_recordings_on_clear``: whether a clear deletes a fault's recordings, ``auto_cleanup`` and a + ``max_bags`` of 1 (the fault's rule in ``kConfigured``, else ``max_bags_per_fault``). The private + ``clear_deletes`` decides it with the retention mutex held, for the store's ``row_still_wanted`` and + for this locked call, which ``RosbagCapture::on_fault_cleared`` makes. A fault that cannot be read + keeps its recordings. - ``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. +- ``on_fault_cleared``: removes every row of a cleared fault. ``RosbagCapture`` calls it only when + ``deletes_recordings_on_clear`` says so. - ``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. @@ -638,7 +653,11 @@ The rank of a recording is read from the rows as they will be after the insert a - 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 +The eviction order is priority ascending, then cleared, healed, active, then unprotected before +protected, then oldest first. A recording is protected when it is the first stored recording of at +least one of its fault codes whose rule has ``keep_first`` with a cap of 2 or more. Protection is +computed once per store from the rows before that store's changes: a recording that becomes first +because an earlier victim of the same store was removed is protected from the next store on. 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``. @@ -665,7 +684,7 @@ depends on the path: 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 cap victim: ``Recording removed: (its max_bags)``; - 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; diff --git a/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/core/retention_policy.hpp b/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/core/retention_policy.hpp index ccaa7502e..56730d611 100644 --- a/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/core/retention_policy.hpp +++ b/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/core/retention_policy.hpp @@ -14,11 +14,13 @@ #pragma once +#include #include #include #include #include #include +#include #include #include @@ -38,12 +40,16 @@ enum class OverQuota { kKeep, kDrop }; struct RetentionRule { std::optional priority; std::optional over_quota; + std::optional max_bags; + std::optional keep_first; }; -/// The rule of one fault, every field set. +/// The rule of one fault. struct ResolvedRule { int64_t priority{0}; OverQuota over_quota{OverQuota::kKeep}; + std::optional max_bags; ///< Unset when no level sets it: the caller uses max_bags_per_fault + bool keep_first{false}; }; struct RetentionParse; @@ -69,6 +75,10 @@ class RetentionPolicy { /// One line naming each level, its fields and the pattern order. std::string describe() const; + /// The first level that sets max_bags to a value other than @p value: its key relative to the + /// retention prefix and the value. Levels in the order defaults, severity, fault_codes, patterns. + std::optional> max_bags_other_than(int64_t value) const; + private: struct Pattern { std::string match; diff --git a/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/core/rosbag_retention.hpp b/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/core/rosbag_retention.hpp index 1e446451b..e76031f91 100644 --- a/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/core/rosbag_retention.hpp +++ b/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/core/rosbag_retention.hpp @@ -31,7 +31,7 @@ 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_bags_per_fault{1}; ///< Cap of a fault code no max_bags rule sets, 0 = no cap size_t max_total_bytes{500ULL * 1024 * 1024}; ///< Quota over every recording bool auto_cleanup{true}; ///< A cleared fault loses its recordings }; @@ -51,9 +51,9 @@ struct RetentionPolicyState { /// Why a recording's directory is no longer named by any row. enum class RemovalReason { - kCap, ///< The per-fault cap (max_bags_per_fault) + kCap, ///< The per-fault cap (max_bags) kQuota, ///< The quota (max_total_storage_mb) - kCleared, ///< The fault was cleared (auto_cleanup) + kCleared, ///< The fault was cleared (auto_cleanup with a max_bags of 1) kStale, ///< The directory was already missing }; @@ -137,7 +137,8 @@ class RosbagRetention { /// 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. + /// With rules the cap of each fault code is its rule's max_bags and keep_first, and 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. @@ -149,6 +150,11 @@ class RosbagRetention { /// @return The paths to unlink, in eviction order std::vector evict_over_quota(size_t max_bytes, const std::string & keep_recording_id = {}); + /// Whether a clear of @p fault_code deletes its recordings: auto_cleanup and a max_bags of 1. The + /// max_bags is the fault's own rule in kConfigured, else max_bags_per_fault. False when the fault + /// cannot be read. Never throws. + bool deletes_recordings_on_clear(const std::string & fault_code); + /// Remove every row of @p fault_code. The caller decides whether a clear removes recordings. /// @throws the storage failure; no row changed then, except with RosbagCommitInDoubt: the rows /// may be gone @@ -170,38 +176,54 @@ class RosbagRetention { using FactsCache = std::unordered_map; /// The store without rules: quota eviction oldest first. - StoreOutcome store_oldest_first(const std::vector & rows); + StoreOutcome store_oldest_first(const std::vector & rows, const RetentionPolicyState & state, + FactsCache & cache); /// The store with rules (kConfigured) or in degrade (kDegraded). - StoreOutcome store_ranked(const std::vector & rows, const RetentionPolicyState & state); + StoreOutcome store_ranked(const std::vector & rows, const RetentionPolicyState & state, + FactsCache & cache); /// What the quota does with a new recording, decided before anything is applied. /// @throws a failure of a read the decision needs QuotaDecision decide_quota(const std::vector & rows, const RosbagChangeSet & changes, - const RetentionPolicyState & state); + const RetentionPolicyState & state, FactsCache & cache); /// Apply @p changes of a store. Lists the directories no row names any more in @p outcome. /// False when the apply throws: kInDoubt in @p outcome for RosbagCommitInDoubt, else kStoreFailed. bool apply_store(const std::vector & rows, const RosbagChangeSet & changes, const std::unordered_map & recording_ids, StoreOutcome & outcome); - /// Severity, rule and status of a fault as the storage holds it now. A fault the storage does - /// not hold counts as cleared with severity INFO. - /// @throws a storage failure + /// Rule and status of a fault as the storage holds it now, read once per @p cache. A fault the + /// storage does not hold counts as cleared with severity INFO. Without a policy the rule is the + /// built-in one. + /// @throws a storage failure, also for a read that failed earlier with the same @p cache FaultFacts fault_facts(const RetentionPolicyState & state, const std::string & fault_code, FactsCache & cache); /// The rank of a recording from the faults its rows link. RecordingRank rank_of(const RetentionPolicyState & state, const std::vector & fault_codes, FactsCache & cache); - /// Whether a fault keeps its row: false only under auto_cleanup with a cap of exactly 1, for a - /// fault the storage holds as cleared. A fault that cannot be read keeps its row. - bool row_still_wanted(const std::string & fault_code); + /// Whether a clear of @p fault_code deletes its recordings (deletes_recordings_on_clear). + /// Expects mutex_ held. + /// @throws a failure of the fault read + bool clear_deletes(const RetentionPolicyState & state, const std::string & fault_code, FactsCache & cache); + + /// Log a failed read of @p fault_code once per @p cache: the row check and the cap of one store + /// share the line. + void warn_unreadable(const RetentionPolicyState & state, const std::string & fault_code, const std::string & error, + FactsCache & cache); + + /// Whether a fault keeps its row: false only when its clear deletes its recordings and the + /// storage holds it as cleared. A fault that cannot be read keeps its row. + bool row_still_wanted(const RetentionPolicyState & state, const std::string & fault_code, FactsCache & cache); - /// 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. + /// The insert and the per-fault cap removals of @p rows, as one change set. In kConfigured each + /// fault code takes the cap of its rule, a code whose fault cannot be read is not capped, and + /// with @p store_logs the store's warnings are logged. 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, + RosbagChangeSet cap_changes(const std::vector & rows, const RetentionPolicyState & state, + FactsCache & cache, bool store_logs, std::unordered_map & recording_ids); /// Quota eviction. @p out holds what was applied, also when this throws. 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 index db5911df4..5e3400839 100644 --- 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 @@ -51,7 +51,7 @@ class RetentionWorker { 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 + /// reason: `Recording removed: (its max_bags)` 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. 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 568dd125e..21b94fad3 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 @@ -348,18 +348,6 @@ class RosbagCapture { /// @return True when the rows are known to be durable. bool store_rows_or_discard_bag(std::vector rows, const std::string & bag_path); - /// 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. 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; - } - /// Start the post-fault window: re-arm the timer, creating it the first time. /// /// The timer is created once and re-armed, never replaced per recording. A timer diff --git a/src/ros2_medkit_fault_manager/src/core/retention_policy.cpp b/src/ros2_medkit_fault_manager/src/core/retention_policy.cpp index ef9252a81..ff0774810 100644 --- a/src/ros2_medkit_fault_manager/src/core/retention_policy.cpp +++ b/src/ros2_medkit_fault_manager/src/core/retention_policy.cpp @@ -82,7 +82,7 @@ const char * over_quota_name(OverQuota value) { return value == OverQuota::kDrop ? "drop" : "keep"; } -/// Applies a priority or over_quota value to @p rule, or adds the reason it is invalid to @p errors. +/// Applies a field value to @p rule, or adds the reason it is invalid to @p errors. void set_field(const std::string & key, const std::string & field, const ParamValue & value, RetentionRule & rule, std::vector & errors) { if (field == "priority") { @@ -106,13 +106,33 @@ void set_field(const std::string & key, const std::string & field, const ParamVa } else { errors.push_back(key + ": over_quota must be keep or drop, got '" + *text + "'"); } + } else if (field == "max_bags") { + const auto * number = std::get_if(&value); + if (number == nullptr) { + errors.push_back(key + ": max_bags must be an integer, got " + type_name(value)); + } else if (*number < 0) { + errors.push_back(key + ": max_bags must be 0 or more, got " + std::to_string(*number)); + } else { + rule.max_bags = *number; + } + } else if (field == "keep_first") { + const auto * flag = std::get_if(&value); + if (flag == nullptr) { + errors.push_back(key + ": keep_first must be true or false, got " + type_name(value)); + } else { + rule.keep_first = *flag; + } } else if (field == "match") { errors.push_back(key + ": match is only valid under patterns.