From 8dd1ca888b2d05f0349ab372918c7e549043c4d5 Mon Sep 17 00:00:00 2001 From: Bartosz Burda Date: Tue, 1 Dec 2026 14:41:05 +0100 Subject: [PATCH] fault_manager: on_healed and on_cleared per rosbag retention rule * feat(fault_manager): on_healed and on_cleared per rosbag retention rule * fix(fault_manager): the rosbag store drops the row of a fault healed with delete * fix(fault_manager): one rosbag decision per status change * docs(fault_manager): fail-closed audit and unreadable faults in the rosbag status actions * docs(fault_manager): a status action removes the fault's links, not a shared recording --- docs/config/fault-manager.rst | 66 ++- docs/tutorials/snapshots.rst | 27 +- src/ros2_medkit_fault_manager/CMakeLists.txt | 5 + src/ros2_medkit_fault_manager/README.md | 18 +- .../config/rosbag_retention.example.yaml | 16 +- .../config/snapshots.yaml | 1 + .../design/architecture.puml | 1 + .../design/index.rst | 70 ++- .../core/fault_manager_core.hpp | 4 + .../core/fault_manager_startup.hpp | 10 +- .../core/retention_policy.hpp | 7 + .../core/rosbag_retention.hpp | 88 +++- .../retention_worker.hpp | 2 +- .../ros2/ros_capture_hooks.hpp | 9 +- .../rosbag_capture.hpp | 41 +- .../src/core/fault_manager_core.cpp | 3 + .../src/core/fault_manager_startup.cpp | 12 +- .../src/core/retention_policy.cpp | 48 +- .../src/core/rosbag_retention.cpp | 116 ++++- .../src/fault_manager_node.cpp | 30 +- .../src/retention_worker.cpp | 3 + .../src/rosbag_capture.cpp | 109 ++-- .../test/integration/rosbag_fm_harness.py | 24 + .../integration/test_rosbag_quota_pg.test.py | 3 + .../test_rosbag_status_actions.test.py | 471 ++++++++++++++++++ .../test/test_retention_policy.cpp | 38 +- 26 files changed, 1072 insertions(+), 150 deletions(-) create mode 100644 src/ros2_medkit_fault_manager/test/integration/test_rosbag_status_actions.test.py diff --git a/docs/config/fault-manager.rst b/docs/config/fault-manager.rst index a976a73ea..24cf9b9c2 100644 --- a/docs/config/fault-manager.rst +++ b/docs/config/fault-manager.rst @@ -665,6 +665,8 @@ Capture continuous rosbag recordings around fault events. 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. + A retention rule's ``on_cleared`` replaces it for the fault codes the rule + covers (see Rosbag Retention Rules below). .. note:: @@ -789,7 +791,8 @@ Rosbag Retention Rules ~~~~~~~~~~~~~~~~~~~~~~ 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 +``over_quota`` choice, a ``max_bags`` cap, ``keep_first``, and what happens to the fault's recordings +when it heals (``on_healed``) or is cleared (``on_cleared``). 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 @@ -805,6 +808,8 @@ before. An example file is ``config/rosbag_retention.example.yaml``. defaults: priority: 10 severity: + INFO: + on_healed: delete ERROR: priority: 50 fault_codes: @@ -816,6 +821,7 @@ before. An example file is ``config/rosbag_retention.example.yaml``. gnss_fix: match: 'GNSS\.FIX_LOST' priority: 300 + on_cleared: delete pattern_order: [gnss_fix] Grammar, relative to ``snapshots.rosbag.retention.``: @@ -861,6 +867,14 @@ Fields: - ``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. + * - ``on_healed`` + - ``keep`` (default) or ``delete`` + - What happens to the fault's recordings when it becomes HEALED. HEALED needs + ``healing_enabled: true`` (default ``false``). + * - ``on_cleared`` + - ``keep`` or ``delete``; default ``delete`` when ``rosbag.auto_cleanup`` is true and the fault's + ``max_bags`` is 1, else ``keep`` + - What happens to the fault's recordings when it becomes CLEARED. **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 @@ -872,9 +886,41 @@ store of that fault code logs a warning. A fault that cannot be read when a reco 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. +**The clear.** A clear deletes the fault's recordings when its rule says ``on_cleared: delete``, and +keeps them with ``on_cleared: keep``, whatever ``rosbag.auto_cleanup`` and the cap are. Without +``on_cleared`` the default applies: 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. + +**The heal.** A fault that becomes HEALED loses its recordings when its rule says +``on_healed: delete``. That holds for every status the fault heals from, PREFAILED included, and also +removes the recordings of earlier episodes of the code. Without ``on_healed`` the recordings stay. + +Both actions run at the status change, resolved with the fault's severity at that moment. A recording +shared by a burst loses only the link of the fault that healed or was cleared; the directory is +removed with the last link. Each removed recording is logged as ``Recording removed: (fault +healed)`` or ``(fault cleared)``, after its directory is gone. + +**A recording made before a delete action never survives it.** Each fault code joins a recording when +the recording opens or when the fault confirms inside its post-fault window. A fault that heals or is +cleared with delete inside the window gets no row in that recording; a recording no fault keeps a row +in is discarded when it is stored. A recording that is closed but not stored yet when its fault heals +or is cleared with delete is not stored for that fault, also when the fault fails again before the +store. A fault that joins after the delete action keeps its row, unless it is still HEALED or +CLEARED with delete when the recording is stored: a confirmation whose capture runs only after the +fault healed or was cleared with delete stores no row. + +**Startup reclassification.** A fault that is HEALED at startup while healing is now disabled for its +code becomes CLEARED. Its recordings are deleted only when its rule says ``on_cleared: delete`` +explicitly; the default of ``on_cleared`` does not apply there. A restart with healing turned off thus +deletes nothing that no rule asks to delete. + +With ``audit_log.fail_closed: true``, a failed audit append stops the status actions that follow it: +a heal stops before its ``on_healed``, a startup reclassification before its ``on_cleared``, and a +symptom auto-cleared with its root cause stops its own ``on_cleared`` and that of the root cause. The +stored recordings stay until a space limit or a later status change removes them; a recording stored +after the failed append follows the fault's status like any store. **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 @@ -914,7 +960,7 @@ it in its post-fault window is dropped when it is stored. 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, with ``max_bags_per_fault`` for -every fault code. +every fault code. A heal keeps the recordings (``on_healed`` is ``keep``). A failed attempt to open a recording keeps the ring buffer, so the next fault within ``duration_sec`` still gets its history. @@ -947,7 +993,8 @@ A file the fault manager cannot read is reported with a warning and skipped. - 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``; + below 0, ``over_quota`` other than ``keep`` or ``drop``, ``on_healed`` or ``on_cleared`` other than + ``keep`` or ``delete`` (``on_cleared: 1`` is an integer); - 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. @@ -1018,7 +1065,12 @@ by default: with it off there is no table, no file and no write cost. already committed to the separate fault-store database and the two databases cannot be made atomic. It signals a broken audit chain so an operator has to act. Off by default so the audit can never block fault - processing. + processing. A heal, a startup reclassification, or a symptom auto-cleared + with its root cause whose append fails does not run the rosbag status + actions that follow it (``on_healed``, ``on_cleared``; for the symptom also + the root cause's ``on_cleared``): the stored recordings stay until a space + limit or a later status change removes them, and a recording stored after + the failed append follows the fault's status like any store. * - ``audit_log.database_path`` - ``""`` - Where the audit database lives. Empty puts it beside the fault database, diff --git a/docs/tutorials/snapshots.rst b/docs/tutorials/snapshots.rst index e09bafe62..87d327f3a 100644 --- a/docs/tutorials/snapshots.rst +++ b/docs/tutorials/snapshots.rst @@ -53,12 +53,16 @@ configuration always overrides the zero-config fallback when present. of that code's leftover HEALED rows as it reclassifies them, without a clear at all. ``snapshots.retain_on_clear: true`` keeps the value snapshots across all of it, and only those. The rosbag recording is not covered by that - setting. A clear deletes the recording under + setting. A clear removes the fault's link to each of its recordings under ``snapshots.rosbag.auto_cleanup``, unless that is off or - ``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 + ``snapshots.rosbag.max_bags_per_fault`` keeps a history; a recording is + deleted with its last link. 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. + ``snapshots.rosbag.max_total_storage_mb`` bounds it. A retention rule's + ``on_cleared`` (``keep`` or ``delete``) overrides all of this for the faults it + covers, and its ``on_healed: delete`` removes the fault's links when the + fault heals. Quick Start ----------- @@ -503,11 +507,13 @@ Rosbag Capture (Time-Window Recording) In addition to JSON snapshots, you can enable **rosbag capture** for "black box" 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. A retention rule's ``max_bags`` replaces -``max_bags_per_fault`` for the faults it covers. +to a bag file when a fault is confirmed. When the fault is cleared, its link to +each of its recordings is removed, unless ``snapshots.rosbag.auto_cleanup`` is +off or ``snapshots.rosbag.max_bags_per_fault`` keeps a history, which takes over +the retention decision. A recording is deleted with its last link. A retention +rule's ``max_bags`` replaces ``max_bags_per_fault`` for the faults it covers, and +its ``on_cleared`` (``keep`` or ``delete``) overrides the clear decision. A rule's +``on_healed: delete`` removes the fault's links when the fault heals. **Key differences from JSON snapshots:** @@ -651,7 +657,8 @@ Rosbag Configuration Options 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. + governs retention there instead. A retention rule's ``on_cleared`` + (``keep`` or ``delete``) overrides it for the faults the rule covers. * - ``snapshots.rosbag.lazy_start`` - ``false`` - Controls when the ring buffer starts recording. See diagram below. diff --git a/src/ros2_medkit_fault_manager/CMakeLists.txt b/src/ros2_medkit_fault_manager/CMakeLists.txt index dae901663..aa2676c1e 100644 --- a/src/ros2_medkit_fault_manager/CMakeLists.txt +++ b/src/ros2_medkit_fault_manager/CMakeLists.txt @@ -299,6 +299,11 @@ endif() medkit_add_launch_test(test_rosbag_max_bags test/integration/test_rosbag_max_bags.test.py TIMEOUT 600 LABELS "integration") + # on_healed and on_cleared per retention rule: the heal, the clear, the delete generation and the + # startup reclassification. + medkit_add_launch_test(test_rosbag_status_actions test/integration/test_rosbag_status_actions.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 f426c7653..593517a2e 100644 --- a/src/ros2_medkit_fault_manager/README.md +++ b/src/ros2_medkit_fault_manager/README.md @@ -135,12 +135,17 @@ parameter list and recording lifecycle. #### Rosbag Retention Rules `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 +`max_bags` cap, `keep_first`, `on_healed` and `on_cleared` (`keep` or `delete`) 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 +the fault code still stored. A heal deletes a fault's recordings with `on_healed: delete` (default `keep`; HEALED +needs `healing_enabled: true`). A clear deletes them with `on_cleared: delete` and keeps them with +`on_cleared: keep`; without `on_cleared`, a clear with `auto_cleanup` deletes them only when the fault's `max_bags` +is 1. A fault the startup turns from HEALED into CLEARED, because healing is now disabled, loses its recordings +only with an explicit `on_cleared: delete`. A recording made before such a delete never survives it, also when +the fault fails again before the recording is stored; a burst's shared recording loses only that fault's link. +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. @@ -593,11 +598,12 @@ and some of them build an `rclcpp::Clock`. the clamps and fallbacks and returns the lines to log as `ConfigNotice` values; - `core::build_core_parts()`: opens the storage and the audit log, loads the threshold and correlation files. It throws when the storage or the audit log cannot be opened. - `core::reclassify_stale_healed()` is the startup pass for stale HEALED rows; + `core::reclassify_stale_healed()` is the startup pass for stale HEALED rows and returns the codes it changed; - `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 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 retention rules, the open-time quota check, the clear, the heal, the startup reclassification 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. @@ -605,7 +611,7 @@ The core reaches the outside through four interfaces. The ROS adapter implements | Interface | Role | | --- | --- | | `core::EventSink` | `publish()` receives every fault event the core emits. | -| `core::CaptureHooks` | `capture_now()` queues the snapshot and rosbag capture of a fault code. The core has already applied the recapture cooldown. `on_prefailed()` and `on_cleared()` notify the capture side. | +| `core::CaptureHooks` | `capture_now()` queues the snapshot and rosbag capture of a fault code. The core has already applied the recapture cooldown. `on_prefailed()`, `on_cleared()` and `on_healed()` notify the capture side. | | `core::WallClock` | `now_ns()` returns nanoseconds since the Unix epoch. | | `core::LogSink` | `log()` receives the log lines. | 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 299413bfd..7af187018 100644 --- a/src/ros2_medkit_fault_manager/config/rosbag_retention.example.yaml +++ b/src/ros2_medkit_fault_manager/config/rosbag_retention.example.yaml @@ -4,13 +4,18 @@ # 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), 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 (integer 0 or more, built-in snapshots.rosbag.max_bags_per_fault), keep_first (true or +# false, built-in false), on_healed (keep or delete, built-in keep) and on_cleared (keep or delete, +# built-in: the clear default below). # 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. +# with a max_bags below 2 is ignored with a warning. +# on_healed and on_cleared run when the fault becomes HEALED or CLEARED. HEALED needs +# healing_enabled: true. Without on_cleared a clear deletes the fault's recordings when +# snapshots.rosbag.auto_cleanup is true and its max_bags is 1. A fault turned from HEALED into +# CLEARED at startup, because healing is now disabled, loses its recordings only with an explicit +# on_cleared: delete. A recording shared by a burst loses only the link of that fault. # A new recording evicts only recordings of equal or lower priority: lowest priority first, then # 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. @@ -31,6 +36,8 @@ fault_manager: over_quota: keep severity: # Severity names: INFO, WARN, ERROR, CRITICAL. + INFO: + on_healed: delete ERROR: priority: 50 CRITICAL: @@ -46,6 +53,7 @@ fault_manager: DEBUG_NOISE: priority: 0 over_quota: drop + on_cleared: delete patterns: # A dotted fault code goes through a pattern whose match escapes the dot. # The match covers the whole fault code (ECMAScript regular expression). diff --git a/src/ros2_medkit_fault_manager/config/snapshots.yaml b/src/ros2_medkit_fault_manager/config/snapshots.yaml index 701e2ac0e..32d145359 100644 --- a/src/ros2_medkit_fault_manager/config/snapshots.yaml +++ b/src/ros2_medkit_fault_manager/config/snapshots.yaml @@ -199,6 +199,7 @@ rosbag: # 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 + # A retention rule's on_cleared (keep or delete) replaces it for the faults it covers auto_cleanup: true # ============================================================================= diff --git a/src/ros2_medkit_fault_manager/design/architecture.puml b/src/ros2_medkit_fault_manager/design/architecture.puml index 54877faf9..dd105d580 100644 --- a/src/ros2_medkit_fault_manager/design/architecture.puml +++ b/src/ros2_medkit_fault_manager/design/architecture.puml @@ -65,6 +65,7 @@ package "ros2_medkit_fault_manager" { + capture_now(code): CaptureResult + on_prefailed(code): void + on_cleared(code): void + + on_healed(code): void } class WallClock <> { diff --git a/src/ros2_medkit_fault_manager/design/index.rst b/src/ros2_medkit_fault_manager/design/index.rst index abbb7e887..c9e32f0ab 100644 --- a/src/ros2_medkit_fault_manager/design/index.rst +++ b/src/ros2_medkit_fault_manager/design/index.rst @@ -91,6 +91,7 @@ The following diagram shows the relationships between the main components of the + capture_now(code): CaptureResult + on_prefailed(code): void + on_cleared(code): void + + on_healed(code): void } class WallClock <> { @@ -341,7 +342,8 @@ defaults if not. When healing is disabled for a code, any HEALED row of that cod previous (healing-enabled) run is reclassified to CLEARED once at startup so it does not behave inconsistently under the latch. The code's own ``healing_enabled`` decides, and the global value applies when the code does not set one. Entity overrides are not used, because a stored fault -belongs to its code and can have several sources. +belongs to its code and can have several sources. ``core::reclassify_stale_healed`` returns the +reclassified codes, and the node hands each to ``RosbagRetention::on_startup_reclassified``. Rosbag Black-Box Recording ~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -564,8 +566,9 @@ 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`` of 1), applies the per-fault cap in the same change set as the insert, +- ``store``: drops the rows of codes whose delete generation moved since they joined the + recording (see below) and of faults the storage holds as cleared with a deleting clear + (``clear_deletes``) or as healed with a deleting heal (``heal_deletes``), 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. 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. @@ -602,20 +605,49 @@ 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. 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`` calls it only when - ``deletes_recordings_on_clear`` says so. +- ``on_fault_cleared``, ``on_fault_healed`` and ``on_startup_reclassified``: one status change of a + fault, in one hold of the mutex, and the only decision of it. Each decides with the private + ``clear_deletes`` (the ``on_cleared`` of the fault's rule in ``kConfigured`` when the rule sets it, + else ``auto_cleanup`` and a ``max_bags`` of 1), ``heal_deletes`` (the ``on_healed`` of the rule in + ``kConfigured``, never otherwise), or an explicit ``on_cleared: delete`` for the startup + reclassification, where the clear default does not apply. ``clear_deletes`` and ``heal_deletes`` + also serve the store's ``row_still_wanted``. A deleting change sets ``RemovalOutcome::deletes``, + advances the code's delete generation and removes every row of the code, with + ``RemovalReason::kCleared`` or ``kHealed``. Only with valid rules (``kConfigured``) the decision + reads the fault; a fault that cannot be read then: nothing is removed, one WARN, an empty outcome. + Without valid rules (``kUnconfigured``, ``kDegraded``) the clear default is decided without a read, + and the heal and the startup reclassification keep. ``RosbagCapture`` calls the first two from the + clear and heal hooks; the node calls the third for each code ``reclassify_stale_healed`` returns, + and posts the directories to the retention worker. +- ``delete_generation``: the code's delete generation, read by ``RosbagCapture`` when a code joins a + recording. - ``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. +**Delete generation.** A recording closes on the executor and is stored later on the store worker, +so a fault can heal or be cleared, and fail again, between the two. The status at the store then +says nothing about the delete action in between. ``RosbagRetention`` keeps, under its mutex, a +counter per fault code that each deleting clear, heal and startup reclassification advances. A code +reads it when it joins a recording: ``RosbagCapture::on_fault_confirmed`` reads it before the +attach and before the open, so the primary and every attached code carry the value they read. The +values travel with the recording (``ClosedRecording::delete_generations``, and the inline store +path), and ``store`` drops the row of a code whose counter moved since; a recording that keeps no +row is discarded (``kAllFaultsCleared``). The map holds one entry per code that ever had a delete +action and is looked up only by code. A code that joins after the delete action keeps its row, +unless the store finds its fault still HEALED or CLEARED with delete: the capture of a confirmation +runs on the capture pool, so it can join after a heal that came later than the confirmation. + +``RosbagCapture::on_fault_cleared`` and ``on_fault_healed`` run in the core's hooks, under the core +mutex. Each calls the retention's operation once; it is the only decision of the change. Only when +the outcome says ``deletes`` it takes ``post_fault_timer_mutex_`` to detach the code from an +in-flight recording, releases it, and posts the directories to the retention worker. With valid +rules, a fault the retention cannot read is not detached and loses nothing. ``!enabled`` returns +early; ``auto_cleanup`` is only the clear default. + ``core::RetentionPolicy`` (``core/retention_policy.*``, no ROS types) parses the ``snapshots.rosbag.retention.*`` parameters, flattened by the node into a map of keys relative to the prefix, and resolves the rule of a fault code and severity field by field: fault code, the first @@ -662,10 +694,11 @@ candidates are every stored recording except the new one and the paths the cap r 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 -retention mutex only storage calls and logging run. No other lock is taken and no file system -call runs. +Lock order: the caller's outer locks (the node's rosbag mutex on the inline store path and for +``delete_generation``, the core mutex on the clear and heal paths), 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 store worker calls the retention with no lock of +``RosbagCapture`` held and never takes the core mutex. 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 @@ -677,15 +710,16 @@ depends on the path: logged. The executor never runs a store. A bag that never got a row is discarded on the same thread. A store in doubt (``kInDoubt``) returns no paths: the new directory stays, and a cap victim's directory can stay with no row when the commit was applied. -- 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. +- Clear, heal, startup reclassification and stale rows (the executor): the rows go inside the + service call or the constructor. The node's ``RetentionWorker``, one thread with a FIFO queue, + removes the directories, so the clear and report services return 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: (its max_bags)``; - a recording of a cleared fault: ``Recording removed: (fault cleared)``; +- a recording of a fault that healed: ``Recording removed: (fault healed)``; - 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. @@ -694,7 +728,7 @@ 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 bag. A heal logs ``Heal cleanup: deleted the recordings of fault ''`` the same way. 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()``, diff --git a/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/core/fault_manager_core.hpp b/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/core/fault_manager_core.hpp index 445a35d5c..afff61ec2 100644 --- a/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/core/fault_manager_core.hpp +++ b/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/core/fault_manager_core.hpp @@ -83,6 +83,10 @@ class CaptureHooks { virtual void on_confirmed(const std::string & code) { (void)code; } + /// An existing fault that just moved to HEALED from any other status, PREFAILED included. + virtual void on_healed(const std::string & code) { + (void)code; + } /// A FAILED report reached a fault that was not CONFIRMED and the core could not read the result back. The /// receiver checks the status itself. virtual void on_confirm_candidate(const std::string & code) { diff --git a/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/core/fault_manager_startup.hpp b/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/core/fault_manager_startup.hpp index f486e92c0..4c52adf81 100644 --- a/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/core/fault_manager_startup.hpp +++ b/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/core/fault_manager_startup.hpp @@ -18,6 +18,7 @@ #include #include #include +#include #include "ros2_medkit_fault_detection/fault_types.hpp" #include "ros2_medkit_fault_manager/core/fault_manager_config.hpp" @@ -49,8 +50,11 @@ using ReclassifyAuditFn = /// Turns stale HEALED rows into CLEARED for codes whose healing is now disabled. Calls @p audit for /// each flipped fault when @p audit_enabled. Storage that is unreachable skips it with a warning. -void reclassify_stale_healed(FaultStorage & storage, const FaultCodeThresholdResolver * fault_code_resolver, - const DebounceConfig & global_debounce, bool audit_enabled, LogSink & sink, - const std::string & logger, const ReclassifyAuditFn & audit); +/// @return The codes turned into CLEARED; empty when it was skipped +std::vector reclassify_stale_healed(FaultStorage & storage, + const FaultCodeThresholdResolver * fault_code_resolver, + const DebounceConfig & global_debounce, bool audit_enabled, + LogSink & sink, const std::string & logger, + const ReclassifyAuditFn & audit); } // namespace ros2_medkit_fault_manager::core 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 56730d611..06797e286 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 @@ -36,12 +36,17 @@ using FlatParams = std::map; /// What happens to a new recording that cannot fit the quota. enum class OverQuota { kKeep, kDrop }; +/// What happens to a fault's recordings when it heals or is cleared. +enum class StatusAction { kKeep, kDelete }; + /// The fields one level of the configuration sets. An unset field falls through to the next level. struct RetentionRule { std::optional priority; std::optional over_quota; std::optional max_bags; std::optional keep_first; + std::optional on_healed; + std::optional on_cleared; }; /// The rule of one fault. @@ -50,6 +55,8 @@ struct ResolvedRule { 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}; + StatusAction on_healed{StatusAction::kKeep}; + std::optional on_cleared; ///< Unset when no level sets it: the caller applies the clear default }; struct RetentionParse; 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 e76031f91..7df6487f3 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 @@ -33,7 +33,7 @@ namespace ros2_medkit_fault_manager::core { struct RosbagRetentionLimits { 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 + bool auto_cleanup{true}; ///< Clear default: a clear deletes when max_bags is 1 }; /// How the quota treats a new recording. @@ -53,10 +53,14 @@ struct RetentionPolicyState { enum class RemovalReason { kCap, ///< The per-fault cap (max_bags) kQuota, ///< The quota (max_total_storage_mb) - kCleared, ///< The fault was cleared (auto_cleanup with a max_bags of 1) + kCleared, ///< The fault was cleared: its on_cleared, else auto_cleanup with a max_bags of 1 + kHealed, ///< The fault healed and its on_healed is delete kStale, ///< The directory was already missing }; +/// Per fault code, the delete generation the code read when it joined a recording. +using DeleteGenerations = std::unordered_map; + /// A directory no row names any more: the caller removes it and logs the removal. struct FreedRecording { std::string path; @@ -65,8 +69,10 @@ struct FreedRecording { }; 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. + kStored, ///< The rows were applied. Also when the cap removed every new row. + /// Every fault of the recording was cleared or healed with delete, or released by a delete action after it was + /// recorded. Nothing was stored. + kAllFaultsCleared, 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. kInDoubt, ///< The rows may or may not be stored (RosbagCommitInDoubt); the caller keeps the bag. @@ -95,6 +101,7 @@ struct StoreOutcome { struct RemovalOutcome { size_t removed_rows{0}; std::vector unlink_paths; ///< Directories no row names any more, each path once + bool deletes{false}; ///< A status change decided to delete the fault's recordings }; /// Every rosbag retention decision of the fault manager, on FaultStorage::apply_rosbag_changes(). @@ -135,14 +142,21 @@ class RosbagRetention { bool admits_new_recording(const std::string & fault_code, size_t reserve_bytes, const std::vector> & 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 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. + /// Store the rows of one recording. In one hold of the mutex: drop the rows of faults whose + /// delete generation moved since @p joined and of faults the storage holds as cleared with a + /// deleting clear or as healed with a deleting heal, apply the per-fault cap together with the + /// insert, then the quota. 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. A code + /// @p joined does not list is not checked for its delete generation. /// 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); + StoreOutcome store(std::vector rows, const DeleteGenerations & joined = {}); + + /// The delete generation of @p fault_code: how many deleting clears, heals and startup + /// reclassifications it had in this process. A code reads it when it joins a recording. + /// Takes the mutex; no storage call. + uint64_t delete_generation(const std::string & fault_code); /// Evict whole recordings, oldest first, until the total is at or under @p max_bytes. Never /// evicts @p keep_recording_id. @@ -150,16 +164,28 @@ 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 + /// The clear of @p fault_code, the only decision of it. It deletes on the on_cleared of the + /// fault's rule in kConfigured, else on auto_cleanup and a max_bags of 1 (the fault's own rule in + /// kConfigured, else max_bags_per_fault). Then it sets `deletes`, advances the code's delete + /// generation and removes every row of the code (RemovalReason::kCleared). Only with valid rules + /// (kConfigured) the decision reads the fault; a fault that cannot be read then: nothing is + /// removed, one WARN, the outcome is empty. Without valid rules the clear default is decided + /// without a read. + /// @throws the storage failure of the removal, with the generation already advanced; no row + /// changed then, except with RosbagCommitInDoubt: the rows may be gone RemovalOutcome on_fault_cleared(const std::string & fault_code); + /// The heal of @p fault_code: as on_fault_cleared(), deciding on the on_healed of the fault's rule + /// in kConfigured, with RemovalReason::kHealed. Without valid rules it keeps, without a read. + /// @throws as on_fault_cleared() + RemovalOutcome on_fault_healed(const std::string & fault_code); + + /// A fault the startup turned from HEALED into CLEARED: as on_fault_cleared(), but only an + /// on_cleared: delete its rule sets in kConfigured deletes. The clear default does not apply; + /// without valid rules it keeps, without a read. + /// @throws as on_fault_cleared() + RemovalOutcome on_startup_reclassified(const std::string & fault_code); + /// Remove every row of a recording whose directory is gone. /// @throws the storage failure; no row changed then, except with RosbagCommitInDoubt: the rows /// may be gone @@ -175,6 +201,9 @@ class RosbagRetention { struct QuotaDecision; using FactsCache = std::unordered_map; + /// A status change that may delete a fault's recordings. + enum class StatusChange { kCleared, kHealed, kReclassified }; + /// The store without rules: quota eviction oldest first. StoreOutcome store_oldest_first(const std::vector & rows, const RetentionPolicyState & state, FactsCache & cache); @@ -203,18 +232,33 @@ class RosbagRetention { RecordingRank rank_of(const RetentionPolicyState & state, const std::vector & fault_codes, FactsCache & cache); - /// Whether a clear of @p fault_code deletes its recordings (deletes_recordings_on_clear). - /// Expects mutex_ held. + /// Whether a clear of @p fault_code deletes its recordings (on_fault_cleared). Expects mutex_ held. /// @throws a failure of the fault read bool clear_deletes(const RetentionPolicyState & state, const std::string & fault_code, FactsCache & cache); + /// Whether a heal of @p fault_code deletes its recordings (on_fault_healed). Expects mutex_ held. + /// @throws a failure of the fault read + bool heal_deletes(const RetentionPolicyState & state, const std::string & fault_code, FactsCache & cache); + + /// Whether @p change of @p fault_code deletes its recordings. Expects mutex_ held. + /// @throws a failure of the fault read + bool change_deletes(const RetentionPolicyState & state, StatusChange change, const std::string & fault_code, + FactsCache & cache); + + /// on_fault_cleared(), on_fault_healed() and on_startup_reclassified(). + RemovalOutcome on_status_change(StatusChange change, const std::string & fault_code); + + /// Expects mutex_ held. + uint64_t generation_of(const std::string & fault_code) const; + /// 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. + /// Whether a fault keeps its row: false only when the storage holds it as cleared and its clear + /// deletes its recordings, or as healed and its heal deletes them. 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. In kConfigured each @@ -240,6 +284,8 @@ class RosbagRetention { const std::string logger_name_; std::shared_ptr state_; ///< Only through std::atomic_load / std::atomic_store std::mutex mutex_; + /// One entry per fault code that had a delete action. Guarded by mutex_; only looked up by code. + std::unordered_map delete_generations_; }; } // namespace ros2_medkit_fault_manager::core 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 5e3400839..7d4cc6570 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: (its max_bags)` or `(fault cleared)`, or main's + /// reason: `Recording removed: (its max_bags)`, `(fault cleared)` or `(fault healed)`, 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/ros2/ros_capture_hooks.hpp b/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/ros2/ros_capture_hooks.hpp index 765f36654..de22487ee 100644 --- a/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/ros2/ros_capture_hooks.hpp +++ b/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/ros2/ros_capture_hooks.hpp @@ -30,12 +30,13 @@ class RosCaptureHooks : public core::CaptureHooks { using CodeFn = std::function; RosCaptureHooks(CaptureFn capture_now, CodeFn on_prefailed, CodeFn on_cleared, CodeFn on_confirmed, - CodeFn on_confirm_candidate) + CodeFn on_confirm_candidate, CodeFn on_healed) : capture_now_(std::move(capture_now)) , on_prefailed_(std::move(on_prefailed)) , on_cleared_(std::move(on_cleared)) , on_confirmed_(std::move(on_confirmed)) - , on_confirm_candidate_(std::move(on_confirm_candidate)) { + , on_confirm_candidate_(std::move(on_confirm_candidate)) + , on_healed_(std::move(on_healed)) { } core::CaptureResult capture_now(const std::string & code) override { @@ -53,6 +54,9 @@ class RosCaptureHooks : public core::CaptureHooks { void on_confirm_candidate(const std::string & code) override { on_confirm_candidate_(code); } + void on_healed(const std::string & code) override { + on_healed_(code); + } private: CaptureFn capture_now_; @@ -60,6 +64,7 @@ class RosCaptureHooks : public core::CaptureHooks { CodeFn on_cleared_; CodeFn on_confirmed_; CodeFn on_confirm_candidate_; + CodeFn on_healed_; }; } // namespace ros2_medkit_fault_manager::ros2 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 21b94fad3..75c5f61f2 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 @@ -16,6 +16,7 @@ #include #include +#include #include #include #include @@ -57,7 +58,7 @@ struct BufferedMessage { /// Lifecycle: /// - start() begins buffering messages (or lazy_start waits for PREFAILED) /// - on_fault_confirmed() flushes buffer to bag file -/// - on_fault_cleared() deletes bag file if auto_cleanup enabled +/// - on_fault_cleared() and on_fault_healed() delete the fault's recordings when the retention says so /// /// Only one recording is open at a time (one ring buffer, one writer, one post-roll /// state machine). Right after a post-fault window closes the ring buffer holds nothing @@ -131,13 +132,18 @@ class RosbagCapture { /// @param fault_code The fault code that was confirmed void on_fault_confirmed(const std::string & fault_code); - /// Called when a fault is cleared - deletes its bag record if auto_cleanup. - /// A shared bag survives until its last referencing fault clears; a fault - /// cleared during its burst's post-roll is dropped from the in-flight - /// recording state and never gets a record. + /// Called when a fault is cleared - core::RosbagRetention::on_fault_cleared() decides and deletes + /// its rows; the directories no other fault names are removed on the retention worker. Only when + /// it deleted, a fault cleared during its burst's post-roll is dropped from the in-flight + /// recording state and never gets a row. Runs under the core mutex. /// @param fault_code The fault code that was cleared void on_fault_cleared(const std::string & fault_code); + /// Called when a fault heals - as on_fault_cleared(), with + /// core::RosbagRetention::on_fault_healed(). + /// @param fault_code The fault code that healed + void on_fault_healed(const std::string & fault_code); + /// Get current configuration const RosbagConfig & config() const { return config_; @@ -306,6 +312,8 @@ class RosbagCapture { /// Empty when the primary fault was cleared during the post-roll. std::string fault_code; std::set attached_fault_codes; + /// Per code of the recording, the delete generation it read when it joined. + core::DeleteGenerations delete_generations; double duration_sec{0.0}; int64_t created_at_ns{0}; }; @@ -345,8 +353,12 @@ class RosbagCapture { /// and logged once the directory is gone. A store in doubt (core::StoreResult::kInDoubt) keeps /// the bag and logs one warning: its rows may be committed. /// + /// @p joined holds, per code of the rows, the delete generation it read when it joined the + /// recording: a row whose code had a delete action since is not stored. + /// /// @return True when the rows are known to be durable. - bool store_rows_or_discard_bag(std::vector rows, const std::string & bag_path); + bool store_rows_or_discard_bag(std::vector rows, const std::string & bag_path, + const core::DeleteGenerations & joined); /// Start the post-fault window: re-arm the timer, creating it the first time. /// @@ -387,7 +399,13 @@ class RosbagCapture { /// and a full graph enumeration on every repeat, none of which it can use. bool is_current_recording_primary(const std::string & fault_code) const; - bool attach_to_active_recording(const std::string & fault_code, const std::set & entity_topics); + /// @p generation is the delete generation @p fault_code read before it joins. + bool attach_to_active_recording(const std::string & fault_code, const std::set & entity_topics, + uint64_t generation); + + /// Drop @p fault_code from the in-flight recording state, so the finalize writes no row for it. + /// Takes post_fault_timer_mutex_ and releases it before it returns. + void detach_from_active_recording(const std::string & fault_code); /// Try to subscribe to a single topic /// @param topic The topic to subscribe to @@ -453,6 +471,9 @@ class RosbagCapture { /// recording window (one root cause, one burst), so each gets a metadata row /// pointing at the same bag when it finalises. std::set attached_fault_codes_; + /// Per code of the in-flight recording, primary and attached, the delete generation it read + /// before it joined. Guarded by post_fault_timer_mutex_. + core::DeleteGenerations recording_generations_; /// Protects post_fault_timer_, the recording_post_fault_ transitions and the /// state above against concurrent access from on_fault_confirmed() (capture-pool /// thread) and post_fault_timer_callback() / stop() (executor thread). The @@ -463,7 +484,13 @@ class RosbagCapture { /// node rosbag mutex -> post_fault_timer_mutex_ -> capture_topics_mutex_ /// node rosbag mutex -> post_fault_timer_mutex_ -> writer_mutex_ /// node rosbag mutex -> post_fault_timer_mutex_ -> node_ops_mutex_ + /// node rosbag mutex -> retention mutex -> storage lock (the delete generation, the open-time quota check) + /// core mutex -> retention mutex -> storage lock (the clear and heal hooks decide and remove) + /// core mutex -> post_fault_timer_mutex_ (then the hooks detach a code the retention deleted) + /// core mutex -> retention worker queue lock (the hooks post the removals) /// plugin_mutex() (file-scope, in rosbag_capture.cpp) -> writer_mutex_ + /// The hooks hold neither the retention mutex nor post_fault_timer_mutex_ while they take the + /// other, and no path takes the core mutex or a lock of this class under the retention mutex. /// buffer_mutex_ is never held across another lock. The paths that take /// capture_topics_mutex_ or writer_mutex_ on their own (the flush loop, the /// post-roll write path) release each before taking the next, so they add no diff --git a/src/ros2_medkit_fault_manager/src/core/fault_manager_core.cpp b/src/ros2_medkit_fault_manager/src/core/fault_manager_core.cpp index 38967fd0d..ad1bf2df0 100644 --- a/src/ros2_medkit_fault_manager/src/core/fault_manager_core.cpp +++ b/src/ros2_medkit_fault_manager/src/core/fault_manager_core.cpp @@ -449,6 +449,9 @@ ReportOutcome FaultManagerCore::report_locked(const fd::FaultReport & report) { hooks_.on_confirmed(report.fault_code); capture_on_confirm(report.fault_code); } + if (just_healed) { + hooks_.on_healed(report.fault_code); + } // PREFAILED starts the lazy_start rosbag capture bool just_prefailed = (is_new && fault_after->status == fd::fault_status::kPrefailed) || 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 a3bcb3aee..d502758ce 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 @@ -312,11 +312,13 @@ CoreParts build_core_parts(const FaultManagerConfig & config, LogSink & sink) { return parts; } -void reclassify_stale_healed(FaultStorage & storage, const FaultCodeThresholdResolver * fault_code_resolver, - const DebounceConfig & global_debounce, bool audit_enabled, LogSink & sink, - const std::string & logger, const ReclassifyAuditFn & audit) { +std::vector reclassify_stale_healed(FaultStorage & storage, + const FaultCodeThresholdResolver * fault_code_resolver, + const DebounceConfig & global_debounce, bool audit_enabled, + LogSink & sink, const std::string & logger, + const ReclassifyAuditFn & audit) { try { - const auto reclassified = + auto reclassified = storage.reclassify_healed_as_cleared([fault_code_resolver, &global_debounce](const std::string & fault_code) { if (fault_code_resolver) { return fault_code_resolver->resolve(fault_code, global_debounce).healing_enabled; @@ -337,10 +339,12 @@ void reclassify_stale_healed(FaultStorage & storage, const FaultCodeThresholdRes "Reclassified %zu stale HEALED fault(s) as CLEARED, because healing is disabled for their codes", reclassified.size()); } + return reclassified; } catch (const FaultStorage::IgnorableConnectionException & e) { logf(sink, LogLevel::kWarn, logger, "Startup HEALED reclassification not done, fault storage unavailable: %s", e.what()); } + return {}; } } // namespace ros2_medkit_fault_manager::core 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 ff0774810..33bcd44b2 100644 --- a/src/ros2_medkit_fault_manager/src/core/retention_policy.cpp +++ b/src/ros2_medkit_fault_manager/src/core/retention_policy.cpp @@ -82,6 +82,25 @@ const char * over_quota_name(OverQuota value) { return value == OverQuota::kDrop ? "drop" : "keep"; } +const char * status_action_name(StatusAction value) { + return value == StatusAction::kDelete ? "delete" : "keep"; +} + +/// Applies a keep or delete value to @p slot, or adds the reason it is invalid to @p errors. +void set_status_action(const std::string & key, const std::string & field, const ParamValue & value, + std::optional & slot, std::vector & errors) { + const auto * text = std::get_if(&value); + if (text == nullptr) { + errors.push_back(key + ": " + field + " must be a string (keep or delete), got " + type_name(value)); + } else if (*text == "keep") { + slot = StatusAction::kKeep; + } else if (*text == "delete") { + slot = StatusAction::kDelete; + } else { + errors.push_back(key + ": " + field + " must be keep or delete, got '" + *text + "'"); + } +} + /// 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) { @@ -122,15 +141,20 @@ void set_field(const std::string & key, const std::string & field, const ParamVa } else { rule.keep_first = *flag; } + } else if (field == "on_healed") { + set_status_action(key, field, value, rule.on_healed, errors); + } else if (field == "on_cleared") { + set_status_action(key, field, value, rule.on_cleared, errors); } else if (field == "match") { errors.push_back(key + ": match is only valid under patterns.