포스트

[SE-0471] Improved Custom SerialExecutor isolation checking for Concurrency Runtime

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


제안서 정보

이 글의 코드는 모두 아래 명령으로 빌드해서 돌렸다. 파일 이름은 코드 블록 위에 적었다. 글의 코드 블록은 samples 파일의 머리 주석을 뺀 것이라, crash 메시지의 줄 번호(Order.swift:61 등)는 samples 파일 기준이다.

1
xcrun swiftc -parse-as-library -swift-version 6 Order.swift -o order

-parse-as-library

@main 을 쓰는 파일을 최상위 코드 없이 컴파일하는 옵션이다.

-swift-version 6

Swift 6 언어 모드로 빌드한다. 이 글에서 모드가 결과를 바꾸는 곳은 한 군데이고, 그곳에서는 -swift-version 5 로 다시 빌드한 결과를 따로 적었다.

-o order

실행 파일 이름을 소문자로 정했다. 크래시 메시지에 order/Order.swift:61 처럼 모듈 이름이 소문자로 찍히는 것은 이 때문이다.


한 줄 요약

SerialExecutor 에 isIsolatingCurrentContext() -> Bool? 가 생겼다. executor 가 “지금 내 안이다”, “아니다”, “모르겠다” 중 하나로 답할 수 있게 되어서, 런타임이 crash 하지 않고 isolation 을 물을 수 있다.


어떤 문제였나

SE-0424 에서 custom executor 가 isolation 검사에 참여하는 길이 열렸다. 그 길은 “통과하거나 crash 하거나” 둘 중 하나였고, 이 제안은 그 사이에 “아니라고 알려 주는” 길을 하나 더 낸다.


SerialExecutor 와 isolation 검사란?

actor 는 자기 상태를 한 번에 한 곳에서만 만지게 하려고 executor 를 하나 가진다. executor 는 “이 작업을 어디서 돌릴지” 를 정하는 객체이고, 일을 하나씩 차례로 돌리는 executor 가 SerialExecutor 다. 보통은 시스템이 만든 executor 를 쓰지만, 자기 DispatchSerialQueue 위에서 actor 를 돌리고 싶으면 SerialExecutor 를 직접 구현해서 actor 의 unownedExecutor 로 내놓는다. 이것이 custom executor 다.

isolation 검사는 “지금 이 코드가 정말 이 executor 가 보호하는 자리에서 도는가” 를 런타임에 확인하는 일이다. 컴파일러가 증명하지 못하지만 개발자가 알고 있는 경우에 쓴다. 예를 들어 어떤 프로토콜 메서드가 늘 main actor 에서 불린다는 것을 알고 있는데 프로토콜에 @MainActor 가 안 붙어 있으면, MainActor.assumeIsolated 로 “여기는 main actor 다” 라고 선언하고 본문에서 main actor 상태를 만진다. 이때 런타임이 정말 그런지 확인하고, 아니면 멈춘다. assumeIsolated, preconditionIsolated, assertIsolated 가 이 검사를 쓴다.

검사는 두 단계로 이뤄진다. 먼저 현재 task 가 있으면 task 가 속한 executor 와 기대하는 executor 를 비교한다. 이 비교는 executor 의 코드를 부르지 않고 끝나는 빠른 길이다. task 가 없는 자리(예를 들어 DispatchQueue.async 블록 안)이거나 비교가 안 맞으면, 런타임이 executor 에게 직접 묻는다. SE-0424 는 이때 부르는 메서드로 checkIsolated() 를 만들었다. 이 글은 두 번째 단계, 즉 executor 에게 묻는 부분을 다룬다. checkIsolated() 가 어떻게 생겼고 왜 생겼는지는 SE-0424 글에 있다.


pass or crash 의 한계

checkIsolated() 는 반환값이 없다. 맞으면 그냥 돌아오고, 아니면 executor 가 스스로 crash 해야 한다. 제안서는 이것을 “pass or crash” 라고 부르고 두 가지 한계를 든다.

  • crash 메시지가 불친절하다. executor 가 지금 어디서 돌고 있었는지 같은 정보를 런타임이 알 수 없어서 “이 executor 여야 한다” 정도밖에 말하지 못한다
  • 런타임이 warning 만 낼 수 없다. executor 에게 물으면 executor 가 crash 해 버리니, “틀렸지만 계속 가자” 가 불가능하다

두 번째가 더 크다. 라이브러리가 strict concurrency 를 도입하는 과정에서는, 지금까지 우연히 돌아가던 잘못된 호출 방식을 바로 crash 로 막기보다 몇 버전 동안 warning 으로 알리고 싶다. checkIsolated() 만으로는 그럴 수 없었다.


무엇이 바뀌나

SerialExecutor 에 요구사항 하나가 더해지고, actor 에서 executor 를 꺼내는 메서드가 하나 더해진다. 아래는 요구사항의 모양, 그것을 구현한 executor 가 런타임에게 어떻게 불리는지, 불리지 않는 경우는 언제인지, crash 하면 안 되는 검사에서 어떻게 달라지는지, 그리고 actor 에서 executor 를 꺼내 쓰는 법 순서로 본다.


새 요구사항과 세 가지 답

6.4 의 _Concurrency interface 에서 SerialExecutor 의 isolation 검사 부분은 아래와 같다.

1
2
3
4
5
6
7
public protocol SerialExecutor : _Concurrency::Executor {
  ...
  @available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *)
  func checkIsolated()
  @available(anyAppleOS 26.0, *)
  func isIsolatingCurrentContext() -> Swift::Bool?
}

(발췌이고 ... 는 생략한 줄이다.) 기본 구현은 별도 extension 에 있다.

1
2
3
4
5
@available(anyAppleOS 26.0, *)
extension _Concurrency::SerialExecutor {
  @available(anyAppleOS 26.0, *)
  public func isIsolatingCurrentContext() -> Swift::Bool?
}

두 번째 블록이 기본 구현이다. 본문은 interface 에 나오지 않지만, 기본 구현이 어떤 값을 돌려주는지는 직접 불러서 확인했다(아래 Fallback 에서 default isIsolatingCurrentContext() on this executor: nil 이 찍힌다). 기본 구현은 nil 이다. 그래서 기존 executor 는 코드를 고치지 않아도 컴파일된다.

답은 세 가지다.

  • true: 지금 이 executor 의 isolation 안이다. 검사 통과
  • false: 아니다. 검사 실패
  • nil: 이 executor 는 알 수 없다

런타임은 isIsolatingCurrentContext() 를 checkIsolated() 보다 먼저 묻고, true 나 false 가 오면 거기서 끝낸다. nil 이 왔을 때만 다음 단계로 간다. 그 다음 단계가 무엇인지는 어떤 검사냐에 따라 갈리는데, 아래에서 하나씩 잰다.

제안서의 첫 버전에서는 반환형이 Bool 이었다. 리뷰에서 “모른다” 를 표현할 길이 없다는 지적이 나와서 Bool? 로 바뀌었다. 그 과정은 스레드 절에 있다.


확인용 executor 만들기

런타임이 두 메서드를 어떤 순서로 몇 번 부르는지 보려고, 두 메서드를 다 구현하고 부를 때마다 한 줄씩 찍는 executor 를 만들었다. 첫 블록은 executor 자체다.

Order.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
30
31
32
33
34
35
36
37
38
39
40
41
import Dispatch
import Darwin

final class LogExecutor: SerialExecutor, @unchecked Sendable {
  let queue = DispatchSerialQueue(label: "log-queue")
  let key = DispatchSpecificKey<Bool>()
  let answer: String

