포스트

[SE-0420] Inheritance of actor isolation

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


제안서 정보

  • 번호: SE-0420
  • 상태: Implemented (Swift 6.0)
  • upcoming feature flag: 없음 (리뷰 때는 experimental feature flag OptionalIsolatedParameters 로 써 볼 수 있었고, 6.0 에서 정식 기능이 되었다)
  • 저자: John McCall, Holly Borla, Doug Gregor
  • 리뷰 매니저: Xiaodi Wu
  • pitch: Pitch (2023-11-10)
  • 리뷰: Review (2024-01-25 시작, 02-06 까지)
  • 수락: Accepted (2024-02-07, 제안서 그대로 수락)
  • 전제 제안서: SE-0412, SE-0414 (region based isolation), SE-0430 (sending)

한 줄 요약

async 함수가 자기를 부른 쪽의 actor 에 그대로 남게 하는 방법이다. SE-0313 의 isolated parameter 를 optional 과 any Actor 로 넓히고, 부르는 쪽의 isolation 으로 자동으로 펼쳐지는 #isolation 매크로를 기본 인자로 쓰면, 호출할 때마다 isolation 이 함수에 저절로 넘어온다. 컴파일러는 그렇게 넘어온 isolation 을 “같은 isolation” 으로 알아봐서 non-Sendable 값이 경계를 넘는다는 진단을 내지 않는다.


어떤 문제였나

SE-0338 이후 Swift 에서 isolation 이 없는 async 함수(nonisolated async 함수)는 자기를 부른 actor 를 떠나서 돌아간다. 같은 모양의 동기 함수는 부른 쪽의 isolation 을 그대로 물려받는다. 이 비대칭 때문에 async 로 쓴 범용 도구 대부분이 actor 안에서 쓰기 어려웠다. 이 글에서 다루는 SE-0420 은 그 비대칭을 함수 선언 하나로 풀 수 있게 하는 제안이다.

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

  • SE-0412 글: global actor 와 isolation 이 무엇인지
  • SE-0414 글: non-Sendable 값을 “같은 region” 으로 묶어서 다른 isolation 으로 보내도 되는지 컴파일러가 판단하는 방식
  • SE-0430 글: 함수 경계를 넘어 값을 통째로 넘기는 sending

actor isolation 과 executor 란?

actor 는 자기 안의 상태를 한 번에 한 코드만 만지게 해 주는 타입이다. 은행 창구에서 번호표를 뽑고 한 명씩 들어가는 것과 같다. 어떤 함수가 그 창구 안에 있으면 “이 함수는 이 actor 에 isolated 되어 있다” 고 한다. 창구에 속하지 않은 함수는 nonisolated 라고 한다. 프로그램에 하나뿐인 actor 를 이름으로 가리키는 global actor 의 대표가 @MainActor 다.

executor 는 그 일을 실제로 돌리는 줄이다. 창구가 “누가 들어갈 수 있나” 를 정한다면, executor 는 “그 일을 어느 줄에서 처리하나” 를 정한다. main actor 의 executor 는 main thread 이고, 일반 actor 는 개념상 자기 전용 줄을 하나 가진다. 실제로 돌 때는 일반 actor 들이 전역 풀의 스레드를 나눠 쓴다. 아무 actor 에도 속하지 않은 일은 전역 동시 실행 풀(generic executor)에서 돈다.

await 로 다른 isolation 의 함수를 부르면 현재 task 는 멈추고(suspend), 그 함수의 executor 에서 다시 시작한다. 제안서 Motivation 은 이 전환에 비용이 있다고 짚는다. 두 함수의 isolation 이 다르면 task 를 멈췄다가 다른 executor 의 줄에 다시 세워야 할 수 있고, 그럴 필요가 없을 때도 전환에는 대개 오버헤드가 붙는다. 그리고 멈춘 사이에 같은 actor 의 다른 task 가 끼어들어서 actor 안의 값을 바꿔 놓을 수 있다. isolation 이 같은 함수끼리의 호출과 반환에서는 이 끼어들기가 일어나지 않는다고 제안서는 적는다.

제안서의 각주도 하나 짚어 둔다. 한쪽이 main actor 처럼 custom executor 를 쓰는 actor 에 isolated 되어 있으면 전환은 항상 일어난다. main actor 는 일이 반드시 main thread 에서 실행되게 하려고 custom executor 를 쓰기 때문이다. 그 밖의 actor 는 대개 다른 곳에서 그 actor 를 쓰고 있을 때(contended)만 전환이 일어난다.


동기 함수와 async 함수의 isolation 차이

제안서 Motivation 의 핵심은 동기 nonisolated 함수와 async nonisolated 함수가 다르게 행동한다는 것이다. 동기 nonisolated 함수는 부른 쪽의 isolation 을 동적으로 물려받는다. actor 의 메서드가 nonisolated 동기 함수를 부르면, 그 함수는 실행되는 동안 그 actor 에 isolated 된 것처럼 행동한다. 그 함수가 actor 의 저장 프로퍼티를 직접 읽을 수는 없지만(그러려면 정적으로 그 actor 에 isolated 되어야 한다), actor 에 속한 non-Sendable 값을 넘겨받고 돌려줄 수는 있다. 제안서는 actor 안의 non-Sendable 원소 배열에 map 을 쓰는 것이 그래서 되는 것이라고 설명한다.

6.4 에서 이를 확인했다. @MainActor 클래스 안에서 non-Sendable 원소 배열에 map, reduce, forEach 를 쓰는 코드다. 이 글의 코드는 모두 non-Sendable 값을 만드는 NonSendable 클래스를 같이 컴파일한다. 클래스 하나이고, value 를 가진다.

1
final class NonSendable { var value = 0 }
1
2
3
4
5
6
7
8
9
10
11
12
@MainActor final class Model {
  var items = [NonSendable(), NonSendable()]
  var total = 0

  func syncUse() {
    let values = items.map { $0.value }
    total = values.reduce(0, +)
    items.forEach { self.bump($0) }
  }

  func bump(_ ns: NonSendable) { ns.value += 1 }
}

진단은 -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 SyncInherit.swift

진단은 Swift 5, Swift 5 + -strict-concurrency=complete, Swift 6 세 모드 모두 0 개다. map 과 forEach 가 @MainActor 안의 non-Sendable 값을 받아도 경계를 넘는 것으로 보지 않는다. 동기 함수라서 부른 쪽의 isolation 을 물려받는 것으로 본다.

이 글에서 “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 글에서 더 자세히 풀었다.


async 함수가 actor 를 떠나는 모습

같은 동작을 async 함수로 쓰면 어떻게 되는지 보자. 아래 코드는 isolation 이 없는 async 함수 work(_:) 를 @MainActor 클래스의 run() 에서 부른다.

1
2
3
4
5
6
7
8
9
10
func work(_ ns: NonSendable) async -> NonSendable { ns }

@MainActor final class Model {
  var ns = NonSendable()

  func run() async {
    let result = await work(ns)
    print(result.value)
  }
}

Swift 6 모드의 진단이다.

