Swift Concurrency15 min read

The assumeIsolated crash in a BGTask expirationHandler, and why Swift 6 didn't warn

iOS calls a background task's expiration handler on a queue of its own, not the one you registered. One MainActor.assumeIsolated in that closure took down a TestFlight build, and the compiler had nothing to say about it.

Two crash reports came back from TestFlight build 0.7 (10) of ClamNotes ten minutes apart, from an iPhone 15 Pro Max and an iPad Pro. Same exception on both: EXC_BREAKPOINT (SIGTRAP), crashed thread at _dispatch_assert_queue_fail, one frame above it MainActor.assumeIsolated, and above that a closure I had written as the expiration handler of a background task. If you got here by searching for Incorrect actor executor assumption, it's the same bug under a different signature; I'll show where each one comes from.

This post is the whole story: what the crash report says, why assumeIsolated traps instead of quietly doing the right thing, why neither the Swift 5 nor the Swift 6 language mode warned me, the fix that shipped in 0.7 (11) the same night, and how I reproduced it in the Simulator, where background tasks don't exist.

What changed in build 10

ClamNotes transcribes lectures on the device. The first time a speech model loads, Core ML optimizes it for that device, which takes minutes. Build 10 started doing that right after launch, under an iOS 26 BGContinuedProcessingTask: the task type that starts in the foreground, shows its progress in a system Live Activity, and keeps running if the person leaves the app.

A continued processing task can end before its work is done. The person can tap Stop in the system UI. The system can end it under resource pressure. And, per Apple's documentation, the system prioritizes the termination of tasks that reflect minimal or no progress. Apple doesn't document the threshold; developer forum reports and my own logs point to roughly 30 seconds of a progress value that doesn't move. Core ML reports nothing while it optimizes, so my progress sat still for long stretches. Build 10 was the first build where the expiration handler actually ran on people's devices, and the iPhone crashed four minutes and forty seconds after launch.

Here is the code that shipped, trimmed:

SpeechSetup.swift, build 0.7 (10)
// simplified
@MainActor
final class SpeechSetup: NSObject {
    private var continued: BGContinuedProcessingTask?

    private func beginContinued() {
        let registered = BGTaskScheduler.shared.register(
            forTaskWithIdentifier: identifier, using: .main
        ) { [weak self] task in
            MainActor.assumeIsolated { self?.started(task) }   // fine: runs on .main
        }
        // ... build a BGContinuedProcessingTaskRequest and submit it
    }

    private func started(_ task: BGTask) {
        guard let task = task as? BGContinuedProcessingTask else { return }
        continued = task
        task.expirationHandler = { [weak self] in
            MainActor.assumeIsolated {                          // line 282: the crash
                self?.continued = nil
                task.setTaskCompleted(success: false)
            }
        }
    }
}

The launch handler pattern is correct. I registered with using: .main, the launch handler runs on the main queue, and assumeIsolated there is an honest statement. Then I copied the same pattern one level down, into a closure that the queue parameter never covered.

Reading the crash report

The crashed thread, trimmed to the frames that matter:

ClamNotes 0.7 (10), iPhone16,2, iOS 27.0.1
Exception Type:  EXC_BREAKPOINT (SIGTRAP)
Termination Reason: SIGNAL 5 Trace/BPT trap: 5

Thread 3 Crashed:
0   libdispatch.dylib          _dispatch_assert_queue_fail + 120
1   libdispatch.dylib          dispatch_assert_queue + 196
2   libswift_Concurrency.dylib _swift_task_checkIsolatedSwift + 48
3   libswift_Concurrency.dylib swift_task_isCurrentExecutorWithFlagsImpl(...) + 356
4   ClamNotes                  specialized static MainActor.assumeIsolated<A>(_:file:line:) + 84
5   ClamNotes                  closure #1 in SpeechSetup.started(_:) + 88 (SpeechSetup.swift:282)
6   ClamNotes                  <deduplicated_symbol> + 36
7   BackgroundTasks            -[BGTask _callExpirationHandlerWithReason:] + 92
8   BackgroundTasks            -[BGContinuedProcessingTask _callExpirationHandlerWithReason:] + 116
9   BackgroundTasks            __66-[BGTaskScheduler _invokeExpirationHandlersForExpirationRequests:]_block_invoke + 172
10  libdispatch.dylib          _dispatch_call_block_and_release + 32
...
14  libdispatch.dylib          _dispatch_root_queue_drain + 488
15  libdispatch.dylib          _dispatch_worker_thread2 + 196
16  libsystem_pthread.dylib    _pthread_wqthread + 232