  init(answer: String) {
    self.answer = answer
    queue.setSpecific(key: key, value: true)
  }

  func enqueue(_ job: consuming ExecutorJob) {
    let job = UnownedJob(job)
    let me = asUnownedSerialExecutor()
    queue.async { job.runSynchronously(on: me) }
  }

  func asUnownedSerialExecutor() -> UnownedSerialExecutor {
    UnownedSerialExecutor(ordinary: self)
  }

  var onQueue: Bool { DispatchQueue.getSpecific(key: key) == true }

  func checkIsolated() {
    print("  [executor] checkIsolated() onQueue=\(onQueue)")
    precondition(onQueue, "checkIsolated: not on log-queue")
  }

  func isIsolatingCurrentContext() -> Bool? {
    let result: Bool? = switch answer {
      case "honest": onQueue
      case "true": true
      case "false": false
      default: nil
    }
    print("  [executor] isIsolatingCurrentContext() onQueue=\(onQueue) -> \(String(describing: result))")
    return result
  }
}

DispatchSerialQueue

executor 가 일을 돌릴 자리다. 일을 하나씩 차례로 돌리는 queue 라서 SerialExecutor 의 뒷받침으로 쓰기 좋다. 공식 문서는 DispatchSerialQueue 에 있다.

DispatchSpecificKey

queue 에 꼬리표를 붙이고 나중에 “지금 그 queue 위인가” 를 읽는 도구다. setSpecific(key:value:) 로 queue 에 붙이고, DispatchQueue.getSpecific(key:) 는 지금 도는 queue 에 그 꼬리표가 있을 때만 값을 돌려준다. 그래서 onQueue 가 “지금 log-queue 위인가” 의 답이 된다. 문서는 DispatchSpecificKey 에 있다.

ExecutorJob, UnownedJob, runSynchronously(on:)

enqueue 는 executor 가 일을 받는 자리다. 받은 ExecutorJob 은 소비되는 값이라 그대로 queue 의 클로저에 들고 갈 수 없어서, UnownedJob 으로 감싸서 들고 간다. queue 에서 runSynchronously(on:) 을 부르면 그 job 이 그 자리에서 돈다.

UnownedSerialExecutor(ordinary:)

actor 가 unownedExecutor 로 내놓는 값이다. ordinary: 로 만들면 “이 객체가 executor 다” 라는 가장 평범한 표시가 된다. 문서는 UnownedSerialExecutor 에 있다.

isIsolatingCurrentContext() 는 answer 값에 따라 답을 고른다. honest 는 실제로 queue 위인지 보고 true 나 false 를 답하고, true, false 는 늘 그 값을 답하고, 나머지는 nil 이다. 이 값을 바꿔 가며 런타임의 반응을 본다.

두 번째 블록은 이 executor 를 쓰는 actor 다.

Order.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
actor Logged {
  nonisolated let executor: LogExecutor
  nonisolated var unownedExecutor: UnownedSerialExecutor { executor.asUnownedSerialExecutor() }
  var count = 0
  init(answer: String) { executor = LogExecutor(answer: answer) }

  func inTask(_ api: String) {
    check(api)
  }

  nonisolated func check(_ api: String) {
    print("call \(api)")
    switch api {
    case "precondition": self.preconditionIsolated("precondition message")
    case "assert": self.assertIsolated("assert message")
    default:
      let n = self.assumeIsolated { a in
        a.count += 1
        return a.count
      }
      print("assumeIsolated body ran, count=\(n)")
    }
    print("returned")
  }
}

assumeIsolated, preconditionIsolated, assertIsolated

세 메서드는 모두 “지금 이 actor 의 자리인지” 를 런타임에 확인한다. preconditionIsolated 와 assertIsolated 는 확인만 하고 아니면 멈춘다. assumeIsolated 는 맞으면 클로저 안에서 actor 상태를 바로 만지게 해 준다. 문서는 preconditionIsolated, assertIsolated 에 있다.

check 는 nonisolated 라서 어디서 불러도 된다. inTask 는 actor 메서드라서 task 안에서 check 를 부른다.

세 번째 블록은 호출 자리를 정한다. 일부러 main 을 동기 함수로 두고 DispatchQueue.async 블록 안에서 검사를 했다. 이 자리에는 task 가 없어서, 위에서 말한 빠른 길(task 의 executor 비교)이 끼지 않는다.

Order.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
30
@main
struct Main {
  // main 을 동기로 두고, 검사는 task 가 없는 queue 블록 안에서 한다
  static func main() {
    setvbuf(stdout, nil, _IONBF, 0)
    let args = CommandLine.arguments
    let answer = args.count > 1 ? args[1] : "honest"
    let place = args.count > 2 ? args[2] : "onQueue"
    let api = args.count > 3 ? args[3] : "assume"
    print("answer=\(answer) where=\(place) api=\(api)")
    let a = Logged(answer: answer)
    let done = DispatchSemaphore(value: 0)
    switch place {
    case "onQueue":
      a.executor.queue.async {
        print("withUnsafeCurrentTask: \(withUnsafeCurrentTask { $0 == nil ? "no task" : "task" })")
        a.check(api); done.signal()
      }
    case "offQueue":
      DispatchQueue(label: "other").async {
        print("withUnsafeCurrentTask: \(withUnsafeCurrentTask { $0 == nil ? "no task" : "task" })")
        a.check(api); done.signal()
      }
    default:
      Task.detached { await a.inTask(api); done.signal() }
    }
    done.wait()
    print("end")
  }
}

withUnsafeCurrentTask

지금 코드가 task 안에서 도는지 알려 준다. 안이면 task 가, 아니면 nil 이 클로저에 넘어온다. 두 자리 모두 no task 가 찍혀서 task 없이 검사한다는 것을 확인했다. 문서는 withUnsafeCurrentTask(body:) 에 있다.

DispatchSemaphore

비동기 블록이 끝날 때까지 main 이 기다리게 한다. 문서는 DispatchSemaphore 에 있다.

실행 인자는 <answer> <where> <api> 순서다. where 는 세 가지다. onQueue 는 task 없이 executor 의 queue 위, offQueue 는 task 없이 다른 queue 위, inTask 는 actor 메서드 안이다.


호출 순서 재기

먼저 preconditionIsolated 로 본다. 이 경우 검사는 한 번이라 호출이 한눈에 보인다. 답이 정직할 때, executor 가 실제 queue 위에서 불리면 통과한다.

1
2
3
4
5
6
7
8
$ ./order honest onQueue precondition
answer=honest where=onQueue api=precondition
withUnsafeCurrentTask: no task
call precondition
  [executor] isIsolatingCurrentContext() onQueue=true -> Optional(true)
returned
end
[exit 0]

checkIsolated() 줄이 없다. true 가 오면 거기서 끝난다. 다른 queue 에서 부르면 false 가 오고, 런타임이 직접 멈춘다.

1
2
3
4
5
6
7
$ ./order honest offQueue precondition
answer=honest where=offQueue api=precondition
withUnsafeCurrentTask: no task
call precondition
  [executor] isIsolatingCurrentContext() onQueue=false -> Optional(false)
order/Order.swift:61: Precondition failed: Incorrect actor executor assumption; Expected 'UnownedSerialExecutor(executor: (Opaque Value))' executor. precondition message
[exit 133]

이번에도 checkIsolated() 는 불리지 않았다. crash 메시지의 order/Order.swift:61 은 preconditionIsolated 를 부른 줄이고, 끝에 내가 넘긴 precondition message 가 붙는다. 메시지 틀은 런타임이 만들었다. 이전 방식에서는 이 자리에 executor 자신의 메시지가 나왔다. 답이 nil 일 때를 보면 그 차이가 보인다.

