포스트

[SE-0430] sending parameter and result values

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


제안서 정보

  • 번호: SE-0430
  • 상태: Implemented (Swift 6.0)
  • 저자: Michael Gottesman, Holly Borla, John McCall
  • 리뷰 매니저: Becca Royal-Gordon
  • 이전 제안서: SE-0414 (region based isolation)
  • pitch: Pitch (2024-02-23, 이때 키워드 이름은 transferring)
  • 1차 리뷰: First review (2024-03-22 시작, 04-01 까지)
  • 수정 회부: Returned for revision (2024-04-16, 키워드만 다시 정하라는 결정이고 설계는 accepted in principle)
  • 2차 리뷰: Second review (2024-05-07 시작, 05-13 까지, 이때 키워드는 sendable)
  • 수정 포함 수락: Accepted with modifications (2024-05-14, 키워드는 sending, borrowing sending 금지)
  • amendment pitch: Amendment pitch (2024-06-06, UnsafeContinuation 에도 sending 을 쓰자는 제안)
  • amendment 리뷰: Amendment review (2024-06-21 시작, 06-28 까지)
  • amendment 수락: 2024-07-17 (같은 스레드의 결정 글)

한 줄 요약

parameter 나 결과 타입에 sending 을 붙이면 “이 값은 함수 경계에서 어디에도 연결되지 않은 disconnected region 에 있다” 는 약속이 함수 시그니처에 들어간다. 부르는 쪽은 값을 넘긴 뒤 손을 떼야 하고, 받는 쪽은 그 값을 다른 actor 로 보내거나 actor 의 상태에 합쳐도 된다. CheckedContinuation, UnsafeContinuation, AsyncStream.Continuation, Task 의 생성 API 가 이 약속을 쓰도록 바뀌었다.


어떤 문제였나

SE-0414 가 region based isolation 을 들여오면서 non-Sendable 값을 다른 isolation 으로 보내는 길이 열렸다. 다만 그 검사는 함수 안쪽만 본다. 함수 하나를 컴파일할 때 컴파일러는 그 함수 안에서 만든 값이 어디에 연결되어 있는지는 따라갈 수 있지만, 함수 경계 너머에서 무슨 일이 벌어지는지는 모른다. 그래서 경계에서는 보수적으로 가정한다. 호출한 쪽이 넘겨 준 parameter 는 호출한 쪽 region 에 묶인 값이고, 함수가 끝난 뒤에도 호출한 쪽이 계속 쓸 수 있는 값이라고 본다. 이 가정 때문에 “받은 값을 다른 actor 로 넘기는 함수” 를 쓸 수 없었다.


region 과 disconnected 다시 보기

먼저 이 글이 기대는 개념을 짧게 다시 짚는다. 자세한 설명은 SE-0414 글에 있다.

Sendable 은 여러 곳에서 동시에 써도 안전한 타입에 붙이는 표시다. 이 표시가 없는 타입을 이 글에서는 non-Sendable 이라고 부른다. 안에 바뀌는 상태가 있는 평범한 class 가 대표적이다. 이 글의 모든 예제가 다음 class 를 쓴다. mutate() 는 값을 바꾸는 메서드라서 두 곳에서 동시에 부르면 data race 가 날 수 있다는 점을 보여 주는 장치다. 두 번째 함수 sendToMain 은 아무 값이나 main actor 로 보내는 함수이고, 몸체는 비어 있다. 값이 main actor 로 건너가는 순간만 만들어 내려는 것이다.

1
2
3
4
5
6
final class NonSendable {
  var value = 0
  func mutate() { value += 1 }
}

@MainActor func sendToMain<T>(_ t: T) async {}

region 은 “서로 연결되어 있어서 한 덩어리로 다뤄야 하는 값들의 묶음” 이다. 값 a 의 프로퍼티에 값 b 를 넣으면 둘은 같은 region 이 된다. 한쪽을 다른 thread 에 넘기면 다른 쪽도 같이 넘어간 셈이기 때문이다. 어떤 actor 의 상태에도, 호출한 쪽의 값에도 연결되지 않은 새 값은 disconnected region 에 있다고 말한다. NonSendable() 로 방금 만든 값이 그렇다. disconnected 인 값은 통째로 다른 isolation 으로 보낼 수 있다. 다만 보낸 뒤에는 보낸 쪽이 그 값을 다시 쓰면 안 된다. 컴파일러는 이 규칙을 “보낸 줄에 error, 나중에 쓴 줄에 note” 모양으로 알려 준다.

한 가지 더 있다. 함수의 parameter 는 호출한 쪽에서 온 값이므로, 함수 안에서는 task-isolated, 곧 “이 호출을 실행 중인 task 쪽에 묶인 값” 으로 취급된다. 이 글에서 계속 보게 될 문제의 뿌리가 이 취급이다. 함수 안에서 만든 값은 disconnected 이고 함수가 받은 값은 task-isolated 이니, 받은 값은 어디로도 보낼 수 없다.


받은 값을 보낼 수 없던 함수

제안서 Motivation 의 첫 예제다. trySend 는 non-Sendable parameter ns 를 받아서 main actor 의 함수에 넘기려 한다.

1
2
3
4
5
@MainActor func main(ns: NonSendable) {}

func trySend(ns: NonSendable) async {
  await main(ns: ns)
}

@MainActor 와 async 함수 호출

@MainActor 는 선언을 main actor 에 묶는 표시다. main actor 에 묶인 함수를 다른 곳에서 부르려면 줄을 서야 하고, 그 줄서기가 await 다. await 를 만나는 지점은 값이 isolation 경계를 넘는 지점이기도 하다.

진단은 모두 -emit-sil 로 뽑았다. SIL 은 타입 검사가 끝난 뒤 컴파일러가 분석과 최적화에 쓰는 중간 표현이다. region 검사가 그 SIL 단계에서 돌기 때문에, 타입 검사까지만 하는 -typecheck 로는 이 글의 진단이 나오지 않는다. 파일을 하나씩 따로 컴파일하면 NonSendable 의 선언이 보이지 않으므로, 공용 파일 Common.swift 와 예제 파일 하나를 -wmo 로 같이 컴파일했다.

