diff --git a/include/Void/Sqlite/Sqlite.hpp b/include/Void/Sqlite/Sqlite.hpp index 4e4410e..25a9142 100644 --- a/include/Void/Sqlite/Sqlite.hpp +++ b/include/Void/Sqlite/Sqlite.hpp @@ -182,7 +182,9 @@ namespace Void::Sqlite /// RAII transaction retaining shared ConnectionState. Never marks Committed /// before COMMIT succeeds; inspects sqlite3_get_autocommit on error and after - /// statements so an automatic rollback is reported as RolledBack. + /// statements so an automatic rollback is reported as RolledBack. A failed + /// COMMIT whose outcome cannot be proven (WAL I/O error) is reported as + /// Unknown, never as RolledBack. class Transaction { public: @@ -199,6 +201,10 @@ namespace Void::Sqlite [[nodiscard]] TransactionState state() const noexcept; [[nodiscard]] bool is_active() const noexcept; + /// Commits the transaction. On failure state() is Active (SQLite kept + /// the transaction open; retry or roll back), RolledBack (SQLite ended + /// it and it was not committed), or Unknown (SQLite ended it but a WAL + /// I/O error means the commit may have taken effect). Result commit(); [[nodiscard]] Result rollback_checked(); void rollback() noexcept; diff --git a/include/Void/Sqlite/Types.hpp b/include/Void/Sqlite/Types.hpp index 37a85ba..7c9aed3 100644 --- a/include/Void/Sqlite/Types.hpp +++ b/include/Void/Sqlite/Types.hpp @@ -50,10 +50,22 @@ namespace Void::Sqlite }; enum class TransactionState : std::uint8_t { + /// The transaction is open; statements execute inside it. Active, + /// COMMIT succeeded and the transaction is durable. Committed, + /// SQLite ended the transaction without committing it (explicit or + /// automatic rollback, or the transaction never started). RolledBack, - RecoveryRequired + /// The connection or rollback state is unusable; the application must + /// recover before continuing. + RecoveryRequired, + /// COMMIT failed and SQLite ended the transaction, but the wrapper cannot + /// prove whether the commit took effect. A WAL I/O error can be reported + /// after the commit record became durable, so this must never be treated + /// as a definite rollback: inspect the database before assuming either + /// outcome. + Unknown }; enum class ColumnType : std::uint8_t { @@ -453,6 +465,10 @@ namespace Void::Sqlite /// If true along with fail_next_commit_rc, simulates SQLite /// auto-rollback before returning the error. bool auto_rollback_on_faulted_commit{false}; + /// If true along with fail_next_commit_rc, the COMMIT is executed and + /// committed first, and the error is reported afterwards. Models a lost + /// commit acknowledgement, where the outcome is genuinely unknown. + bool commit_applied_before_error{false}; /// If non-zero, next explicit close() returns this SQLite error code. int fail_next_close_rc{0}; }; diff --git a/src/Sqlite/Sqlite.cpp b/src/Sqlite/Sqlite.cpp index 89b3b24..81e4b1d 100644 --- a/src/Sqlite/Sqlite.cpp +++ b/src/Sqlite/Sqlite.cpp @@ -33,6 +33,8 @@ namespace Void::Sqlite out.fail_next_commit_rc = std::exchange(g_fault_config.fail_next_commit_rc, 0); out.auto_rollback_on_faulted_commit = std::exchange(g_fault_config.auto_rollback_on_faulted_commit, false); + out.commit_applied_before_error = + std::exchange(g_fault_config.commit_applied_before_error, false); } return out; } @@ -82,6 +84,16 @@ namespace Void::Sqlite } } + /// A WAL I/O error during COMMIT can be reported after the commit record + /// was written, so the wrapper cannot prove whether the transaction + /// committed. SQLite documents automatic rollback for other COMMIT + /// failures, and a rollback journal has crash recovery to resolve them. + [[nodiscard]] bool commit_outcome_unknown( + int rc, std::string_view journal_mode) noexcept + { + return (rc & 0xFF) == SQLITE_IOERR && journal_mode == "wal"; + } + [[nodiscard]] Error sqlite_error_from_db( sqlite3* db, int primary_rc, @@ -1403,7 +1415,9 @@ namespace Void::Sqlite SqliteErrorCode::misuse, m_state == TransactionState::RolledBack ? "Sqlite: commit() called on a transaction that was already rolled back" - : "Sqlite: commit() called on non-active transaction")); + : m_state == TransactionState::Unknown + ? "Sqlite: commit() called after an unknown commit outcome; inspect the database" + : "Sqlite: commit() called on non-active transaction")); } if (!m_conn || m_conn->db == nullptr) { m_state = TransactionState::RecoveryRequired; @@ -1414,15 +1428,30 @@ namespace Void::Sqlite const auto fault = consume_fault_commit(); if (fault.fail_next_commit_rc != 0) { - if (fault.auto_rollback_on_faulted_commit) { + bool applied = false; + if (fault.commit_applied_before_error) { + char* apply_err = nullptr; + applied = sqlite3_exec( + m_conn->db, "COMMIT", nullptr, nullptr, &apply_err) == SQLITE_OK; + if (apply_err) sqlite3_free(apply_err); + } else if (fault.auto_rollback_on_faulted_commit) { (void)sqlite3_exec(m_conn->db, "ROLLBACK", nullptr, nullptr, nullptr); } - if (sqlite3_get_autocommit(m_conn->db) == 0) { + + if (applied) { + // The commit took effect even though the caller sees an error. + m_state = TransactionState::Unknown; + m_conn->active_transaction = false; + m_conn->active_transaction_id = 0; + } else if (sqlite3_get_autocommit(m_conn->db) == 0) { m_state = TransactionState::Active; m_conn->active_transaction = true; m_conn->active_transaction_id = m_id; } else { - m_state = TransactionState::RolledBack; + m_state = commit_outcome_unknown( + fault.fail_next_commit_rc, m_conn->caps.journal_mode) + ? TransactionState::Unknown + : TransactionState::RolledBack; m_conn->active_transaction = false; m_conn->active_transaction_id = 0; } @@ -1453,15 +1482,23 @@ namespace Void::Sqlite m_state = TransactionState::Active; m_conn->active_transaction = true; m_conn->active_transaction_id = m_id; - } else { - m_state = TransactionState::RolledBack; - m_conn->active_transaction = false; - m_conn->active_transaction_id = 0; + return Void::Result::fail(make_sqlite_error( + map_sqlite_rc(rc), + std::format("Sqlite: commit: {}", msg), + rc, + ext)); } + m_conn->active_transaction = false; + m_conn->active_transaction_id = 0; + const bool unknown = commit_outcome_unknown(rc, m_conn->caps.journal_mode); + m_state = unknown ? TransactionState::Unknown : TransactionState::RolledBack; return Void::Result::fail(make_sqlite_error( map_sqlite_rc(rc), - std::format("Sqlite: commit: {}", msg), + unknown + ? std::format("Sqlite: commit outcome unknown after WAL I/O error; " + "inspect the database: {}", msg) + : std::format("Sqlite: commit: {}", msg), rc, ext)); } @@ -1472,6 +1509,11 @@ namespace Void::Sqlite if (m_state == TransactionState::RolledBack) { return {}; } + if (m_state == TransactionState::Unknown) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::recovery_required, + "Sqlite: rollback after an unknown commit outcome; inspect the database")); + } if (m_state != TransactionState::Active) { return Void::Result::fail(make_sqlite_error( SqliteErrorCode::misuse, diff --git a/tests/standalone/Sqlite/SqliteHardening.cpp b/tests/standalone/Sqlite/SqliteHardening.cpp index c0aa841..ab7ed22 100644 --- a/tests/standalone/Sqlite/SqliteHardening.cpp +++ b/tests/standalone/Sqlite/SqliteHardening.cpp @@ -716,3 +716,93 @@ Void::Testing::Test sqlite_busy_timeout_override_is_scoped() negative.error().code().value, static_cast(SqliteErrorCode::invalid_argument)); } + +Void::Testing::Test sqlite_failed_commit_outcome_is_unknown_not_rolled_back() +{ + TempSqliteDir dir; + const auto db_path = dir.path / "unknown-commit.db"; + + auto db_r = open_database(db_path); + Void::Testing::require(db_r.has_value()); + auto& db = *db_r; + Void::Testing::expect_eq(db.capabilities().journal_mode, std::string{"wal"}); + Void::Testing::require( + db.exec("CREATE TABLE t(id INTEGER PRIMARY KEY, v TEXT)").has_value()); + + // A WAL I/O error can be reported after the commit record became durable. + // The wrapper must not claim the transaction was definitely rolled back. + { + auto tx = db.begin(BeginMode::Immediate); + Void::Testing::require(tx.has_value()); + Void::Testing::require( + db.exec("INSERT INTO t VALUES(1, 'maybe committed')").has_value()); + { + ScopedFaultGuard guard{FaultConfig{ + .fail_next_commit_rc = SQLITE_IOERR, + .commit_applied_before_error = true}}; + auto failed_commit = tx->commit(); + Void::Testing::expect(!failed_commit.has_value()); + Void::Testing::expect(failed_commit.error().code().value == + static_cast(SqliteErrorCode::io)); + } + Void::Testing::expect(tx->state() == TransactionState::Unknown); + Void::Testing::expect(!tx->is_active()); + + // The row is visible: reporting RolledBack would have been a lie. + auto count = db.prepare("SELECT COUNT(*) FROM t WHERE id = 1"); + Void::Testing::require(count.has_value() && *count->step()); + Void::Testing::expect_eq(*count->try_column_int(0), static_cast(1)); + + // The ambiguous transaction cannot be committed or rolled back again; + // the caller must inspect the database. + auto stale_commit = tx->commit(); + Void::Testing::expect(!stale_commit.has_value()); + Void::Testing::expect(stale_commit.error().code().value == + static_cast(SqliteErrorCode::misuse)); + auto stale_rollback = tx->rollback_checked(); + Void::Testing::expect(!stale_rollback.has_value()); + Void::Testing::expect(stale_rollback.error().code().value == + static_cast(SqliteErrorCode::recovery_required)); + } + + // A WAL I/O error that leaves the transaction open keeps it Active so the + // caller can retry or roll back explicitly. + { + auto tx = db.begin(BeginMode::Immediate); + Void::Testing::require(tx.has_value()); + Void::Testing::require(db.exec("INSERT INTO t VALUES(2, 'retry')").has_value()); + { + ScopedFaultGuard guard{FaultConfig{.fail_next_commit_rc = SQLITE_IOERR}}; + auto failed_commit = tx->commit(); + Void::Testing::expect(!failed_commit.has_value()); + Void::Testing::expect(tx->state() == TransactionState::Active); + Void::Testing::expect(sqlite3_get_autocommit(db.handle()) == 0); + } + Void::Testing::require(tx->rollback_checked().has_value()); + } + + // The same error in rollback-journal mode is a known rollback: SQLite has + // crash recovery for a hot journal, so the wrapper reports RolledBack. + { + OpenOptions rollback_opts; + rollback_opts.journal_mode = JournalMode::Rollback; + const auto rollback_path = dir.path / "rollback.db"; + auto rdb_r = open_database(rollback_path, rollback_opts); + Void::Testing::require(rdb_r.has_value()); + auto& rdb = *rdb_r; + Void::Testing::require( + rdb.exec("CREATE TABLE t(id INTEGER PRIMARY KEY)").has_value()); + + auto tx = rdb.begin(BeginMode::Immediate); + Void::Testing::require(tx.has_value()); + Void::Testing::require(rdb.exec("INSERT INTO t VALUES(1)").has_value()); + { + ScopedFaultGuard guard{FaultConfig{ + .fail_next_commit_rc = SQLITE_IOERR, + .auto_rollback_on_faulted_commit = true}}; + auto failed_commit = tx->commit(); + Void::Testing::expect(!failed_commit.has_value()); + } + Void::Testing::expect(tx->state() == TransactionState::RolledBack); + } +}