1
2
3
4
5
6
7
8
9
$ ./order nil onQueue precondition
answer=nil where=onQueue api=precondition
withUnsafeCurrentTask: no task
call precondition
  [executor] isIsolatingCurrentContext() onQueue=true -> nil
  [executor] checkIsolated() onQueue=true
returned
end
[exit 0]
1
2
3
4
5
6
7
8
$ ./order nil offQueue precondition
answer=nil where=offQueue api=precondition
withUnsafeCurrentTask: no task
call precondition
  [executor] isIsolatingCurrentContext() onQueue=false -> nil
  [executor] checkIsolated() onQueue=false
order/Order.swift:33: Precondition failed: checkIsolated: not on log-queue
[exit 133]

nil 이면 같은 자리에서 checkIsolated() 가 이어서 불린다. 실패하면 33행, 즉 LogExecutor.checkIsolated 안의 precondition 이 executor 자신의 메시지로 멈춘다. 같은 “다른 queue 에서 부른 실수” 인데, false 로 답하면 런타임의 메시지, nil 로 답하면 executor 의 메시지가 나온다.

task 안에서는 어떤 답이든 executor 를 부르지 않는다.

1
2
3
4
5
6
$ ./order honest inTask precondition
answer=honest where=inTask api=precondition
call precondition
returned
end
[exit 0]

[executor] 줄이 하나도 없다. check 를 부른 자리가 이 actor 의 task 라서 task 의 executor 와 기대한 executor 가 같고, 거기서 끝났다. 앞에서 말한 빠른 길이다.

assertIsolated 도 같은 순서로 불리고, 메시지만 Fatal error 로 나온다.

1
2
3
4
5
6
7
$ ./order honest offQueue assert
answer=honest where=offQueue api=assert
withUnsafeCurrentTask: no task
call assert
  [executor] isIsolatingCurrentContext() onQueue=false -> Optional(false)
order/Order.swift:62: Fatal error: Incorrect actor executor assumption; Expected 'UnownedSerialExecutor(executor: (Opaque Value))' executor. assert message
[exit 133]

assumeIsolated 는 조금 다르다. 맞는 자리에서 한 번만 불리는 것이 아니라 두 번 불린다.

1
2
3
4
5
6
7
8
9
10
$ ./order honest onQueue assume
answer=honest where=onQueue api=assume
withUnsafeCurrentTask: no task
call assume
  [executor] isIsolatingCurrentContext() onQueue=true -> Optional(true)
  [executor] isIsolatingCurrentContext() onQueue=true -> Optional(true)
assumeIsolated body ran, count=1
returned
end
[exit 0]
1
2
3
4
5
6
7
8
9
10
11
12
$ ./order nil onQueue assume
answer=nil where=onQueue api=assume
withUnsafeCurrentTask: no task
call assume
  [executor] isIsolatingCurrentContext() onQueue=true -> nil
  [executor] checkIsolated() onQueue=true
  [executor] isIsolatingCurrentContext() onQueue=true -> nil
  [executor] checkIsolated() onQueue=true
assumeIsolated body ran, count=1
returned
end
[exit 0]

두 번째 묶음이 어디서 오는지 확인했다. lldb 로 런타임의 검사 함수 swift_task_isCurrentExecutorWithFlagsImpl 에 breakpoint 를 걸고 호출한 자리를 읽었다.

1
bash lldb-assume.sh
1
2
3
* frame #0: 0x00000002b846629c libswift_Concurrency.dylib`swift_task_isCurrentExecutorWithFlagsImpl(swift::SerialExecutorRef, swift::swift_task_is_current_executor_flag)
  frame #1: 0x0000000100002d10 order`Actor.assumeIsolated(_:file:line:) + 104
  frame #2: 0x00000001000028e4 order`Logged.check(_:) + 932
1
2
* frame #0: 0x00000002b846629c libswift_Concurrency.dylib`swift_task_isCurrentExecutorWithFlagsImpl(swift::SerialExecutorRef, swift::swift_task_is_current_executor_flag)
  frame #1: 0x0000000100002bdc order`closure #1 in Logged.check(_:) + 92

첫 번째 호출은 Actor.assumeIsolated(_:file:line:) 안에서 나온다. 두 번째는 closure #1 in Logged.check(_:) 안에서 나온다. 두 번째가 assumeIsolated 에 넘긴 내 클로저의 시작 부분이다. hit 마다 stop 줄이 한 번 더 찍히는데 중복이라 뺐고, 두 번째 hit 의 frame #2 이하(reabstraction thunk 등)도 생략했다.

클로저 시작에 검사가 들어 있는 이유는 SE-0423 의 동적 isolation 검사다. Swift 6 모드에서는 actor isolated 클로저의 첫머리에 “지금 이 executor 위가 맞는가” 를 확인하는 코드가 들어간다. SIL 로 뽑아서 확인했다.

sil-check.sh

1
2
3
bash sil-check.sh -swift-version 6
bash sil-check.sh -swift-version 5
bash sil-check.sh -swift-version 6 -Xfrontend -disable-dynamic-actor-isolation
1
2
3
4
5
  %10 = function_ref @swift_task_isCurrentExecutor : $@convention(thin) (Builtin.Executor) -> Bool // user: %11
  %15 = function_ref @swift_task_reportUnexpectedExecutor : $@convention(thin) (Builtin.RawPointer, Builtin.Word, Builtin.Int1, Builtin.Word, Builtin.Executor) -> () // user: %16
[matches: 2]
[matches: 0]
[matches: 0]

Swift 6 에서는 클로저 안에 swift_task_isCurrentExecutor 와 swift_task_reportUnexpectedExecutor 가 있고, -swift-version 5 와 -disable-dynamic-actor-isolation 으로 뽑으면 없다. Swift 5 모드로 빌드해서 돌리면 호출이 한 번씩이다.

1
2
3
4
5
6
7
8
9
$ ./order5 honest onQueue assume
answer=honest where=onQueue api=assume
withUnsafeCurrentTask: no task
call assume
  [executor] isIsolatingCurrentContext() onQueue=true -> Optional(true)
assumeIsolated body ran, count=1
returned
end
[exit 0]
1
2
3
4
5
6
7
8
9
10
$ ./order5 nil onQueue assume
answer=nil where=onQueue api=assume
withUnsafeCurrentTask: no task
call assume
  [executor] isIsolatingCurrentContext() onQueue=true -> nil
  [executor] checkIsolated() onQueue=true
assumeIsolated body ran, count=1
returned
end
[exit 0]

즉 호출이 두 번인 것은 이 제안의 동작이 아니라 Swift 6 모드의 클로저 검사가 하나 더 붙었기 때문이다. 이 제안의 몫은 한 묶음 안의 순서(isIsolatingCurrentContext(), 필요하면 checkIsolated())다.

실패하는 경우는 첫 묶음에서 끝난다.

1
2
3
4
5
6
7
$ ./order honest offQueue assume
answer=honest where=offQueue api=assume
withUnsafeCurrentTask: no task
call assume
  [executor] isIsolatingCurrentContext() onQueue=false -> Optional(false)
order/Order.swift:64: Fatal error: Incorrect actor executor assumption; Expected same executor as order.Logged.
[exit 133]
1
2
3
4
5
6
7
8
$ ./order nil offQueue assume
answer=nil where=offQueue api=assume
withUnsafeCurrentTask: no task
call assume
  [executor] isIsolatingCurrentContext() onQueue=false -> nil
  [executor] checkIsolated() onQueue=false
order/Order.swift:33: Precondition failed: checkIsolated: not on log-queue
[exit 133]

