Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion docs/config/fault-manager.rst
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,12 @@ reclassification of HEALED faults run only at startup, so they are skipped when
be reached then. Snapshot capture starts with the first answer of the server. The bags of a fault
cleared while the server cannot be reached are not deleted then.

A connection lost during the commit of a recording's metadata keeps the recording, because its row
may be stored. If the row was not stored, the directory stays on disk, not listed and not counted
against ``snapshots.rosbag.max_total_storage_mb``, until it is removed by hand. When the connection
is lost while ``GetRosbag`` or ``ListRosbags`` removes the rows of a recording whose directory is
gone, the request fails and the node keeps running; the next request removes what is left.

Report Queue
~~~~~~~~~~~~

Expand Down Expand Up @@ -730,7 +736,9 @@ written (unwritable ``storage_path``, missing storage backend), no recording is
opened and no metadata entry is stored.

A capture never leaves a row pointing at a bag that is not there, and never leaves a
bag that no row points at. If the metadata cannot be stored, the recording is
bag that no row points at, except after a connection lost during the commit with PostgreSQL
(see `PostgreSQL Storage`_) and when the removal of a discarded bag fails (logged with the
path). If the metadata cannot be stored, the recording is
discarded with it: nothing could reach that bag anyway, since retrieval is keyed by
fault code and the quota is computed from rows, so it would sit on disk unreachable
and uncounted. If the quota sweep that follows fails instead, the bag and its rows
Expand Down
4 changes: 4 additions & 0 deletions src/ros2_medkit_fault_manager/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -303,6 +303,10 @@ endif()
# was unreachable at start answers.
medkit_add_launch_test(test_retention_config_pg test/integration/test_retention_config_pg.test.py TIMEOUT 300
LABELS "integration")

# A connection lost during the rosbag store transaction, cut by a protocol-aware proxy.
medkit_add_launch_test(test_rosbag_commit_in_doubt_pg test/integration/test_rosbag_commit_in_doubt_pg.test.py
TIMEOUT 300 LABELS "integration")
endif()

# Launches without snapshots.rosbag.format, so the parameter default (mcap)
Expand Down
2 changes: 2 additions & 0 deletions src/ros2_medkit_fault_manager/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,8 @@ The build downloads libpqxx 7.10.7 from GitHub at configure time and links it st

A wrong configuration stops the node at startup with exit code 1: a connection string libpq cannot parse, or a server that accepts the connection but does not allow creating the schema, or a table that lacks a column the node uses. A server that cannot be reached (including a wrong password or a missing database) does not stop it: the node runs without storage, services with an error field answer `Fault storage unavailable`, and `ReportFault` answers `accepted=false`. After a failed connection attempt, requests fail at once for 5 s and the next request tries again. An attempt waits at most 2 s per host address unless `connect_timeout` or `PGCONNECT_TIMEOUT` says otherwise, and a request on an open connection to a server that went off the network fails after `tcp_user_timeout` (5 s). With a libpq service, these values come from the service file. See `docs/config/fault-manager.rst` for the full table.

A connection lost during the commit of a recording's metadata keeps the recording, because its row may be stored. If the row was not stored, the directory stays on disk, not listed and not counted against `snapshots.rosbag.max_total_storage_mb`, until it is removed by hand. When the connection is lost while `GetRosbag` or `ListRosbags` removes the rows of a recording whose directory is gone, the request fails and the node keeps running; the next request removes what is left.

## Near-Miss Series

A **near miss** is a FAILED report that moved the debounce counter without the fault ending up
Expand Down
12 changes: 9 additions & 3 deletions src/ros2_medkit_fault_manager/design/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -528,7 +528,8 @@ span can also legitimately exceed ``duration_sec + duration_after_sec``.

If the metadata row cannot be stored, the bag is discarded rather than kept: retrieval is
keyed by fault code and quota accounting enumerates rows, so a bag with no row would
occupy disk that nothing can find and nothing can evict.
occupy disk that nothing can find and nothing can evict. When the outcome of the commit is
unknown (``kInDoubt``, PostgreSQL only), the bag is kept: its row may be stored.