1
xcrun swiftc -emit-sil -o /dev/null -parse-as-library -wmo -swift-version 6 Common.swift TrySend.swift
1
2
3
4
5
6
7
8
9
10
11
TrySend.swift:4:9: error: sending 'ns' risks causing data races [#RegionIsolation::SendingRisksDataRace]
2 | 
3 | func trySend(ns: NonSendable) async {
4 |   await main(ns: ns)
  |         |- error: sending 'ns' risks causing data races [#RegionIsolation::SendingRisksDataRace]
  |         `- note: sending 'ns' to main actor-isolated global function 'main(ns:)' risks causing data races between main actor-isolated code and code in the current isolation context
5 | }
6 | 

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

between main actor-isolated code and code in the current isolation context 가 위에서 말한 task-isolated 취급이다. 이 함수를 부른 쪽에는 ns 를 아직 쥐고 있는 코드가 있을 수 있다. 그 코드와 main actor 에서 돌 main(ns:) 가 같은 값을 동시에 만질 수 있으니 컴파일러가 막는다. 이 글의 진단 블록에서는 앞으로 맨 끝의 [#RegionIsolation] 과 [#SendingRisksDataRace] 링크 두 줄을 생략한다. 두 줄은 모든 error 끝에 똑같이 붙는다. 뒤의 것은 sending risks data race 진단 문서로 이어진다.


actor initializer 에만 있던 특례

SE-0414 는 한 군데에만 예외를 두었다. actor 의 initializer 가 받는 parameter 는 actor 의 region 안으로 “보내지는” 값으로 본다. actor 의 저장 프로퍼티를 초기화하려면 바깥에서 받은 값이 필요하기 때문이다. 제안서의 예제를 옮겼다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
actor MyActor {
  let ns: NonSendable
  init(ns: NonSendable) {
    self.ns = ns
  }
}

func send() {
  let ns = NonSendable()
  let myActor = MyActor(ns: ns)
  _ = myActor
}

func invalidSend() {
  let ns = NonSendable()
  let myActor = MyActor(ns: ns)
  print(ns)
  _ = myActor
}

func send(ns: NonSendable) {
  let myActor = MyActor(ns: ns)
  _ = myActor
}

send() 는 지역 값을 넘기고 끝이라 통과한다. 나머지 둘이 error 다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
ActorInit.swift:16:17: error: sending 'ns' risks causing data races [#RegionIsolation::SendingRisksDataRace]
14 | func invalidSend() {
15 |   let ns = NonSendable()
16 |   let myActor = MyActor(ns: ns)
   |                 |- error: sending 'ns' risks causing data races [#RegionIsolation::SendingRisksDataRace]
   |                 `- note: sending 'ns' to actor-isolated initializer 'init(ns:)' risks causing data races between actor-isolated and local nonisolated uses
17 |   print(ns)
   |         `- note: access can happen concurrently
18 |   _ = myActor
19 | }

ActorInit.swift:22:17: error: sending 'ns' risks causing data races [#RegionIsolation::SendingRisksDataRace]
20 | 
21 | func send(ns: NonSendable) {
22 |   let myActor = MyActor(ns: ns)
   |                 |- error: sending 'ns' risks causing data races [#RegionIsolation::SendingRisksDataRace]
   |                 `- note: sending 'ns' to actor-isolated initializer 'init(ns:)' risks causing data races between actor-isolated code and code in the current isolation context
23 |   _ = myActor
24 | }

첫 번째는 넘긴 뒤 print(ns) 로 다시 쓴 invalidSend 이고, note 가 그 줄을 가리킨다. 두 번째는 마지막 함수 send(ns:) 다. 넘기는 값이 parameter 라서 “current isolation context” 쪽의 코드가 같은 값을 계속 쓸 수 있다는 뜻이다. 제안서는 이 대목을 이렇게 푼다. “보낸다” 는 동작이 actor initializer 에서는 이미 특례로 쓰이고 있으니, 그 특례를 아무 함수에서나 골라 쓸 수 있게 하자는 것이다. 어떤 함수가 “이 parameter 는 내가 받아서 보내도 된다” 고 시그니처에 말할 수 있게 하는 것이 이 제안서의 출발점이다.


CheckedContinuation 의 구멍

그 시그니처가 없어서 생긴 구멍이 하나 더 있다. 제안서가 든 예는 withCheckedContinuation 이다.

1
2
3
4
5
6
7
8
9
10
11
12
@MainActor var mainActorState: NonSendable?

nonisolated func test() async {
  let ns = await withCheckedContinuation { continuation in
    Task { @MainActor in
      let ns = NonSendable()
      continuation.resume(returning: ns)
      mainActorState = ns
    }
  }
  ns.mutate()
}

withCheckedContinuation 과 Task

  1. withCheckedContinuation(function:_:) 은 콜백 방식으로 결과를 주는 코드를 await 로 기다릴 수 있게 감싸는 함수다. 넘긴 closure 가 받은 continuation 의 resume(returning:) 을 부르면 그 값이 await 의 결과로 돌아온다. Checked 는 continuation 을 정확히 한 번 쓰는지 런타임에 검사한다는 뜻이다.
  2. Task 는 새 비동기 작업을 시작한다. Task { @MainActor in ... } 은 그 작업을 main actor 에서 돌린다.

코드가 하는 일을 따라가 보자. 바깥의 test() 는 nonisolated 라서 특정 actor 에 묶여 있지 않다. 안의 Task 는 main actor 에서 NonSendable 을 새로 만들고, continuation.resume(returning: ns) 로 그 값을 바깥 test() 쪽으로 돌려 준다. 그런데 곧바로 mainActorState = ns 로 같은 값을 main actor 의 전역 상태에도 저장한다. 결과적으로 test() 의 ns 와 mainActorState 는 같은 객체다. 바깥에서 ns.mutate() 를 부르는 순간 main actor 에서 도는 코드와 동시에 같은 객체를 바꿀 수 있다.

제안서의 Motivation 은 예전의 resume(returning:) 이 이 코드를 아무 진단 없이 통과시켰다고 설명한다. resume(returning:) 이 값의 타입에 Sendable 을 요구하지 않았고, 그렇다고 값이 어디에서 왔는지 따지지도 않았기 때문이다. Sendable 을 요구하는 방법은 있었다. 하지만 제안서는 그것이 지나치게 거칠다고 한다. 값이 disconnected region 에 있고 resume(returning:) 뒤에 그 region 의 어떤 값도 다시 쓰이지 않는다면 non-Sendable 값을 넘겨도 안전하기 때문이다. 이 제안서가 sending 으로 표현하려는 것이 바로 그 조건이다.

6.4 에서 같은 코드를 돌리면 이 구멍은 error 로 막힌다.

1
2
3
4
5
6
7
8
9
10
Continuation.swift:7:20: error: sending 'ns' risks causing data races [#RegionIsolation::SendingRisksDataRace]
 5 |     Task { @MainActor in
 6 |       let ns = NonSendable()
 7 |       continuation.resume(returning: ns)
   |                    |- error: sending 'ns' risks causing data races [#RegionIsolation::SendingRisksDataRace]
   |                    `- note: 'ns' used after being passed as a 'sending' parameter; Later uses could race
 8 |       mainActorState = ns
   |                        `- note: access can happen concurrently
 9 |     }
10 |   }

note 의 passed as a 'sending' parameter 가 resume(returning:) 의 parameter 에 sending 이 붙어 있다는 사실을 컴파일러가 이미 알고 있다는 증거다. 그 정의는 뒤의 “Concurrency 라이브러리가 바뀐 곳” 에서 직접 본다. 같은 코드에서 mainActorState = ns 줄을 빼고, 대신 ns.mutate() 와 await sendToMain(ns) 로 돌려 받은 값을 바깥에서 쓰기만 하면 진단은 0개다. 값이 resume 으로 건너간 뒤 main actor 쪽에서 더 쓰지 않으니 안전하다는 판단이다.


무엇이 바뀌나

제안서의 해법은 단순하다. parameter 나 결과 타입 앞에 문맥 키워드(특정 자리에서만 키워드로 읽히는 단어) sending 을 쓴다. 컴파일러가 이 표시를 함수 안쪽과 호출하는 쪽에서 서로 반대 방향으로 쓴다. 받는 함수 안에서는 “이 값은 disconnected 이니 보내도 된다” 는 근거가 되고, 부르는 쪽에서는 “이 값을 이 함수에 넘기면 더는 못 쓴다” 는 제약이 된다. 같은 표시가 한쪽에는 권한이고 다른 쪽에는 책임이라는 점이 이 제안서의 핵심이다. 아래에서 parameter, 결과, 함수 타입, protocol, inout, ownership, overload, 표준 라이브러리 순으로 하나씩 본다.


sending parameter란?

sending parameter 는 “이 인자는 disconnected region 에 있는 값이어야 하고, 호출이 끝난 뒤 부른 쪽은 그 값을 다시 쓰면 안 된다” 를 뜻한다. 부른 쪽의 region 에서 값이 떨어져 나가 받은 함수에게 넘어간다고 보면 된다.

sending parameter 는 함수 경계에서 값을 호출한 쪽에서 떼어 받는 쪽에 넘긴다. 왼쪽 호출한 쪽 상자에 disconnected region 에 있는 ns 가 있고, 점선 경계를 넘어 오른쪽 받는 쪽 상자로 화살표가 간다. 받는 쪽은 그 값을 다른 actor 로 보내거나 actor 의 상태에 합칠 수 있다. 호출한 쪽에는 ns 가 남아 있지만 이제 받는 쪽 region 에 속하고, 다시 쓰면 넘긴 줄에 error 다.

제안서의 예제로 확인한다. acceptSend 는 main actor 의 함수이고 parameter 가 sending 이다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
@MainActor
func acceptSend(_: sending NonSendable) {}

func sendToMainOK() async {
  let ns = NonSendable()
  await acceptSend(ns)
}

func sendToMainThenUse() async {
  let ns = NonSendable()
  await acceptSend(ns)
  print(ns)
}

func syncSendingCaller() {
  let ns = NonSendable()
  takeSync(ns)
  print(ns)
}

func takeSync(_ ns: sending NonSendable) {}

sendToMainOK 는 새로 만든 값을 넘기고 끝이라 진단이 0개다. 나머지 둘이 error 다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
SendingParam.swift:11:9: error: sending 'ns' risks causing data races [#RegionIsolation::SendingRisksDataRace]
 9 | func sendToMainThenUse() async {
10 |   let ns = NonSendable()
11 |   await acceptSend(ns)
   |         |- error: sending 'ns' risks causing data races [#RegionIsolation::SendingRisksDataRace]
   |         `- note: 'ns' used after being passed as a 'sending' parameter; Later uses could race
12 |   print(ns)
   |         `- note: access can happen concurrently
13 | }
14 | 

SendingParam.swift:17:3: error: sending 'ns' risks causing data races [#RegionIsolation::SendingRisksDataRace]
15 | func syncSendingCaller() {
16 |   let ns = NonSendable()
17 |   takeSync(ns)
   |   |- error: sending 'ns' risks causing data races [#RegionIsolation::SendingRisksDataRace]
   |   `- note: 'ns' used after being passed as a 'sending' parameter; Later uses could race
18 |   print(ns)
   |         `- note: access can happen concurrently
19 | }
20 | 

첫 번째는 그림의 경우 그대로다. 11 번째 줄에서 ns 를 넘겼고 12 번째 줄에서 다시 썼다. error 가 붙는 자리는 쓴 줄이 아니라 넘긴 줄이고, 쓴 줄은 note 로 붙는다. SE-0414 글에서 본 모양과 같다.

두 번째 error 가 눈여겨볼 대목이다. takeSync 는 동기 함수라서 await 가 없고, isolation 경계를 넘지도 않는다. 그래도 error 다. sending 은 “부르는 쪽이 값을 더 쓰지 않는다” 는 계약이므로, 받는 함수가 값을 어디로 보내는지와 상관없이 부르는 쪽에는 같은 제약이 걸린다. 받는 함수 안쪽은 호출한 쪽에게 열려 있지 않다. 제안서도 받은 함수가 값을 다른 곳으로 보낼 수도 있고 다른 parameter 의 region 에 합칠 수도 있으며, 그것은 호출한 쪽에게 보이지 않는다고 쓴다.

Swift 5 언어 모드에서는 같은 코드가 어떻게 보이는지도 확인했다. 컴파일 옵션 -strict-concurrency 의 minimal 과 complete 를 각각 줬다. minimal 은 진단이 0개다. complete 는 같은 위치에 warning 이 나오고, 꼬리에 Swift 6 모드에서는 error 라는 말이 붙는다.

1
2
SendingParam.swift:11:9: warning: sending 'ns' risks causing data races; this is an error in the Swift 6 language mode [#RegionIsolation::SendingRisksDataRace]
SendingParam.swift:17:3: warning: sending 'ns' risks causing data races; this is an error in the Swift 6 language mode [#RegionIsolation::SendingRisksDataRace]

Swift 6 모드에서는 error 이므로 호출한 쪽 region 진단은 minimal 이 조용하고, complete 가 warning, Swift 6 이 error 인 계단이 된다. 이 계단에는 예외가 있다. 함수 타입 변환은 minimal 에서도 warning 이 나오고(Subtyping.swift 7:34 와 15:38), protocol 의 Protocols.swift 는 minimal 에서 0개, complete 에서 task or actor-isolated value cannot be sent warning (25:8 과 43:8) 이다.

이번에는 받는 함수 안쪽에서 sending 이 하는 일이다. 다음 다섯 함수에서 Callee.swift 가 두 쪽을 짝으로 비교한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
func withSending(_ ns: sending NonSendable) async {
  await sendToMain(ns)
}

func withoutSending(_ ns: NonSendable) async {
  await sendToMain(ns)
}

func storeInTask(_ ns: sending NonSendable) {
  Task { @MainActor in
    ns.mutate()
  }
}

func storeInTaskPlain(_ ns: NonSendable) {
  Task { @MainActor in
    ns.mutate()
  }
}

func passingParamToSending(_ ns: NonSendable) async {
  await withSending(ns)
}

withSending 과 storeInTask 는 진단이 0개이고, 나머지 셋은 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
Callee.swift:6:9: error: sending 'ns' risks causing data races [#RegionIsolation::SendingRisksDataRace]
 4 | 
 5 | func withoutSending(_ ns: NonSendable) async {
 6 |   await sendToMain(ns)
   |         |- error: sending 'ns' risks causing data races [#RegionIsolation::SendingRisksDataRace]
   |         `- note: sending 'ns' to main actor-isolated global function 'sendToMain' risks causing data races between main actor-isolated code and code in the current isolation context
 7 | }
 8 | 

Callee.swift:17:8: error: sending 'ns' risks causing data races [#RegionIsolation::SendingRisksDataRace]
15 | func storeInTaskPlain(_ ns: NonSendable) {
16 |   Task { @MainActor in
17 |     ns.mutate()
   |        |- error: sending 'ns' risks causing data races [#RegionIsolation::SendingRisksDataRace]
   |        `- note: 'ns' is captured by a main actor-isolated closure. main actor-isolated uses in closure may race against code in the current isolation context
18 |   }
19 | }

Callee.swift:22:9: error: sending 'ns' risks causing data races [#RegionIsolation::SendingRisksDataRace]
20 | 
21 | func passingParamToSending(_ ns: NonSendable) async {
22 |   await withSending(ns)
   |         |- error: sending 'ns' risks causing data races [#RegionIsolation::SendingRisksDataRace]
   |         `- note: 'ns' is passed as a 'sending' parameter; Uses in callee may race with code in the current isolation context
23 | }

withSending 과 withoutSending 은 몸체가 같고 parameter 앞의 sending 만 다르다. 앞의 것은 통과하고 뒤의 것은 TrySend.swift 와 같은 error 다. sending 이 하는 일이 정확히 그것이다. 함수 시그니처에 sending 을 쓰는 순간, 안에서는 parameter 를 disconnected 값처럼 다룰 수 있다. storeInTask 는 Task 가 main actor 에서 돌 closure 에 ns 를 담아 보내는데, sending 이면 통과하고 storeInTaskPlain 은 막힌다.

마지막 passingParamToSending 이 이 설계의 한계를 보여 준다. 일반 parameter 를 sending 이 붙은 함수에 넘기면 error 다. 일반 parameter 는 호출한 쪽 region 에 묶여 있으니 “넘긴 뒤 못 쓴다” 는 약속을 지킬 수 없기 때문이다. sending 은 값이 disconnected 일 때만 건네줄 수 있고, 한 번 받은 뒤에는 sending 이 아닌 곳으로 흘려 보내도 그 사실이 이어지지 않는다. 시그니처에 sending 을 붙이는 것이 연쇄적이어야 하는 이유다.


sending 결과

결과 타입에 sending 을 붙이면 반대 방향의 약속이 된다. “이 함수는 disconnected region 에 있는 값만 돌려준다.” 호출한 쪽은 그 약속을 믿고, 돌려받은 값을 다른 isolation 으로 보낼 수 있다. 제안서의 예제는 main actor 에 묶인 struct 다.

1
2
3
4
5
6
7
8
9
10
11
12
@MainActor
struct S {
  let ns: NonSendable

  func getNonSendableInvalid() -> sending NonSendable {
    return ns
  }

  func getNonSendable() -> sending NonSendable {
    return NonSendable()
  }
}

저장 프로퍼티 ns 를 그대로 돌려주는 getNonSendableInvalid 가 error 다. 새로 만든 값을 돌려주는 getNonSendable 은 통과한다.

1
2
3
4
5
6
7
8
SendingResult.swift:6:5: error: sending 'self.ns' risks causing data races [#RegionIsolation::SendingRisksDataRace]
 4 | 
 5 |   func getNonSendableInvalid() -> sending NonSendable {
 6 |     return ns
   |     |- error: sending 'self.ns' risks causing data races [#RegionIsolation::SendingRisksDataRace]
   |     `- note: main actor-isolated 'self.ns' cannot be a 'sending' result. main actor-isolated uses may race with caller uses
 7 |   }
 8 | 

self.ns 는 main actor 에 묶여 있는 값이다. 그 값을 돌려주면 돌려받은 쪽과 main actor 쪽이 같은 값을 갖게 되므로 sending 결과가 될 수 없다는 설명이다. 약속을 지킬 수 없는 함수는 시그니처가 아니라 몸체에서 막힌다.

약속을 지키는 쪽에서는 어떤 이득이 있을까. nonisolated 함수가 main actor 의 메서드에서 sending 결과를 받고, 그 값을 다시 main actor 의 함수로 보내 본다. 같은 파일 아래에는 sending 결과를 돌려주는 일반 함수 하나도 같이 넣었다.

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
@MainActor
struct S {
  let ns: NonSendable
  func getNonSendable() -> sending NonSendable {
    return NonSendable()
  }
}

@MainActor func onMain(_: NonSendable) {}

nonisolated func f(s: S) async {
  let ns = await s.getNonSendable()
  await onMain(ns)
}

func makeFrom(_ ns: NonSendable) -> NonSendable { ns }
func makeFromSending(_ ns: NonSendable) -> sending NonSendable { NonSendable() }

func h(_ ns: NonSendable) async {
  let a = makeFrom(ns)
  await sendToMain(a)
}

func hSending(_ ns: NonSendable) async {
  let a = makeFromSending(ns)
  await sendToMain(a)
}

f 와 hSending 은 진단이 0개이고, h 만 error 다.

1
2
3
4
5
6
7
8
SendingResultCaller.swift:21:9: error: sending 'a' risks causing data races [#RegionIsolation::SendingRisksDataRace]
19 | func h(_ ns: NonSendable) async {
20 |   let a = makeFrom(ns)
21 |   await sendToMain(a)
   |         |- error: sending 'a' risks causing data races [#RegionIsolation::SendingRisksDataRace]
   |         `- note: sending 'a' to main actor-isolated global function 'sendToMain' risks causing data races between main actor-isolated code and code in the current isolation context
22 | }
23 | 

getNonSendable() 의 결과가 sending 이라서 f 는 돌려받은 ns 를 다시 main actor 로 보낼 수 있다. 일반 결과와 sending 결과의 차이는 non-Sendable 인자를 받는 factory 에서 드러난다. makeFrom(ns) 는 인자를 그대로 돌려주므로 결과가 호출한 쪽 값과 이어져 있을 수 있고, 컴파일러는 시그니처만 보고 그 가능성을 배제하지 못한다. 그래서 a 는 호출한 쪽 region 에 묶인 값으로 취급되어 보낼 수 없다. 결과에 sending 을 붙인 makeFromSending 은 몸체가 새 값을 만든다는 약속을 시그니처에 적었으므로 같은 코드가 통과한다. 인자 없이 새 값을 만들어 돌려주는 일반 factory 는 이런 걱정이 없어서, 결과에 sending 이 없어도 돌려받은 값을 보내는 코드가 0개다.

sending 이 없으면 어떻게 되는지도 같은 모양으로 측정했다.

1
2
3
4
5
6
7
8
9
10
11
@MainActor
struct S {
  func getPlain() -> NonSendable {
    return NonSendable()
  }
}

nonisolated func g(s: S) async {
  let ns = await s.getPlain()
  _ = ns
}
1
2
3
4
5
6
7
8
9
10
11
12
13
PlainResult.swift:9:20: error: non-Sendable 'NonSendable'-typed result can not be returned from main actor-isolated instance method 'getPlain()' to nonisolated context [#RegionIsolation]
 7 | 
 8 | nonisolated func g(s: S) async {
 9 |   let ns = await s.getPlain()
   |                    `- error: non-Sendable 'NonSendable'-typed result can not be returned from main actor-isolated instance method 'getPlain()' to nonisolated context [#RegionIsolation]
10 |   _ = ns
11 | }

Common.swift:1:13: note: class 'NonSendable' does not conform to the 'Sendable' protocol
1 | final class NonSendable {
  |             `- note: class 'NonSendable' does not conform to the 'Sendable' protocol
2 |   var value = 0
3 |   func mutate() { value += 1 }

getPlain() 도 새 값을 돌려주지만, 시그니처에 sending 이 없어서 컴파일러가 그 사실을 믿을 수 없다. main actor 에 묶인 메서드가 non-Sendable 값을 nonisolated 쪽으로 돌려주는 것 자체가 error 다. sending 결과는 “이 함수의 몸체가 약속하니 믿고 넘겨도 된다” 는 허락 표시다.

결과 쪽에서 한 가지 더 있다. disconnected 인 값을 합치는 경우다. 제안서는 sending 값이 어떻게 계속 sending 값으로 남는지 두 예제로 보인다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
actor MyActor {
  var myNS = NonSendable()

  func g() async {
    let ns = NonSendable()
    myNS = ns
    await sendToMain(ns)
  }
}

func h() async {
  let ns = NonSendable()
  let ns2 = NonSendable()
  let t = (ns, ns2)
  await sendToMain(t)
}
1
2
3
4
5
6
7
8
Merge.swift:7:11: error: sending 'ns' risks causing data races [#RegionIsolation::SendingRisksDataRace]
 5 |     let ns = NonSendable()
 6 |     myNS = ns
 7 |     await sendToMain(ns)
   |           |- error: sending 'ns' risks causing data races [#RegionIsolation::SendingRisksDataRace]
   |           `- note: sending 'self'-isolated 'ns' to main actor-isolated global function 'sendToMain' risks causing data races between main actor-isolated and 'self'-isolated uses
 8 |   }
 9 | }

g 에서 ns 는 처음에는 disconnected 값이다. 그런데 myNS = ns 로 actor 의 저장 프로퍼티에 넣는 순간 actor 의 region 에 합쳐지고, 더는 sending 값이 아니다. 그다음 줄의 sendToMain(ns) 가 error 인 이유다. 반면 h 는 disconnected 값 두 개를 tuple 로 묶어도 진단이 0개다. 제안서의 설명은 “disconnected region 둘을 합치면 새로 생기는 region 도 disconnected” 라는 것이다. 연결되는 대상이 actor 이면 값이 거기에 묶이지만, 연결 대상이 둘 다 아무 데도 묶이지 않은 값이면 아무것도 변하지 않는다.


Sendable 값과 Sendable 타입

앞에서 sending 값이라고 부른 것은 “지금 disconnected 라서 통째로 보낼 수 있는 값” 이고, Sendable 타입은 “값이 어디에 있든 동시에 써도 안전한 타입” 이다. 둘의 관계는 1차 리뷰에서 hborla 가 정리했다(리뷰 #31). 이때는 키워드 이름이 아직 transferring 이었고, Sendable 은 transferring 의 부분집합이라는 설명이다. 이 글의 이름으로 옮기면 Sendable 타입의 값은 항상 안전하게 보낼 수 있으니 sending 이 그 값에 제약을 더하지 않는다는 뜻이다. 같은 글에는 API 를 고르는 기준도 있다. 값이 여러 곳에서 동시에 쓰여야 하면 Sendable, 한 곳으로 넘기기만 하면 sending 을 쓰면 된다는 것이다. 동시에 여러 child task 에서 부르는 map 같은 API 의 closure 는 @Sendable 이어야 하고, 한 곳으로 넘기기만 하는 closure 는 sending 이면 충분하다.

1
2
3
4
5
6
7
8
9
func takesSendingInt(_ x: sending Int) {}

func useInt() {
  let x = 1
  takesSendingInt(x)
  print(x)
}

func closureSending(_ f: sending @escaping () -> Void) {}

Int 는 Sendable 이라서 sending Int 에 넘긴 뒤 print(x) 로 다시 써도 진단이 0개다. 이 파일 전체가 0개다. sending 은 non-Sendable 값을 안전하게 보내기 위한 장치이고, 이미 안전한 값은 그냥 통과한다.


함수 타입 변환

함수 타입에도 sending 이 들어갈 수 있다. parameter 와 결과에 sending 이 붙은 함수 값과 붙지 않은 함수 값 사이의 변환 규칙이 필요하다. 제안서는 일반 타입 T 에 대해 sending T 가 T 의 subtype 이라고 정리한다. subtype 은 “더 구체적인 약속을 하는 타입” 이어서, T 가 필요한 자리에 sending T 를 넣을 수 있다. 문제는 parameter 자리와 결과 자리에서 방향이 서로 반대가 된다는 점이다. 이것을 전문 용어로 parameter 는 반변(contravariant), 결과는 공변(covariant) 이라고 한다.

제안서의 두 예제를 옮겼다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
func sendingParameterConversions(
  f1: @escaping (sending NonSendable) -> Void,
  f2: @escaping (NonSendable) -> Void
) {
  let _: (sending NonSendable) -> Void = f1
  let _: (sending NonSendable) -> Void = f2
  let _: (NonSendable) -> Void = f1
}

func sendingResultConversions(
  f1: @escaping () -> sending NonSendable,
  f2: @escaping () -> NonSendable
) {
  let _: () -> sending NonSendable = f1
  let _: () -> sending NonSendable = f2
  let _: () -> NonSendable = f1
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Subtyping.swift:7:34: error: converting a value of type '(sending NonSendable) -> Void' to type '(NonSendable) -> Void' risks causing data races
 5 |   let _: (sending NonSendable) -> Void = f1
 6 |   let _: (sending NonSendable) -> Void = f2
 7 |   let _: (NonSendable) -> Void = f1
   |                                  |- error: converting a value of type '(sending NonSendable) -> Void' to type '(NonSendable) -> Void' risks causing data races
   |                                  `- note: converting a function typed value with a sending parameter to one without risks allowing actor-isolated values to escape their isolation domain as an argument to an invocation of value
 8 | }
 9 | 

Subtyping.swift:15:38: error: converting a value of type '() -> NonSendable' to type '() -> sending NonSendable' risks causing data races
13 | ) {
14 |   let _: () -> sending NonSendable = f1
15 |   let _: () -> sending NonSendable = f2
   |                                      |- error: converting a value of type '() -> NonSendable' to type '() -> sending NonSendable' risks causing data races
   |                                      `- note: converting a function typed value without a sending result as one with risks allowing actor-isolated values to escape their isolation domain through a result of an invocation of value
16 |   let _: () -> NonSendable = f1
17 | }

함수마다 변환이 세 번씩, 합쳐 여섯 번이고, 그 가운데 error 는 함수마다 하나씩이다. 반변과 공변을 어려운 말 없이 풀면 이렇다. 함수 값을 변수에 넣는 변환은 “받는 자리가 요구하는 약속을 이 함수가 지켜 주는가” 로 판단한다.

parameter 쪽부터 본다. (sending NonSendable) -> Void 자리는 이 함수를 부르는 쪽이 “항상 disconnected 값을 넘길 것” 이라는 약속을 하는 자리다. 이 자리에 f2, 곧 아무 값이나 받는 함수를 넣는 것은 괜찮다. 부르는 쪽이 필요 이상으로 조심스러울 뿐이다. 반대로 (NonSendable) -> Void 자리는 부르는 쪽이 아무 값이나 넘길 수 있다. 여기에 f1, 곧 disconnected 값만 받겠다는 함수를 넣으면 약속이 깨진다. 7 번째 줄의 error 다.

결과 쪽은 방향이 뒤집힌다. () -> sending NonSendable 자리는 이 함수를 부르는 쪽이 결과를 disconnected 로 믿는 자리다. 여기에 결과를 아무 약속 없이 돌려주는 f2 를 넣으면 믿음이 깨진다. 15 번째 줄이다. 반대로 f1 을 () -> NonSendable 자리에 넣는 것은 약속을 하나 쓰지 않을 뿐이라 괜찮다.

함수 타입 변환은 자리가 요구하는 약속보다 지켜지는 약속이 적어지는 방향이 error 다. parameter 는 (NonSendable) -> Void 에서 (sending NonSendable) -> Void 로만 바꿀 수 있고 반대는 7:34 의 error 다. 결과는 () -> sending NonSendable 에서 () -> NonSendable 로만 바꿀 수 있고 반대는 15:38 의 error 다.

그림에서 sending 이 붙은 상자의 위치가 두 쪽에서 반대인 이유가 이것이다. sending 이 붙은 쪽이 parameter 에서는 변환의 도착점이고, 결과에서는 출발점이다. parameter 는 “함수가 요구하는 약속” 이 늘어나는 방향이 위험하고, 결과는 “함수가 지키는 약속” 이 줄어드는 방향이 위험하다. 둘을 하나로 말하면, 자리가 요구하는 약속보다 지켜지는 약속이 적어지는 변환은 error 라는 규칙이다.


protocol 요구사항과 sending

protocol 요구사항에도 sending 을 쓸 수 있다. 그리고 구현이 요구사항을 채울 때 같은 규칙이 적용된다. 요구사항이 “자리” 고 구현이 “함수 값” 이다. 이 구현, 곧 protocol 요구사항을 실제로 채우는 함수를 witness 라고 부른다. 예제는 제안서의 P1, P2 에 반대 방향인 P3, P4 를 더해서 만들었다. 제안서 원문은 Y1, Y2 가 P1 을 따르게 적혀 있는데, 이 글에서는 P2 를 따르도록 바로잡았다.

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
protocol P1 {
  func requirement(_: sending NonSendable)
}

protocol P2 {
  func requirement() -> sending NonSendable
}

struct X1: P1 {
  func requirement(_: sending NonSendable) {}
}

struct X2: P1 {
  func requirement(_: NonSendable) {}
}

struct Y1: P2 {
  func requirement() -> sending NonSendable {
    return NonSendable()
  }
}

struct Y2: P2 {
  let ns: NonSendable
  func requirement() -> NonSendable {
    return ns
  }
}

protocol P3 {
  func requirement() -> NonSendable
}

struct Z1: P3 {
  func requirement() -> sending NonSendable { NonSendable() }
}

protocol P4 {
  func requirement(_: NonSendable)
}

struct Z2: P4 {
  func requirement(_: sending NonSendable) {}
}

X1, X2, Y1, Z1 은 통과하고, Y2 와 Z2 가 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
Protocols.swift:23:8: error: type 'Y2' does not conform to protocol 'P2'
 4 | 
 5 | protocol P2 {
 6 |   func requirement() -> sending NonSendable
   |        `- note: protocol requires function 'requirement()' with type '() -> sending NonSendable'
 7 | }
 8 | 
   :
21 | }
22 | 
23 | struct Y2: P2 {
   |        |- error: type 'Y2' does not conform to protocol 'P2'
   |        `- note: add stubs for conformance
24 |   let ns: NonSendable
25 |   func requirement() -> NonSendable {
   |        `- note: candidate has non-matching type '() -> NonSendable'
26 |     return ns
27 |   }

Protocols.swift:42:8: error: type 'Z2' does not conform to protocol 'P4'
37 | 
38 | protocol P4 {
39 |   func requirement(_: NonSendable)
   |        `- note: protocol requires function 'requirement' with type '(NonSendable) -> ()'
40 | }
41 | 
42 | struct Z2: P4 {
   |        |- error: type 'Z2' does not conform to protocol 'P4'
   |        `- note: add stubs for conformance
43 |   func requirement(_: sending NonSendable) {}
   |        `- note: candidate has non-matching type '(sending NonSendable) -> ()'
44 | }

앞의 함수 타입 규칙과 똑같이 읽힌다. P1 의 요구사항은 sending parameter 를 건네받는 자리인데, 일반 parameter 로 받는 X2 가 채워도 된다. 구현이 요구사항보다 덜 요구하는 쪽이다. 반대인 Z2 는 P4 가 아무 값이나 넘길 수 있다고 해 둔 자리를 sending 으로 요구하는 구현이 채우려 한 것이라 막힌다. 결과도 같다. 일반 결과를 요구하는 P3 는 sending 결과로 채워도 되지만(Z1), sending 결과를 요구하는 P2 를 일반 결과로 채울 수는 없다(Y2). 에러 메시지가 “candidate has non-matching type” 이라고 한 것이 이 규칙을 이름으로 말한다. sending 의 유무가 witness 가 요구사항 자리에 넣을 수 있는, 곧 변환 가능한 타입이냐를 가르는 기준에 들어간다는 뜻이다. X2 는 타입이 요구사항과 달라도 변환이 가능해서 통과한다.


inout sending

parameter 에 inout 과 sending 을 같이 쓸 수 있다. 제안서가 정한 의미는 이렇다. 인자로 넘길 때 값이 disconnected 여야 하고, 함수가 끝날 때 parameter 안에 든 값도 disconnected 여야 한다. 함수 안에서는 actor 의 일과 합치거나 다른 곳으로 보낼 수 있고, 끝나기 전에 새 disconnected 값을 다시 대입하면 된다.

이 의미는 pitch 단계에서 정해졌다. Alejandro 가 Mutex 의 withLock 처럼 값을 inout 으로 빌려주는 API 에 transferring inout 이 맞느냐고 물었고(pitch #2), hborla 는 transferring 이 “받은 쪽이 마음대로 해도 된다” 는 뜻이고 inout 은 “호출한 쪽이 다시 쓴다” 는 뜻이라 어색하다고 답했다(pitch #3). Michael Gottesman 은 inout 을 “들어갈 때 초기화되어 있고 나올 때도 초기화되어 있어야 하는 것” 으로 보는 모델을 내놓았다(pitch #4). 그 모델에서 transferring inout 은 나올 때 값이 disconnected 이기만 하면 되고, 함수 안에서는 합치거나 보내도 된다. 지금의 inout sending 이 이 모델이다. (Mutex 는 SE-0433 이 표준 라이브러리에 넣은 타입이다.)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
func reassigns(_ x: inout sending NonSendable) async {
  await sendToMain(x)
  x = NonSendable()
}

func forgets(_ x: inout sending NonSendable) async {
  await sendToMain(x)
}

actor A {
  var stored = NonSendable()
  func merges(_ x: inout sending NonSendable) {
    stored = x
  }
}

reassigns 는 보낸 뒤 새 값을 다시 대입하므로 진단이 0개다. 나머지 둘이 error 다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Inout.swift:7:9: error: sending 'x' risks causing data races [#RegionIsolation::SendingRisksDataRace]
 5 | 
 6 | func forgets(_ x: inout sending NonSendable) async {
 7 |   await sendToMain(x)
   |         |- error: sending 'x' risks causing data races [#RegionIsolation::SendingRisksDataRace]
   |         `- note: sending 'x' to main actor-isolated global function 'sendToMain' risks causing data races between main actor-isolated and local nonisolated uses
 8 | }
   | `- note: 'inout sending' parameter must be reinitialized before function exit with a non-actor-isolated value
 9 | 
10 | actor A {

Inout.swift:14:3: error: 'inout sending' parameter 'x' cannot be 'self'-isolated at end of function [#RegionIsolation]
12 |   func merges(_ x: inout sending NonSendable) {
13 |     stored = x
14 |   }
   |   |- error: 'inout sending' parameter 'x' cannot be 'self'-isolated at end of function [#RegionIsolation]
   |   `- note: 'self'-isolated 'x' risks causing races in between 'self'-isolated uses and caller uses since caller assumes value is not actor isolated
15 | }
16 | 

forgets 는 보낸 뒤 대입하지 않았다. 함수가 끝나는 자리, 곧 8 번째 줄의 } 에 note 가 붙는다. “inout sending parameter 는 함수가 끝나기 전에 actor 에 묶이지 않은 값으로 다시 채워야 한다” 는 것이다. merges 는 actor 의 저장 프로퍼티 stored 에 x 를 넣어서 x 가 actor 의 region 에 합쳐진 채 끝난다. 호출한 쪽은 인자가 여전히 disconnected 라고 믿는데, actor 쪽에서도 같은 값을 쥐고 있게 되므로 14 번째 줄 } 에서 막힌다.


sending 과 ownership

sending 은 값의 소유권에도 관여한다. Swift 에는 parameter 의 소유권을 적는 modifier 가 있다. consuming 은 “함수가 이 값을 가져가서 마음대로 쓴다”, borrowing 은 “함수가 잠깐 빌려서 읽기만 한다” 는 뜻이다. 이것을 ownership modifier 라고 부르고, SE-0377 에서 도입되었다.

제안서는 sending parameter 가 기본으로 consuming 이라고 쓴다. 값을 받는 함수가 가져가는 것이므로 자연스럽다. 다만 consuming parameter 와 다른 점이 하나 있다고도 쓴다. 한 값을 두 번 consume 하는 것을 막는 no-implicit-copy 의미가 sending 에는 없고, 그것을 원하면 consuming sending 으로 같이 써야 한다는 설명이다. 6.4 에서 이 설명을 하나씩 측정했다. 먼저 Ownership.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
func reassignInside(_ x: sending NonSendable) {
  x = NonSendable()
  _ = x
}

func consumingSending(_ x: consuming sending NonSendable) {
  let y = x
  _ = y
}

func useConsumingSending() {
  let ns = NonSendable()
  consumingSending(ns)
}

func take(_ x: consuming NonSendable) {}

func sendingTwice(_ x: sending NonSendable) {
  take(x)
  take(x)
}

func consumingSendingTwice(_ x: consuming sending NonSendable) {
  take(x)
  take(x)
}

func consumingTwice(_ x: consuming NonSendable) {
  take(x)
  take(x)
}

func plainTwice(_ x: NonSendable) {
  take(x)
  take(x)
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
Ownership.swift:23:30: error: 'x' consumed more than once
21 | }
22 | 
23 | func consumingSendingTwice(_ x: consuming sending NonSendable) {
   |                              `- error: 'x' consumed more than once
24 |   take(x)
   |        `- note: consumed here
25 |   take(x)
   |        `- note: consumed again here
26 | }
27 | 

Ownership.swift:28:23: error: 'x' consumed more than once
26 | }
27 | 
28 | func consumingTwice(_ x: consuming NonSendable) {
   |                       `- error: 'x' consumed more than once
29 |   take(x)
   |        `- note: consumed here
30 |   take(x)
   |        `- note: consumed again here
31 | }
32 | 

take 는 값을 가져가는 consuming parameter 를 가진 함수다. 이 함수에 같은 x 를 두 번 넘기면 error 가 나는 것은 consuming sending 과 consuming 이고, sending 만 붙은 sendingTwice 와 아무것도 안 붙은 plainTwice 는 진단이 0개다. 제안서의 설명 그대로다. sending 은 값을 넘겨 받는 약속이지만 “두 번 못 쓴다” 는 검사까지 따라오지는 않고, 그 검사는 consuming 을 같이 써야 받는다. sending parameter 에 새 값을 대입하는 것(reassignInside)과 consuming sending 인 값을 let y = x 로 옮겨 담는 것(consumingSending)은 모두 통과한다. 이어서 명시적인 consume 은 Consuming2.swift 로 따로 봤다.

1
2
3
4
5
6
7
8
9
func explicitConsume(_ x: consuming NonSendable) {
  _ = consume x
  _ = x
}

func explicitConsumeSending(_ x: sending NonSendable) {
  _ = consume x
  _ = x
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
Consuming2.swift:1:24: error: 'x' used after consume
 1 | func explicitConsume(_ x: consuming NonSendable) {
   |                        `- error: 'x' used after consume
 2 |   _ = consume x
   |               `- note: consumed here
 3 |   _ = x
   |     `- note: used here
 4 | }
 5 | 

Consuming2.swift:6:31: error: 'x' used after consume
 4 | }
 5 | 
 6 | func explicitConsumeSending(_ x: sending NonSendable) {
   |                               `- error: 'x' used after consume
 7 |   _ = consume x
   |               `- note: consumed here
 8 |   _ = x
   |     `- note: used here
 9 | }
10 | 

consume 연산자는 변수의 값을 “여기서 끝” 으로 넘기는 표시이고, 그 뒤에 쓰면 error 다. 이 error 는 consuming 이든 sending 이든 똑같이 나온다. 앞의 결과와 합치면 sending 은 소유권을 넘긴다는 점에서 consuming 과 같은 길을 가고, 복사를 막는 검사만 consuming sending 이어야 받는다.

반대쪽 borrowing 은 어떤지도 봤다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
func b(_ x: borrowing NonSendable) {
  let a = x
  _ = a
}
func c(_ x: consuming NonSendable) {
  let a = x
  let b = x
  _ = (a, b)
}
func d(_ x: consuming [Int]) {
  let a = x
  let b = x
  _ = (a, b)
}
1
2
3
4
5
6
7
Borrow2.swift:1:10: error: 'x' is borrowed and cannot be consumed
 1 | func b(_ x: borrowing NonSendable) {
   |          `- error: 'x' is borrowed and cannot be consumed
 2 |   let a = x
   |           `- note: consumed here
 3 |   _ = a
 4 | }

borrowing parameter 를 let a = x 로 복사하는 것은 error 다. c 와 d 는 consuming 이라서 0개다. 빌려 온 값은 가져갈 수 없다는 규칙이다. borrowing 과 sending 을 같이 쓰는 것은 아예 금지되어 있다. 이유는 아래 “borrowing sending 을 막은 이유” 에서 본다.

1
func borrowSend(_ x: borrowing sending NonSendable) {}
1
2
3
4
Borrowing.swift:1:32: error: 'sending' cannot be used together with 'borrowing'
1 | func borrowSend(_ x: borrowing sending NonSendable) {}
  |                                `- error: 'sending' cannot be used together with 'borrowing'
2 | 

한 가지 더 있다. sending 은 함수 타입의 가장 바깥 parameter 와 결과 자리에서만 쓸 수 있다. tuple 의 한 원소에는 붙일 수 없다.

1
2
3
func tupleResult() -> (sending NonSendable, NonSendable) {
  (NonSendable(), NonSendable())
}
1
2
3
4
5
Tuple.swift:1:24: error: 'sending' cannot be applied to tuple elements
1 | func tupleResult() -> (sending NonSendable, NonSendable) {
  |                        `- error: 'sending' cannot be applied to tuple elements
2 |   (NonSendable(), NonSendable())
3 | }

1차 리뷰에서 hborla 가 이 제한을 설명했다(리뷰 #46). sending 은 함수 타입 안의 중첩된 자리에서만 허용되는 한정자이고, tuple 의 원소는 그런 자리가 아니라는 이유다.


overload 와 이름

sending 이 붙은 함수와 붙지 않은 함수를 overload 로 같이 둘 수 있을까. 두 함수를 만들고 불러 봤다.

1
2
3
4
5
6
func overload(_: sending NonSendable) {}
func overload(_: NonSendable) {}

func callOverload() {
  overload(NonSendable())
}
1
2
3
4
5
6
7
8
9
10
11
Overload.swift:5:3: error: ambiguous use of 'overload'
1 | func overload(_: sending NonSendable) {}
  |      `- note: found this candidate 
2 | func overload(_: NonSendable) {}
  |      `- note: found this candidate 
3 | 
4 | func callOverload() {
5 |   overload(NonSendable())
  |   `- error: ambiguous use of 'overload'
6 | }
7 | 

ambiguous use 다. 선언은 통과하지만 부르는 순간 컴파일러가 둘 중 하나를 고르지 못한다. 1차 리뷰에서 hborla 가 이유를 설명했다(리뷰 #43). overload 를 고르는 단계가 region 분석보다 훨씬 앞이라서, 그 시점에는 인자가 disconnected 인지 알 수 없다는 것이다. 그래서 parameter 에 바로 붙은 sending 은 overload 를 구분하는 기준이 될 수 없다. 반면 함수 타입 안에 들어간 sending 은 타입의 일부이므로 구분이 된다.

1
2
3
4
struct GenericType<T> {}

func nested(_: GenericType<(NonSendable) -> Void>) {}
func nested(_: GenericType<(sending NonSendable) -> Void>) {}

이 파일은 진단이 0개다. GenericType<(NonSendable) -> Void> 와 GenericType<(sending NonSendable) -> Void> 는 서로 다른 타입이라서 두 선언이 공존한다.

같은 선이 함수의 “이름” 에도 있다. 컴파일러는 함수 이름과 타입을 한 문자열로 줄여 바이너리에 남긴다. 이 변환을 mangling 이라고 한다. 같은 이름의 함수 둘을 구분하고, 라이브러리가 다른 모듈의 함수를 가리키는 데 쓰는 이름이다. sending 을 붙이면 이 이름이 바뀌는지 직접 라이브러리를 만들어 확인했다.

1
2
3
4
5
6
public final class Box {}
public func plain(_ x: Box) {}
public func sendingParam(_ x: sending Box) {}
public func sendingResult() -> sending Box { Box() }
public func consumingParam(_ x: consuming Box) {}
public func ownedParam(_ x: __owned Box) {}
1
xcrun swiftc -emit-library -module-name M -parse-as-library -swift-version 6 Mangle.swift -o libM.dylib

nm libM.dylib 로 심볼을 뽑고 xcrun swift-demangle -compact 로 되돌린 결과다. 왼쪽이 심볼, 오른쪽이 읽을 수 있게 되돌린 이름이다. nm 이 심볼 앞에 밑줄을 하나 더 붙인다.

1
2
3
4
5
_$s1M5plainyyAA3BoxCF            M.plain(M.Box) -> ()
_$s1M12sendingParamyyAA3BoxCnF   M.sendingParam(__owned M.Box) -> ()
_$s1M14consumingParamyyAA3BoxCnF M.consumingParam(__owned M.Box) -> ()
_$s1M10ownedParamyyAA3BoxCnF     M.ownedParam(__owned M.Box) -> ()
_$s1M13sendingResultAA3BoxCyF    M.sendingResult() -> M.Box

sendingParam, consumingParam, ownedParam 은 이름 끝이 AA3BoxCnF 로 같고, plain 의 AA3BoxCF 와는 n 이 하나 더 있는 점이 다르다. 이 n 이 ownership 표시이고, sending parameter 가 consuming 과 같은 소유권을 갖는다는 앞의 설명이 이름에도 그대로 나타난다. 결과 쪽 sendingResult 는 sending 이 이름에 아무 흔적도 남기지 않는다. 함수 타입 안에 들어간 sending 은 다르다.

1
2
3
4
public class Box {}
public struct G<T> {}
public func nestedPlain(_: G<(Box) -> Void>) {}
public func nestedSending(_: G<(sending Box) -> Void>) {}
1
2
_$s1M11nestedPlainyyAA1GVyyAA3BoxCcGF     M.nestedPlain(M.G<(M.Box) -> ()>) -> ()
_$s1M13nestedSendingyyAA1GVyyAA3BoxCnYucGF M.nestedSending(M.G<(sending __owned M.Box) -> ()>) -> ()

nestedSending 의 이름에는 Yu 라는 표시가 들어가고, 되돌린 이름에도 sending 이 그대로 적힌다. 1차 리뷰에서 hborla 는 선언의 parameter 와 결과에 바로 붙은 sending 은 mangling 에서 빼자고 제안했다(리뷰 #43). 이름을 지키려고 @_silgen_name 같은 보존 장치를 따로 쓰지 않아도 되게 하자는 취지였다. 6.4 에서 측정한 모양이 그 제안과 같은 선을 따른다. 바로 붙은 sending 은 overload 의 기준이 되지 못하고 이름에도 따로 남지 않으며, 함수 타입 안에 들어간 sending 은 overload 의 기준도 되고 이름에도 남는다.

제안서의 ABI 설명과 같이 읽는다. ABI 는 이미 컴파일된 바이너리끼리 서로를 부르는 약속이고, library evolution 은 앱을 다시 빌드하지 않고도 라이브러리를 새 판으로 바꿀 수 있게 하는 빌드 모드다. 제안서는 “library evolution 을 쓰는 라이브러리는 sending 이 mangling 을 바꾸므로 @_silgen_name 으로 이름을 보존해야 하고, ownership 은 원래와 같게 유지해야 한다” 고 쓴다. 위 측정에서는 parameter 의 n, 곧 ownership 표시가 plain 과 sendingParam 의 차이였다. 이미 consuming 이던 parameter 에 sending 을 붙이면 이름이 같다는 말이다.


Concurrency 라이브러리가 바뀐 곳

제안서는 표준 라이브러리 Concurrency 모듈의 API 몇 개가 Sendable 대신 sending 을 쓰도록 바꾼다고 한다. CheckedContinuation.resume(returning:), UnsafeContinuation.resume(returning:), AsyncStream 과 AsyncThrowingStream 의 continuation 에 있는 yield, 그리고 Task 를 만드는 API 들이다. 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
func streamExample() async {
  let (stream, continuation) = AsyncStream<NonSendable>.makeStream()
  let ns = NonSendable()
  continuation.yield(ns)
  ns.mutate()
  continuation.finish()
  for await _ in stream {}
}

func unsafeContinuation() async {
  let ns = await withUnsafeContinuation { (c: UnsafeContinuation<NonSendable, Never>) in
    let value = NonSendable()
    c.resume(returning: value)
    value.mutate()
  }
  _ = ns
}

func taskInit() async {
  let ns = NonSendable()
  let t = Task {
    ns.mutate()
  }
  ns.mutate()
  await t.value
}

세 함수 모두 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
Stream.swift:4:16: error: sending 'ns' risks causing data races [#RegionIsolation::SendingRisksDataRace]
 2 |   let (stream, continuation) = AsyncStream<NonSendable>.makeStream()
 3 |   let ns = NonSendable()
 4 |   continuation.yield(ns)
   |                |- error: sending 'ns' risks causing data races [#RegionIsolation::SendingRisksDataRace]
   |                `- note: 'ns' used after being passed as a 'sending' parameter; Later uses could race
 5 |   ns.mutate()
   |      `- note: access can happen concurrently
 6 |   continuation.finish()
 7 |   for await _ in stream {}

Stream.swift:13:7: error: sending 'value' risks causing data races [#RegionIsolation::SendingRisksDataRace]
11 |   let ns = await withUnsafeContinuation { (c: UnsafeContinuation<NonSendable, Never>) in
12 |     let value = NonSendable()
13 |     c.resume(returning: value)
   |       |- error: sending 'value' risks causing data races [#RegionIsolation::SendingRisksDataRace]
   |       `- note: 'value' used after being passed as a 'sending' parameter; Later uses could race
14 |     value.mutate()
   |           `- note: access can happen concurrently
15 |   }
16 |   _ = ns

Stream.swift:21:11: error: sending value of non-Sendable type '() async -> ()' risks causing data races [#RegionIsolation::SendingRisksDataRace]
19 | func taskInit() async {
20 |   let ns = NonSendable()
21 |   let t = Task {
   |           |- error: sending value of non-Sendable type '() async -> ()' risks causing data races [#RegionIsolation::SendingRisksDataRace]
   |           `- note: Passing value of non-Sendable type '() async -> ()' as a 'sending' argument to initializer 'init(name:priority:operation:)' risks causing races in between local and caller code
22 |     ns.mutate()
23 |   }
24 |   ns.mutate()
   |      `- note: access can happen concurrently
25 |   await t.value
26 | }

AsyncStream.Continuation 과 UnsafeContinuation 과 Task 초기화

  1. AsyncStream 은 값을 하나씩 흘려 보내는 비동기 sequence 다. makeStream(of:bufferingPolicy:) 가 stream 과 그 stream 에 값을 넣는 continuation 을 한 쌍으로 만들어 준다. yield(_:) 가 값을 하나 흘려 보내고, finish() 가 stream 을 끝낸다. for await _ in stream {} 은 값이 올 때마다 하나씩 받는 반복문이다.
  2. UnsafeContinuation 은 CheckedContinuation 에서 “정확히 한 번 쓰는지” 검사를 뺀 버전이다. withUnsafeContinuation(_:) 로 얻는다.
  3. Task { ... } 는 새 비동기 작업을 시작하는 Task 의 초기화 구문이고, closure 가 task 가 돌릴 일이다. await t.value 는 그 task 가 끝나기를 기다리는 코드다.

첫 번째 yield 는 값을 stream 에 넘기는 순간 ns 는 값을 받는 쪽으로 가고, 그 뒤 ns.mutate() 로 다시 쓰면 note 가 붙는다. 두 번째는 앞에서 본 CheckedContinuation 과 같은 모양인데 UnsafeContinuation 에서 error 가 난다. 이 구멍이 amendment 로 막힌 것이고, 뒤의 “UnsafeContinuation 을 예외로 두기” 에서 이유를 다시 본다. 세 번째 error 는 모양이 다르다. 경계를 넘기는 대상이 ns 가 아니라 Task 에 넘긴 closure 자체다. closure 가 ns 를 붙잡고 있으니 closure 도 non-Sendable 이고, 그 closure 를 Task 에 sending 으로 넘긴 뒤 ns 를 다시 쓰면 error 라는 설명이다. note 가 init(name:priority:operation:) 이라고 하는 곳이 Task 초기화 API 의 operation parameter 가 sending 이라는 증거다.

표준 라이브러리 선언을 직접 확인했다. Xcode 27 SDK 의 _Concurrency.swiftmodule/arm64e-apple-macos.swiftinterface 에서 해당 선언을 뽑았고, 읽기 쉽도록 _Concurrency:: 와 Swift:: 접두어를 지웠다. 이 가운데 @_alwaysEmitIntoClient 가 붙은 함수는 호출하는 쪽 바이너리에 코드가 들어간다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// CheckedContinuation<T, E>
public func resume(returning value: sending T)

// withCheckedContinuation (nonisolated(nonsending) 은 부르는 쪽의 isolation 에서 실행한다는 표시다)
@inlinable @_alwaysEmitIntoClient nonisolated(nonsending) public func withCheckedContinuation<T>(function: String = #function, _ body: (CheckedContinuation<T, Never>) -> Void) async -> sending T

// UnsafeContinuation<T, E>
@_alwaysEmitIntoClient public func resume(returning value: sending T) where E == Never

// withUnsafeContinuation
@_alwaysEmitIntoClient @unsafe nonisolated(nonsending) public func withUnsafeContinuation<T>(_ fn: (UnsafeContinuation<T, Never>) -> Void) async -> sending T

// AsyncStream<Element>.Continuation
public func yield(_ value: sending Element) -> AsyncStream<Element>.Continuation.YieldResult
public func yield(with result: __shared sending Result<Element, Never>) -> AsyncStream<Element>.Continuation.YieldResult

// Task
@_alwaysEmitIntoClient public init(name: String? = nil, priority: TaskPriority? = nil, @_inheritActorContext @_implicitSelfCapture operation: sending @escaping @isolated(any) () async -> Success)
@_alwaysEmitIntoClient public static func detached(name: String? = nil, priority: TaskPriority? = nil, operation: sending @escaping @isolated(any) () async -> Success) -> Task<Success, Never>

// TaskGroup
@_alwaysEmitIntoClient public mutating func addTask(name: String?, priority: TaskPriority? = nil, operation: sending @escaping @isolated(any) () async -> ChildTaskResult)

CheckedContinuation 과 UnsafeContinuation 의 resume 과 sending 결과

CheckedContinuation.resume(returning:) 와 UnsafeContinuation.resume(returning:) 은 parameter 가 sending T 다. 앞에서 본 구멍은 이 sending 덕분에 닫혔다. 두 with...Continuation 함수의 결과도 async -> sending T 로 바뀌었다. 안쪽에서 resume 으로 값을 넣는 쪽은 sending 으로 넣고, 바깥에서 await 로 받는 쪽은 sending 결과로 받는다는 양 끝의 짝이다.

AsyncStream.Continuation 의 yield

yield(_:) 는 sending Element 이다. 이름 하나 아래 yield(with:) 도 있는데 parameter 가 __shared sending Result<Element, Never> 이다. __shared 는 소유권을 sending 이 기본으로 주는 consuming 이 아니라 빌려 쓰는 쪽으로 바꾸는 표시다. 수락 글은 표준 라이브러리가 compiler-internal facility(컴파일러 내부 장치)를 임시로 써서 ABI 를 지키겠다고 했고, SDK 의 yield(with:) 에 실제로 붙은 것이 __shared sending 이다. 원래 소유권을 유지하면서 sending 을 붙이는 데 쓴 것으로 읽힌다.

Task 의 init 과 detached 와 addTask

Task.init, Task.detached, TaskGroup.addTask 의 operation 은 sending @escaping @isolated(any) closure 다. closure 를 sending 으로 받는다는 뜻이라서, closure 가 붙잡은 값들이 모두 disconnected 일 때만 새 task 로 보낼 수 있다. (@isolated(any) 는 SE-0431 의 함수 타입 표시로 이 글의 주제가 아니고, nonisolated(nonsending) 도 SE-0461 의 별개 기능이다.)

옛 심볼을 지키는 함수도 SDK 에 남아 있다. 함수 이름이 _unsafeInheritExecutor_withCheckedContinuation 으로 바뀐 뒤에도, 이전에 컴파일된 바이너리가 부르던 심볼을 그대로 유지하려고 @_silgen_name 을 붙인 것이다.

1
@_silgen_name("$ss23withCheckedContinuation8function_xSS_yScCyxs5NeverOGXEtYalF") @_unsafeInheritExecutor public func _unsafeInheritExecutor_withCheckedContinuation<T>(function: String = #function, _ body: (CheckedContinuation<T, Never>) -> Void) async -> T

@_silgen_name 은 컴파일러가 만드는 이름 대신 직접 적은 이름을 심볼로 쓰라는 표시다. 이 함수의 사연은 sending 과 별개다. 앞에서 본 것처럼 결과에 바로 붙은 sending 은 심볼 이름에 남지 않는다.


기대 효과

sending 이 들어와서 달라지는 점이 셋이다.

첫째, 값의 소유권 이동을 시그니처에 적을 수 있다. 전에는 non-Sendable 값을 actor 사이에 옮기는 함수를 만들려면 값을 @unchecked Sendable 상자에 담거나, 타입 전체를 @unchecked Sendable 로 선언해서 컴파일러를 믿어 달라고 해야 했다. 이제는 parameter 에 sending 을 붙이면 컴파일러가 부르는 쪽을 검사해 준다. 약속을 코드 바깥의 문서가 아니라 시그니처가 갖는다.

둘째, continuation 구멍이 닫혔다. 앞에서 본 CheckedContinuation 과 UnsafeContinuation 의 resume(returning:) 에서 값을 넘기고 다시 쓰는 코드, AsyncStream 의 yield 뒤에 값을 다시 쓰는 코드, Task 에 넘긴 closure 가 붙잡은 값을 다시 쓰는 코드가 모두 error 다.

셋째, 단계적으로 도입할 수 있다. 호출한 쪽 region 진단은 Swift 5 모드의 minimal 에서는 조용하고, complete 에서는 warning 이며, Swift 6 모드에서는 error 라는 앞의 측정이 그것이다. 함수 타입 변환만은 minimal 에서도 warning 이다. 이미 Swift 6 로 옮긴 프로젝트가 아니라면 error 가 한꺼번에 몰려오지 않는다.


다른 선택지는 왜 안 됐나

이 제안서는 설계 자체보다 이름을 두고 가장 오래 논쟁했다. 다음은 그 논쟁과 설계에서 갈라진 선택지 세 가지다.


이름 논쟁

처음 pitch 는 transferring 이었다. 1차 리뷰에서 nkbelov 가 sending 이 어떠냐고 먼저 물었다(리뷰 #4). 이미 있는 Sendable 과의 비유가 좋고, 어차피 non-Sendable 값을 “여전히 보내는” 중이라는 점을 드러낸다는 이유였다.

John McCall 은 바로 반론을 달았다(리뷰 #5). 겉으로 Sendable 값은 send 할 수 있는 것처럼 읽히는데 실제로는 거의 반대라는 것이다. Sendable 값은 언제든 보낼 수 있으니 따로 신경 쓸 필요가 없고, 명시적으로 send 해야 하는 것은 non-Sendable 값이다. 그는 disconnected 가 더 자연스럽다고 보고, 변수나 inout 에도 붙는 한정자로 쓰자고 했다. weak 처럼 타입 자체를 바꾸지 않는 한정자로 두자는 제안이었고, 값 자체를 감싸는 타입이 필요한 경우를 위해서는 Disconnected<T> 같은 타입을 따로 두자는 생각이었다.

Jumhyn 은 같은 sending 을 다른 방향으로 읽었다(리뷰 #6). 타입 전체로는 non-Sendable 인 값이라도 함수 경계에서 “이 값을 정말 보내는 것” 이라고 분명히 적으면 sending T 가 일종의 sendability 를 회복한다는 읽기다. Becca 는 리뷰 매니저 모자를 벗고 의견을 냈다(리뷰 #19). Sendable 이 “자동으로 암묵적인 sending” 이라고 말할 수 있다면 sending 이 더 편하겠지만, sending 이나 transferring 을 붙이면 ABI 가 깨지는 현실에서는 그렇게 말할 수 없다는 것이다.

논쟁 중간에 sendable 이 후보로 올라왔다. John McCall 은 이 이름이 “disconnected 라서 보낼 수 있는 non-Sendable 값” 이라는 개념을 직관적으로 담는다고 인정했다. 다만 sendability 를 이야기하기가 어려워지는 문제가 있다고도 했다(리뷰 #21). Jumhyn 이 구체적으로 짚었다(리뷰 #22). 타입에 붙는 @Sendable 과 parameter 한정자 sendable 이 전혀 다른 뜻인데 이름이 비슷하면 가르치기 어렵다는 것이다. sendable T 가 Sendable 이 아니라는 점도 혼란스럽다. 그래서 sending 을 지지했다. 이 이름은 sendability 의 아이디어를 불러내면서도 명목상으로는 구분되고, -ing 은 경계에서 일어나는 일에 쓰는 형태라는 이유였다.

hborla 는 sending 이 정확한 말이 아니라고 짚었다(리뷰 #38). 필요한 조건이 “보낼 수 있는 값” 보다 엄격하기 때문이다. 이 호출이 isolation 경계를 넘는다면 모든 인자가 “보낼 수 있는” 값이어야 하는데, 그것은 disconnected 이거나 타입이 Sendable 이라는 뜻이다. 그런데 이 제안서의 조건은 값이 다른 인자들과 별개의 region 에 있어야 한다는 것이다. 받는 함수가 그 값을 다른 인자들과 다른 region 에 합칠 수 있어야 하기 때문이다.

2024-04-16 의 수정 회부 글이 이 논쟁을 정리했다. 설계는 accepted in principle 이고, transferring 이라는 단어가 ownership modifier 처럼 들린다는 우려가 컸다. 그래서 키워드만 다시 정하라고 저자에게 돌려보냈다. 2차 리뷰는 sendable 로 올라갔다. Jumhyn 은 sendable 과 Sendable 이 설명하기 어렵다고 다시 말했고(2차 리뷰 #3), throws 와 async 처럼 “해도 된다” 는 허락을 나타내는 말로 sending 을 읽는 편이 낫다고 했다. KeithBauerANZ 도 같은 혼동을 지적했다(2차 리뷰 #5). xwu 는 BitwiseCopyable 과 Fooable 에 빗대어 sendable 이 “~할 수 있다” 는 성질을 나타내는 이름 규칙에는 맞지만 sending 이나 sent 도 괜찮다고 했다(2차 리뷰 #6). 그는 SE-0433 의 Mutex 가 sendable 을 완화로 쓴 점도 짚었다.

Becca 는 2차 리뷰에서 이 제안서가 필요한 이유를 구체적인 모양으로 설명했다(2차 리뷰 #4). 현재 함수가 객체 그래프로 이어지는 외부 참조를 유일하게 쥐고 있고, 그 가운데 어느 참조 하나를 보내는 순간 나머지 참조는 쓸 수 없다는 것이다. 이어서 CurrencyData 예제로, noncopyable 타입이 유일한 소유권을 모델링하고 sending 은 객체 그래프를 다룬다고 설명했다(2차 리뷰 #9).

2024-05-14 의 수락 글이 최종 결정을 냈다. 키워드는 sending 이다. consuming, borrowing, @escaping 과 문법적으로 맞는 -ing 형이라는 점을 이유로 들었다. 나중에 프로퍼티에도 지원하게 되면 -ing 형이 조금 어색할 수 있다는 점도 같이 적었다.


borrowing sending 을 막은 이유

수락 글은 borrowing 과 sending 을 같이 쓰는 것도 금지했다. 앞의 Borrowing.swift 의 error 가 그 결과다. 이유는 borrowing sending 을 나중에 다른 뜻으로 쓸 자리를 남기려는 것이다. 지금 borrowing 은 값의 소유권만 빌리지만, John McCall 이 1차 리뷰에서 설명한 모양은 다르다(리뷰 #29). 현재 제안서의 borrowing transferring 은 쓸모가 거의 없다. borrowing 은 parameter 의 소유권만 바꾸는데 region 의 소유권은 여전히 받는 쪽으로 넘어가서, 부른 쪽이 값으로 할 수 있는 일이 파괴할 책임뿐이기 때문이다. 이 조합이 필요한 경우는 이미 있는 API 에 바이너리 호환을 깨지 않고 transferring 을 붙일 때뿐이다.

그는 borrowing disconnected 처럼 borrowing 이 region 의 소유권까지 바꾸는 쪽이 훨씬 쓸모 있다고 했다. 객체 그래프의 deep copy 가 예다. 그래프 전체를 복사하는 함수는 옛 객체와 새 객체를 연결하는 context 가 필요하다. 이 경우 반환값은 context 와 연결되어 있으므로 disconnected 가 아니다. 그렇다면 옛 객체를 borrowing disconnected 로 받는 쪽이 더 정확하다. 호출 동안 region 을 빌려 쓰고 돌려주는 의미가 되기 때문이다. 이런 쓰임을 위해 borrowing sending 이라는 조합을 지금은 비워 둔다는 것이 수락 글의 설명이다.


UnsafeContinuation 을 예외로 두기

가장 늦게 바뀐 부분이다. 수락된 제안서는 처음에 UnsafeContinuation.resume(returning:) 만 sending 대상에서 뺐다. 이름 그대로 이미 안전하지 않은 타입이라서, sendability 검사에서도 빠지는 열린 문을 두는 것이 어색하지 않다고 본 것이다. 컨티뉴에이션을 같은 actor 안에서 다시 깨우는 코드처럼 sending 도 Sendable 도 과한 사용처가 있다는 점도 이유였다.

2024-06-06 의 amendment pitch 에서 John McCall 이 이 결정을 되돌리자고 했다. 제안서의 Alternatives 에 정리된 논거는 이렇다. UnsafeContinuation 이 위험한 이유는 “정확히 한 번 resume 해야 한다” 는 조건을 검사하지 않는다는 데 있다. 이 위험에 sendability 검사가 빠지는 다른 종류의 위험까지 더하면 놀랍다. 반대로 sendability 검사만 빼고 싶은 프로그래머가 resume 횟수를 확신하지 못하는 경우에도 UnsafeContinuation 을 써야 하는 것은 오히려 나쁜 유도다. 두 continuation 의 인터페이스가 달라지면 문제를 추적하느라 unsafe 에서 checked 로 옮길 때도 불편하다.

선례도 있다. UnsafePointer 는 SE-0302 에서 Sendable 이었다가 SE-0331 에서 그 conformance 가 빠졌다. 안전하지 않은 타입에 다른 종류의 안전하지 않음을 더하지 않겠다는 방향이다. 끝으로 sendability 검사를 끄는 일반적인 방법은 이미 nonisolated(unsafe) 하나가 있다. 여러 API 마다 따로 구멍을 두는 것보다 한 가지 opt-out 으로 모으는 편이 찾고 감사하기 쉽다.

amendment 리뷰는 2024-06-21 에 시작했다(Becca #1). grynspan 과 johannesweiss 가 찬성했고(#2, #3), 2024-07-17 에 수락되었다(Becca #6). 그래서 지금의 UnsafeContinuation.resume(returning:) 은 sending 이고 withUnsafeContinuation 의 결과도 sending 이다. 앞의 Stream.swift 두 번째 error 가 그 결과다.


Disconnected 타입

제안서의 Future directions 에 있는 이야기다. sending 은 함수 경계에서만 disconnected 라는 사실을 표현한다. 값을 저장 프로퍼티나 컬렉션에 넣는 순간 그 사실은 사라진다. 이것을 타입 시스템으로 이어 가려면 Concurrency 라이브러리에 Disconnected 타입을 넣을 수 있다고 한다. 이 타입은 ~Copyable 로 복사를 막고, Sendable 을 따르며, 만들 때 감싸는 값이 disconnected 여야 하고, 다른 isolation region 에 합쳐질 수 없다.

쓰임새는 이렇다. sending T parameter 를 받아서 Disconnected<T> 컬렉션에 쌓아 두었다가, 나중에 꺼내 sending T 결과로 돌려주는 패턴이다. 일부 AsyncSequence 가 non-Sendable 원소를 sending 으로 내줄 때, 구현 안에서 unsafe opt-out 을 쓰지 않아도 된다. John McCall 은 1차 리뷰에서 이런 타입이 T 와 Disconnected<T> 사이에서 암묵적으로 오가면 타입 검사가 예측하기 어려워질 수 있다는 걱정을 적었다(리뷰 #5). 이 방향은 제안서에서도 제안이 아니라 가능성으로만 남아 있다.


마이그레이션

sending 은 이미 있는 코드를 바꾸지 않는다. 제안서의 ABI 절이 “이 제안서는 기존 코드의 컴파일 방식을 바꾸지 않는다” 고 쓴다. 영향은 표준 라이브러리의 API 가 sending 을 쓰게 되면서 부르는 쪽에서 새 진단이 나오는 데서 온다.

먼저 Swift 5 모드의 프로젝트라면 -strict-concurrency=complete 로 warning 부터 본다. 앞의 SendingParam.swift 가 보여 주었듯 호출한 쪽 region 진단은 minimal 이 조용하고 complete 는 warning 이다. 함수 타입 변환은 예외라서 minimal 에서도 warning 이 나온다. 이미 Swift 6 모드이면 error 로 바로 나온다. 어느 쪽이든 고칠 자리는 같다.

  1. resume(returning:) 이나 yield 뒤에서 같은 값을 다시 쓰는 코드는 넘긴 값을 다시 쓰지 않도록 고친다. 다시 써야 한다면 값을 복사해 넘기거나 Sendable 타입으로 바꾼다.
  2. 받은 parameter 를 다른 actor 로 넘기던 함수에는 parameter 에 sending 을 붙인다. 그러면 함수 안의 error 는 사라지고, 부르는 쪽에서 “넘긴 뒤 못 쓴다” 는 제약이 생긴다. 부르는 쪽이 이미 값을 더 쓰지 않는 코드라면 그대로 통과한다.
  3. sending 이 붙은 함수와 안 붙은 함수를 overload 로 같이 두지 않는다. 앞의 Overload.swift 처럼 부르는 순간 ambiguous 다.
  4. 공개 라이브러리에서 parameter 에 sending 을 붙일 때는 이름이 바뀌는지 본다. 앞의 측정에서 plain 과 sendingParam 의 이름은 소유권 표시 하나가 달랐고, 함수 타입 안에 들어간 sending 은 이름에 Yu 로 남았다. library evolution 을 쓰는 라이브러리라면 제안서의 설명대로 @_silgen_name 으로 이름을 보존하면서 소유권을 원래대로 유지한다.

정리

  • sending 은 parameter 와 결과에 붙이는 한정자로, 값이 함수 경계에서 disconnected region 에 있다는 약속을 시그니처에 적는다. 같은 표시가 받는 쪽에는 권한이고 부르는 쪽에는 “넘긴 뒤 다시 쓰지 않는다” 는 책임이다.
  • 6.4 에서 SendingParam.swift 는 넘긴 뒤 쓴 줄에서 error 가 나고, 동기 함수에 넘겨도 같다. 같은 코드가 Swift 5 minimal 에서는 0개, complete 에서는 warning 이다. 함수 타입 변환은 minimal 에서도 warning 이다.
  • 함수 타입 변환과 protocol witness 는 같은 규칙을 따른다. 자리가 요구하는 약속보다 지켜지는 약속이 적어지는 변환은 error 이고, 그래서 parameter 와 결과의 방향이 반대다.
  • Sendable 타입의 값에는 sending 이 제약을 더하지 않는다. inout sending 은 함수가 끝날 때 disconnected 로 다시 채워야 한다. ownership 쪽에서 sending 은 consuming 처럼 값을 넘기지만 두 번 쓰는 것을 막는 검사는 consuming sending 으로 같이 써야 받는다. borrowing sending 은 error 로 막혀 있다.
  • 바로 붙은 sending 은 overload 로 구분되지 않아 모호하고 이름에도 따로 남지 않는다. 함수 타입 안의 sending 은 overload 가 되고 이름에 Yu 로 남는다.
  • CheckedContinuation, UnsafeContinuation, AsyncStream.Continuation, Task 생성 API 가 sending 을 쓴다. UnsafeContinuation 은 처음에 빠졌다가 amendment 로 들어왔다.

관련 글


참고자료

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