마지막으로, 런타임이 답을 그대로 믿는다는 것도 확인했다. 다른 queue 인데 executor 가 true 라고 답하게 하면 assumeIsolated 본문이 돈다.

1
2
3
4
5
6
7
8
9
10
$ ./order true offQueue assume
answer=true where=offQueue api=assume
withUnsafeCurrentTask: no task
call assume
  [executor] isIsolatingCurrentContext() onQueue=false -> Optional(true)
  [executor] isIsolatingCurrentContext() onQueue=false -> Optional(true)
assumeIsolated body ran, count=1
returned
end
[exit 0]

onQueue=false 인데 본문이 돌았다. 답이 틀리면 런타임이 막아 주지 않는다. isIsolatingCurrentContext() 를 구현하는 쪽이 책임을 진다는 뜻이다.


하나만 구현한 executor

기존 executor 는 checkIsolated() 만 구현하고, 새 executor 는 isIsolatingCurrentContext() 만 구현하거나 둘 다 구현하지 않을 수도 있다. 네 가지를 task 없이 executor 의 queue 위(실제로 격리된 자리)에서 preconditionIsolated 로 시험했다.

Fallback.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
30
31
32
33
34
class QueueExecutor: @unchecked Sendable {
  let queue = DispatchSerialQueue(label: "q")
  let key = DispatchSpecificKey<Bool>()
  init() { queue.setSpecific(key: key, value: true) }
  var onQueue: Bool { DispatchQueue.getSpecific(key: key) == true }
}

final class CheckOnly: QueueExecutor, SerialExecutor, @unchecked Sendable {
  func enqueue(_ job: consuming ExecutorJob) {}
  func checkIsolated() {
    print("  [CheckOnly] checkIsolated() onQueue=\(onQueue)")
    precondition(onQueue)
  }
}

final class IsOnly: QueueExecutor, SerialExecutor, @unchecked Sendable {
  func enqueue(_ job: consuming ExecutorJob) {}
  func isIsolatingCurrentContext() -> Bool? {
    print("  [IsOnly] isIsolatingCurrentContext() -> \(onQueue)")
    return onQueue
  }
}

final class IsOnlyNil: QueueExecutor, SerialExecutor, @unchecked Sendable {
  func enqueue(_ job: consuming ExecutorJob) {}
  func isIsolatingCurrentContext() -> Bool? {
    print("  [IsOnlyNil] isIsolatingCurrentContext() -> nil")
    return nil
  }
}

final class Neither: QueueExecutor, SerialExecutor, @unchecked Sendable {
  func enqueue(_ job: consuming ExecutorJob) {}
}

나머지 부분(actor A 와 main)은 kind 인자로 위 네 클래스 중 하나를 골라 ex.queue.async 안에서 a.preconditionIsolated() 를 부르고, 통과하면 passed 를 찍는다. 첫 줄에는 Neither().isIsolatingCurrentContext() 의 값을 찍어서 기본 구현의 답을 확인한다.

1
2
3
4
5
6
$ ./fallback checkOnly
kind=checkOnly
default isIsolatingCurrentContext() on this executor: nil
  [CheckOnly] checkIsolated() onQueue=true
passed
[exit 0]
1
2
3
4
5
6
$ ./fallback isOnly
kind=isOnly
default isIsolatingCurrentContext() on this executor: nil
  [IsOnly] isIsolatingCurrentContext() -> true
passed
[exit 0]

checkIsolated() 만 구현한 executor 는 이전처럼 돌고, isIsolatingCurrentContext() 만 구현한 executor 는 checkIsolated() 없이 통과한다. 두 메서드 중 하나만 있으면 된다.

nil 만 돌려주거나 아무것도 구현하지 않으면 기본 경로로 내려가서 멈춘다.

1
2
3
4
5
6
$ ./fallback isOnlyNil
kind=isOnlyNil
default isIsolatingCurrentContext() on this executor: nil
  [IsOnlyNil] isIsolatingCurrentContext() -> nil
_Concurrency/Executor.swift:393: Fatal error: Unexpected isolation context, expected to be executing on IsOnlyNil
[exit 133]
1
2
3
4
5
$ ./fallback neither
kind=neither
default isIsolatingCurrentContext() on this executor: nil
_Concurrency/Executor.swift:393: Fatal error: Unexpected isolation context, expected to be executing on Neither
[exit 133]

두 경우 메시지가 같다. checkIsolated() 의 기본 구현이 부른 Executor.swift:393 의 crash 다. 실제로 격리된 자리에서 부른 것인데도 executor 가 아무 답도 못 하니 멈춘다.


crash 하면 안 되는 검사

checkIsolated() 는 crash 하는 메서드라서, 런타임이 “틀려도 crash 하면 안 되는” 검사에서는 부를 수 없다. 그런 검사에서 nil 은 어떻게 처리되는지 보려고 두 곳을 시험했다. 하나는 Task.immediate(SE-0472)이고, 하나는 isolated conformance 의 as? 캐스트(SE-0470)다.

NoCrash.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
30
31
32
33
34
35
36
final class LogExecutor: SerialExecutor, @unchecked Sendable {
  let queue = DispatchSerialQueue(label: "g-queue")
  let key = DispatchSpecificKey<Bool>()
  nonisolated(unsafe) static var answer = "honest"
  init() { queue.setSpecific(key: key, value: true) }

  func enqueue(_ job: consuming ExecutorJob) {
    let job = UnownedJob(job)
    let me = asUnownedSerialExecutor()
    queue.async { job.runSynchronously(on: me) }
  }
  var onQueue: Bool { DispatchQueue.getSpecific(key: key) == true }

  func checkIsolated() {
    print("  [executor] checkIsolated() onQueue=\(onQueue)")
    precondition(onQueue, "checkIsolated: not on g-queue")
  }
  func isIsolatingCurrentContext() -> Bool? {
    let r: Bool? = LogExecutor.answer == "nil" ? nil : onQueue
    print("  [executor] isIsolatingCurrentContext() onQueue=\(onQueue) -> \(String(describing: r))")
    return r
  }
}

@globalActor
actor G {
  static let shared = G()
  static let executor = LogExecutor()
  nonisolated var unownedExecutor: UnownedSerialExecutor { G.executor.asUnownedSerialExecutor() }
}

protocol P { func hello() -> String }
struct S {}
extension S: @G P {
  func hello() -> String { "hello from S" }
}

main 은 g-queue 위(onQueue)나 다른 queue 위(offQueue)에서 아래 두 가지를 차례로 한다.

NoCrash.swift

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
    queue.async {
      print("1. Task.immediate")
      Task.immediate { @G in
        print("   Task.immediate body")
        done.signal()
      }
      print("   after Task.immediate")
      print("2. as? any P")
      let value: Any = S()
      if let p = value as? any P {
        print("   cast succeeded: \(p.hello())")
      } else {
        print("   cast failed (nil)")
      }
      done.signal()
    }

Task.immediate 는 지금 자리가 이미 그 actor 의 isolation 안이면 본문을 그 자리에서 바로 돌리고, 아니면 일반 task 처럼 executor 에 넘긴다. 어느 쪽인지는 isIsolatingCurrentContext() 로 정한다. 답이 정직할 때 결과는 다음과 같다.

1
2
3
4
5
6
7
8
9
10
11
$ ./nocrash honest onQueue
answer=honest where=onQueue
1. Task.immediate
  [executor] isIsolatingCurrentContext() onQueue=true -> Optional(true)
   Task.immediate body
   after Task.immediate
2. as? any P
  [executor] isIsolatingCurrentContext() onQueue=true -> Optional(true)
   cast succeeded: hello from S
