Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
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
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
# Changelog

## Unreleased

### Features

- Add pending task queue during SDK initialization on a background queue (#7377)

## 9.4.0

### Breaking Changes
Expand Down
32 changes: 25 additions & 7 deletions Sources/Sentry/SentrySDKInternal.m
Original file line number Diff line number Diff line change
Expand Up @@ -231,6 +231,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

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 @@ -451,14 +457,23 @@ + (void)configureScope:(void (^)(SentryScope *scope))callback

+ (void)setUser:(SentryUser *_Nullable)user
{
SentryPendingTaskQueue *pendingTaskQueue
= SentryDependencyContainer.sharedInstance.pendingTaskQueue;

// Clear any older pending setUser tasks so only the latest value is kept.
// This also handles the race condition window between setCurrentHub and
// executePendingTasks: if setUser is called directly while an older setUser
// task is still queued, the stale task is removed before it can overwrite.
// See https://github.com/getsentry/sentry-cocoa/issues/6872
[pendingTaskQueue removeAllWithType:SentryPendingTaskTypeSetUser];

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. Enqueue the task to be executed
// once the SDK is fully initialized.
[pendingTaskQueue
enqueue:^{ [SentrySDKInternal.currentHub setUser:user]; }
type:SentryPendingTaskTypeSetUser];
return;
}

[SentrySDKInternal.currentHub setUser:user];
Expand Down Expand Up @@ -538,6 +553,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
92 changes: 92 additions & 0 deletions Sources/Swift/Core/Helper/SentryPendingTaskQueue.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
@_implementationOnly import _SentryPrivate
import Foundation

@objc @_spi(Private)
// swiftlint:disable:next missing_docs
public enum SentryPendingTaskType: Int {
// swiftlint:disable:next missing_docs
case setUser
}

/// 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.
///
/// Tasks have a type that callers can use for deduplication via ``removeAll(type:)`` before
/// enqueueing, ensuring only the most recent value for a given type is applied during execution.
///
/// See https://github.com/getsentry/sentry-cocoa/issues/6872
@objc
@_spi(Private)
public final class SentryPendingTaskQueue: NSObject {

private struct PendingTask {
let type: SentryPendingTaskType
let task: () -> Void
}

private let lock = NSRecursiveLock()
private var pendingTasks: [PendingTask] = []

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

/// Adds a typed task to the pending queue.
/// - Parameters:
/// - task: A closure containing the operation to be executed.
/// - type: An enum identifying the task type.
@objc public func enqueue(_ task: @escaping () -> Void, type: SentryPendingTaskType) {
lock.synchronized {
pendingTasks.append(PendingTask(type: type, task: task))
}
SentrySDKLog.debug("Typed task '\(type)' enqueued. SDK is not fully initialized yet.")
}

/// Removes all pending tasks of the given type without executing them.
@objc public func removeAll(type: SentryPendingTaskType) {
lock.synchronized {
pendingTasks.removeAll { $0.type == type }
}
}

/// 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.synchronized {
let tasks = pendingTasks
pendingTasks = []
return tasks
}

guard !tasks.isEmpty else {
return
}

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

for entry in tasks {
entry.task()
}
}

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

#if SENTRY_TEST || SENTRY_TEST_CI
/// Returns the number of pending tasks.
/// Used for testing.
@objc public var pendingTaskCount: Int {
lock.synchronized {
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
185 changes: 185 additions & 0 deletions Tests/SentryTests/Helper/SentryPendingTaskQueueTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,185 @@
@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({ }, type: .setUser)

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

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

// -- Act --
sut.enqueue({ }, type: .setUser)
sut.enqueue({ }, type: .setUser)
sut.enqueue({ }, type: .setUser)

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

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

sut.enqueue({ executionOrder.append(1) }, type: .setUser)
sut.enqueue({ executionOrder.append(2) }, type: .setUser)
sut.enqueue({ executionOrder.append(3) }, type: .setUser)

// -- 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 }, type: .setUser)
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 }, type: .setUser)

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

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

// MARK: - removeAll(type:)

func testRemoveAllWithType_shouldRemoveMatchingTasks() {
// -- Arrange --
var executedValue = ""
sut.enqueue({ executedValue = "old" }, type: .setUser)
XCTAssertEqual(1, sut.pendingTaskCount)

// -- Act --
sut.removeAll(type: .setUser)

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

func testRemoveAllWithType_shouldRemoveAllMatchingTasks() {
// -- Arrange --
sut.enqueue({ }, type: .setUser)
sut.enqueue({ }, type: .setUser)
sut.enqueue({ }, type: .setUser)
XCTAssertEqual(3, sut.pendingTaskCount)

// -- Act --
sut.removeAll(type: .setUser)

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

func testRemoveAllThenEnqueue_shouldKeepOnlyLatestTask() {
// -- Arrange --
var executedValues: [String] = []

sut.enqueue({ executedValues.append("old-user") }, type: .setUser)

// -- Act --
// Simulates what setUser does: clear old, enqueue new
sut.removeAll(type: .setUser)
sut.enqueue({ executedValues.append("new-user") }, type: .setUser)

// -- Assert --
XCTAssertEqual(1, sut.pendingTaskCount)
sut.executePendingTasks()
XCTAssertEqual(["new-user"], executedValues)
}

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.synchronized {
executionCount += 1
}
}, type: .setUser)
expectation.fulfill()
}

queue2.async {
self.sut.enqueue({
lock.synchronized {
executionCount += 1
}
}, type: .setUser)
expectation.fulfill()
}
}

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

// Execute all pending tasks
sut.executePendingTasks()

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