Known interval: between the empty-buffer flush and the moment the recording guard is
published, the writer is being created - directory creation plus a storage-backend open.
Expand All @@ -545,7 +546,11 @@ in one transaction: ``insert`` upserts on ``(fault_code, file_path)``, ``remove`
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.
under the mutex in memory. One exception: PostgreSQL throws ``RosbagCommitInDoubt`` when libpqxx
does not know the outcome of the commit (``pqxx::in_doubt_error``, for example a connection lost
during ``COMMIT``). The rows may then be either way, and the call is not retried. SQLite and memory
never throw it. A store in doubt returns ``StoreResult::kInDoubt``, and ``RosbagCapture`` keeps the
bag and logs one warning.

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.
Expand Down Expand Up @@ -649,7 +654,8 @@ depends on the path:
own thread removes the cap victims, a new recording that lost the cap and the quota evictions,
once the retention mutex is released and before "Bag file created" or "Bag file completed" is
logged. The executor never runs a store. A bag that never got a row is discarded on the same
thread.
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.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ enum class StoreResult {
kAllFaultsCleared, ///< Every fault of the recording is cleared. Nothing was stored.
kStoreFailed, ///< The cap read or the insert failed. Nothing was stored.
kDroppedOverQuota, ///< The recording does not fit the quota. Nothing was stored; the caller removes the bag.
kInDoubt, ///< The rows may or may not be stored (RosbagCommitInDoubt); the caller keeps the bag.
};

struct StoreOutcome {
Expand All @@ -86,7 +87,8 @@ struct StoreOutcome {
bool quota_failed{false};
std::string error; ///< Exception text of the store failure or of the quota failure
/// Directories no row names any more, each path once. Never the path of a recording that
/// kAllFaultsCleared or kStoreFailed left without rows: the caller discards that one.
/// kAllFaultsCleared or kStoreFailed left without rows: the caller discards that one. Empty with
/// kInDoubt.
std::vector<FreedRecording> unlink_paths;
};

Expand Down Expand Up @@ -143,11 +145,13 @@ class RosbagRetention {
std::vector<std::string> evict_over_quota(size_t max_bytes, const std::string & keep_recording_id = {});

/// Remove every row of @p fault_code. The caller decides whether a clear removes recordings.
/// @throws the storage failure; no row changed then
/// @throws the storage failure; no row changed then, except with RosbagCommitInDoubt: the rows
/// may be gone
RemovalOutcome on_fault_cleared(const std::string & fault_code);

/// Remove every row of a recording whose directory is gone.
/// @throws the storage failure; no row changed then
/// @throws the storage failure; no row changed then, except with RosbagCommitInDoubt: the rows
/// may be gone
RemovalOutcome forget_recording(const std::string & recording_id);

private:
Expand All @@ -172,7 +176,7 @@ class RosbagRetention {
const RetentionPolicyState & state);

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

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
#include <mutex>
#include <optional>
#include <set>
#include <stdexcept>
#include <string>
#include <vector>

Expand Down Expand Up @@ -214,6 +215,15 @@ struct RosbagApplyResult {
std::vector<std::string> orphaned_paths;
};

/// Thrown by FaultStorage::apply_rosbag_changes() when the outcome of its commit is unknown: the
/// rows may or may not have changed. Only PostgreSQL throws it.
class RosbagCommitInDoubt : public std::runtime_error {
public:
explicit RosbagCommitInDoubt(const std::string & detail)
: std::runtime_error("the commit outcome is unknown: " + detail) {
}
};

/// 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
Expand Down Expand Up @@ -387,7 +397,8 @@ class FaultStorage {
/// Apply a set of rosbag row changes in one transaction. The only write of the rosbag rows;
/// core::RosbagRetention makes every retention decision on top of it.
///
/// - All or nothing: when anything throws, no row has changed.
/// - All or nothing: when anything throws, no row has changed. Except RosbagCommitInDoubt, which
/// only PostgreSQL throws: the rows may then be either way. SQLite and memory never throw it.
/// - 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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -124,9 +124,20 @@ class PgFaultStorage : public FaultStorage {
/// Open a new connection unless the current one is open. Caller holds mutex_.
void ensure_connection() const;

/// How run_in_transaction() reports a commit whose outcome libpqxx does not know (pqxx::in_doubt_error).
enum class InDoubt {
kAsFailure, ///< Like any other failure
kReport, ///< As RosbagCommitInDoubt, without a retry
};

/// Run @p fn in one transaction and commit. On a broken connection, reconnect and run it again. Caller holds mutex_.
template <typename Fn>
auto run_in_transaction(const char * what, Fn && fn) const -> decltype(fn(std::declval<pqxx::work &>()));
auto run_in_transaction(const char * what, Fn && fn,
InDoubt in_doubt = InDoubt::kAsFailure) const -> decltype(fn(std::declval<pqxx::work &>()));

/// Throw the failure of a transaction: IgnorableConnectionException after fail_round() when the
/// connection is closed, std::runtime_error otherwise. Caller holds mutex_.
[[noreturn]] void throw_transaction_failure(const char * what, const std::string & error) const;

/// Create the tables and indexes that do not exist yet, in @p tx, and check the columns of existing ones.
void create_schema(pqxx::work & tx) const;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -327,7 +327,8 @@ class RosbagCapture {
/// Both finalisation paths end here, so a bag that cannot be looked up never
/// survives on disk: retrieval is keyed by fault code and the quota enumerates
/// rows, so a directory with no row is unreachable, uncounted, and can never be
/// evicted to make room.
/// evicted to make room. Except a store in doubt: it returns no paths, the new
/// directory stays, and a cap victim's directory can stay when the commit was applied.
///
/// The decisions are core::RosbagRetention::store(). The bag is discarded here when
/// every fault of it is cleared or the store failed, and nothing else. A failed quota
Expand All @@ -341,9 +342,10 @@ class RosbagCapture {
/// into a log with the bag already orphaned.
///
/// A recording the quota refused (core::StoreResult::kDroppedOverQuota) is removed here too,
/// and logged once the directory is gone.
/// 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.
///
/// @return True when the rows are durable.
/// @return True when the rows are known to be durable.
bool store_rows_or_discard_bag(std::vector<RosbagFileInfo> rows, const std::string & bag_path);

/// Whether the operator asked this fault code to keep a recording history.
Expand Down
5 changes: 5 additions & 0 deletions src/ros2_medkit_fault_manager/src/core/rosbag_retention.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -253,6 +253,11 @@ bool RosbagRetention::apply_store(const std::vector<RosbagFileInfo> & rows, cons
outcome.unlink_paths =
freed(storage_.apply_rosbag_changes(changes).orphaned_paths, recording_ids, RemovalReason::kCap);
}
} catch (const RosbagCommitInDoubt & e) {
// The caller logs it: the bag stays, and no eviction runs on rows that may not exist.
outcome.result = StoreResult::kInDoubt;
outcome.error = e.what();
return false;
} catch (const std::exception & e) {
outcome.result = StoreResult::kStoreFailed;
outcome.error = e.what();
Expand Down
10 changes: 10 additions & 0 deletions src/ros2_medkit_fault_manager/src/fault_manager_node.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1216,6 +1216,10 @@ void FaultManagerNode::handle_get_rosbag(const std::shared_ptr<ros2_medkit_msgs:
} catch (const FaultStorage::IgnorableConnectionException & e) {
RCLCPP_WARN(get_logger(), "Failed to connect with the fault storage server: %s", e.what());
return;
} catch (const RosbagCommitInDoubt & e) {
RCLCPP_WARN(get_logger(), "Stale rows of recording '%s' may still be stored: %s",
rosbag_info->recording_id.c_str(), e.what());
return;
}
return;
}
Expand Down Expand Up @@ -1269,6 +1273,12 @@ void FaultManagerNode::handle_list_rosbags(
response->success = false;
response->error_message = storage_unavailable(e);
return;
} catch (const RosbagCommitInDoubt & e) {
RCLCPP_WARN(get_logger(), "Stale rows of recording '%s' may still be stored: %s", info.recording_id.c_str(),
e.what());
response->success = false;
response->error_message = storage_unavailable(e);
return;
}
}
continue;
Expand Down
32 changes: 22 additions & 10 deletions src/ros2_medkit_fault_manager/src/postgres_fault_storage.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -246,9 +246,18 @@ void PgFaultStorage::ensure_connection() const {
throw IgnorableConnectionException("Failed to connect to PostgreSQL: " + last_error);
}

void PgFaultStorage::throw_transaction_failure(const char * what, const std::string & error) const {
// Some errors hide a lost connection: a closed connection counts as unreachable.
if (!db_conn_ || !db_conn_->is_open()) {
fail_round(error);
throw FaultStorage::IgnorableConnectionException(std::string(what) + " failed to connect to PostgreSQL: " + error);
}
throw std::runtime_error(std::string(what) + " PostgreSQL error: " + error);
}

template <typename Fn>
auto PgFaultStorage::run_in_transaction(const char * what,
Fn && fn) const -> decltype(fn(std::declval<pqxx::work &>())) {
auto PgFaultStorage::run_in_transaction(const char * what, Fn && fn,
InDoubt in_doubt) const -> decltype(fn(std::declval<pqxx::work &>())) {
using Result = decltype(fn(std::declval<pqxx::work &>()));

for (int attempt = 0;; ++attempt) {
Expand Down Expand Up @@ -281,16 +290,18 @@ auto PgFaultStorage::run_in_transaction(const char * what,
core::logf(log_sink_, core::LogLevel::kWarn, "postgres_fault_storage",
"%s lost the connection (%s); retrying transaction %d/%d", what, error.c_str(), attempt + 1,
max_retries_);
} catch (const std::exception & e) {
// There are other types of error that "hide" connection issues
// Before throwing a runtime_error, check if the connection is open
} catch (const pqxx::in_doubt_error & e) {
// The commit may have been applied: a retry could apply it twice.
const std::string error = redact(e.what());
if (in_doubt == InDoubt::kAsFailure) {
throw_transaction_failure(what, error);
}
if (!db_conn_ || !db_conn_->is_open()) {
fail_round(error);
throw FaultStorage::IgnorableConnectionException(std::string(what) +
" failed to connect to PostgreSQL: " + error);
}
throw std::runtime_error(std::string(what) + " PostgreSQL error: " + error);
throw RosbagCommitInDoubt(std::string(what) + ": " + error);
} catch (const std::exception & e) {
throw_transaction_failure(what, redact(e.what()));
}
}
}
Expand Down Expand Up @@ -1111,7 +1122,7 @@ RosbagApplyResult PgFaultStorage::apply_rosbag_changes(const RosbagChangeSet & c
std::lock_guard<std::mutex> lock(mutex_);

RosbagApplyResult result;
result.orphaned_paths = run_in_transaction("apply_rosbag_changes", [&](pqxx::work & tx) {
const auto apply = [&](pqxx::work & tx) {
std::set<std::string> 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",
Expand Down Expand Up @@ -1149,7 +1160,8 @@ RosbagApplyResult PgFaultStorage::apply_rosbag_changes(const RosbagChangeSet & c
}
}
return orphaned;
});
};
result.orphaned_paths = run_in_transaction("apply_rosbag_changes", apply, InDoubt::kReport);
return result;
}

Expand Down
9 changes: 9 additions & 0 deletions src/ros2_medkit_fault_manager/src/rosbag_capture.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1602,6 +1602,15 @@ bool RosbagCapture::store_rows_or_discard_bag(std::vector<RosbagFileInfo> rows,
return false;
}

if (outcome.result == core::StoreResult::kInDoubt) {
// The row may be committed: removing the directory could lose a stored recording.
RCLCPP_WARN(node_->get_logger(),
"Recording '%s' kept: the commit outcome of its rosbag metadata is unknown (%s). If its row was not "
"stored, the directory is not listed and not counted against the quota",
bag_path.c_str(), outcome.error.c_str());
return false;
}

if (outcome.result == core::StoreResult::kStoreFailed) {
// Without a row nothing can ever reach this bag: retrieval is keyed by fault
// code, and quota accounting enumerates rows, so a kept directory would sit
Expand Down
Loading
Loading