end
[exit 0]

본문(Task.immediate body)이 after Task.immediate 보다 먼저 찍혔다. 동기로 바로 돈 것이다. as? 도 성공한다. 다른 queue 에서는 false 가 오고, 둘 다 crash 하지 않고 “아니다” 로 끝난다.

1
2
3
4
5
6
7
8
9
10
11
$ ./nocrash honest offQueue
answer=honest where=offQueue
1. Task.immediate
  [executor] isIsolatingCurrentContext() onQueue=false -> Optional(false)
   after Task.immediate
2. as? any P
  [executor] isIsolatingCurrentContext() onQueue=false -> Optional(false)
   cast failed (nil)
   Task.immediate body
end
[exit 0]

after Task.immediate 가 먼저 찍혔으니 본문은 executor 에 넘어갔고, as? 는 nil 을 돌려줬다. exit 는 0 이다.

이제 executor 가 nil 을 답하게 하고, 실제로 g-queue 위에서 부른다.

1
2
3
4
5
6
7
8
9
10
11
$ ./nocrash nil onQueue
answer=nil where=onQueue
1. Task.immediate
  [executor] isIsolatingCurrentContext() onQueue=true -> nil
   after Task.immediate
2. as? any P
  [executor] isIsolatingCurrentContext() onQueue=true -> nil
   cast failed (nil)
   Task.immediate body
end
[exit 0]

실제로는 그 queue 위인데도, nil 이 오면 checkIsolated() 를 부르지 않고 “아니다” 로 처리했다. Task.immediate 는 넘겼고 as? 는 실패했다. 이 두 검사에서 nil 은 “아니다” 와 같다.

경합이 있는 줄이 하나 있다. Task.immediate body 가 넘겨진 뒤에는 g-queue 위에서 따로 돌기 때문에, 이 줄의 위치는 실행마다 바뀔 수 있다. onQueue 두 경우는 20번 돌려도 출력이 한 가지였지만, offQueue 는 100번씩 여러 번 돌려서 이 줄이 찍힌 위치를 셌다.

runs.sh

1
2
bash runs.sh honest
bash runs.sh nil

여러 번 나눠 돌린 범위는 이렇다. 정직한 답에서는 cast failed (nil) 뒤가 100번 중 86~95번이었고, 2. as? any P 뒤가 4~14번이었으며, 그 사이(두 번째 [executor] 줄과 cast failed (nil) 줄 사이)는 0~1번이었다. nil 답에서는 cast failed (nil) 뒤가 46~96번, 2. as? any P 뒤가 4~48번이었고 나머지 위치는 0~6번이었다. 정직한 답에서 after Task.immediate 줄 앞에 찍힌 경우는 500번 중 0번이었다. 위에 붙인 honest offQueue 출력은 가장 흔한 쪽이다. 어느 쪽이든 Task.immediate 와 as? 는 crash 하지 않고 “아니다” 로 끝난다.

세 번째 검사는 SE-0371 의 isolated deinit 이다. 마지막 reference 가 풀릴 때, deinit 을 지금 자리에서 바로 돌릴지 actor 의 executor 로 넘길지 정하려고 런타임이 executor 를 묻는다. 피치에서 이 제안의 동기로 인용된 것도 이 자리다.

Deinit.swift

1
2
3
4
5
6
7
8
9
10
actor Resource {
  nonisolated let executor: LogExecutor
  nonisolated var unownedExecutor: UnownedSerialExecutor { executor.asUnownedSerialExecutor() }
  let done: DispatchSemaphore
  init(_ e: LogExecutor, _ done: DispatchSemaphore) { executor = e; self.done = done }
  isolated deinit {
    print("   isolated deinit runs")
    done.signal()
  }
}

LogExecutor 는 Order.swift 와 같은 모양에 answer 만 honest 나 nil 로 받는다. main 은 queue 위에서 Resource 를 만들고 마지막 reference 를 놓은 뒤 after release 를 찍는다.

1
2
3
4
5
6
7
8
9
$ ./deinit honest onQueue
answer=honest where=onQueue
   release last reference
  [executor] isIsolatingCurrentContext() onQueue=true -> Optional(true)
  [executor] isIsolatingCurrentContext() onQueue=true -> Optional(true)
   isolated deinit runs
   after release
end
[exit 0]
1
2
3
4
5
6
7
8
$ ./deinit honest offQueue
answer=honest where=offQueue
   release last reference
  [executor] isIsolatingCurrentContext() onQueue=false -> Optional(false)
   after release
   isolated deinit runs
end
[exit 0]
1
2
3
4
5
6
7
8
$ ./deinit nil onQueue
answer=nil where=onQueue
   release last reference
  [executor] isIsolatingCurrentContext() onQueue=true -> nil
   after release
   isolated deinit runs
end
[exit 0]

위 세 출력을 보면 정직한 답이 true 일 때 deinit 이 after release 보다 먼저 바로 돌고, false 이거나 nil 이면 after release 뒤에 돈다. nil 도 checkIsolated() 를 부르지 않고 “아니다” 처럼 처리된다. true 일 때 호출이 두 번인 이유도 확인했다. lldb 로 보면 하나는 Resource.__deallocating_deinit 이 부르는 swift_task_deinitOnExecutor 에서, 다른 하나는 Resource.deinit 의 SIL 첫머리에 들어 있는 swift_task_isCurrentExecutor 에서 나온다. honest onQueue, honest offQueue, nil onQueue 세 경우 모두 20번씩 돌려서 출력이 같았다.

정리하면 이 그림이 된다.

런타임이 isIsolatingCurrentContext 를 먼저 묻고 true 나 false 면 거기서 끝내며, nil 이면 crash 해도 되는 검사만 checkIsolated 로 내려가고 crash 하면 안 되는 검사는 아니라고 처리한다는 흐름도

맨 위가 task 의 executor 비교(빠른 길)이고, 그 아래가 isIsolatingCurrentContext() 다. true 와 false 는 checkIsolated() 를 거치지 않는다. nil 만 갈라진다.

답preconditionIsolated, assumeIsolatedTask.immediateas?isolated deinit
true통과그 자리에서 바로성공그 자리에서 바로
falsecrashexecutor 로 넘김nilexecutor 로 넘김
nilcheckIsolated() 로 내려감executor 로 넘김nilexecutor 로 넘김

Actor 에서 executor 꺼내 warning 만 내기

isIsolatingCurrentContext() 를 쓰는 쪽은 런타임만이 아니다. 라이브러리도 부를 수 있어야 “틀렸을 때 warning 만 내자” 가 된다. 그런데 손에 있는 것이 executor 가 아니라 any Actor 일 수 있다. @isolated(any) 클로저의 .isolation 이 그런 경우다. 그래서 제안은 Actor 에서 executor 를 꺼내는 withSerialExecutor 를 더한다. 6.4 interface 에서 보이는 모양은 이렇다.

1
2
3
4
5
6
extension _Concurrency::Actor {
  @available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
  @_alwaysEmitIntoClient nonisolated public func withSerialExecutor<T, E>(_ operation: (any _Concurrency::SerialExecutor) throws(E) -> T) throws(E) -> T where E : Swift::Error, T : ~Copyable {
    try operation(unsafeBitCast(self.unownedExecutor, to: (any SerialExecutor).self))
  }
}

본문은 unownedExecutor 를 any SerialExecutor 로 바꿔서 클로저에 넘긴다. @_alwaysEmitIntoClient 라서 이 함수는 호출하는 쪽 모듈에 복사되어 들어가고, 그 덕에 런타임 버전과 무관하게 쓸 수 있다(제안서도 back-deploy 된다고 적었다). 같은 이름의 async 판도 있고, 그쪽 클로저에는 nonisolated(nonsending) 이 붙어 있다(SE-0461).

