From f2a3dde40d6476fc811334a45cc42b6affe63e12 Mon Sep 17 00:00:00 2001 From: Bartosz Burda Date: Tue, 1 Dec 2026 14:41:02 +0100 Subject: [PATCH] fault_manager: add one atomic rosbag write primitive and pin today's retention behaviour * test(fault_manager): pin rosbag retention against a real fault manager process * feat(fault_manager): add apply_rosbag_changes beside the rosbag mutators * ci: run the fault manager tests under ASan and TSan * test(fault_manager): wait for the earlier subscriber to leave before the next run * test(fault_manager): put multi-line docstring summaries on the second line * test(fault_manager): tighten the upsert, store-failure and race checks * ci: make the fault manager sanitizer job comments describe this job * test(fault_manager): rosbag test harness waits for the payload --- .github/workflows/quality.yml | 161 ++++- src/ros2_medkit_fault_manager/CMakeLists.txt | 9 + .../design/index.rst | 18 + .../fault_storage.hpp | 38 ++ .../postgres_fault_storage.hpp | 1 + .../sqlite_fault_storage.hpp | 1 + src/ros2_medkit_fault_manager/package.xml | 1 + .../src/fault_storage.cpp | 81 +++ .../src/postgres_fault_storage.cpp | 47 ++ .../src/sqlite_fault_storage.cpp | 72 +++ .../test/integration/rosbag_fm_harness.py | 594 ++++++++++++++++++ .../integration/test_rosbag_quota.test.py | 333 ++++++++++ .../integration/test_rosbag_quota_pg.test.py | 89 +++ .../test/test_rosbag_storage_parity.cpp | 355 ++++++++++- 14 files changed, 1790 insertions(+), 10 deletions(-) create mode 100644 src/ros2_medkit_fault_manager/test/integration/rosbag_fm_harness.py create mode 100644 src/ros2_medkit_fault_manager/test/integration/test_rosbag_quota.test.py create mode 100644 src/ros2_medkit_fault_manager/test/integration/test_rosbag_quota_pg.test.py diff --git a/.github/workflows/quality.yml b/.github/workflows/quality.yml index 5b9650e58..a1420131e 100644 --- a/.github/workflows/quality.yml +++ b/.github/workflows/quality.yml @@ -446,9 +446,9 @@ jobs: for pkg_dir in build/ros2_medkit_cmake/ build/ros2_medkit_*/; do pkg=$(basename "$pkg_dir") if [[ " ${pkgs[*]} " == *" $pkg "* ]]; then continue; fi - # graph_watchdog is tested in sanitizer-graph-watchdog, in a job - # of its own. - if [ "$pkg" = "ros2_medkit_graph_watchdog" ]; then continue; fi + # graph_watchdog and fault_manager are tested in their own jobs + # (sanitizer-graph-watchdog, sanitizer-fault-manager). + if [ "$pkg" = "ros2_medkit_graph_watchdog" ] || [ "$pkg" = "ros2_medkit_fault_manager" ]; then continue; fi while [ "$(jobs -rp | wc -l)" -ge "$max_pkgs" ]; do wait -n || true; done (cd "$pkg_dir" && run_shard) \ > "$log_dir/$pkg.log" 2>&1 & @@ -473,7 +473,7 @@ jobs: if: always() run: | for pkg_dir in build/ros2_medkit_*/; do - if [ "$(basename "$pkg_dir")" = "ros2_medkit_graph_watchdog" ]; then continue; fi + case "$(basename "$pkg_dir")" in ros2_medkit_graph_watchdog | ros2_medkit_fault_manager) continue ;; esac colcon test-result --test-result-base "$pkg_dir" --verbose 2>/dev/null || true done @@ -636,9 +636,9 @@ jobs: for pkg_dir in build/ros2_medkit_cmake/ build/ros2_medkit_*/; do pkg=$(basename "$pkg_dir") if [[ " ${pkgs[*]} " == *" $pkg "* ]]; then continue; fi - # graph_watchdog is tested in sanitizer-graph-watchdog, in a job - # of its own. - if [ "$pkg" = "ros2_medkit_graph_watchdog" ]; then continue; fi + # graph_watchdog and fault_manager are tested in their own jobs + # (sanitizer-graph-watchdog, sanitizer-fault-manager). + if [ "$pkg" = "ros2_medkit_graph_watchdog" ] || [ "$pkg" = "ros2_medkit_fault_manager" ]; then continue; fi while [ "$(jobs -rp | wc -l)" -ge "$max_pkgs" ]; do wait -n || true; done (cd "$pkg_dir" && run_shard) \ > "$log_dir/$pkg.log" 2>&1 & @@ -663,7 +663,7 @@ jobs: if: always() run: | for pkg_dir in build/ros2_medkit_*/; do - if [ "$(basename "$pkg_dir")" = "ros2_medkit_graph_watchdog" ]; then continue; fi + case "$(basename "$pkg_dir")" in ros2_medkit_graph_watchdog | ros2_medkit_fault_manager) continue ;; esac colcon test-result --test-result-base "$pkg_dir" --verbose 2>/dev/null || true done @@ -841,13 +841,156 @@ jobs: colcon test-result --test-result-base build/ros2_medkit_graph_watchdog \ --verbose 2>/dev/null || true + # The fault manager's own tests, including the launch tests that start the + # node as a process, so a sanitizer report inside it fails the test. + sanitizer-fault-manager: + name: Sanitizer ${{ matrix.name }} (fault_manager) + needs: changes + if: needs.changes.outputs.code == 'true' + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + sanitizer: [asan, tsan] + include: + - sanitizer: asan + name: ASan + UBSan + cmake_sanitizer: asan,ubsan + # Both sizes are the ones the matching workspace job argued for. + # This job restores that job's cache and must not evict what it + # restored, so it cannot be smaller here. + ccache_size: 2G + - sanitizer: tsan + name: TSan + cmake_sanitizer: tsan + ccache_size: 1.5G + container: + image: ros:jazzy-ros-base + # See sanitizer-asan: the instrumented build tree does not fit the + # container overlay on small GitHub runners, so build on /mnt. + volumes: + - "/mnt:/mnt" + options: ${{ matrix.sanitizer == 'tsan' && '--privileged' || '' }} + # Covers a cold-cache sanitizer build plus the 45-minute test step. + timeout-minutes: 90 + defaults: + run: + shell: bash + + steps: + # TSan needs at most 28 bits of mmap ASLR entropy. Newer runner kernels use more. + - name: Lower mmap ASLR entropy + if: matrix.sanitizer == 'tsan' + run: | + sysctl -w vm.mmap_rnd_bits=28 + cat /proc/sys/vm/mmap_rnd_bits + test "$(cat /proc/sys/vm/mmap_rnd_bits)" = 28 + + - name: Checkout repository + uses: actions/checkout@v4 + + - name: Install ccache + run: | + apt-get update + apt-get install -y ccache + + - name: Restore ccache + # Restore, never save. This job compiles a subset of the sources + # sanitizer-${{ matrix.sanitizer }} compiles, with the same flags, so + # that job's cache is a superset of what this one needs and serves its + # misses. A second copy would buy nothing and would spend the + # repository's 10 GB Actions cache quota twice for one set of objects. + uses: actions/cache/restore@v4 + with: + path: /root/.cache/ccache + key: ccache-jazzy-${{ matrix.sanitizer }}-${{ github.sha }} + restore-keys: | + ccache-jazzy-${{ matrix.sanitizer }}- + + - name: Install dependencies + run: | + apt-get update + apt-get install -y ros-jazzy-test-msgs + source /opt/ros/jazzy/setup.bash + for attempt in 1 2 3; do rosdep update && break; [ "$attempt" = 3 ] && exit 1; echo "rosdep update attempt $attempt failed, retrying" >&2; sleep 5; done + rosdep install --from-paths src --ignore-src -y + + - name: Redirect heavy build output to /mnt + run: | + # Build on /mnt, as the workspace sanitizer jobs do. The path must match the + # sanitizer job whose ccache this job restores, so ccache can hit. + mkdir -p /mnt/${{ matrix.sanitizer }}/build /mnt/${{ matrix.sanitizer }}/tmp + ln -sfn /mnt/${{ matrix.sanitizer }}/build build + df -h / /mnt + + - name: Build with ${{ matrix.name }} + env: + CCACHE_DIR: /root/.cache/ccache + CCACHE_MAXSIZE: ${{ matrix.ccache_size }} + CCACHE_SLOPPINESS: pch_defines,time_macros + TMPDIR: /mnt/${{ matrix.sanitizer }}/tmp + run: | + source /opt/ros/jazzy/setup.bash + ccache -z + # --packages-up-to builds the fault manager and the packages it + # depends on, not the whole workspace. + colcon build --symlink-install \ + --packages-up-to ros2_medkit_fault_manager \ + --cmake-args -DCMAKE_BUILD_TYPE=RelWithDebInfo \ + -DSANITIZER=${{ matrix.cmake_sanitizer }} \ + --event-handlers console_direct+ + ccache -s + ./scripts/ccache_report.sh jazzy-${{ matrix.sanitizer }}-fault-manager + df -h / /mnt + + - name: Extend test timeouts for sanitizer overhead + run: | + # The same generic x3 rewrite the workspace sanitizer jobs apply - see + # the comment in sanitizer-asan for why it is not a list of literals. + find build/ -name "CTestTestfile.cmake" -exec \ + perl -pi -e 's/\bTIMEOUT "(\d+)"/sprintf(q{TIMEOUT "%d"}, $1 * 3)/ge' {} + + find build/ -name "CTestTestfile.cmake" -exec cat {} + \ + | grep -oE 'TIMEOUT "[0-9]+"' | sort -t'"' -k2 -n | uniq -c + + - name: Run fault_manager tests with ${{ matrix.name }} + timeout-minutes: 45 + env: + # Same factor as the ctest TIMEOUT rewrite above, for the wall-clock + # budgets tests assert internally - ctest's clock cannot reach those. + MEDKIT_TEST_TIME_SCALE: 3 + # Lets tests size instrumented-only-expensive resources down. + MEDKIT_TEST_SANITIZED: 1 + # Tests the package's ctest runs at once. Sanitizer builds use more + # CPU and memory per test than Release ones. + CTEST_PARALLEL_LEVEL: 2 + run: | + if [ "${{ matrix.sanitizer }}" = "tsan" ]; then + TSAN_OPTIONS="halt_on_error=0:history_size=4:suppressions=$(pwd)/tsan_suppressions.txt" + export TSAN_OPTIONS + else + # detect_leaks=0: FastDDS allocator leaks on shutdown (not our code) + # new_delete_type_mismatch=0: ROS 2 DDS scalar/array new/delete mismatch + export ASAN_OPTIONS=halt_on_error=1:detect_leaks=0:new_delete_type_mismatch=0 + export UBSAN_OPTIONS=halt_on_error=1:print_stacktrace=1 + fi + source /opt/ros/jazzy/setup.bash + source install/setup.bash + cd build/ros2_medkit_fault_manager + ctest -LE "linter" --no-tests=error --output-on-failure + + - name: Show test results + if: always() + run: | + colcon test-result --test-result-base build/ros2_medkit_fault_manager \ + --verbose 2>/dev/null || true + # The one check branch rules require from this workflow. A matrix job skipped by # its `if` does not report its per-entry checks, so the rules cannot require them. # always(), not !cancelled(): a skipped gate would count as passed. clang-tidy # stays out: it is advisory. quality-ok: if: always() - needs: [changes, format-lint, sanitizer-asan, sanitizer-tsan, sanitizer-graph-watchdog] + needs: [changes, format-lint, sanitizer-asan, sanitizer-tsan, sanitizer-graph-watchdog, sanitizer-fault-manager] runs-on: ubuntu-latest timeout-minutes: 5 steps: diff --git a/src/ros2_medkit_fault_manager/CMakeLists.txt b/src/ros2_medkit_fault_manager/CMakeLists.txt index 08649ed0f..b82f4e734 100644 --- a/src/ros2_medkit_fault_manager/CMakeLists.txt +++ b/src/ros2_medkit_fault_manager/CMakeLists.txt @@ -278,6 +278,15 @@ endif() medkit_add_launch_test(test_rosbag_integration test/integration/test_rosbag_integration.test.py TIMEOUT 150 LABELS "integration") + # Rosbag retention pins: a real fault_manager_node, sized payloads, SQLite file. + medkit_add_launch_test(test_rosbag_quota test/integration/test_rosbag_quota.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") + endif() + # Launches without snapshots.rosbag.format, so the parameter default (mcap) # is what is under test rather than an operator's explicit choice. medkit_add_launch_test(test_rosbag_default_format test/integration/test_rosbag_default_format.test.py TIMEOUT 150 diff --git a/src/ros2_medkit_fault_manager/design/index.rst b/src/ros2_medkit_fault_manager/design/index.rst index 7f4031c32..cce9b5cfc 100644 --- a/src/ros2_medkit_fault_manager/design/index.rst +++ b/src/ros2_medkit_fault_manager/design/index.rst @@ -535,3 +535,21 @@ published, the writer is being created - directory creation plus a storage-backe Messages arriving in that interval take the buffering path rather than the new bag, so a post-fault-only recording can miss its first few milliseconds. They are not lost; they stay in the ring buffer and serve the next fault as pre-history. + +Rosbag storage primitive +"""""""""""""""""""""""" + +``FaultStorage::apply_rosbag_changes(RosbagChangeSet)`` changes the rosbag rows of every backend +in one transaction: ``insert`` upserts on ``(fault_code, file_path)``, ``remove`` drops links, and +``remove_recordings`` drops every link of a recording id. It applies no per-fault cap and never +unlinks a file. ``RosbagApplyResult::orphaned_paths`` lists each path whose last link the call +removed, once, so the caller decides what happens to the directory. A throw leaves every row as +it was: ``BEGIN IMMEDIATE`` in SQLite, one ``run_in_transaction`` in PostgreSQL, a copy swapped in +under the mutex in memory. + +A set must not insert and remove the same link, directly or through ``remove_recordings`` of an +inserted row's recording id. The call throws ``std::invalid_argument`` before it changes a row. +With that rule, applying a set twice leaves the same rows and the second call returns no +orphaned paths. + +Production code does not call it yet. The six existing rosbag mutators keep serving the node. diff --git a/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/fault_storage.hpp b/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/fault_storage.hpp index e82c01e9b..56d185398 100644 --- a/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/fault_storage.hpp +++ b/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/fault_storage.hpp @@ -194,6 +194,31 @@ struct RosbagFileInfo { int64_t created_at_ns{0}; ///< Timestamp when bag was created }; +/// One link between a fault and a recording: the unit a rosbag row stores. +struct RosbagLink { + std::string fault_code; + std::string file_path; +}; + +/// Rosbag row changes applied together by FaultStorage::apply_rosbag_changes(). +struct RosbagChangeSet { + std::vector insert; ///< Upsert on (fault_code, file_path) + std::vector remove; ///< Remove these links + std::vector remove_recordings; ///< Remove every link of these recording ids +}; + +/// What apply_rosbag_changes() reports back. +struct RosbagApplyResult { + /// Each path whose last link the call removed, once, in ascending order. A path another link + /// still references is not listed. The caller decides what to do with the directory. + std::vector orphaned_paths; +}; + +/// Check the precondition of FaultStorage::apply_rosbag_changes() the same way in every backend. +/// @throws std::invalid_argument when @p changes inserts and removes the same link, directly or +/// through remove_recordings of an inserted row's recording id +void check_rosbag_change_set(const RosbagChangeSet & changes); + /// Abstract interface for fault storage backends class FaultStorage { public: @@ -396,6 +421,18 @@ class FaultStorage { } } + /// Apply a set of rosbag row changes in one transaction. + /// + /// - All or nothing: when anything throws, no row has changed. + /// - Applies no per-fault cap. + /// - Never unlinks a file or a directory. orphaned_paths names the paths the caller may unlink. + /// - Precondition: the set never inserts and removes the same link, directly or through + /// remove_recordings of an inserted row's recording id. A violation throws + /// std::invalid_argument before any row changes. With it, applying a set twice leaves the + /// same rows and the second call returns no orphaned paths. + /// An empty recording id in remove_recordings matches nothing. + virtual RosbagApplyResult apply_rosbag_changes(const RosbagChangeSet & changes) = 0; + /// The MOST RECENT recording of a fault, or nullopt. /// /// A fault can hold several recordings, so "the" recording is a choice: newest @@ -530,6 +567,7 @@ class InMemoryFaultStorage : public FaultStorage { /// All-or-nothing, as the base class requires: the batch is built beside the live /// map and swapped in, so a throw leaves the store exactly as it was. void store_rosbag_files(const std::vector & infos) override; + RosbagApplyResult apply_rosbag_changes(const RosbagChangeSet & changes) override; std::optional get_rosbag_file(const std::string & fault_code) const override; std::vector get_rosbag_files(const std::string & fault_code) const override; std::vector get_rosbag_files_by_recording(const std::string & recording_id) const override; diff --git a/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/postgres_fault_storage.hpp b/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/postgres_fault_storage.hpp index 360082c63..78e231029 100644 --- a/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/postgres_fault_storage.hpp +++ b/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/postgres_fault_storage.hpp @@ -98,6 +98,7 @@ class PgFaultStorage : public FaultStorage { void store_rosbag_file(const RosbagFileInfo & info) override; void store_rosbag_files(const std::vector & infos) override; + RosbagApplyResult apply_rosbag_changes(const RosbagChangeSet & changes) override; std::optional get_rosbag_file(const std::string & fault_code) const override; std::vector get_rosbag_files(const std::string & fault_code) const override; std::vector get_rosbag_files_by_recording(const std::string & recording_id) const override; diff --git a/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/sqlite_fault_storage.hpp b/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/sqlite_fault_storage.hpp index 12fcd9b27..b69e829b8 100644 --- a/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/sqlite_fault_storage.hpp +++ b/src/ros2_medkit_fault_manager/include/ros2_medkit_fault_manager/sqlite_fault_storage.hpp @@ -85,6 +85,7 @@ class SqliteFaultStorage : public FaultStorage { void store_rosbag_file(const RosbagFileInfo & info) override; void store_rosbag_files(const std::vector & infos) override; + RosbagApplyResult apply_rosbag_changes(const RosbagChangeSet & changes) override; std::optional get_rosbag_file(const std::string & fault_code) const override; std::vector get_rosbag_files(const std::string & fault_code) const override; std::vector get_rosbag_files_by_recording(const std::string & recording_id) const override; diff --git a/src/ros2_medkit_fault_manager/package.xml b/src/ros2_medkit_fault_manager/package.xml index 5a5bcc4f2..61fbeb9ec 100644 --- a/src/ros2_medkit_fault_manager/package.xml +++ b/src/ros2_medkit_fault_manager/package.xml @@ -46,6 +46,7 @@ launch_testing_ament_cmake launch_testing_ros python3-pytest + python3-psycopg2 rosbag2_py rosbag2_storage_mcap rosbag2_storage_default_plugins diff --git a/src/ros2_medkit_fault_manager/src/fault_storage.cpp b/src/ros2_medkit_fault_manager/src/fault_storage.cpp index ceddfff19..24461f123 100644 --- a/src/ros2_medkit_fault_manager/src/fault_storage.cpp +++ b/src/ros2_medkit_fault_manager/src/fault_storage.cpp @@ -18,6 +18,7 @@ #include #include #include +#include #include namespace ros2_medkit_fault_manager { @@ -543,6 +544,26 @@ std::vector InMemoryFaultStorage::get_near_misses(const std::str return it->second; } +void check_rosbag_change_set(const RosbagChangeSet & changes) { + std::set> inserted_links; + std::set inserted_recordings; + for (const auto & in : changes.insert) { + inserted_links.emplace(in.fault_code, in.file_path); + inserted_recordings.insert(in.recording_id.empty() ? rosbag_recording_id(in.file_path) : in.recording_id); + } + for (const auto & link : changes.remove) { + if (inserted_links.count({link.fault_code, link.file_path}) != 0) { + throw std::invalid_argument("rosbag change set inserts and removes the link (" + link.fault_code + ", " + + link.file_path + ")"); + } + } + for (const auto & recording_id : changes.remove_recordings) { + if (inserted_recordings.count(recording_id) != 0) { + throw std::invalid_argument("rosbag change set inserts into and removes the recording " + recording_id); + } + } +} + void InMemoryFaultStorage::set_max_rosbags_per_fault(size_t max_count) { std::lock_guard lock(mutex_); max_rosbags_per_fault_ = max_count; @@ -636,6 +657,66 @@ void InMemoryFaultStorage::store_rosbag_files(const std::vector } } +RosbagApplyResult InMemoryFaultStorage::apply_rosbag_changes(const RosbagChangeSet & changes) { + check_rosbag_change_set(changes); + std::lock_guard lock(mutex_); + + // Built beside the live vector and swapped in, so a throw leaves the rows as they were. + auto updated = rosbag_files_; + uint64_t next_seq = rosbag_seq_; + std::set candidates; + + std::set> doomed_links; + for (const auto & link : changes.remove) { + doomed_links.emplace(link.fault_code, link.file_path); + } + std::set doomed_recordings; + for (const auto & id : changes.remove_recordings) { + if (!id.empty()) { + doomed_recordings.insert(id); + } + } + const auto is_doomed = [&](const RosbagRow & r) { + const bool by_link = doomed_links.count({r.info.fault_code, r.info.file_path}) != 0; + const bool by_recording = doomed_recordings.count(r.info.recording_id) != 0; + if (by_link || by_recording) { + candidates.insert(r.info.file_path); + return true; + } + return false; + }; + updated.erase(std::remove_if(updated.begin(), updated.end(), is_doomed), updated.end()); + + for (const auto & in : changes.insert) { + RosbagFileInfo row = in; + if (row.recording_id.empty()) { + row.recording_id = rosbag_recording_id(row.file_path); + } + auto it = std::find_if(updated.begin(), updated.end(), [&row](const RosbagRow & r) { + return r.info.fault_code == row.fault_code && r.info.file_path == row.file_path; + }); + if (it != updated.end()) { + it->info = row; + } else { + updated.push_back(RosbagRow{row, ++next_seq}); + } + } + + RosbagApplyResult result; + for (const auto & path : candidates) { + const bool referenced = std::any_of(updated.begin(), updated.end(), [&path](const RosbagRow & r) { + return r.info.file_path == path; + }); + if (!referenced) { + result.orphaned_paths.push_back(path); + } + } + + rosbag_files_.swap(updated); + rosbag_seq_ = next_seq; + return result; +} + std::optional InMemoryFaultStorage::get_rosbag_file(const std::string & fault_code) const { std::lock_guard lock(mutex_); diff --git a/src/ros2_medkit_fault_manager/src/postgres_fault_storage.cpp b/src/ros2_medkit_fault_manager/src/postgres_fault_storage.cpp index e130fbc7b..fa53b6c64 100644 --- a/src/ros2_medkit_fault_manager/src/postgres_fault_storage.cpp +++ b/src/ros2_medkit_fault_manager/src/postgres_fault_storage.cpp @@ -1157,6 +1157,53 @@ void PgFaultStorage::store_rosbag_files(const std::vector & info } } +RosbagApplyResult PgFaultStorage::apply_rosbag_changes(const RosbagChangeSet & changes) { + check_rosbag_change_set(changes); + std::lock_guard lock(mutex_); + + RosbagApplyResult result; + result.orphaned_paths = run_in_transaction("apply_rosbag_changes", [&](pqxx::work & tx) { + std::set candidates; + for (const auto & link : changes.remove) { + auto res = execute(tx, "DELETE FROM rosbag_files WHERE fault_code = $1 AND file_path = $2 RETURNING file_path", + link.fault_code, link.file_path); + for (const auto & r : res) { + candidates.insert(r["file_path"].as()); + } + } + for (const auto & recording_id : changes.remove_recordings) { + if (recording_id.empty()) { + continue; + } + auto res = execute(tx, "DELETE FROM rosbag_files WHERE recording_id = $1 RETURNING file_path", recording_id); + for (const auto & r : res) { + candidates.insert(r["file_path"].as()); + } + } + for (const auto & in : changes.insert) { + const std::string recording_id = in.recording_id.empty() ? rosbag_recording_id(in.file_path) : in.recording_id; + execute(tx, + "INSERT INTO rosbag_files " + "(fault_code, recording_id, file_path, format, duration_sec, size_bytes, created_at_ns) " + "VALUES ($1, $2, $3, $4, $5, $6, $7) " + "ON CONFLICT (fault_code, file_path) DO UPDATE SET " + "recording_id = EXCLUDED.recording_id, format = EXCLUDED.format, " + "duration_sec = EXCLUDED.duration_sec, size_bytes = EXCLUDED.size_bytes, " + "created_at_ns = EXCLUDED.created_at_ns", + in.fault_code, recording_id, in.file_path, in.format, in.duration_sec, + static_cast(in.size_bytes), in.created_at_ns); + } + std::vector orphaned; + for (const auto & path : candidates) { + if (execute(tx, "SELECT 1 FROM rosbag_files WHERE file_path = $1 LIMIT 1", path).empty()) { + orphaned.push_back(path); + } + } + return orphaned; + }); + return result; +} + std::vector PgFaultStorage::store_rosbag_file_locked(const RosbagFileInfo & info, pqxx::work & tx) { RosbagFileInfo row = info; if (row.recording_id.empty()) { diff --git a/src/ros2_medkit_fault_manager/src/sqlite_fault_storage.cpp b/src/ros2_medkit_fault_manager/src/sqlite_fault_storage.cpp index 29b2a23b1..8ec07d758 100644 --- a/src/ros2_medkit_fault_manager/src/sqlite_fault_storage.cpp +++ b/src/ros2_medkit_fault_manager/src/sqlite_fault_storage.cpp @@ -1471,6 +1471,78 @@ void SqliteFaultStorage::store_rosbag_files(const std::vector & } } +RosbagApplyResult SqliteFaultStorage::apply_rosbag_changes(const RosbagChangeSet & changes) { + check_rosbag_change_set(changes); + std::lock_guard lock(mutex_); + + RosbagApplyResult result; + exec_or_throw("BEGIN IMMEDIATE"); + try { + std::set candidates; + for (const auto & link : changes.remove) { + SqliteStatement del(db_, "DELETE FROM rosbag_files WHERE fault_code = ? AND file_path = ?"); + del.bind_text(1, link.fault_code); + del.bind_text(2, link.file_path); + if (del.step() != SQLITE_DONE) { + throw std::runtime_error(std::string("Failed to remove rosbag link: ") + sqlite3_errmsg(db_)); + } + if (sqlite3_changes(db_) > 0) { + candidates.insert(link.file_path); + } + } + for (const auto & recording_id : changes.remove_recordings) { + if (recording_id.empty()) { + continue; + } + { + SqliteStatement select(db_, "SELECT DISTINCT file_path FROM rosbag_files WHERE recording_id = ?"); + select.bind_text(1, recording_id); + while (select.step() == SQLITE_ROW) { + candidates.insert(select.column_text(0)); + } + } + SqliteStatement del(db_, "DELETE FROM rosbag_files WHERE recording_id = ?"); + del.bind_text(1, recording_id); + if (del.step() != SQLITE_DONE) { + throw std::runtime_error(std::string("Failed to remove rosbag recording: ") + sqlite3_errmsg(db_)); + } + } + for (const auto & in : changes.insert) { + const std::string recording_id = in.recording_id.empty() ? rosbag_recording_id(in.file_path) : in.recording_id; + SqliteStatement stmt(db_, + "INSERT INTO rosbag_files " + "(fault_code, recording_id, file_path, format, duration_sec, size_bytes, created_at_ns) " + "VALUES (?, ?, ?, ?, ?, ?, ?) " + "ON CONFLICT(fault_code, file_path) DO UPDATE SET " + "recording_id = excluded.recording_id, format = excluded.format, " + "duration_sec = excluded.duration_sec, size_bytes = excluded.size_bytes, " + "created_at_ns = excluded.created_at_ns"); + stmt.bind_text(1, in.fault_code); + stmt.bind_text(2, recording_id); + stmt.bind_text(3, in.file_path); + stmt.bind_text(4, in.format); + if (sqlite3_bind_double(stmt.get(), 5, in.duration_sec) != SQLITE_OK) { + throw std::runtime_error(std::string("Failed to bind duration_sec: ") + sqlite3_errmsg(db_)); + } + stmt.bind_int64(6, static_cast(in.size_bytes)); + stmt.bind_int64(7, in.created_at_ns); + if (stmt.step() != SQLITE_DONE) { + throw std::runtime_error(std::string("Failed to store rosbag file: ") + sqlite3_errmsg(db_)); + } + } + for (const auto & path : candidates) { + if (!path_referenced(path)) { + result.orphaned_paths.push_back(path); + } + } + exec_or_throw("COMMIT"); + } catch (...) { + sqlite3_exec(db_, "ROLLBACK", nullptr, nullptr, nullptr); + throw; + } + return result; +} + std::vector SqliteFaultStorage::store_rosbag_file_locked(const RosbagFileInfo & info) { RosbagFileInfo row = info; if (row.recording_id.empty()) { diff --git a/src/ros2_medkit_fault_manager/test/integration/rosbag_fm_harness.py b/src/ros2_medkit_fault_manager/test/integration/rosbag_fm_harness.py new file mode 100644 index 000000000..b1189a5be --- /dev/null +++ b/src/ros2_medkit_fault_manager/test/integration/rosbag_fm_harness.py @@ -0,0 +1,594 @@ +# Copyright 2026 bburda +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +Harness for the rosbag retention tests: a real fault_manager_node and a ROS client for it. + +The fault manager runs as its own process, started with debug logging, and its output is read on a +thread. A test waits on output lines or on polled service state, each with a deadline. +""" + +import contextlib +import ctypes +import os +import re +import shutil +import signal +import sqlite3 +import subprocess +import tempfile +import threading +import time +import unittest + +from ament_index_python.packages import get_package_prefix +from rcl_interfaces.msg import ParameterType +from rcl_interfaces.srv import GetParameters +import rclpy +from rclpy.duration import Duration +from rclpy.node import Node +from rclpy.qos import HistoryPolicy, QoSProfile, ReliabilityPolicy +from ros2_medkit_msgs.srv import ( + ClearFault, GetRosbag, ListFaults, ListFaultsForEntity, ListRosbags, ReportFault, +) +from std_msgs.msg import UInt8MultiArray + +MIB = 1024 * 1024 +KIB = 1024 +PAYLOAD_TOPIC = '/pin/payload' +SOURCE_ID = '/pin_node' +FM_NODE = 'fault_manager' +QOS_MATCH_PARAM = 'snapshots.rosbag.qos_match' +# prctl option: the kernel sends the child this signal when the test process dies. +PR_SET_PDEATHSIG = 1 + + +def time_scale(): + """Return MEDKIT_TEST_TIME_SCALE, or 1.0 when unset, unparseable or below 1.""" + try: + return max(1.0, float(os.environ.get('MEDKIT_TEST_TIME_SCALE', '1'))) + except ValueError: + return 1.0 + + +SCALE = time_scale() +STARTUP_TIMEOUT_SEC = 60.0 * SCALE +EVENT_TIMEOUT_SEC = 60.0 * SCALE +EXIT_TIMEOUT_SEC = 60.0 * SCALE +SERVICE_TIMEOUT_SEC = 30.0 * SCALE +# A read-only call is sent again after this long without an answer. +CALL_TRY_SEC = 5.0 * SCALE +# The probe after a start is sent again after this long without an answer. +PROBE_TRY_SEC = 2.0 * SCALE +# Lines of fault manager output a failed call's message carries. +FAILURE_TAIL_LINES = 60 +# Services whose handler changes no state: a call is sent again until answered. Any other request +# is sent once. +READ_ONLY_SERVICES = frozenset(('list_faults', 'get_parameters')) + + +def _die_with_parent(): + ctypes.CDLL('libc.so.6', use_errno=True).prctl(PR_SET_PDEATHSIG, signal.SIGKILL) + + +def _fm_binary(): + return os.path.join(get_package_prefix('ros2_medkit_fault_manager'), 'lib', + 'ros2_medkit_fault_manager', 'fault_manager_node') + + +def _ros_value(value): + if isinstance(value, bool): + return 'true' if value else 'false' + return str(value) + + +class FaultManager: + """A fault_manager_node process whose output lines are read on a thread.""" + + # The newest process, named in a failed call's message. + latest = None + + def __init__(self, params): + env = os.environ.copy() + env['RCUTILS_LOGGING_BUFFERED_STREAM'] = '0' + env['ROS_LOCALHOST_ONLY'] = '1' + try: + from ros2_medkit_test_utils.coverage import get_coverage_env + env.update(get_coverage_env()) + except ImportError: + pass + args = [_fm_binary(), '--ros-args', '--log-level', f'{FM_NODE}:=debug'] + for key, value in params.items(): + args += ['-p', f'{key}:={_ros_value(value)}'] + self.proc = subprocess.Popen( + args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, env=env, + preexec_fn=_die_with_parent) + FaultManager.latest = self + self.lines = [] + self._eof = False + self._seen = threading.Condition() + self._reader = threading.Thread(target=self._read, daemon=True) + self._reader.start() + + def _read(self): + for line in self.proc.stdout: + with self._seen: + self.lines.append(line) + self._seen.notify_all() + with self._seen: + self._eof = True + self._seen.notify_all() + + def mark(self): + """Return the index after the last line read, to search from later.""" + with self._seen: + return len(self.lines) + + def wait_line(self, pattern, since=0, timeout=None): + """Return the match of the first line from index `since` on, or None at the deadline.""" + regex = re.compile(pattern) + deadline = time.monotonic() + (EVENT_TIMEOUT_SEC if timeout is None else timeout) + index = since + with self._seen: + while True: + while index < len(self.lines): + match = regex.search(self.lines[index]) + index += 1 + if match: + return match + remaining = deadline - time.monotonic() + if remaining <= 0 or self._eof: + return None + self._seen.wait(remaining) + + def count_lines(self, pattern, since=0): + regex = re.compile(pattern) + with self._seen: + return sum(1 for line in self.lines[since:] if regex.search(line)) + + def tail(self, count): + with self._seen: + return ''.join(self.lines[-count:]) + + def output(self): + with self._seen: + return ''.join(self.lines) + + def wait_exit(self, timeout=None): + return self.proc.wait(timeout=EXIT_TIMEOUT_SEC if timeout is None else timeout) + + def terminate(self): + """SIGTERM the process and return its exit code.""" + if self.proc.poll() is None: + self.proc.send_signal(signal.SIGTERM) + code = self.wait_exit() + self._reader.join(timeout=10) + return code + + def kill(self): + if self.proc.poll() is None: + self.proc.kill() + self.proc.wait() + self._reader.join(timeout=10) + + +@contextlib.contextmanager +def running_fault_manager(params, wait_for_subscription=True): + """ + Start a fault manager, yield it once ready, end it with SIGTERM and assert exit code 0. + + A sanitizer report inside the process shows as a non-zero exit code. The body may end the + process itself (a SIGTERM inside it); the exit code is checked either way. + """ + fm = FaultManager(params) + try: + if fm.wait_line(r'FaultManager node started', timeout=STARTUP_TIMEOUT_SEC) is None: + raise AssertionError('the fault manager never started:\n' + fm.output()[-4000:]) + if wait_for_subscription and params.get('snapshots.rosbag.enabled'): + subscribed = f"Subscribed to '{PAYLOAD_TOPIC}'" + if fm.wait_line(subscribed, timeout=STARTUP_TIMEOUT_SEC) is None: + raise AssertionError('rosbag capture never subscribed:\n' + fm.output()[-4000:]) + yield fm + except BaseException: + fm.kill() + raise + code = fm.terminate() + if code != 0: + raise AssertionError(f'the fault manager exited with {code}:\n' + fm.output()[-4000:]) + + +class FaultManagerClient: + """The ROS side of a test: a payload publisher and clients of the fault manager services.""" + + def __init__(self, node_name): + self.node = Node(node_name) + qos = QoSProfile(reliability=ReliabilityPolicy.RELIABLE, history=HistoryPolicy.KEEP_LAST, + depth=500) + self.publisher = self.node.create_publisher(UInt8MultiArray, PAYLOAD_TOPIC, qos) + self._clients = {} + + def reset_clients(self): + """Drop the service clients so the next calls match a freshly started fault manager.""" + for client in self._clients.values(): + self.node.destroy_client(client) + self._clients = {} + + def destroy(self): + self.node.destroy_node() + + def _client(self, srv_type, name): + key = (srv_type, name) + if key not in self._clients: + self._clients[key] = self.node.create_client(srv_type, f'/{FM_NODE}/{name}') + return self._clients[key] + + def wait_for_services(self): + """ + Create a client for every service the tests call, then wait until the probe answers. + + Each side announces its endpoints in creation order and creates list_faults_for_entity + last. Once it answers, the fault manager matched each client and each client its server. + """ + for srv_type, name in ((ReportFault, 'report_fault'), (ClearFault, 'clear_fault'), + (GetRosbag, 'get_rosbag'), (ListRosbags, 'list_rosbags'), + (ListFaults, 'list_faults'), (GetParameters, 'get_parameters'), + (ListFaultsForEntity, 'list_faults_for_entity')): + client = self._client(srv_type, name) + if not client.wait_for_service(timeout_sec=SERVICE_TIMEOUT_SEC): + raise AssertionError(f'service {name} never appeared\n' + self.failure_context()) + # An empty entity_id is refused at once, with no storage read. + answer = self._send_until_answered( + self._client(ListFaultsForEntity, 'list_faults_for_entity'), + ListFaultsForEntity.Request(), PROBE_TRY_SEC, STARTUP_TIMEOUT_SEC) + if answer is None: + raise AssertionError('list_faults_for_entity never answered after the start\n' + + self.failure_context()) + + def failure_context(self): + """Describe the newest fault manager: its state, its output tail and the nodes seen.""" + nodes = sorted(ns.rstrip('/') + '/' + name + for name, ns in self.node.get_node_names_and_namespaces()) + fm = FaultManager.latest + if fm is None: + return f'no fault manager was started; nodes seen: {nodes}' + code = fm.proc.poll() + state = 'running' if code is None else f'exited with {code}' + return (f'fault manager pid {fm.proc.pid} {state}; nodes seen: {nodes}\n' + f'its last {FAILURE_TAIL_LINES} output lines:\n{fm.tail(FAILURE_TAIL_LINES)}') + + def _send_until_answered(self, client, request, try_sec, timeout_sec): + """Send `request` every `try_sec` until one send is answered; None at the deadline.""" + deadline = time.monotonic() + timeout_sec + resend_at = time.monotonic() + sent = [] + while True: + for future in sent: + if future.done(): + return future.result() + now = time.monotonic() + if now >= deadline: + return None + if now >= resend_at: + sent.append(client.call_async(request)) + resend_at = now + try_sec + rclpy.spin_once(self.node, timeout_sec=min(resend_at, deadline) - now) + + def _call(self, srv_type, name, request): + try_sec = CALL_TRY_SEC if name in READ_ONLY_SERVICES else SERVICE_TIMEOUT_SEC + answer = self._send_until_answered(self._client(srv_type, name), request, try_sec, + SERVICE_TIMEOUT_SEC) + if answer is None: + raise AssertionError(f'{name} did not answer\n' + self.failure_context()) + return answer + + def report(self, code): + request = ReportFault.Request() + request.fault_code = code + request.event_type = ReportFault.Request.EVENT_FAILED + request.severity = 2 + request.description = 'pin' + request.source_id = SOURCE_ID + return self._call(ReportFault, 'report_fault', request) + + def clear(self, code): + request = ClearFault.Request() + request.fault_code = code + return self._call(ClearFault, 'clear_fault', request) + + def get_rosbag(self, code='', recording_id=''): + request = GetRosbag.Request() + request.fault_code = code + request.recording_id = recording_id + return self._call(GetRosbag, 'get_rosbag', request) + + def list_rosbags(self, entity=SOURCE_ID): + request = ListRosbags.Request() + request.entity_fqn = entity + return self._call(ListRosbags, 'list_rosbags', request) + + def _wait_for_subscription_count(self, reached, what): + deadline = time.monotonic() + STARTUP_TIMEOUT_SEC + while not reached(self.publisher.get_subscription_count()): + if time.monotonic() > deadline: + raise AssertionError(what + PAYLOAD_TOPIC) + rclpy.spin_once(self.node, timeout_sec=0.1) + + def wait_for_payload_subscriber(self): + """Block until the fault manager's subscription on the payload topic is matched.""" + self._wait_for_subscription_count(lambda n: n > 0, + 'the fault manager never subscribed to ') + + def wait_for_no_payload_subscriber(self): + """ + Block until the subscription of an earlier fault manager is gone. + + A new fault manager is matched only once the old reader is unmatched, so a stale reader + cannot stand in for it and let messages go out before it is listening. + """ + self._wait_for_subscription_count(lambda n: n == 0, 'a subscriber stayed on ') + + def publish_bytes(self, count, size): + """ + Publish `count` messages of `size` random bytes; return once the fault manager took each. + + Each message is acknowledged, then followed by a service round trip to the fault manager. + Its single-threaded executor serves ready subscriptions before ready services of one wait + result and takes one message per subscription: rclcpp 28.1.22, src/rclcpp/executor.cpp, + Executor::get_next_ready_executable and Executor::execute_subscription. An acknowledged + message is ready before the request arrives, so its callback runs first. Without the round + trip a report can be served while two or more payload messages still wait. + + Holds while the capture's reader is reliable. With snapshots.rosbag.qos_match false the + capture subscribes best effort, the acknowledgement does not cover it, and the helper + refuses. + """ + # The fence assumes no concurrent publisher on the topic, a Ticker of this client included. + if not self.sync_with_fault_manager(): + raise AssertionError('publish_bytes() needs snapshots.rosbag.qos_match true: the ' + 'acknowledgement does not cover a best-effort capture reader') + wait = getattr(self.publisher, 'wait_for_all_acked', None) + for _ in range(count): + msg = UInt8MultiArray() + msg.data = list(os.urandom(size)) + self.publisher.publish(msg) + if wait is not None and not wait(Duration(seconds=SERVICE_TIMEOUT_SEC)): + raise AssertionError('the payload was not acknowledged by every reader') + self.sync_with_fault_manager() + + def sync_with_fault_manager(self): + """ + Return after one service round trip through the fault manager's executor. + + The round trip reads snapshots.rosbag.qos_match. False only when the parameter is false. + """ + client = self._client(GetParameters, 'get_parameters') + if not client.wait_for_service(timeout_sec=SERVICE_TIMEOUT_SEC): + raise AssertionError('service get_parameters never appeared') + request = GetParameters.Request() + request.names = [QOS_MATCH_PARAM] + values = self._call(GetParameters, 'get_parameters', request).values + return not (values and values[0].type == ParameterType.PARAMETER_BOOL + and not values[0].bool_value) + + +class Ticker: + """Publishes small messages on the payload topic from a thread until stopped.""" + + def __init__(self, client, period_sec=0.01, size=1024): + self._client = client + self._period = period_sec + self._size = size + self._stop = threading.Event() + self._thread = threading.Thread(target=self._run, daemon=True) + + def _run(self): + msg = UInt8MultiArray() + msg.data = list(os.urandom(self._size)) + while not self._stop.wait(self._period): + self._client.publisher.publish(msg) + + def __enter__(self): + self._thread.start() + return self + + def __exit__(self, *exc): + self._stop.set() + self._thread.join(timeout=10) + + +def poll(predicate, timeout=None, interval=0.05): + """Return True once `predicate()` is true, False at the deadline.""" + deadline = time.monotonic() + (EVENT_TIMEOUT_SEC if timeout is None else timeout) + waiter = threading.Event() + while True: + if predicate(): + return True + if time.monotonic() >= deadline: + return False + waiter.wait(interval) + + +def dir_size(path): + total = 0 + for root, _, files in os.walk(path): + for name in files: + total += os.path.getsize(os.path.join(root, name)) + return total + + +def bag_dirs(storage_path): + """Return the recording directories under the storage path, sorted by name.""" + if not os.path.isdir(storage_path): + return [] + return sorted(name for name in os.listdir(storage_path) + if os.path.isdir(os.path.join(storage_path, name))) + + +def storage_bytes(storage_path): + return sum(dir_size(os.path.join(storage_path, name)) for name in bag_dirs(storage_path)) + + +def sqlite_rows(db_path): + """Return (fault_code, file_path, size_bytes, created_at_ns) of every rosbag_files row.""" + conn = sqlite3.connect(db_path, timeout=30) + try: + return conn.execute( + 'SELECT fault_code, file_path, size_bytes, created_at_ns FROM rosbag_files ' + 'ORDER BY id').fetchall() + finally: + conn.close() + + +def sqlite_exec(db_path, sql, *args): + conn = sqlite3.connect(db_path, timeout=30) + try: + conn.execute(sql, args) + conn.commit() + finally: + conn.close() + + +def base_params(db_path, storage_path, **overrides): + """Parameters for a fault manager with rosbag capture on a SQLite file.""" + params = { + 'storage_type': 'sqlite', + 'database_path': db_path, + 'confirmation_threshold': -1, + 'snapshots.recapture_cooldown_sec': 0.0, + 'snapshots.rosbag.enabled': True, + 'snapshots.rosbag.topics': PAYLOAD_TOPIC, + 'snapshots.rosbag.format': 'mcap', + 'snapshots.rosbag.storage_path': storage_path, + 'snapshots.rosbag.duration_sec': 60.0, + 'snapshots.rosbag.duration_after_sec': 0.0, + 'snapshots.rosbag.lazy_start': False, + 'snapshots.rosbag.max_bag_size_mb': 50, + 'snapshots.rosbag.max_total_storage_mb': 500, + 'snapshots.rosbag.max_bags_per_fault': 1, + 'snapshots.rosbag.auto_cleanup': True, + } + params.update(overrides) + return params + + +MESSAGE_SIZE = 128 * KIB +# Payload bytes plus the mcap and metadata overhead a recording may carry. +SIZE_SLACK = 0.1 * MIB + + +class RetentionCase(unittest.TestCase): + """Base of the retention tests: ROS context, scratch directories and recording helpers.""" + + @classmethod + def setUpClass(cls): + os.environ['ROS_LOCALHOST_ONLY'] = '1' + rclpy.init() + cls.client = FaultManagerClient('rosbag_pin_client') + + @classmethod + def tearDownClass(cls): + cls.client.destroy() + rclpy.shutdown() + + def setUp(self): + self.new_scratch() + + def new_scratch(self): + """Start a fresh database file and bag directory, removed at the end of the test.""" + tmp = tempfile.mkdtemp(prefix='rosbag_pin_') + self.addCleanup(shutil.rmtree, tmp, True) + self.storage = os.path.join(tmp, 'bags') + self.db = os.path.join(tmp, 'faults.db') + + def storage_params(self): + return {'storage_type': 'sqlite', 'database_path': self.db} + + def stored_rows(self): + """Return (fault_code, file_path) of every stored rosbag row.""" + return [(code, path) for code, path, _, _ in sqlite_rows(self.db)] + + def row_paths(self, code): + return [path for row_code, path in self.stored_rows() if row_code == code] + + @contextlib.contextmanager + def fm_run(self, **overrides): + """Start a fault manager on this case's storage and yield it ready for faults.""" + params = base_params(self.db, self.storage, **overrides) + params.update(self.storage_params()) + self.client.reset_clients() + self.client.wait_for_no_payload_subscriber() + with running_fault_manager(params) as fm: + self.client.wait_for_services() + if params.get('snapshots.rosbag.enabled'): + self.client.wait_for_payload_subscriber() + yield fm + + def check_size(self, path, mib): + payload = int(mib * MIB) + actual = dir_size(path) + self.assertTrue(payload <= actual <= payload + SIZE_SLACK, + f'{path} holds {actual} bytes, expected {payload}' + f' plus at most {SIZE_SLACK}') + + def record(self, fm, code, mib, burst=()): + """ + Publish `mib` MiB, confirm `code` and `burst`, and return the bag path. + + The `burst` faults confirm inside the post-fault window of `code`. + """ + mark = fm.mark() + self.client.publish_bytes(int(mib * MIB) // MESSAGE_SIZE, MESSAGE_SIZE) + self.assertTrue(self.client.report(code).accepted) + if burst: + self.assertIsNotNone( + fm.wait_line(r'Recording [\d.]+s more after fault confirmation', since=mark), + 'the post-fault window never opened:\n' + fm.output()[-3000:]) + for other in burst: + self.assertTrue(self.client.report(other).accepted) + self.assertIsNotNone( + fm.wait_line(f"Fault '{other}' confirmed during post-fault recording", + since=mark), + f'{other} did not land inside the window:\n' + fm.output()[-3000:]) + done = fm.wait_line(rf'Bag file (?:created|completed): (\S*fault_{code}_\d+)', since=mark) + self.assertIsNotNone(done, f'no recording for {code}:\n' + fm.output()[-3000:]) + path = done.group(1) + self.assertTrue(os.path.isdir(path), f'{path} is not on disk') + self.check_size(path, mib) + return path + + def assert_recording_present(self, code, path): + self.assertTrue(os.path.isdir(path), f'{path} is gone') + self.assertIn(path, self.row_paths(code), f'{code} has no row for {path}') + served = self.client.get_rosbag(code) + self.assertTrue(served.success, f'GetRosbag({code}) failed: {served.error_message}') + + def assert_recording_gone(self, code, path): + self.assertFalse(os.path.exists(path), f'{path} is still on disk') + self.assertNotIn(path, self.row_paths(code), f'{code} still has a row for {path}') + + def check_quota_evicts_oldest_first(self): + """Five recordings fit a quota for three: the two oldest go, by time and not by name.""" + quota_mib = 7 + order = ['FAULT_E', 'FAULT_A', 'FAULT_D', 'FAULT_B', 'FAULT_C'] + with self.fm_run(**{'snapshots.rosbag.max_bags_per_fault': 0, + 'snapshots.rosbag.max_total_storage_mb': quota_mib}) as fm: + paths = {code: self.record(fm, code, 2) for code in order} + for code in order[:2]: + self.assert_recording_gone(code, paths[code]) + self.assertFalse(self.client.get_rosbag(code).success) + for code in order[2:]: + self.assert_recording_present(code, paths[code]) + self.assertLessEqual(storage_bytes(self.storage), quota_mib * MIB) + self.assertEqual(sorted(bag_dirs(self.storage)), + sorted(os.path.basename(paths[code]) for code in order[2:])) diff --git a/src/ros2_medkit_fault_manager/test/integration/test_rosbag_quota.test.py b/src/ros2_medkit_fault_manager/test/integration/test_rosbag_quota.test.py new file mode 100644 index 000000000..e8d2d4d5f --- /dev/null +++ b/src/ros2_medkit_fault_manager/test/integration/test_rosbag_quota.test.py @@ -0,0 +1,333 @@ +#!/usr/bin/env python3 +# Copyright 2026 bburda +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +Rosbag retention against a real fault_manager_node on a SQLite file. + +Each test starts the fault manager as its own process, feeds it sized payloads, confirms faults +over the ROS services and reads the outcome from the services, the database file and the bag +directory. A run ends with SIGTERM and an exit code of 0. +""" + +import os +import pathlib +import shutil +import sys + +from launch import LaunchDescription +import launch_testing +import launch_testing.actions +import launch_testing.util + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) + +from rosbag_fm_harness import ( # noqa: E402 + bag_dirs, MIB, poll, RetentionCase, sqlite_exec, Ticker, +) + +RACE_REPETITIONS = 50 +DISCARDED_BEFORE_STORE = 'Bag file discarded (all its faults cleared before it was stored)' +FUTURE_NS = 4_000_000_000 * 1_000_000_000 + + +def generate_test_description(): + return LaunchDescription([launch_testing.util.KeepAliveProc(), + launch_testing.actions.ReadyToTest()]), {} + + +class TestRosbagQuota(RetentionCase): + + def test_quota_evicts_oldest_first(self): + self.check_quota_evicts_oldest_first() + + def test_burst_shared_recording(self): + """A recording shared by two faults counts once towards the quota and is evicted whole.""" + with self.fm_run(**{'snapshots.rosbag.max_bags_per_fault': 0, + 'snapshots.rosbag.max_total_storage_mb': 7, + 'snapshots.rosbag.duration_after_sec': 5.0}) as fm: + burst = self.record(fm, 'BURST_A', 2, burst=('BURST_B',)) + self.assertEqual(bag_dirs(self.storage), [os.path.basename(burst)]) + self.assertEqual(sorted(self.stored_rows()), + [('BURST_A', burst), ('BURST_B', burst)]) + + # Counted twice the burst plus two more recordings would be 8 MiB and over the quota. + self.record(fm, 'FILL_1', 2) + self.record(fm, 'FILL_2', 2) + self.assert_recording_present('BURST_A', burst) + self.assert_recording_present('BURST_B', burst) + + self.record(fm, 'FILL_3', 2) + self.assert_recording_gone('BURST_A', burst) + self.assert_recording_gone('BURST_B', burst) + self.assertEqual([code for code, _ in self.stored_rows()], + ['FILL_1', 'FILL_2', 'FILL_3']) + + def test_oversized_recording_kept(self): + """A recording larger than the quota evicts everything older and is kept itself.""" + with self.fm_run(**{'snapshots.rosbag.max_bags_per_fault': 0, + 'snapshots.rosbag.max_total_storage_mb': 3}) as fm: + older = {code: self.record(fm, code, 1) for code in ('OLD_A', 'OLD_B')} + mark = fm.mark() + big = self.record(fm, 'BIG', 4) + self.assertIsNotNone( + fm.wait_line(r'alone exceeds snapshots\.rosbag\.max_total_storage_mb \(3 MB\)', + since=mark), + 'no warning for the oversized recording:\n' + fm.output()[-3000:]) + for code, path in older.items(): + self.assert_recording_gone(code, path) + self.assert_recording_present('BIG', big) + + def test_cap_and_quota_together(self): + """The cap runs with the insert; the quota then sweeps what is left, oldest first.""" + params = {'snapshots.rosbag.max_bags_per_fault': 1, + 'snapshots.rosbag.max_total_storage_mb': 5, + 'snapshots.rosbag.auto_cleanup': False} + + with self.subTest('a: the cap frees the old recording before the quota counts'): + self.new_scratch() + with self.fm_run(**params) as fm: + b = self.record(fm, 'CQ_B', 1) + a_old = self.record(fm, 'CQ_A', 1.5) + c = self.record(fm, 'CQ_C', 1.5) + self.client.clear('CQ_A') + a_new = self.record(fm, 'CQ_A', 1.5) + self.assert_recording_gone('CQ_A', a_old) + self.assert_recording_present('CQ_A', a_new) + self.assert_recording_present('CQ_B', b) + self.assert_recording_present('CQ_C', c) + + with self.subTest('b: a bigger replacement pushes the oldest other recording out'): + self.new_scratch() + with self.fm_run(**params) as fm: + a_old = self.record(fm, 'CQ_A', 1.5) + b = self.record(fm, 'CQ_B', 1.5) + c = self.record(fm, 'CQ_C', 1.5) + self.client.clear('CQ_A') + a_new = self.record(fm, 'CQ_A', 3) + self.assert_recording_gone('CQ_A', a_old) + self.assert_recording_present('CQ_A', a_new) + self.assert_recording_gone('CQ_B', b) + self.assert_recording_present('CQ_C', c) + + with self.subTest('c: the cap leaves a burst a sibling holds, the quota evicts it whole'): + self.new_scratch() + with self.fm_run(**{**params, 'snapshots.rosbag.duration_after_sec': 3.0}) as fm: + burst = self.record(fm, 'CQ_A', 1.5, burst=('CQ_X',)) + b = self.record(fm, 'CQ_B', 1.5) + c = self.record(fm, 'CQ_C', 1.5) + self.client.clear('CQ_A') + a_new = self.record(fm, 'CQ_A', 1.5) + self.assert_recording_gone('CQ_A', burst) + self.assert_recording_gone('CQ_X', burst) + self.assert_recording_present('CQ_A', a_new) + self.assert_recording_present('CQ_B', b) + self.assert_recording_present('CQ_C', c) + + def _seed_future_row(self, code): + sqlite_exec(self.db, 'UPDATE rosbag_files SET created_at_ns = ? WHERE fault_code = ?', + FUTURE_NS, code) + + def test_new_recording_loses_the_cap(self): + """The cap keeps the newest row by timestamp, so a new recording can lose to an old one.""" + params = {'snapshots.rosbag.max_bags_per_fault': 1, 'snapshots.rosbag.auto_cleanup': False} + + with self.subTest('plain'): + self.new_scratch() + with self.fm_run(**params) as fm: + seeded = self.record(fm, 'LOSE_A', 1) + self._seed_future_row('LOSE_A') + with self.fm_run(**params) as fm: + self.client.clear('LOSE_A') + mark = fm.mark() + self.client.publish_bytes(8, 128 * 1024) + self.assertTrue(self.client.report('LOSE_A').accepted) + done = fm.wait_line(r'Bag file (?:created|completed): (\S*fault_LOSE_A_\d+)', + since=mark) + self.assertIsNotNone(done, fm.output()[-3000:]) + fresh = done.group(1) + self.assertNotEqual(fresh, seeded) + self.assertTrue(poll(lambda: not os.path.exists(fresh)), f'{fresh} was kept') + self.assertEqual(self.stored_rows(), [('LOSE_A', seeded)]) + self.assertEqual(bag_dirs(self.storage), [os.path.basename(seeded)]) + + with self.subTest('burst'): + self.new_scratch() + with self.fm_run(**params) as fm: + seeded = self.record(fm, 'LOSE_A', 1) + self._seed_future_row('LOSE_A') + with self.fm_run(**{**params, 'snapshots.rosbag.duration_after_sec': 3.0}) as fm: + self.client.clear('LOSE_A') + fresh = self.record(fm, 'LOSE_A', 1, burst=('LOSE_X',)) + self.assertNotEqual(fresh, seeded) + self.assertEqual(sorted(self.stored_rows()), + [('LOSE_A', seeded), ('LOSE_X', fresh)]) + self.assertEqual(sorted(bag_dirs(self.storage)), + sorted([os.path.basename(seeded), os.path.basename(fresh)])) + + def _trigger(self, name, event, code=None): + row = 'NEW' if event == 'INSERT' else 'OLD' + condition = f" WHEN {row}.fault_code = '{code}'" if code else '' + sqlite_exec(self.db, + f'CREATE TRIGGER {name} BEFORE {event} ON rosbag_files{condition} ' + f"BEGIN SELECT RAISE(ABORT, 'pinned failure'); END") + + def _confirm_expecting_failure(self, fm, code, mib, post_roll=False): + mark = fm.mark() + self.client.publish_bytes(int(mib * MIB) // (128 * 1024), 128 * 1024) + self.assertTrue(self.client.report(code).accepted) + if post_roll: + self.assertIsNotNone( + fm.wait_line(r'Recording [\d.]+s more after fault confirmation', since=mark), + 'the post-fault window never opened:\n' + fm.output()[-3000:]) + failed = fm.wait_line(rf"Failed to store rosbag metadata for '(\S*fault_{code}_\d+)'", + since=mark) + self.assertIsNotNone(failed, fm.output()[-3000:]) + stored = rf'Bag file (?:created|completed): \S*fault_{code}_\d+' + self.assertEqual(fm.count_lines(stored, since=mark), 0) + return failed.group(1) + + def test_store_failures(self): + """A failing store discards the new bag; a failing quota sweep keeps it.""" + with self.subTest('i: insert fails, bag discarded, no post-roll'): + self.new_scratch() + with self.fm_run() as fm: + self._trigger('fail_insert', 'INSERT') + bag = self._confirm_expecting_failure(fm, 'STORE_A', 1) + self.assertFalse(os.path.exists(bag)) + self.assertEqual(self.stored_rows(), []) + self.assertEqual(bag_dirs(self.storage), []) + + with self.subTest('i: insert fails, bag discarded, post-roll'): + self.new_scratch() + with self.fm_run(**{'snapshots.rosbag.duration_after_sec': 1.0}) as fm: + self._trigger('fail_insert', 'INSERT') + bag = self._confirm_expecting_failure(fm, 'STORE_A', 1, post_roll=True) + self.assertFalse(os.path.exists(bag)) + self.assertEqual(self.stored_rows(), []) + self.assertEqual(bag_dirs(self.storage), []) + + with self.subTest('ii: the cap cannot delete, the store fails, the new bag is discarded'): + self.new_scratch() + with self.fm_run(**{'snapshots.rosbag.auto_cleanup': False}) as fm: + kept = self.record(fm, 'STORE_A', 1) + self.client.clear('STORE_A') + self._trigger('fail_delete', 'DELETE') + bag = self._confirm_expecting_failure(fm, 'STORE_A', 1) + self.assertNotEqual(bag, kept) + self.assertFalse(os.path.exists(bag)) + self.assertEqual(self.stored_rows(), [('STORE_A', kept)]) + self.assertEqual(bag_dirs(self.storage), [os.path.basename(kept)]) + + with self.subTest('iii: the quota sweep cannot delete, the new bag and its row are kept'): + self.new_scratch() + with self.fm_run(**{'snapshots.rosbag.max_bags_per_fault': 0, + 'snapshots.rosbag.max_total_storage_mb': 3}) as fm: + first = self.record(fm, 'STORE_A', 2) + self._trigger('fail_delete', 'DELETE') + mark = fm.mark() + second = self.record(fm, 'STORE_B', 2) + self.assertIsNotNone( + fm.wait_line(r'Failed to enforce the rosbag storage limit after storing ' + r"'\S*fault_STORE_B_\d+'", since=mark), + fm.output()[-3000:]) + self.assert_recording_present('STORE_B', second) + self.assert_recording_present('STORE_A', first) + + def _race(self, **overrides): + """Confirm and clear fault after fault; none may keep a row or a directory.""" + discarded = 0 + no_data = 0 + with self.fm_run(**overrides) as fm, Ticker(self.client): + for i in range(RACE_REPETITIONS): + code = f'RACE_{i}' + mark = fm.mark() + self.assertTrue(self.client.report(code).accepted) + self.assertTrue(self.client.clear(code).success) + outcome = fm.wait_line( + rf'Bag file (?:created|completed|discarded)[^\n]*?(\S*fault_{code}_\d+)' + rf"|No data buffered for fault '{code}'", since=mark) + self.assertIsNotNone(outcome, f'no outcome for {code}:\n' + fm.output()[-3000:]) + if outcome.group(1) is None: + no_data += 1 # the ring buffer was empty at the confirm + continue + bag = outcome.group(1) + if DISCARDED_BEFORE_STORE in outcome.group(0): + discarded += 1 + self.assertFalse(self.client.get_rosbag(code).success) + self.assertEqual(self.row_paths(code), []) + self.assertTrue(poll(lambda: not os.path.exists(bag)), + f'{bag} was kept for {code}') + return discarded, no_data + + def test_clear_racing_store(self): + """A fault cleared right after it confirms leaves neither a row nor a directory.""" + with self.subTest('inline store'): + self.new_scratch() + discarded, _ = self._race(**{'snapshots.rosbag.duration_after_sec': 0.0}) + self.assertGreater(discarded, 0, + 'no clear landed before the store, so the discard path never ran') + with self.subTest('post-roll store'): + self.new_scratch() + _, no_data = self._race(**{'snapshots.rosbag.duration_after_sec': 0.3}) + self.assertEqual(no_data, 0, 'a post-roll confirm always opens a recording') + + def test_shutdown_during_post_roll(self): + """SIGTERM inside the post-fault window keeps the recording, with its row.""" + with self.fm_run(**{'snapshots.rosbag.duration_after_sec': 30.0}) as fm: + mark = fm.mark() + self.client.publish_bytes(8, 128 * 1024) + self.assertTrue(self.client.report('SHUT_A').accepted) + self.assertIsNotNone( + fm.wait_line(r'Recording [\d.]+s more after fault confirmation', since=mark)) + self.assertEqual(fm.terminate(), 0, fm.output()[-3000:]) + self.assertEqual(len(bag_dirs(self.storage)), 1) + with self.fm_run(**{'snapshots.rosbag.duration_after_sec': 30.0}): + served = self.client.get_rosbag('SHUT_A') + self.assertTrue(served.success, served.error_message) + self.assertTrue(os.path.isdir(served.file_path)) + self.assertEqual([code for code, _ in self.stored_rows()], ['SHUT_A']) + + def test_shutdown_right_after_clear(self): + """SIGTERM as soon as ClearFault returns leaves no directory and a clean exit.""" + with self.fm_run() as fm: + bag = self.record(fm, 'SHUT_B', 4) + self.assertTrue(self.client.clear('SHUT_B').success) + self.assertEqual(fm.terminate(), 0, fm.output()[-3000:]) + self.assertFalse(os.path.exists(bag)) + self.assertEqual(bag_dirs(self.storage), []) + + def test_stale_rows(self): + """A row whose directory is gone is reaped on the next listing, with rosbag on or off.""" + with self.subTest('rosbag off on the next run'): + self.new_scratch() + with self.fm_run() as fm: + bag = self.record(fm, 'STALE_A', 1) + shutil.rmtree(bag) + self.assertEqual(self.row_paths('STALE_A'), [bag]) + with self.fm_run(**{'snapshots.rosbag.enabled': False}): + listed = self.client.list_rosbags() + self.assertTrue(listed.success, listed.error_message) + self.assertEqual(list(listed.fault_codes), []) + self.assertEqual(self.stored_rows(), []) + + with self.subTest('rosbag on, directory removed while running'): + self.new_scratch() + with self.fm_run() as fm: + bag = self.record(fm, 'STALE_A', 1) + shutil.rmtree(bag) + served = self.client.get_rosbag('STALE_A') + self.assertFalse(served.success) + self.assertIn('not found on disk', served.error_message) + self.assertEqual(self.stored_rows(), []) diff --git a/src/ros2_medkit_fault_manager/test/integration/test_rosbag_quota_pg.test.py b/src/ros2_medkit_fault_manager/test/integration/test_rosbag_quota_pg.test.py new file mode 100644 index 000000000..9dc827288 --- /dev/null +++ b/src/ros2_medkit_fault_manager/test/integration/test_rosbag_quota_pg.test.py @@ -0,0 +1,89 @@ +#!/usr/bin/env python3 +# Copyright 2026 bburda +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +Rosbag retention against a real fault_manager_node on a real PostgreSQL server. + +ROS2_MEDKIT_TEST_PG_CONN names the server, as `postgresql://user:password@host:port/database`. +Each test creates its own database on it. An unreachable server fails the test. +""" + +import os +import pathlib +import sys +import urllib.parse +import uuid + +from launch import LaunchDescription +import launch_testing +import launch_testing.actions +import launch_testing.util +import psycopg2 + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) + +from rosbag_fm_harness import bag_dirs, RetentionCase # noqa: E402 + + +def generate_test_description(): + return LaunchDescription([launch_testing.util.KeepAliveProc(), + launch_testing.actions.ReadyToTest()]), {} + + +class TestRosbagQuotaPostgres(RetentionCase): + + def setUp(self): + super().setUp() + base = os.environ.get('ROS2_MEDKIT_TEST_PG_CONN') + self.assertTrue(base, 'ROS2_MEDKIT_TEST_PG_CONN is not set') + self.admin_url = base + self.database = 'rosbag_pin_' + uuid.uuid4().hex[:12] + self._admin('CREATE DATABASE ' + self.database) + self.addCleanup(self._admin, f'DROP DATABASE IF EXISTS {self.database} WITH (FORCE)') + parts = urllib.parse.urlsplit(base) + self.url = urllib.parse.urlunsplit(parts._replace(path='/' + self.database)) + + def _admin(self, statement): + conn = psycopg2.connect(self.admin_url) + try: + conn.autocommit = True + with conn.cursor() as cur: + cur.execute(statement) + finally: + conn.close() + + def storage_params(self): + return {'storage_type': 'postgres', 'database_url': self.url} + + def stored_rows(self): + conn = psycopg2.connect(self.url) + try: + with conn.cursor() as cur: + cur.execute('SELECT fault_code, file_path FROM rosbag_files ORDER BY id') + return cur.fetchall() + finally: + conn.close() + + def test_quota_evicts_oldest_first(self): + self.check_quota_evicts_oldest_first() + + def test_clear_removes_the_row_and_the_directory(self): + with self.fm_run() as fm: + bag = self.record(fm, 'PG_A', 1) + self.assert_recording_present('PG_A', bag) + self.assertTrue(self.client.clear('PG_A').success) + self.assert_recording_gone('PG_A', bag) + self.assertEqual(self.stored_rows(), []) + self.assertEqual(bag_dirs(self.storage), []) diff --git a/src/ros2_medkit_fault_manager/test/test_rosbag_storage_parity.cpp b/src/ros2_medkit_fault_manager/test/test_rosbag_storage_parity.cpp index 7cb06c262..cb5c2f854 100644 --- a/src/ros2_medkit_fault_manager/test/test_rosbag_storage_parity.cpp +++ b/src/ros2_medkit_fault_manager/test/test_rosbag_storage_parity.cpp @@ -27,17 +27,27 @@ #include +#include + #include #include #include #include #include +#include #include #include +#ifdef POSTGRES_SUPPORT +#include +#endif + #include "rclcpp/rclcpp.hpp" #include "ros2_medkit_fault_manager/fault_storage.hpp" #include "ros2_medkit_fault_manager/sqlite_fault_storage.hpp" +#ifdef POSTGRES_SUPPORT +#include "ros2_medkit_fault_manager/postgres_fault_storage.hpp" +#endif #include "ros2_medkit_msgs/msg/fault.hpp" #include "ros2_medkit_msgs/srv/report_fault.hpp" #include "test_log_sink.hpp" @@ -47,9 +57,15 @@ namespace { using ros2_medkit_fault_manager::FaultStorage; using ros2_medkit_fault_manager::InMemoryFaultStorage; using ros2_medkit_fault_manager::rosbag_recording_id; +using ros2_medkit_fault_manager::RosbagApplyResult; +using ros2_medkit_fault_manager::RosbagChangeSet; using ros2_medkit_fault_manager::RosbagFileInfo; +using ros2_medkit_fault_manager::RosbagLink; using ros2_medkit_fault_manager::SnapshotData; using ros2_medkit_fault_manager::SqliteFaultStorage; +#ifdef POSTGRES_SUPPORT +using ros2_medkit_fault_manager::PgFaultStorage; +#endif /// Backends differ only in how they are constructed, so the fixture reaches them /// through this rather than through #ifdef-style branching inside the test bodies. @@ -61,6 +77,8 @@ struct BackendFactory { static std::unique_ptr make(const std::filesystem::path & /*dir*/) { return std::make_unique(); } + static void cleanup(const std::filesystem::path & /*dir*/) { + } }; template <> @@ -68,7 +86,92 @@ struct BackendFactory { static std::unique_ptr make(const std::filesystem::path & dir) { return std::make_unique((dir / "parity.db").string(), test_log_sink()); } + static void cleanup(const std::filesystem::path & /*dir*/) { + } + + /// A trigger that raises on every INSERT or DELETE of a row of `fault_code`. + static void add_failing_trigger(const std::filesystem::path & dir, const std::string & event, + const std::string & fault_code) { + const std::string row = event == "INSERT" ? "NEW" : "OLD"; + const std::string when = row + ".fault_code = '" + fault_code + "'"; + exec(dir, "CREATE TRIGGER fail_" + event + " BEFORE " + event + " ON rosbag_files WHEN " + when + + " BEGIN SELECT RAISE(ABORT, 'forced failure'); END"); + } + + static void exec(const std::filesystem::path & dir, const std::string & sql) { + sqlite3 * db = nullptr; + ASSERT_EQ(sqlite3_open((dir / "parity.db").c_str(), &db), SQLITE_OK); + char * err = nullptr; + const int rc = sqlite3_exec(db, sql.c_str(), nullptr, nullptr, &err); + const std::string message = err ? err : ""; + sqlite3_free(err); + sqlite3_close(db); + ASSERT_EQ(rc, SQLITE_OK) << message; + } +}; + +#ifdef POSTGRES_SUPPORT +/// One schema per test on the server named by ROS2_MEDKIT_TEST_PG_CONN, as test_postgres_storage does. +template <> +struct BackendFactory { + static std::string base_conn_info() { + if (const char * env = std::getenv("ROS2_MEDKIT_TEST_PG_CONN")) { + return env; + } + return "postgresql://user:password@localhost:5432/ros2_medkit_faults_database"; + } + + static std::string schema_of(const std::filesystem::path & dir) { + return "parity_" + dir.filename().string(); + } + + static std::string conn_info(const std::filesystem::path & dir) { + return base_conn_info() + "?options=-csearch_path%3D" + schema_of(dir); + } + + static std::unique_ptr make(const std::filesystem::path & dir) { + try { + pqxx::connection conn(base_conn_info()); + pqxx::work tx(conn); + tx.exec("CREATE SCHEMA " + tx.quote_name(schema_of(dir))); + tx.commit(); + } catch (const std::exception & e) { + ADD_FAILURE() << "No PostgreSQL server reachable (set ROS2_MEDKIT_TEST_PG_CONN): " << e.what(); + return nullptr; + } + return std::make_unique(conn_info(dir), test_log_sink()); + } + + static void cleanup(const std::filesystem::path & dir) { + try { + pqxx::connection conn(base_conn_info()); + pqxx::work tx(conn); + tx.exec("DROP SCHEMA IF EXISTS " + tx.quote_name(schema_of(dir)) + " CASCADE"); + tx.commit(); + } catch (const std::exception &) { + // The server is gone; nothing is left to drop. + } + } + + static void add_failing_trigger(const std::filesystem::path & dir, const std::string & event, + const std::string & fault_code) { + const std::string row = event == "INSERT" ? "NEW" : "OLD"; + const std::string name = "fail_" + event; + const std::string when = row + ".fault_code = '" + fault_code + "'"; + exec(dir, "CREATE FUNCTION " + name + + "_fn() RETURNS trigger AS $$ BEGIN RAISE EXCEPTION 'forced failure'; END $$ LANGUAGE plpgsql"); + exec(dir, "CREATE TRIGGER " + name + " BEFORE " + event + " ON rosbag_files FOR EACH ROW WHEN (" + when + + ") EXECUTE FUNCTION " + name + "_fn()"); + } + + static void exec(const std::filesystem::path & dir, const std::string & sql) { + pqxx::connection conn(conn_info(dir)); + pqxx::work tx(conn); + tx.exec(sql); + tx.commit(); + } }; +#endif template class RosbagRetentionParityTest : public ::testing::Test { @@ -79,10 +182,12 @@ class RosbagRetentionParityTest : public ::testing::Test { std::filesystem::remove_all(dir_); std::filesystem::create_directories(dir_); storage_ = BackendFactory::make(dir_); + ASSERT_NE(storage_, nullptr); } void TearDown() override { storage_.reset(); + BackendFactory::cleanup(dir_); std::error_code ec; std::filesystem::remove_all(dir_, ec); } @@ -112,7 +217,13 @@ class RosbagRetentionParityTest : public ::testing::Test { std::unique_ptr storage_; }; +#ifdef POSTGRES_SUPPORT +using Backends = ::testing::Types; +using SqlBackends = ::testing::Types; +#else using Backends = ::testing::Types; +using SqlBackends = ::testing::Types; +#endif TYPED_TEST_SUITE(RosbagRetentionParityTest, Backends); TYPED_TEST(RosbagRetentionParityTest, RecordingIdIsTheBasenameOfEveryStoredRow) { @@ -393,6 +504,247 @@ TYPED_TEST(RosbagRetentionParityTest, GetAllRosbagFilesListsEveryRecordingOldest EXPECT_EQ(rows[2].recording_id, "fault_ALL_1"); } +// apply_rosbag_changes: the one write primitive. Same body over every backend. + +TYPED_TEST(RosbagRetentionParityTest, ApplyTwiceIsIdempotent) { + const auto a = this->row("TWICE_A", "fault_TWICE_1", 1000); + const auto b = this->row("TWICE_B", "fault_TWICE_2", 2000); + this->storage_->set_max_rosbags_per_fault(0); + this->storage_->store_rosbag_file(a); + this->storage_->store_rosbag_file(b); + + RosbagChangeSet set; + set.insert.push_back(this->row("TWICE_C", "fault_TWICE_3", 3000)); + set.remove.push_back({"TWICE_A", a.file_path}); + + const auto first = this->storage_->apply_rosbag_changes(set); + EXPECT_EQ(first.orphaned_paths, std::vector{a.file_path}); + const auto after_first = this->storage_->get_all_rosbag_files(); + + const auto second = this->storage_->apply_rosbag_changes(set); + EXPECT_TRUE(second.orphaned_paths.empty()); + const auto after_second = this->storage_->get_all_rosbag_files(); + + ASSERT_EQ(after_first.size(), 2u); + ASSERT_EQ(after_second.size(), after_first.size()); + for (size_t i = 0; i < after_first.size(); ++i) { + EXPECT_EQ(after_second[i].fault_code, after_first[i].fault_code); + EXPECT_EQ(after_second[i].file_path, after_first[i].file_path); + EXPECT_EQ(after_second[i].size_bytes, after_first[i].size_bytes); + EXPECT_EQ(after_second[i].created_at_ns, after_first[i].created_at_ns); + } +} + +TYPED_TEST(RosbagRetentionParityTest, OrphanedPathOnlyWhenLastLinkRemoved) { + this->storage_->set_max_rosbags_per_fault(0); + auto shared = this->row("ORPHAN_A", "fault_ORPHAN_1", 1000); + this->storage_->store_rosbag_file(shared); + shared.fault_code = "ORPHAN_B"; + this->storage_->store_rosbag_file(shared); + + RosbagChangeSet first; + first.remove.push_back({"ORPHAN_A", shared.file_path}); + EXPECT_TRUE(this->storage_->apply_rosbag_changes(first).orphaned_paths.empty()) + << "ORPHAN_B still references the bag"; + + RosbagChangeSet unknown; + unknown.remove.push_back({"ORPHAN_NONE", shared.file_path}); + unknown.remove.push_back({"ORPHAN_B", "/no/such/bag"}); + EXPECT_TRUE(this->storage_->apply_rosbag_changes(unknown).orphaned_paths.empty()) + << "a link that was not there frees nothing"; + + RosbagChangeSet last; + last.remove.push_back({"ORPHAN_B", shared.file_path}); + last.remove.push_back({"ORPHAN_B", shared.file_path}); + EXPECT_EQ(this->storage_->apply_rosbag_changes(last).orphaned_paths, std::vector{shared.file_path}) + << "listed once, however often the set names the link"; +} + +TYPED_TEST(RosbagRetentionParityTest, ASetThatMovesTheLastLinkToAnotherFaultOrphansNothing) { + this->storage_->set_max_rosbags_per_fault(0); + const auto old_link = this->row("MOVE_A", "fault_MOVE_1", 1000); + this->storage_->store_rosbag_file(old_link); + + RosbagChangeSet set; + set.remove.push_back({"MOVE_A", old_link.file_path}); + auto moved = old_link; + moved.fault_code = "MOVE_B"; + set.insert.push_back(moved); + + EXPECT_TRUE(this->storage_->apply_rosbag_changes(set).orphaned_paths.empty()); + EXPECT_EQ(this->storage_->get_rosbag_files("MOVE_B").size(), 1u); + EXPECT_TRUE(this->storage_->get_rosbag_files("MOVE_A").empty()); +} + +TYPED_TEST(RosbagRetentionParityTest, UpsertOnLinkKeepsOneRow) { + this->storage_->set_max_rosbags_per_fault(0); + auto info = this->row("APPLY_UPSERT", "fault_APPLY_UPSERT_1", 1000); + const auto sibling = this->row("APPLY_UPSERT", "fault_APPLY_UPSERT_2", 1000); + + RosbagChangeSet first; + first.insert.push_back(info); + first.insert.push_back(sibling); + this->storage_->apply_rosbag_changes(first); + + info.size_bytes = 4096; + RosbagChangeSet refresh; + refresh.insert.push_back(info); + this->storage_->apply_rosbag_changes(refresh); + + // A refresh replaces every field but the link itself. + auto full = this->row("APPLY_UPSERT_FULL", "fault_APPLY_UPSERT_3", 3000); + RosbagChangeSet seed; + seed.insert.push_back(full); + this->storage_->apply_rosbag_changes(seed); + full.recording_id = "renamed_recording"; + full.format = "sqlite3"; + full.duration_sec = 9.5; + full.size_bytes = 8192; + full.created_at_ns = 7000; + RosbagChangeSet replace; + replace.insert.push_back(full); + this->storage_->apply_rosbag_changes(replace); + const auto replaced = this->storage_->get_rosbag_files("APPLY_UPSERT_FULL"); + ASSERT_EQ(replaced.size(), 1u); + EXPECT_EQ(replaced[0].file_path, full.file_path); + EXPECT_EQ(replaced[0].recording_id, "renamed_recording"); + EXPECT_EQ(replaced[0].format, "sqlite3"); + EXPECT_DOUBLE_EQ(replaced[0].duration_sec, 9.5); + EXPECT_EQ(replaced[0].size_bytes, 8192u); + EXPECT_EQ(replaced[0].created_at_ns, 7000); + + const auto rows = this->storage_->get_rosbag_files("APPLY_UPSERT"); + ASSERT_EQ(rows.size(), 2u); + EXPECT_EQ(rows[0].recording_id, "fault_APPLY_UPSERT_2") << "a refresh keeps the row's place in a tie group"; + EXPECT_EQ(rows[1].recording_id, "fault_APPLY_UPSERT_1"); + EXPECT_EQ(rows[1].size_bytes, 4096u); +} + +TYPED_TEST(RosbagRetentionParityTest, RemoveRecordingsRemovesEveryLink) { + this->storage_->set_max_rosbags_per_fault(0); + auto burst = this->row("RECS_A", "fault_RECS_1", 1000); + this->storage_->store_rosbag_file(burst); + burst.fault_code = "RECS_B"; + this->storage_->store_rosbag_file(burst); + const auto other = this->row("RECS_A", "fault_RECS_2", 2000); + this->storage_->store_rosbag_file(other); + + RosbagChangeSet set; + set.remove_recordings = {"fault_RECS_1", "fault_RECS_1", "fault_RECS_UNKNOWN", ""}; + const auto result = this->storage_->apply_rosbag_changes(set); + + EXPECT_EQ(result.orphaned_paths, std::vector{burst.file_path}); + EXPECT_TRUE(this->storage_->get_rosbag_files_by_recording("fault_RECS_1").empty()); + const auto survivors = this->storage_->get_rosbag_files("RECS_A"); + ASSERT_EQ(survivors.size(), 1u); + EXPECT_EQ(survivors[0].recording_id, "fault_RECS_2"); +} + +TYPED_TEST(RosbagRetentionParityTest, ApplyNeverUnlinks) { + this->storage_->set_max_rosbags_per_fault(0); + const auto a = this->row("KEEP_A", "fault_KEEP_1", 1000); + const auto b = this->row("KEEP_B", "fault_KEEP_2", 2000); + this->storage_->store_rosbag_file(a); + this->storage_->store_rosbag_file(b); + + RosbagChangeSet set; + set.remove.push_back({"KEEP_A", a.file_path}); + set.remove_recordings.push_back("fault_KEEP_2"); + const auto result = this->storage_->apply_rosbag_changes(set); + + EXPECT_EQ(result.orphaned_paths.size(), 2u); + EXPECT_TRUE(std::filesystem::exists(a.file_path)) << "unlinking is the caller's decision"; + EXPECT_TRUE(std::filesystem::exists(b.file_path)); + EXPECT_TRUE(this->storage_->get_all_rosbag_files().empty()); +} + +TYPED_TEST(RosbagRetentionParityTest, ApplyAppliesNoCap) { + this->storage_->set_max_rosbags_per_fault(1); + RosbagChangeSet set; + for (int i = 1; i <= 3; ++i) { + set.insert.push_back(this->row("NOCAP", "fault_NOCAP_" + std::to_string(i), i * 1000)); + } + const auto result = this->storage_->apply_rosbag_changes(set); + + EXPECT_TRUE(result.orphaned_paths.empty()); + EXPECT_EQ(this->storage_->get_rosbag_files("NOCAP").size(), 3u); +} + +TYPED_TEST(RosbagRetentionParityTest, RejectsInsertAndRemoveOfTheSameLink) { + this->storage_->set_max_rosbags_per_fault(0); + const auto kept = this->row("REJECT_A", "fault_REJECT_1", 1000); + this->storage_->store_rosbag_file(kept); + const auto before = this->storage_->get_all_rosbag_files(); + + auto fresh = this->row("REJECT_B", "fault_REJECT_2", 2000); + + RosbagChangeSet direct; + direct.remove.push_back({"REJECT_A", kept.file_path}); // would apply on its own + direct.insert.push_back(fresh); + direct.remove.push_back({"REJECT_B", fresh.file_path}); + EXPECT_THROW(this->storage_->apply_rosbag_changes(direct), std::invalid_argument); + + RosbagChangeSet by_recording; + by_recording.remove.push_back({"REJECT_A", kept.file_path}); + by_recording.insert.push_back(fresh); + by_recording.remove_recordings.push_back("fault_REJECT_2"); + EXPECT_THROW(this->storage_->apply_rosbag_changes(by_recording), std::invalid_argument); + + fresh.recording_id.clear(); // derived from the path, as the store does + RosbagChangeSet derived; + derived.insert.push_back(fresh); + derived.remove_recordings.push_back("fault_REJECT_2"); + EXPECT_THROW(this->storage_->apply_rosbag_changes(derived), std::invalid_argument); + + const auto after = this->storage_->get_all_rosbag_files(); + ASSERT_EQ(after.size(), before.size()); + EXPECT_EQ(after[0].file_path, kept.file_path); +} + +/// Atomicity needs a failure in the middle of one transaction, which only the SQL backends can be made to produce. +template +class RosbagApplyAtomicityTest : public RosbagRetentionParityTest {}; +TYPED_TEST_SUITE(RosbagApplyAtomicityTest, SqlBackends); + +TYPED_TEST(RosbagApplyAtomicityTest, ApplyIsAtomicOnInsertFailure) { + this->storage_->set_max_rosbags_per_fault(0); + const auto a = this->row("ATOM_A", "fault_ATOM_1", 1000); + this->storage_->store_rosbag_file(a); + BackendFactory::add_failing_trigger(this->dir_, "INSERT", "ATOM_FAIL"); + + RosbagChangeSet set; + set.remove.push_back({"ATOM_A", a.file_path}); + set.insert.push_back(this->row("ATOM_OK", "fault_ATOM_2", 2000)); + set.insert.push_back(this->row("ATOM_FAIL", "fault_ATOM_3", 3000)); + EXPECT_THROW(this->storage_->apply_rosbag_changes(set), std::exception); + + const auto rows = this->storage_->get_all_rosbag_files(); + ASSERT_EQ(rows.size(), 1u) << "the removal ran before the failing insert and must have been undone"; + EXPECT_EQ(rows[0].fault_code, "ATOM_A"); + EXPECT_TRUE(this->storage_->get_rosbag_files("ATOM_OK").empty()); +} + +TYPED_TEST(RosbagApplyAtomicityTest, ApplyIsAtomicOnDeleteFailure) { + this->storage_->set_max_rosbags_per_fault(0); + const auto a = this->row("ATOM_A", "fault_ATOM_1", 1000); + const auto failing = this->row("ATOM_FAIL", "fault_ATOM_2", 2000); + this->storage_->store_rosbag_file(a); + this->storage_->store_rosbag_file(failing); + BackendFactory::add_failing_trigger(this->dir_, "DELETE", "ATOM_FAIL"); + + RosbagChangeSet set; + set.remove.push_back({"ATOM_A", a.file_path}); + set.remove.push_back({"ATOM_FAIL", failing.file_path}); + set.insert.push_back(this->row("ATOM_OK", "fault_ATOM_3", 3000)); + EXPECT_THROW(this->storage_->apply_rosbag_changes(set), std::exception); + + const auto rows = this->storage_->get_all_rosbag_files(); + ASSERT_EQ(rows.size(), 2u) << "the first removal ran before the failing one and must have been undone"; + EXPECT_EQ(rows[0].fault_code, "ATOM_A"); + EXPECT_EQ(rows[1].fault_code, "ATOM_FAIL"); + EXPECT_TRUE(this->storage_->get_rosbag_files("ATOM_OK").empty()); +} + /// Snapshot retention parity. Same two backends, same reason. template class SnapshotRetentionParityTest : public ::testing::Test { @@ -437,7 +789,8 @@ class SnapshotRetentionParityTest : public ::testing::Test { std::unique_ptr storage_; }; -TYPED_TEST_SUITE(SnapshotRetentionParityTest, Backends); +using SnapshotBackends = ::testing::Types; +TYPED_TEST_SUITE(SnapshotRetentionParityTest, SnapshotBackends); TYPED_TEST(SnapshotRetentionParityTest, ACaptureLargerThanTheCapIsKeptWholeRatherThanTorn) { // The in-memory trim used to evict the newest set too, leaving the fault with no