From 1b2e171a60fe3ec5babdf208b949442fe12f9cb8 Mon Sep 17 00:00:00 2001 From: AR Abdul Azeez Date: Tue, 27 Oct 2026 08:57:07 -0500 Subject: [PATCH 1/4] fix: merge the anonymous user on composite login Composite login creates the user directly, so data set on the anonymous user before login was left behind. It now sends the anonymous user's onesignal_id with the external ID, and Create User attaches the external ID to that user, matching what login(externalId) does through SetAlias. A 409 means the external ID already belongs to another user, so it retries without the onesignal_id. Co-authored-by: Cursor --- OneSignalSDK/detekt/detekt-baseline-core.xml | 6 +- .../executors/LoginUserOperationExecutor.kt | 15 +++++ .../LoginUserOperationExecutorTests.kt | 58 +++++++++++++++++++ 3 files changed, 76 insertions(+), 3 deletions(-) diff --git a/OneSignalSDK/detekt/detekt-baseline-core.xml b/OneSignalSDK/detekt/detekt-baseline-core.xml index 74e9f501d2..40db555e47 100644 --- a/OneSignalSDK/detekt/detekt-baseline-core.xml +++ b/OneSignalSDK/detekt/detekt-baseline-core.xml @@ -8,7 +8,7 @@ ComplexMethod:ConfigModelStoreListener.kt$ConfigModelStoreListener$private fun fetchParams() ComplexMethod:HttpClient.kt$HttpClient$private suspend fun makeRequestIODispatcher( url: String, method: String?, jsonBody: JSONObject?, timeout: Int, headers: OptionalHeaders?, ): HttpResponse ComplexMethod:IdentityOperationExecutor.kt$IdentityOperationExecutor$override suspend fun execute(operations: List<Operation>): ExecutionResponse - ComplexMethod:LoginUserOperationExecutor.kt$LoginUserOperationExecutor$private suspend fun createUser( createUserOperation: LoginUserOperation, operations: List<Operation>, ): ExecutionResponse + ComplexMethod:LoginUserOperationExecutor.kt$LoginUserOperationExecutor$private suspend fun createUser( createUserOperation: LoginUserOperation, operations: List<Operation>, mergeIntoOnesignalId: String? = null, ): ExecutionResponse ComplexMethod:OSDatabase.kt$OSDatabase$@Synchronized private fun internalOnUpgrade( db: SQLiteDatabase, oldVersion: Int, newVersion: Int, ) ComplexMethod:OperationModelStore.kt$OperationModelStore$override fun create(jsonObject: JSONObject?): Operation? ComplexMethod:OperationRepo.kt$OperationRepo$internal suspend fun executeOperations(ops: List<OperationQueueItem>) @@ -194,7 +194,7 @@ LongMethod:FeatureFlagsBackendService.kt$FeatureFlagsBackendService$override suspend fun fetchRemoteFeatureFlags(appId: String): RemoteFeatureFlagsFetchOutcome LongMethod:HttpClient.kt$HttpClient$private suspend fun makeRequestIODispatcher( url: String, method: String?, jsonBody: JSONObject?, timeout: Int, headers: OptionalHeaders?, ): HttpResponse LongMethod:IdentityOperationExecutor.kt$IdentityOperationExecutor$override suspend fun execute(operations: List<Operation>): ExecutionResponse - LongMethod:LoginUserOperationExecutor.kt$LoginUserOperationExecutor$private suspend fun createUser( createUserOperation: LoginUserOperation, operations: List<Operation>, ): ExecutionResponse + LongMethod:LoginUserOperationExecutor.kt$LoginUserOperationExecutor$private suspend fun createUser( createUserOperation: LoginUserOperation, operations: List<Operation>, mergeIntoOnesignalId: String? = null, ): ExecutionResponse LongMethod:LoginUserOperationExecutor.kt$LoginUserOperationExecutor$private suspend fun loginUser( loginUserOp: LoginUserOperation, operations: List<Operation>, ): ExecutionResponse LongMethod:OperationRepo.kt$OperationRepo$internal suspend fun executeOperations(ops: List<OperationQueueItem>) LongMethod:OperationRepo.kt$OperationRepo$private fun internalEnqueue( queueItem: OperationQueueItem, flush: Boolean, addToStore: Boolean, index: Int? = null, ) @@ -293,7 +293,7 @@ NestedBlockDepth:IdentityOperationExecutor.kt$IdentityOperationExecutor$override suspend fun execute(operations: List<Operation>): ExecutionResponse NestedBlockDepth:InfluenceManager.kt$InfluenceManager$private fun attemptSessionUpgrade( entryAction: AppEntryAction, directId: String? = null, ) NestedBlockDepth:JSONUtils.kt$JSONUtils$fun compareJSONArrays( jsonArray1: JSONArray?, jsonArray2: JSONArray?, ): Boolean - NestedBlockDepth:LoginUserOperationExecutor.kt$LoginUserOperationExecutor$private suspend fun createUser( createUserOperation: LoginUserOperation, operations: List<Operation>, ): ExecutionResponse + NestedBlockDepth:LoginUserOperationExecutor.kt$LoginUserOperationExecutor$private suspend fun createUser( createUserOperation: LoginUserOperation, operations: List<Operation>, mergeIntoOnesignalId: String? = null, ): ExecutionResponse NestedBlockDepth:RefreshUserOperationExecutor.kt$RefreshUserOperationExecutor$private suspend fun getUser(op: RefreshUserOperation): ExecutionResponse NestedBlockDepth:ServiceRegistration.kt$ServiceRegistrationReflection$override fun resolve(provider: IServiceProvider): Any? NestedBlockDepth:ServiceRegistration.kt$ServiceRegistrationReflection$private fun doesHaveAllParameters( constructor: Constructor<*>, provider: IServiceProvider, ): Boolean diff --git a/OneSignalSDK/onesignal/core/src/main/java/com/onesignal/user/internal/operations/impl/executors/LoginUserOperationExecutor.kt b/OneSignalSDK/onesignal/core/src/main/java/com/onesignal/user/internal/operations/impl/executors/LoginUserOperationExecutor.kt index a325fd2a53..aae025b2f3 100644 --- a/OneSignalSDK/onesignal/core/src/main/java/com/onesignal/user/internal/operations/impl/executors/LoginUserOperationExecutor.kt +++ b/OneSignalSDK/onesignal/core/src/main/java/com/onesignal/user/internal/operations/impl/executors/LoginUserOperationExecutor.kt @@ -100,6 +100,11 @@ internal class LoginUserOperationExecutor( // rewrite the call to identify by the new (not-yet-registered) `external_id`, producing // a 404 or idempotent success against the wrong user. createUser's identities-map path // handles the merge correctly through backend upsert semantics. + anonymousUserToMerge(loginUserOp, alias)?.let { anonymousId -> + val merged = createUser(loginUserOp, operations, anonymousId) + // 409: the external ID already belongs to another user, so there is nothing to merge into. + if (merged.httpStatusCode != HTTP_CONFLICT) return merged + } return createUser(loginUserOp, operations) } else { // before we create a user we attempt to associate the user defined by existingOnesignalId with the @@ -179,8 +184,10 @@ internal class LoginUserOperationExecutor( private suspend fun createUser( createUserOperation: LoginUserOperation, operations: List, + mergeIntoOnesignalId: String? = null, ): ExecutionResponse { val identities = mutableMapOf() + mergeIntoOnesignalId?.let { identities[IdentityConstants.ONESIGNAL_ID] = it } var subscriptions = mapOf() val properties = PropertiesObject( @@ -469,6 +476,13 @@ internal class LoginUserOperationExecutor( return op.existingOnesignalId == null || alias == null } + // A profile login sends the anonymous user's ID with the new external ID, so Create User attaches + // the external ID to that user instead of creating a new one, like the SetAlias path does. + private fun anonymousUserToMerge(op: LoginUserOperation, alias: String?): String? { + if (!op.hasProfileFields() || _identityVerificationService.ivBehaviorActive || alias == null) return null + return op.existingOnesignalId?.takeUnless { IDManager.isLocalId(it) } + } + private fun backendExecutionResponse( result: ExecutionResult, ex: BackendException, @@ -481,6 +495,7 @@ internal class LoginUserOperationExecutor( companion object { const val LOGIN_USER = "login-user" + private const val HTTP_CONFLICT = 409 } } diff --git a/OneSignalSDK/onesignal/core/src/test/java/com/onesignal/user/internal/operations/LoginUserOperationExecutorTests.kt b/OneSignalSDK/onesignal/core/src/test/java/com/onesignal/user/internal/operations/LoginUserOperationExecutorTests.kt index 63bf4ed713..94ea1194ed 100644 --- a/OneSignalSDK/onesignal/core/src/test/java/com/onesignal/user/internal/operations/LoginUserOperationExecutorTests.kt +++ b/OneSignalSDK/onesignal/core/src/test/java/com/onesignal/user/internal/operations/LoginUserOperationExecutorTests.kt @@ -6,6 +6,7 @@ import br.com.colman.kotest.android.extensions.robolectric.RobolectricTest import com.onesignal.OneSignalUserProfile import com.onesignal.common.AndroidUtils import com.onesignal.common.DeviceUtils +import com.onesignal.common.IDManager import com.onesignal.common.OneSignalUtils import com.onesignal.common.PIIHasher import com.onesignal.common.RootToolsInternalMethods @@ -1650,6 +1651,63 @@ class LoginUserOperationExecutorTests : FunSpec({ coVerify(exactly = 0) { identityExecutor.execute(any()) } } + test("composite login from an anonymous user sends its onesignal_id so the user is merged") { + val mockUserBackendService = mockk() + coEvery { mockUserBackendService.createUser(any(), any(), any(), any()) } returns + CreateUserResponse(mapOf(IdentityConstants.ONESIGNAL_ID to "existing-osid"), PropertiesObject(), listOf()) + + val response = + profileExecutor(mockUserBackendService).execute( + listOf(LoginUserOperation(appId, localOneSignalId, "externalId", "existing-osid", OneSignalUserProfile(tags = mapOf("plan" to "pro")))), + ) + + response.result shouldBe ExecutionResult.SUCCESS + response.idTranslations shouldBe mapOf(localOneSignalId to "existing-osid") + coVerify(exactly = 1) { + mockUserBackendService.createUser( + appId, + mapOf(IdentityConstants.EXTERNAL_ID to "externalId", IdentityConstants.ONESIGNAL_ID to "existing-osid"), + any(), + any(), + ) + } + } + + test("composite login retries without onesignal_id when the external ID belongs to another user") { + val mockUserBackendService = mockk() + val mergeIdentities = mapOf(IdentityConstants.EXTERNAL_ID to "externalId", IdentityConstants.ONESIGNAL_ID to "existing-osid") + val plainIdentities = mapOf(IdentityConstants.EXTERNAL_ID to "externalId") + coEvery { mockUserBackendService.createUser(appId, mergeIdentities, any(), any()) } throws BackendException(409, "user-1") + coEvery { mockUserBackendService.createUser(appId, plainIdentities, any(), any()) } returns + CreateUserResponse(mapOf(IdentityConstants.ONESIGNAL_ID to remoteOneSignalId), PropertiesObject(), listOf()) + + val response = + profileExecutor(mockUserBackendService).execute( + listOf(LoginUserOperation(appId, localOneSignalId, "externalId", "existing-osid", OneSignalUserProfile(tags = mapOf("plan" to "pro")))), + ) + + response.result shouldBe ExecutionResult.SUCCESS + response.idTranslations shouldBe mapOf(localOneSignalId to remoteOneSignalId) + coVerify(exactly = 1) { mockUserBackendService.createUser(appId, mergeIdentities, any(), any()) } + coVerify(exactly = 1) { mockUserBackendService.createUser(appId, plainIdentities, any(), any()) } + } + + test("composite login does not merge when the anonymous user is still local, or under IV") { + for ((existingId, ivActive) in listOf(IDManager.createLocalId() to false, "existing-osid" to true)) { + val mockUserBackendService = mockk() + coEvery { mockUserBackendService.createUser(any(), any(), any(), any(), any()) } returns + CreateUserResponse(mapOf(IdentityConstants.ONESIGNAL_ID to remoteOneSignalId), PropertiesObject(), listOf()) + + profileExecutor(mockUserBackendService, ivActive = ivActive).execute( + listOf(LoginUserOperation(appId, localOneSignalId, "externalId", existingId, OneSignalUserProfile(tags = mapOf("plan" to "pro")))), + ) + + coVerify(exactly = 1) { + mockUserBackendService.createUser(appId, mapOf(IdentityConstants.EXTERNAL_ID to "externalId"), any(), any(), any()) + } + } + } + test("identity-only login still associates via SetAlias when existingOnesignalId is set") { val mockUserBackendService = mockk() val identityExecutor = mockk() From 638a53c427af7e38db2ac0c8410e7d27303df04a Mon Sep 17 00:00:00 2001 From: AR Abdul Azeez Date: Tue, 27 Oct 2026 12:20:40 -0500 Subject: [PATCH 2/4] fix: [SDK-5615] recover composite login when the anonymous merge cannot be kept A non-conflict failure was dropped. Retry Create User without onesignal_id, and skip that retry when the 409 is an alias conflict. Co-authored-by: Cursor --- .../executors/LoginUserOperationExecutor.kt | 68 +++++++++++++------ .../LoginUserOperationExecutorTests.kt | 44 +++++++++++- 2 files changed, 91 insertions(+), 21 deletions(-) diff --git a/OneSignalSDK/onesignal/core/src/main/java/com/onesignal/user/internal/operations/impl/executors/LoginUserOperationExecutor.kt b/OneSignalSDK/onesignal/core/src/main/java/com/onesignal/user/internal/operations/impl/executors/LoginUserOperationExecutor.kt index aae025b2f3..c8e90a2b8e 100644 --- a/OneSignalSDK/onesignal/core/src/main/java/com/onesignal/user/internal/operations/impl/executors/LoginUserOperationExecutor.kt +++ b/OneSignalSDK/onesignal/core/src/main/java/com/onesignal/user/internal/operations/impl/executors/LoginUserOperationExecutor.kt @@ -46,6 +46,8 @@ import com.onesignal.user.internal.subscriptions.SubscriptionModel import com.onesignal.user.internal.subscriptions.SubscriptionModelStore import com.onesignal.user.internal.subscriptions.SubscriptionStatus import com.onesignal.user.internal.subscriptions.SubscriptionType +import org.json.JSONException +import org.json.JSONObject @Suppress("TooManyFunctions") internal class LoginUserOperationExecutor( @@ -91,19 +93,11 @@ internal class LoginUserOperationExecutor( return ExecutionResponse(ExecutionResult.FAIL_NORETRY) } if (shouldCreateUserDirectly(loginUserOp, alias)) { - // When there is no existing user to attempt to associate with the externalId provided, we go right to - // createUser. If there is no externalId provided this is an insert, if there is this will be an - // "upsert with retrieval" as the user may already exist. - // - // Under IV, also skip the optimistic SetAliasOperation: that inline op identifies the - // target user by `onesignal_id = existingOnesignalId`, but IV's alias-resolution would - // rewrite the call to identify by the new (not-yet-registered) `external_id`, producing - // a 404 or idempotent success against the wrong user. createUser's identities-map path - // handles the merge correctly through backend upsert semantics. + // A server anonymous user is merged by sending its onesignal_id. Under IV, skip + // SetAlias: alias resolution would target the new external_id and 404 or hit the wrong user. anonymousUserToMerge(loginUserOp, alias)?.let { anonymousId -> val merged = createUser(loginUserOp, operations, anonymousId) - // 409: the external ID already belongs to another user, so there is nothing to merge into. - if (merged.httpStatusCode != HTTP_CONFLICT) return merged + if (!shouldAbandonMerge(merged)) return merged } return createUser(loginUserOp, operations) } else { @@ -321,17 +315,23 @@ internal class LoginUserOperationExecutor( metadata = LoginWaitMetadata(backendOneSignalId, emailSubscriptionId, smsSubscriptionId), ) } catch (ex: BackendException) { - Logging.error("LoginUserOperationExecutor.createUser failed: HTTP ${ex.statusCode}") val responseType = NetworkUtils.getResponseStatusType(ex.statusCode) - - return when (responseType) { - NetworkUtils.ResponseStatusType.RETRYABLE -> - backendExecutionResponse(ExecutionResult.FAIL_RETRY, ex) - NetworkUtils.ResponseStatusType.UNAUTHORIZED -> - backendExecutionResponse(ExecutionResult.FAIL_UNAUTHORIZED, ex) - else -> - backendExecutionResponse(ExecutionResult.FAIL_NORETRY, ex) + val response = + when (responseType) { + NetworkUtils.ResponseStatusType.RETRYABLE -> + backendExecutionResponse(ExecutionResult.FAIL_RETRY, ex) + NetworkUtils.ResponseStatusType.UNAUTHORIZED -> + backendExecutionResponse(ExecutionResult.FAIL_UNAUTHORIZED, ex) + else -> + backendExecutionResponse(ExecutionResult.FAIL_NORETRY, ex) + } + // The caller retries an abandoned merge, so this failure is not the outcome. + if (mergeIntoOnesignalId != null && shouldAbandonMerge(response)) { + Logging.debug("LoginUserOperationExecutor merge attempt failed: HTTP ${ex.statusCode}") + } else { + Logging.error("LoginUserOperationExecutor.createUser failed: HTTP ${ex.statusCode}") } + return response } } @@ -483,6 +483,33 @@ internal class LoginUserOperationExecutor( return op.existingOnesignalId?.takeUnless { IDManager.isLocalId(it) } } + // Drop the anonymous id and create the identified user. A readable 409 retries only + // when onesignal_id collided, or the code is user-2. An alias conflict is final. + private fun shouldAbandonMerge(response: ExecutionResponse): Boolean { + if (response.result != ExecutionResult.FAIL_NORETRY) return false + if (response.httpStatusCode != HTTP_CONFLICT) return true + return onesignalIdConflict(response.httpResponse) != false + } + + /** False when the body is a conflict that does not name onesignal_id. Null when it cannot be read. */ + private fun onesignalIdConflict(body: String?): Boolean? { + if (body.isNullOrBlank()) return null + return try { + val errors = JSONObject(body).optJSONArray("errors") ?: return null + var sawConflict = false + for (index in 0 until errors.length()) { + val error = errors.optJSONObject(index) ?: continue + sawConflict = true + if (error.optString("code") == ALIAS_CLAIMED_BY_ANOTHER_USER) return true + val aliases = error.optJSONObject("meta")?.optJSONObject("conflicting_aliases") + if (aliases?.has(IdentityConstants.ONESIGNAL_ID) == true) return true + } + if (sawConflict) false else null + } catch (_: JSONException) { + null + } + } + private fun backendExecutionResponse( result: ExecutionResult, ex: BackendException, @@ -496,6 +523,7 @@ internal class LoginUserOperationExecutor( companion object { const val LOGIN_USER = "login-user" private const val HTTP_CONFLICT = 409 + private const val ALIAS_CLAIMED_BY_ANOTHER_USER = "user-2" } } diff --git a/OneSignalSDK/onesignal/core/src/test/java/com/onesignal/user/internal/operations/LoginUserOperationExecutorTests.kt b/OneSignalSDK/onesignal/core/src/test/java/com/onesignal/user/internal/operations/LoginUserOperationExecutorTests.kt index 94ea1194ed..3bc086f83e 100644 --- a/OneSignalSDK/onesignal/core/src/test/java/com/onesignal/user/internal/operations/LoginUserOperationExecutorTests.kt +++ b/OneSignalSDK/onesignal/core/src/test/java/com/onesignal/user/internal/operations/LoginUserOperationExecutorTests.kt @@ -1677,7 +1677,31 @@ class LoginUserOperationExecutorTests : FunSpec({ val mockUserBackendService = mockk() val mergeIdentities = mapOf(IdentityConstants.EXTERNAL_ID to "externalId", IdentityConstants.ONESIGNAL_ID to "existing-osid") val plainIdentities = mapOf(IdentityConstants.EXTERNAL_ID to "externalId") - coEvery { mockUserBackendService.createUser(appId, mergeIdentities, any(), any()) } throws BackendException(409, "user-1") + coEvery { mockUserBackendService.createUser(appId, mergeIdentities, any(), any()) } throws + BackendException( + 409, + """{"errors":[{"code":"user-1","meta":{"conflicting_aliases":{"external_id":"externalId","onesignal_id":"existing-osid"}}}]}""", + ) + coEvery { mockUserBackendService.createUser(appId, plainIdentities, any(), any()) } returns + CreateUserResponse(mapOf(IdentityConstants.ONESIGNAL_ID to remoteOneSignalId), PropertiesObject(), listOf()) + + val response = + profileExecutor(mockUserBackendService).execute( + listOf(LoginUserOperation(appId, localOneSignalId, "externalId", "existing-osid", OneSignalUserProfile(tags = mapOf("plan" to "pro")))), + ) + + response.result shouldBe ExecutionResult.SUCCESS + response.idTranslations shouldBe mapOf(localOneSignalId to remoteOneSignalId) + coVerify(exactly = 1) { mockUserBackendService.createUser(appId, mergeIdentities, any(), any()) } + coVerify(exactly = 1) { mockUserBackendService.createUser(appId, plainIdentities, any(), any()) } + } + + test("composite login retries without onesignal_id when the merge attempt is not a conflict") { + val mockUserBackendService = mockk() + val mergeIdentities = mapOf(IdentityConstants.EXTERNAL_ID to "externalId", IdentityConstants.ONESIGNAL_ID to "existing-osid") + val plainIdentities = mapOf(IdentityConstants.EXTERNAL_ID to "externalId") + coEvery { mockUserBackendService.createUser(appId, mergeIdentities, any(), any()) } throws + BackendException(404, """{"errors":[{"code":"user-0","title":"User not found"}]}""") coEvery { mockUserBackendService.createUser(appId, plainIdentities, any(), any()) } returns CreateUserResponse(mapOf(IdentityConstants.ONESIGNAL_ID to remoteOneSignalId), PropertiesObject(), listOf()) @@ -1692,6 +1716,24 @@ class LoginUserOperationExecutorTests : FunSpec({ coVerify(exactly = 1) { mockUserBackendService.createUser(appId, plainIdentities, any(), any()) } } + test("composite login does not retry a merge when the 409 is an alias conflict") { + val mockUserBackendService = mockk() + coEvery { mockUserBackendService.createUser(any(), any(), any(), any()) } throws + BackendException( + 409, + """{"errors":[{"code":"user-1","meta":{"conflicting_aliases":{"facebook":"bob","external_id":"externalId"}}}]}""", + ) + + val response = + profileExecutor(mockUserBackendService).execute( + listOf(LoginUserOperation(appId, localOneSignalId, "externalId", "existing-osid", OneSignalUserProfile(aliases = mapOf("facebook" to "bob")))), + ) + + response.result shouldBe ExecutionResult.FAIL_NORETRY + response.httpStatusCode shouldBe 409 + coVerify(exactly = 1) { mockUserBackendService.createUser(any(), any(), any(), any()) } + } + test("composite login does not merge when the anonymous user is still local, or under IV") { for ((existingId, ivActive) in listOf(IDManager.createLocalId() to false, "existing-osid" to true)) { val mockUserBackendService = mockk() From eacd31948b2e163ede5376fb3c60ba1ee15a43d7 Mon Sep 17 00:00:00 2001 From: AR Abdul Azeez Date: Tue, 27 Oct 2026 12:45:56 -0500 Subject: [PATCH 3/4] fix: [SDK-5615] do not retry a composite login merge that fails for the payload A 400 would fail the same way without the anonymous id. Conflict checks now go through OneSignalError, and only an alias conflict that does not name onesignal_id is final. Co-authored-by: Cursor --- .../executors/LoginUserOperationExecutor.kt | 45 +++++++------- .../LoginUserOperationExecutorTests.kt | 59 +++++++++++++++++++ 2 files changed, 80 insertions(+), 24 deletions(-) diff --git a/OneSignalSDK/onesignal/core/src/main/java/com/onesignal/user/internal/operations/impl/executors/LoginUserOperationExecutor.kt b/OneSignalSDK/onesignal/core/src/main/java/com/onesignal/user/internal/operations/impl/executors/LoginUserOperationExecutor.kt index c8e90a2b8e..b1c631ea91 100644 --- a/OneSignalSDK/onesignal/core/src/main/java/com/onesignal/user/internal/operations/impl/executors/LoginUserOperationExecutor.kt +++ b/OneSignalSDK/onesignal/core/src/main/java/com/onesignal/user/internal/operations/impl/executors/LoginUserOperationExecutor.kt @@ -1,6 +1,7 @@ package com.onesignal.user.internal.operations.impl.executors import android.os.Build +import com.onesignal.OneSignalError import com.onesignal.common.AndroidUtils import com.onesignal.common.DeviceUtils import com.onesignal.common.IDManager @@ -46,8 +47,6 @@ import com.onesignal.user.internal.subscriptions.SubscriptionModel import com.onesignal.user.internal.subscriptions.SubscriptionModelStore import com.onesignal.user.internal.subscriptions.SubscriptionStatus import com.onesignal.user.internal.subscriptions.SubscriptionType -import org.json.JSONException -import org.json.JSONObject @Suppress("TooManyFunctions") internal class LoginUserOperationExecutor( @@ -483,32 +482,29 @@ internal class LoginUserOperationExecutor( return op.existingOnesignalId?.takeUnless { IDManager.isLocalId(it) } } - // Drop the anonymous id and create the identified user. A readable 409 retries only - // when onesignal_id collided, or the code is user-2. An alias conflict is final. + // Drop the anonymous id only when it can be why Create User failed. + // A 400 is the payload, so a second request would fail the same way. private fun shouldAbandonMerge(response: ExecutionResponse): Boolean { if (response.result != ExecutionResult.FAIL_NORETRY) return false - if (response.httpStatusCode != HTTP_CONFLICT) return true - return onesignalIdConflict(response.httpResponse) != false + val status = response.httpStatusCode?.let { NetworkUtils.getResponseStatusType(it) } + return status == NetworkUtils.ResponseStatusType.MISSING || + (status == NetworkUtils.ResponseStatusType.CONFLICT && onesignalIdConflict(response.httpResponse) != false) } - /** False when the body is a conflict that does not name onesignal_id. Null when it cannot be read. */ - private fun onesignalIdConflict(body: String?): Boolean? { - if (body.isNullOrBlank()) return null - return try { - val errors = JSONObject(body).optJSONArray("errors") ?: return null - var sawConflict = false - for (index in 0 until errors.length()) { - val error = errors.optJSONObject(index) ?: continue - sawConflict = true - if (error.optString("code") == ALIAS_CLAIMED_BY_ANOTHER_USER) return true - val aliases = error.optJSONObject("meta")?.optJSONObject("conflicting_aliases") - if (aliases?.has(IdentityConstants.ONESIGNAL_ID) == true) return true - } - if (sawConflict) false else null - } catch (_: JSONException) { - null - } - } + /** False when a parsed error does not name onesignal_id. Null when the body has none. */ + private fun onesignalIdConflict(body: String?): Boolean? = + OneSignalError.fromBackendResponse(HTTP_CONFLICT, body) + .details + .filter { it.backendCode != null || conflictingAliases(it).isNotEmpty() } + .takeIf { it.isNotEmpty() } + ?.any { namesMergedUser(it) } + + private fun namesMergedUser(detail: OneSignalError.Detail): Boolean = + detail.backendCode == ALIAS_CLAIMED_BY_ANOTHER_USER || + conflictingAliases(detail).containsKey(IdentityConstants.ONESIGNAL_ID) + + private fun conflictingAliases(detail: OneSignalError.Detail): Map<*, *> = + detail.meta?.get(CONFLICTING_ALIASES) as? Map<*, *> ?: emptyMap() private fun backendExecutionResponse( result: ExecutionResult, @@ -524,6 +520,7 @@ internal class LoginUserOperationExecutor( const val LOGIN_USER = "login-user" private const val HTTP_CONFLICT = 409 private const val ALIAS_CLAIMED_BY_ANOTHER_USER = "user-2" + private const val CONFLICTING_ALIASES = "conflicting_aliases" } } diff --git a/OneSignalSDK/onesignal/core/src/test/java/com/onesignal/user/internal/operations/LoginUserOperationExecutorTests.kt b/OneSignalSDK/onesignal/core/src/test/java/com/onesignal/user/internal/operations/LoginUserOperationExecutorTests.kt index 3bc086f83e..6f2275b540 100644 --- a/OneSignalSDK/onesignal/core/src/test/java/com/onesignal/user/internal/operations/LoginUserOperationExecutorTests.kt +++ b/OneSignalSDK/onesignal/core/src/test/java/com/onesignal/user/internal/operations/LoginUserOperationExecutorTests.kt @@ -1734,6 +1734,65 @@ class LoginUserOperationExecutorTests : FunSpec({ coVerify(exactly = 1) { mockUserBackendService.createUser(any(), any(), any(), any()) } } + test("composite login does not retry a merge when the payload is invalid") { + val mockUserBackendService = mockk() + coEvery { mockUserBackendService.createUser(any(), any(), any(), any()) } throws BackendException(400, "INVALID EMAIL") + + val response = + profileExecutor(mockUserBackendService).execute( + listOf( + LoginUserOperation( + appId, + localOneSignalId, + "externalId", + "existing-osid", + OneSignalUserProfile(email = "not-an-email"), + ), + ), + ) + + response.result shouldBe ExecutionResult.FAIL_NORETRY + response.httpStatusCode shouldBe 400 + coVerify(exactly = 1) { mockUserBackendService.createUser(any(), any(), any(), any()) } + } + + test("composite login retries without onesignal_id when the merge 409 is user-2") { + val mockUserBackendService = mockk() + val mergeIdentities = mapOf(IdentityConstants.EXTERNAL_ID to "externalId", IdentityConstants.ONESIGNAL_ID to "existing-osid") + val plainIdentities = mapOf(IdentityConstants.EXTERNAL_ID to "externalId") + coEvery { mockUserBackendService.createUser(appId, mergeIdentities, any(), any()) } throws + BackendException(409, """{"errors":[{"code":"user-2","title":"One or more Aliases claimed by another User"}]}""") + coEvery { mockUserBackendService.createUser(appId, plainIdentities, any(), any()) } returns + CreateUserResponse(mapOf(IdentityConstants.ONESIGNAL_ID to remoteOneSignalId), PropertiesObject(), listOf()) + + val response = + profileExecutor(mockUserBackendService).execute( + listOf(LoginUserOperation(appId, localOneSignalId, "externalId", "existing-osid", OneSignalUserProfile(tags = mapOf("plan" to "pro")))), + ) + + response.result shouldBe ExecutionResult.SUCCESS + coVerify(exactly = 1) { mockUserBackendService.createUser(appId, mergeIdentities, any(), any()) } + coVerify(exactly = 1) { mockUserBackendService.createUser(appId, plainIdentities, any(), any()) } + } + + test("composite login retries without onesignal_id when the 409 body cannot be read") { + val mockUserBackendService = mockk() + val mergeIdentities = mapOf(IdentityConstants.EXTERNAL_ID to "externalId", IdentityConstants.ONESIGNAL_ID to "existing-osid") + val plainIdentities = mapOf(IdentityConstants.EXTERNAL_ID to "externalId") + coEvery { mockUserBackendService.createUser(appId, mergeIdentities, any(), any()) } throws BackendException(409, "CONFLICT") + coEvery { mockUserBackendService.createUser(appId, plainIdentities, any(), any()) } returns + CreateUserResponse(mapOf(IdentityConstants.ONESIGNAL_ID to remoteOneSignalId), PropertiesObject(), listOf()) + + val response = + profileExecutor(mockUserBackendService).execute( + listOf(LoginUserOperation(appId, localOneSignalId, "externalId", "existing-osid", OneSignalUserProfile(tags = mapOf("plan" to "pro")))), + ) + + response.result shouldBe ExecutionResult.SUCCESS + coVerify(exactly = 1) { mockUserBackendService.createUser(appId, mergeIdentities, any(), any()) } + coVerify(exactly = 1) { mockUserBackendService.createUser(appId, plainIdentities, any(), any()) } + } + test("composite login does not merge when the anonymous user is still local, or under IV") { for ((existingId, ivActive) in listOf(IDManager.createLocalId() to false, "existing-osid" to true)) { val mockUserBackendService = mockk() From fc520cd1d4017095fa8c743d38cb9ccd569dc9bc Mon Sep 17 00:00:00 2001 From: AR Abdul Azeez Date: Tue, 27 Oct 2026 15:56:22 -0500 Subject: [PATCH 4/4] fix: [SDK-5615] log a handled merge conflict and ignore user-2 Create User never returns user-2, and a handled 409 should not read as a failure. Co-authored-by: Cursor --- .../impl/executors/LoginUserOperationExecutor.kt | 11 ++++++++--- .../operations/LoginUserOperationExecutorTests.kt | 14 +++++--------- 2 files changed, 13 insertions(+), 12 deletions(-) diff --git a/OneSignalSDK/onesignal/core/src/main/java/com/onesignal/user/internal/operations/impl/executors/LoginUserOperationExecutor.kt b/OneSignalSDK/onesignal/core/src/main/java/com/onesignal/user/internal/operations/impl/executors/LoginUserOperationExecutor.kt index b1c631ea91..9a39143f76 100644 --- a/OneSignalSDK/onesignal/core/src/main/java/com/onesignal/user/internal/operations/impl/executors/LoginUserOperationExecutor.kt +++ b/OneSignalSDK/onesignal/core/src/main/java/com/onesignal/user/internal/operations/impl/executors/LoginUserOperationExecutor.kt @@ -327,6 +327,12 @@ internal class LoginUserOperationExecutor( // The caller retries an abandoned merge, so this failure is not the outcome. if (mergeIntoOnesignalId != null && shouldAbandonMerge(response)) { Logging.debug("LoginUserOperationExecutor merge attempt failed: HTTP ${ex.statusCode}") + if (responseType == NetworkUtils.ResponseStatusType.CONFLICT) { + // Hardcode user-1. The 409 line above reads like a failure to the app. + Logging.debug( + "LoginUserOperationExecutor now handling 409 response with \"code\": \"user-1\" by switching to user with \"external_id\": \"${createUserOperation.externalId}\"", + ) + } } else { Logging.error("LoginUserOperationExecutor.createUser failed: HTTP ${ex.statusCode}") } @@ -499,9 +505,9 @@ internal class LoginUserOperationExecutor( .takeIf { it.isNotEmpty() } ?.any { namesMergedUser(it) } + // user-1 is any alias clash. Retry only when conflicting_aliases names onesignal_id. private fun namesMergedUser(detail: OneSignalError.Detail): Boolean = - detail.backendCode == ALIAS_CLAIMED_BY_ANOTHER_USER || - conflictingAliases(detail).containsKey(IdentityConstants.ONESIGNAL_ID) + conflictingAliases(detail).containsKey(IdentityConstants.ONESIGNAL_ID) private fun conflictingAliases(detail: OneSignalError.Detail): Map<*, *> = detail.meta?.get(CONFLICTING_ALIASES) as? Map<*, *> ?: emptyMap() @@ -519,7 +525,6 @@ internal class LoginUserOperationExecutor( companion object { const val LOGIN_USER = "login-user" private const val HTTP_CONFLICT = 409 - private const val ALIAS_CLAIMED_BY_ANOTHER_USER = "user-2" private const val CONFLICTING_ALIASES = "conflicting_aliases" } } diff --git a/OneSignalSDK/onesignal/core/src/test/java/com/onesignal/user/internal/operations/LoginUserOperationExecutorTests.kt b/OneSignalSDK/onesignal/core/src/test/java/com/onesignal/user/internal/operations/LoginUserOperationExecutorTests.kt index 6f2275b540..3805b5e8fd 100644 --- a/OneSignalSDK/onesignal/core/src/test/java/com/onesignal/user/internal/operations/LoginUserOperationExecutorTests.kt +++ b/OneSignalSDK/onesignal/core/src/test/java/com/onesignal/user/internal/operations/LoginUserOperationExecutorTests.kt @@ -1756,23 +1756,19 @@ class LoginUserOperationExecutorTests : FunSpec({ coVerify(exactly = 1) { mockUserBackendService.createUser(any(), any(), any(), any()) } } - test("composite login retries without onesignal_id when the merge 409 is user-2") { + test("composite login does not retry a merge when the 409 is user-2") { val mockUserBackendService = mockk() - val mergeIdentities = mapOf(IdentityConstants.EXTERNAL_ID to "externalId", IdentityConstants.ONESIGNAL_ID to "existing-osid") - val plainIdentities = mapOf(IdentityConstants.EXTERNAL_ID to "externalId") - coEvery { mockUserBackendService.createUser(appId, mergeIdentities, any(), any()) } throws + coEvery { mockUserBackendService.createUser(any(), any(), any(), any()) } throws BackendException(409, """{"errors":[{"code":"user-2","title":"One or more Aliases claimed by another User"}]}""") - coEvery { mockUserBackendService.createUser(appId, plainIdentities, any(), any()) } returns - CreateUserResponse(mapOf(IdentityConstants.ONESIGNAL_ID to remoteOneSignalId), PropertiesObject(), listOf()) val response = profileExecutor(mockUserBackendService).execute( listOf(LoginUserOperation(appId, localOneSignalId, "externalId", "existing-osid", OneSignalUserProfile(tags = mapOf("plan" to "pro")))), ) - response.result shouldBe ExecutionResult.SUCCESS - coVerify(exactly = 1) { mockUserBackendService.createUser(appId, mergeIdentities, any(), any()) } - coVerify(exactly = 1) { mockUserBackendService.createUser(appId, plainIdentities, any(), any()) } + response.result shouldBe ExecutionResult.FAIL_NORETRY + response.httpStatusCode shouldBe 409 + coVerify(exactly = 1) { mockUserBackendService.createUser(any(), any(), any(), any()) } } test("composite login retries without onesignal_id when the 409 body cannot be read") {