Read it from the bottom. Frames 14 to 16 are a worker thread draining a root (global) dispatch queue, not the main thread. Frame 9 is BackgroundTasks delivering expirations from a block it dispatched itself. Frames 7 and 8 call my handler. Frame 4 is assumeIsolated asking the runtime whether it is on the main actor, and frames 0 to 3 are the answer: the runtime asks the main executor to check, the main executor asks libdispatch to assert it's on the main queue, and libdispatch stops the process.

The iPad report has the same stack on a different thread number. Thread numbers in these reports are not meaningful; the bottom frames are.

MAIN QUEUE GLOBAL QUEUE (IOS PICKS) register + submit using: .main launch handler on main, as promised sets expirationHandler closure inherits @MainActor work + progress minutes of Core ML iOS ends the task Stop, stall or pressure expirationHandler same closure, other thread assumeIsolated traps in libdispatch
Figure 1. The queue you pass to register governs the launch handler only. The closure stored in expirationHandler is created on main but called by BackgroundTasks from a global queue worker thread.

The queue you register with is for the launch handler only

Apple's documentation for register(forTaskWithIdentifier:using:launchHandler:) describes the queue parameter as A queue for executing the task, and the summary says the launch handler is executed on the specified queue. The page for BGTask.expirationHandler says nothing about threads at all. I read "a queue for executing the task" as "a queue for everything this task calls back". The crash report says otherwise, and so does the Simulator reproduction later in this post.

There's a hint in Apple's own sample for continued processing tasks. Its export function sets task.expirationHandler = { wasExpired = true } and then loops, calling sleep(1), until the work finishes or wasExpired turns true. The thread running that loop is blocked in sleep, so the flag can only ever flip if the handler runs on some other thread. The sample quietly depends on the behavior the reference documentation leaves out.

assumeIsolated checks, it does not hop

assumeIsolated arrived with SE-0392 (custom actor executors), next to preconditionIsolated and assertIsolated. It exists for one situation: synchronous code that you know runs on the main actor's executor, but that the type system can't prove, typically a callback from an older API. It is marked unavailable from async contexts, it never suspends, and it never moves your code anywhere. The proposal is direct about the failure case: If the current executor is not the MainActor's serial executor, this function will crash.

So it's an assertion that also grants isolation, not a scheduling tool. That is the right design: if it hopped, it would have to be async, and if it ran the closure anyway, every main-actor-only line inside would be a data race. Trapping turns a race into a crash with a stack trace pointing at the wrong assumption. In my case it pointed at line 282.

Two crash signatures for one bug

The Swift standard library's implementation calls fatalError("Incorrect actor executor assumption; Expected same executor as \(self).") when the check fails. My crash reports never printed that. Since Swift 6.0, the runtime's "is this the current executor?" check can call the executor's own checkIsolated (SE-0424), and for the main actor that ends in dispatch_assert_queue on the main queue, which traps inside libdispatch before Swift's message is reached. That's frames 0 to 3 above.

The runtime has an environment variable, SWIFT_IS_CURRENT_EXECUTOR_LEGACY_MODE_OVERRIDE, that restores the older non-crashing check. With it set to legacy, my local reproduction (below) printed the familiar line instead:

Terminal
$ ./repro assume
# EXC_BREAKPOINT in _dispatch_assert_queue_fail, nothing printed
$ SWIFT_IS_CURRENT_EXECUTOR_LEGACY_MODE_OVERRIDE=legacy ./repro assume
repro/main.swift:17: Fatal error: Incorrect actor executor assumption; Expected same executor as MainActor.