제안서의 예제는 이 함수로 “틀리면 warning” 을 내는 모양이다. 6.4 에서 되는 모양으로 고쳐서 돌렸다. 고친 곳은 isolation 이 옵셔널이라 guard let 으로 벗기는 것, 그리고 답이 Bool? 이라 switch 로 세 갈래를 다 다루는 것이다.

WarnMode.swift

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
func warn(_ message: String) { print("warning:", message) }

func something(operation: @escaping @isolated(any) () -> ()) {
  guard let isolation = operation.isolation else {
    print("  isolation: nil (nonisolated closure), skip check")
    return
  }
  isolation.withSerialExecutor { se in
    let answer = se.isIsolatingCurrentContext()
    print("  executor type: \(type(of: se)), isIsolatingCurrentContext() -> \(String(describing: answer))")
    switch answer {
    case false?:
      warn("'something' must be called from the same isolation as the operation closure is isolated to!")
    case true?:
      print("  ok")
    case nil:
      print("  unknown: executor cannot tell")
    }
  }
}

something 에 @Custom 클로저를 넘기는데, Custom 은 앞에서와 같은 모양의 custom executor 를 쓰는 global actor 다. 그 executor 는 isIsolatingCurrentContext() 를 DispatchQueue.getSpecific(key: key) == true 로 구현했다. 호출 자리만 바꿔서 돌렸다.

1
2
3
4
5
6
$ ./warnmode customOn
case=customOn
  executor type: QueueExecutor, isIsolatingCurrentContext() -> Optional(true)
  ok
end
[exit 0]
1
2
3
4
5
6
$ ./warnmode customOff
case=customOff
  executor type: QueueExecutor, isIsolatingCurrentContext() -> Optional(false)
warning: 'something' must be called from the same isolation as the operation closure is isolated to!
end
[exit 0]

다른 queue 에서 불러도 crash 하지 않고 warning 한 줄로 끝났다. 이 제안의 목적이 이것이다. @MainActor 클로저는 다르다.

1
2
3
4
5
6
$ ./warnmode mainOn
case=mainOn
  executor type: DispatchMainExecutor, isIsolatingCurrentContext() -> nil
  unknown: executor cannot tell
end
[exit 0]
1
2
3
4
5
6
$ ./warnmode mainOff
case=mainOff
  executor type: DispatchMainExecutor, isIsolatingCurrentContext() -> nil
  unknown: executor cannot tell
end
[exit 0]

DispatchMainExecutor 는 main thread 위에서 불러도 nil 이다. 이 자리에서 nil 을 false 처럼 다뤘다면 main actor 위에서 불러도 warning 이 났을 것이다. nil 을 따로 다뤄야 하는 자리를 이 출력이 보여 준다. nonisolated 클로저는 isolation 이 nil 이라서 something 이 검사를 건너뛴다.

1
2
3
4
5
$ ./warnmode nilIsolation
case=nilIsolation
  isolation: nil (nonisolated closure), skip check
end
[exit 0]

DispatchSerialQueue 를 executor 로 바로 쓰는 actor 는 true 와 false 를 답한다. 피치에서 ktoso 가 말한 Swift 전용 SPI 구현이 6.4 에서 이렇게 나타난다.

DispatchQ.swift

1
2
3
4
actor OnQueue {
  nonisolated let queue = DispatchSerialQueue(label: "actor-queue")
  nonisolated var unownedExecutor: UnownedSerialExecutor { queue.asUnownedSerialExecutor() }
}
1
2
3
4
5
$ ./dq
on queue:  Optional(true)
via withSerialExecutor: OS_dispatch_queue_serial Optional(true)
off queue: Optional(false)
main thread: Optional(false)

withSerialExecutor 로 받은 executor 의 타입은 OS_dispatch_queue_serial 이고, queue 위에서는 true, 다른 queue 와 main thread 에서는 false 다.

주의할 점이 하나 있다. custom executor 가 없는 기본 actor 에 withSerialExecutor 를 부르고 그 안에서 isIsolatingCurrentContext() 를 부르면 프로세스가 죽었다.

1
2
3
actor Plain {
  static let shared = Plain()
}
1
2
3
4
5
6
7
      other.async {
        Plain.shared.withSerialExecutor { se in
          print("  executor type: \(type(of: se))")
          print("  isIsolatingCurrentContext() -> \(String(describing: se.isIsolatingCurrentContext()))")
        }
        done.signal()
      }
1
2
3
4
$ ./warnmode defaultActor
case=defaultActor
  executor type: Plain
[exit 139]

executor 타입으로 Plain, 즉 actor 자신이 찍혔다. 리뷰에서 ktoso 가 말한 대로 기본 actor 에서는 executor 의 정체가 actor 자신이기 때문이다. lldb 로 보면 EXC_BAD_ACCESS (code=1, address=0x40) 이고, 0번 frame 이 dispatch thunk of SerialExecutor.isIsolatingCurrentContext() + 4 다. 그래서 withSerialExecutor 는 custom executor 를 쓰는 actor 나 @isolated(any) 클로저의 .isolation 처럼 executor 가 분명한 자리에서 쓰고, 기본 actor 에는 쓰지 않는 쪽이 안전하다.

마지막으로 수락 공지가 말한 Actor.executor 프로퍼티가 6.4 에 있는지 확인했다.

ExecutorProp.swift

