포스트

[SE-0463] Import Objective-C completion handler parameters as @Sendable

이 글은 Swift Evolution 제안서 원문과 포럼 리뷰 스레드를 Claude Code 로 정리한 글이다. 코드는 Xcode 27 의 Swift 6.4 컴파일러로 빌드하고, 진단 메시지와 실행 결과는 실제로 컴파일하고 실행해서 나온 것을 옮겼다.


제안서 정보


한 줄 요약

Objective-C 메서드의 completion handler 매개변수가 Swift 로 들어올 때 @Sendable 이 기본으로 붙는다. 조건은 두 가지다. 그 메서드에 async 변형이 생기고, 메서드가 nonisolated 여야 한다. global actor 에 묶인 메서드의 handler 는 지금처럼 non-Sendable 로 두고, handler 가 정말로 같은 isolation 에서 불린다고 약속하는 헤더는 NS_SWIFT_NONSENDABLE 로 빠져나간다. 이 글은 그 규칙이 어떤 선언에 붙고 어떤 선언에 안 붙는지, 붙으면 크래시가 어떻게 사라지고 경고가 어떻게 생기는지를 컴파일러와 실행 결과로 직접 확인한다.


어떤 문제였나

Swift 6 의 정적 검사는 컴파일러가 소스를 볼 수 있는 코드만 지켜 준다. Objective-C 로 쓴 프레임워크는 “이 block 은 어느 스레드에서 불린다” 같은 약속을 헤더의 주석이나 문서에만 적어 두는 경우가 많다. 약속이 타입에 적혀 있지 않으니 Swift 컴파일러는 가장 느슨한 쪽으로 가정하고, 그 가정이 틀리면 실행 중에 프로그램이 멈춘다. SE-0463 은 그 가정을 바꾸는 제안이다.

이 글은 문제를 세 겹으로 본다. 먼저 completion handler 와 Sendable 이 무엇인지 짚고, @MainActor 안에서 만든 클로저가 왜 배경 스레드에서 불리면 죽는지를 크래시와 SIL 로 보고, 마지막으로 이 문제를 헤더 하나하나에 손으로 막던 방식을 본다. 앞 글들의 내용은 필요한 만큼만 짚는다.

  • SE-0423 글: non-Sendable 클로저의 머리에 동적 isolation 검사가 들어가는 원리. 이 글은 그 검사가 Objective-C completion handler 에서 터지는 모습에 집중한다
  • SE-0434 글: @MainActor 가 붙은 함수 타입은 @Sendable 을 함축한다
  • SE-0337 글: Objective-C 에서 가져온 선언은 암묵적으로 @preconcurrency 라서 data-race 위반이 Swift 6 모드에서도 경고에 그친다
  • SE-0418 글: 메서드 참조의 Sendable 추론. SDK 실례에서 맨 앞에 붙은 @Sendable 을 읽을 때 쓴다

completion handler 와 Sendable 이란?

completion handler 는 “일이 끝나면 이 함수를 불러 달라” 고 함수에 넘겨 두는 클로저다. 식당에서 진동벨을 받아 가는 것과 같다. 주문(메서드 호출)은 바로 끝나고, 음식이 나오면 가게가 벨(handler)을 울린다. 가게가 어느 직원(스레드)을 시켜 벨을 울릴지는 호출한 쪽이 정하지 못한다.

Sendable 은 “여러 스레드와 actor 사이를 오가도 안전하다” 는 표시다. @Sendable 클로저는 어느 스레드에서 불려도 괜찮은 클로저여야 해서, 컴파일러가 이 클로저 안에서 actor 에 묶인 상태를 만지는 코드를 막는다. 클로저를 만든 자리의 isolation 을 물려받지도 않는다. non-Sendable 클로저는 그 반대여서, 만든 자리의 isolation 을 물려받고 안에서 그 자리의 상태를 마음껏 만질 수 있다. 대신 불리는 자리가 만든 자리와 같아야 한다는 약속이 따라붙는다.

Objective-C 에서 이 약속을 적는 방법은 헤더 매크로뿐이다. 그 약속이 없는 block 을 Swift 가 어떻게 들여오느냐가 이 제안의 주제다.


만든 자리의 isolation 을 물려받는 non-Sendable 클로저

SE-0423 글에서 본 규칙을 한 문장으로 다시 적으면 이렇다. @MainActor 안에서 만든 non-Sendable 클로저는 @MainActor 로 취급되고, 컴파일러는 그 클로저의 머리에 “지금 main actor 의 executor 위에 있는가” 를 묻는 검사를 넣는다. 그 클로저를 받은 라이브러리가 컴파일러의 검사를 받지 않는 Objective-C 라면, 라이브러리는 클로저를 아무 스레드에서나 부르고 그 순간 검사가 실패해 프로그램이 멈춘다.

SE-0434 는 여기에 한 가지를 더했다. @MainActor 가 붙은 함수 타입은 @Sendable 을 함축한다. 그래서 handler 타입에 @MainActor 를 직접 적은 헤더는 이미 @Sendable 이다. 아래 측정에서 notify 가 그 경우다.


Objective-C completion handler 에서 터지는 크래시

실험 코드는 한 쌍의 Objective-C 파일과 Swift 파일이다. 헤더에서 이 절에 필요한 메서드만 발췌했다.

1
2
3
4
5
6
7
8
@interface Ops : NSObject
// 제안서 예: async 변형이 있는 completion handler
- (void)performOperation:(NSString *)operation
       completionHandler:(void (^ _Nullable)(NSString * _Nullable, NSError * _Nullable))completionHandler;

// completion handler 가 아닌 block 매개변수 (구현은 배경 큐에서 부른다)
- (void)runLater:(void (^)(void))block;
@end

구현은 두 메서드 모두 배경 큐에서 block 을 부른다.

1
2
3
4
5
6
7
8
9
static dispatch_queue_t bg(void) { return dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0); }

- (void)performOperation:(NSString *)operation
       completionHandler:(void (^)(NSString *, NSError *))completionHandler {
  dispatch_async(bg(), ^{ if (completionHandler) completionHandler(operation, nil); });
}
- (void)runLater:(void (^)(void))block {
  dispatch_async(bg(), ^{ block(); });
}

dispatch_async 로 배경 큐에서 block 부르기

dispatch_get_global_queue 는 시스템이 관리하는 전역 동시 큐를 돌려준다. QOS_CLASS_DEFAULT 는 우선순위 등급이고 두 번째 인자 0 은 예약된 값이다. dispatch_async 는 block 을 그 큐에 올려 두고 바로 돌아온다. block 은 큐의 worker 스레드 중 하나에서 돈다. main 스레드가 아니라는 점이 이 실험의 전부다.

Swift 쪽은 @MainActor 클래스 안에서 두 메서드를 부른다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import Foundation

@MainActor
final class Model {
  var count = 0

  func viaCompletion(_ ops: Ops) {
    ops.performOperation("a") { value, error in
      print("performOperation main:", Thread.isMainThread)
    }
  }

  func viaPlainBlock(_ ops: Ops) {
    ops.runLater {
      print("runLater main:", Thread.isMainThread)
    }
  }
}

@main struct Program {
  static func main() async {
    let ops = Ops()
    let model = Model()
    let which = CommandLine.arguments.dropFirst().first ?? "completion"
    if which == "completion" {
      model.viaCompletion(ops)
    } else {
      model.viaPlainBlock(ops)
    }
    try? await Task.sleep(for: .milliseconds(300))
    print("done")
  }
}

Thread.isMainThread와 Task.sleep으로 실행 스레드 확인하기

Thread.isMainThread 는 지금 코드가 main 스레드에서 도는지 알려 주는 Bool 이다. 클로저가 어느 스레드에서 불렸는지를 출력으로 남기려고 썼다. Task.sleep(for:) 는 현재 task 를 주어진 시간만큼 재운다. 배경 큐의 block 이 돌 시간을 주려고 300 밀리초를 잤다. CommandLine.arguments 는 프로그램을 실행할 때 넘긴 인자의 배열이고 0번째가 실행 파일 이름이라서 dropFirst().first 로 첫 인자를 꺼냈다. @main 이 붙은 타입의 static func main() async 는 프로그램의 진입점이고, async 라서 안에서 await 를 쓸 수 있다.

컴파일하면 진단이 없다.

1
xcrun swiftc -emit-sil -o /dev/null -parse-as-library -wmo -swift-version 6 -import-objc-header Ops.h Run.swift
1
[exit 0]

-emit-sil 은 SIL(컴파일러 중간 표현) 단계까지 컴파일해서 그 단계의 진단까지 낸다. -typecheck 는 SIL 단계 진단을 빼먹기 때문에 이 글의 진단은 모두 -emit-sil 로 뽑았다. -import-objc-header Ops.h 는 Objective-C 헤더를 Swift 소스가 바로 쓸 수 있게 가져오는 옵션이다. 실행 파일은 이렇게 만든다.

