포스트

[SE-0431] @isolated(any) Function Types

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


제안서 정보

  • 번호: SE-0431
  • 상태: Implemented (Swift 6.0)
  • upcoming feature flag: 없음 (리뷰 때는 experimental feature flag IsolatedAny 로 써 볼 수 있었고, 6.0 에서 정식 기능이 되었다)
  • 저자: John McCall
  • 리뷰 매니저: Doug Gregor
  • pitch: Pitch (2024-03-10)
  • 리뷰: Review (2024-03-27 시작, 04-09 까지였고 철자 논의와 region based isolation 과의 상호작용을 따지느라 연장)
  • 수락: Accepted (2024-05-03, 수정 한 가지를 붙여 수락)
  • 전제 제안서: SE-0412, SE-0414 (region based isolation), SE-0430 (sending), SE-0420 (#isolation)

한 줄 요약

함수 타입에 @isolated(any) 를 붙이면, 그 함수 값이 어느 isolation 에서 돌아야 하는지가 타입 안에 남는다. 값을 받은 쪽은 .isolation 으로 그 isolation 을 (any Actor)? 로 꺼내 볼 수 있고, 부를 때는 await 만 붙이면 컴파일러가 알아서 그 isolation 으로 옮겨 준다. 표준 라이브러리의 Task 와 TaskGroup 생성 함수가 이 타입으로 바뀐 덕분에, 새 task 가 처음부터 올바른 actor 의 줄에 선다.


어떤 문제였나

actor 와 global actor 에 묶인 closure 는 함수 값이기도 하다. 이 값을 다른 함수에 넘기면, 받는 함수의 parameter 타입에는 “어느 isolation 에서 돌아야 하는가” 를 적을 자리가 없다. 그래서 받는 쪽은 그 값이 어디서 돌아야 하는지 모른 채 부르거나, 타입에서 isolation 이 지워진 채로 넘겨받는다. SE-0431 은 이 정보가 타입에서 사라지는 문제를 푸는 제안이다.

앞 글들의 내용은 짧게 짚고 간다. actor, isolation, global actor, region, sending 이 낯설면 먼저 읽으면 좋다.

  • SE-0412 글: global actor 와 isolation 이 무엇인지
  • SE-0414 글: non-Sendable 값을 “같은 region” 으로 묶어서 다른 isolation 으로 보내도 되는지 컴파일러가 판단하는 방식
  • SE-0430 글: 함수 경계를 넘어 값을 통째로 넘기는 sending. Task.init 의 operation 이 sending @escaping @isolated(any) 인 이유도 거기서 짧게 다뤘다
  • SE-0420 글: nonisolated async 함수가 부른 쪽 actor 를 떠나는 이유와 #isolation
  • SE-0434 글: global actor 에 묶인 타입을 쓰기 편하게 만든 제안. 이 글의 수락 때 빠진 @Sendable 함의와도 이어진다

함수 값이 가진 isolation

은행 창구로 생각하면 쉽다. actor 는 창구이고, 그 안에서 돌아야 하는 함수는 창구 직원에게만 맡길 수 있는 업무다. @MainActor 가 붙은 함수는 “main 창구 업무” 라고 이름표가 붙은 업무이고, 창구 이름이 따로 없는 함수는 아무 창구에서나 처리해도 되는 업무다.

함수를 직접 부를 때는 컴파일러가 이름표를 읽는다. await onMain() 이라고 쓰면 컴파일러는 onMain 이 main 창구 업무임을 알고, 부르는 쪽이 다른 창구에 있으면 main 창구로 옮겨 가는 코드를 넣는다. 그런데 이 업무를 “업무 상자” 에 담아 다른 함수에 넘기면 사정이 달라진다. 상자(함수 타입)에는 이름표를 적는 칸이 없다. 상자를 받은 함수는 안에 든 업무가 어느 창구의 것인지 알 방법이 없다.

Swift 의 함수 타입에는 isolation 을 적는 칸이 이미 하나 있다. @MainActor () -> Void 처럼 global actor 를 타입에 적는 것이다. 이 칸은 이름이 고정된 isolation 만 적을 수 있다. 받는 쪽이 “무슨 isolation 이든 받는다” 고 하려면 타입에 isolation 이 값처럼 들어 있어야 한다. 이 글의 @isolated(any) 가 그 칸이다.

제안서는 이 개념을 “dynamic isolation” 이라고 부른다. 함수 타입 자체는 isolation 을 정적으로 모르는데, 그 값이 돌 isolation 은 실행 중에 값에서 꺼낼 수 있다는 뜻이다. 꺼낸 값의 타입은 (any Actor)? 다. nil 이면 nonisolated 이고, global actor 에 묶인 함수는 그 global actor 의 shared 인스턴스이고, actor 안의 함수는 그 actor 참조다. 뒤에서 이 세 경우를 실제로 출력해서 확인한다.


타입에서 isolation 이 지워지는 모습

@isolated(any) 가 없을 때 어떻게 되는지 먼저 본다. 아래 코드는 actor 의 메서드를 두 가지 함수 타입으로 넘긴다.

Erase.swift

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
actor Model {
  var count = 0
  func bump() { count += 1 }
}

// 동기 함수 타입: isolation 이 없다(nonisolated)는 뜻이다
func runSync(_ f: @escaping () -> Void) { f() }

// async 로 지우면 받을 수 있다
func runAsync(_ f: @escaping @Sendable () async -> Void) async { await f() }

func test(model: Model) async {
  runSync(model.bump)
  await runAsync(model.bump)
}

runSync 의 parameter 는 동기 함수 타입이라서 isolation 이 없다. actor 안에서만 돌 수 있는 model.bump 를 이 타입으로 바꾸는 것은 막힌다. 동기 함수는 await 없이 불리므로, 부르는 쪽이 어느 actor 에 있든 bump 를 그 자리에서 실행해 버리기 때문이다. runAsync 는 async 로 지운다. async 함수 타입은 부를 때 await 가 붙으니 다른 actor 의 함수를 담을 수 있다. 다만 이 타입은 @Sendable 이어야 하고, actor 에 묶인 메서드 참조는 @Sendable 이 아닌 값으로 취급되어서 그 자리에 바로 넘길 수 없다.

진단은 -emit-sil 로 뽑았다. -emit-sil 은 타입 검사 뒤 SIL(컴파일러 중간 표현) 단계까지 컴파일해서 그 단계에서 나오는 진단까지 빠짐없이 낸다. 타입 검사까지만 하는 -typecheck 는 SIL 단계의 진단(초기화 검사, sending 검사 같은 것)을 빼먹는다. 아래 명령에서 -o /dev/null 은 결과 파일을 버리고, -parse-as-library 는 최상위 코드가 없는 일반 소스 파일로 다루라는 옵션이며, -wmo 는 모든 파일을 한 모듈로 같이 컴파일하게 한다.

1
xcrun swiftc -emit-sil -o /dev/null -parse-as-library -wmo -swift-version 6 Common.swift Erase.swift

Common.swift 에는 이 글 전체에서 쓰는 non-Sendable 클래스가 들어 있다.

1
final class NonSendable { var value = 0 }

Swift 6 모드의 진단이다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
Erase.swift:14:24: error: converting non-Sendable function value to '@Sendable () async -> Void' may introduce data races
12 | func test(model: Model) async {
13 |   runSync(model.bump)
14 |   await runAsync(model.bump)
   |                        `- error: converting non-Sendable function value to '@Sendable () async -> Void' may introduce data races
15 | }
16 | 
Erase.swift:13:17: error: actor-isolated instance method 'bump()' can not be partially applied
11 | 
12 | func test(model: Model) async {
13 |   runSync(model.bump)
   |                 `- error: actor-isolated instance method 'bump()' can not be partially applied
14 |   await runAsync(model.bump)
15 | }

이 글에서 “Swift 5 모드” 와 “Swift 6 모드” 는 컴파일러 버전이 아니라 언어 모드다. 컴파일러는 Xcode 27 에 들어 있는 Swift 6.4 하나이고, -swift-version 5 를 받으면 옛 규칙으로, -swift-version 6 을 받으면 새 규칙으로 검사한다. “Swift 5 complete” 는 Swift 5 모드에 -strict-concurrency=complete 를 준 상태로, concurrency 검사만 Swift 6 수준으로 하되 위반을 error 가 아니라 warning 으로 보여 준다. 이 옵션들은 SE-0423 글에서 더 자세히 풀었다. 세 모드를 한 번에 돌리려고 modes.sh 를 만들어 썼다. 모드별 결과는 이렇다.

모드진단
Swift 514:24 warning (converting non-Sendable), 13:17 error, 14:24 error (can not be partially applied)
Swift 5 completeSwift 5 와 같은 세 개
Swift 614:24 error (converting non-Sendable), 13:17 error

13:17 의 error 는 모든 모드에서 같다. runSync(model.bump) 는 어느 모드에서도 안 된다. 동기 함수 타입으로 바꾸면 isolation 이 사라지는데, 사라진 채로 actor 안 함수를 부르게 둘 수는 없기 때문이다.

14:24 는 async 로 지우는 쪽이다. Model 은 actor 라서 Sendable 이지만, model.bump 는 actor 에 isolated 된 메서드 참조라서 @Sendable 이 아닌 함수 값으로 취급된다. 그 값을 @Sendable 을 요구하는 자리에 넘기면 Swift 5 계열은 warning 에 can not be partially applied error 가 더해지고, Swift 6 은 error 하나다. runSync 줄이 없어도 같은지 보려고 runAsync 만 남긴 EraseOK.swift 를 따로 돌렸다. Swift 6 에서는 9:24 의 converting non-Sendable function value error 하나이고, Swift 5 에서는 같은 자리에 warning 과 can not be partially applied error 가 함께 나온다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
EraseOK.swift:9:24: warning: converting non-Sendable function value to '@Sendable () async -> Void' may introduce data races
 7 | 
 8 | func test(model: Model) async {
 9 |   await runAsync(model.bump)
   |                        `- warning: converting non-Sendable function value to '@Sendable () async -> Void' may introduce data races
10 | }
11 | 

EraseOK.swift:9:24: error: actor-isolated instance method 'bump()' can not be partially applied
 7 | 
 8 | func test(model: Model) async {
 9 |   await runAsync(model.bump)
   |                        `- error: actor-isolated instance method 'bump()' can not be partially applied
10 | }
11 | 

6.4 에서 actor 에 묶인 메서드 참조를 @Sendable () async 로 바꾸는 길은 어느 모드에서도 error 로 끝난다. isolation 을 지워서 받는 방법은 “지우면 받을 수 있다” 가 아니라 “지워도 받을 수 없을 때가 있다” 가 된다.


parameter 가 있는 함수에서의 같은 문제

같은 문제는 인자를 받는 함수에서도 나온다.

EraseArg.swift

1
2
3
4
5
6
7
8
9
10
11
12
13
actor Store {
  var items: [NonSendable] = []
  func add(_ item: NonSendable) { items.append(item) }
}

func forEachItem(_ body: @escaping @Sendable (NonSendable) async -> Void) async {
  let item = NonSendable()
  await body(item)
}

func test(store: Store) async {
  await forEachItem(store.add)
}

Swift 6 모드의 진단이다.

1
2
3
4
5
6
7
EraseArg.swift:12:27: error: converting non-Sendable function value to '@Sendable (NonSendable) async -> Void' may introduce data races
10 | 
11 | func test(store: Store) async {
12 |   await forEachItem(store.add)
   |                           `- error: converting non-Sendable function value to '@Sendable (NonSendable) async -> Void' may introduce data races
13 | }
14 | 

Swift 5 와 Swift 5 complete 에서는 12:27 에 위와 같은 converting non-Sendable function value warning 과 actor-isolated instance method 'add' can not be partially applied error 가 함께 나온다. forEachItem 같은 “각 항목마다 body 를 부르는” 범용 함수는 SE-0420 글에서 본 forEachAsync 와 같은 모양이다. isolation 을 보존한 채로 받으려면 타입이 그 정보를 들고 있어야 한다.


지운 함수로 만든 Task 의 순서 뒤섞임

타입에서 isolation 을 지우면 정확성뿐 아니라 실행 순서도 문제가 된다. 이 제안서가 가장 먼저 겨냥하는 곳이 Task 를 만드는 wrapper 다. pitch 에서 ktoso 는 async let 과 Task {} 가 “enqueued to the global pool first, and then hop to the actor” 되어서 순서가 바뀔 수 있다고 짚었다(pitch #3). 말 그대로 전역 풀에 먼저 들어갔다가 actor 로 다시 건너가는 구조다. 아래 코드는 이것을 숫자로 센다.

TaskOrder.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
@MainActor var log: [Int] = []

func spawnErased(_ op: @escaping @Sendable () async -> Void) {
  Task(operation: op)
}

func spawnKept(_ op: sending @escaping @isolated(any) () async -> Void) {
  Task(operation: op)
}

@MainActor
func run(_ name: String, _ spawn: (Int) -> Void) async {
  log = []
  let n = 10_000
  for i in 0..<n { spawn(i) }
  while log.count < n { await Task.yield() }
  var inversions = 0
  for k in 1..<n where log[k] < log[k - 1] { inversions += 1 }
  print("\(name): 순서가 뒤집힌 자리 \(inversions)곳")
}

@main
struct App {
  @MainActor
  static func main() async {
    await run("Task { @MainActor in }") { i in Task { @MainActor in log.append(i) } }
    await run("@Sendable () async 로 지운 wrapper") { i in spawnErased { @MainActor in log.append(i) } }
    await run("@isolated(any) 를 받는 wrapper") { i in spawnKept { @MainActor in log.append(i) } }
  }
}

Task 는 비동기 작업 하나를 만드는 타입이다. Task(operation:) 은 operation 을 새 task 로 돌린다. Task.yield() 는 현재 task 가 잠깐 양보해서 다른 task 가 돌게 한다. 위 코드는 main actor 에서 task 를 1 만 개 만들고, 각 task 가 log 에 자기 번호를 넣게 한다. 다 끝나면 log[k] < log[k - 1], 즉 앞 번호가 뒤 번호보다 먼저 기록되지 못한 자리를 센다. 세 가지 방법을 비교한다.

  • Task { @MainActor in ... } 로 직접 만든다.
  • @Sendable () async -> Void 로 isolation 을 지운 wrapper 를 거친다.
  • sending @escaping @isolated(any) () async -> Void 로 받는 wrapper 를 거친다.

빌드와 실행은 단계별로 했다.

1
xcrun swiftc -parse-as-library -swift-version 6 Common.swift TaskOrder.swift -o taskorder
1
./taskorder
1
2
3
Task { @MainActor in }: 순서가 뒤집힌 자리 0곳
@Sendable () async 로 지운 wrapper: 순서가 뒤집힌 자리 877곳
@isolated(any) 를 받는 wrapper: 순서가 뒤집힌 자리 0곳

지운 wrapper 만 순서가 섞인다. 이 값은 돌릴 때마다 달라서, 이 글을 쓰며 돌린 값은 790, 848, 877, 1280 곳이었다. 매번 수백 곳이 나온다. 직접 만든 Task 와 @isolated(any) wrapper 는 매번 0 곳이었다.

@Sendable 로 지운 함수를 넘긴 Task 는 global pool 을 거쳐 main actor 로 다시 건너가서 순서가 섞이고, @isolated(any) 로 받은 함수를 넘긴 Task 는 main actor 의 queue 에 바로 들어가서 만든 순서대로 돈다.

위 그림이 두 길의 차이다. 지운 쪽은 Task 를 만드는 시점에 함수의 isolation 이 타입에 안 보이므로, 일단 전역 풀에서 시작한 다음 closure 안에서 main actor 로 건너간다. 건너가는 시점이 task 마다 달라서 순서가 섞인다. @isolated(any) 쪽은 isolation 을 꺼내서 main actor 의 queue 에 바로 넣는다. main actor 의 queue 는 먼저 들어온 것이 먼저 나온다. 이 글의 나머지는 “이 타입이 무엇이고, 어떻게 쓰고, 왜 이런 모양인가” 를 풀어 간다.

세 경우 모두 closure 가 { @MainActor in } 로 isolation 을 명시했다. 이렇게 명시한 closure 는 formal isolation 의 executor 에서 시작하는 것이 보장되고, 그래서 만든 순서대로 main actor 에서 시작한다. 보장이 걸리는 조건은 뒤의 Task 절에서 본다.


무엇이 바뀌나

SE-0431 은 함수 타입에 붙이는 속성 하나 @isolated(any) 와, 그 값에서 isolation 을 꺼내는 .isolation 프로퍼티, 그리고 표준 라이브러리 Task 생성 함수의 시그니처 변경으로 이루어진다. 아래에서 문법, 변환 규칙, .isolation 의 값, 실행 위치, 호출할 때의 검사, Task 생성 함수, 배포 대상 순서로 본다.


@isolated(any) 함수 타입

제안서의 첫 예제는 점진적으로 작업을 진행하는 함수다. operation 이 무슨 isolation 을 갖든 받을 수 있게 하는 것이 목적이다.

Basic.swift

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
func gradually(steps: Int, operation: @isolated(any) (Double) -> Void) async {
  for i in 1...steps {
    await operation(Double(i) / Double(steps))
  }
}

actor WorldModel {
  var position = 0.0

  func move() async {
    await gradually(steps: 4) { progress in
      self.position = progress
    }
  }
}

gradually 는 operation 이 동기 함수 타입인데도 await 로 부른다. @isolated(any) 함수는 어느 isolation 에서 돌지 모르므로, 부를 때 항상 await 가 필요하다. 부르는 쪽이 operation 의 isolation 으로 건너가야 하기 때문이다. 이 문장은 함수 자체가 async 이든 아니든 같다.

WorldModel.move() 의 closure 는 self.position 을 바꾼다. 그래서 이 closure 는 WorldModel 에 isolated 된 값이고, gradually 는 이것을 @isolated(any) 로 받아서 필요할 때 WorldModel 로 건너가 돌린다. 이 코드는 Swift 6 모드에서 진단이 난다.

1
2
3
4
5
6
7
8
9
10
11
Basic.swift:11:11: error: sending value of non-Sendable type '(Double) -> Void' risks causing data races [#RegionIsolation::SendingRisksDataRace]
 9 | 
10 |   func move() async {
11 |     await gradually(steps: 4) { progress in
   |           |- error: sending value of non-Sendable type '(Double) -> Void' risks causing data races [#RegionIsolation::SendingRisksDataRace]
   |           `- note: sending 'self'-isolated value of non-Sendable type '(Double) -> Void' to @concurrent global function 'gradually(steps:operation:)' risks causing races in between 'self'-isolated and @concurrent uses
12 |       self.position = progress
13 |     }

[#RegionIsolation]: <https://docs.swift.org/compiler/documentation/diagnostics/region-isolation>
[#SendingRisksDataRace]: <https://docs.swift.org/compiler/documentation/diagnostics/sending-risks-data-race>

Swift 5 모드는 진단이 0 개이고, Swift 5 complete 는 같은 메시지에 this is an error in the Swift 6 language mode 가 붙은 warning 이다. 이 error 는 SE-0430 글에서 본 모양이다. gradually 는 nonisolated async 함수라서 부른 actor 를 떠나 @concurrent 처럼 돈다. 그러면 self 에 isolated 된 closure 를 그쪽으로 보내는 것이 되고, closure 는 @Sendable 도 sending 도 아니므로 막힌다. 메시지가 @concurrent global function 이라고 부르는 것이 6.4 에서 nonisolated async 함수를 일컫는 말이다. @concurrent 와 nonisolated(nonsending) 은 SE-0461 에서 들어왔고 이 글에서는 이름만 쓴다. @isolated(any) 함수 값이 저절로 @Sendable 이 되지 않는다는 점이 이 error 의 바탕이다. 수락 때 그 함의가 빠진 경위는 “다른 선택지는 왜 안 됐나” 에서 본다.

이 error 를 없애는 방법이 세 가지 있다. 각각 BasicSendable.swift, BasicSending.swift, BasicNonsending.swift 로 만들어 모든 모드에서 돌렸다. 세 파일은 Basic.swift 와 한 줄씩만 다르다.

파일바꾼 줄진단
BasicSendable.swiftoperation: @Sendable @isolated(any) (Double) -> Void모든 모드에서 error
BasicSending.swiftoperation: sending @isolated(any) (Double) -> Void모든 모드에서 error
BasicNonsending.swiftnonisolated(nonsending) func gradually(...)모든 모드에서 0 개

@Sendable 을 붙이면 closure 가 @Sendable 이어야 해서, actor 의 프로퍼티를 바꾸는 순간 막힌다.

1
2
3
4
5
6
7
8
9
10
11
12
BasicSendable.swift:12:12: error: actor-isolated property 'position' can not be mutated from a Sendable closure
 6 | 
 7 | actor WorldModel {
 8 |   var position = 0.0
   |       `- note: mutation of this property is only permitted within the actor
 9 | 
10 |   func move() async {
11 |     await gradually(steps: 4) { progress in
12 |       self.position = progress
   |            `- error: actor-isolated property 'position' can not be mutated from a Sendable closure
13 |     }
14 |   }

sending 은 closure 가 어느 isolation 에도 묶이지 않은 상태로 넘어가야 하므로, self 에 묶인 closure 는 안 된다. 같은 모양의 error 가 can not be mutated from a nonisolated context 로 나온다. 세 번째 길은 gradually 를 nonisolated(nonsending) 으로 바꿔 부른 쪽 isolation 에서 돌게 하는 것이고, 진단이 0 개다. gradually 가 WorldModel 에서 돌고 closure 도 WorldModel 에서 도니 경계를 넘는 일이 없기 때문이다. @Sendable 과 sending 은 값이 경계를 넘어 다른 곳에서 돌 수 있다는 전제를 두는 표시이고, nonisolated(nonsending) 은 그 전제를 없애는 길이다. 값을 다른 isolation 으로 보내는 일이 실제로 있는 Task 는 뒤에서 sending 쪽을 어떻게 만족시키는지 본다.


await 가 필요한 호출

@isolated(any) 함수는 동기 함수 타입이어도 await 없이 부를 수 없다.

NoAwait.swift

1
2
3
4
func callTwice(_ operation: @isolated(any) () -> Void) async {
  operation()
  await operation()
}

모든 모드의 진단이다.

1
2
3
4
5
6
7
NoAwait.swift:2:3: error: expression is 'async' but is not marked with 'await'
1 | func callTwice(_ operation: @isolated(any) () -> Void) async {
2 |   operation()
  |   |- error: expression is 'async' but is not marked with 'await'
  |   `- note: calls to parameter 'operation' from outside of its actor context are implicitly asynchronous
3 |   await operation()
4 | }

첫 줄은 error 이고 둘째 줄은 통과한다. 이 규칙이 필요한 이유는 간단하다. 부르는 쪽이 operation 과 같은 isolation 인지 컴파일러가 모르기 때문에, 건너가야 할 수 있다고 가정해야 한다. 건너갈 수 있는 호출은 중간에 멈출 수 있어서 await 가 필요하다.


문법과 구조 규칙

@isolated(any) 는 함수 타입에만 붙는 속성이다. 제안서는 이 속성을 다른 isolation 표시와 같이 쓸 수 없고, isolated parameter 를 가진 함수 타입에도 쓸 수 없다고 정한다. 세 가지 위반을 한 파일에 모아서 돌렸다.

Rules.swift

1
2
3
4
5
6
7
8
9
10
actor Worker {}

// 1. 다른 isolation 표시와 같이 쓸 수 없다
func both(_ f: @isolated(any) @MainActor () -> Void) {}

// 2. isolated parameter 와 같이 쓸 수 없다
func withParam(_ f: @isolated(any) (isolated Worker) -> Void) {}

// 3. 함수 타입이 아닌 곳에는 붙일 수 없다
func notFunction(_ x: @isolated(any) Int) {}

세 모드 모두 같은 진단이다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Rules.swift:4:45: error: function type cannot have both a global actor and '@isolated(any)'
 2 | 
 3 | // 1. 다른 isolation 표시와 같이 쓸 수 없다
 4 | func both(_ f: @isolated(any) @MainActor () -> Void) {}
   |                                             `- error: function type cannot have both a global actor and '@isolated(any)'
 5 | 
 6 | // 2. isolated parameter 와 같이 쓸 수 없다
Rules.swift:7:54: error: function with 'isolated' parameter cannot also be '@isolated(any)'
 5 | 
 6 | // 2. isolated parameter 와 같이 쓸 수 없다
 7 | func withParam(_ f: @isolated(any) (isolated Worker) -> Void) {}
   |                                                      `- error: function with 'isolated' parameter cannot also be '@isolated(any)'
 8 | 
 9 | // 3. 함수 타입이 아닌 곳에는 붙일 수 없다
Rules.swift:10:23: error: '@isolated' only applies to function types
 8 | 
 9 | // 3. 함수 타입이 아닌 곳에는 붙일 수 없다
10 | func notFunction(_ x: @isolated(any) Int) {}
   |                       `- error: '@isolated' only applies to function types
11 |

이 세 규칙은 이유가 하나로 이어진다. @isolated(any) 는 “isolation 이 값에서 나온다” 는 표시인데, @MainActor 는 isolation 이 타입에 이미 적혀 있다는 뜻이고 isolated parameter 는 isolation 이 부르는 쪽이 넘기는 인자라는 뜻이다. 둘 다 “어디서 돌지” 를 다른 방식으로 이미 정해 놓은 표시라서, 하나를 더 붙이면 어느 쪽이 맞는지 정할 수 없다.

속성이라고 아무 데나 붙는 것도 아니다. 선언과 closure 에 직접 붙여 보면 파서가 거절한다.

RulesDecl.swift

1
2
// 선언에는 붙일 수 없다
@isolated(any) func run() {}
1
2
3
4
5
6
7
8
9
10
RulesDecl.swift:2:1: error: 'isolated' is a declaration modifier, not an attribute
1 | // 선언에는 붙일 수 없다
2 | @isolated(any) func run() {}
  | `- error: 'isolated' is a declaration modifier, not an attribute
3 | 
RulesDecl.swift:2:10: error: expected declaration
1 | // 선언에는 붙일 수 없다
2 | @isolated(any) func run() {}
  |          `- error: expected declaration
3 |

RulesClosure.swift

1
2
// closure 에도 직접 붙일 수 없다
let c = { @isolated(any) in print("hi") }
1
2
3
4
5
6
7
8
9
10
RulesClosure.swift:2:11: error: 'isolated' is a declaration modifier, not an attribute
1 | // closure 에도 직접 붙일 수 없다
2 | let c = { @isolated(any) in print("hi") }
  |           `- error: 'isolated' is a declaration modifier, not an attribute
3 | 
RulesClosure.swift:2:21: error: cannot infer type of closure parameter 'any' without a type annotation
1 | // closure 에도 직접 붙일 수 없다
2 | let c = { @isolated(any) in print("hi") }
  |                     `- error: cannot infer type of closure parameter 'any' without a type annotation
3 |

6.4 에서 @isolated(any) 는 타입 자리에서만 쓴다. 선언이나 closure 에 붙이는 속성이 아니라, 함수 값을 받는 parameter 나 변수의 타입에 붙는다. 이 제약이 철자 논의의 한가운데에 있었다. 파서 메시지가 “isolated 는 declaration modifier 이지 attribute 가 아니다” 라고 말하는 것이 바로 isolated parameter 와 @isolated(any) 가 헷갈리는 지점이다. 이 논의는 “다른 선택지는 왜 안 됐나” 에서 다시 본다.


변환 규칙

@isolated(any) 함수 값은 다른 함수 타입으로 바꾸고 받을 수 있다. 6.4 에서 방향별로 측정한 규칙은 다음과 같다.

  • 양쪽이 모두 @isolated(any) 이면 isolation 이 그대로 보존된다.
  • 도착 타입만 @isolated(any) 이면, 출발 함수가 isolated parameter 를 가진 경우는 error 다. 그 밖에는 값이 isolation 을 얻는다. closure 는 capture 한 isolation 을 얻고, nonisolated 함수와 메서드 참조는 nil 이며, global actor 함수는 그 global actor 를 얻는다.
  • 출발 타입만 @isolated(any) 일 때, 동기 함수 타입으로 바꾸면 warning 이고, isolation 표시가 없는 async 함수 타입으로 바꾸면 통과하며, global actor 가 적힌 async 함수 타입으로 바꾸면 error 다.
  • 중간에 다른 타입을 한 번 거치면 isolation 이 지워진다.

모든 값은 -emit-sil 로 Swift 5, Swift 5 complete, Swift 6 세 모드에서 돌렸고, 모드에 따라 갈리는 곳만 따로 적는다.


isolated parameter 를 가진 함수에서

isolated parameter 를 가진 함수는 @isolated(any) 로 바꿀 수 없다. 리뷰에서 juliand665 가 왜 안 되는지 물었고(리뷰 #11), John McCall 은 isolation 을 부르는 쪽이 고르기 때문에 isolation 이 무엇을 돌려줘야 할지 알 수 없다고 답했다(리뷰 #12). 같은 답에서 그는 isolated 를 capture 한 closure 로 바꾸면 표현할 수 있다고 했다. 둘 다 이 글의 6.4 로 돌려 봤다.

IsolatedParam.swift

1
2
3
4
5
6
7
8
9
10
actor Worker {
  func work() {}
}

func take(_ f: @isolated(any) (Worker) -> Void) {}

func test() {
  let byParam: (isolated Worker) -> Void = { w in w.work() }
  take(byParam)
}
1
2
3
4
5
6
7
IsolatedParam.swift:9:8: error: cannot convert value of type '(isolated Worker) -> Void' to expected argument type '@isolated(any) (Worker) -> Void'
 7 | func test() {
 8 |   let byParam: (isolated Worker) -> Void = { w in w.work() }
 9 |   take(byParam)
   |        `- error: cannot convert value of type '(isolated Worker) -> Void' to expected argument type '@isolated(any) (Worker) -> Void'
10 | }
11 |

모든 모드에서 error 다. 리뷰 #12 의 예제는 { [isolated myActor] in fn(myActor) } 로 isolated 를 capture list 에 적는다. 같은 모양의 [isolated self] capture 는 6.4 에서 파서가 받지 않는다.

IsolatedSelf.swift

1
2
3
4
5
6
7
actor A {
  func f() {}
  func g() {
    let c = { [isolated self] in self.f() }
    _ = c
  }
}
1
2
3
4
5
6
7
IsolatedSelf.swift:4:16: error: expected 'weak', 'unowned', or no specifier in capture list
2 |   func f() {}
3 |   func g() {
4 |     let c = { [isolated self] in self.f() }
  |                `- error: expected 'weak', 'unowned', or no specifier in capture list
5 |     _ = c
6 |   }

6.4 에서 capture list 가 받는 것은 weak, unowned, 또는 아무 것도 없는 경우뿐이다. 리뷰에 나온 [isolated myActor] 와 같은 철자는 6.4 에서 쓸 수 없다. closure 안에서 self 를 쓰면 그 closure 는 actor 에 묶이므로, 같은 일을 하려면 self 를 쓰는 closure 로 감싸는 길을 쓴다.


@isolated(any) 에서 동기 함수 타입으로

출발 타입만 @isolated(any) 일 때 동기 함수 타입으로 바꾸려고 하면 6.4 는 이렇게 낸다.

FromAny.swift

1
2
3
4
func toSync(_ f: @escaping @isolated(any) () -> Void) {
  let g: () -> Void = f
  _ = g
}
1
2
3
4
5
6
7
FromAny.swift:2:23: warning: converting @isolated(any) function of type '@isolated(any) () -> Void' to synchronous function type '() -> Void' is not allowed; this will be an error in a future Swift language mode [#ConversionFromIsolatedAnyToSynchronous]
1 | func toSync(_ f: @escaping @isolated(any) () -> Void) {
2 |   let g: () -> Void = f
  |                       `- warning: converting @isolated(any) function of type '@isolated(any) () -> Void' to synchronous function type '() -> Void' is not allowed; this will be an error in a future Swift language mode [#ConversionFromIsolatedAnyToSynchronous]
3 |   _ = g
4 | }
[#ConversionFromIsolatedAnyToSynchronous]: <https://docs.swift.org/compiler/documentation/diagnostics/conversion-from-isolated-any-to-synchronous>

6.4 에서는 이 변환이 error 가 아니라 warning 이고, 메시지가 “future Swift language mode 에서 error 가 된다” 고 말한다. 이 warning 은 Swift 6 모드에서도 error 가 아니라 warning 이다. 함수 인자로 넘기는 자리도 같다. SyncWarn.swift 는 func runSync(_ f: () -> Void) 에 @isolated(any) parameter 를 그대로 넘기는 코드인데, 5:11 에 같은 모양의 warning 이 모든 모드에서 하나 나온다.

SyncWarn.swift

1
2
3
4
5
6
// sync 로 지우는 변환을 함수 인자로 넘길 때
func runSync(_ f: () -> Void) { f() }

func forward(_ f: @isolated(any) () -> Void) {
  runSync(f)
}

이 warning 이 나오는 변환은 동기 함수 타입 쪽에서 isolation 을 잃는 변환이다. 도착 타입이 async 이면 같은 변환이 통과한다.


@isolated(any) 에서 async 함수 타입으로

FromAnyOK.swift

1
2
3
4
5
6
func toAsync(_ f: @escaping @isolated(any) () -> Void) async {
  let g: () async -> Void = f
  await g()
  let h: @MainActor () async -> Void = f
  await h()
}

2 번째 줄의 () async -> Void 변환은 통과한다. 4 번째 줄의 @MainActor () async -> Void 는 거절된다. Swift 6 모드의 진단이다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
FromAnyOK.swift:4:40: error: using non-Sendable parameter 'f' in a context expecting a '@Sendable' closure
1 | func toAsync(_ f: @escaping @isolated(any) () -> Void) async {
  |                `- note: parameter 'f' is implicitly non-Sendable
2 |   let g: () async -> Void = f
3 |   await g()
4 |   let h: @MainActor () async -> Void = f
  |                                        `- error: using non-Sendable parameter 'f' in a context expecting a '@Sendable' closure
5 |   await h()
6 | }
FromAnyOK.swift:4:40: error: cannot convert value of type '@isolated(any) () -> Void' to specified type '@MainActor @Sendable () async -> Void'
2 |   let g: () async -> Void = f
3 |   await g()
4 |   let h: @MainActor () async -> Void = f
  |                                        `- error: cannot convert value of type '@isolated(any) () -> Void' to specified type '@MainActor @Sendable () async -> Void'
5 |   await h()
6 | }

Swift 5 와 Swift 5 complete 는 4:40: error: cannot convert value of type '@isolated(any) () -> Void' to specified type '@MainActor () async -> Void' 하나만 낸다. Swift 6 의 error 두 개 중 첫째는 @MainActor 함수 타입이 @Sendable 로 추론되어서 non-Sendable 인 f 와 부딪힌 것이다. 그 부딪힘을 없애려고 f 에 @Sendable 을 붙여 따로 돌렸다.

FromAnySendable.swift

1
2
3
4
func toMain(_ f: @escaping @Sendable @isolated(any) () -> Void) async {
  let h: @MainActor () async -> Void = f
  await h()
}
1
2
3
4
5
6
FromAnySendable.swift:2:40: error: cannot convert value of type '@isolated(any) @Sendable () -> Void' to specified type '@MainActor @Sendable () async -> Void'
1 | func toMain(_ f: @escaping @Sendable @isolated(any) () -> Void) async {
2 |   let h: @MainActor () async -> Void = f
  |                                        `- error: cannot convert value of type '@isolated(any) @Sendable () -> Void' to specified type '@MainActor @Sendable () async -> Void'
3 |   await h()
4 | }

Swift 5 와 Swift 5 complete 도 같은 위치에서 error 하나를 내고, 도착 타입이 '@MainActor () async -> Void' 로 적힌다. @Sendable 을 붙여도 변환 자체는 거절되므로, 6.4 에서 @isolated(any) 값을 global actor 가 적힌 함수 타입으로 바꾸는 것은 @Sendable 여부와 상관없이 안 된다.

인자가 non-Sendable 이면 같은 변환에 error 가 하나 더 붙는다. FromAnyArg.swift 는 main actor 의 NonSendable 값을 도착 함수에 넘긴다.

FromAnyArg.swift

1
2
3
4
5
6
7
@MainActor var shared = NonSendable()

@MainActor
func toAsync(_ f: @escaping @isolated(any) (NonSendable) -> Void) async {
  let g: @MainActor (NonSendable) async -> Void = f
  await g(shared)
}

Swift 6 모드는 5:51 에 error 둘이다. 하나는 using non-Sendable parameter 'f' in a context expecting a '@Sendable' closure(4 번째 줄에 parameter 'f' is implicitly non-Sendable note 가 붙는다)이고, 다른 하나는 cannot convert value of type '@isolated(any) (NonSendable) -> Void' to specified type '@MainActor @Sendable (NonSendable) async -> Void' 이다.

변환을 정리한 표다.

변환6.4 결과
nonisolated 함수, global actor 함수, self 를 쓰는 closure 를 @isolated(any) 로통과 (isolation 이 값에 담긴다)
isolated parameter 를 가진 함수를 @isolated(any) 로error
@isolated(any) 를 동기 함수 타입으로warning (모든 모드)
@isolated(any) 를 () async 로통과
@isolated(any) 를 @MainActor () async 로error
중간에 다른 타입을 한 번 거치면isolation 이 지워짐 (다음 절에서 값으로 확인)

isolation 프로퍼티

@isolated(any) 함수 값에는 .isolation 프로퍼티가 있다. 타입은 (any Actor)? 이다. nonisolated 함수는 nil, global actor 에 묶인 함수는 그 global actor 의 shared, actor 안의 함수는 그 actor 참조다. 아래 코드는 실제로 어떤 값이 나오는지 출력한다.

Iso.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
42
43
44
45
46
47
48
49
50
51
52
func describe(_ f: @isolated(any) () -> Void) -> String {
  guard let iso = f.isolation else { return "nil" }
  return String(describing: type(of: iso))
}

func describeAsync(_ f: @isolated(any) () async -> Void) -> String {
  guard let iso = f.isolation else { return "nil" }
  return String(describing: type(of: iso))
}

func plain() {}
@MainActor func onMain() {}

@globalActor actor MyGlobal {
  static let shared = MyGlobal()
}
@MyGlobal func onMyGlobal() {}

actor Worker {
  var count = 0
  func method() { count += 1 }

  func inside() {
    print("actor 메서드 참조:", describe(method))
    print("self 를 쓰는 closure:", describe { self.count += 1 })
    print("self 를 안 쓰는 closure:", describe { print("hi") })
    let m: @isolated(any) () -> Void = method
    print("isolation === self:", m.isolation === self)
  }
}

@main struct App {
  static func main() async {
    print("nonisolated 함수:", describe(plain))
    print("@MainActor 함수:", describe(onMain))
    print("@MyGlobal 함수:", describe(onMyGlobal))
    print("{ @MainActor in }:", describe { @MainActor in })

    let w = Worker()
    await w.inside()

    // 중간 변환
    let asMain: @MainActor () -> Void = plain
    print("plain 을 @MainActor 로 바꾼 뒤:", describe(asMain))
    let erased: @Sendable () async -> Void = { @MainActor in }
    print("@MainActor closure 를 () async 로 지운 뒤:", describeAsync(erased))

    // 같은 인스턴스인가
    let g: @isolated(any) () -> Void = onMyGlobal
    print("isolation === MyGlobal.shared:", g.isolation === MyGlobal.shared)
  }
}

.isolation 의 타입에 나오는 Actor 는 모든 actor 가 따르는 protocol 이고, any Actor 는 어떤 actor 든 담는 existential 타입이다. String(describing: type(of: iso)) 는 꺼낸 값의 실제 타입 이름을 문자열로 만든다. MainActor 는 main thread 에서 도는 global actor 이고, @globalActor 로 선언한 MyGlobal 은 직접 만든 global actor 다. 빌드와 실행은 이렇게 했다.

1
xcrun swiftc -parse-as-library -swift-version 6 Common.swift Iso.swift -o iso
1
./iso
1
2
3
4
5
6
7
8
9
10
11
nonisolated 함수: nil
@MainActor 함수: MainActor
@MyGlobal 함수: MyGlobal
{ @MainActor in }: MainActor
actor 메서드 참조: nil
self 를 쓰는 closure: Worker
self 를 안 쓰는 closure: nil
isolation === self: false
plain 을 @MainActor 로 바꾼 뒤: MainActor
@MainActor closure 를 () async 로 지운 뒤: nil
isolation === MyGlobal.shared: true

앞의 네 줄은 설명대로다. nonisolated 는 nil, global actor 두 개는 그 이름이다. { @MainActor in } 은 isolation 이 closure 의 표시에서 나온다. isolation === MyGlobal.shared 가 true 이니 .isolation 이 돌려주는 것은 global actor 의 복사본이 아니라 shared 인스턴스 자체다.

self 를 쓰는 closure 는 Worker 이고, self 를 안 쓰는 closure 는 nil 이다. 같은 actor 안에서 만든 closure 라도 isolation 을 가르는 것은 isolated parameter 인 self 를 capture 하는지다. actor 의 상태를 만지는지는 기준이 아니다. 이 구분은 제안서 각주도 같은 말로 적는다. closure 는 isolation 의 대상이 되는 값을 본문에서 실제로 쓸 때에만 그 값에 isolated 된다. 상태를 건드리지 않아도 self 만 capture 하면 Worker 가 나오는지 따로 돌렸다.

IsoCapture.swift

1
2
3
4
5
6
7
actor Worker {
  var count = 0
  func inside() {
    print("self 를 capture 만:", describe { _ = self })
    print("self 를 읽기만:", describe { print(self.count) })
  }
}
1
xcrun swiftc -parse-as-library -swift-version 6 Common.swift IsoCapture.swift -o isocap
1
./isocap
1
2
self 를 capture 만: Worker
self 를 읽기만: Worker

describe 는 Iso.swift 와 같은 함수다. self 를 capture 하기만 해도 Worker 이고, 프로퍼티를 읽기만 해도 Worker 이다. 뒤쪽 그림이 이 규칙을 한 장으로 모은 것이다.

nonisolated 함수는 nil, global actor 함수는 그 global actor 의 shared, actor 안에서 self 를 쓰는 closure 는 그 actor, self 를 쓰지 않는 closure 는 nil 이 isolation 으로 꺼내진다.

중간 변환은 줄 단위로 읽는다. plain 을 @MainActor () -> Void 로 바꿔서 describe 에 넘기면 MainActor 가 나온다. plain 자신은 nonisolated 인데, 한 번 @MainActor 타입으로 바뀐 순간 값이 main actor 로 표시된다는 뜻이다. 반대로 @MainActor closure 를 @Sendable () async -> Void 로 지운 뒤에는 nil 이다. 지우는 순간 isolation 정보가 사라져서, 다시 @isolated(any) 로 받아도 되살릴 수 없다. 앞에서 본 Task 순서 문제가 이 nil 에서 나온다. isolation 을 지운 wrapper 를 거치면 Task 가 받는 값의 .isolation 이 nil 이어서, Task 는 “nonisolated 함수” 로 보고 전역 풀에서 시작한다.

actor 메서드 참조 가 nil 인 것이 눈에 띈다. isolation === self 도 false 다. 같은 actor 안에서 method 를 이름으로 참조하면 @isolated(any) 값의 isolation 은 nil 이다. self 를 쓰는 closure 로 감싸야 Worker 가 된다. 이 값이 어떻게 쓰이는지는 아래에서 본다.


actor 밖에서 만든 메서드 참조

actor 밖에서는 메서드 참조 자체가 거절된다.

IsoPartial.swift

1
2
3
4
5
6
7
8
9
10
11
12
actor Worker {
  func method() {}
}

func describe(_ f: @isolated(any) () -> Void) -> String {
  guard let iso = f.isolation else { return "nil" }
  return String(describing: type(of: iso))
}

func outside(w: Worker) {
  print(describe(w.method))
}
1
2
3
4
5
6
7
8
9
10
11
12
13
IsoPartial.swift:11:20: error: actor-isolated instance method 'method()' can not be referenced from a nonisolated context
 1 | actor Worker {
 2 |   func method() {}
   |        `- note: calls to instance method 'method()' from outside of its actor context are implicitly asynchronous
 3 | }
 4 | 
   :
 9 | 
10 | func outside(w: Worker) {
11 |   print(describe(w.method))
   |                    `- error: actor-isolated instance method 'method()' can not be referenced from a nonisolated context
12 | }
13 |

모든 모드에서 같다. actor 밖의 w.method 는 이름으로 참조할 수 없고, 참조하려면 { await w.method() } 같은 closure 로 감싸야 한다.


actor 안의 메서드 참조가 nil 이 되는 결과

actor 안에서 만든 메서드 참조의 .isolation 이 nil 이라는 것은 “함수를 바깥에서 부르면 actor 밖에서 돈다” 는 뜻이다. 이 사실을 눈으로 보려고 preconditionIsolated 를 넣은 코드를 만들었다. preconditionIsolated(_:file:line:) 는 지금 이 actor 의 executor 에서 돌고 있지 않으면 프로그램을 멈추는 검사다. 먼저 callElsewhere 를 부르지 않는 MethodRef6.swift 다.

MethodRef6.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
func describe(_ f: @isolated(any) () -> Void) -> String {
  guard let iso = f.isolation else { return "nil" }
  return String(describing: type(of: iso))
}

func callElsewhere(_ f: @escaping @isolated(any) () -> Void) async {
  await f()
}

actor Worker {
  var count = 0
  func method() {
    self.preconditionIsolated("method() 가 actor 밖에서 돌았다")
    count += 1
  }

  func inside() async {
    print("method:", describe(method))
    print("self.method:", describe(self.method))
    print("{ self.method() }:", describe { self.method() })
    print("Worker.method(self):", describe(Worker.method(self)))
    print("count:", count)
  }
}

@main struct App {
  static func main() async {
    await Worker().inside()
  }
}
1
xcrun swiftc -parse-as-library -swift-version 6 Common.swift MethodRef6.swift -o mref6
1
./mref6
1
2
3
4
5
method: nil
self.method: nil
{ self.method() }: Worker
Worker.method(self): nil
count: 0

method, self.method, Worker.method(self) 는 모두 nil 이고, 오직 self 를 쓰는 closure 만 Worker 다. 6.4 에서 측정한 값이 그렇다. describe 는 그 값으로 함수를 부르지 않으므로 preconditionIsolated 가 돌지 않고 count 는 0 이다.

이제 callElsewhere(method) 한 줄을 더한 MethodRef.swift 다. 이 함수는 @isolated(any) 값을 await f() 로 부른다. Swift 6 모드에서는 컴파일 단계에서 막힌다.

1
2
3
4
5
6
7
8
9
10
11
MethodRef.swift:22:11: error: sending value of non-Sendable type '() -> ()' risks causing data races [#RegionIsolation::SendingRisksDataRace]
20 |     print("{ self.method() }:", describe { self.method() })
21 |     print("Worker.method(self):", describe(Worker.method(self)))
22 |     await callElsewhere(method)
   |           |- error: sending value of non-Sendable type '() -> ()' risks causing data races [#RegionIsolation::SendingRisksDataRace]
   |           `- note: sending 'self'-isolated value of non-Sendable type '() -> ()' to @concurrent global function 'callElsewhere' risks causing races in between 'self'-isolated and @concurrent uses
23 |     print("count:", count)
24 |   }

[#RegionIsolation]: <https://docs.swift.org/compiler/documentation/diagnostics/region-isolation>
[#SendingRisksDataRace]: <https://docs.swift.org/compiler/documentation/diagnostics/sending-risks-data-race>

Swift 5 complete 에서는 warning 이고, Swift 5 모드는 진단이 없다. 진단이 없는 Swift 5 모드로 빌드해서 실행하면 일이 벌어진다.

1
xcrun swiftc -parse-as-library -swift-version 5 Common.swift MethodRef.swift -o app5
1
./app5
1
2
3
4
5
Incorrect actor executor assumption; expected 'app5.Worker' executor.
method: nil
self.method: nil
{ self.method() }: Worker
Worker.method(self): nil

종료 코드는 134(SIGABRT)다. 앞의 네 줄 출력 뒤에 callElsewhere(method) 에서 Worker.method() 가 actor 밖에서 돌아서 preconditionIsolated 가 멈춘 것이다. 이 호출 경로를 lldb 로 확인했다.

1
timeout 20 xcrun lldb --batch -o run -k bt -k quit ./app5
1
2
3
4
5
6
7
8
* thread #4, name = 'Task 1', queue = 'com.apple.root.default-qos.cooperative', stop reason = signal SIGABRT
  * frame #7: libswift_Concurrency.dylib`Actor.preconditionIsolated(_:file:line:) + 100
    frame #9: app5`Worker.method() + 112
    frame #10: app5`implicit closure #8 in implicit closure #7 in Worker.inside() + 44
    frame #11: app5`reabstraction thunk helper from @escaping @callee_guaranteed () -> () to @escaping @isolated(any) @callee_guaranteed () -> () + 20
    frame #12: app5`callElsewhere(_:) + 44
    frame #13: app5`Worker.inside()
    frame #14: app5`static App.main()

위쪽 몇 프레임과 아래쪽 런타임 프레임은 줄였다. callElsewhere 가 reabstraction thunk 를 거쳐 method 를 부르는데, 그 순간 thread 는 Task 1 이고 전역 동시 실행 queue 위다. 메서드 참조의 isolation 이 nil 이라서 callElsewhere 가 Worker 로 건너가지 않고 그대로 부른 결과다.

backtrace 의 프레임 #11 이 reabstraction thunk helper from @escaping @callee_guaranteed () -> () to @escaping @isolated(any) @callee_guaranteed () -> () 다. isolation 표시가 없는 일반 함수 값에서 @isolated(any) 함수 값으로 바꾸는 thunk 를 지난다는 것이다. 메서드 참조는 먼저 isolation 이 없는 함수 값으로 만들어진 뒤에 변환되는 것으로 보이고, 그래서 nil 이 나오는 것으로 읽힌다.

여기서 얻는 실용적 결론은 하나다. actor 의 메서드를 @isolated(any) 로 넘길 때는 메서드 참조를 그대로 쓰지 말고 { self.method() } 처럼 closure 로 감싼다. 이 closure 는 .isolation 이 Worker 이므로 받는 쪽이 올바른 곳으로 건너가서 돈다.


실행 위치

@isolated(any) 함수를 부르면 실제로 어느 thread 에서 도는지 본다. 아래 코드는 함수가 도는 thread 가 main thread 인지 출력한다.

Runtime.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
import Foundation

func where_() -> String { pthread_main_np() != 0 ? "main thread" : "다른 thread" }

func syncPlain() { print("  sync nonisolated:", where_()) }
func asyncPlain() async { print("  async nonisolated:", where_()) }
@MainActor func syncMain() { print("  sync @MainActor:", where_()) }

// 부르는 함수가 main actor 에 있을 때
@MainActor func callSyncOnMain(_ f: @isolated(any) () -> Void) async { await f() }
@MainActor func callAsyncOnMain(_ f: @isolated(any) () async -> Void) async { await f() }

// 부르는 함수가 nonisolated async 일 때
func callSyncPlain(_ f: @isolated(any) () -> Void) async { await f() }

@main
struct App {
  @MainActor
  static func main() async {
    print("@MainActor 함수 안에서 부를 때")
    await callSyncOnMain(syncPlain)
    await callAsyncOnMain(asyncPlain)
    await callSyncOnMain(syncMain)
    print("nonisolated async 함수 안에서 부를 때")
    await callSyncPlain(syncPlain)
    await callSyncPlain(syncMain)
  }
}

pthread_main_np() 는 지금 thread 가 main thread 이면 0 이 아닌 값을 돌려주는 시스템 함수다. Foundation 을 가져오면 쓸 수 있다.

1
xcrun swiftc -parse-as-library -swift-version 6 Common.swift Runtime.swift -o runtime
1
./runtime
1
2
3
4
5
6
7
@MainActor 함수 안에서 부를 때
  sync nonisolated: 다른 thread
  async nonisolated: 다른 thread
  sync @MainActor: main thread
nonisolated async 함수 안에서 부를 때
  sync nonisolated: 다른 thread
  sync @MainActor: main thread

@MainActor 로 표시한 함수는 어디서 부르든 main thread 에서 돈다. 이것이 @isolated(any) 가 하는 일이다. nonisolated 함수는 @MainActor 함수 안에서 불러도 main thread 가 아니라 다른 thread 에서 돈다. 동기 함수와 async 함수가 같고, 부르는 쪽 자리가 main actor 이든 nonisolated async 함수이든 결과는 같다. 이 코드는 Swift 6 모드에서 진단이 없고, Swift 5 complete 에서는 26:11 에 sending value of non-Sendable type '() -> ()' risks causing data races; this is an error in the Swift 6 language mode warning 이 하나 나온다.

컴파일러가 어떤 코드를 만드는지는 SIL 로 본다. 함수 이름 mangling 에 모듈 이름이 들어가므로 모듈 이름을 rt 로 지정해 뽑았다.

1
xcrun swiftc -emit-sil -parse-as-library -wmo -module-name rt -swift-version 6 Common.swift Runtime.swift -o rt.sil

callSyncOnMain 의 SIL 에서 핵심 줄만 옮긴다.

1
2
3
4
5
6
7
8
9
10
// callSyncOnMain(_:)
// Isolation: global_actor. type: MainActor
sil hidden @$s2rt14callSyncOnMainyyyyYAXEYaF : $@convention(thin) @async (@guaranteed @isolated(any) @noescape @callee_guaranteed () -> ()) -> () {
  ...
  %5 = function_extract_isolation %0              // user: %6
  hop_to_executor %5                              // id: %6
  %7 = apply %0() : $@isolated(any) @noescape @callee_guaranteed () -> ()
  hop_to_executor %4                              // id: %8
  ...
}

function_extract_isolation 은 함수 값에서 isolation 을 꺼내는 SIL 명령이고, hop_to_executor 는 그 isolation 의 executor 로 건너가는 명령이다. 이 줄들이 .isolation 이 실제 코드에서 하는 일이다. 순서는 이렇다. 호출 전에 함수 값에서 isolation 을 꺼내고, 그 executor 로 건너가고, 함수를 부르고, 끝나면 %4(부른 쪽의 MainActor)로 돌아온다. nil 인 함수도 같은 명령을 지난다. nil 이면 generic executor 로 건너가므로 main thread 에 남지 않는다. 위 출력의 “다른 thread” 가 그 결과다.


호출할 때의 Sendable 검사

@isolated(any) 함수를 부르는 것은 isolation 이 다른 함수를 부르는 것과 같은 규칙으로 검사된다. 인자와 결과는 경계를 넘는 값으로 보고, non-Sendable 이면 진단이 난다. 제안서의 Isolation checking 은 이렇게 적는다. 함수 값 자체가 Sendable 이어야 하는 경우도 있다. 함수가 async 이고 부르는 문맥이 정적으로 nonisolated 가 아닐 때다. 각주는 actor 에 isolated 된 함수는 원래 Sendable 로 다룬다고 덧붙인다.

인자 쪽부터 본다. CallSend.swift 는 같은 함수를 nonisolated 자리와 main actor 자리에서 부른다.

CallSend.swift

1
2
3
4
5
6
7
8
9
10
11
12
@MainActor var shared = NonSendable()

// nonisolated 자리에서 부를 때
func fromNonisolated(_ f: @isolated(any) (NonSendable) -> Void) async {
  await f(NonSendable())
}

// @MainActor 자리에서, main actor 가 가진 값을 넘길 때
@MainActor
func fromMain(_ f: @isolated(any) (NonSendable) -> Void) async {
  await f(shared)
}

fromNonisolated 는 방금 만든 값을 넘기니 조용하다. fromMain 은 main actor 가 가진 non-Sendable 값을 @isolated(any) 함수에 넘기는데, 그 함수가 어느 isolation 에서 돌지 모르므로 Swift 6 모드에서 error 다.

1
2
3
4
5
6
7
8
9
10
11
CallSend.swift:11:9: error: sending value of non-Sendable type 'NonSendable' risks causing data races [#RegionIsolation::SendingRisksDataRace]
 9 | @MainActor
10 | func fromMain(_ f: @isolated(any) (NonSendable) -> Void) async {
11 |   await f(shared)
   |         |- error: sending value of non-Sendable type 'NonSendable' risks causing data races [#RegionIsolation::SendingRisksDataRace]
   |         `- note: sending main actor-isolated value of non-Sendable type 'NonSendable' to @isolated(any) callee risks causing races in between main actor-isolated and @isolated(any) uses
12 | }
13 | 

[#RegionIsolation]: <https://docs.swift.org/compiler/documentation/diagnostics/region-isolation>
[#SendingRisksDataRace]: <https://docs.swift.org/compiler/documentation/diagnostics/sending-risks-data-race>

Swift 5 complete 에서는 같은 자리가 warning 이고, Swift 5 모드는 진단이 없다. note 의 to @isolated(any) callee 가 이 호출을 가리키는 말이다. 호출을 받는 쪽이 @isolated(any) 라서 어디서 돌지 모른다는 점이 그대로 진단에 들어갔다.

함수 값 자체를 부를 때의 검사는 세 모양으로 확인했다.

CallValue.swift

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// 함수 값 자체를 보내야 하는가
@MainActor
func mainSync(_ f: @isolated(any) () -> Void) async {
  await f()
}

@MainActor
func mainAsync(_ f: @isolated(any) () async -> Void) async {
  await f()
}

func nonisolatedAsync(_ f: @isolated(any) () async -> Void) async {
  await f()
}

세 함수 모두 모든 모드에서 진단이 0 개다. 인자가 없는 호출은 막히지 않는다는 뜻이다.

반대로 @isolated(any) 값을 @Sendable 이 필요한 자리에 넘기는 것은 막힌다.

NotSendable.swift

1
2
3
4
5
6
7
8
9
func needsSendable(_ f: @escaping @Sendable () async -> Void) {}

func pass(_ f: @escaping @isolated(any) () async -> Void) {
  needsSendable(f)
}

func passSendable(_ f: @escaping @Sendable @isolated(any) () async -> Void) {
  needsSendable(f)
}

Swift 6 모드의 진단이다.

1
2
3
4
5
6
7
8
9
NotSendable.swift:4:17: error: passing non-Sendable parameter 'f' to function expecting a '@Sendable' closure
 1 | func needsSendable(_ f: @escaping @Sendable () async -> Void) {}
 2 | 
 3 | func pass(_ f: @escaping @isolated(any) () async -> Void) {
   |             `- note: parameter 'f' is implicitly non-Sendable
 4 |   needsSendable(f)
   |                 `- error: passing non-Sendable parameter 'f' to function expecting a '@Sendable' closure
 5 | }
 6 |

Swift 5 와 Swift 5 complete 는 같은 4:17 에 warning: passing non-Sendable parameter 'f' to function expecting a '@Sendable' closure 가 나온다. passSendable 은 모든 모드에서 조용하다. 두 함수의 차이는 @Sendable 을 직접 적었는지뿐이다. 같은 측정이 SE-0434 글에도 있으니 필요하면 @Sendable @isolated(any) 로 둘 다 적는다는 것만 기억하면 된다.


Task 생성 함수의 isolated(any)

이 제안이 겨냥하는 곳은 표준 라이브러리의 task 생성 함수다. 6.4 SDK 의 _Concurrency.swiftinterface 에서 @isolated(any) 가 들어간 줄은 58 줄이다. 그중 한 줄은 deprecated 메시지 문구이므로 선언은 57 개다. Task.init 은 이렇게 선언되어 있다.

1
@_alwaysEmitIntoClient public init(name: Swift::String? = nil, priority: _Concurrency::TaskPriority? = nil, @_inheritActorContext @_implicitSelfCapture operation: sending @escaping @isolated(any) () async -> Success) {

operation 이 sending @escaping @isolated(any) 다. 본문에는 이런 줄이 있다.

1
2
let builtinSerialExecutor =
  Builtin.extractFunctionIsolation(operation)?.unownedExecutor.executor

operation 의 isolation 을 꺼내서 그 executor 를 새 task 의 시작 executor 로 넘긴다. 그래서 앞의 TaskOrder 에서 @isolated(any) wrapper 가 0 곳이었다. isolation 을 nil 로 넘기면 initialSerialExecutor 가 비어서 전역 풀에서 시작하고, MainActor 를 넘기면 main actor 의 queue 에 바로 들어간다. Task.detached, 네 종류의 task group(TaskGroup, ThrowingTaskGroup, DiscardingTaskGroup, ThrowingDiscardingTaskGroup)의 addTask 와 addTaskUnlessCancelled(executorPreference 가 있는 것과 없는 것 모두)도 sending @escaping @isolated(any) 를 받는다. Task.immediate, Task.immediateDetached, addImmediateTask, addImmediateTaskUnlessCancelled 도 sending @escaping @isolated(any) 를 받는다. 다만 이 immediate 계열은 executorPreference 를 함께 받고, Task.immediate 와 Task.immediateDetached 는 @_inheritActorContext(always) 가 붙어 있다. addImmediateTask 와 addImmediateTaskUnlessCancelled 는 Task.init 처럼 @_inheritActorContext 다. 옛 이름인 detach, runDetached, asyncDetached 와 async 는 __owned @escaping @isolated(any) @Sendable 이다. 이 함수들은 deprecated 가 붙어 있다. .isolation 과 같은 일을 하는 extractIsolation 이라는 함수도 deprecated 로 남아 있고, 붙은 메시지는 다음과 같다.

1
Use `.isolation` on @isolated(any) closure values instead.

6.4 SDK 는 .isolation 을 쓰라고 안내한다.


시작 executor 의 예외 둘

task 함수는 formal dynamic isolation 의 executor 에서 시작한다. 예외는 둘이다. nonisolated 함수와, isolation 이 암묵적으로만 정해진 closure 다. 암묵적이라는 것은 isolated capture 를 명시하지 않았고 global actor 속성도 없다는 뜻이고, 지금은 Task {} 가 여기에 해당한다. 이 경우 Swift 는 closure 를 다른 곳에서 시작해도 된다. pitch 에서 bjhomer 가 이 예외를 물었고(pitch #8), John McCall 은 Task {} 가 성능 함정이 되지 않게 하려는 것이라고 답했다(pitch #10). actor 의 안에서 Task {} 를 쓰면 closure 가 그 actor 의 formal isolation 이 되는데, 이를 꼭 actor 의 queue 에 먼저 올려야 하면 queue 의 앞선 일이 다 끝날 때까지 새 task 가 기다린다. 특히 main actor 에서 그렇다는 것이다. 그래서 암묵적 isolation 인 경우는 최적화를 허락한다.


isolation 을 명시한 task 의 순서

앞의 순서 실험은 세 경우가 모두 { @MainActor in } 로 isolation 을 명시했다. 명시된 isolation 은 시작 executor 가 보장되므로, task 는 만든 순서대로 main actor 에서 시작한다. 암묵적인 Task {} 만 최적화로 그 단계를 건너뛸 수 있다. cal 이 swift-async-queue 로 순서를 다루는 코드를 들고 와서 물었고(pitch #28), John McCall 은 이렇게 답했다(pitch #32). 암묵적 isolation 인 closure 도 formally 는 main actor 에 isolated 이므로, 그 task 들은 main actor 에 동기적으로 enqueue 되고 main actor 의 queue 는 FIFO 이며, 이어서 counter 로 건너가는데 우선순위가 같아서 원래 순서가 유지된다. 다만 closure 가 main actor 에 명시적으로 isolated 된 것이 아니라서 Swift 가 main actor 에 올리는 단계를 건너뛰고 counter 로 바로 갈 수 있고, 그것이 한 반복문 안의 closure 마다 다르게 일어나면 이론상 순서가 달라진다. 그는 이것을 막으려면 closure 의 isolation 을 명시하라고 했고, 가능하면 counter 로 적으라고 했다. 현재 함수가 @MainActor 가 아니면 closure 는 formally nonisolated 이므로 순서를 얻으려면 반드시 명시해야 한다. 그의 결론은 “if you want the ordering guarantee, you should be explicit about the isolation of your tasks” 라는 한 줄이다. 이 답에 cal 은 크게 개선된 것이라고 답했다(pitch #33).


wrapper 를 만들 때

noremac 은 Task.init 이 앞으로 @isolated(any) 형태가 되는지 묻고, 언제 쓰면 좋은지 설명하는 절을 요청했다(pitch #14). John McCall 은 논리적으로는 그렇지만 표준 라이브러리가 Sendable 을 명시적으로 계속 적는 이유가 “feature suppression” 이라고 설명했다. 옛 컴파일러가 새 .swiftinterface 를 읽을 수 있어야 해서다(pitch #16). 그의 권고는 task 를 만드는 wrapper 를 쓰면 @isolated(any) 함수를 받게 하라는 것이다. 제안서의 When to use 도 같은 취지다. task 를 만드는 wrapper 와, 병렬 map 같은 병렬 알고리즘에 쓴다. 병렬이 아닌 map 은 non-Sendable 함수를 받는 편이 낫고, UI 이벤트 핸들러나 actor 의 run 처럼 특정 isolation 에서 부르는 API 에도 맞지 않는다.


task executor 와 함께 쓸 때

jamieQ 는 SE-0417 의 task executor preference 와 어떻게 어울리는지 물었고, 우선순위 순서 같은 거시적 동작이 바뀔 수 있다는 걱정도 보탰다(리뷰 #17). John McCall 은 둘이 충돌하면 함수의 isolation 이 이겨야 하지만, 항상 충돌하는 것은 아니라고 답했다. actor 는 기본으로 task executor 에서 돌기 때문이다(리뷰 #18). 스케줄링이 달라지면 이론상 기존 코드가 달라질 수 있지만 그 때문에 걱정할 일은 아니라고 덧붙였다(리뷰 #19).


Task wrapper 와 inheritActorContext

Task.init 의 선언에는 @_inheritActorContext 가 붙어 있다. 이 속성은 closure 가 만들어지는 곳의 actor isolation 을 물려받게 한다. 밑줄이 붙어서 공식 문서에는 없지만, 표준 라이브러리가 쓰는 속성이다. 직접 만든 wrapper 에도 붙일 수 있다.

InheritCtx.swift

1
2
3
4
5
6
7
8
9
10
func myTask(@_inheritActorContext _ op: sending @escaping @isolated(any) () async -> Void) -> Task<Void, Never> {
  Task(operation: op)
}

actor Worker {
  var n = 0
  func start() {
    myTask { self.n += 1 }
  }
}

모든 모드에서 진단은 myTask 의 결과를 쓰지 않았다는 warning 하나뿐이다.

1
2
3
4
5
6
7
8
InheritCtx.swift:8:5: warning: result of call to 'myTask' is unused [#NoUsage]
 6 |   var n = 0
 7 |   func start() {
 8 |     myTask { self.n += 1 }
   |     `- warning: result of call to 'myTask' is unused [#NoUsage]
 9 |   }
10 | }
[#NoUsage]: <https://docs.swift.org/compiler/documentation/diagnostics/no-usage>

self.n 을 바꾸는 closure 가 non-Sendable 인데도 sending 이라서 막히지 않는다. @_inheritActorContext 가 closure 에 Worker 의 isolation 을 물려주고, @isolated(any) 가 그 isolation 을 타입에 담아 Task 까지 건네기 때문이다. 이 두 속성이 함께 있어야 wrapper 가 Task {} 와 같은 모양으로 쓰인다.


배포 대상 OS

@isolated(any) 는 런타임 지원이 필요한 타입이다. macOS 15 보다 낮은 배포 대상으로 컴파일하면 제안서가 말한 제약이 그대로 나온다. 제안서는 [@isolated(any) () async -> Void] 처럼 @isolated(any) 를 generic 인자로 쓰거나 Any 로 감싸는 데 macOS 15 가 필요하고, 우회는 필드 하나짜리 struct 로 감싸는 것이라고 한다.

BackDeploy.swift

1
2
3
4
5
6
7
8
9
10
11
12
struct Holder {
  var ops: [@isolated(any) () async -> Void] = []
}

func call(_ f: @isolated(any) () -> Void) async {
  _ = f.isolation
  await f()
}

func store(_ f: @escaping @isolated(any) () -> Void) -> Any {
  f
}
1
xcrun swiftc -emit-sil -o /dev/null -parse-as-library -wmo -swift-version 6 -target arm64-apple-macos14.0 Common.swift BackDeploy.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
BackDeploy.swift:2:48: error: runtime support for '@isolated(any)' function types is only available in macOS 15.0.0 or newer
 1 | struct Holder {
   |        `- note: add '@available' attribute to enclosing struct
 2 |   var ops: [@isolated(any) () async -> Void] = []
   |                                                `- error: runtime support for '@isolated(any)' function types is only available in macOS 15.0.0 or newer
 3 | }
 4 | 
BackDeploy.swift:2:7: error: runtime support for '@isolated(any)' function types is only available in macOS 15.0.0 or newer
 1 | struct Holder {
   |        `- note: add '@available' attribute to enclosing struct
 2 |   var ops: [@isolated(any) () async -> Void] = []
   |       `- error: runtime support for '@isolated(any)' function types is only available in macOS 15.0.0 or newer
 3 | }
 4 | 
BackDeploy.swift:11:3: error: runtime support for '@isolated(any)' function types is only available in macOS 15.0.0 or newer
 8 | }
 9 | 
10 | func store(_ f: @escaping @isolated(any) () -> Void) -> Any {
   |      `- note: add '@available' attribute to enclosing global function
11 |   f
   |   |- error: runtime support for '@isolated(any)' function types is only available in macOS 15.0.0 or newer
   |   `- note: add 'if #available' version check
12 | }
13 | 

error 는 세 곳이다. 배열에 담은 타입이 2:48 과 2:7(저장 프로퍼티)에서, Any 로 감싼 f 가 11:3 에서 나온다. 반면 call 은 .isolation 을 읽고 await 로 불러도 진단이 없고, parameter 로만 받는 것도 괜찮다. 이 타입을 런타임에 메타데이터로 만들어야 하는 자리만 막힌다. -target arm64-apple-macos15.0 으로 바꾸면 출력 없이 exit 0 이다.


기대 효과

  • isolation 이 타입에 남는다. 고차 함수가 @isolated(any) 로 함수를 받으면 @Sendable () async 로 지울 때 잃던 isolation 을 그대로 들고 있다. 앞의 Erase 에서 본 두 길이 모두 막힌 자리가 이 타입 하나로 열린다.
  • 부르는 쪽이 신경 쓸 일이 줄어든다. await f() 한 줄이면 컴파일러가 function_extract_isolation 과 hop_to_executor 로 함수의 isolation 으로 건너갔다가 돌아온다.
  • Task 가 올바른 queue 에서 시작한다. Task.init, Task.detached, task group 의 addTask 가 모두 isolation 을 꺼내서 쓴다. 이 글의 순서 실험에서 지운 wrapper 가 수백 곳에서 순서를 뒤집었고, @isolated(any) wrapper 는 0 곳이었다.
  • wrapper 를 쓰는 비용이 사라진다. 사용자 코드의 Task {} 는 그대로 두고, wrapper 만 받는 parameter 타입을 sending @escaping @isolated(any) () async -> Void 로 바꾸면 된다.
상황지금까지@isolated(any)
actor 에 묶인 closure 를 받는 범용 함수동기 타입은 변환이 막히고 @Sendable () async 로 지우는 길은 non-Sendable 진단이 난다타입이 isolation 을 들고 있어 그대로 받는다
받은 함수의 isolation 을 알고 싶을 때알 방법이 없다.isolation 으로 (any Actor)? 를 읽는다
함수를 부를 때 어느 actor 로 건너가야 하나부르는 쪽이 알아서await 만 쓰면 컴파일러가 처리
wrapper 로 만든 Task 의 시작 위치전역 풀을 거쳐 순서가 뒤집힐 수 있다isolation 의 queue 에 바로 들어간다

다른 선택지는 왜 안 됐나

이 제안의 대안은 세 갈래다. 처음 검토된 제안서는 @Sendable 을 자동으로 붙였고, 수락 때 빠졌다. 철자는 리뷰 내내 논의됐고, 마지막에 @isolated(any) 가 유지됐다. Task 만 컴파일러가 특별 취급하자는 안은 pitch 에서 나왔다.


@Sendable 을 자동으로 붙이는 방법

리뷰 때의 제안서 는 @isolated(any) 함수가 암묵적으로 @Sendable 이라고 적었다. 수락 글은 이 추론을 빼고 수락했다. Doug Gregor 는 이 규칙이 non-Sendable 인 @isolated(any) 는 쓸모가 없다는 가정에서 나왔는데, SE-0414 의 region based isolation 과 후속인 SE-0430 이 있는 지금은 그 가정이 맞지 않다고 설명했다. 그래서 @isolated(any) 도 다른 함수 타입처럼 @Sendable 을 붙일 수도 있고 안 붙일 수도 있다.

이 결정의 흔적이 이 글에 이미 여러 번 나왔다. Basic 의 sending 경로, NotSendable 의 error, BasicNonsending 의 진단 0 개가 모두 @isolated(any) 함수 값이 non-Sendable 일 수 있다는 전제 위에 있다. SE-0434 글에서도 이 함의가 빠진 것을 확인했다.


다른 철자

@isolated(any) 라는 철자는 리뷰의 중심이었다. 불만은 두 갈래였다.

  • Dmitriy_Ignatyev 는 @isolated(MainActor) 처럼 통일된 철자를 물었고(리뷰 #3, #5), John McCall 은 @MainActor 가 isolation 속성이라는 것을 사람들이 이해하는 데 어려움이 없다며, 이런 인위적인 스타일 충돌은 피하려 한다고 답했다(리뷰 #4). 그는 같은 답에서 제네릭 global actor 를 어떻게 적을지(@Self 나 @isolated(globalActor: Self))가 열린 문제라고 짚었다. ktoso 는 @isolated(to: MainActor.shared) 를 GlobalActor.assumeIsolated 에 쓸 수 있다고 제안했다(리뷰 #7). 타입 이름 자체를 속성 인자로 쓰는 특수한 철자에는 반대했다. Swift 는 보통 TheType.self 로 쓰기 때문이다(리뷰 #9).
  • 리뷰 후반에 John McCall 이 철자를 다시 열었다(리뷰 #20). @isolated 는 @isolated(caller), @isolated(to: value) 같은 이름 공간이 될 텐데, @ 를 빼면 isolated parameter(타입에 안 드러난다)와 isolated(any)(타입의 일부)가 헷갈린다. 그래서 @dynamicallyIsolated 도 후보였다. Jon_Shier 는 @isolated 가 인자를 받는 점이 좋다고 했고(리뷰 #21), Doug Gregor 는 Isolated 접미사 속성이 여럿 생기는 것이 @ 유무의 혼동보다 나쁠 것 같다고 했다(리뷰 #22). 도구가 @ 를 붙이고 떼어 줄 수 있다는 점도 짚었다. Nickolas_Pohilets 는 @isolated(any) 와 장기적인 @isolated(arg) 를 지지했다(리뷰 #23). wadetregaskis 는 parameter modifier 보다 함수 수준에 두는 것이 합리적이라고 말했다(리뷰 #24).

수락 글은 이렇게 정리한다. @ 를 빼서 isolated parameter 와 겉보기를 맞추면 파싱 모호성이 생기고 함수 타입의 일부라는 점이 흐려진다. @dynamicallyIsolated 같은 이름은 새 속성이 여럿 있다는 인상을 준다. @isolated(...) 는 같은 문법 안에서 앞으로 넓힐 여지를 남긴다. 앞에서 본 파서 메시지 'isolated' is a declaration modifier, not an attribute 가 이 혼동의 다른 면이다.

사용법을 헷갈린 기록도 있다. stephencelis 는 closure.isolated 로 접근하지 못했고(리뷰 #25), hborla 가 .isolated 가 아니라 .isolation 이라고 바로잡았다(리뷰 #27). jamieQ 는 { @MainActor in } closure 에서 op.isolation ?? "nil" 이 Swift.MainActor 를 출력한다고 보고했다(리뷰 #26). 이 글의 Iso 실행에서도 타입 이름이 MainActor 로 나오는 것과 이어진다.


컴파일러가 Task 생성 함수만 특별 취급하는 방법

“그냥 컴파일러가 Task 만 알아서 처리하면 되지 않나” 는 의문이 pitch 에 나왔다. Nickolas_Pohilets 가 비슷한 질문을 했고(pitch #18), John McCall 은 그 용도 하나뿐이면 컴파일러에 박아 넣을 수 있었겠지만 일반 기능이면 API 별 컴파일러 마법 없이 보장이 가능하다고 답했다(pitch #19).

async let 은 이야기가 다르다. ktoso 는 async let 도 Task {} 처럼 전역 풀에 먼저 들어간 뒤 actor 로 건너간다고 짚었고(pitch #3), John McCall 은 async let 이 언어에 내장되어 있어서 formal isolation 에서 시작하는 일은 내장 로직으로 만들어야 하고 @isolated(any) 가 필요 없다고 답했다(pitch #4). ktoso 는 지금 async let 의 task 가 nonisolated 로 취급된다고 확인했고(pitch #5), 따로 분리해도 좋다고 했다(pitch #7). John McCall 은 async let 이 명시적인 함수나 closure 없이 task 를 만드는 유일한 방법이라는 점도 짚었다(pitch #9).

pitch 의 다른 줄기는 enqueue 였다. task 를 isolation 의 queue 에 직접 enqueue 하게 되면, SE-0392 의 enqueue 문구가 job 을 enqueue 안에서 동기로 실행해도 된다고 읽힌다는 문제가 드러난다. John McCall 이 이를 짚었고(pitch #22), FranzBusch 는 NIO 에서 직접 겪은 메모리 손상 때문에 항상 queue 에 넣는다고 했으며(pitch #23), ktoso 는 의도한 문구가 아니라 표현의 실수라고 보았다(pitch #25).


앞으로의 방향

제안서는 후속 가능성 세 가지를 남긴다. assumeIsolated 와 함께 쓰기, 정적으로 isolation 이 정해진 함수 타입, 값 일반으로 넓히기다.


assumeIsolated 와 함께 쓰기

.isolation 을 꺼냈으면, 그 actor 에서 이미 돌고 있다고 선언하고 동기로 바로 부르고 싶어진다. assumeIsolated(_:file:line:) 는 지금 이 actor 에서 돌고 있다고 가정하고 동기 closure 를 실행하는 함수다. 맞으면 closure 를 바로 실행하고, 아니면 멈춘다. 아래 코드가 그 시도다.

Assume.swift

1
2
3
4
5
6
7
func runNow(_ op: @isolated(any) () -> Void) {
  if let actor = op.isolation {
    actor.assumeIsolated { _ in op() }
  } else {
    op()
  }
}

모든 모드의 진단이다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Assume.swift:3:33: error: call to @isolated(any) parameter 'op' in a synchronous actor-isolated context [#ActorIsolatedCall]
1 | func runNow(_ op: @isolated(any) () -> Void) {
  |               `- note: calls to parameter 'op' from outside of its actor context are implicitly asynchronous
2 |   if let actor = op.isolation {
3 |     actor.assumeIsolated { _ in op() }
  |                                 `- error: call to @isolated(any) parameter 'op' in a synchronous actor-isolated context [#ActorIsolatedCall]
4 |   } else {
5 |     op()
Assume.swift:5:5: error: call to @isolated(any) parameter 'op' in a synchronous nonisolated context [#ActorIsolatedCall]
1 | func runNow(_ op: @isolated(any) () -> Void) {
  |               `- note: calls to parameter 'op' from outside of its actor context are implicitly asynchronous
2 |   if let actor = op.isolation {
3 |     actor.assumeIsolated { _ in op() }
4 |   } else {
5 |     op()
  |     `- error: call to @isolated(any) parameter 'op' in a synchronous nonisolated context [#ActorIsolatedCall]
6 |   }
7 | }
[#ActorIsolatedCall]: <https://docs.swift.org/compiler/documentation/diagnostics/actor-isolated-call>

assumeIsolated 의 closure 안에서도, nil 인 경우의 else 안에서도, 동기 문맥에서는 @isolated(any) 함수를 부를 수 없다. 컴파일러가 actor 가 op.isolation 에서 나왔다는 것을 closure 와 연결짓지 못한다. 제안서는 이 연결이 없어서 지금은 이 방식을 쓸 수 없다고 말하고, 방향도 정한다. isolation 검사가 isolated parameter 와 assumeIsolated 의 self 가 같은 값임을 알아보게 가르치는 것이다. ktoso 의 @isolated(to:) 제안(리뷰 #7)도 이 자리를 겨냥한 것이다.


정적으로 isolation 이 정해진 함수 타입

@isolated(any) 가 isolation 을 값으로 들고 다닌다면, 반대로 어떤 값에서 나온 isolation 을 타입에 고정하는 @isolated(to:) 도 생각해 볼 수 있다. 제안서는 이것을 value-dependent type 으로 설명하고, 만들 가능성이 낮다고 평가한다. @isolated(any) 가 existential 에 가깝다면 @isolated(to:) 는 그에 대응하는 generic 이다. dnadoba 가 이 생각을 다른 타입이나 generic 으로 넓히자고 했을 때(리뷰 #15), John McCall 은 generic 에서 추상적인 isolation 은 value-dependent type 이 필요한데 개념적으로 본래 어려워서 추진될 가능성이 낮다고 답했다(리뷰 #16).


값 일반으로 넓히기

Nickolas_Pohilets 는 함수가 아닌 값에도 같은 틀을 쓰자고 제안했다(pitch #34). let obj: @isolated(any) NonSendable = await a.getObject() 처럼 쓰고, await obj.foo() 가 obj.isolation 으로 건너가게 하자는 것이다. John McCall 은 흥미롭지만 함수와 방식이 다르다고 했다(pitch #35). 값을 만들 때는 늘 현재 문맥에서 값을 가져오는데, 함수는 만든 곳과 달라도 되는 고유 isolation 을 가지기 때문이다. Nickolas_Pohilets 는 비함수 값을 감싸는 것이 주된 쓰임이니 @Sendable 함의를 다시 생각해야 한다고 덧붙였다(pitch #36). 그러자 John McCall 은 @isolated(any) T 기능이 들어올 것 같지는 않다고 하면서, 라이브러리로 만들 수 있다고 했다(pitch #37). 그가 든 예가 IsolatedValue<Element> 라는 Sendable struct 다. nonisolated(unsafe) let value 와 let isolation: any Actor 를 들고, init(_:isolation: isolated any Actor = #isolation) 으로 만들고, withValue 로 접근하며, 짝이 되는 Actor extension 의 run 으로 실행한다. optional actor 로는 안전하지 않다는 단서도 붙었다. 이 이야기에는 SE-0420 글의 #isolation 이 그대로 쓰인다.


마이그레이션

SE-0431 은 source compatible 이다. 이미 쓰던 코드가 새 타입 때문에 깨지는 경우는 하나다. var fn = Task.init 처럼 인자 없이 Task.init 을 값으로 꺼내 쓰는 코드는 operation 의 타입이 바뀌어서 영향을 받을 수 있다고 제안서는 적는다. 그 밖에는 이 글에서 본 점을 옮기면 된다.

지금 쓰는 것바꿀 것
task 를 만드는 wrapper 의 @Sendable () async -> Void parametersending @escaping @isolated(any) () async -> Void
extractIsolation(_:)closure 값의 .isolation
actor 메서드 참조를 @isolated(any) 로 넘기는 코드{ self.method() } 처럼 closure 로 감싼다 (6.4 에서 메서드 참조의 isolation 은 nil)
@isolated(any) 를 동기 함수 타입으로 바꾸는 코드async 함수 타입으로 받거나 await 로 부른다 (6.4 에서 warning)
순서가 중요한 Taskisolation 을 명시한 Task { @MainActor in ... } (최적화 여지가 있어서 약속이 아니다)
macOS 15 보다 낮은 배포 대상에서 [@isolated(any) ...] 나 Any@available 로 막거나 필드 하나짜리 struct 로 감싼다

wrapper 의 parameter 를 @isolated(any) 로 바꾸면 안에서 Task(operation: op) 로 넘길 때 isolation 이 그대로 따라간다. 직접 .isolation 을 읽을 필요가 없다. 반대로 @Sendable () async 로 쓰던 wrapper 는 이 글의 첫 실험처럼 순서가 섞이는 자리에 서 있을 수 있다.


정리

  • 함수 타입에 isolation 을 값으로 남기는 속성이 @isolated(any) 다. .isolation 은 (any Actor)? 이고 nonisolated 는 nil, global actor 는 shared, actor 안의 self 를 쓰는 closure 는 그 actor 다.
  • 부를 때는 항상 await 가 필요하다. 6.4 의 SIL 은 function_extract_isolation 과 hop_to_executor 로 함수의 isolation 으로 건너가고, nonisolated 함수는 main actor 안에서 불러도 main thread 가 아닌 곳에서 돈다.
  • @MainActor 같은 global actor 나 isolated parameter 와는 함께 쓸 수 없고, 선언과 closure 에 직접 붙지 않는다. @isolated(any) 를 동기 함수 타입으로 바꾸는 것은 warning 이고 @MainActor () async 로는 error 다.
  • 6.4 에서 actor 안의 메서드 참조는 .isolation 이 nil 이다. @isolated(any) 로 받는 함수에서 부르면 actor 밖에서 돌 수 있어서, { self.method() } 처럼 closure 로 감싼다.
  • Task.init, Task.detached, task group 의 addTask 가 sending @escaping @isolated(any) 를 받는다. 새 task 가 함수의 isolation queue 에 바로 들어가서, 지운 wrapper 가 돌릴 때마다 수백 곳에서 순서를 뒤집던 것이 0 곳이 됐다. isolation 을 명시한 task 는 시작 executor 가 보장되어 만든 순서가 유지되고, 암묵적인 Task {} 만 그 단계를 건너뛸 수 있다.
  • 수락 때 @Sendable 함의가 빠졌고 철자 @isolated(any) 는 유지됐다. 후속으로 assumeIsolated 와의 연결, @isolated(to:), 값 일반으로의 확장이 거론되지만 모두 확정은 아니다.

관련 글


참고자료

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