If your crash log shows either signature with MainActor.assumeIsolated one frame up, it's the same mistake: the closure ran somewhere you said it wouldn't.

Why the compiler said nothing

BackgroundTasks is an Objective-C framework, and its headers carry no concurrency annotations: no NS_SWIFT_SENDABLE, no NS_SWIFT_UI_ACTOR, nothing in its API notes. The property is declared as void (^expirationHandler)(void) and Swift imports it as var expirationHandler: (() -> Void)?. Not @Sendable, not isolated to anything.

Now look at it from the compiler's side. A closure literal written inside a @MainActor method, assigned to a non-@Sendable function type, inherits the isolation of its context. A non-Sendable closure isn't allowed to cross into another isolation domain, so the compiler reasons it will be called on the main actor and lets you touch main-actor state in it. That reasoning is sound for Swift code. Objective-C never signed up for it: BackgroundTasks keeps the block and calls it from whatever thread it likes. The compiler's model of the world and the framework's behavior disagree, and nothing in the imported signature tells the compiler so.

I wanted to know how far that goes, so I built a minimal Objective-C class with the same block property and a method that calls it from dispatch_get_global_queue, then assigned three versions of the handler from a @MainActor class:

main.swift (minimal repro)
// Caller.h:  @property (nullable, strong) void (^expirationHandler)(void);
//            - (void)expireFromGlobalQueue;   // calls the block on a global queue

@MainActor
final class Setup {
    var count = 0
    let caller = Caller()

    func implicit() {
        caller.expirationHandler = { self.count += 1 }                  // inferred @MainActor
    }
    func assume() {
        caller.expirationHandler = { MainActor.assumeIsolated { self.count += 1 } }
    }
    func sendable() {
        caller.expirationHandler = { @Sendable [weak self] in
            Task { @MainActor in self?.count += 1 }
        }
    }
}

Compiled with the Swift 6.4 compiler, in both language modes, and run on a Mac:

HandlerSwift 5 modeSwift 6 mode
implicitNo warning. Runs off main, mutates main-actor state, exits normally.Same. No warning, no trap.
assumeNo warning. Traps (SIGTRAP).Same.
sendableRuns off main, then hops; the mutation happens on main.Same.

The first row is the uncomfortable one. Dumping SIL for the implicit version shows the closure marked Isolation: global_actor. type: MainActor, with no runtime check inside it in either mode. SE-0423 added dynamic isolation checks for Swift 6 code, but they cover specific seams: @objc thunks, witnesses of @preconcurrency conformances, and isolated functions converted to isolation-erasing types for modules without strict checking. A closure literal that is simply inferred as main-actor-isolated and handed to an unannotated Objective-C property fell through all of them in my test. The only check in the whole file was the one inside assumeIsolated.

That has an awkward consequence. If I had "fixed" the crash by deleting MainActor.assumeIsolated, the crash would have gone away and a silent data race on the main actor's state would have taken its place. The trap was the honest outcome.

Amana's write-up "Swift 6 Gave Me Zero Warnings, but Two Objective-C Callbacks Still Crashed at Runtime" found the same silence for expirationHandler: no warning and no trap in their repro. That matches my implicit row. The difference in ClamNotes was the explicit assumeIsolated, which is what turned the silent case into a crash in the field.

The fix in 0.7 (11)

Four changes, applied to both continued processing tasks in the app (the speech models' and the one that keeps a note's writing alive in the background):

SpeechSetup.swift, build 0.7 (11)
// simplified
private func started(_ task: BGTask) {
    guard let task = task as? BGContinuedProcessingTask, task.identifier == submitted else {
        task.setTaskCompleted(success: true)
        return
    }
    submitted = nil
    continued = task
    // iOS calls this on a queue of its own, not the main one, though the task was
    // registered with the main queue.
    let identifier = task.identifier
    task.expirationHandler = { @Sendable [weak self] in
        Task { @MainActor in self?.expired(identifier) }
    }
}