1
2
xcrun clang -c -fobjc-arc Ops.m -o Ops.o
xcrun swiftc -parse-as-library -swift-version 6 -import-objc-header Ops.h Run.swift Ops.o -o run

Program.main 은 CommandLine.arguments 로 실행 인자를 읽어 어느 갈래를 탈지 고른다. 인자가 없으면 completion 으로 보고, completion 이면 performOperation 쪽, 그 밖의 값(plain)이면 runLater 쪽이다. 먼저 performOperation 쪽이다.

1
./run completion
1
2
3
performOperation main: false
done
[exit 0]

handler 는 main 이 아닌 스레드에서 불렸고 아무 일도 없었다. 이 handler 는 @Sendable 로 들어왔기 때문이다. 이 글의 컴파일러(Swift 6.4)에서는 SE-0463 이 이미 들어가 있다. 같은 코드를 runLater 로 바꾸면 이 제안이 없던 시절의 모습이 나온다. runLater: 는 매개변수 이름이 block 이고 async 변형이 없어서 completion handler 로 취급되지 않고 non-Sendable 로 들어온다. Swift 6.2 이전에는 performOperation 의 handler 도 이 runLater 의 block 과 같은 non-Sendable 타입으로 들어왔다.

1
./run plain
1
[exit 133]

출력 없이 종료 코드 133(SIGTRAP)으로 끝난다. done 도 찍히지 않는다. lldb 에서 실행하면 어디서 멈추는지 보인다.

1
timeout 20 xcrun lldb --batch -o run -k bt -k quit -- ./run plain
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
* thread #2, queue = 'com.apple.root.default-qos', stop reason = EXC_BREAKPOINT (code=1, subcode=...)
    frame #0: libdispatch.dylib`_dispatch_assert_queue_fail + 120
    frame #1: libdispatch.dylib`dispatch_assert_queue$V2.cold.1 + 116
    frame #2: libdispatch.dylib`dispatch_assert_queue + 108
    frame #3: libswift_Concurrency.dylib`_swift_task_checkIsolatedSwift + 48
    frame #4: libswift_Concurrency.dylib`swift_task_isCurrentExecutorWithFlagsImpl(swift::SerialExecutorRef, swift::swift_task_is_current_executor_flag) + 356
    frame #5: run`closure #1 in Model.viaPlainBlock(_:) + 72
    frame #6: run`reabstraction thunk helper from @escaping @callee_guaranteed () -> () to @escaping @callee_unowned @convention(block) () -> () + 48
    frame #7: run`__16-[Ops runLater:]_block_invoke + 40
    frame #8: libdispatch.dylib`_dispatch_call_block_and_release + 32
    frame #9: libdispatch.dylib`_dispatch_client_callout + 16
    frame #10: libdispatch.dylib`_dispatch_queue_override_invoke.cold.3 + 32
    frame #11: libdispatch.dylib`_dispatch_queue_override_invoke + 848
    frame #12: libdispatch.dylib`_dispatch_root_queue_drain + 360
    frame #13: libdispatch.dylib`_dispatch_worker_thread2 + 184
    frame #14: libsystem_pthread.dylib`_pthread_wqthread + 232

주소는 뺐다. 이 backtrace 는 아래에서 위로 읽는다. 배경 큐의 worker 스레드가 Ops.m 의 block_invoke 를 부르고, Swift 가 만든 reabstraction thunk(Swift 클로저를 Objective-C block 모양으로 바꿔 주는 중간 함수)를 거쳐 closure #1 in Model.viaPlainBlock 으로 들어간다. 이 클로저의 첫머리에서 swift_task_isCurrentExecutor 계열 함수가 “지금 main actor 의 executor 인가” 를 묻고, 답이 아니라서 dispatch_assert_queue 가 실패한다. 클로저 안에는 print 한 줄뿐이다. 코드 어디에도 오류가 없고 진단도 없는데 실행하면 죽는다.

이 검사가 클로저의 어디에 들어가는지는 SIL 로 볼 수 있다. 앞 실행 파일을 만들 때 쓴 소스에서 SIL 을 뽑아 demangle 한 뒤, 검사 함수를 부르는 곳만 찾았다.

