From 5fe300b733cc9cc296b24045665ff033cd23dc25 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 1 Nov 2026 15:44:37 +0100 Subject: [PATCH] More failing SharedValueObservation tests --- .../SharedValueObservationTests.swift | 298 ++++++++++++++++++ 1 file changed, 298 insertions(+) diff --git a/Tests/GRDBTests/ValueObservation/SharedValueObservationTests.swift b/Tests/GRDBTests/ValueObservation/SharedValueObservationTests.swift index 9104e28ae..0c21e727f 100644 --- a/Tests/GRDBTests/ValueObservation/SharedValueObservationTests.swift +++ b/Tests/GRDBTests/ValueObservation/SharedValueObservationTests.swift @@ -972,6 +972,266 @@ class SharedValueObservationTests: GRDBTestCase { XCTAssertEqual(cancellationDidCompleteMutex.load(), true) } + // Regression test: a client cancelled from another thread is not + // notified of a value that is being notified to other clients. + func test_no_value_notification_after_cancellation_from_other_thread() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + } + } + + let queue = DispatchQueue(label: "SharedValueObservationTests") + let sharedObservation = ValueObservation + .tracking(Table("player").fetchCount) + .shared( + in: dbQueue, + scheduling: .async(onQueue: queue), + extent: .observationLifetime) + + let initialValuesExp = expectation(description: "initial values") + initialValuesExp.expectedFulfillmentCount = 2 + let notificationDidStartSemaphore = DispatchSemaphore(value: 0) + let cancellationDidCompleteSemaphore = DispatchSemaphore(value: 0) + + // Client 1 blocks the notification of the second value until + // client 2 is cancelled. + let cancellable1 = sharedObservation.start( + onError: { XCTFail("Unexpected error \($0)") }, + onChange: { value in + if value == 0 { + initialValuesExp.fulfill() + } else { + notificationDidStartSemaphore.signal() + _ = cancellationDidCompleteSemaphore.wait(timeout: .now() + 5) + } + }) + + let values2Mutex: Mutex<[Int]> = Mutex([]) + let cancellable2 = sharedObservation.start( + onError: { XCTFail("Unexpected error \($0)") }, + onChange: { value in + values2Mutex.withLock { $0.append(value) } + if value == 0 { + initialValuesExp.fulfill() + } + }) + wait(for: [initialValuesExp], timeout: 5) + + try dbQueue.write { try $0.execute(sql: "INSERT INTO player DEFAULT VALUES") } + XCTAssertEqual(notificationDidStartSemaphore.wait(timeout: .now() + 5), .success) + cancellable2.cancel() + cancellationDidCompleteSemaphore.signal() + queue.sync { } + + XCTAssertEqual(values2Mutex.load(), [0]) + withExtendedLifetime(cancellable1) { } + } + + // Regression test: a client cancelled from another thread is not + // notified of an error that is being notified to other clients. + func test_no_error_notification_after_cancellation_from_other_thread() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + } + } + + let fetchErrorMutex: Mutex = Mutex(nil) + let queue = DispatchQueue(label: "SharedValueObservationTests") + let sharedObservation = ValueObservation + .tracking { db -> Int in + try fetchErrorMutex.withLock { error in + if let error { throw error } + } + return try Table("player").fetchCount(db) + } + .shared( + in: dbQueue, + scheduling: .async(onQueue: queue), + extent: .observationLifetime) + + let initialValuesExp = expectation(description: "initial values") + initialValuesExp.expectedFulfillmentCount = 2 + let notificationDidStartSemaphore = DispatchSemaphore(value: 0) + let cancellationDidCompleteSemaphore = DispatchSemaphore(value: 0) + + // Client 1 blocks the notification of the error until + // client 2 is cancelled. + let cancellable1 = sharedObservation.start( + onError: { _ in + notificationDidStartSemaphore.signal() + _ = cancellationDidCompleteSemaphore.wait(timeout: .now() + 5) + }, + onChange: { _ in + initialValuesExp.fulfill() + }) + + let error2Mutex: Mutex = Mutex(nil) + let cancellable2 = sharedObservation.start( + onError: { error in + error2Mutex.store(error) + }, + onChange: { _ in + initialValuesExp.fulfill() + }) + wait(for: [initialValuesExp], timeout: 5) + + fetchErrorMutex.store(TestError()) + try dbQueue.write { try $0.execute(sql: "INSERT INTO player DEFAULT VALUES") } + XCTAssertEqual(notificationDidStartSemaphore.wait(timeout: .now() + 5), .success) + cancellable2.cancel() + cancellationDidCompleteSemaphore.signal() + queue.sync { } + + XCTAssertNil(error2Mutex.load()) + withExtendedLifetime(cancellable1) { } + } + + // Regression test: a client cancelled before the last value is + // notified as its initial value is not notified. + func test_no_initial_value_notification_after_cancellation() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + } + } + + let queue = DispatchQueue(label: "SharedValueObservationTests") + let sharedObservation = ValueObservation + .tracking(Table("player").fetchCount) + .shared( + in: dbQueue, + scheduling: .async(onQueue: queue), + extent: .observationLifetime) + + let initialValueExp = expectation(description: "initial value") + let cancellable1 = sharedObservation.start( + onError: { XCTFail("Unexpected error \($0)") }, + onChange: { _ in initialValueExp.fulfill() }) + wait(for: [initialValueExp], timeout: 5) + + // Block the queue until client 2 is cancelled. + let cancellationDidCompleteSemaphore = DispatchSemaphore(value: 0) + queue.async { + _ = cancellationDidCompleteSemaphore.wait(timeout: .now() + 5) + } + + let values2Mutex: Mutex<[Int]> = Mutex([]) + let cancellable2 = sharedObservation.start( + onError: { XCTFail("Unexpected error \($0)") }, + onChange: { value in + values2Mutex.withLock { $0.append(value) } + }) + cancellable2.cancel() + cancellationDidCompleteSemaphore.signal() + queue.sync { } + + XCTAssertEqual(values2Mutex.load(), []) + withExtendedLifetime(cancellable1) { } + } + + // Regression test: a shared observation that is restarted while the + // failed upstream observation is starting keeps on observing + // the database. + func test_restart_during_failed_start_whileObserved() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + } + } + + // The first fetch fails + let fetchCountMutex = Mutex(0) + let sharedObservation = ValueObservation + .tracking { db -> Int in + if fetchCountMutex.increment() == 1 { + throw TestError() + } + return try Table("player").fetchCount(db) + } + .shared( + in: dbQueue, + scheduling: .immediate, + extent: .whileObserved) + + let cancellable2Mutex: Mutex = Mutex(nil) + let values2Mutex: Mutex<[Int]> = Mutex([]) + let value2Exp = expectation(description: "value") + let cancellable1 = sharedObservation.start( + onError: { _ in + // Restart the shared observation from the immediate + // error notification, before the failed upstream + // observation has returned its cancellable. + let cancellable2 = sharedObservation.start( + onError: { XCTFail("Unexpected error \($0)") }, + onChange: { value in + values2Mutex.withLock { $0.append(value) } + if value == 1 { + value2Exp.fulfill() + } + }) + cancellable2Mutex.store(cancellable2) + }, + onChange: { _ in XCTFail("Unexpected value") }) + XCTAssertEqual(values2Mutex.load(), [0]) + + try dbQueue.write { try $0.execute(sql: "INSERT INTO player DEFAULT VALUES") } + wait(for: [value2Exp], timeout: 5) + XCTAssertEqual(values2Mutex.load(), [0, 1]) + withExtendedLifetime(cancellable1) { } + withExtendedLifetime(cancellable2Mutex) { } + } + + // Regression test: the last value, notified as the initial value of a + // new client, is not notified after a fresher value. + func test_initial_value_is_not_notified_after_fresher_value() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + } + } + + let scheduler = ManualScheduler() + let sharedObservation = ValueObservation + .tracking(Table("player").fetchCount) + .shared( + in: dbQueue, + scheduling: scheduler, + extent: .observationLifetime) + + // Client 1 makes 0 the last value. + let values1Mutex: Mutex<[Int]> = Mutex([]) + let cancellable1 = sharedObservation.start( + onError: { XCTFail("Unexpected error \($0)") }, + onChange: { value in values1Mutex.withLock { $0.append(value) } }) + XCTAssertTrue(scheduler.waitForScheduledActions(count: 1)) + scheduler.runScheduledActions() + XCTAssertEqual(values1Mutex.load(), [0]) + + // The fresh value 1 is scheduled, but not notified yet. + try dbQueue.write { try $0.execute(sql: "INSERT INTO player DEFAULT VALUES") } + XCTAssertTrue(scheduler.waitForScheduledActions(count: 1)) + + // Client 2 starts. The last value 0 is scheduled as its initial + // value, after the fresh value 1. + let values2Mutex: Mutex<[Int]> = Mutex([]) + let cancellable2 = sharedObservation.start( + onError: { XCTFail("Unexpected error \($0)") }, + onChange: { value in values2Mutex.withLock { $0.append(value) } }) + XCTAssertTrue(scheduler.waitForScheduledActions(count: 2)) + scheduler.runScheduledActions() + + XCTAssertEqual(values1Mutex.load(), [0, 1]) + XCTAssertEqual(values2Mutex.load(), [1]) + withExtendedLifetime((cancellable1, cancellable2)) { } + } + /// Cancels `cancellable` from another thread, and returns whether the /// cancellation completed before a timeout. /// @@ -1009,3 +1269,41 @@ private class Log: TextOutputStream { } private struct TestError: Error { } + +/// A scheduler that runs scheduled actions on demand. +private final class ManualScheduler: ValueObservationScheduler, @unchecked Sendable { + private let condition = NSCondition() + private var actions: [@Sendable () -> Void] = [] // protected by condition + + func immediateInitialValue() -> Bool { false } + + func schedule(_ action: @escaping @Sendable () -> Void) { + condition.lock() + actions.append(action) + condition.broadcast() + condition.unlock() + } + + /// Waits until `count` actions are scheduled, and returns whether + /// they were scheduled before a timeout. + func waitForScheduledActions(count: Int) -> Bool { + let deadline = Date(timeIntervalSinceNow: 5) + condition.lock() + defer { condition.unlock() } + while actions.count < count { + if !condition.wait(until: deadline) { return false } + } + return true + } + + /// Runs scheduled actions, in order. + func runScheduledActions() { + condition.lock() + let actions = self.actions + self.actions = [] + condition.unlock() + for action in actions { + action() + } + } +}