Skip to content
Draft
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 17 additions & 7 deletions Sources/Sentry/SentrySDKInternal.m
Original file line number Diff line number Diff line change
Expand Up @@ -229,6 +229,12 @@ + (void)startWithOptions:(SentryOptions *)options
andScope:scope];
[SentrySDKInternal setCurrentHub:hub];

// Execute any pending tasks that were queued before the SDK was fully initialized.
// This handles the race condition when SDK is started on a background thread
// and methods like setUser are called before main thread initialization finishes.
// See https://github.com/getsentry/sentry-cocoa/issues/6872
[SentryDependencyContainer.sharedInstance.pendingTaskQueue executePendingTasks];
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Race condition causes incorrect ordering of setUser operations

Medium Severity

There's a race condition window between setCurrentHub (line 230) and executePendingTasks (line 236) where isEnabled returns true but pending tasks haven't executed yet. If setUser is called from another thread during this window, it calls the hub directly while older queued tasks are still pending. When executePendingTasks subsequently runs, it executes the older tasks, potentially overwriting the newer value with stale data. This can cause the wrong user to be set when multiple setUser calls happen around SDK initialization time.

Additional Locations (1)

Fix in Cursor Fix in Web


[SentryDependencyContainer.sharedInstance.crashWrapper startBinaryImageCache];
[SentryDependencyContainer.sharedInstance.binaryImageCache start:options.debug];