1
2
3
4
5
6
7
8
9
import Distributed
actor A {}
func f(_ a: A) {
  let e: any SerialExecutor = a.executor
  _ = e
}
func g(_ d: some DistributedActor) {
  d.withSerialExecutor { _ in }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
ExecutorProp.swift:5:33: error: value of type 'A' has no member 'executor'
 3 | actor A {}
 4 | func f(_ a: A) {
 5 |   let e: any SerialExecutor = a.executor
   |                                 `- error: value of type 'A' has no member 'executor'
 6 |   _ = e
 7 | }

ExecutorProp.swift:9:5: error: value of type 'some DistributedActor' has no member 'withSerialExecutor'
 8 | func g(_ d: some DistributedActor) {
 9 |   d.withSerialExecutor { _ in }
   |     `- error: value of type 'some DistributedActor' has no member 'withSerialExecutor'
10 | }
11 |
[exit 1]

6.4 의 Actor 에는 executor 프로퍼티가 없고, DistributedActor 에는 withSerialExecutor 가 없다. 6.4 에서 actor 에서 executor 를 꺼내는 길은 Actor.withSerialExecutor 하나다.


스레드에서 오간 이야기

이 제안의 스레드는 피치, 리뷰, 수락 공지 셋이고 2025년 3월부터 5월까지 이어졌다. 시간순으로 따라간다. 인용 표기는 (스레드 #번호, 글쓴이) 로 적는다.


피치

2025년 3월 3일, ktoso 가 func isIsolatingCurrentContext() -> Bool 요구사항으로 피치를 열었다. 목적은 두 가지였다. 실패 메시지에 “지금 어느 executor 위였는가” 를 넣는 것과, 라이브러리가 strict 모드를 켜기 전에 warning 만 내는 것이다(피치 #1, ktoso).

같은 날 ktoso 가 SE-0424 스레드에서 Nickolas_Pohilets 가 한 말을 끌어왔다. isolated deinit 의 구현이 swift_task_isCurrentExecutor() 로 “바로 돌릴지, 넘길지” 를 고르니 Bool 을 돌려주는 API 가 필요하다는 말이다(피치 #2, ktoso). 이 제안이 deinit 의 빠른 길과 연결되는 지점이고, 위의 Deinit 측정이 그 자리다.

그 바로 뒤에 Nickolas_Pohilets 가 질문했다. SE-0424 가 “모든 구현이 확실한 예, 아니오를 답할 수는 없다” 고 했으니 반환형이 Optional<Bool> 이어야 하지 않느냐는 것이다(피치 #3, Nickolas_Pohilets). ktoso 는 세 상태에 이름을 붙이는 안을 말하면서, 런타임이 Swift 쪽을 더 많이 부르게 되는 비용을 걱정했다(피치 #4, ktoso).

3월 18일에는 방향을 바꿨다. 요구사항의 반환형은 Bool 로 두고, 컴파일러와 런타임이 “기본 구현이 아닌 구현이 있는가” 를 감지해서 있을 때만 새 메서드를 부르는 방식이다. 이렇게 하면 checkIsolated 를 서서히 대체할 수 있고, 다른 런타임 기능이 crash 걱정 없이 검사를 부르는 “warning 모드” 에도 맞는다고 했다(피치 #5, ktoso).

3월 22일에는 dispatch queue 도 이 API 를 구현할 수 있느냐는 질문이 나왔다. Nickolas_Pohilets 는 SE-0424 가 그런 모양이 된 이유가 dispatch queue 에 Bool 을 돌려주는 공개 API 가 없어서였다고 이해한다며, 그 사정이 바뀌었는지 물었다(피치 #6, Nickolas_Pohilets). 답은 “DispatchSerialQueue 는 Swift 만 쓸 수 있는 SPI 로 구현한다” 였다(피치 #7, ktoso). 위 DispatchQ 측정이 이 구현의 결과다.


리뷰

리뷰에서 먼저 나온 질문은 “available” 이 무슨 뜻이냐는 것이었다. 기본 구현이 checkIsolated() 를 부르게 하면 되지 않느냐는 제안도 함께 나왔다(리뷰 #3, CrystDragon). ktoso 는 “available” 이 개발자가 기본 구현이 아닌 구현을 제공했다는 뜻이고 컴파일러가 이를 감지한다고 답했다. 기본 구현이 checkIsolated() 를 부르는 방식은 warning 만 내려던 자리에서 crash 를 일으켜서 쓸 수 없다고 했다(리뷰 #4, ktoso). 이 대목이 앞에서 본 두 번째 한계, 즉 warning 을 낼 수 없다는 문제와 이어진다.

4월 2일 Doug Gregor 가 이 “감지” 방식에 우려 셋을 적었다. 런타임만 “모름” 을 구분할 수 있고 사용자는 못 한다는 것, 컴파일러와 런타임에 감지용 복잡도가 더해진다는 것, “모름” 이 정말 일시적인가 하는 것이다. 그는 이 API 가 초보자용이 아니고 대부분은 assumeIsolated 같은 상위 API 를 쓸 것이라는 점을 짚었다. 그래서 사용자가 “모름” 을 직접 다루는 번거로움보다, 1, 2년 뒤에 같은 API 를 세 번째로 일반화하게 되는 쪽을 더 걱정한다고 했다(리뷰 #5, Douglas_Gregor).

4월 8일 ktoso 가 답했다. 처음에 Bool 을 고른 것은 “모름” 을 의미 있게 다룰 길이 안 보였고 보통 “아니다” 로 가정해야 한다고 생각해서였다. 하지만 “확실히 틀렸을 때만 warning 을 내는” warning 모드에서는 쓸모가 있을 수 있고, 실패하는 길에서 호출이 두 번 되는 비용은 괜찮으니 세 상태로 가도 된다는 것이다. 대부분의 executor 가 새 API 를 구현하면 호출이 한 번으로 돌아온다고도 했다(리뷰 #6, ktoso).

4월 24일에 ktoso 가 두 가지 바뀐 점을 올렸다. 반환형을 Bool? 로 바꾸는 것, 그리고 any Actor 만 있을 때 이 API 를 부를 수 있게 Actor/withSerialExecutor 를 더하는 것이다. 이렇게 하면 컴파일러의 특수 처리가 줄고 사용자 코드에서도 쓰기 쉬워진다고 했다(리뷰 #7, ktoso). 같은 날 j-f1 이 noncopyable 값을 돌려줄 수 있게 T: ~Copyable 로 하자고 했고(리뷰 #8, j-f1), Doug 가 리뷰를 4월 29일까지 연장했다(리뷰 #9, Douglas_Gregor). 다음 날 4월 25일 ktoso 가 T: ~Copyable 과 typed throws 를 함께 받아들였다(리뷰 #10, ktoso). 6.4 interface 의 시그니처에 둘 다 들어 있다.

4월 29일 John_McCall 이 with 모양이 필요 없다고 했다. unownedExecutor 문서에 있는 “holding on to the actor must keep the executor alive” 문장은 executor 를 actor 가 살아 있는 동안만 쓰라는 뜻이 아니라, actor 가 executor 를 빌려 주는 결과라는 뜻이니 평범한 getter 면 된다는 것이다(리뷰 #11, John_McCall). ktoso 가 with 를 빼는 데 동의했고(리뷰 #12, ktoso), 반환형으로 연관 타입을 써서 구체 타입을 돌려줄지를 두고 Doug, John_McCall, ktoso 가 주고받다가 any SerialExecutor 로 정리했다(리뷰 #13부터 #17).

5월 1일 ktoso 가 제안을 Actor.executor 와 DistributedActor.executor 프로퍼티로 고친다고 했다. 변환은 단순한 cast 가 아니라서 구현이 까다롭다는 말이 붙었다(리뷰 #18, ktoso). 그 뒤에 “기본 actor 의 executor 는 무엇이냐” 는 이야기가 이어졌다. 기본 actor 에서는 executor 의 정체가 actor 자신이고 custom executor 가 있으면 그 객체라는 설명(리뷰 #20, ktoso), a as! SerialExecutor 는 되지 않는다는 설명(리뷰 #22, ktoso), 그렇다면 진짜 SerialExecutor 를 구현하는 proxy 객체를 돌려주자는 제안(리뷰 #23, Nickolas_Pohilets)이 나왔다. 5월 6일 John_McCall 은 매번 새 proxy 를 만드는 것은 unownedExecutor 의 규칙 위반이라서, proxy 를 쓰려면 actor 가 캐시해서 강하게 들고 있어야 한다고 답했다. 그는 executor 가 unownedExecutor 를 더 자연스러운 타입으로 쓰는 방법일 뿐이고 모델을 바꾸는 것이 아니라고 했다(리뷰 #24, John_McCall). 위 default actor 측정에서 executor 타입이 Plain 으로 찍히고 isIsolatingCurrentContext() 를 부르면 죽은 것은 이 대화에서 나온 우려가 실제로 나타난 모양이다.

5월 7일에는 Karl 이 @ActorExecutor 매크로 아이디어를 올렸다(리뷰 #28, Karl).


수락 공지

5월 14일 Doug Gregor 가 수락을 알렸다. 리뷰는 4월 29일에 끝났고, 연장 기간에 바뀐 것은 둘이다. isIsolatingCurrentContext 가 Bool? 을 돌려주게 되었다는 것, 그리고 Actor.executor 프로퍼티가 더해졌다는 것이다. Language Steering Group 이 이 변경을 포함해서 수락했다(수락 #1, Douglas_Gregor). 앞에서 본 것처럼 6.4 에서 Bool? 은 그대로이고, actor 에서 executor 를 꺼내는 길은 Actor.withSerialExecutor 다.


기대 효과

  • 라이브러리가 crash 대신 warning 으로 시작할 수 있다. customOff 에서 보았듯 틀린 자리에서 불려도 warning 한 줄로 끝나고, 몇 버전 뒤에 crash 로 올리면 된다
  • 제안서는 isIsolatingCurrentContext() 가 false 를 답하는 경로에서 런타임이 현재 executor 정보를 담은 더 자세한 메시지를 만들 수 있다고 기대했다. 6.4 의 이 경로 메시지는 Incorrect actor executor assumption; Expected 'UnownedSerialExecutor(executor: (Opaque Value))' executor. 에 호출 때 넘긴 문구가 붙는 모양이고, 위 측정에서 현재 executor 정보는 나오지 않았다
  • executor 가 쉽게 구현된다. DispatchSpecificKey 하나로 true, false 를 답하는 executor 는 checkIsolated() 의 dispatchPrecondition 을 쓰지 않아도 된다
  • Task.immediate, isolated conformance 의 as?, isolated deinit 처럼 crash 하면 안 되는 검사가 같은 질문을 쓴다. executor 가 true, false 로 답하면 이 검사들이 그 답대로 갈라지고, 모르면 안전한 쪽(아니다)으로 간다

다른 선택지는 왜 안 됐나

제안서의 Alternatives 에는 셋이 있다.

  • checkIsolated 가 Bool 을 돌려주게 바꾸기: 이상적이지만 프로토콜 요구사항의 시그니처를 바꾸는 것은 ABI 를 깨서 안 된다. 그래서 새 요구사항을 따로 더했다
  • checkIsolated 를 deprecate 하기: 여러 Swift 버전을 지원하는 라이브러리가 deprecation warning 을 받지 않도록 deprecate 하지 않는다. 나중에 할 수도 있지만 지금은 계획이 없다고 적었다
  • Actor 와 executor 사이의 수명 관계를 ~Escapable 로 표현하기: any SerialExecutor 는 AnyObject 제약이 붙은 타입이라 ~Escapable 과 합칠 수 없다. 그래서 scope 를 가진 with 모양을 택했다. 나중에 non-escapable executor 가 가능해지면 다시 볼 수 있다고 했다

Future directions 에는 Actor 에 isIsolated 같은 공개 API 를 더하지 않는다는 결정이 있다. 오용될 우려 때문이고, 쓸 곳이 많다고 판단되면 다시 보겠다고 했다. 리뷰 중에는 Bool 대신 enum 으로 세 상태를 모델링하자는 안(isolated, notIsolated, unknown)도 있었는데, 리뷰 #6 에서 ktoso 가 “세 상태로 가도 된다” 고 한 뒤 최종 모양은 Bool? 이 되었다.


Swift 6 모드와 마이그레이션

제안서는 source 호환이고 ABI 는 additive(더해지기만 함)라고 적었다. 기본 구현이 함께 들어와서 기존 SerialExecutor 는 고치지 않아도 컴파일된다. availability 는 6.4 에서 이렇게 잡힌다. isIsolatingCurrentContext() 는 anyAppleOS 26.0(macOS 26.0) 이고, withSerialExecutor 는 10.15 부터다. 배포 대상을 macOS 14 나 15 로 두고 any SerialExecutor 로 부르면 진단이 난다.

Avail.swift

1
2
3
4
5
6
7
8
9
10
11
12
13
14
final class E: SerialExecutor, @unchecked Sendable {
  func enqueue(_ job: consuming ExecutorJob) {}
  func checkIsolated() {}
  func isIsolatingCurrentContext() -> Bool? { true }
}

actor A {}

func call(_ e: E, _ a: A) {
  _ = e.isIsolatingCurrentContext()
  a.withSerialExecutor { se in
    _ = se.isIsolatingCurrentContext()
  }
}
1
xcrun swiftc -emit-sil -o /dev/null -parse-as-library -wmo -swift-version 6 -target arm64-apple-macos14 Avail.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
Avail.swift:13:12: error: 'isIsolatingCurrentContext()' is only available in macOS 26.0 or newer
 8 | actor A {}
 9 |
10 | func call(_ e: E, _ a: A) {
   |      `- note: add '@available' attribute to enclosing global function
11 |   _ = e.isIsolatingCurrentContext()
12 |   a.withSerialExecutor { se in
13 |     _ = se.isIsolatingCurrentContext()
   |            |- error: 'isIsolatingCurrentContext()' is only available in macOS 26.0 or newer
   |            `- note: add 'if #available' version check
14 |   }
15 | }
[exit 1]

진단은 13행 하나뿐이다. any SerialExecutor 로 부른 줄만 걸리고, 구체 타입 E 에 부른 11행과 withSerialExecutor 호출, 그리고 @available 없이 isIsolatingCurrentContext() 를 구현한 선언은 진단이 없다. -target arm64-apple-macos26 으로 빌드하면 진단이 하나도 없다.

executor 를 구현하는 쪽의 마이그레이션은 이렇다.

  • 새 Swift 와 새 런타임만 대상으로 하면 isIsolatingCurrentContext() 를 구현하고, 답을 알 수 없는 경우에만 nil 을 돌려준다
  • 예전 런타임까지 지원해야 하면 checkIsolated() 를 그대로 두고 isIsolatingCurrentContext() 를 같이 구현한다. 제안서는 새 런타임에서만 효과가 나타난다고 적었다. -target arm64-apple-macos14 로 빌드한 Order.swift 는 이 기계의 런타임에서 같은 출력을 냈고, 다른 queue 에서 false 를 답하면 order14/Order.swift:61: Precondition failed: ... 로 멈췄다
  • 답이 틀리면 런타임이 믿고 따른다. Order.swift 의 true offQueue 에서 본 대로, 확실하지 않으면 true 를 돌려주지 말고 nil 을 돌려준다

언어 모드는 이 API 의 사용 여부에 영향을 주지 않는다. Swift 5 와 Swift 6 모드 모두 같은 요구사항을 구현하고 부른다. 앞에서 본 호출 횟수 차이는 Swift 6 모드에서만 들어가는 SE-0423 의 클로저 검사 때문이다.

호출하는 쪽에서는 @isolated(any) 클로저의 .isolation 에서 withSerialExecutor 로 꺼내 Bool? 의 세 갈래(false?, true?, nil)를 모두 다루는 것이 안전하다.


정리

구분내용
새 요구사항SerialExecutor.isIsolatingCurrentContext() -> Bool? (26.0), 기본 구현은 nil
세 가지 답true 는 통과, false 는 실패, nil 은 모름
호출 순서task 의 executor 비교, isIsolatingCurrentContext(), nil 일 때만 checkIsolated()
호출 횟수true, false 면 checkIsolated() 를 부르지 않는다. Swift 6 의 assumeIsolated 는 SE-0423 의 클로저 검사 때문에 두 묶음이다
crash 하면 안 되는 검사Task.immediate, isolated conformance 의 as?, isolated deinit 은 nil 을 “아니다” 로 처리한다
한쪽만 구현둘 중 하나만 구현해도 된다. nil 만 돌려주거나 둘 다 없으면 기본 checkIsolated() 로 가서 crash 한다
Actor 에서 꺼내기Actor.withSerialExecutor (10.15 부터, back-deploy). 6.4 에는 Actor.executor 프로퍼티가 없다
주의기본 actor 에 withSerialExecutor 를 부르고 그 안에서 isIsolatingCurrentContext() 를 부르면 6.4 에서 EXC_BAD_ACCESS
책임런타임은 답을 믿는다. 확실하지 않으면 nil

관련 글


참고자료

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