Retry a rollback in case of SQLITE_INTERRUPT error

This should fix a race condition about cancellation that happens during a rollback
This commit is contained in:
Gwendal Roué committed 2025-12-08 21:11:26 +01:00
1 parent 2212a17950
commit 5dba64d545
2 files changed
+54 -1

No files matched your search

+17 -1
View File
@@ -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)
}
+37
View File
@@ -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..<repeatCount {
try await withThrowingTaskGroup(of: Void.self) { group in
for _ in 0..<taskCount{
let task = Task {
try await dbWriter.writeWithoutTransaction { db in
try db.beginTransaction()
try db.rollback()
}
}
group.addTask {
Task {
// For the test to fail, we need to be lucky, here:
// Cancellation must occur during the compilation
// or the execution of the rollback statement.
task.cancel()
}
// Ignore expected CancellationError
try? await task.value
}
}
try await group.waitForAll()
}
}
}
try await test(makeDatabaseQueue())
try await test(makeDatabasePool())
try await test(AnyDatabaseWriter(makeDatabaseQueue()))
}
}