/// Nothing to do when the work ended first and completed the task.
private func expired(_ identifier: String) {
    guard let task = continued, task.identifier == identifier else { return }
    log.warning("iOS ended the speech models' continued processing task.")
    continued = nil
    stopTicker()
    task.setTaskCompleted(success: false)
}
  1. @Sendable on the closure. This is the change that matters most, because it puts the compiler back to work. A @Sendable closure doesn't inherit the main actor, so touching self.continued directly inside it is now a compile error in both language modes: main actor-isolated property 'continued' can not be mutated from a Sendable closure.
  2. Capture only Sendable values. The old closure captured task. BGTask isn't Sendable, and in the Swift 6 mode capturing it in a @Sendable closure is an error. The compiler then offers to add @preconcurrency to the import to turn such errors into warnings. Don't take that offer here: it would hide exactly the information you just gained. The closure captures the task's identifier, a String, and a weak reference to a @MainActor class, which is Sendable.
  3. Hop explicitly. Task { @MainActor in … } enqueues the cleanup on the main actor and returns at once, so the handler itself finishes quickly, which Apple asks for: All expiration handlers must complete before the allocated time. The cost is that cleanup runs on the main actor's next turn instead of synchronously.
  4. Check that the task is still the current one. Expiration and completion race. The work can finish and call setTaskCompleted(success: true) on main while iOS is already delivering the expiration on another thread. By the time the hop lands, continued may be nil or a newer task. The identifier guard makes a late expiration a no-op.

For the note-writing task, one ordering detail changed too. Its handler now hands the in-flight network requests over to iOS (a background URLSession) before calling setTaskCompleted(success: false), since completing the task lets iOS suspend the app, and anything not yet handed over at that point would be stranded.

The launch handlers kept their MainActor.assumeIsolated. They are registered with using: .main, and that contract is documented, so the assertion is true there. Each one now has a comment saying which callback is covered and which isn't.

Reproducing it without a device

I wanted to see build 10 crash and build 11 survive before uploading anything, from a fresh install. The obvious tool doesn't work in the Simulator: there is no BGTaskScheduler service there, and submit(_:) throws BGTaskScheduler is not available on this platform. Apple's own debugging recipe, Starting and Terminating Tasks During Development, uses the private _simulateLaunchForTaskWithIdentifier: and _simulateExpirationForTaskWithIdentifier: from LLDB, and says plainly that The debug functions work only on devices.

So I let LLDB play the scheduler. A shell script installs the app fresh, launches it with simctl launch --wait-for-debugger, attaches LLDB in batch mode, and then:

  1. Breaks in -[BGTaskScheduler submitTaskRequest:error:] and reads the request from the argument register.
  2. Builds a BGContinuedProcessingTask by hand through its private initializer, gives it an NSProgress through key-value coding, a handler queue and a completion block that logs.
  3. Looks up the app's registration for that identifier, and dispatches its launch handler on the registration's queue (main), exactly as iOS would.
  4. Makes the submit return YES with thread return 1.
  5. Breaks again when the app sets expirationHandler, then schedules _callExpirationHandlerWithReason: on a global queue two seconds later. That's the same call the device stack shows in frames 7 and 8.
  6. Logs the task's progress every second, lets the app run for 15 seconds, detaches, and checks with launchctl list whether the app is still alive.
bgtask-expire-test.sh (excerpt)
# Trimmed. Private API, Simulator debugging only. Never ship any of this.
E="expr -l objc++ --"
xcrun lldb --batch \
  -o "process attach --pid $PID" \
  -o "breakpoint set -n '-[BGTaskScheduler submitTaskRequest:error:]'" \
  -o "continue" \
  -o "$E @import Foundation" \
  -o "$E id \$req = (id)\$x2" \
  -o "$E id \$task = (id)[[NSClassFromString(@\"BGContinuedProcessingTask\") alloc] _initWithIdentifier:(id)[\$req identifier] activity:nil]" \
  -o "$E (void)[\$task setValue:(id)[NSProgress progressWithTotalUnitCount:0] forKey:@\"progress\"]" \
  -o "$E (void)[\$task _setHandlerQueue:dispatch_get_global_queue(0, 0)]" \
  -o "$E id \$reg = (id)[(id)[NSClassFromString(@\"BGTaskScheduler\") sharedScheduler] _unsafe_registrationForIdentifier:(id)[\$req identifier]]" \
  -o "$E id tsk = \$task; id rgs = \$reg; (void)dispatch_async((id)[rgs queue], ^{ ((void (^)(id))(id)[rgs launchHandler])(tsk); }); (void)0" \
  -o "breakpoint delete -f" \
  -o "breakpoint set -n '-[BGTask setExpirationHandler:]'" \
  -o "thread return 1" \
  -o "continue" \
  -o "$E id tsk = \$task; (void)dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 2000000000LL), dispatch_get_global_queue(0, 0), ^{ (void)[tsk _callExpirationHandlerWithReason:0]; }); (void)0" \
  -o "breakpoint delete -f" \
  -o "process continue"
  # ... then log progress, wait, detach, and check whether the app still runs