Expand Down Expand Up @@ -450,13 +456,14 @@ + (void)configureScope:(void (^)(SentryScope *scope))callback
+ (void)setUser:(SentryUser *_Nullable)user
{
if (![SentrySDKInternal isEnabled]) {
// We must log with level fatal because only fatal messages get logged even when the SDK
// isn't started. We've seen multiple times that users try to set the user before starting
// the SDK, and it confuses them. Ideally, we would do something to store the user and set
// it once we start the SDK, but this is a breaking change, so we live with the workaround
// for now.
SENTRY_LOG_FATAL(@"The SDK is disabled, so setUser doesn't work. Please ensure to start "
@"the SDK before setting the user.");
// The SDK isn't fully initialized yet. This can happen when:
// 1. The user calls setUser before starting the SDK
// 2. The SDK was started on a background thread and main thread initialization
// hasn't completed yet (see https://github.com/getsentry/sentry-cocoa/issues/6872)
// Enqueue the task to be executed once the SDK is fully initialized.
[SentryDependencyContainer.sharedInstance.pendingTaskQueue
enqueue:^{ [SentrySDKInternal.currentHub setUser:user]; }];
return;
}

[SentrySDKInternal.currentHub setUser:user];
Expand Down Expand Up @@ -536,6 +543,9 @@ + (void)close
{
SENTRY_LOG_DEBUG(@"Starting to close SDK.");

// Clear any pending tasks that were queued before the SDK was fully initialized.
[SentryDependencyContainer.sharedInstance.pendingTaskQueue clearPendingTasks];

[SentryDependencyContainer.sharedInstance.dispatchQueueWrapper dispatchSyncOnMainQueue:^{

#if SENTRY_TARGET_PROFILING_SUPPORTED
Expand Down
70 changes: 70 additions & 0 deletions Sources/Swift/Core/Helper/SentryPendingTaskQueue.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
@_implementationOnly import _SentryPrivate
import Foundation

/// A thread-safe queue for pending SDK operations that are called before the SDK is fully initialized.
///
/// When the SDK is started on a background thread, there's a window where the SDK is not fully
/// initialized but user code may call methods like `setUser`, `configureScope`, or `addBreadcrumb`.
/// This queue stores those operations and executes them once the SDK is ready.
///
/// See https://github.com/getsentry/sentry-cocoa/issues/6872
@objc(SentryPendingTaskQueue)
@objcMembers
@_spi(Private)
public final class SentryPendingTaskQueue: NSObject {

private let lock = NSLock()
private var pendingTasks: [() -> Void] = []

override public init() {
super.init()
}

/// Adds a task to the pending queue.
/// The task will be executed when `executePendingTasks` is called.
/// - Parameter task: A closure containing the operation to be executed.
@objc public func enqueue(_ task: @escaping () -> Void) {
lock.withLock {
pendingTasks.append(task)
}
SentrySDKLog.debug("Task enqueued. SDK is not fully initialized yet.")
}

/// Executes all pending tasks and clears the queue.
/// This should be called from the SDK initialization code after the hub is fully set up.
@objc public func executePendingTasks() {
let tasks = lock.withLock {
let tasks = pendingTasks
pendingTasks = []
return tasks
}

guard !tasks.isEmpty else {
return
}

SentrySDKLog.debug("Executing \(tasks.count) pending task(s) after SDK initialization.")

for task in tasks {
task()
}
}

/// Clears all pending tasks without executing them.
/// This is useful when the SDK is closed.
@objc public func clearPendingTasks() {
lock.withLock {
pendingTasks.removeAll()
}
}

#if SENTRY_TEST || SENTRY_TEST_CI
/// Returns the number of pending tasks.
/// Used for testing.
@objc public var pendingTaskCount: Int {
lock.withLock {
return pendingTasks.count
}
}
#endif
}
1 change: 1 addition & 0 deletions Sources/Swift/SentryDependencyContainer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,7 @@ extension SentryFileManager: SentryFileManagerProtocol { }

@objc public var dispatchQueueWrapper = Dependencies.dispatchQueueWrapper
@objc public var random = Dependencies.random
@objc public var pendingTaskQueue = SentryPendingTaskQueue()
@objc public var threadWrapper = Dependencies.threadWrapper
@objc public var binaryImageCache = Dependencies.binaryImageCache
@objc public var dateProvider: SentryCurrentDateProvider = Dependencies.dateProvider
Expand Down
137 changes: 137 additions & 0 deletions Tests/SentryTests/Helper/SentryPendingTaskQueueTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
@testable import Sentry
import XCTest

class SentryPendingTaskQueueTests: XCTestCase {

private var sut: SentryPendingTaskQueue!

override func setUp() {
super.setUp()
sut = SentryDependencyContainer.sharedInstance().pendingTaskQueue
sut.clearPendingTasks()
}

override func tearDown() {
sut.clearPendingTasks()
super.tearDown()
}

func testEnqueue_whenCalled_shouldIncreasePendingTaskCount() {
// -- Arrange --
XCTAssertEqual(0, sut.pendingTaskCount)

// -- Act --
sut.enqueue { }

// -- Assert --
XCTAssertEqual(1, sut.pendingTaskCount)
}

func testEnqueue_whenCalledMultipleTimes_shouldAccumulateTasks() {
// -- Arrange --
XCTAssertEqual(0, sut.pendingTaskCount)

// -- Act --
sut.enqueue { }
sut.enqueue { }
sut.enqueue { }

// -- Assert --
XCTAssertEqual(3, sut.pendingTaskCount)
}

func testExecutePendingTasks_whenTasksExist_shouldExecuteAllTasksInOrder() {
// -- Arrange --
var executionOrder: [Int] = []

sut.enqueue { executionOrder.append(1) }
sut.enqueue { executionOrder.append(2) }
sut.enqueue { executionOrder.append(3) }

// -- Act --
sut.executePendingTasks()

// -- Assert --
XCTAssertEqual([1, 2, 3], executionOrder)
XCTAssertEqual(0, sut.pendingTaskCount)
}

func testExecutePendingTasks_whenNoTasks_shouldDoNothing() {
// -- Arrange --
XCTAssertEqual(0, sut.pendingTaskCount)

// -- Act --
sut.executePendingTasks()

// -- Assert --
XCTAssertEqual(0, sut.pendingTaskCount)
}

func testClearPendingTasks_whenTasksExist_shouldRemoveAllWithoutExecuting() {
// -- Arrange --
var wasExecuted = false
sut.enqueue { wasExecuted = true }
XCTAssertEqual(1, sut.pendingTaskCount)

// -- Act --
sut.clearPendingTasks()

// -- Assert --
XCTAssertEqual(0, sut.pendingTaskCount)
XCTAssertFalse(wasExecuted)
}

func testExecutePendingTasks_whenCalledTwice_shouldOnlyExecuteOnce() {
// -- Arrange --
var executionCount = 0
sut.enqueue { executionCount += 1 }

// -- Act --
sut.executePendingTasks()
sut.executePendingTasks()

// -- Assert --
XCTAssertEqual(1, executionCount)
}

func testEnqueueAndExecute_whenConcurrent_shouldBeThreadSafe() {
// -- Arrange --
let queue1 = DispatchQueue(label: "test.queue1", attributes: .concurrent)
let queue2 = DispatchQueue(label: "test.queue2", attributes: .concurrent)
let expectation = XCTestExpectation(description: "All tasks completed")
expectation.expectedFulfillmentCount = 100

var executionCount = 0
let lock = NSLock()

// -- Act --
for _ in 0..<50 {
queue1.async {
self.sut.enqueue {
lock.withLock {
executionCount += 1
}
}
expectation.fulfill()
}

queue2.async {
self.sut.enqueue {
lock.withLock {
executionCount += 1
}
}
expectation.fulfill()
}
}

wait(for: [expectation], timeout: 5.0)

// Execute all pending tasks
sut.executePendingTasks()

// -- Assert --
XCTAssertEqual(100, executionCount)
XCTAssertEqual(0, sut.pendingTaskCount)
}
}
87 changes: 72 additions & 15 deletions Tests/SentryTests/SentrySDKInternalTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -229,25 +229,26 @@ class SentrySDKInternalTests: XCTestCase {
XCTAssertEqual(event?.user, user)
}

func testSetUserBeforeStartingSDK_LogsFatalMessage() throws {
// Arrange
let oldOutput = SentrySDKLog.getLogOutput()

defer {
SentrySDKLog.setOutput(oldOutput)
}
func testSetUserBeforeStartingSDK_EnqueuesTaskForLaterExecution() throws {
// -- Arrange --
let pendingTaskQueue = SentryDependencyContainer.sharedInstance().pendingTaskQueue
pendingTaskQueue.clearPendingTasks()

let logOutput = TestLogOutput()
SentrySDKLog.setLogOutput(logOutput)
// -- Act --
let user = TestData.user
SentrySDK.setUser(user)

// Act
SentrySDK.setUser(nil)
// -- Assert --
// Task should be enqueued
XCTAssertEqual(1, pendingTaskQueue.pendingTaskCount)

// Assert
let actualLogMessage = try XCTUnwrap(logOutput.loggedMessages.first)
let expectedLogMessage = "The SDK is disabled, so setUser doesn't work. Please ensure to start the SDK before setting the user."
// Start SDK and verify user is applied
givenSdkWithHub()
pendingTaskQueue.executePendingTasks()

XCTAssertTrue(actualLogMessage.contains(expectedLogMessage), "Expected log message to contain '\(expectedLogMessage)', but got '\(actualLogMessage)'")
let actualScope = SentrySDKInternal.currentHub().scope
let event = actualScope.applyTo(event: fixture.event, maxBreadcrumbs: 10)
XCTAssertEqual(event?.user, user)
}

func testSetUserAFterStartingSDK_DoesNotLogFatalMessage() {
Expand Down Expand Up @@ -314,6 +315,62 @@ class SentrySDKInternalTests: XCTestCase {
XCTAssertEqual(0, logOutput.loggedMessages.count, "Expected no log messages, but got \(logOutput.loggedMessages.count)")
}

/// Tests the race condition fix for https://github.com/getsentry/sentry-cocoa/issues/6872
/// When SDK is started on a background thread and setUser is called before main thread
/// initialization completes, the user should still be set correctly.
func testSetUser_whenSDKStartedOnBackgroundThread_shouldApplyUserAfterInit() throws {
// -- Arrange --
SentryDependencyContainer.sharedInstance().pendingTaskQueue.clearPendingTasks()
clearTestState()

let expectation = XCTestExpectation(description: "SDK started on background thread")

// -- Act --
// Start SDK on background thread
DispatchQueue.global(qos: .utility).async {
SentrySDK.start { options in
options.dsn = SentrySDKInternalTests.dsnAsString
options.removeAllIntegrations()
}

// SDK is started but main thread init may not be complete yet
// Set user immediately (simulating the race condition)
let user = User(userId: "test-user-123")
user.email = "test@example.com"
SentrySDK.setUser(user)

// Wait for main thread dispatch to complete
SentryDependencyContainer.sharedInstance().dispatchQueueWrapper.dispatchAsyncOnMainQueueIfNotMainThread {
expectation.fulfill()
}
}

wait(for: [expectation], timeout: 5.0)

// -- Assert --
let actualScope = SentrySDKInternal.currentHub().scope
let event = actualScope.applyTo(event: Event(), maxBreadcrumbs: 10)
XCTAssertEqual("test-user-123", event?.user?.userId)
XCTAssertEqual("test@example.com", event?.user?.email)
}

func testClose_whenPendingTasksExist_shouldClearThem() {
// -- Arrange --
let pendingTaskQueue = SentryDependencyContainer.sharedInstance().pendingTaskQueue
pendingTaskQueue.clearPendingTasks()

// Enqueue some tasks before SDK is started
SentrySDK.setUser(User(userId: "should-be-cleared"))
XCTAssertEqual(1, pendingTaskQueue.pendingTaskCount)

// -- Act --
SentrySDK.close()

// -- Assert --
// After close, the dependency container is reset, so we need to get the new instance
XCTAssertEqual(0, SentryDependencyContainer.sharedInstance().pendingTaskQueue.pendingTaskCount)
}

func testStartTransaction() throws {
givenSdkWithHub()

Expand Down
Loading