From 5dba64d5457edc5bf8f74e79883e686d6badd2e6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 8 Dec 2025 20:34:02 +0100 Subject: [PATCH] Retry a rollback in case of SQLITE_INTERRUPT error This should fix a race condition about cancellation that happens during a rollback --- GRDB/Core/Database.swift | 18 ++++++++++- Tests/GRDBTests/DatabaseWriterTests.swift | 37 +++++++++++++++++++++++ 2 files changed, 54 insertions(+), 1 deletion(-) diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 2614602dd..513903a16 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -1764,7 +1764,23 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib // which rollback errors should be ignored, and which rollback errors // should be exposed to the library user. if isInsideTransaction { - try execute(sql: "ROLLBACK TRANSACTION") + do { + try execute(sql: "ROLLBACK TRANSACTION") + } catch is CancellationError, DatabaseError.SQLITE_INTERRUPT { + // Maybe we were unlucky, and user has interrupted the database + // during the rollback. CancellationError is thrown when + // the rollback is interrupted during execution. SQLITE_INTERRUPT + // is thrown when the rollback is interrupted during compilation. + // + // Let's rollback again. This is a correct behavior, because: + // 1. Since the interrupt was concurrent, we can reorder it + // and pretend it occurred before or after the rollback. + // 2. If we do not rollback, we might leave a database + // transaction open, with no other opportunity to close it. + // This might trigger a fatal error in + // `SerializedDatabase.preconditionNoUnsafeTransactionLeft`. + try execute(sql: "ROLLBACK TRANSACTION") + } } assert(!isInsideTransaction) } diff --git a/Tests/GRDBTests/DatabaseWriterTests.swift b/Tests/GRDBTests/DatabaseWriterTests.swift index 9a8cf4062..2e527cdab 100644 --- a/Tests/GRDBTests/DatabaseWriterTests.swift +++ b/Tests/GRDBTests/DatabaseWriterTests.swift @@ -896,4 +896,41 @@ class DatabaseWriterTests : GRDBTestCase { try await test(makeDatabasePool()) try await test(AnyDatabaseWriter(makeDatabaseQueue())) } + + // Regression test for https://github.com/groue/GRDB.swift/pull/1838 + func test_cancellation_does_not_prevent_rollback() async throws { + func test(_ dbWriter: some DatabaseWriter) async throws { + // Numbers that have the test fail more or less reliably + // (on my machine) unless the #1838 patch is applied. + // When the test fails, we have a fatal error: A transaction has been left opened at the end of a database access. + let repeatCount = 400 + let taskCount = 50 + for _ in 0..