Build 10's code crashed with the TestFlight stack: _dispatch_assert_queue_fail, dispatch_assert_queue, MainActor.assumeIsolated, my closure, _callExpirationHandlerWithReason:. Build 11 logged the expiration on the main thread and kept running. The progress log also confirmed the ticker moved the value every two seconds.

Getting LLDB to cooperate took a few tries, so here are the traps I hit:

  • In --batch mode, evaluating an Objective-C expression while stopped in a Swift frame prints a note that the expression ran as Objective-C++, and the batch stops there. Evaluate only in Objective-C frames (the breakpoints above are all on Objective-C methods), with expr -l objc++.
  • Run @import Foundation first, or half the types are unknown.
  • Don't spell out dispatch_queue_t in expressions; it was ambiguous for LLDB. Cast to (id) instead, and cast every private message send to (id) or (void).
  • A convenience variable named t clashed with an existing symbol. Use longer names.

The private selectors here are discovered from the framework at runtime and can change with any iOS release. The script is a test harness for my own machine, nothing in the app references these names, and I wouldn't trust it beyond the iOS version I ran it on without checking the results against a real device. The final check for this fix was still on hardware: start the optimization and tap Stop on the system's progress UI.

A rule for Apple callbacks under Swift 6

Strict concurrency checking is only as good as the signatures it reads, and plenty of Apple's Objective-C API still has none. Here is what I do now with any callback from an Apple framework:

  1. Read the imported Swift signature, not the Objective-C one. Option-click it or open the generated interface. @MainActor on the closure type is a contract from Apple. @Sendable without an actor means "any thread". A bare () -> Void from an Objective-C framework means nobody said, which in practice also means any thread.
  2. Treat unannotated callbacks as @Sendable yourself. Writing { @Sendable in … } costs nothing, stops the closure from inheriting @MainActor, and makes the compiler check every capture and every access to isolated state inside it.
  3. Hop explicitly and capture plain values. Identifiers, value types, weak references to actor-isolated classes. Not the framework object that called you.
  4. Keep assumeIsolated for documented contracts. A queue you passed and the documentation says is used, or a header that says main thread. Leave a comment saying which. A queue parameter covers what its documentation names and nothing else.
  5. Never delete an assumeIsolated to make a crash go away. Removing it doesn't move the code to the main actor; it removes the only check.
  6. Make the rare paths run. Expiration, cancellation and failure handlers are the code that runs least often in development and most often on a stranger's phone at the worst moment. If the platform won't trigger them in the Simulator, a debugger can.

A quick audit for an existing codebase: search for assumeIsolated and for Handler = {, and for each match ask which thread calls it and where that is written down. In ClamNotes the note-writing task had the same pattern as the speech models' task and got the same fix in the same build; the UIKit beginBackgroundTask handler next to it was fine, because UIKit promises the main thread.

Built for ClamNotes

The continued processing task from this post is the one that optimizes ClamNotes' speech models on your iPhone.

ClamNotes records a class, transcribes it on the device and writes a study note in the language that was spoken. For iPhone, iPad and Mac.

See ClamNotes

Artur BerkovicsI build ClamNotes, a note-taking app for students, on my own: the iPhone, iPad and Mac apps, the relay behind them and the website. I write about what broke and how I fixed it.