1
2
3
4
5
6
7
8
9
10
11
Reset.swift:7:24: error: sending 'self.ns' risks causing data races [#RegionIsolation::SendingRisksDataRace]
 5 | 
 6 |   func run() async {
 7 |     let result = await work(ns)
   |                        |- error: sending 'self.ns' risks causing data races [#RegionIsolation::SendingRisksDataRace]
   |                        `- note: sending main actor-isolated 'self.ns' to @concurrent global function 'work' risks causing data races between @concurrent and main actor-isolated uses
 8 |     print(result.value)
 9 |   }

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

세 모드의 결과는 이렇다. 진단이 나오는 줄은 7:24 하나뿐이다.

모드진단
Swift 50 개
Swift 5 complete1 개 (warning, this is an error in the Swift 6 language mode 가 붙는다)
Swift 61 개 (error)

note 의 @concurrent 가 핵심이다. SE-0338 은 nonisolated async 함수가 부른 actor 를 떠나 generic executor 에서 돌게 했다. 6.4 의 진단은 그 상태를 @concurrent 라고 부른다. @concurrent 는 SE-0461 이 도입한 attribute 다. work(_:) 는 자기가 어느 actor 에도 묶여 있지 않으므로 호출은 “main actor 에서 @concurrent 로” 경계를 넘는 것이고, main actor 에 묶여 있는 non-Sendable 값 self.ns 를 그 경계 너머로 보내는 것이 되어 막힌다. work(_:) 가 하는 일이 ns 를 그대로 돌려주는 것뿐이어도 컴파일러는 안쪽을 보고 판단하지 않는다. 호출하는 자리에서 경계를 넘는지만 본다.

제안서는 이 막힘의 원인을 세 가지 제약으로 설명한다. isolated 함수에서 nonisolated async 함수를 부르면 (1) 결과가 Sendable 이어야 하고, (2) self 인자가 Sendable 이어야 하고, (3) 나머지 인자도 Sendable 이어야 한다. actor 안에서 async 범용 함수를 쓰려면 다루는 타입이 전부 Sendable 이어야 한다는 뜻이다. 그리고 비용이 있다. 제안서는 isolation 이 같은 호출이면 불필요한 전환이 없지만, async 함수가 위처럼 generic executor 로 갔다가 곧바로 다른 isolation 의 closure 를 부르면 “generic executor 로 갔다가 곧바로 closure 의 isolation 으로 돌아오는” 낭비가 생긴다고 적는다.


Motivation 의 AsyncStream 예제

제안서 Motivation 은 AsyncStream 의 iterator 로 이 문제를 보였다. @MainActor 함수에서 iterator.next() 를 부르는 예제다.

1
2
3
4
5
6
@MainActor func iterate(over stream: AsyncStream<Int>) async {
  var iterator = stream.makeAsyncIterator()
  while let element = await iterator.next() {
    print(element)
  }
}

AsyncStream 과 AsyncIteratorProtocol 로 값을 하나씩 받기

AsyncStream 은 값을 시간에 걸쳐 하나씩 내보내는 async 시퀀스다. makeAsyncIterator() 가 돌려주는 iterator 는 AsyncIteratorProtocol 을 따르고, next() 를 await 로 부를 때마다 다음 값(없으면 nil)을 준다. while let element = await iterator.next() 는 값이 끝날 때까지 도는 표준 모양이다. for await 는 이 모양을 대신 써 주는 문법이지만, 컴파일된 호출은 next() 가 아니라 next(isolation:) 이다. 이 함수는 아래 “표준 라이브러리의 #isolation” 에서 따로 본다.

6.4 에서 세 모드로 측정하면 이 예제는 진단이 0 개다. AsyncIteratorProtocol.next() 는 nonisolated async 함수이고 AsyncStream.Iterator 는 Sendable 이 아닌데도 통과하는 것은 SE-0414 의 region 분석 덕분이다. iterator 는 함수 안에서 makeAsyncIterator() 로 만든 지역 변수라서 다른 값과 이어지지 않은 독립된 region(disconnected region)에 있고, 그런 값은 isolation 경계를 넘겨도 된다. #isolation 과는 관계없는 통과다.

같은 next() 호출도 iterator 가 actor 에 묶여 있으면 막힌다. MotivationProperty.swift 는 iterator 를 @MainActor 클래스의 프로퍼티로 들고 있다.

1
2
3
4
5
6
7
8
9
10
11
@MainActor final class Reader {
  var iterator: AsyncStream<Int>.Iterator

  init(_ stream: AsyncStream<Int>) {
    iterator = stream.makeAsyncIterator()
  }

  func readOne() async -> Int? {
    await iterator.next()
  }
}

세 모드 모두 같은 error 다. Swift 6 모드는 같은 진단을 두 번 출력해서 한 번만 옮긴다.

1
2
3
4
5
6
7
8
9
10
MotivationProperty.swift:9:20: error: cannot call mutating async function 'next()' on actor-isolated property 'iterator' [#ActorIsolatedMutatingAsync]
 7 | 
 8 |   func readOne() async -> Int? {
 9 |     await iterator.next()
   |           |        `- error: cannot call mutating async function 'next()' on actor-isolated property 'iterator' [#ActorIsolatedMutatingAsync]
   |           `- note: 'iterator' can be concurrently accessed during mutation, risking data races
10 |   }
11 | }

[#ActorIsolatedMutatingAsync]: <https://docs.swift.org/compiler/documentation/diagnostics/actor-isolated-mutating-async>

프로퍼티는 main actor 에 묶여 있어서 await 로 nonisolated 함수를 부르는 사이 다른 곳에서 접근될 수 있고, 그래서 mutating 호출이 막힌다는 것이 note 의 내용이다. 이런 자리를 위해 AsyncIteratorProtocol 에는 부른 쪽 isolation 을 받는 next(isolation:) 가 프로토콜 요구사항으로 있다(SE-0421). 표준 라이브러리 쪽 변경은 SE-0420 리뷰에서 Jason_Gregori 가 AsyncSequence 에 적용하는 제안이 따로 있는지 물었을 때(리뷰 #25), hborla 가 SE-0421 로 리뷰 중이라고 답한 것(리뷰 #26)이다.


@_unsafeInheritExecutor 의 한계

SE-0420 이전에도 부른 쪽 isolation 을 물려받는 비공식 방법이 있었다. 밑줄이 붙은 attribute @_unsafeInheritExecutor 다. 표준 라이브러리의 withCheckedContinuation 같은 함수가 이것을 썼다.

1
2
3
4
@_unsafeInheritExecutor
func legacy(_ ns: NonSendable) async {
  ns.value += 1
}

6.4 에서 이 파일을 세 모드로 돌리면 같은 줄에 진단이 하나씩 나온다. Swift 5 와 Swift 5 complete 에서는 warning 이다.

1
UnsafeInherit.swift:2:6: warning: '@_unsafeInheritExecutor' is deprecated; consider an 'isolated' parameter defaulted to '#isolation' instead; this is an error in the Swift 6 language mode

Swift 6 모드에서는 error 다. 문장 끝의 this is an error in the Swift 6 language mode 만 빠지고 같다.

1
2
3
4
5
6
UnsafeInherit.swift:2:6: error: '@_unsafeInheritExecutor' is deprecated; consider an 'isolated' parameter defaulted to '#isolation' instead
1 | @_unsafeInheritExecutor
2 | func legacy(_ ns: NonSendable) async {
  |      `- error: '@_unsafeInheritExecutor' is deprecated; consider an 'isolated' parameter defaulted to '#isolation' instead
3 |   ns.value += 1
4 | }

진단 문구가 이 제안서가 가리키는 대안을 그대로 말한다. isolated parameter 를 #isolation 기본값으로 두라는 것이다.

이 attribute 의 문제는 pitch 와 리뷰에서 Realm 팀의 tgoyne 가 구체적으로 적었다. 받은 non-Sendable 객체를 deep copy 해서 @unchecked Sendable wrapper 에 담은 다음에 호출한 쪽을 풀어 주는 함수에 @_unsafeInheritExecutor 를 썼는데, 이 attribute 는 실제로 isolation 을 물려받는 것이 아니라서 await 뒤에 같은 executor 에서 재개되지 않아 쓰기에 error-prone 했고, 지금까지는 그 문제를 간신히 피해 왔다(dodged the problem)고 한다(pitch #6). 호출한 쪽 isolation 에서 non-Sendable 타입을 꺼내 쓰는 것도 이 attribute 로는 할 수 없다고 한다. 리뷰에서는 같은 이야기를 _unsafeInheritExecutor 를 공식 기능으로 바꾸는 쪽으로 정리했다(리뷰 #9). withCheckedContinuation 도 #isolation 을 써야 하지 않느냐는 이야기가 거기서 나왔다.


무엇이 바뀌나

제안서는 변화를 두 가지로 요약한다. 하나는 SE-0313 의 isolated parameter 가 optional 타입을 가질 수 있게 하는 것이고, 다른 하나는 default argument 표현식에 #isolation 이라는 특별한 형태를 허용하는 것이다. 설계 접근도 같은 순서다. 먼저 함수가 임의의 동적 isolation 을 가질 수 있게 하고(isolation 에 대한 다형성), 그 isolation 이 호출에서 자동으로 전파되게 하는 장치를 더하고, 마지막으로 컴파일러가 “부른 쪽의 isolation 을 그대로 넘겼다” 는 것을 충분히 알아볼 수 있는 모양일 때 callee 가 현재 context 와 같은 isolation 이라고 판단하게 한다.


isolated parameter 의 일반화

SE-0313 은 함수가 특정 actor 에 isolated 되는 방법으로 isolated parameter 를 도입했다. 정의는 이렇다. isolated 가 붙은 parameter 로 받은 actor 에 함수 본문이 isolated 된다. 예를 들어 func report(_ account: isolated Account) 의 본문은 account 에 isolated 되어 있어서 await 없이 account 의 프로퍼티를 읽고 쓴다. 제안서의 설명으로는 isolation 은 값에 의존한다. actor 의 메서드는 “그 타입의 아무 actor” 가 아니라 “그 구체적인 인스턴스” 에 isolated 되는 것이므로, generic 만으로는 표현할 수 없고 parameter 로 받는 것이 자연스럽다. 이 제안서가 한 일은 그 isolated parameter 의 타입 제한을 풀어 준 것이다. 전에는 구체적인 actor 타입이나 Actor 를 함의하는 protocol 타입만 되었는데, 두 가지가 바뀐다.

  • isolated (any Actor)? 처럼 optional 이 허용된다. isolation 이 없는 함수(nonisolated)도 같은 parameter 로 표현하려면 nil 이 필요하기 때문이다. 인자가 nil 이면 함수는 동적으로 nonisolated 인 것처럼 행동하고, async 함수면 SE-0338 에 따라 isolation 을 reset 한다. 인자가 nil 이 아니면 그 actor 에 isolated 인 것처럼 행동한다.
  • any Actor 라는 existential(어떤 actor 든 담는 타입)을 쓸 수 있다. 어떤 actor 든 받아서 그 actor 의 isolation 으로 돌게 하려는 것이다.

제안서의 Design approach 를 풀면 이렇다. global actor 에 isolated 되는 것도 실제 실행에서는 “global actor 의 shared 인스턴스에 isolated” 인 것이라서, 함수의 동적 isolation 은 어떤 경우에도 “optional actor 참조 하나” 로 표현된다. nil 이 isolation 없음이다. 그래서 (any Actor)? 한 타입이 세 가지 경우를 다 담는다.

robert.ryan 은 리뷰에서(리뷰 #20), wadetregaskis 는 pitch 에서(pitch #2) 이 설계의 약점을 짚었다. 함수가 받는 isolation parameter 를 함수 안에서 쓰지 않는 경우가 많다는 것이다. 제안서도 약점을 세 가지로 적는다. 첫째, 가장 많을 것으로 예상하는 “부른 쪽 isolation 을 물려받기” 가 쓰기에 번거롭다. 둘째, 계산 프로퍼티의 getter 처럼 parameter 를 추가할 수 없는 자리가 있다. 셋째, actor 참조를 넘기면 실제 executor 를 꺼내려고 동적 디스패치를 한 번 해야 해서, 필요한 UnownedSerialExecutor? 를 그대로 넘기는 것보다 효율이 떨어진다. 이 세 가지는 뒤의 “함수 단위 표시” 와 SE-0461 로 이어진다.


#isolation 매크로와 기본 인자

parameter 를 받는다고 해도 부르는 쪽이 매번 isolation: self 를 쓰라고 하면 쓸 수 없다. 그래서 제안서의 두 번째 변화가 있다. #isolation 은 매크로다. 매크로는 컴파일할 때 그 자리에 코드를 채워 넣는 표시이고, #line, #file 처럼 # 으로 시작한다. #isolation 은 호출하는 자리의 isolation 을 나타내는 표현식으로 펼쳐진다. 이것을 isolated parameter 의 기본 인자로 두면, 부르는 쪽이 아무것도 쓰지 않아도 자기 isolation 이 함수에 넘어간다.

Reset 의 work(_:) 에 parameter 하나만 더한 것이 이 코드다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
func work(_ ns: NonSendable, isolation: isolated (any Actor)? = #isolation) async -> NonSendable {
  ns.value += 1
  return ns
}

@MainActor final class Model {
  var ns = NonSendable()

  func run() async {
    let result = await work(ns)
    print(result.value)
  }
}

actor Worker {
  var ns = NonSendable()

  func run() async {
    let result = await work(ns)
    print(result.value)
  }
}

호출하는 줄은 await work(ns) 로 Reset 과 같다. 세 모드 모두 진단이 0 개다. 호출하는 쪽이 @MainActor 클래스든 actor Worker 든 같다. work 가 non-Sendable 인 ns 의 value 를 바꾸고 돌려주는데도 경계를 넘지 않는 것으로 본다. work 가 부른 쪽의 isolation 에서 돌기 때문이다.

nonisolated async 함수는 부른 actor 를 떠나 다른 executor 에서 돌지만, isolated (any Actor)? = #isolation parameter 가 있으면 부른 쪽 actor 에 남는다. 위쪽은 parameter 가 없는 work 가 Reset.swift 7:24 에서 error 가 나고, 아래쪽은 parameter 를 더한 work 가 Inherit.swift 에서 진단 0 개인 것을 보여 준다.


#isolation 이 펼쳐지는 값

#isolation 이 실제로 무엇으로 펼쳐지는지 보려고 받은 isolation 의 타입 이름을 출력하는 함수를 만들었다. Macro.swift 이고 @main 을 가진다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
func whereAmI(_ label: String, isolation: isolated (any Actor)? = #isolation) async {
  print(label, isolation.map { String(describing: type(of: $0)) } ?? "nil")
}

actor Worker {
  func run() async { await whereAmI("actor") }
}

@MainActor func fromMain() async { await whereAmI("main") }

func fromNone() async { await whereAmI("nonisolated") }

@main struct App {
  static func main() async {
    await fromMain()
    await Worker().run()
    await fromNone()
    let x = #isolation
    print("main() 안의 #isolation:", x.map { String(describing: type(of: $0)) } ?? "nil")
  }
}
1
xcrun swiftc -swift-version 6 Common.swift Macro.swift -o macro

실행 결과는 이렇다.

1
2
3
4
main MainActor
actor Worker
nonisolated nil
main() 안의 #isolation: MainActor

@MainActor 함수에서는 MainActor, actor 의 메서드에서는 그 Worker 인스턴스, nonisolated 함수에서는 nil 이 나왔다. 마지막 줄은 @main 구조체의 static func main() 이 main actor 에서 돈다는 것을 보여 준다. 제안서 #isolation default argument 절이 이 값들을 목록으로 정한다.

부른 자리#isolation 이 펼쳐지는 것
정적으로 nonisolatednil (parameter 가 optional 이어야 한다)
global actor T 에 isolatedT.shared
isolated actor parameter 가 있는 자리 (actor 메서드의 self 포함)그 parameter 를 가리키는 참조
isolated distributed actor parameter d 가 있는 자리d 를 로컬 actor 로 바꾼 값 (아래 절)
isolated parameter 나 그 non-optional binding 을 붙잡은 closure그 붙잡은 값을 가리키는 참조

API 한 가지를 짚는다. Actor 는 모든 actor 타입이 자동으로 따르는 protocol 이다. any Actor 는 어떤 actor 든 담는 existential 이고, (any Actor)? 는 그것이 없을 수도(nil) 있다는 타입이다. MainActor 는 main thread 를 대표하는 global actor 다. String(describing: type(of: $0)) 는 값의 실제 타입 이름을 문자열로 만들어 위 출력에 쓴 것이다.


문맥 타입을 따르는 #isolation

제안서는 #isolation 의 타입이 #file, #line 같은 다른 내장 매크로처럼 문맥에서 받는 타입 표기를 따른다고 정한다. 아무 문맥 타입이 없으면 기본은 (any Actor)? 다. 후보 함수를 고를 때 컴파일러는 이 표현식이 parameter 타입으로 변환될 것이라고 가정하고, 그 후보로 실제 호출이 정해지면 변환이 성공해야 하며 성공하지 못하면 호출이 잘못된 것이다. 부른 쪽의 isolation 을 정하기 전에 호출을 resolve 해야 하기 때문에 필요한 규칙이라고 제안서는 설명한다.

6.4 에서 이 규칙을 두 갈래로 확인했다. 먼저 성공하는 쪽이다. isolated any Actor, isolated MainActor 를 받는 parameter 에 #isolation 을 기본값으로 두었고, @MainActor 클래스 안에서 let m: MainActor = #isolation 도 썼다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
func needsActor(_ ns: NonSendable, _ a: isolated any Actor = #isolation) async { ns.value += 1 }
func needsMain(_ ns: NonSendable, _ a: isolated MainActor = #isolation) async { ns.value += 1 }

@MainActor final class Model {
  var ns = NonSendable()
  func run() async {
    await needsActor(ns)
    await needsMain(ns)
    let m: MainActor = #isolation
    print(m)
  }
}

actor Worker {
  var ns = NonSendable()
  func run() async {
    await needsActor(ns)
  }
}

세 모드 모두 진단이 0 개다. #isolation 은 any Actor 에도 MainActor 에도 (any Actor)? 에도 맞춰 펼쳐진다. 이것이 리뷰에서 kabiroberai 가 요구한 것이다. 그는 NodeJS 브리지의 NodeActor 를 예로 들며 #isolation 이 (any Actor)? 만이 아니라 더 좁은 타입으로 쓰일 수 있기를 바랐고(리뷰 #6), 더 좁은 타입이 맞지 않는 자리에서는 오류가 아니라 그 overload 가 후보에서 빠지는 substitution failure 가 되기를 기대했다(리뷰 #11). 컴파일 오류로 읽은 쪽은 tgoyne 였다(리뷰 #12). 같은 리뷰에서 kabiroberai 가 당시 toolchain 으로 isolated any Actor 에 #isolation 을 넘겼을 때 “Value of optional type ‘(any Actor)?’ must be unwrapped” 가 났다는 것(리뷰 #13)에 hborla 는 구현이 완벽하지 않을 뿐 제안서가 맞다고 답했다(리뷰 #14). 수락 공지가 구현이 아직 따라가지 못하는 곳으로 꼽은 #isolation 의 문맥 타입과 parameter 기본값 쓰임은 6.4 에서 위처럼 동작한다.

이제 실패하는 쪽이다. 문맥 타입에 맞지 않는 자리를 일부러 만들었다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
func needsActor(_ a: isolated any Actor = #isolation) async {}
func needsMain(_ a: isolated MainActor = #isolation) async {}
func plain(_ a: (any Actor)? = #isolation) -> (any Actor)? { a }

@MainActor func fromMain() async {
  await needsActor()
  await needsMain()
  let m: MainActor = #isolation
  _ = m
  _ = plain()
}

actor Worker {
  func run() async {
    await needsActor()
    await needsMain()
  }
}

func fromNone() async {
  await needsActor()
}

@MainActor 함수 fromMain() 은 모두 통과한다. Worker 안에서 needsMain() 을 부르는 16번 줄과, nonisolated 함수에서 needsActor() 를 부르는 21번 줄이 error 다. 매크로가 펼쳐진 자리의 에러라서 MacroType.swift:줄:열: 로 시작하지 않는다. 첫째 에러다.

1
2
3
4
5
6
7
8
9
10
macro expansion #isolation:1:1: error: cannot convert value of type 'Worker' to expected argument type 'MainActor'
`- MacroType.swift:16:20: note: expanded code originates here
14 |   func run() async {
15 |     await needsActor()
16 |     await needsMain()
   +--- MacroType.swift ------------------------------------------------
   |14 |
   |15 |
   |16 |                    #isolation
   |   |                    `- note: in expansion of macro 'isolation' here

둘째 에러다. needsActor 의 parameter 가 non-optional any Actor 인데 nonisolated 자리에서 #isolation 이 nil 이 된다.

1
2
macro expansion #isolation:1:1: error: 'nil' is not compatible with expected argument type 'any Actor'
`- MacroType.swift:21:19: note: expanded code originates here

두 에러는 Swift 5, Swift 5 complete, Swift 6 세 모드 모두 같고, 같은 에러가 사이트마다 두 번씩 출력된다. 위에는 한 번씩만, 매크로 확장 상자는 빼고 옮겼다. Worker 인스턴스는 MainActor 가 될 수 없고, nil 은 optional 이 아닌 any Actor 가 될 수 없으니 둘 다 정당한 타입 에러다. 문맥 타입이 맞으면 통과하고 맞지 않으면 그 자리에서 진단이 나온다. ktoso 는 이 진단으로 값이 actor 밖으로 새지 않게 하는 API 를 만들 수 있을지 궁금해했다(리뷰 #15).


같은 isolation 인지 판단하는 규칙

parameter 를 #isolation 이 아니라 직접 인자로 넘길 수도 있다. 그러면 컴파일러는 “이 인자가 현재 context 의 isolation 과 같은가” 를 판단해야 한다. 제안서의 Generalized isolation checking 절이 그 규칙이다. isolated parameter 를 가진 함수를 부를 때 현재 context 와 같은 isolation 으로 보는 경우는 세 가지다.

  • 현재 context 가 nonisolated 이고, parameter 가 optional 이며, 인자 표현식이 nil 이거나 Optional.none 을 가리킬 때
  • 현재 context 에 isolated parameter(actor 메서드의 self 포함)가 있고, 인자 표현식이 그 parameter 를 가리키거나, 그것에서 optional 을 벗겨 낸 값(non-optional derivation)이거나, distributed actor 에서 로컬 actor 로 바꾼 값일 때
  • 현재 context 가 global actor T 에 isolated 이고, 인자 표현식이 T.shared 일 때

컴파일러가 실제 값이 같은지를 실행해서 비교하지 않는다는 것이 이 규칙의 핵심이다. 값이 어디서 왔는지를 소스에서 보고 판단한다. 제안서의 Counter 예제를 6.4 로 돌려서 그것을 확인했다. 제안서의 testActor 등은 async 가 빠진 형태여서 async 를 붙이고 try? 를 더한 것만 다르다.

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
class Counter {
  var count = 0
}

extension Counter {
  func incrementAndSleep(isolation: isolated (any Actor)?) async {
    count += 1
    try? await Task.sleep(nanoseconds: 1_000_000)
  }
}

actor MyActor {
  var counter = Counter()
}

extension MyActor {
  func testActor(other: MyActor) async {
    await counter.incrementAndSleep(isolation: self)          // allowed
    await counter.incrementAndSleep(isolation: other)         // not allowed
    await counter.incrementAndSleep(isolation: MainActor.shared) // not allowed
    await counter.incrementAndSleep(isolation: nil)           // not allowed
  }
}

@MainActor func testMainActor(counter: Counter) async {
  await counter.incrementAndSleep(isolation: MainActor.shared) // allowed
  await counter.incrementAndSleep(isolation: nil)              // not allowed
}

func testNonIsolated(counter: Counter) async {
  await counter.incrementAndSleep(isolation: nil)              // allowed
  await counter.incrementAndSleep(isolation: MainActor.shared) // not allowed
}

Task.sleep 으로 잠깐 멈추기

Task.sleep(nanoseconds:) 는 현재 task 를 주어진 나노초 동안 멈춘다. 1_000_000 나노초는 1 밀리초다. 멈추는 동안 같은 actor 의 다른 task 가 끼어들 수 있어서, 제안서는 이 예제로 “멈춘 사이에 actor 상태를 만질 수 있는” 상황을 만들려고 썼다. 취소되면 던지는 함수라서 try? 로 오류를 버렸다.

6.4 에서 주석의 allowed 와 not allowed 가 정확히 맞는다. allowed 라고 적힌 18, 26, 31번 줄은 진단이 없고, not allowed 라고 적힌 19, 20, 21, 27, 32번 줄은 Swift 6 모드에서 error 다. Swift 5 모드는 0 개이고, Swift 5 complete 에서는 같은 5 개 자리가 warning 이다. 첫 세 개와 MainActor 에서 nil 을 넘긴 자리의 error 원문은 이렇다.

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
Counter.swift:19:19: error: sending 'self.counter' risks causing data races [#RegionIsolation::SendingRisksDataRace]
17 |   func testActor(other: MyActor) async {
18 |     await counter.incrementAndSleep(isolation: self)          // allowed
19 |     await counter.incrementAndSleep(isolation: other)         // not allowed
   |                   |- error: sending 'self.counter' risks causing data races [#RegionIsolation::SendingRisksDataRace]
   |                   `- note: sending 'self'-isolated 'self.counter' to actor-isolated instance method 'incrementAndSleep(isolation:)' risks causing data races between actor-isolated and 'self'-isolated uses
20 |     await counter.incrementAndSleep(isolation: MainActor.shared) // not allowed
21 |     await counter.incrementAndSleep(isolation: nil)           // not allowed

Counter.swift:20:19: error: sending 'self.counter' risks causing data races [#RegionIsolation::SendingRisksDataRace]
18 |     await counter.incrementAndSleep(isolation: self)          // allowed
19 |     await counter.incrementAndSleep(isolation: other)         // not allowed
20 |     await counter.incrementAndSleep(isolation: MainActor.shared) // not allowed
   |                   |- error: sending 'self.counter' risks causing data races [#RegionIsolation::SendingRisksDataRace]
   |                   `- note: sending 'self'-isolated 'self.counter' to main actor-isolated instance method 'incrementAndSleep(isolation:)' risks causing data races between main actor-isolated and 'self'-isolated uses
21 |     await counter.incrementAndSleep(isolation: nil)           // not allowed
22 |   }

Counter.swift:21:19: error: sending 'self.counter' risks causing data races [#RegionIsolation::SendingRisksDataRace]
19 |     await counter.incrementAndSleep(isolation: other)         // not allowed
20 |     await counter.incrementAndSleep(isolation: MainActor.shared) // not allowed
21 |     await counter.incrementAndSleep(isolation: nil)           // not allowed
   |                   |- error: sending 'self.counter' risks causing data races [#RegionIsolation::SendingRisksDataRace]
   |                   `- note: sending 'self'-isolated 'self.counter' to @concurrent instance method 'incrementAndSleep(isolation:)' risks causing data races between @concurrent and 'self'-isolated uses
22 |   }
23 | }

Counter.swift:27:17: error: sending 'counter' risks causing data races [#RegionIsolation::SendingRisksDataRace]
25 | @MainActor func testMainActor(counter: Counter) async {
26 |   await counter.incrementAndSleep(isolation: MainActor.shared) // allowed
27 |   await counter.incrementAndSleep(isolation: nil)              // not allowed
   |                 |- error: sending 'counter' risks causing data races [#RegionIsolation::SendingRisksDataRace]
   |                 `- note: sending main actor-isolated 'counter' to @concurrent instance method 'incrementAndSleep(isolation:)' risks causing data races between @concurrent and main actor-isolated uses
28 | }

마지막 줄 32번(nonisolated 함수에서 MainActor.shared 를 넘긴 자리)의 note 는 이렇다.

1
2
Counter.swift:32:17: error: sending 'counter' risks causing data races [#RegionIsolation::SendingRisksDataRace]
   |                 `- note: sending 'counter' to main actor-isolated instance method 'incrementAndSleep(isolation:)' risks causing data races between main actor-isolated code and code in the current isolation context

note 의 문장이 어느 쪽이 어느 쪽으로 가는지를 그대로 말해 준다. 19번 줄은 “self 에 isolated 된 self.counter 를 other 라는 다른 actor 의 isolation 으로 돌리는 함수에 넘긴다” 이고, 20번 줄은 상대가 main actor 가 되고, 21번 줄은 nil 이라서 상대가 @concurrent 다. 값이 같은 actor 에 있다고 컴파일러가 믿을 근거가 self 에는 있고 나머지에는 없다.

컴파일러는 넘긴 isolation 값의 출처로 같은 actor 인지 판단한다. MyActor 안에서 isolation: self 는 18번 줄에서 진단 0 개로 통과하고, other, MainActor.shared, nil 은 각각 19, 20, 21번 줄에서 다른 isolation 으로 보여 error 가 난다.


실행 중 같은 actor 확인의 한계

수락 공지에서 xwu 가 든 예제가 이 규칙의 한계를 가장 잘 보여 준다. 제안서의 Counter 예제를 들어 “other 를 넘기는 것은 허용되지 않고, if other == self 로 감싸도 여전히 허용되지 않는다” 고 적었다. 그리고 이렇게 판단한 이유를 이렇게 말한다. 이 제안은 컴파일러가 현재 isolation 을 물려받는 철자를 전부 알아보게 하는 것이 아니라 대부분을 알아보게 하는 것이고, “공인된 대체 철자(위 예에서는 self)” 가 있어서 충분하다는 것이다. 더 꼼꼼한 컴파일러 지원은 소스를 깨지 않고 나중에 더할 수 있다.

6.4 에서 같은 모양을 === 로 확인해 보았다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Counter {
  var count = 0
  func incrementAndSleep(isolation: isolated (any Actor)?) async {
    count += 1
  }
}

actor MyActor {
  var counter = Counter()

  func testActor(other: MyActor) async {
    await counter.incrementAndSleep(isolation: self)
    if other === self {
      await counter.incrementAndSleep(isolation: other)
    }
  }
}

Swift 5 에서는 0 개, Swift 5 complete 에서는 14:21 warning, Swift 6 모드에서는 14:21 error 다.

1
2
AcceptOther.swift:14:21: error: sending 'self.counter' risks causing data races [#RegionIsolation::SendingRisksDataRace]
   |                     `- note: sending 'self'-isolated 'self.counter' to actor-isolated instance method 'incrementAndSleep(isolation:)' risks causing data races between actor-isolated and 'self'-isolated uses

other === self 로 두 참조가 같은 actor 임을 확인한 안쪽에서도 other 를 넘기면 에러다. 컴파일러는 값을 비교한 결과를 타입 검사에 쓰지 않고 표현식의 모양만 본다.


isolation 에서 파생한 값

self 말고도 “isolation parameter 에서 나온 값” 은 어떨까? 제안서는 optional 을 벗겨 낸 값(non-optional derivation)도 같은 isolation 으로 본다고 적고, 예로 param?, param!, if let ref = param 의 ref 를 든다. 괄호, try/try?/try!/await, 동적 bridging 이 아닌 as, Optional 로의 암시적 승격은 무시한다고도 한다. 일곱 가지 철자를 Derive.swift 로 6.4 에서 재 보았다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Counter {
  var count = 0
  func increment(isolation: isolated (any Actor)?) async { count += 1 }
}

func test(counter: Counter, isolation: isolated (any Actor)?) async {
  await counter.increment(isolation: isolation)       // 1: 그대로
  await counter.increment(isolation: (isolation))     // 2: 괄호
  if let a = isolation {
    await counter.increment(isolation: a)             // 3: non-optional binding
    await counter.increment(isolation: a as any Actor) // 4: as
  }
  guard let b = isolation else { return }
  await counter.increment(isolation: b)               // 5: guard let
  await counter.increment(isolation: isolation!)      // 6: 강제 unwrap
}

func other(counter: Counter, isolation: isolated (any Actor)?, another: (any Actor)?) async {
  await counter.increment(isolation: another)         // 7: 다른 actor
}

6.4 에서 측정한 결과다. Swift 6 모드에서 에러가 난 자리는 Derive.swift 의 10, 11, 14, 15, 19번 줄이고, 첫 줄은 모두 error: sending 'counter' risks causing data races 이며 note 도 같다.

1
2
Derive.swift:10:19: error: sending 'counter' risks causing data races [#RegionIsolation::SendingRisksDataRace]
   |                   `- note: sending 'isolation'-isolated 'counter' to actor-isolated instance method 'increment(isolation:)' risks causing data races between actor-isolated and 'isolation'-isolated uses
번호넘긴 인자Swift 5Swift 5 completeSwift 6
1isolation 그대로000
2(isolation) 괄호000
3if let a 의 a0warningerror
4a as any Actor0warningerror
5guard let b 의 b0warningerror
6isolation!0warningerror
7다른 parameter another0warningerror

6.4 에서 측정하면 그대로 넘긴 것과 괄호로 감싼 것만 통과하고, optional 을 풀어서 얻은 값(3, 4, 5, 6번)은 다른 isolation 으로 본다. 6.4 컴파일러가 같은 isolation 으로 알아보는 것은 isolation 이라는 이름을 그대로 쓴 표현뿐이다. 그래서 isolation: isolated (any Actor)? 를 받은 함수가 그것을 다시 다른 함수에 넘기려면 풀지 말고 그대로 넘겨야 한다.


Task closure 가 물려받는 isolation

Task { ... } 의 closure 가 어떤 isolation 에서 도는지는 SE-0304 의 actor context propagation 규칙이 정한다. Task 초기화에 직접 넘긴 closure 는 다음 경우에 현재 context 의 정적 isolation 을 물려받는다. 현재 context 가 nonisolated 이거나, global actor 에 isolated 이거나, isolated parameter(actor 메서드의 self 포함)가 있고 closure 가 그것을 강하게 붙잡았을 때다. SE-0420 은 셋째 조건을 넓힌다. isolated parameter 의 non-optional binding 을 붙잡아도 물려받는다.

네 가지를 TaskCapture.swift 로 6.4 에서 확인했다.

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
func useInTask(ns: NonSendable, isolation: isolated (any Actor)?) {
  Task {
    _ = isolation
    ns.value += 1
  }
}

func useInTaskBound(ns: NonSendable, isolation: isolated (any Actor)?) {
  guard let a = isolation else { return }
  Task {
    _ = a
    ns.value += 1
  }
}

func useInTaskNonOptional(ns: NonSendable, isolation: isolated any Actor) {
  Task {
    _ = isolation
    ns.value += 1
  }
}

func useInTaskNoCapture(ns: NonSendable, isolation: isolated any Actor) {
  Task {
    ns.value += 1
  }
}

Task 로 closure 를 isolation 에 올려 실행하기

Task 의 초기화에 closure 를 넘기면 새 task 가 만들어져 그 closure 를 비동기로 실행한다. 이 코드의 _ = isolation 은 isolation parameter 를 읽어서 “closure 가 isolation 을 붙잡았다” 는 사실을 만드는 한 줄이다. 값은 쓰지 않는다. 붙잡은 것이 있어야 SE-0304 의 규칙에서 closure 가 그 isolation 을 물려받는다.

결과는 이렇다.

함수붙잡은 것Swift 5Swift 5 completeSwift 6
useInTaskoptional isolation 그대로000
useInTaskBoundguard let a 로 푼 a0warningerror
useInTaskNonOptionalnon-optional isolation000
useInTaskNoCapture안 붙잡음0warningerror

useInTask 와 useInTaskNonOptional 은 closure 가 isolation 을 붙잡았으므로 Task 가 그 isolation 을 물려받고, non-Sendable 인 ns 를 안에서 써도 경계를 넘지 않는다. 안 붙잡은 useInTaskNoCapture 는 SE-0304 규칙 그대로 isolation 을 물려받지 못해서 error 다.

에러 메시지의 sending 은 SE-0430 글에서 다룬 한정자다. Task 초기화가 closure 를 sending parameter 로 받으므로, closure 가 붙잡은 값이 부른 쪽 isolation 에 계속 묶여 있으면 안 된다는 뜻이다.

1
2
3
4
5
6
7
8
9
TaskCapture.swift:24:3: error: passing closure as a 'sending' parameter risks causing data races between 'isolation'-isolated code and concurrent execution of the closure [#RegionIsolation::SendingClosureRisksDataRace]
22 | 
23 | func useInTaskNoCapture(ns: NonSendable, isolation: isolated any Actor) {
24 |   Task {
   |   `- error: passing closure as a 'sending' parameter risks causing data races between 'isolation'-isolated code and concurrent execution of the closure [#RegionIsolation::SendingClosureRisksDataRace]
25 |     ns.value += 1
   |     `- note: closure captures 'isolation'-isolated 'ns'
26 |   }
27 | }

useInTaskBound(10번 줄) 의 에러도 같은 문구이고 note 가 12번 줄의 closure captures 'isolation'-isolated 'ns' 다. optional 을 guard let 으로 풀어서 얻은 a 를 붙잡은 것이 같은 isolation 의 증거로 쓰이지 않는다. 앞의 Derive 에서 본 것과 같은 현상이다. 6.4 에서는 풀어낸 값을 같은 isolation 으로 보지 않는다.


isolated distributed actor 와 asLocalActor

distributed actor(여러 프로세스나 기계에 걸쳐 원격으로 부를 수 있는 actor)는 Actor 를 따르지 않는다. SE-0336 이 DistributedActor protocol 을 Actor 와 별개로 둔 이유는 distributed actor 가 로컬에 있을 때만 일반 actor 처럼 행동하기 때문이다. 그래서 isolated (any Actor)? parameter 에 distributed actor 를 직접 넘길 수 없다.

제안서의 해법은 DistributedActor 에 로컬 actor 참조를 돌려주는 API 를 더하는 것이다. 그것을 isolated distributed actor parameter 로 바꾸면 로컬임이 이미 알려져 있다. 6.4 SDK 에서 그 API 의 이름은 asLocalActor 다. Distributed.swift 로 distributed actor 의 메서드 안에서 확인했다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import Distributed

func useHere(_ ns: NonSendable, isolation: isolated (any Actor)? = #isolation) async {
  ns.value += 1
}

distributed actor Greeter {
  typealias ActorSystem = LocalTestingDistributedActorSystem
  var ns = NonSendable()

  distributed func greet() async {
    await useHere(ns)
    let local: any Actor = self.asLocalActor
    _ = local
  }
}

DistributedActor 와 LocalTestingDistributedActorSystem 으로 로컬 actor 얻기

DistributedActor 는 distributed actor 가 따르는 protocol 이다. LocalTestingDistributedActorSystem 은 한 프로세스 안에서 distributed actor 를 실험해 보라고 제공되는 시스템이다. 원격 전송 없이 distributed actor 를 만들고 부를 수 있어서 이 글의 확인용으로 썼다. distributed func 는 distributed actor 밖에서 await 로 부를 수 있는 메서드다. 메서드 안에서 self 는 로컬임이 알려져 있어서 self.asLocalActor 로 any Actor 를 얻을 수 있고, #isolation 기본 인자는 이 변환을 자동으로 한다. 세 모드 모두 진단 0 개다.

그 변환은 actor 안에서만 된다. 밖의 nonisolated 함수에서 asLocalActor 를 부르면 이렇다.

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

distributed actor Greeter {
  typealias ActorSystem = LocalTestingDistributedActorSystem
}

func useHere(_ ns: NonSendable, isolation: isolated (any Actor)? = #isolation) async {
  ns.value += 1
}

func outside(_ g: Greeter, ns: NonSendable) async {
  await useHere(ns, isolation: g.asLocalActor)
}

세 모드 모두 같은 error 다. distributed actor 는 원격일 수 있어서, 로컬인지 모르는 자리에서는 로컬 actor 참조를 줄 수 없다.

1
2
DistributedOutside.swift:12:34: error: distributed actor-isolated property 'asLocalActor' can not be accessed from a nonisolated context
Distributed.DistributedActor.asLocalActor:3:14: note: access to property 'asLocalActor' is only permitted within distributed actor 'DistributedActor'

note 가 가리키는 선언은 6.4 SDK 에서 @backDeployed(before: macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0)(새 OS 에서 추가된 API 를 옛 OS 에서도 쓸 수 있게 본문을 앱에 같이 넣어 주는 표시)가 붙은 public var asLocalActor: any Actor { get } 다. 제안서도 같은 @backDeployed 를 달았다.


표준 라이브러리의 #isolation

6.4 SDK 의 _Concurrency.swiftmodule/arm64e-apple-macos.swiftinterface 를 열어서 #isolation 기본 인자가 들어간 자리를 찾았다.

1
2
grep -n 'isolation: isolated (any _Concurrency::Actor)? = #isolation' \
  "$(xcrun --show-sdk-path)/usr/lib/swift/_Concurrency.swiftmodule/arm64e-apple-macos.swiftinterface"

isolation: isolated (any Actor)? = #isolation 이 들어간 줄이 16 개 나왔다. 이 중 internal 함수 awaitAllRemainingTasks 2 개와 밑줄이 붙은 _isolatedParameter_withTaskPriorityEscalationHandler 2 개를 빼면 공개 API 는 12 개다. 대표적인 것들이다.

  • Clock.measure(isolation:_:)
  • withDiscardingTaskGroup, withThrowingDiscardingTaskGroup
  • withTaskGroup, withThrowingTaskGroup
  • TaskGroup.next(isolation:), ThrowingTaskGroup.next(isolation:), nextResult
  • waitForAll(isolation:) (TaskGroup 과 ThrowingTaskGroup 에 하나씩)
  • withTaskExecutorPreference(_:isolation:operation:)
  • TaskLocal.withValue(_:operation:isolation:file:line:)

nonisolated(nonsending) 은 SE-0461 이 도입한 한정자로, nonisolated async 함수를 부른 쪽 isolation 에서 돌게 한다. nonsending 은 인자와 결과를 다른 isolation 으로 보내지(send) 않는다는 뜻이다. 어디서 부르든 부른 쪽 isolation 에서 실행되므로 값이 경계를 넘을 일이 없다. 위 12 개 중 Clock.measure(isolation:_:), waitForAll(isolation:) 두 곳, nextResult(isolation:) 네 곳에는 @available(*, deprecated, message: "Replaced by nonisolated(nonsending) overload") 가 붙어 있다. nonisolated(nonsending) 판으로 대체되었다는 뜻이다.

AsyncIteratorProtocol 에는 next(isolation:) 가 있다. 인터페이스 파일에 이렇게 선언되어 있다.

1
mutating func next(isolation actor: isolated (any Actor)?) async throws(Self.Failure) -> Self.Element?

SE-0421 이 더한 프로토콜 요구사항이고, 앞에서 본 for await 가 부르는 함수가 이것이다. macOS 15 이상에서 쓰이고 AsyncMapSequence 같은 표준 시퀀스가 구현한다. 이 선언에는 기본 인자가 없다. 구현하는 쪽이 받는 parameter 이기 때문이다. 그래서 iterator.next() 를 직접 부르는 앞의 Motivation 예제는 이 함수를 거치지 않고, SE-0414 region 분석으로 통과한다.

withCheckedContinuation 은 6.4 에서 한 단계 더 나갔다. 같은 인터페이스의 1504~1536 줄에 두 판이 있다. 주된 판은 1506 줄과 1508 줄이다.

1
2
@abi(nonisolated(nonsending) func withCheckedContinuationNonisolatedNonsending<T>(function: Swift::String, _ body: (_Concurrency::CheckedContinuation<T, Swift::Never>) -> Swift::Void) async -> sending T)
@inlinable @_alwaysEmitIntoClient nonisolated(nonsending) public func withCheckedContinuation<T>(function: Swift::String = #function, _ body: (_Concurrency::CheckedContinuation<T, Swift::Never>) -> Swift::Void) async -> sending T {

붙은 attribute 를 짚는다. @abi(...) 는 소스에 쓴 선언과 별개로 바이너리에 남는 이름과 모양을 지정한다. @inlinable 은 함수 본문을 인터페이스에 공개해서 호출하는 쪽이 본문을 펼쳐 넣을 수 있게 하고, @_alwaysEmitIntoClient 는 그 본문을 라이브러리가 아니라 호출하는 쪽 바이너리에 항상 만들어 넣게 한다.

옛 판은 1529 줄과 1530 줄이다.

1
2
@available(*, deprecated, message: "Replaced by nonisolated(nonsending) overload")
@inlinable @_disfavoredOverload public func withCheckedContinuation<T>(isolation: isolated (any _Concurrency::Actor)?, function: Swift::String = #function, _ body: (_Concurrency::CheckedContinuation<T, Swift::Never>) -> Swift::Void) async -> sending T {

isolation: parameter 를 받는 이 판은 withCheckedContinuation(isolation:) overload 자체가 deprecated 이고, @_disfavoredOverload(같은 이름 후보가 여럿일 때 우선순위를 뒤로 미룬다)로 밀려나 있다. 앞에서 본 리뷰 tgoyne #9 가 withCheckedContinuation 을 #isolation 으로 만들자고 한 것이, 이 제안서가 아니라 다음 단계 SE-0461 의 nonisolated(nonsending) 으로 정착했다.


기대 효과

  • @_unsafeInheritExecutor 가 정식 도구로 바뀐다. 앞의 UnsafeInherit.swift 진단 문구가 대안을 그대로 가리킨다. isolation: isolated (any Actor)? = #isolation parameter 를 더하면 된다.
  • 불필요한 executor 전환이 없어진다. 제안서가 Motivation 에서 짚은 “generic executor 로 갔다가 곧바로 다른 isolation 으로 돌아오는” 낭비가 next(isolation:) 처럼 isolation 을 받는 API 에서는 생기지 않는다.
  • non-Sendable 값을 그대로 넘기는 범용 async 유틸리티를 쓸 수 있다. 위 Inherit.swift 처럼 같은 값을 await 로 넘겨도 진단이 없다. TaskGroup, AsyncSequence, 직접 만든 higher-order 함수가 같은 방식을 쓴다.
  • Realm 처럼 현재 actor 에 묶인 객체를 만드는 API 를 만들 수 있다. tgoyne 는 try await Realm() 이 호출한 쪽 isolation 에 묶인 객체를 돌려주기를 바랐다고 적었다(pitch #6). 당시에는 try await Realm(actor: actor) 처럼 actor 를 명시적으로 넘겨야 했고 잘못된 actor 를 넘기면 런타임 오류가 난다는 것이다.
  • 사용 비용은 parameter 한 줄이다. 제안서도 이 제안이 새 타입이나 새 런타임 지원을 요구하지 않고 컴파일러만으로 구현할 수 있다고 적는다.

다른 선택지는 왜 안 됐나

pitch 와 리뷰 스레드에서 가장 오래 오간 이야기는 “왜 이렇게 parameter 와 기본 인자라는 우회로를 쓰는가” 였다. 부른 쪽 isolation 을 물려받는 것이 이렇게 중요하다면 함수에 표시를 하나 달면 되지 않느냐는 것이다. 제안서의 Alternatives considered 와 스레드의 답을 묶어서 본다.


물려받기를 기본값으로 바꾸는 방법

juliand665 는 처음부터 이것을 물었다. 나중에 isolation 을 물려받는 쪽이 기본이고 떠나는 쪽이 opt-in 이어야 했던 것 아니냐는 의견이다(pitch #15, #18). 리뷰에서 mattie 도 Future directions 에 나온 opt-in 을 짚으면서, 오히려 물려받는 쪽이 기본이고 거부하는 쪽을 표시하는 opt-out 이어야 하지 않느냐고 물었다(리뷰 #4).

hborla 는 SE-0338 의 근거를 그대로 인용해서 답했다(리뷰 #10). 제안서도 같은 입장이다. 핵심은 두 가지다.

  • ABI 제약이다. ABI 는 컴파일된 바이너리끼리 맞물리는 약속이다. 함수가 어떤 이름으로 어떤 parameter 를 받는지도 거기에 들어간다. 기존 nonisolated async 함수는 부른 쪽의 isolation 정보를 받도록 컴파일되지 않았다. 그래서 이미 배포된 라이브러리의 기본을 바꿀 수 없다. 이미 있는 parameter 에 #isolation 기본값을 붙이는 것은 ABI 를 깨지 않지만, 없던 isolation: parameter 를 새로 더하면 소스는 그대로 컴파일되는데도(source compatible) 바이너리가 보는 함수 모양이 바뀌어서 ABI 는 깨진다. 그래서 표준 라이브러리는 기존 함수를 고치지 않고 새 overload 를 더하고, @_disfavoredOverload 와 @abi 로 두 판이 공존하게 한다. 앞의 withCheckedContinuation 이 그 모양이다.
  • 의미의 문제다. SE-0338 은 async 함수가 부른 actor 를 점유한 채로 오래 돌아서 생기는 문제(리뷰 #10 이 인용한 표현으로는 actor 가 “overhang” 을 겪는 것)를 줄이려고 nonisolated async 를 actor 밖에서 돌게 했다. 물려받는 쪽을 기본으로 하면 그 문제가 되살아난다.

ktoso 도 pitch 스레드에서 SE-0338 의 근거를 설명하면서, 그 결정이 이후 SE-0417 의 task executor 쪽 논의와도 이어진다고 적었다(pitch #16). 그는 SE-0338 이 “over-corrected” 했을 수 있다고 하면서도 그 근거는 SE-0338 에 설명되어 있다고 답했다. 이 제안은 그 과한 부분을 되돌리는 것이 아니라 필요한 함수만 고르게 해 주는 것이다.


함수 단위 표시

pitch 초안에는 함수 attribute @inheritsIsolation 이 들어 있었다. 함수에 이 표시를 달면 부른 쪽 isolation 을 물려받는 방식이다. pitch 스레드에서 arennow(#3), tgoyne(#6), mklbtz(#7) 가 이 attribute 를 두고 이야기했고, 제안서는 리뷰에 올라가기 전에 이것을 Future directions 로 옮겼다. 그래서 스레드에는 함수 단위 표시를 두고 여러 문법이 나왔다.

제안낸 사람비고
@inheritsIsolation 함수 attributepitch 초안 (arennow #3, tgoyne #6, mklbtz #7 이 논의)리뷰 전에 Future directions 로 옮겼다
isolated(caller) 같은 함수 표시wadetregaskis (pitch #2) 가 처음 제안했고, mklbtz (pitch #7) 가 구체화했다John_McCall 이 마음에 들어 했지만 파싱을 걱정했다 (pitch #8)
@CallerActor attributeJon_Shier (pitch #11) 
isolated(inherited)Dmitriy_Ignatyev (pitch #17) 가 철자만 제안했다수락 후에도 asdf_bro 가 시기를 물었다
reisolated 처럼 isolated 를 확장wadetregaskis (pitch #2) 
await(isolated) foo() 처럼 부르는 쪽에서 표시juliand665 (pitch #18) 

John_McCall 은 isolated(caller) 방향이 마음에 들지만 파싱이 까다롭다고 했고(pitch #8), 이미 isolated 가 parameter modifier 로 쓰이고 있어서 같은 단어를 함수 쪽에 쓰면 겹치는 것이 “deal-breaker” 라고 했다(pitch #9). xwu 는 농담조로 funcisolated 같은 이름까지 거론하며 이름 짓기가 어렵다는 것을 보였다(pitch #12). 한동안 John_McCall 은 isolated(caller), isolated(any) 같은 형태로 기존 modifier 를 대체하는 방향을 생각했다고 밝혔다(pitch #13).

리뷰에서는 robert.ryan 이 함수 단위 한정자를 다시 제안했다(리뷰 #20). John_McCall 은 parameter 에 붙는 modifier 가 조금 아쉽다고(a little unfortunate) 인정하면서, 이 문제는 나중에 modifier 를 함수 전체에 거는 위치로 옮기는 것으로 다룰 수 있으니 두 문제를 분리하자고 답했다(리뷰 #22). 제안서는 이 분리를 이렇게 정리한다. isolation 이 값이라는 것을 먼저 표현하는 것이 이 제안이고, 값이 되면 부른 쪽이 그 값을 넘겨받는 방식은 parameter 와 기본 인자라는 기존 도구로 얻을 수 있다. 함수 단위 한정자는 그 위에 얹는 편의 문법으로 Future directions 에 있다. 그 편의 문법은 약점이 세 가지(장황함, 계산 프로퍼티 접근자에 parameter 를 달 수 없음, UnownedSerialExecutor 를 그대로 넘기는 쪽의 효율)를 풀려는 것이다.

실제로 이 편의 문법은 뒤에 나왔다. 아래에서 SE-0461 의 nonisolated(nonsending) 으로 이어진다.


SerialExecutor 로 isolation 을 표현하는 방법

제안서는 isolation 을 (any Actor)? 로 표현했다. 대안으로 검토했던 것이 SerialExecutor 나 UnownedSerialExecutor 를 isolation 의 타입으로 쓰는 것이다. 이유 세 가지를 들어 기각한다.

  • actor 는 “실행 정책(어떤 executor 에서 도는가)” 이 아니라 “isolation 그 자체” 로 생각해야 한다. isolation 을 executor 로 표현하면 두 개념이 섞인다.
  • UnownedSerialExecutor 는 unsafe 하다. 참조를 세지 않아서 executor 가 이미 사라졌는지를 보장하지 못한다.
  • any SerialExecutor 는 복잡하고, 최적화 이득도 없다.

isolation 의 타입을 (any Actor)? 보다 좁게 쓰고 싶다는 요구는 SerialExecutor 와는 다른 이야기다. kabiroberai 는 NodeActor 를 만드는 입장에서 (any Actor)? 보다 좁은 actor 타입을 쓰고 싶다고 했다(리뷰 #6, #11, #13, #16). executor 대신 actor 를 쓰는 선택과 충돌하지 않는 요구이고, 앞의 “문맥 타입을 따르는 #isolation” 에서 본 것이 그 결과다. #isolation 이 문맥 타입을 따르므로 isolated MainActor 같은 좁은 parameter 도 쓸 수 있다.


isolated function type 은 나중으로

closure 의 isolation 을 타입에 싣는 방법이다. 제안서가 미래 방향으로 든 것은 @isolated () -> () 같은 isolated function type 과, 그것으로 sequentialMap 처럼 closure 의 isolation 을 따르는 고차 함수를 쓰는 것이다. 이 방향은 뒤에 SE-0431 의 @isolated(any) 로 구체화되었다(SE-0431 글). 이 제안에서는 다루지 않고 부른 쪽 isolation 을 물려받는 데에 집중한다.


forEachAsync 와 async closure parameter

hborla 는 리뷰에서 이 제안이 푸는 모양을 forEachAsync 로 보였다(리뷰 #23). 이 글은 누군가 warning 이 난다고 보고한 것에 대한 답이었고, -enable-experimental-feature OptionalIsolatedParameters 로 빌드했는지 되묻는 것으로 시작한다. 먼저 hborla 가 든 코드를 6.4 로 돌려 보았다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class NotSendable {}

@MainActor
class ActorIsolatedType {
  func foo() async {
    await (1...3).forEachAsync(MainActor.shared) { _ in
      await bar(NotSendable())
    }
  }
  func bar(_: NotSendable) async {}
}

extension Sequence where Element: Sendable {
  func forEachAsync(_: isolated Actor, _ operation: (Element) async -> Void) async {
    for element in self {
      await operation(element)
    }
  }
}

세 모드 모두 진단이 0 개다. 이 코드에서 isolated parameter 가 지키는 것은 NotSendable() 이 아니다. 그 값은 closure 안에서 만들어서 bar 에 넘기기만 하므로 어디에도 걸리지 않는다. 지키는 것은 non-Sendable 인 closure 값 (Int) async -> Void 자체를 forEachAsync 에 넘기는 일이다. 이 closure 는 @MainActor 클래스 안에서 만들어져 main actor 에 묶여 있다. isolated parameter 가 없는 같은 모양의 함수를 ForEachHollyNoIso.swift 로 재 보았다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class NotSendable {}

@MainActor
class ActorIsolatedType {
  func foo() async {
    await (1...3).forEachAsync { _ in
      await bar(NotSendable())
    }
  }
  func bar(_: NotSendable) async {}
}

extension Sequence where Element: Sendable {
  func forEachAsync(_ operation: (Element) async -> Void) async {
    for element in self {
      await operation(element)
    }
  }
}

Swift 5 에서는 0 개이고, Swift 5 complete 에서는 6:19 warning, Swift 6 모드에서는 6:19 error 다.

1
ForEachHollyNoIso.swift:6:19: error: sending value of non-Sendable type '(Int) async -> Void' risks causing data races [#RegionIsolation::SendingRisksDataRace]

두 판의 차이는 forEachAsync 에 isolated parameter 가 있느냐뿐이다. parameter 가 없으면 forEachAsync 는 nonisolated async 함수라서 main actor 에 묶인 closure 를 다른 isolation 으로 보내는 것이 되어 막힌다. parameter 가 있으면 forEachAsync 가 부른 쪽 actor 에서 돌아서 closure 가 경계를 넘지 않는다.


#isolation 기본 인자를 쓴 forEachAsync

같은 함수를 #isolation 기본 인자로 써서 호출하는 쪽에서 isolation 을 쓰지 않게 바꿔 보았다. 이번에는 closure 가 @MainActor 클래스 Model 의 non-Sendable 원소를 만진다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
extension Collection {
  func forEachAsync(
    _ isolation: isolated (any Actor)? = #isolation,
    _ body: (Element) async -> Void
  ) async {
    for element in self {
      await body(element)
    }
  }
}

@MainActor final class Model {
  var items = [NonSendable(), NonSendable()]
  var total = 0
  func run() async {
    await items.forEachAsync { ns in
      ns.value += 1
      self.total += ns.value
    }
  }
}

Swift 5 에서는 0 개이고, Swift 5 complete 에서는 7:13 warning, Swift 6 모드에서는 7:13 error 다. 6.4 의 원문이다.

1
2
3
4
5
6
7
8
ForEachAsync.swift:7:13: error: sending 'element' risks causing data races [#RegionIsolation::SendingRisksDataRace]
 5 |   ) async {
 6 |     for element in self {
 7 |       await body(element)
   |             |- error: sending 'element' risks causing data races [#RegionIsolation::SendingRisksDataRace]
   |             `- note: sending 'isolation'-isolated 'element' to @concurrent callee risks causing data races between @concurrent and 'isolation'-isolated uses
 8 |     }
 9 |   }

에러가 난 자리는 forEachAsync 의 호출 쪽이 아니라 함수 본문 안의 body(element) 다. isolation parameter 로 부른 쪽 isolation 을 받았지만, body 라는 closure 의 타입은 (Element) async -> Void 이고 nonisolated async 이다. 그래서 body 를 부르면 @concurrent 로 경계를 넘는 것이 되어 isolation 에 isolated 된 element 를 보낸 것으로 막힌다. isolation 을 물려받는 것은 forEachAsync 자신이고, 그 안에서 부르는 closure 는 따로 물려받지 않는다.

이 막힘은 NonisolatedNonsendingByDefault 라는 upcoming feature 를 켜면 사라진다. -swift-version 6 에 -enable-upcoming-feature NonisolatedNonsendingByDefault 를 더하면 진단이 0 개다. 이 feature 는 nonisolated async 함수의 기본 동작을 “부른 쪽 isolation 을 물려받기” 로 바꾼다. SE-0461 이 정한 것이다.

SE-0461 이 도입한 nonisolated(nonsending) 을 closure 타입에 직접 써도 같은 결과를 얻는다. ForEachAsyncNonsending.swift 는 위 코드에서 body 의 타입만 nonisolated(nonsending) (Element) async -> Void 로 바꾼 것이다.

1
2
3
4
5
6
7
8
9
10
extension Collection {
  func forEachAsync(
    _ isolation: isolated (any Actor)? = #isolation,
    _ body: nonisolated(nonsending) (Element) async -> Void
  ) async {
    for element in self {
      await body(element)
    }
  }
}

세 모드 모두 진단이 0 개다. body 도 부른 쪽 isolation 에서 돌게 하니 @concurrent 로 넘어가는 경계가 없어진다.


SE-0420 이후의 변화: nonisolated(nonsending)

이 제안이 푼 것은 “부른 쪽 isolation 을 parameter 로 받아서 그대로 쓰기” 였다. 쓰기에 번거로운 쪽 약점이 컸고, 그 약점은 SE-0461 이 풀었다. 같은 일을 nonisolated(nonsending) 한 단어로 쓴다.

1
2
3
4
nonisolated(nonsending) func work(_ ns: NonSendable) async -> NonSendable {
  ns.value += 1
  return ns
}

호출하는 쪽은 @MainActor final class Model 과 actor Worker 에서 ns = await work(ns) 로 부른다. 세 모드 모두 진단이 0 개다. 처음 본 Reset 의 work(_:) 가 막힌 것이 @concurrent 였는데, nonisolated(nonsending) 으로 바꾸면 같은 호출이 통과한다.

SE-0420 이 없어진 것은 아니다. nonisolated(nonsending) 도 내부적으로는 부른 쪽 isolation 을 숨은 parameter 로 받는 방식이고, 그 숨은 parameter 의 도구가 이 제안의 isolated parameter 다. isolated parameter 를 직접 받아서 값으로 쓰는 일(예: actor 를 다른 함수에 넘기기)은 지금도 이 제안의 문법이다. 앞에서 본 withCheckedContinuation 이 isolation: 판을 @_disfavoredOverload 로 두고 주된 판을 nonisolated(nonsending) 으로 바꾼 것이 이 변화의 한 예다.


마이그레이션

제안서의 Implications for adoption 이 정리하는 것은 세 가지다.

1. ABI 영향. 이미 있는 isolated parameter 에 #isolation 기본값을 더하는 것은 ABI 를 깨지 않는다. 없던 parameter 를 새로 추가하는 것은 ABI 를 깬다. 그래서 @_unsafeInheritExecutor 를 쓰던 함수에 isolation: isolated (any Actor)? = #isolation 을 더하면 호출하는 소스는 그대로 컴파일되지만(source compatible), 바이너리끼리의 약속인 ABI 는 바뀐다. 이미 배포된 라이브러리는 기존 함수를 두고 isolation: 을 받는 새 overload 를 더하는 식으로 옮긴다. 6.4 의 진단이 대안으로 안내하는 것도 이 parameter 다.

2. 물려받는 것은 크게 부담이 아니다. isolation 을 물려받는 함수는 어떤 isolated context 에서 불려도 돌아가야 한다. 제안서는 이것이 겉보기에는 강한 보장 같지만 실제로는 nonisolated 로 두는 것과 크게 다르지 않다고 적는다. 두 경우 모두 함수가 기댈 수 있는 isolation 전제가 없기 때문이다. 그래서 라이브러리 저자가 이 제안을 채택하는 데 망설일 필요가 없다고 한다.

3. 오래 걸리는 일은 나눈다. 제안서가 채택을 조심할 만한 이유로 드는 것은 actor 를 오래 점유하는 “hangover” 다. isolation 을 물려받는 함수가 오래 돌면 부른 actor 의 다른 task 가 그동안 기다려야 한다. 제안서는 계산이 많은 일은 nonisolated 로 두고, 대개 빨리 끝나는 빠른 경로만 isolation 을 물려받는 함수로 빼는 것이 좋은 분리라고 제안한다.

기존 코드를 옮길 때는 이렇게 하면 된다.

지금 쓰는 것바꿀 것
@_unsafeInheritExecutorisolation: isolated (any Actor)? = #isolation parameter (6.4 에서는 Swift 6 모드 error)
직접 actor 를 넘기는 isolated parameter그대로, 필요하면 optional 로 넓힌다
isolation: isolated (any Actor)? = #isolation 으로 부른 쪽 isolation 에서 돌게 한 async 함수nonisolated(nonsending) (SE-0461). 함수 안에서 isolation 값을 직접 쓰면 parameter 를 그대로 둔다

정리

  • nonisolated async 함수는 부른 actor 를 떠나고 동기 함수는 물려받는다. 이 비대칭 때문에 async 범용 도구에는 Sendable 제약이 붙었다. 6.4 의 Reset 이 7:24 에서 @concurrent 로 error 가 나는 것이 그 모양이다.
  • SE-0420 은 isolated parameter 를 optional 과 any Actor 로 넓히고, 기본 인자 #isolation 으로 부른 쪽 isolation 이 저절로 전달되게 했다. #isolation 은 nil, T.shared, actor 참조로 펼쳐지고 문맥 타입을 따른다.
  • 컴파일러는 값이 같은지가 아니라 값이 어디서 왔는지로 “같은 isolation” 을 판단한다. 6.4 에서 self 는 통과하고 other, MainActor.shared, nil 은 error 이며, other === self 로 감싸도 error 다.
  • 6.4 에서 isolation parameter 에서 파생한 값은 그대로 넘기거나 괄호로 감싼 것만 통과한다. if let, guard let, !, as 로 푼 값은 다른 isolation 으로 본다. Task closure 도 isolation 을 붙잡아야 물려받는다.
  • distributed actor 는 asLocalActor 로 로컬 actor 를 얻고, actor 밖에서는 쓸 수 없다. 표준 라이브러리는 withTaskGroup 등 공개 API 12 곳에서 #isolation 을 기본 인자로 받고, 그중 4 곳은 6.4 에서 nonisolated(nonsending) 판으로 대체되어 deprecated 가 붙었다.
  • 함수 단위 표시, SerialExecutor 타입, 기본값 변경은 ABI 와 개념 분리 때문에 이 제안에서는 채택되지 않았다. 함수 단위 표시는 SE-0461 의 nonisolated(nonsending) 으로 이어졌다.

관련 글


참고자료

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