1
2
3
xcrun swiftc -emit-sil -o run.raw.sil -parse-as-library -wmo -swift-version 6 -import-objc-header Ops.h Run.swift
xcrun swift-demangle < run.raw.sil > run.sil
awk '/^sil /{c=$0} /function_ref @swift_task_isCurrentExecutor/{print c}' run.sil
1
2
sil private @closure #1 () -> () in main.Model.viaPlainBlock(__C.Ops) -> () : $@convention(thin) () -> () {
sil public_external [transparent] [available 12.0.0] @Swift._checkExpectedExecutor(_filenameStart: Builtin.RawPointer, _filenameLength: Builtin.Word, _filenameIsASCII: Builtin.Int1, _line: Builtin.Word, _executor: Builtin.Executor) -> () : $@convention(thin) (Builtin.RawPointer, Builtin.Word, Builtin.Int1, Builtin.Word, Builtin.Executor) -> () {

첫 줄이 runLater 에 넘긴 non-Sendable 클로저고, 둘째 줄은 표준 라이브러리에 있는 _checkExpectedExecutor 자신이다. viaCompletion 의 클로저는 목록에 없다. 이 클로저의 SIL 앞부분을 발췌하면 검사의 모양이 보인다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
sil private @closure #1 () -> () in main.Model.viaPlainBlock(__C.Ops) -> () : $@convention(thin) () -> () {
bb0:
  %0 = metatype $@thick MainActor.Type
  %1 = function_ref @static Swift.MainActor.shared.getter : Swift.MainActor : $@convention(method) (@thick MainActor.Type) -> @owned MainActor
  %2 = apply %1(%0) : $@convention(method) (@thick MainActor.Type) -> @owned MainActor
  %3 = extract_executor %2
  %4 = string_literal utf8 "main/Run.swift"
  %5 = integer_literal $Builtin.Word, 14
  %6 = integer_literal $Builtin.Int1, -1
  %7 = integer_literal $Builtin.Word, 14
  ...
  %8 = function_ref @swift_task_isCurrentExecutor : $@convention(thin) (Builtin.Executor) -> Bool
  %9 = apply %8(%3) : $@convention(thin) (Builtin.Executor) -> Bool
  %10 = struct_extract %9, #Bool._value
  cond_br %10, bb1, bb2
  ...
bb2:
  %13 = function_ref @swift_task_reportUnexpectedExecutor : $@convention(thin) (Builtin.RawPointer, Builtin.Word, Builtin.Int1, Builtin.Word, Builtin.Executor) -> ()
  %14 = apply %13(%4, %5, %6, %7, %3) : ...

MainActor.shared 에서 executor 를 꺼내 swift_task_isCurrentExecutor 로 비교하고, 아니면 swift_task_reportUnexpectedExecutor 로 간다. swift_task_reportUnexpectedExecutor 의 인자는 파일명 포인터(%4), 파일명 길이(%5), ASCII 여부(%6), 줄 번호(%7), executor(%3) 순서다. %5 의 14 는 main/Run.swift 라는 문자열의 길이이고, 줄 번호는 %7 의 14 로 ops.runLater { 가 있는 줄이다. 둘이 우연히 같은 값이라 헷갈리기 쉬운데, Edge.swift 로 만든 SIL 에서는 파일명 main/Edge.swift 의 길이가 15 이고 줄 번호가 10 과 17 로 갈려 나온다. 아래 그림은 같은 흐름을 두 클로저로 나란히 그린 것이다.

non-Sendable 클로저는 머리에서 main actor 의 executor 를 검사해 배경 큐에서 불리면 멈추고, @Sendable 클로저는 검사 없이 본문을 실행한다

nonisolated @Sendable 클로저는 비교할 isolation 이 없고, viaCompletion 의 클로저는 SIL 에 이 호출이 없다. 이 제안이 하는 일은 performOperation 같은 handler 를 오른쪽 열로 옮기는 것이다.


헤더에 하나씩 적던 표시

이 문제는 제안 전에도 알려져 있었고, 막는 방법은 헤더에 NS_SWIFT_SENDABLE 을 적는 것이었다. 이 매크로는 SDK 의 NSObjCRuntime.h 에서 __attribute__((swift_attr("@Sendable"))) 로 펼쳐진다.

1
grep -n 'define NS_SWIFT_SENDABLE\|define NS_SWIFT_NONSENDABLE\|define NS_SWIFT_SENDING' "$(xcrun --show-sdk-path)/System/Library/Frameworks/Foundation.framework/Headers/NSObjCRuntime.h"
1
2
3
4
5
6
274:#  define NS_SWIFT_SENDING __attribute__((swift_attr("sending")))
276:#  define NS_SWIFT_SENDING
285:#  define NS_SWIFT_SENDABLE __attribute__((swift_attr("@Sendable")))
291:#  define NS_SWIFT_NONSENDABLE __attribute__((swift_attr("@_nonSendable")))
307:#  define NS_SWIFT_SENDABLE
309:#  define NS_SWIFT_NONSENDABLE

274행과 276행은 NS_SWIFT_SENDING 의 두 가지 정의다. 285행과 307행도 NS_SWIFT_SENDABLE 의 두 가지고, 291행과 309행은 NS_SWIFT_NONSENDABLE 이다. Swift 컴파일러가 아닌 쪽(예를 들어 일반 C 컴파일러)에서는 매크로가 빈 문자열이 된다. SDK 의 헤더에서 block 타입 앞에 이 표시를 직접 적은 곳을 세어 보면 이렇다.

1
grep -rE '\^ *NS_SWIFT_SENDABLE' "$(xcrun --show-sdk-path)/System/Library/Frameworks" | wc -l
1
     183

183곳이다. Apple 이 몇 년에 걸쳐 헤더를 한 줄씩 고쳐 온 결과고, Fritzt 도 리뷰 스레드에서 자기 Objective-C 코드의 handler 에 NS_SWIFT_SENDABLE 을 이미 다 붙여 두었다고 적었다(리뷰 #12). 그러나 헤더를 고칠 수 있는 쪽은 라이브러리 작성자뿐이고, 빠진 헤더 하나가 곧 사용자 앱의 크래시다. Swift forums 에도 handler 를 자동으로 @Sendable 로 감사하는 방법이 없느냐는 질문 이 올라와 있었다. 제안서 Motivation 이 이 글을 근거로 든다.

pitch 를 연 hborla 가 든 사례는 SecAddSharedWebCredential 이 Swift 6 에서 크래시한다는 포럼 글 이었고, 거기서 KeithBauerANZ 는 이렇게 적었다. “importing ObjC closures without @Sendable is no longer a conservative choice.” (pitch #1 이 인용한 글.) Swift 6 가 되면서 “일단 @Sendable 을 안 붙이는 것” 이 안전한 쪽이 아니게 됐다는 말이다.


무엇이 바뀌나

제안서 Detailed design 의 첫 문장이 규칙 전부다. 가져온 메서드에 SE-0297(Concurrency Interoperability with Objective-C) 이 정한 async 변형이 있고, 그 메서드가 암묵적으로든 명시적으로든 nonisolated 이면, 원래 메서드의 completion handler 매개변수에 @Sendable 을 붙인다. SE-0297 제안서 가 정한 async 변형은, 마지막 매개변수가 completion handler 이고 반환 타입이 void 인 메서드에서 컴파일러가 이름과 모양으로 알아보고 만든다. 아래는 이 규칙이 실제 선언에 어떻게 적용되는지를 한 절씩 본다.

ObjC block 매개변수가 Swift 로 들어올 때 @Sendable 이 되는지를 가르는 결정 순서와 갈래마다의 실행 결과


completion handler 를 알아보는 규칙

가져온 선언을 보는 도구는 swift-synthesize-interface 다. Objective-C 헤더를 module map 으로 감싸 주면 Swift 쪽에서 본 모양을 그대로 출력한다.

1
xcrun swift-synthesize-interface -module-name Ops -I mod -sdk "$(xcrun --show-sdk-path)" -target arm64-apple-macos15

Ops.h 의 선언 중 이 절에서 볼 것은 세 가지다. 맨 아래 Loader 는 프로토콜이다.

1
2
3
4
5
6
- (BOOL)tryOperation:(NSString *)operation
   completionHandler:(void (^)(NSString * _Nullable))completionHandler;

@protocol Loader <NSObject>
- (void)loadWithCompletionHandler:(void (^)(NSInteger))completionHandler;
@end

performOperation: 은 앞 절에서 본 그대로다. 결과를 선언 순서대로 발췌한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
open class Ops : NSObject {

    open func performOperation(_ operation: String, completionHandler: (@Sendable (String?, (any Error)?) -> Void)? = nil)

    open func performOperation(_ operation: String) async throws -> String

    open func tryOperation(_ operation: String, completionHandler: @escaping (String?) -> Void) -> Bool

    open func runLater(_ block: @escaping () -> Void)
    ...
}

public protocol Loader : NSObjectProtocol {

    func load(completionHandler: @escaping @Sendable (Int) -> Void)

    func load() async -> Int
}
  • performOperation 의 handler 는 @Sendable 이고, 같은 메서드의 async throws -> String 변형이 따로 생겼다. 제안서의 예다
  • tryOperation 은 이름이 completion handler 처럼 보여도 BOOL 을 돌려주기 때문에 async 변형이 없다. handler 는 @escaping (String?) -> Void 그대로고 Sendable 이 아니다
  • runLater 는 async 변형이 없고 매개변수 이름도 completion handler 가 아니다. 역시 @escaping () -> Void 다
  • 프로토콜 요구사항도 대상이다. Loader.load 의 handler 는 @escaping @Sendable (Int) -> Void 로 들어온다

이 규칙을 한 줄로 줄이면 “async 변형이 생기는 메서드의 handler 만 @Sendable 이 된다” 이다. handler 라고 볼 수 있어도 async 변형을 만들 수 없는 모양이면 건드리지 않는다. 이름만 보고 판단하지 않고 컴파일러가 async 변형을 만들 수 있는지를 기준으로 삼은 셈이다.

이 구분이 실행에서도 갈리는지 tryOperation 과 save 로 재 본다. 둘 다 구현이 배경 큐에서 handler 를 부르고, save 는 헤더에 NS_SWIFT_SENDABLE 이 붙은 메서드다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import Foundation

@MainActor
final class Model {
  var count = 0
  func viaTry(_ ops: Ops) {
    _ = ops.tryOperation("a") { _ in
      print("try main:", Thread.isMainThread)
    }
  }
  func viaSave(_ ops: Ops) {
    ops.save {
      print("save main:", Thread.isMainThread)
    }
  }
}

@main struct Program {
  static func main() async {
    let model = Model()
    let which = CommandLine.arguments.dropFirst().first ?? "save"
    if which == "try" { model.viaTry(Ops()) } else { model.viaSave(Ops()) }
    try? await Task.sleep(for: .milliseconds(300))
    print("done")
  }
}
1
2
xcrun swiftc -parse-as-library -swift-version 6 -import-objc-header Ops.h Try.swift Ops.o -o trybin6
./trybin6 try
1
[exit 133]
1
./trybin6 save
1
2
3
save main: false
done
[exit 0]

tryOperation 의 handler 는 non-Sendable 이라 runLater 와 같이 출력 없이 종료 코드 133 으로 멈추고, save 의 @Sendable handler 는 배경 스레드에서 불려도 done 까지 간다.


@Sendable 이 된 클로저

앞 절의 실행에서 performOperation 의 handler 는 main 이 아닌 스레드에서 불리고도 멀쩡했다. 이유는 SIL 에 이미 나왔다. nonisolated @Sendable 클로저는 첫머리에 swift_task_isCurrentExecutor 호출이 없다. 같은 @MainActor 클래스 안에서 만들었어도, non-Sendable 클로저는 만든 자리의 isolation 을 물려받고 @Sendable 클로저는 물려받지 않는다.

그렇다고 공짜는 아니다. 클로저가 @Sendable 이 되었으니 컴파일러는 그 클로저 안에서 @MainActor 상태를 만지는 코드를 더 이상 허락하지 않는다. 크래시가 컴파일 경고로 바뀌는 것이다. 다음 절에서 본다.


새로 생기는 경고

@MainActor 클래스 안에서 performOperation 의 클로저가 actor 상태를 만지거나 non-Sendable 값을 캡처한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
final class Log { var lines: [String] = [] }

@MainActor
final class Model {
  var count = 0
  let log = Log()

  func load(_ ops: Ops) {
    ops.performOperation("a") { value, error in
      self.count += 1
    }
  }

  func capture(_ ops: Ops) {
    let local = Log()
    ops.performOperation("b") { value, error in
      local.lines.append(value ?? "")
    }
  }

  func refresh(_ ops: Ops) {
    ops.refresh {
      self.count += 1
    }
  }

  func plain(_ ops: Ops) {
    ops.runLater {
      self.count += 1
    }
  }
}
1
bash diag.sh -import-objc-header Ops.h Diag.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
Diag.swift:10:12: warning: main actor-isolated property 'count' can not be mutated from a Sendable closure
 3 | @MainActor
 4 | final class Model {
 5 |   var count = 0
   |       `- note: mutation of this property is only permitted within the actor
 6 |   let log = Log()
 7 | 
 8 |   func load(_ ops: Ops) {
 9 |     ops.performOperation("a") { value, error in
10 |       self.count += 1
   |            `- warning: main actor-isolated property 'count' can not be mutated from a Sendable closure
11 |     }
12 |   }

Diag.swift:17:7: warning: capture of 'local' with non-Sendable type 'Log' in a '@Sendable' closure [#SendableClosureCaptures]
 1 | final class Log { var lines: [String] = [] }
   |             `- note: class 'Log' does not conform to the 'Sendable' protocol
 2 | 
 3 | @MainActor
   :
15 |     let local = Log()
16 |     ops.performOperation("b") { value, error in
17 |       local.lines.append(value ?? "")
   |       `- warning: capture of 'local' with non-Sendable type 'Log' in a '@Sendable' closure [#SendableClosureCaptures]
18 |     }
19 |   }

[#SendableClosureCaptures]: <https://docs.swift.org/compiler/documentation/diagnostics/sendable-closure-captures>
[exit 0]

diag.sh 는 위의 -emit-sil -o /dev/null -parse-as-library -wmo -swift-version 6 명령에 -import-objc-header 같은 옵션을 이어 붙여 주는 한 줄짜리 스크립트고, 마지막에 [exit N] 으로 종료 코드를 찍는다. 경고는 두 개다.

  • load 의 self.count += 1: @Sendable 클로저에서 main actor 의 프로퍼티를 바꿀 수 없다. 이 클로저는 배경 스레드에서 불릴 수 있으니 맞는 말이다
  • capture 의 local.lines.append(...): Sendable 이 아닌 Log 를 @Sendable 클로저가 캡처했다. 같은 Log 를 다른 스레드가 동시에 만질 수 있다는 경고다

반대로 refresh 와 plain 의 self.count += 1 은 진단이 없다. refresh 는 global actor 메서드라서 handler 가 non-Sendable 이고(다음 절), plain 은 runLater 의 non-Sendable block 이다. 진단이 없다고 안전한 것은 아니다. plain 은 앞 절에서 실행하면 크래시한 바로 그 코드의 변형이다.

이 경고가 Swift 6 모드에서도 error 가 아니라 warning 인 이유는 SE-0337 에서 왔다. Objective-C 에서 가져온 선언은 암묵적으로 @preconcurrency 라서 data-race 위반이 경고로 낮아진다. 같은 일을 Swift 로 선언한 함수로 하면 error 다.

1
2
3
4
5
6
7
8
9
10
11
12
func swiftPerform(_ handler: @escaping @Sendable () -> Void) {}

@MainActor
final class Model {
  var count = 0

  func load() {
    swiftPerform {
      self.count += 1
    }
  }
}
1
bash diag.sh -import-objc-header Ops.h Contrast.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
Contrast.swift:9:12: error: main actor-isolated property 'count' can not be mutated from a Sendable closure
 3 | @MainActor
 4 | final class Model {
 5 |   var count = 0
   |       `- note: mutation of this property is only permitted within the actor
 6 | 
 7 |   func load() {
 8 |     swiftPerform {
 9 |       self.count += 1
   |            `- error: main actor-isolated property 'count' can not be mutated from a Sendable closure
10 |     }
11 |   }
[exit 1]

문구는 같고 심각도만 다르다. 이 차이가 이 제안이 소스를 한꺼번에 깨지 않는 이유다. 새로 생기는 진단은 모두 경고여서 지금 빌드가 되는 프로젝트가 빌드되지 않게 되지는 않는다.

경고를 없애는 길은 둘이다. 하나는 클로저 안의 일을 Task { @MainActor in ... } 로 main actor 에 넘기는 것이고, 하나는 async 변형으로 바꿔 쓰는 것이다.

1
2
3
4
5
6
7
8
9
10
11
12
  func fixed(_ ops: Ops) {
    ops.performOperation("a") { value, error in
      Task { @MainActor in
        self.count += 1
      }
    }
  }

  func modern(_ ops: Ops) async throws {
    let value = try await ops.performOperation("a")
    count += value.count
  }

이 두 함수는 Contrast.swift 13행부터 24행에 load 와 나란히 들어 있다. load 를 뺀 변형(ContrastFix.swift)을 같은 명령으로 돌리면 이렇게 나온다.

1
bash diag.sh -import-objc-header Ops.h ContrastFix.swift
1
[exit 0]

두 함수 모두 진단이 없다. Task { @MainActor in ... } 은 @Sendable 클로저 안에서 새 task 를 만들고 그 task 가 main actor 에서 돌게 한다. 클로저 자신은 어느 스레드에서 불려도 되고, actor 상태를 만지는 줄만 main actor 로 건너간다. modern 은 handler 가 아예 사라진다.


global actor 메서드의 예외

pitch 에서 KeithBauerANZ 가 한 가지를 제안했다(#2). @MainActor 메서드의 completion handler 는 @Sendable 이 아니라 @MainActor 로 보자는 것이다. 이유는 Objective-C 의 흔한 관용이 “main actor 메서드는 handler 도 main actor 에서 부른다” 이기 때문이다. @MainActor 추정은 받아들여지지 않았고, 대신 non-Sendable 로 두는 carve-out 이 됐다. global actor 메서드의 handler 는 @Sendable 로 만들지 않고 non-Sendable 로 둔다. Swift 쪽에서 @MainActor 문맥에서 만든 non-Sendable 클로저는 이미 main actor 로 취급되니, 따로 @MainActor 를 붙이지 않아도 결과가 같기 때문이다.

1
2
3
4
5
6
7
// main actor 에 묶인 메서드
- (void)refreshWithCompletionHandler:(void (^)(void))completionHandler NS_SWIFT_UI_ACTOR;

NS_SWIFT_UI_ACTOR
@interface Screen : NSObject
- (void)reloadWithCompletionHandler:(void (^)(void))completionHandler;
@end

NS_SWIFT_UI_ACTOR 는 @MainActor 로 가져오라는 매크로다. 메서드에 붙이면 그 메서드만, 클래스에 붙이면 클래스의 모든 멤버가 main actor 에 묶인다. interface 는 이렇게 나온다.

1
2
3
4
5
6
7
8
9
10
    @MainActor open func refresh(completionHandler: @escaping () -> Void)

    @MainActor open func refresh() async
...
@MainActor open class Screen : NSObject {

    open func reload(completionHandler: @escaping () -> Void)

    open func reload() async
}

두 handler 모두 @Sendable 이 없다. 구현은 main 큐에서 handler 를 부르고, Swift 쪽 코드는 클로저 안에서 self.count += 1 을 쓴다.

1
2
3
4
5
6
7
8
9
10
11
12
13
  func viaMainActorMethod(_ ops: Ops) {
    ops.refresh {
      self.count += 1
      print("refresh main:", Thread.isMainThread, "count:", self.count)
    }
  }

  func viaMainActorClass(_ screen: Screen) {
    screen.reload {
      self.count += 1
      print("reload main:", Thread.isMainThread, "count:", self.count)
    }
  }
1
bash diag.sh -import-objc-header Ops.h Carve.swift
1
[exit 0]
1
./carve main
1
2
3
4
refresh main: true count: 1
reload main: true count: 2
done
[exit 0]

진단이 없고 실행도 멀쩡하다. 클로저가 @Sendable 이었다면 self.count += 1 은 앞 절의 경고가 되었을 것이다. 이 예외는 “main actor 메서드는 handler 를 main actor 에서 부른다” 는 약속을 믿고 거짓 경고를 줄이는 장치다. 제안서도 이 점을 적었다. 새로 @Sendable 을 붙이는 경우가 아니라 지금 non-Sendable 인 경우를 그대로 두는 것이라서 새 동적 검사가 생기지도 않는다. hborla 도 pitch #6 에서 같은 말을 했다.

그 약속이 깨지는 API 도 있다. refreshLater 는 NS_SWIFT_UI_ACTOR 메서드인데 구현이 배경 큐에서 handler 를 부른다.

1
2
3
4
5
6
  // main actor 예외: 구현이 배경 큐에서 부른다
  func later(_ ops: Ops) {
    ops.refreshLater {
      print("refreshLater main:", Thread.isMainThread)
    }
  }
1
timeout 20 xcrun lldb --batch -o run -k bt -k quit -- ./edge later
1
2
3
4
5
6
7
8
9
10
* thread #2, queue = 'com.apple.root.default-qos', stop reason = EXC_BREAKPOINT (code=1, subcode=...)
    frame #0: libdispatch.dylib`_dispatch_assert_queue_fail + 120
    frame #1: libdispatch.dylib`dispatch_assert_queue$V2.cold.1 + 116
    frame #2: libdispatch.dylib`dispatch_assert_queue + 108
    frame #3: libswift_Concurrency.dylib`_swift_task_checkIsolatedSwift + 48
    frame #4: libswift_Concurrency.dylib`swift_task_isCurrentExecutorWithFlagsImpl(swift::SerialExecutorRef, swift::swift_task_is_current_executor_flag) + 356
    frame #5: edge`closure #1 in Model.later(_:) + 72
    frame #6: edge`reabstraction thunk helper from @escaping @callee_guaranteed () -> () to @escaping @callee_unowned @convention(block) () -> () + 48
    frame #7: edge`__41-[Ops refreshLaterWithCompletionHandler:]_block_invoke + 40
    ...

주소와 아래쪽 dispatch 프레임은 줄였다. runLater 와 같은 backtrace 다. 이 제안이 handler 를 @Sendable 로 만들지 않았으니 SE-0423 의 검사가 그대로 남은 것이다. “main actor 메서드면 handler 도 main 에서 부른다” 는 가정이 깨지는 API 는 이 제안 뒤에도 크래시한다. 이 제안은 그 크래시를 늘리지도 줄이지도 않는다.


한편 handler 타입에 @MainActor 를 직접 적은 헤더는 사정이 다르다. grynspan 이 리뷰 #3 에서 던진 질문이다. 메서드는 actor 에 묶이지 않았는데 handler 타입에만 @MainActor 가 적혀 있으면 @Sendable 이 붙지 않는가. John_McCall 은 #5 에서 @MainActor 가 붙은 함수 타입은 @Sendable 을 함축한다고 답했다. 처음에는 그렇지 않았는데 SE-0434 에서 고쳤다는 것이다.

1
2
// handler 타입 자체에 @MainActor 를 적은 경우
- (void)notifyWithCompletionHandler:(void (^ __attribute__((swift_attr("@MainActor"))))(void))completionHandler;

interface 는 open func notify(completionHandler: @escaping @MainActor @Sendable () -> Void) 로 나온다. @MainActor 와 @Sendable 이 함께 찍혔다. 구현은 main 큐에서 handler 를 부른다.

1
2
3
4
5
6
  func viaNotify(_ ops: Ops) {
    ops.notify {
      self.count += 1
      print("notify main:", Thread.isMainThread, "count:", self.count)
    }
  }
1
./edge notify
1
2
3
notify main: true count: 1
done
[exit 0]

클로저가 @MainActor 라서 self.count += 1 이 경고 없이 된다. 이 경우 handler 는 @Sendable 이지만 main actor 에 묶여 있어서 actor 상태를 만질 수 있다.


헤더에서 빼기

handler 가 정말로 호출한 쪽의 isolation 에서 불리는 API 도 있다. 그런 헤더는 NS_SWIFT_NONSENDABLE 로 @Sendable 을 빼 달라고 적는다. NS_SWIFT_NONSENDABLE 은 swift_attr("@_nonSendable") 로 펼쳐지고, 이것을 block 타입 자리에 붙이면 handler 가 non-Sendable 이 된다.

1
2
// NS_SWIFT_NONSENDABLE 로 빼기 (구현은 배경 큐에서 부른다)
- (void)fetchWithCompletionHandler:(void (^ NS_SWIFT_NONSENDABLE)(NSInteger))completionHandler;

interface 에서 fetch 는 이렇게 보인다.

1
2
3
    open func fetch(completionHandler: @escaping (Int) -> Void)

    open func fetch() async -> Int

handler 는 non-Sendable 이고 async 변형은 그대로 남는다. 반대로 NS_SWIFT_SENDABLE 을 이미 붙인 save 는 원래부터 @escaping @Sendable () -> Void 다. 이 제안이 있어도 없어도 같다.

이 표시는 약속이다. 구현이 정말 같은 isolation 에서 부를 때만 붙여야 한다. 구현이 배경 큐에서 fetch 의 handler 를 부르는 Ops.m 을 @MainActor 에서 부르면 이렇게 된다.

1
2
3
4
5
  func viaNonSendable(_ ops: Ops) {
    ops.fetch { value in
      print("fetch main:", Thread.isMainThread)
    }
  }
1
timeout 20 xcrun lldb --batch -o run -k bt -k quit -- ./carve fetch
1
2
3
4
5
6
7
8
9
10
* thread #2, queue = 'com.apple.root.default-qos', stop reason = EXC_BREAKPOINT (code=1, subcode=...)
    frame #0: libdispatch.dylib`_dispatch_assert_queue_fail + 120
    frame #1: libdispatch.dylib`dispatch_assert_queue$V2.cold.1 + 116
    frame #2: libdispatch.dylib`dispatch_assert_queue + 108
    frame #3: libswift_Concurrency.dylib`_swift_task_checkIsolatedSwift + 48
    frame #4: libswift_Concurrency.dylib`swift_task_isCurrentExecutorWithFlagsImpl(swift::SerialExecutorRef, swift::swift_task_is_current_executor_flag) + 356
    frame #5: carve`closure #1 in Model.viaNonSendable(_:) + 80
    frame #6: carve`reabstraction thunk helper from @escaping @callee_guaranteed (@unowned Swift.Int) -> () to @escaping @callee_unowned @convention(block) (@unowned Swift.Int) -> () + 56
    frame #7: carve`__34-[Ops fetchWithCompletionHandler:]_block_invoke + 44
    ...

NS_SWIFT_NONSENDABLE 은 컴파일러에게 검사를 끄라는 표시가 아니라 “이 handler 는 호출한 자리와 같은 isolation 에서 불린다” 는 보증이다. 보증이 틀리면 SE-0423 의 검사가 그 자리에서 잡는다.

SDK 에서 이 표시를 쓰는 곳은 9개 파일이다. Virtualization 의 VZUSBController 와 VZVirtualMachine, VZVirtioSocketDevice, AVFAudio 의 AVAudioEngine, AVAudioNode 같은 곳이다.

1
grep -rlE '\^ *NS_SWIFT_NONSENDABLE' "$(xcrun --show-sdk-path)/System/Library/Frameworks" | sort
1
2
3
4
5
6
7
8
9
.../AVFAudio.framework/Versions/A/Headers/AVAudioConverter.h
.../AVFAudio.framework/Versions/A/Headers/AVAudioEngine.h
.../AVFAudio.framework/Versions/A/Headers/AVAudioIONode.h
.../AVFAudio.framework/Versions/A/Headers/AVAudioNode.h
.../AVFAudio.framework/Versions/A/Headers/AVAudioSinkNode.h
.../AVFAudio.framework/Versions/A/Headers/AVAudioSourceNode.h
.../Virtualization.framework/Versions/A/Headers/VZUSBController.h
.../Virtualization.framework/Versions/A/Headers/VZVirtioSocketDevice.h
.../Virtualization.framework/Versions/A/Headers/VZVirtualMachine.h

경로 앞부분은 줄였다.


처음부터 안전한 async 변형

같은 fetch 를 async 변형으로 부르면 크래시가 나지 않는다.

1
2
3
4
5
  // NS_SWIFT_NONSENDABLE 인 메서드의 async 변형
  func viaAsync(_ ops: Ops) async {
    let value = await ops.fetch()
    print("async fetch:", value)
  }
1
./edge async
1
2
3
async fetch: 42
done
[exit 0]

fetch 의 handler 는 non-Sendable 이어서 completion handler 로 부르면 크래시했다(앞 절). async 변형은 같은 메서드인데도 async fetch: 42 가 나온다. 컴파일러가 async 변형을 만들 때 completion handler 를 직접 만들어 넘기는데, John_McCall 이 수락 공지 뒤의 글(acceptance #3)에서 말한 대로 이 handler 는 늘 sendable 패턴을 쓴다. 그래서 fetch 가 어느 스레드에서 handler 를 부르든 안전하다. 제안서가 마지막에 “region isolation 을 쓰고 싶으면 async/await 로 고치라” 고 권하는 이유가 이것이다.


override 와 프로토콜 구현

handler 가 @Sendable 이 되면 그 메서드를 override 하거나 프로토콜을 구현한 기존 코드가 깨지지 않을까. 시험해 본다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
final class MyOps: Ops {
  override func performOperation(
    _ operation: String,
    completionHandler: ((String?, (any Error)?) -> Void)? = nil
  ) {
    completionHandler?(operation, nil)
  }
}

final class MyLoader: NSObject, Loader {
  func load(completionHandler: @escaping (Int) -> Void) {
    completionHandler(1)
  }
}

final class SendableLoader: NSObject, Loader {
  func load(completionHandler: @escaping @Sendable (Int) -> Void) {
    completionHandler(1)
  }
}
1
bash modes.sh -import-objc-header Ops.h Override.swift
1
2
3
=== -import-objc-header Ops.h Override.swift [-swift-version 5]
=== -import-objc-header Ops.h Override.swift [-swift-version 5 -strict-concurrency=complete]
=== -import-objc-header Ops.h Override.swift [-swift-version 6]

세 모드 모두 진단이 하나도 없다. modes.sh 는 Swift 5, Swift 5 complete, Swift 6 로 차례로 컴파일해서 error 와 warning 줄만 보여 주는 스크립트다. @Sendable 없이 override 한 MyOps 도, non-Sendable 로 구현한 MyLoader 도, @Sendable 로 구현한 SendableLoader 도 통과한다. 기존 코드의 override 와 구현이 깨지지 않는다. 이 사실이 Alternatives 의 sending 논의와 이어진다. 뒤에서 다시 본다.


SDK 에서 보기

실제 SDK 선언은 어떻게 들어올까. 일부러 Int 에 대입하는 타입 오류를 내서 컴파일러가 출력하는 타입을 읽는다. 오류 문구가 목적이라 진단은 -emit-sil 로 뽑는다.

1
2
3
4
5
6
7
import AppKit
import Virtualization

func show(w: NSWorkspace, c: VZUSBController) {
  let a: Int = w.openApplication(at:configuration:completionHandler:)
  let b: Int = c.attach(device:completionHandler:)
}
1
xcrun swiftc -emit-sil -o /dev/null -parse-as-library -wmo -swift-version 6 SDK.swift
1
2
SDK.swift:5:18: error: cannot convert value of type '(URL, NSWorkspace.OpenConfiguration, (@Sendable (NSRunningApplication?, (any Error)?) -> Void)?) -> Void' to specified type 'Int'
SDK.swift:6:18: error: cannot convert value of type '(any VZUSBDevice, @escaping ((any Error)?) -> Void) -> Void' to specified type 'Int'

출력에서 오류 줄만 골랐다. NSWorkspace.openApplication(at:configuration:completionHandler:) 는 헤더(NSWorkspace.h 46행)와 AppKit 의 apinotes 에 Sendable 표시가 없는데도 handler 가 @Sendable 이다. 이 제안의 규칙으로 붙은 것이다. 반면 VZUSBController.attach(device:completionHandler:) 는 헤더(VZUSBController.h 48행)에 NS_SWIFT_NONSENDABLE 이 적혀 있어서 handler 가 @escaping ((any Error)?) -> Void 그대로다. 같은 completion handler 모양인데 헤더 표시 하나로 갈린다.

다음은 스레드에서 사례로 나온 두 API 다.

1
2
3
4
5
6
import AVFAudio

func probe(_ node: AVAudioPlayerNode) {
  let a: Int = AVAudioApplication.requestRecordPermission(completionHandler:)
  let b: Int = node.scheduleBuffer(_:completionCallbackType:completionHandler:)
}
1
xcrun swiftc -emit-sil -o /dev/null -parse-as-library -wmo -swift-version 6 SDK2.swift
1
2
SDK2.swift:4:35: error: cannot convert value of type '@Sendable (@escaping @Sendable (Bool) -> Void) -> Void' to specified type 'Int'
SDK2.swift:5:21: error: cannot convert value of type '@Sendable (AVAudioPCMBuffer, AVAudioPlayerNodeCompletionCallbackType, (@Sendable (AVAudioPlayerNodeCompletionCallbackType) -> Void)?) -> Void' to specified type 'Int'

두 타입 모두 맨 앞에 @Sendable 이 하나 더 붙어 있다. 이것은 handler 와 상관없고 메서드 참조의 Sendable 추론이다(SE-0418). 경우가 둘로 갈린다.

  • AVAudioApplication.requestRecordPermission(completionHandler:) 는 인스턴스 없이 메타타입으로 참조한 unapplied 참조라서 @Sendable 이 붙는다
  • node.scheduleBuffer(...) 는 Sendable 인 AVAudioPlayerNode 인스턴스에 부분 적용한 참조라서 @Sendable 이 붙는다

앞의 w.openApplication 타입에는 이 맨 앞 @Sendable 이 없다. NSWorkspace 가 Sendable 이 아니기 때문이다. 아래처럼 Sendable 제약을 거는 함수에 두 클래스를 넘겨 보면 NSWorkspace 쪽만 오류가 난다.

1
2
3
4
5
6
7
import AVFAudio
import AppKit
func need<T: Sendable>(_: T.Type) {}
func probe() {
  need(AVAudioPlayerNode.self)
  need(NSWorkspace.self)
}
1
SendCheck.swift:6:3: error: conformance of 'NSWorkspace' to 'Sendable' is unavailable

AVAudioPlayerNode 줄은 오류가 없다. 읽어야 할 것은 타입의 괄호 안이다.

  • requestRecordPermission 의 handler 는 @escaping @Sendable (Bool) -> Void 다. 헤더(AVAudioApplication.h 119행)에 표시가 없고 AVFAudio.apinotes 에도 AVAudioApplication 항목이 없다. 이 제안이 붙인 @Sendable 이다. Karl 이 수락 공지 뒤에 적은 API 이고, 권한이 이미 있으면 handler 를 바로 부르고 없으면 사용자에게 물은 뒤 임의 스레드에서 부른다고 했다
  • scheduleBuffer(_:completionCallbackType:completionHandler:) 의 handler 는 @Sendable (AVAudioPlayerNodeCompletionCallbackType) -> Void 다. Karl 이 리뷰 #14 에서 AVAudioPlayerNode 의 완료 콜백이 임의 스레드에서 불려 크래시한 경험으로 든 API 다. 이 API 의 typedef AVAudioPlayerNodeCompletionHandler 에는 NS_SWIFT_SENDING 이 붙어 있는데(AVAudioPlayerNode.h 78행), Swift 로 들어온 매개변수 타입은 @Sendable 이다

스레드에서 오간 이야기

pitch 는 7개 글, 리뷰는 14개 글(번호는 #1 부터 #15 까지이고 #4 는 없다), 수락 공지 뒤에 두 글이 더 달렸다. 논의는 규모에 비해 조용했고 방향이 거의 한쪽이었다.


찬성의 결

  • tclementdev 는 pitch #3 에서 이 변경이 “Swift 6 로 옮기는 실제 코드에서 꽤 많은 크래시를 일으키는” 문제를 막는다고 했고, 리뷰 #7 에서는 Objective-C interface 가 아무 약속도 하지 않으면 @Sendable 만이 말이 된다고 적었다
  • KeithBauerANZ 는 pitch #2 에서 모두의 코드에 경고가 늘겠지만 대부분 진짜 경고일 것이고 더 나은 선택지가 보이지 않는다고 했다
  • Fritzt 는 리뷰 #12 에서 자기 Objective-C handler 에 이미 NS_SWIFT_SENDABLE 을 다 붙여 왔다고 했다. 이 제안은 그 일을 기본값으로 올린다

main actor 에서 global actor 로

KeithBauerANZ 의 pitch #2 가 carve-out 의 시작이다. ksluder 가 pitch #5 에서 “@MainActor 타입의 completion handler 메서드에 @MainActor 를 추론하는 다른 휴리스틱이 이미 있지 않느냐” 고 물었고, hborla 는 #6 에서 그런 추론 규칙은 없지만 non-Sendable 클로저가 만든 자리의 isolation 을 물려받는 규칙 덕에 대부분 맞아떨어진다고 답했다. @MainActor 메서드는 거의 늘 @MainActor 문맥에서 불리고(아니면 await 가 필요하니 async 변형이 낫다), 그래서 handler 클로저도 그 규칙으로 main actor 에 묶인다는 것이다. 오늘 non-Sendable 인 경우에만 해당하니 동적 검사가 새로 생기지 않는다는 설명도 여기서 나왔다.

grynspan 은 pitch #7 에서 @MainActor 만이 아니라 모든 global actor 로 넓히자고 했다. custom serial executor 를 쓰는 global actor 가 생각보다 많을 수 있다는 이유였다. 최종 제안서의 문구가 “global actor 전체” 인 것이 이 제안이 받아들여진 결과다.


handler 타입에 직접 적은 @MainActor

위 절에서 본 grynspan 리뷰 #3 의 질문과 John_McCall #5 의 답이다. grynspan 은 #6 에서 “SE-0434 를 완전히 잊고 있었다” 고 받아들였다.


minimal 모드의 경고 걱정

nukka123 은 리뷰 #9 에서 Core Data 의 perform 을 들었다. NSManagedObjectContext(non-Sendable)를 perform 클로저 안에서 만져야 하는데, Xcode 에서는 strict concurrency 를 minimal 아래로 내릴 수 없어서 피할 수 없는 경고가 생기지 않느냐는 것이다. hborla 는 #10 에서 제안서의 Source compatibility 절을 가리키며, minimal 에서는 Sendable 경고가 모두 억제되고 complete 나 Swift 6 에서만 경고가 늘어난다고 답했다. BastianKusserow 가 #11 에서 Swift 6 모드와 complete 를 쓰는 프로젝트라면 그 경고는 피할 수 없지 않느냐고 되물었고, nukka123 은 #13 에서 Xcode 16.0 의 버그 때문에 minimal 을 잘못 이해했다고 정정했다. 자기 코드의 NSPredicate 를 DispatchQueue 클로저로 넘기는 곳에서 16.0 은 경고를 냈고 16.2 는 내지 않았다는 이야기다. 참고로 Core Data 의 performBlock: 은 헤더에 이미 NS_SWIFT_SENDABLE 이 붙어 있다(NSManagedObjectContext.h 93행).

이 대화는 다음 절 “Swift 6 모드와 마이그레이션” 의 minimal 측정과 이어진다.


클로저 머리의 검사

Karl 은 리뷰 #14 에서 AVAudioPlayerNode 의 schedule 콜백이 임의 스레드에서 불려 크래시한 일을 적었다. @MainActor 클래스 안에서 클로저에 self.state += 1 을 썼더니 컴파일러는 가만히 있었고 실행하면 죽었다. 그는 클로저를 @Sendable _ in 으로 적으면 피할 수 있음을 스스로 찾아냈다. 더 나아가, 클로저 안에서 isolation 이 필요한 일만 detached Task 로 넘겨도 소용없다고 했다. 크래시가 컴파일러가 만든 클로저 머리에서 일어나기 때문이다.

hborla 는 #15 에서 이 문제가 실재한다고 인정하고 클로저가 isolated 상태에 접근하지 않으면 컴파일러가 동적 검사를 생략해야 한다며 swiftlang/swift#75856 을 가리켰다. 세 가지를 6.4 로 재 봤다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
  // 빈 클로저
  func empty(_ ops: Ops) {
    ops.runLater { }
  }

  // 클로저 안에서 Task 로 넘기기
  func hop(_ ops: Ops) {
    ops.runLater {
      Task { @MainActor in self.bump() }
    }
  }

  // 클로저에 @Sendable 을 직접 적기
  func explicit(_ ops: Ops) {
    ops.runLater { @Sendable in
      Task { @MainActor in self.bump() }
    }
  }
1
bash diag.sh -import-objc-header Ops.h Edge.swift
1
[exit 0]

세 함수 모두 진단이 없다. 실행하면 결과가 갈린다.

1
timeout 20 xcrun lldb --batch -o run -k bt -k quit -- ./edge empty
1
2
3
4
5
6
7
8
* thread #2, queue = 'com.apple.root.default-qos', stop reason = EXC_BREAKPOINT (code=1, subcode=...)
    frame #0: libdispatch.dylib`_dispatch_assert_queue_fail + 120
    ...
    frame #4: libswift_Concurrency.dylib`swift_task_isCurrentExecutorWithFlagsImpl(swift::SerialExecutorRef, swift::swift_task_is_current_executor_flag) + 356
    frame #5: edge`closure #1 in Model.empty(_:) + 72
    frame #6: edge`reabstraction thunk helper from @escaping @callee_guaranteed () -> () to @escaping @callee_unowned @convention(block) () -> () + 48
    frame #7: edge`__16-[Ops runLater:]_block_invoke + 40
    ...
1
timeout 20 xcrun lldb --batch -o run -k bt -k quit -- ./edge hop
1
2
3
4
5
6
7
8
* thread #2, queue = 'com.apple.root.default-qos', stop reason = EXC_BREAKPOINT (code=1, subcode=...)
    frame #0: libdispatch.dylib`_dispatch_assert_queue_fail + 120
    ...
    frame #4: libswift_Concurrency.dylib`swift_task_isCurrentExecutorWithFlagsImpl(swift::SerialExecutorRef, swift::swift_task_is_current_executor_flag) + 356
    frame #5: edge`closure #1 in Model.hop(_:) + 180
    frame #6: edge`reabstraction thunk helper from @escaping @callee_guaranteed () -> () to @escaping @callee_unowned @convention(block) () -> () + 48
    frame #7: edge`__16-[Ops runLater:]_block_invoke + 40
    ...
1
./edge explicit
1
2
done
[exit 0]
  • 빈 클로저 { } 도 크래시한다. 클로저가 아무 상태에도 접근하지 않아도 머리의 검사는 있다
  • hop 은 Karl 의 관찰 그대로다. isolation 이 필요한 일을 Task { @MainActor in ... } 로 넘겨 놓았는데도 클로저 머리에서 죽는다
  • @Sendable 을 클로저에 직접 적으면 done 이 나오고 끝난다. Karl 이 찾은 우회가 그대로 통한다

swiftlang/swift#75856 은 이 글을 쓴 2026-11-26 기준 열려 있다(gh issue view 75856 -R swiftlang/swift --json state,title). 제목은 “Elide dynamic actor isolation check when closure does not access actor-isolated state.” 다. 이 제안은 async 변형이 있는 completion handler 에 대해서만 이 문제를 없앴고, runLater 처럼 completion handler 로 볼 수 없는 block 은 이 제안의 바깥이다.


수락과 그 뒤

John_McCall 은 수락 공지(#1)에서 리뷰 피드백이 적었지만 긍정적이었고 Language Steering Group 이 커뮤니티와 같은 생각이라 SE-0463 을 수락한다고 했다. 2주 뒤 Karl 이 #2 에서 오늘도 같은 문제를 만났다며 AVAudioApplication.requestRecordPermission 예를 올렸다. 이미 권한이 있으면 handler 를 동기로 부르고, 없으면 프레임워크가 사용자에게 물은 뒤 임의 스레드에서 부르는데, 이 정보가 현재 문서 에는 없고 이미 deprecated 된 AVAudioSession 쪽 문서 에만 남아 있다고 했다. Xcode 16.3 에 이 수정이 들어가는지도 물었다.

John_McCall 은 #3 에서 이 변경이 Xcode 16.3 에는 너무 늦었고 Swift 6.2 가 들어간 릴리스를 기다려야 한다고 했다. 그리고 Objective-C async 호출을 위해 컴파일러가 만드는 completion handler 는 늘 sendable 패턴을 쓴다고 덧붙였다. 앞의 ./edge async 측정이 이 말과 맞는다. 이 글에서 requestRecordPermission 의 타입을 직접 읽었을 때 handler 가 @Sendable 이었으므로, Karl 이 만난 크래시가 이 API 에서는 막혔다.


기대 효과

  • 크래시가 경고로 바뀐다. 헤더에 NS_SWIFT_SENDABLE 이 빠진 completion handler 를 @MainActor 안에서 쓰면 SE-0423 의 동적 검사가 배경 스레드에서 프로그램을 멈췄다. 이제 컴파일러가 “이 클로저는 main actor 상태를 만질 수 없다” 고 먼저 말한다
  • 헤더를 고치는 쪽의 일이 거꾸로 선다. 지금까지는 @Sendable 을 붙이는 것이 작업이었고, 이제는 handler 가 같은 isolation 에서 불린다는 보증이 있을 때만 NS_SWIFT_NONSENDABLE 을 붙여 빼는 것이 작업이다. 틀렸을 때의 비용이 크래시에서 경고로 옮겨 갔다
  • 서드파티 Objective-C 라이브러리도 헤더를 고치지 않고 이 규칙의 혜택을 본다. Apple SDK 의 183곳에 표시가 붙기를 기다릴 필요가 없다
  • async 변형으로 옮기라는 압력이 생긴다. 경고를 고치는 가장 짧은 길이 await 이기 때문이다

다른 선택지는 왜 안 됐나

제안서가 따로 검토한 대안은 하나이고, 스레드에서 두 가지가 더 나왔다. 셋을 차례로 본다.


sending 대신 @Sendable

Alternatives 의 유일한 항목이다. handler 를 sending 으로 가져와도 되지 않았느냐는 질문이다(SE-0430 글). sending 은 region 분석으로 “이 값은 이 호출 뒤 호출한 쪽이 더 쓰지 않는다” 고 보증하는 쪽이라 @Sendable 보다 느슨하다. 제안서가 @Sendable 을 고른 이유는 실용적이다.

  • SendableCompletionHandlers 실험 기능이 2021년부터 있었고 source 호환 면에서 충분히 시험되었다. 6.4 에서는 이 이름이 플래그로 남아 있지 않고 늘 켜져 있다
  • @Sendable 은 Objective-C 프레임워크에 몇 해째 명시적으로 채택되어 왔다. @Sendable 이 맞지 않는 구석에서 컴파일러가 보이던 문제들도 그동안 다듬어졌다
  • sending 은 아직 새롭고 채택이 덜 되었다. @preconcurrency 와 함께 써도 Swift 6 모드에서 진단 수준을 낮추지 못한다
  • 나중에 sending 으로 바꾸면 source 호환이 깨진다. sending 으로 가져온 프로토콜 요구사항을 @Sendable 로 구현한 코드, 같은 방식으로 override 한 클래스 메서드가 무효가 된다

위 override 와 프로토콜 구현 측정에서 SendableLoader 가 @Sendable 로 구현해 통과했다. 이 제안이 sending 이었다면 이 코드가 깨진다는 뜻이다. region 분석의 이득을 원하는 코드에는 async/await 로 옮기라고 권하는 것이 제안서의 답이다.


main actor 메서드의 handler 를 @MainActor 로 추정하기

KeithBauerANZ 의 pitch #2 제안이다. @MainActor 추정은 받아들여지지 않았고, 대신 non-Sendable 로 두는 carve-out 이 됐다. handler 를 @MainActor 로 만드는 대신 non-Sendable 로 두어서, @MainActor 문맥에서 만든 클로저가 이미 main actor 로 취급되는 규칙에 맡겼다. 결과는 같고 새 동적 검사는 없다. hborla 가 pitch #6 에서 말한 대로, 대부분의 @MainActor handler 가 실제로는 @Sendable 이어야 한다고 드러나면 나중에 규칙을 넓힐 수 있다.


모든 global actor 로 넓히기

grynspan 의 pitch #7 제안이고 받아들여졌다. main actor 에 한정하지 않고 global actor 전체로 carve-out 을 쓴 것이 최종안이다. 앞의 Screen 측정이 같은 규칙의 클래스 단위 적용이다.


Swift 6 모드와 마이그레이션

이 변경이 기존 프로젝트에 어떤 영향을 주는지를 소스 호환, ABI, 경고를 고치는 길로 나눠 본다.


소스 호환

제안서의 Source compatibility 는 이 변경이 새 경고만 만들고 모두 @preconcurrency 덕에 경고에 그친다고 말한다. Contrast 측정에서 같은 일을 Swift 로 선언한 함수로 하면 error 였던 것과 맞는다. 이제 strict concurrency 단계별로 같은 코드를 재 본다. Minimal.swift 는 동시성 기능을 하나도 쓰지 않은 클래스가 non-Sendable Log 를 performOperation 클로저에 캡처하는 코드다.

1
2
3
4
5
6
7
8
9
10
11
12
13
import Foundation

final class Log { var lines: [String] = [] }

// 동시성 기능을 하나도 쓰지 않은 코드
final class Plain {
  func capture(_ ops: Ops) {
    let local = Log()
    ops.performOperation("a") { value, error in
      local.lines.append(value ?? "")
    }
  }
}
1
xcrun swiftc -emit-sil -o /dev/null -parse-as-library -wmo -swift-version 5 -strict-concurrency=minimal -import-objc-header Ops.h Minimal.swift
1

출력이 없다. -strict-concurrency=targeted 도 마찬가지고, complete 로 올리면 경고가 나온다.

1
xcrun swiftc -emit-sil -o /dev/null -parse-as-library -wmo -swift-version 5 -strict-concurrency=complete -import-objc-header Ops.h Minimal.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Minimal.swift:10:7: warning: capture of 'local' with non-Sendable type 'Log' in a '@Sendable' closure [#SendableClosureCaptures]
 1 | import Foundation
 2 | 
 3 | final class Log { var lines: [String] = [] }
   |             `- note: class 'Log' does not conform to the 'Sendable' protocol
 4 | 
 5 | // 동시성 기능을 하나도 쓰지 않은 코드
   :
 8 |     let local = Log()
 9 |     ops.performOperation("a") { value, error in
10 |       local.lines.append(value ?? "")
   |       `- warning: capture of 'local' with non-Sendable type 'Log' in a '@Sendable' closure [#SendableClosureCaptures]
11 |     }
12 |   }

[#SendableClosureCaptures]: <https://docs.swift.org/compiler/documentation/diagnostics/sendable-closure-captures>

앞의 Diag.swift(@MainActor 를 명시한 코드)까지 네 모드로 경고 수를 센 표다. 경고 수만 세었고 note 는 세지 않았다.

코드Swift 5 minimalSwift 5 targetedSwift 5 completeSwift 6
Minimal.swift (동시성 기능을 쓰지 않음)0011
Diag.swift (@MainActor 명시)2222

표에서 읽히는 것은 이렇다. minimal 은 동시성 기능을 명시적으로 쓴 코드에만 Sendable 검사를 한다. Plain 은 동시성 기능을 하나도 쓰지 않아서 minimal 과 targeted 에서 조용하고 complete 에서 경고가 나온다. Diag.swift 의 Model 은 @MainActor 를 명시해서 minimal 에서도 경고가 보인다. Swift 5 모드의 기본 단계가 minimal 이니, 기존 Swift 5 프로젝트가 Plain 같은 코드만 갖고 있다면 새 경고를 보지 않는다. 따라서 nukka123 의 Core Data 걱정은 동시성 기능을 쓰지 않은 코드에서는 minimal 이 지켜 주고, @MainActor 를 쓴 코드에서는 지켜 주지 않는다는 결론이 된다.


ABI 와 플래그

ABI 영향은 없다. 클로저의 Sendable 여부는 ABI 에 들어가지 않는 타입 정보다. upcoming feature flag 도 없다. 같은 approachable concurrency 묶음인 SE-0461 과 SE-0466 은 플래그나 build setting 으로 켜지만, 이 제안은 켜고 끌 스위치가 없다. SendableCompletionHandlers 는 2021년부터 있던 실험 기능의 이름이고, 6.4 에서는 플래그 없이 늘 켜져 있다.


경고를 고치는 길

  1. 클로저 안에서 actor 상태를 만지는 일을 Task { @MainActor in ... } 으로 넘긴다
  2. async 변형으로 바꿔 쓴다. handler 가 없어지고 위의 modern 처럼 한 줄이 된다
  3. handler 가 정말로 같은 isolation 에서 불리는 라이브러리의 헤더를 고칠 수 있다면 NS_SWIFT_NONSENDABLE 을 붙인다. 이 표시는 보증이다. 틀리면 앞의 fetch 처럼 실행 중에 멈춘다

정리

  • Objective-C 메서드에 async 변형이 생기고 메서드가 nonisolated 이면 completion handler 매개변수가 @Sendable 로 들어온다. 기준은 이름이 아니라 컴파일러가 async 변형을 만들 수 있는지다. tryOperation 처럼 async 변형이 없는 메서드와 runLater 처럼 completion handler 가 아닌 block 은 non-Sendable 그대로다. 프로토콜 요구사항도 대상이다
  • nonisolated @Sendable 클로저는 첫머리에 동적 isolation 검사가 없다. 배경 큐에서 불려도 크래시하지 않고, 대신 클로저 안에서 @MainActor 상태를 만지거나 non-Sendable 값을 캡처하면 경고가 난다. 같은 일이 Swift 로 선언한 함수에서는 error 인데 여기서는 암묵적 @preconcurrency 덕에 경고다
  • global actor 에 묶인 메서드와 클래스의 handler 는 non-Sendable 로 둔다. @MainActor 문맥에서 만든 non-Sendable 클로저가 이미 main actor 로 취급되어 거짓 경고가 사라진다. 구현이 배경 큐에서 부르는 refreshLater 같은 API 는 이 제안 뒤에도 크래시한다
  • handler 타입에 @MainActor 를 직접 적은 헤더는 @MainActor @Sendable 이다(SE-0434). NS_SWIFT_SENDABLE 은 원래대로, NS_SWIFT_NONSENDABLE 은 handler 를 non-Sendable 로 빼는 보증이다. NS_SWIFT_NONSENDABLE 은 @_nonSendable 로 펼쳐져 block 타입 자리에서 handler 를 non-Sendable 로 바꾼다
  • async 변형은 컴파일러가 늘 sendable 패턴으로 completion handler 를 만들어서 처음부터 안전하다. override 와 프로토콜 구현은 @Sendable 이 있든 없든 깨지지 않는다
  • 클로저 머리의 동적 검사는 이 제안 뒤에도 남아 있다. 빈 클로저도, 안에서 Task 로 넘기는 클로저도 크래시하고 @Sendable 을 직접 적어야 피한다. swiftlang/swift#75856 은 2026-11-26 기준 열려 있다
  • 소스 호환은 경고 수준에서 끝난다. Swift 5 minimal 에서 동시성 기능을 쓰지 않은 코드는 조용하고, @MainActor 를 쓴 코드는 minimal 에서도 경고가 보인다. ABI 영향은 없고 플래그도 없다. approachable concurrency 로 묶인 SE-0461, SE-0466 과 같은 날 Swift 6.2 에 들어갔다

관련 글


참고자료

이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.