From b369e688174c858dfed8af81df0825b2b9824324 Mon Sep 17 00:00:00 2001 From: Fadi George Date: Thu, 19 Nov 2026 14:27:42 -0800 Subject: [PATCH 01/10] test: wait on state instead of timing in flaky badge and JWT tests Co-Authored-By: Claude Opus 5.5 --- .../OneSignalNotificationsTests.swift | 9 ++++----- .../OneSignalUserTests/UserJwtLifecycleTests.swift | 9 +++++---- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/iOS_SDK/OneSignalSDK/OneSignalNotificationsTests/OneSignalNotificationsTests.swift b/iOS_SDK/OneSignalSDK/OneSignalNotificationsTests/OneSignalNotificationsTests.swift index a788cb67e8..a1e08c88d1 100644 --- a/iOS_SDK/OneSignalSDK/OneSignalNotificationsTests/OneSignalNotificationsTests.swift +++ b/iOS_SDK/OneSignalSDK/OneSignalNotificationsTests/OneSignalNotificationsTests.swift @@ -61,12 +61,11 @@ final class OneSignalNotificationsTests: XCTestCase { } } + /// The swizzled setter caches the count before calling the system, whose completion can take + /// seconds on a freshly booted simulator, so this waits on the cache rather than the completion. private func setBadgeCountAndWait(_ count: Int) { - let badgeSet = expectation(description: "Badge set") - setBadgeCount(count) { - badgeSet.fulfill() - } - wait(for: [badgeSet], timeout: 5) + setBadgeCount(count) + waitForCachedBadgeCount(count) } private func waitForCachedBadgeCount(_ count: Int) { diff --git a/iOS_SDK/OneSignalSDK/OneSignalUserTests/UserJwtLifecycleTests.swift b/iOS_SDK/OneSignalSDK/OneSignalUserTests/UserJwtLifecycleTests.swift index ec1896a881..858c067c86 100644 --- a/iOS_SDK/OneSignalSDK/OneSignalUserTests/UserJwtLifecycleTests.swift +++ b/iOS_SDK/OneSignalSDK/OneSignalUserTests/UserJwtLifecycleTests.swift @@ -270,11 +270,12 @@ final class UserJwtLifecycleTests: XCTestCase { OSCoreMocks.hydrateSharedJwtConfig(requiresUserAuth: true) let jwtRepo = OneSignalUserManagerImpl.sharedInstance.userJwtRepo - // The Create User parks for want of a token, which asks the app once. Asking is what the - // assertion reads, so it cannot be polled: the first poll would consume the pending ask. + // The Create User parks for want of a token, which asks the app once. `pendingTokenAsks` reads + // the ask without consuming it, unlike `askForToken`. OneSignalUserManagerImpl.sharedInstance.login(externalId: userA_EUID, token: nil) - allowAsyncWorkToRun() - XCTAssertFalse(jwtRepo.askForToken(externalId: userA_EUID)) + OneSignalCoreMocks.waitUntil("The parked Create User did not ask for a token") { + jwtRepo.pendingTokenAsks().contains(userA_EUID) + } // Log back in as the same user, which builds a new Identity Model rather than reusing the parked one. OneSignalUserManagerImpl.sharedInstance.logout() From 72d4cef0fbc72dfc0ae9e2a2ed19593747c5582c Mon Sep 17 00:00:00 2001 From: Fadi George Date: Thu, 19 Nov 2026 17:05:59 -0800 Subject: [PATCH 02/10] fix: set the login token before publishing the new user A reader on another queue, like the in-app message fetch, could catch the new user before its token was stored and ask the app for one it had just supplied. Co-Authored-By: Claude Opus 5.5 --- .../Source/OneSignalUserManagerImpl.swift | 11 +++++-- .../UserJwtLifecycleTests.swift | 30 +++++++++++++++++++ 2 files changed, 38 insertions(+), 3 deletions(-) diff --git a/iOS_SDK/OneSignalSDK/OneSignalUser/Source/OneSignalUserManagerImpl.swift b/iOS_SDK/OneSignalSDK/OneSignalUser/Source/OneSignalUserManagerImpl.swift index 3c745e308a..7d4eec479e 100644 --- a/iOS_SDK/OneSignalSDK/OneSignalUser/Source/OneSignalUserManagerImpl.swift +++ b/iOS_SDK/OneSignalSDK/OneSignalUser/Source/OneSignalUserManagerImpl.swift @@ -468,7 +468,7 @@ public class OneSignalUserManagerImpl: NSObject, OneSignalUserManager { prepareForNewUser() } - let newUser = setNewInternalUser(externalId: externalId, pushSubscriptionModel: pushSubscriptionModel) + let newUser = setNewInternalUser(externalId: externalId, pushSubscriptionModel: pushSubscriptionModel, jwtBearerToken: token) if let externalId = externalId { storeJwtOrRearmAsk(externalId: externalId, token: token) } @@ -494,7 +494,7 @@ public class OneSignalUserManagerImpl: NSObject, OneSignalUserManager { // Immediately drop the old user and set a new user in the SDK let pushSubscriptionModel = pushSubscriptionModelStore.getModel(key: OS_PUSH_SUBSCRIPTION_MODEL_KEY) prepareForNewUser() - let newUser = setNewInternalUser(externalId: externalId, pushSubscriptionModel: pushSubscriptionModel) + let newUser = setNewInternalUser(externalId: externalId, pushSubscriptionModel: pushSubscriptionModel, jwtBearerToken: token) // The token belongs on the model that carries `external_id`: the Fetch User this leads to is signed // with it, as is the Create User this becomes if the requirement turns out to be on. storeJwtOrRearmAsk(externalId: externalId, token: token) @@ -608,7 +608,7 @@ extension OneSignalUserManagerImpl { /** Creates and sets a blank new SDK user with the provided externalId, if any. */ - func setNewInternalUser(externalId: String?, pushSubscriptionModel: OSSubscriptionModel?) -> OSUserInternal { + func setNewInternalUser(externalId: String?, pushSubscriptionModel: OSSubscriptionModel?, jwtBearerToken: String? = nil) -> OSUserInternal { let aliases: [String: String]? if let externalIdToUse = externalId { aliases = [OS_EXTERNAL_ID: externalIdToUse] @@ -617,6 +617,11 @@ extension OneSignalUserManagerImpl { } let identityModel = OSIdentityModel(aliases: aliases, changeNotifier: OSEventProducer()) + // Set before `_user` publishes the model: a caller on another queue that reads the current + // user in between would otherwise find it without a token and ask the app for one. + if let token = jwtBearerToken, !token.isEmpty, token != OS_JWT_TOKEN_INVALID { + identityModel.jwtBearerToken = token + } self.identityModelStore.add(id: OS_IDENTITY_MODEL_KEY, model: identityModel, hydrating: false) self.addIdentityModelToRepo(identityModel) diff --git a/iOS_SDK/OneSignalSDK/OneSignalUserTests/UserJwtLifecycleTests.swift b/iOS_SDK/OneSignalSDK/OneSignalUserTests/UserJwtLifecycleTests.swift index 858c067c86..f5d7065439 100644 --- a/iOS_SDK/OneSignalSDK/OneSignalUserTests/UserJwtLifecycleTests.swift +++ b/iOS_SDK/OneSignalSDK/OneSignalUserTests/UserJwtLifecycleTests.swift @@ -292,6 +292,36 @@ final class UserJwtLifecycleTests: XCTestCase { XCTAssertTrue(jwtRepo.invalidateJwt(externalId: userA_EUID, rejectedToken: "token-a")) } + /// A reader on another queue, like the in-app message fetch, can catch the new user mid-login. It has to + /// find the token already there rather than ask the app for the one it just supplied. The gap is narrow, + /// so this logs in many times to give the reader a chance at it. + func testALoginWithATokenIsNeverCaughtWithoutOneFromAnotherQueue() { + OSCoreMocks.hydrateSharedJwtConfig(requiresUserAuth: true) + let manager = OneSignalUserManagerImpl.sharedInstance + let listener = MockUserJwtInvalidatedListener() + manager.addUserJwtInvalidatedListener(listener) + defer { manager.removeUserJwtInvalidatedListener(listener) } + + let lock = NSLock() + var reading = true + let readerFinished = expectation(description: "The reader stopped") + DispatchQueue.global().async { + while lock.withLock({ reading }) { + _ = manager.authorizationForCurrentUser() + } + readerFinished.fulfill() + } + + for i in 0..<200 { + manager.login(externalId: i % 2 == 0 ? userA_EUID : userB_EUID, token: "token-\(i)") + } + lock.withLock { reading = false } + wait(for: [readerFinished], timeout: 5) + allowAsyncWorkToRun(seconds: 0.5) + + XCTAssertEqual(listener.invalidatedExternalIds, []) + } + // MARK: - a rejected token on the first Create User /** From 247af25effb30d21f3f88ae575c97a854c8d35cc Mon Sep 17 00:00:00 2001 From: Fadi George Date: Thu, 19 Nov 2026 17:13:02 -0800 Subject: [PATCH 03/10] test: move the login race test into an extension to fit the type body limit Co-Authored-By: Claude Opus 5.5 --- .../UserJwtLifecycleTests.swift | 64 ++++++++++--------- 1 file changed, 34 insertions(+), 30 deletions(-) diff --git a/iOS_SDK/OneSignalSDK/OneSignalUserTests/UserJwtLifecycleTests.swift b/iOS_SDK/OneSignalSDK/OneSignalUserTests/UserJwtLifecycleTests.swift index f5d7065439..682336e9b9 100644 --- a/iOS_SDK/OneSignalSDK/OneSignalUserTests/UserJwtLifecycleTests.swift +++ b/iOS_SDK/OneSignalSDK/OneSignalUserTests/UserJwtLifecycleTests.swift @@ -292,36 +292,6 @@ final class UserJwtLifecycleTests: XCTestCase { XCTAssertTrue(jwtRepo.invalidateJwt(externalId: userA_EUID, rejectedToken: "token-a")) } - /// A reader on another queue, like the in-app message fetch, can catch the new user mid-login. It has to - /// find the token already there rather than ask the app for the one it just supplied. The gap is narrow, - /// so this logs in many times to give the reader a chance at it. - func testALoginWithATokenIsNeverCaughtWithoutOneFromAnotherQueue() { - OSCoreMocks.hydrateSharedJwtConfig(requiresUserAuth: true) - let manager = OneSignalUserManagerImpl.sharedInstance - let listener = MockUserJwtInvalidatedListener() - manager.addUserJwtInvalidatedListener(listener) - defer { manager.removeUserJwtInvalidatedListener(listener) } - - let lock = NSLock() - var reading = true - let readerFinished = expectation(description: "The reader stopped") - DispatchQueue.global().async { - while lock.withLock({ reading }) { - _ = manager.authorizationForCurrentUser() - } - readerFinished.fulfill() - } - - for i in 0..<200 { - manager.login(externalId: i % 2 == 0 ? userA_EUID : userB_EUID, token: "token-\(i)") - } - lock.withLock { reading = false } - wait(for: [readerFinished], timeout: 5) - allowAsyncWorkToRun(seconds: 0.5) - - XCTAssertEqual(listener.invalidatedExternalIds, []) - } - // MARK: - a rejected token on the first Create User /** @@ -568,3 +538,37 @@ final class UserJwtLifecycleTests: XCTestCase { XCTAssertEqual(pushSubscriptionPayload()["notification_types"] as? Int, optedInNotificationTypes) } } + +// MARK: - a login racing a reader on another queue + +extension UserJwtLifecycleTests { + /// A reader on another queue, like the in-app message fetch, can catch the new user mid-login. It has to + /// find the token already there rather than ask the app for the one it just supplied. The gap is narrow, + /// so this logs in many times to give the reader a chance at it. + func testALoginWithATokenIsNeverCaughtWithoutOneFromAnotherQueue() { + OSCoreMocks.hydrateSharedJwtConfig(requiresUserAuth: true) + let manager = OneSignalUserManagerImpl.sharedInstance + let listener = MockUserJwtInvalidatedListener() + manager.addUserJwtInvalidatedListener(listener) + defer { manager.removeUserJwtInvalidatedListener(listener) } + + let lock = NSLock() + var reading = true + let readerFinished = expectation(description: "The reader stopped") + DispatchQueue.global().async { + while lock.withLock({ reading }) { + _ = manager.authorizationForCurrentUser() + } + readerFinished.fulfill() + } + + for i in 0..<200 { + manager.login(externalId: i % 2 == 0 ? userA_EUID : userB_EUID, token: "token-\(i)") + } + lock.withLock { reading = false } + wait(for: [readerFinished], timeout: 5) + allowAsyncWorkToRun(seconds: 0.5) + + XCTAssertEqual(listener.invalidatedExternalIds, []) + } +} From bd0df824dff1ca34f78101f5149d80695d071c69 Mon Sep 17 00:00:00 2001 From: Fadi George Date: Thu, 19 Nov 2026 17:57:33 -0800 Subject: [PATCH 04/10] test: replace the login race stress test with a deterministic check The stress test could not catch the race without an injected delay, and the state its 200 logins left behind is the likely cause of a later test in the class timing out in CI. Co-Authored-By: Claude Opus 5.5 --- .../UserJwtLifecycleTests.swift | 43 ++++--------------- 1 file changed, 9 insertions(+), 34 deletions(-) diff --git a/iOS_SDK/OneSignalSDK/OneSignalUserTests/UserJwtLifecycleTests.swift b/iOS_SDK/OneSignalSDK/OneSignalUserTests/UserJwtLifecycleTests.swift index 682336e9b9..7a517cb086 100644 --- a/iOS_SDK/OneSignalSDK/OneSignalUserTests/UserJwtLifecycleTests.swift +++ b/iOS_SDK/OneSignalSDK/OneSignalUserTests/UserJwtLifecycleTests.swift @@ -292,6 +292,15 @@ final class UserJwtLifecycleTests: XCTestCase { XCTAssertTrue(jwtRepo.invalidateJwt(externalId: userA_EUID, rejectedToken: "token-a")) } + /// Another queue, like the in-app message fetch, can read the current user at any point during `login`, + /// so the user has to carry its token from the moment it is published or that reader asks the app for one. + func testANewUserIsPublishedWithTheTokenItLoggedInWith() { + let user = OneSignalUserManagerImpl.sharedInstance.setNewInternalUser( + externalId: userA_EUID, pushSubscriptionModel: nil, jwtBearerToken: "token-a") + + XCTAssertEqual(user.identityModel.jwtBearerToken, "token-a") + } + // MARK: - a rejected token on the first Create User /** @@ -538,37 +547,3 @@ final class UserJwtLifecycleTests: XCTestCase { XCTAssertEqual(pushSubscriptionPayload()["notification_types"] as? Int, optedInNotificationTypes) } } - -// MARK: - a login racing a reader on another queue - -extension UserJwtLifecycleTests { - /// A reader on another queue, like the in-app message fetch, can catch the new user mid-login. It has to - /// find the token already there rather than ask the app for the one it just supplied. The gap is narrow, - /// so this logs in many times to give the reader a chance at it. - func testALoginWithATokenIsNeverCaughtWithoutOneFromAnotherQueue() { - OSCoreMocks.hydrateSharedJwtConfig(requiresUserAuth: true) - let manager = OneSignalUserManagerImpl.sharedInstance - let listener = MockUserJwtInvalidatedListener() - manager.addUserJwtInvalidatedListener(listener) - defer { manager.removeUserJwtInvalidatedListener(listener) } - - let lock = NSLock() - var reading = true - let readerFinished = expectation(description: "The reader stopped") - DispatchQueue.global().async { - while lock.withLock({ reading }) { - _ = manager.authorizationForCurrentUser() - } - readerFinished.fulfill() - } - - for i in 0..<200 { - manager.login(externalId: i % 2 == 0 ? userA_EUID : userB_EUID, token: "token-\(i)") - } - lock.withLock { reading = false } - wait(for: [readerFinished], timeout: 5) - allowAsyncWorkToRun(seconds: 0.5) - - XCTAssertEqual(listener.invalidatedExternalIds, []) - } -} From 4c0291c07e0b71ccde8548bdf6d9fdad98398005 Mon Sep 17 00:00:00 2001 From: Fadi George Date: Thu, 19 Nov 2026 19:02:49 -0800 Subject: [PATCH 05/10] test: keep the combined property batch whole and explain two CI-only failures startNewSession unpauses the operation repo before it enqueues its Delta, so a poll in between split the batch. The identify and IAM fetch tests now report the models and requests involved, since they only fail in CI. Co-Authored-By: Claude Opus 5.5 --- .../IamFetchIdentityVerificationTests.swift | 12 +++++++++++- .../OneSignalUserTests/OneSignalUserTests.swift | 6 ++++++ .../OneSignalUserTests/UserStateReportingTests.swift | 11 ++++++++++- 3 files changed, 27 insertions(+), 2 deletions(-) diff --git a/iOS_SDK/OneSignalSDK/OneSignalInAppMessagesTests/IamFetchIdentityVerificationTests.swift b/iOS_SDK/OneSignalSDK/OneSignalInAppMessagesTests/IamFetchIdentityVerificationTests.swift index ce82ffd259..df83f0b538 100644 --- a/iOS_SDK/OneSignalSDK/OneSignalInAppMessagesTests/IamFetchIdentityVerificationTests.swift +++ b/iOS_SDK/OneSignalSDK/OneSignalInAppMessagesTests/IamFetchIdentityVerificationTests.swift @@ -172,6 +172,14 @@ final class IamFetchIdentityVerificationTests: XCTestCase { return executedFetches().last?.additionalHeaders?["Authorization"] } + /// The current user and what was sent, for a failure that only reproduces in CI. + private func describeCurrentUser() -> String { + let model = OneSignalUserManagerImpl.sharedInstance._user?.identityModel + let sent = client.executedRequests.map { "\($0) auth: \($0.additionalHeaders?["Authorization"] ?? "nil")" } + return "user: \(model?.externalId ?? "nil") \(model?.modelId ?? "nil") token: \(model?.jwtBearerToken ?? "nil"), " + + "pending asks: \(OneSignalUserManagerImpl.sharedInstance.userJwtRepo.pendingTokenAsks()), sent: \(sent)" + } + private func deferredSubscriptionId() -> String? { return OSMessagingController.sharedInstance().deferredFetchSubscriptionId } @@ -257,6 +265,8 @@ final class IamFetchIdentityVerificationTests: XCTestCase { /// The fetch is not a source of truth for whether a token is good, because the server can refuse it /// over a user and subscription it does not have paired. It parks, and the next token releases it. func testARejectedFetchParksWithoutReportingTheTokenItUsed() { + var whenAsked: [String] = [] + jwtListener.setCallback { whenAsked.append(self.describeCurrentUser()) } OSCoreMocks.hydrateSharedJwtConfig(requiresUserAuth: true) login(token: "token-a") rejectFetch(from: identifiedUserPath) @@ -265,7 +275,7 @@ final class IamFetchIdentityVerificationTests: XCTestCase { fetch() XCTAssertEqual(executedFetches().count, fetchesBefore + 1) - XCTAssertEqual(jwtListener.invalidatedExternalIds, []) + XCTAssertEqual(jwtListener.invalidatedExternalIds, [], "when asked: \(whenAsked), now: \(describeCurrentUser())") XCTAssertEqual(deferredSubscriptionId(), testPushSubId) // A token the app supplies for its own reasons, since the fetch never asked for one. diff --git a/iOS_SDK/OneSignalSDK/OneSignalUserTests/OneSignalUserTests.swift b/iOS_SDK/OneSignalSDK/OneSignalUserTests/OneSignalUserTests.swift index 42b18a85e7..07200a09e6 100644 --- a/iOS_SDK/OneSignalSDK/OneSignalUserTests/OneSignalUserTests.swift +++ b/iOS_SDK/OneSignalSDK/OneSignalUserTests/OneSignalUserTests.swift @@ -205,7 +205,13 @@ final class OneSignalUserTests: XCTestCase { // This adds a `session_count` property with value of 1 // It also sets `refresh_device_metadata` to `true` + // It unpauses the repo before enqueueing that Delta, so a poll in between would split the batch. + // Suspending the repo's queue keeps the poll from running until the repo is paused again. + let operationRepo = OneSignalUserManagerImpl.sharedInstance.operationRepo + operationRepo.dispatchQueue.suspend() OneSignalUserManagerImpl.sharedInstance.startNewSession() + operationRepo.paused = true + operationRepo.dispatchQueue.resume() /* Then */ diff --git a/iOS_SDK/OneSignalSDK/OneSignalUserTests/UserStateReportingTests.swift b/iOS_SDK/OneSignalSDK/OneSignalUserTests/UserStateReportingTests.swift index 1af0598be1..e05421999a 100644 --- a/iOS_SDK/OneSignalSDK/OneSignalUserTests/UserStateReportingTests.swift +++ b/iOS_SDK/OneSignalSDK/OneSignalUserTests/UserStateReportingTests.swift @@ -131,13 +131,15 @@ final class UserStateReportingTests: XCTestCase { OneSignalCoreMocks.waitUntil("The Identify User was not started") { self.client.startedRequestCount(ofType: OSRequestIdentifyUser.self) == 1 } + let modelA = OneSignalUserManagerImpl.sharedInstance.user.identityModel // B becomes current while A's Identify User is in flight. OneSignalUserManagerImpl.sharedInstance.login(externalId: userB_EUID, token: nil) client.releaseHeldResponses() waitForTheLoginToSettle() // Still hydrated, for anything queued behind it. - XCTAssertEqual(OneSignalUserManagerImpl.sharedInstance.identityModelRepo.get(externalId: userA_EUID)?.onesignalId, anonUserOSID) + XCTAssertEqual(OneSignalUserManagerImpl.sharedInstance.identityModelRepo.get(externalId: userA_EUID)?.onesignalId, anonUserOSID, + describeModels(for: userA_EUID, loggedIn: modelA)) XCTAssertFalse(observer.states.contains { $0.externalId == userA_EUID }, "the app must not hear about A: \(observer.states)") XCTAssertEqual(observer.states.last?.externalId, userB_EUID) assertPersistedSnapshotNames(externalId: userB_EUID, onesignalId: userB_OSID) @@ -198,6 +200,13 @@ final class UserStateReportingTests: XCTestCase { User starts. A fetch landing later would re-report the current user and hide a wrong report made in between. */ + /// Which models the repo holds for this user, and what was sent, for a failure that only reproduces in CI. + private func describeModels(for externalId: String, loggedIn: OSIdentityModel) -> String { + let models = OneSignalUserManagerImpl.sharedInstance.identityModelRepo.models.values.filter { $0.externalId == externalId } + let described = models.map { "\($0.modelId == loggedIn.modelId ? "login" : "other"): \($0.onesignalId ?? "nil")" } + return "models: \(described), executed: \(client.executedRequests)" + } + private func waitForTheLoginToSettle() { OneSignalCoreMocks.waitUntil("The login did not reach a reported user") { OneSignalUserManagerImpl.sharedInstance.user.identityModel.onesignalId != nil From b1c39e45fe136e4da391347576367099cc630719 Mon Sep 17 00:00:00 2001 From: Fadi George Date: Thu, 19 Nov 2026 19:18:48 -0800 Subject: [PATCH 06/10] test: read the subscription executor's own queue in the update race tests The persisted queue is shared with every executor, including ones earlier tests left running, so one could overwrite it while these tests waited. Co-Authored-By: Claude Opus 5.5 --- .../OSSubscriptionOperationExecutor.swift | 4 +-- .../SubscriptionUpdateRaceTests.swift | 34 ++++++++----------- 2 files changed, 17 insertions(+), 21 deletions(-) diff --git a/iOS_SDK/OneSignalSDK/OneSignalUser/Source/Executors/OSSubscriptionOperationExecutor.swift b/iOS_SDK/OneSignalSDK/OneSignalUser/Source/Executors/OSSubscriptionOperationExecutor.swift index 538859c837..2982a6b2cd 100644 --- a/iOS_SDK/OneSignalSDK/OneSignalUser/Source/Executors/OSSubscriptionOperationExecutor.swift +++ b/iOS_SDK/OneSignalSDK/OneSignalUser/Source/Executors/OSSubscriptionOperationExecutor.swift @@ -34,14 +34,14 @@ class OSSubscriptionOperationExecutor: OSOperationExecutor { // To simplify uncaching, we maintain separate request queues for each type private var addRequestQueue: [OSRequestCreateSubscription] = [] private var removeRequestQueue: [OSRequestDeleteSubscription] = [] - private var updateRequestQueue: [OSRequestUpdateSubscription] = [] + var updateRequestQueue: [OSRequestUpdateSubscription] = [] // non-private for unit test access private var subscriptionModels: [String: OSSubscriptionModel] = [:] private let newRecordsState: OSNewRecordsState private let auth: OSRequestAuthorizing private let retryBackoff: OSRequestRetryBackoff // The Subscription executor dispatch queue, serial. This synchronizes access to the delta and request queues. - private let dispatchQueue = DispatchQueue(label: "OneSignal.OSSubscriptionOperationExecutor", target: .global()) + let dispatchQueue = DispatchQueue(label: "OneSignal.OSSubscriptionOperationExecutor", target: .global()) init( newRecordsState: OSNewRecordsState, diff --git a/iOS_SDK/OneSignalSDK/OneSignalUserTests/Executors/SubscriptionUpdateRaceTests.swift b/iOS_SDK/OneSignalSDK/OneSignalUserTests/Executors/SubscriptionUpdateRaceTests.swift index a90dbf9136..596a0ba90b 100644 --- a/iOS_SDK/OneSignalSDK/OneSignalUserTests/Executors/SubscriptionUpdateRaceTests.swift +++ b/iOS_SDK/OneSignalSDK/OneSignalUserTests/Executors/SubscriptionUpdateRaceTests.swift @@ -100,11 +100,7 @@ final class SubscriptionUpdateRaceTests: XCTestCase { )) executor.processDeltaQueue(inBackground: false) OneSignalCoreMocks.waitUntil("Blocked subscription update was not cached") { - let requests = OneSignalUserDefaults.initShared().getSavedCodeableData( - forKey: OS_SUBSCRIPTION_EXECUTOR_UPDATE_REQUEST_QUEUE_KEY, - defaultValue: [] - ) as? [OSRequestUpdateSubscription] - return requests?.count == 1 + executor.snapshotUpdateRequestQueue().count == 1 } XCTAssertTrue(client.executedRequests.isEmpty, "Update should still be pending without subscriptionId") @@ -141,7 +137,7 @@ final class SubscriptionUpdateRaceTests: XCTestCase { XCTAssertFalse(sentMinus19, "Must not send stale enabled:false / notification_types:-19 after grant") XCTAssertTrue(allSubscribed, "All executed UpdateSubscription payloads should reflect the live subscribed model") XCTAssertEqual(updateRequests.count, 1, "Unsent updates for the same subscription should be coalesced") - waitForUpdateRequestQueueToDrain() + waitForUpdateRequestQueueToDrain(executor) } /** @@ -192,11 +188,7 @@ final class SubscriptionUpdateRaceTests: XCTestCase { )) executor.processDeltaQueue(inBackground: false) OneSignalCoreMocks.waitUntil("Follow-up subscription update was not queued") { - let requests = OneSignalUserDefaults.initShared().getSavedCodeableData( - forKey: OS_SUBSCRIPTION_EXECUTOR_UPDATE_REQUEST_QUEUE_KEY, - defaultValue: [] - ) as? [OSRequestUpdateSubscription] - return requests?.count == 2 + executor.snapshotUpdateRequestQueue().count == 2 } XCTAssertEqual(client.startedRequests.count, 1, "Follow-up must wait for in-flight UpdateSubscription") @@ -209,7 +201,7 @@ final class SubscriptionUpdateRaceTests: XCTestCase { XCTAssertEqual(client.startedRequests.count, 2, "Pending follow-up should send after in-flight completes") try assertSubscribedPayload(client.startedRequests[1]) waitForCompletedUpdateRequests(client, expectedCount: 2) - waitForUpdateRequestQueueToDrain() + waitForUpdateRequestQueueToDrain(executor) } /** @@ -280,7 +272,7 @@ final class SubscriptionUpdateRaceTests: XCTestCase { let lastPayload = try XCTUnwrap(updateRequests.last?.parameters?["subscription"] as? [String: Any]) XCTAssertEqual(lastPayload["notification_types"] as? Int, subscribedNotificationTypes) XCTAssertEqual(lastPayload["enabled"] as? Bool, true) - waitForUpdateRequestQueueToDrain() + waitForUpdateRequestQueueToDrain(executor) } // MARK: - Helpers @@ -298,13 +290,9 @@ final class SubscriptionUpdateRaceTests: XCTestCase { return model } - private func waitForUpdateRequestQueueToDrain() { + private func waitForUpdateRequestQueueToDrain(_ executor: OSSubscriptionOperationExecutor) { OneSignalCoreMocks.waitUntil("Subscription executor cleanup did not complete") { - let requests = OneSignalUserDefaults.initShared().getSavedCodeableData( - forKey: OS_SUBSCRIPTION_EXECUTOR_UPDATE_REQUEST_QUEUE_KEY, - defaultValue: [] - ) as? [OSRequestUpdateSubscription] - return requests?.isEmpty == true + executor.snapshotUpdateRequestQueue().isEmpty } } @@ -322,3 +310,11 @@ final class SubscriptionUpdateRaceTests: XCTestCase { XCTAssertEqual(payload["enabled"] as? Bool, true) } } + +private extension OSSubscriptionOperationExecutor { + /// This executor's queue. The persisted copy is shared with every other executor, including ones + /// earlier tests left running, so a test cannot rely on it naming this executor's requests. + func snapshotUpdateRequestQueue() -> [OSRequestUpdateSubscription] { + return dispatchQueue.sync { updateRequestQueue } + } +} From b1fbe88a2703dac493f84b44a9776390506ffa5b Mon Sep 17 00:00:00 2001 From: Fadi George Date: Thu, 19 Nov 2026 22:21:50 -0800 Subject: [PATCH 07/10] test: report token state when the JWT pending-ask test times out Co-Authored-By: Claude Opus 5.5 --- .../UserJwtLifecycleTests.swift | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/iOS_SDK/OneSignalSDK/OneSignalUserTests/UserJwtLifecycleTests.swift b/iOS_SDK/OneSignalSDK/OneSignalUserTests/UserJwtLifecycleTests.swift index 7a517cb086..f8bf4f32ea 100644 --- a/iOS_SDK/OneSignalSDK/OneSignalUserTests/UserJwtLifecycleTests.swift +++ b/iOS_SDK/OneSignalSDK/OneSignalUserTests/UserJwtLifecycleTests.swift @@ -273,9 +273,10 @@ final class UserJwtLifecycleTests: XCTestCase { // The Create User parks for want of a token, which asks the app once. `pendingTokenAsks` reads // the ask without consuming it, unlike `askForToken`. OneSignalUserManagerImpl.sharedInstance.login(externalId: userA_EUID, token: nil) - OneSignalCoreMocks.waitUntil("The parked Create User did not ask for a token") { + let asked = OneSignalCoreMocks.waitUntilForObjC(timeout: 5) { jwtRepo.pendingTokenAsks().contains(userA_EUID) } + XCTAssertTrue(asked, "The parked Create User did not ask for a token. \(describeTokenState())") // Log back in as the same user, which builds a new Identity Model rather than reusing the parked one. OneSignalUserManagerImpl.sharedInstance.logout() @@ -547,3 +548,16 @@ final class UserJwtLifecycleTests: XCTestCase { XCTAssertEqual(pushSubscriptionPayload()["notification_types"] as? Int, optedInNotificationTypes) } } + +private extension UserJwtLifecycleTests { + func describeTokenState() -> String { + let manager = OneSignalUserManagerImpl.sharedInstance + let model = manager._user?.identityModel + let queued = queuedUserRequests().map { "\($0) sent: \($0.sentToClient)" } + let sent = client.executedRequests.map { "\($0) auth: \($0.additionalHeaders?["Authorization"] ?? "nil")" } + return "requirement: \(manager.identityVerificationService.requirement), " + + "user: \(model?.externalId ?? "nil") \(model?.modelId ?? "nil") token: \(model?.jwtBearerToken ?? "nil"), " + + "pending asks: \(manager.userJwtRepo.pendingTokenAsks()), repo paused: \(manager.operationRepo.paused), " + + "queued: \(queued), sent: \(sent)" + } +} From 4f8a1e99f5b185d5a85d2752e9b6f2ba59868c34 Mon Sep 17 00:00:00 2001 From: Fadi George Date: Thu, 19 Nov 2026 23:07:29 -0800 Subject: [PATCH 08/10] test: isolate the JWT pending-ask test from user A state an earlier test left behind Co-Authored-By: Claude Opus 5.5 --- .../UserJwtLifecycleTests.swift | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/iOS_SDK/OneSignalSDK/OneSignalUserTests/UserJwtLifecycleTests.swift b/iOS_SDK/OneSignalSDK/OneSignalUserTests/UserJwtLifecycleTests.swift index f8bf4f32ea..48a6115d26 100644 --- a/iOS_SDK/OneSignalSDK/OneSignalUserTests/UserJwtLifecycleTests.swift +++ b/iOS_SDK/OneSignalSDK/OneSignalUserTests/UserJwtLifecycleTests.swift @@ -269,28 +269,32 @@ final class UserJwtLifecycleTests: XCTestCase { func testLoggingInWithATokenAnswersAPendingAskForThatUser() { OSCoreMocks.hydrateSharedJwtConfig(requiresUserAuth: true) let jwtRepo = OneSignalUserManagerImpl.sharedInstance.userJwtRepo + // A user no other test logs in as: an earlier test's executors can still be persisting user A's + // Requests after teardown, and the next `start` uncaches them along with user A's token. + let externalId = "pending-ask-user" + MockUserRequests.setDefaultCreateUserResponses(with: client, externalId: externalId) // The Create User parks for want of a token, which asks the app once. `pendingTokenAsks` reads // the ask without consuming it, unlike `askForToken`. - OneSignalUserManagerImpl.sharedInstance.login(externalId: userA_EUID, token: nil) + OneSignalUserManagerImpl.sharedInstance.login(externalId: externalId, token: nil) let asked = OneSignalCoreMocks.waitUntilForObjC(timeout: 5) { - jwtRepo.pendingTokenAsks().contains(userA_EUID) + jwtRepo.pendingTokenAsks().contains(externalId) } XCTAssertTrue(asked, "The parked Create User did not ask for a token. \(describeTokenState())") // Log back in as the same user, which builds a new Identity Model rather than reusing the parked one. OneSignalUserManagerImpl.sharedInstance.logout() - OneSignalUserManagerImpl.sharedInstance.login(externalId: userA_EUID, token: "token-a") + OneSignalUserManagerImpl.sharedInstance.login(externalId: externalId, token: "token-a") // Rejecting the token reads the Identity Model the login hydrates, so let the login finish // rather than stopping at the point the token is merely stored. waitForTheLoginToSettle() OneSignalCoreMocks.waitUntil("The replacement token was not stored") { - jwtRepo.validJwt(externalId: userA_EUID) == "token-a" + jwtRepo.validJwt(externalId: externalId) == "token-a" } - XCTAssertEqual(jwtRepo.validJwt(externalId: userA_EUID), "token-a") + XCTAssertEqual(jwtRepo.validJwt(externalId: externalId), "token-a") // `true` means this rejection reached the app, which only happens once the earlier ask was answered. - XCTAssertTrue(jwtRepo.invalidateJwt(externalId: userA_EUID, rejectedToken: "token-a")) + XCTAssertTrue(jwtRepo.invalidateJwt(externalId: externalId, rejectedToken: "token-a")) } /// Another queue, like the in-app message fetch, can read the current user at any point during `login`, From ddbc74a5568d4e72f39c020bd1aaf33eacff1545 Mon Sep 17 00:00:00 2001 From: Fadi George Date: Fri, 20 Nov 2026 11:00:47 -0800 Subject: [PATCH 09/10] test: drive the token race test through login and stop asserting in the unawaited badge completion Co-Authored-By: Claude Opus 5.5 --- .../OneSignalNotificationsTests.swift | 12 ++-- .../UserJwtLifecycleTests.swift | 55 ++++++++++++++++--- 2 files changed, 50 insertions(+), 17 deletions(-) diff --git a/iOS_SDK/OneSignalSDK/OneSignalNotificationsTests/OneSignalNotificationsTests.swift b/iOS_SDK/OneSignalSDK/OneSignalNotificationsTests/OneSignalNotificationsTests.swift index a1e08c88d1..c4b5226163 100644 --- a/iOS_SDK/OneSignalSDK/OneSignalNotificationsTests/OneSignalNotificationsTests.swift +++ b/iOS_SDK/OneSignalSDK/OneSignalNotificationsTests/OneSignalNotificationsTests.swift @@ -46,18 +46,14 @@ final class OneSignalNotificationsTests: XCTestCase { } /// Helper to set badge count - private func setBadgeCount(_ count: Int, completion: @escaping () -> Void = {}) { + /// Nothing waits for the system's completion, so it must not assert: a late error would fail whichever + /// test is running by then. + private func setBadgeCount(_ count: Int) { if #available(iOS 16.0, *) { - UNUserNotificationCenter.current().setBadgeCount(count) { error in - if let error = error { - XCTFail("Failed to set badge count: \(error)") - } - completion() - } + UNUserNotificationCenter.current().setBadgeCount(count, withCompletionHandler: nil) } else { // Fallback for iOS 15 and earlier UIApplication.shared.applicationIconBadgeNumber = count - completion() } } diff --git a/iOS_SDK/OneSignalSDK/OneSignalUserTests/UserJwtLifecycleTests.swift b/iOS_SDK/OneSignalSDK/OneSignalUserTests/UserJwtLifecycleTests.swift index 48a6115d26..941df4e76f 100644 --- a/iOS_SDK/OneSignalSDK/OneSignalUserTests/UserJwtLifecycleTests.swift +++ b/iOS_SDK/OneSignalSDK/OneSignalUserTests/UserJwtLifecycleTests.swift @@ -41,6 +41,31 @@ private class MockUserStateObserver: NSObject, OSUserStateObserver { } } +/// Forwards to the store's own listener, which the producer's single subscriber slot would otherwise drop. +private class IdentityModelAddRecorder: OSModelStoreChangedHandler { + private let forwardee: OSModelStoreChangedHandler? + var tokensWhenAdded: [String?] = [] + + init(forwardingTo forwardee: OSModelStoreChangedHandler?) { + self.forwardee = forwardee + } + + func onAdded(_ model: OSModel) { + if let identityModel = model as? OSIdentityModel, identityModel.externalId == userA_EUID { + tokensWhenAdded.append(identityModel.jwtBearerToken) + } + forwardee?.onAdded(model) + } + + func onUpdated(_ args: OSModelChangedArgs) { + forwardee?.onUpdated(args) + } + + func onRemoved(_ model: OSModel) { + forwardee?.onRemoved(model) + } +} + /** What `login` and `logout` do differently under Identity Verification: no anonymous user is ever sent to the server, so login creates rather than promotes and logout has to silence the push subscription itself. @@ -297,15 +322,6 @@ final class UserJwtLifecycleTests: XCTestCase { XCTAssertTrue(jwtRepo.invalidateJwt(externalId: externalId, rejectedToken: "token-a")) } - /// Another queue, like the in-app message fetch, can read the current user at any point during `login`, - /// so the user has to carry its token from the moment it is published or that reader asks the app for one. - func testANewUserIsPublishedWithTheTokenItLoggedInWith() { - let user = OneSignalUserManagerImpl.sharedInstance.setNewInternalUser( - externalId: userA_EUID, pushSubscriptionModel: nil, jwtBearerToken: "token-a") - - XCTAssertEqual(user.identityModel.jwtBearerToken, "token-a") - } - // MARK: - a rejected token on the first Create User /** @@ -553,6 +569,27 @@ final class UserJwtLifecycleTests: XCTestCase { } } +extension UserJwtLifecycleTests { + /// Another queue, like the in-app message fetch, can read the current user at any point during `login`, + /// so the user has to carry its token from the moment it is published or that reader asks the app for one. + /// The Identity Model enters the store just before the user is published, and the token `login` stores + /// afterwards would land too late to show up here. + func testLoginPublishesTheNewUserWithTheTokenItLoggedInWith() { + OSCoreMocks.hydrateSharedJwtConfig(requiresUserAuth: true) + // `start` subscribes the store's own listener, which would replace the recorder. + OneSignalUserManagerImpl.sharedInstance.start() + let changeSubscription = OneSignalUserManagerImpl.sharedInstance.identityModelStore.changeSubscription + let storeListener = changeSubscription.subscriber + let recorder = IdentityModelAddRecorder(forwardingTo: storeListener) + changeSubscription.subscriber = recorder + defer { changeSubscription.subscriber = storeListener } + + OneSignalUserManagerImpl.sharedInstance.login(externalId: userA_EUID, token: "token-a") + + XCTAssertEqual(recorder.tokensWhenAdded, ["token-a"]) + } +} + private extension UserJwtLifecycleTests { func describeTokenState() -> String { let manager = OneSignalUserManagerImpl.sharedInstance From 465be6df82893a32974905fb6aedd51b2ff2506f Mon Sep 17 00:00:00 2001 From: Fadi George Date: Fri, 20 Nov 2026 11:32:35 -0800 Subject: [PATCH 10/10] test: give waitUntil a 15s default so a stalled CI runner does not fail a wait Co-Authored-By: Claude Opus 5.5 --- .../OneSignalSDK/OneSignalCoreMocks/OneSignalCoreMocks.swift | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/iOS_SDK/OneSignalSDK/OneSignalCoreMocks/OneSignalCoreMocks.swift b/iOS_SDK/OneSignalSDK/OneSignalCoreMocks/OneSignalCoreMocks.swift index a05160c99a..050786df19 100644 --- a/iOS_SDK/OneSignalSDK/OneSignalCoreMocks/OneSignalCoreMocks.swift +++ b/iOS_SDK/OneSignalSDK/OneSignalCoreMocks/OneSignalCoreMocks.swift @@ -43,9 +43,11 @@ public class OneSignalCoreMocks: NSObject { } } + /// The timeout only bounds a failure: a met condition returns at once. CI runners can stall for + /// several seconds at a time, so it is generous. public static func waitUntil( _ description: String, - timeout: TimeInterval = 5, + timeout: TimeInterval = 15, file: StaticString = #filePath, line: UInt = #line, condition: @escaping () -> Bool