[SE-0414] Region based Isolation
이 글은 Swift Evolution 제안서 원문과 포럼 리뷰 스레드를 Claude Code 로 정리한 글이다. 코드는 Xcode 27 의 Swift 6.4 컴파일러로 빌드하고, 진단 메시지와 실행 결과는 실제로 컴파일하고 실행해서 나온 것을 옮겼다.
제안서 정보
- 번호: SE-0414
- 상태: Implemented (Swift 6.0)
- upcoming feature flag:
RegionBasedIsolation(upcoming feature flag 는 다음 언어 모드에서 기본이 될 동작을 지금 미리 켜 보는 컴파일러 옵션이다. 이 기능은 Swift 6 언어 모드에서 기본으로 켜진다) - 저자: Michael Gottesman, Julia Turcotti
- 리뷰 매니저: Holly Borla
- 1차 pitch: Safely sending non-Sendable values across isolation domains (2023-08-03)
- 2차 pitch: Region based Isolation (2023-10-16)
- 1차 리뷰: First review (2023-12-04 시작, 12-18 까지)
- 수정 요청: Returned for revision (2023-12-22)
- 2차 리뷰: Second review (2024-01-30 시작, 02-06 까지)
- 수락: Accepted with modifications (2024-02-15)
- 전제 제안서: SE-0302 (
Sendable과@Sendableclosure), SE-0337 (incremental migration)
한 줄 요약
non-Sendable 값을 actor 나 다른 task 로 넘기는 것을 무조건 막던 규칙을 바꿨다. 넘기는 값과 서로 닿을 수 있는 값들의 묶음을 region 이라 부르고, 컴파일러가 이 묶음을 따라가 보다가 넘긴 뒤에 그 묶음을 쓰는 곳이 없으면 통과시킨다. 쓰는 곳이 있으면 error 는 값을 넘기는 줄에 붙고, 나중에 쓰는 줄은 note 로 붙는다. 6.4 에서 제안서 Motivation 의 openNewAccount 는 모드를 가리지 않고 진단이 0개이고, 같은 함수 끝에 client.logToAuditStream() 한 줄만 더하면 Swift 6 에서 error 가 나온다.
어떤 문제였나
Swift 의 동시성 검사에는 SE-0302 가 정한 규칙이 하나 있다. non-Sendable 값은 isolation 경계를 넘을 수 없다는 규칙이다. 이 제안서의 Motivation 은 이 규칙이 너무 보수적이라는 예에서 시작한다. 새로 만든 값을 actor 안의 함수로 넘기는 코드다. 제안서는 Client 가 non-Sendable 이라서, 이 코드가 옛 규칙으로는 error 였다고 설명한다. 제안서의 코드에서 init 의 본문(...)을 채우고 @main 을 붙여 실행할 수 있게 만든 것이 아래 코드다.
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
// Not Sendable
final class Client {
let name: String
var balance: Double
init(name: String, initialBalance: Double) {
self.name = name
self.balance = initialBalance
}
func logToAuditStream() { print("audit:", name, balance) }
}
actor ClientStore {
var clients: [Client] = []
static let shared = ClientStore()
func addClient(_ c: Client) {
clients.append(c)
}
}
func openNewAccount(name: String, initialBalance: Double) async {
let client = Client(name: name, initialBalance: initialBalance)
await ClientStore.shared.addClient(client)
}
@main struct App {
static func main() async {
await openNewAccount(name: "John", initialBalance: 0)
print("끝")
}
}
openNewAccount 는 Client 를 하나 만들어서 ClientStore.shared 라는 actor 에게 넘긴다. 제안서는 이 코드가 실제로는 안전하다고 세 가지 이유를 든다.
client는 이니셜라이저에 받은String과Double외에 다른 non-Sendable 상태를 가져오지 않는다. 두 타입은 Sendable 이라서 값이 복사되어 들어올 뿐이다.client는 방금 만들어졌으니,openNewAccount밖에서 이 값을 가리키는 곳이 없다.openNewAccount는addClient를 부른 뒤로client를 다시 쓰지 않는다.
6.4 에서 이 코드를 컴파일한 결과는 이렇다. 모드를 가르는 -strict-concurrency 는 Swift 5 모드에서 동시성 검사 수준을 정한다. minimal 이 기본값으로, 동시성을 직접 쓴 코드만 검사한다. complete 는 모든 코드를 Swift 6 와 같은 규칙으로 검사하되 위반을 warning 으로 알린다. region 검사는 SIL 이라는 컴파일러 중간 표현 단계에서 일어나서, 진단을 보려면 -emit-sil 로 컴파일해야 한다. 같은 이유로 -typecheck 는 이 진단을 하나도 내지 않는다.
1
$ xcrun swiftc -emit-sil -o /dev/null -parse-as-library -wmo -swift-version 6 Common.swift Motivation.swift
| 컴파일 모드 | 진단 |
|---|---|
-swift-version 5 | 0개 |
-swift-version 5 -strict-concurrency=complete | 0개 |
-swift-version 6 | 0개 |
세 모드 모두 진단이 없고, -swift-version 6 으로 빌드한 실행 파일은 끝 을 찍고 끝난다. 제안서가 말한 “값을 넘긴 뒤에 쓰지 않으니 안전하다” 는 판단을 컴파일러가 이제 직접 한다는 뜻이다.
제안서는 이 코드 끝에 줄을 하나 더한 경우도 보여 준다. addClient 로 넘긴 client 를 그 뒤에 다시 쓰는 코드다.
1
2
3
4
5
func openNewAccount(name: String, initialBalance: Double) async {
let client = Client(name: name, initialBalance: initialBalance)
await ClientStore.shared.addClient(client)
client.logToAuditStream()
}
Client 와 ClientStore 는 위와 같게 두고 이 함수만 바꿔서 6.4 의 Swift 6 모드로 컴파일하면 이 error 가 나온다. 6.4 진단은 값을 넘기는 21 번째 줄에 error 를, 나중에 쓰는 22 번째 줄에 note 를 붙인다.
1
2
3
4
5
6
7
8
9
10
11
12
13
UseAfter.swift:21:28: error: sending 'client' risks causing data races [#RegionIsolation::SendingRisksDataRace]
19 | func openNewAccount(name: String, initialBalance: Double) async {
20 | let client = Client(name: name, initialBalance: initialBalance)
21 | await ClientStore.shared.addClient(client)
| |- error: sending 'client' risks causing data races [#RegionIsolation::SendingRisksDataRace]
| `- note: sending 'client' to actor-isolated instance method 'addClient' risks causing data races between actor-isolated and local nonisolated uses
22 | client.logToAuditStream()
| `- note: access can happen concurrently
23 | }
24 |
[#RegionIsolation]: <https://docs.swift.org/compiler/documentation/diagnostics/region-isolation>
[#SendingRisksDataRace]: <https://docs.swift.org/compiler/documentation/diagnostics/sending-risks-data-race>
진단 맨 끝의 두 줄은 이 error 가 속한 진단 묶음의 문서 주소다. 앞의 것이 RegionIsolation 문서이고, 뒤의 것이 sending-risks-data-race 문서다. 같은 두 줄이 이후 진단마다 붙으니, 아래에서는 이 두 줄을 줄여서 옮긴다. error 와 note 의 sending 이라는 낱말은 제안서에는 transfer 로 적혀 있다. 이름은 이 제안서 뒤에 나온 SE-0430 이 sending 으로 정했고, 6.4 의 진단 메시지는 그 이름을 쓴다. 이 글도 설명할 때는 제안서의 말인 transfer 를 쓰고, 진단 원문을 옮길 때만 sending 이 나온다.
같은 코드를 모드별로 돌리면 이렇게 나온다. 이 글의 샘플은 모두 -disable-upcoming-feature RegionBasedIsolation 을 더해서도 돌려 봤는데, 결과가 -strict-concurrency=complete 와 같아서 표에서 뺐다. complete 가 RegionBasedIsolation 을 함께 켜기 때문이다.
| 컴파일 모드 | UseAfter.swift 의 진단 |
|---|---|
-swift-version 5 | 0개 |
-swift-version 5 -strict-concurrency=complete | warning 1개 (끝에 ; this is an error in the Swift 6 language mode) |
-swift-version 6 | error 1개 |
Swift 5 기본 모드는 이 코드를 조용히 통과시키고, complete 로 올리면 같은 내용이 warning 이 되고, Swift 6 모드에서 error 가 된다. 이 단계 구조는 SE-0337 의 점진적 마이그레이션 흐름과 같다. 아래 마이그레이션 절에서 다시 정리한다.
isolation 경계와 Sendable 이란?
이 제안서를 읽으려면 isolation domain, isolation boundary, Sendable 이 무엇인지 알아야 한다.
isolation domain 은 “한 번에 한 곳에서만 만지게 보장된 영역” 이다. 비유하면 사무실의 방이다. 방마다 열쇠가 하나뿐이라, 한 사람이 들어가 있으면 다른 사람은 문 밖에서 기다린다. Swift 에서 방에 해당하는 것은 세 가지다.
- actor 하나. actor 는 자기 안의 프로퍼티를 한 번에 한 작업만 만지도록 보장하는 타입이다.
ClientStore인스턴스 하나가 방 하나다. - global actor.
@MainActor가 대표적이고, 그것이 붙은 모든 전역 변수와 타입과 함수가 같은 방을 쓴다. - task 하나.
Task로 시작한 비동기 작업이나async함수를 실행하는 흐름 하나가 자기 방을 가진다. task 에는 actor 와 달리 따로 저장되는 상태가 없다.
isolation boundary 는 이런 방 사이의 문턱이다. 다른 actor 의 메서드를 await 로 부르거나, Task.detached 에 closure 를 넘기는 곳이 문턱이다. 값이 문턱을 넘어가면 두 방이 같은 값을 들고 있을 수 있다.
Sendable 은 “문턱을 넘겨도 안전한 값” 이라는 표시다. 안전한 이유는 둘 중 하나다. 복사본이 가서 원본과 따로 놀거나(Int, String, 그리고 Sendable 로만 이루어진 struct), 여러 방에서 동시에 만져도 안에서 알아서 막아 주거나(actor 자신) 바뀔 수 없다(필드가 모두 Sendable 인 let 뿐인 final class). 위의 Client 는 var balance 가 있어서 Sendable 이 아니다. 두 방이 같은 Client 를 들고 balance 를 동시에 바꾸면 data race 가 생기기 때문이다.
SE-0302 의 규칙은 이렇다. 경계를 넘기는 값은 Sendable 이어야 한다. 이 규칙은 안전하지만, Client 처럼 “새로 만들어서 한 번 넘기고 끝” 인 값까지 막는다는 점이 문제였다. 개발자는 그런 값을 넘기려고 @unchecked Sendable 로 컴파일러의 검사를 끄는 수밖에 없었다. 그러면 컴파일러는 그 타입을 더 이상 보지 않으니, 정말 위험한 사용도 같이 놓친다.
무엇이 바뀌나
이 제안서는 “Sendable 인가” 만 묻던 검사에 “넘긴 뒤에 어디서 쓰는가” 를 더한다. 값이 Sendable 이 아니어도, 넘긴 뒤에 보낸 쪽이 그 값(과 그 값에서 닿을 수 있는 모든 값)을 쓰지 않으면 문턱을 넘겨도 된다. 이 판단을 하려면 “닿을 수 있는 값” 을 정확히 정의해야 하고, 제안서는 그것을 region 이라 부른다.
제안서의 Detailed Design 은 규칙을 꽤 형식을 갖춰 쓰지만, 맨 앞의 NOTE 가 이 부분을 정리해 준다. 프로그래머가 region 을 이 수준으로 따질 필요는 없고, 컴파일러가 안전하다고 증명하는 곳은 통과시키고 증명하지 못하는 곳은 잠재적으로 동시에 접근할 수 있는 지점에 진단을 낸다는 것이다. 그래도 진단이 왜 나왔는지 이해하려면 규칙을 알아야 하니, 아래에서 차례로 본다.
region 이란?
region 은 non-Sendable 값들의 집합이다. 집합 안의 값은 서로 alias 이거나 서로에게서 닿을 수 있다. alias 는 같은 객체를 가리키는 두 이름이다. 두 값 x 와 y 가 한 프로그램 지점에서 같은 region 에 있다는 것은 둘 중 하나가 성립한다는 말이다.
x가y의 alias 일 수 있다.x나x의 프로퍼티가y의 프로퍼티를 따라가는 연쇄 접근(y.a.b)으로 닿을 수 있다.
이렇게 정의하면 서로 다른 region 에 있는 값은 동시에 써도 된다. 한쪽 값을 아무리 만져도 다른 쪽 값에는 영향이 없기 때문이다. 두 region 이 합쳐지면 한 묶음이 되어, 넘길 때 통째로 간다.
제안서는 이 정의를 두 개의 예로 보인다. 먼저 Client 둘을 따로 만들어 각각 ClientStore 에 넘기는 경우다. john 이 joanna 를 가리킬 방법이 없으니, 둘은 다른 region 이고 joanna 를 넘기는 시점에 john 이 ClientStore 안에서 쓰이고 있어도 안전하다. 반대로 Client 에 friend 프로퍼티를 더하고 john.friend = joanna 로 이으면, joanna 가 john.friend 로 닿을 수 있게 되어 둘은 한 region 이 된다. 이 두 경우를 한 파일에 넣고 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
final class Client {
let name: String
var friend: Client?
init(name: String, initialBalance: Double) { self.name = name }
}
actor ClientStore {
var clients: [Client] = []
static let shared = ClientStore()
func addClient(_ c: Client) { clients.append(c) }
}
func twoClients() async {
let john = Client(name: "John", initialBalance: 0)
let joanna = Client(name: "Joanna", initialBalance: 0)
await ClientStore.shared.addClient(john)
await ClientStore.shared.addClient(joanna)
}
func friends() async {
let john = Client(name: "John", initialBalance: 0)
let joanna = Client(name: "Joanna", initialBalance: 0)
john.friend = joanna
await ClientStore.shared.addClient(john)
await ClientStore.shared.addClient(joanna)
}
twoClients() 는 진단이 0개이고, friends() 에서만 Swift 6 모드에서 error 가 나온다.
1
2
3
4
5
6
7
8
9
10
Friend.swift:24:28: error: sending 'john' risks causing data races [#RegionIsolation::SendingRisksDataRace]
22 | let joanna = Client(name: "Joanna", initialBalance: 0)
23 | john.friend = joanna
24 | await ClientStore.shared.addClient(john)
| |- error: sending 'john' risks causing data races [#RegionIsolation::SendingRisksDataRace]
| `- note: sending 'john' to actor-isolated instance method 'addClient' risks causing data races between actor-isolated and local nonisolated uses
25 | await ClientStore.shared.addClient(joanna)
| `- note: access can happen concurrently
26 | }
27 |
6.4 진단은 이렇게 나온다. error 는 먼저 넘기는 24 번째 줄에, joanna 를 쓰는 25 번째 줄은 access can happen concurrently 라는 note 에 붙는다. john 을 넘기면 john 과 john.friend 로 닿는 joanna 가 한 묶음으로 가는데, 25 번째 줄이 그 묶음의 일부를 다시 쓰기 때문이다.
region 이 합쳐지는 규칙
region 은 프로그램이 두 값 사이에 alias 나 접근 경로를 새로 만들 때마다 합쳐진다. 제안서는 이를 함수 호출 하나로 일반화한다. 프로퍼티 접근, 대입, closure 만들기가 모두 내부적으로는 함수 호출과 같은 모양이라는 관점이다. 값 y 가 y = f(a0, ..., an) 로 만들어질 때 규칙은 셋이다.
- non-Sendable 인 인자들
ai의 region 이f가 실행된 뒤에 모두 하나로 합쳐진다. - 인자 중 하나라도 non-Sendable 이고
y도 non-Sendable 이면y는 합쳐진 그 region 에 들어간다. 인자가 모두 Sendable 이면y는y하나만 있는 새로운 disconnected region 이 된다. y가 새 변수가 아니라 이미 있던var라면, 두 갈래다.y가 그전에 closure 에 reference 로 capture 되어 있었다면, 새 값의 region 이y의 옛 region 으로 합쳐진다.- 그렇지 않으면
y의 옛 region 은 잊힌다.
이 규칙은 일부러 보수적이다. 컴파일러는 f 의 구현을 모르는 채로, f 가 한 인자에서 다른 인자로 가는 경로를 만들 수 있고, 돌려주는 y 가 어떤 인자의 내용을 alias 할 수 있고, closure 가 var 를 reference 로 잡았다면 나중에 그 closure 를 부르는 쪽이 y 의 새 값을 볼 수 있다고 가정한다. 이 가정 때문에 안전한 프로그램이 거절되는 경우는 생기지만, 위험한 프로그램이 통과하는 경우는 생기지 않는다.
규칙을 6.4 로 하나씩 돌려 봤다. 모든 코드는 아래 Common.swift 와 같이 컴파일했다.
1
2
3
4
5
6
7
8
final class NonSendable {
var name = "ns"
var integerField = 1
func doSomething() {}
func useNS(_ other: NonSendable) {}
}
func useValue<T>(_ t: T) {}
@MainActor func transferToMainActor<T>(_ t: T) async {}
NonSendable 은 var 필드가 있는 non-Sendable class 이고, useValue 는 값을 받아 아무것도 하지 않는 함수다. transferToMainActor 는 @MainActor 가 붙은 async 함수라서, 일반 함수에서 부르면 isolation 경계를 넘는 호출이 된다. 값을 일부러 main actor 로 넘기는 용도로 쓴다.
alias. let y = x 는 y 를 x 의 region 에 넣는다. 규칙 2 가 그대로 적용되고, 복사도 “인자를 받아 복사본을 돌려주는 함수” 로 본다.
1
2
3
4
5
6
func alias() async {
let x = NonSendable()
let y = x
await transferToMainActor(x)
print(y)
}
1
2
3
4
5
6
7
8
9
10
Alias.swift:4:9: error: sending 'x' risks causing data races [#RegionIsolation::SendingRisksDataRace]
2 | let x = NonSendable()
3 | let y = x
4 | await transferToMainActor(x)
| |- error: sending 'x' risks causing data races [#RegionIsolation::SendingRisksDataRace]
| `- note: sending 'x' to main actor-isolated global function 'transferToMainActor' risks causing data races between main actor-isolated and local nonisolated uses
5 | print(y)
| `- note: access can happen concurrently
6 | }
7 |
x 를 넘겼는데 error 가 나온 이유는 5 번째 줄의 print(y) 다. y 가 x 와 같은 region 이라, x 를 넘기면 y 도 같이 넘어가서 main actor 쪽 코드와 지금 이 함수가 같은 객체를 동시에 만질 수 있다.
재대입. var 에 새 값을 대입하면 옛 region 이 잊힌다(규칙 3 의 두 번째 갈래).
1
2
3
4
5
6
7
8
9
func reassign() async {
var x = NonSendable()
let y = NonSendable()
x = y
let z = NonSendable()
x = z
await transferToMainActor(y)
useValue(x) // x 는 이제 z 와 같은 region. y 와는 상관없다
}
이 함수는 진단이 0개다. x = y 로 x 가 y 의 region 에 들어갔다가 x = z 로 z 의 region 으로 옮겨 가서, y 를 넘겨도 x 는 영향받지 않는다.
closure capture. closure 가 값을 capture 하면 capture 된 값들과 closure 자신이 한 region 이다.
1
2
3
4
5
6
7
func captureAndTransfer() async {
let x = NonSendable()
let y = NonSendable()
let closure = { useValue(x); useValue(y) }
await transferToMainActor(closure)
useValue(x)
}
1
2
3
4
5
6
7
8
9
10
Closure.swift:5:9: error: sending 'closure' risks causing data races [#RegionIsolation::SendingRisksDataRace]
3 | let y = NonSendable()
4 | let closure = { useValue(x); useValue(y) }
5 | await transferToMainActor(closure)
| |- error: sending 'closure' risks causing data races [#RegionIsolation::SendingRisksDataRace]
| `- note: sending 'closure' to main actor-isolated global function 'transferToMainActor' risks causing data races between main actor-isolated and local nonisolated uses
6 | useValue(x)
| `- note: access can happen concurrently
7 | }
8 |
closure 를 넘기면 그 안에서 capture 한 x 와 y 도 같이 넘어간다. 그래서 6 번째 줄의 useValue(x) 가 note 로 걸린다.
제어 흐름이 만드는 합류
if 같은 분기를 지난 뒤에는 어느 가지에서든 두 값이 합쳐졌다면 합쳐진 것으로 본다. 합쳐지지 않은 가지가 있어도 마찬가지다. 한쪽 가지에서만 일어난 일을 컴파일러가 실행 경로를 알지 못한 채 모든 경우에 대비해 가정하는 것이다.
1
2
3
4
5
6
7
8
9
func flow(_ flag: Bool) async {
var x = NonSendable()
let y = NonSendable()
if flag {
x = y
}
await transferToMainActor(x)
useValue(y)
}
1
2
3
4
5
6
7
8
9
10
ControlFlow.swift:7:9: error: sending 'x' risks causing data races [#RegionIsolation::SendingRisksDataRace]
5 | x = y
6 | }
7 | await transferToMainActor(x)
| |- error: sending 'x' risks causing data races [#RegionIsolation::SendingRisksDataRace]
| `- note: sending 'x' to main actor-isolated global function 'transferToMainActor' risks causing data races between main actor-isolated and local nonisolated uses
8 | useValue(y)
| `- note: access can happen concurrently
9 | }
10 |
flag 가 false 인 실행에서는 x 와 y 가 따로 놀지만, 컴파일러는 flag 의 값을 모르니 x = y 가 일어난 경우를 가정한다. 제안서는 이 규칙이 “합쳐 둬도 항상 안전하다” 는 점에서 보수적이라고 쓴다. 서로 이어지지 않은 값을 이어졌다고 취급하면, 문제없는 프로그램을 거절할 수는 있어도 위험한 프로그램을 통과시키지는 않는다.
제안서의 부록은 이 계산을 dataflow 분석으로 정리한다. 풀어 쓰면 이렇다. 프로그램의 각 지점마다 “어떤 값끼리 같은 region 인가” 를 그래프 하나로 들고 다닌다. 값이 점이고, 같은 region 으로 합친 문장이 선이다. 문장을 하나 지날 때마다 그 문장이 하는 일대로 그래프를 고친다. 함수 호출이면 non-Sendable 인자들 사이에 선을 잇는 식이다. 이 “문장 하나가 그래프를 어떻게 바꾸는가” 를 정한 규칙이 transfer function 이다. 분기가 합류하는 지점에서는 두 가지에서 온 그래프를 합집합으로 합친다. loop 로 되돌아오는 간선(back edge)은 아직 계산하지 않았으니 선이 하나도 없는 그래프로 시작하고, 값이 더 바뀌지 않을 때까지 돌린다. 선이 많은 그래프일수록 “위” 에 있다고 보고 그래프들을 줄 세운 것이 격자(lattice)다. 문장이 선을 더하기만 하고 지우지 않으면(단조, monotonic) 그래프는 위로만 올라가고, 위에는 한계가 있으니 반드시 어디선가 멈춘다. 이 증명은 컴파일러를 만드는 사람의 이야기이고, 사용자가 알아야 할 것은 “한 번 합쳐진 건 합류 뒤에도 합쳐진 채로 남는다” 는 성질이다.
struct 와 tuple 의 field 추적
제안서의 region 계산은 field 단위로 하지 않는다. field 가 둘 이상인 struct 나 tuple 에 field 하나를 대입하면, 그 대입은 “교체” 가 아니라 “합치기” 로 처리된다. 교체로 처리하면 같은 field 를 가리키던 다른 값(x)이 box 의 region 에서 빠지는데, box.0 이 바뀐 뒤에도 x 가 box 안 어딘가에 남아 있는지 컴파일러가 알 수 없기 때문이다. 같은 이유로 box 를 통째로 새 값으로 대입하면 교체가 된다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
func tupleField() async {
var box = (NonSendable(), NonSendable())
let x = NonSendable()
let y = NonSendable()
box.0 = x
box.0 = y
await transferToMainActor(box)
useValue(x)
}
func tupleWhole() async {
var box = (NonSendable(), NonSendable())
let x = NonSendable()
let y = NonSendable()
box.0 = x
box = (y, NonSendable())
await transferToMainActor(box)
useValue(x)
}
tupleWhole() 은 진단이 0개이고, tupleField() 는 error 가 나온다.
1
2
3
4
5
6
7
8
9
10
TupleMerge.swift:7:9: error: sending 'box' risks causing data races [#RegionIsolation::SendingRisksDataRace]
5 | box.0 = x
6 | box.0 = y
7 | await transferToMainActor(box)
| |- error: sending 'box' risks causing data races [#RegionIsolation::SendingRisksDataRace]
| `- note: sending 'box' to main actor-isolated global function 'transferToMainActor' risks causing data races between main actor-isolated and local nonisolated uses
8 | useValue(x)
| `- note: access can happen concurrently
9 | }
10 |
tupleField() 에서 box.0 = y 로 x 를 덮어썼지만, 컴파일러는 x 가 box 의 region 에 남아 있다고 본다. box 를 보낸 뒤의 useValue(x) 가 걸리는 이유다. tupleWhole() 은 box = (y, NonSendable()) 로 box 전체를 새로 만든 값으로 바꾸므로, 옛 region 이 잊혀서 x 가 box 와 상관없는 값이 된다.
제안서는 이 손해를 줄이는 예외를 하나 둔다. field 가 하나뿐인 struct 나 tuple 은 그 field 를 대입해도 다른 field 의 region 을 잃을 일이 없으니, 대입을 교체로 처리한다.
보내기와 진단이 붙는 자리
지금까지는 region 이 합쳐지는 규칙만 봤다. 이제 이 규칙이 “넘기기” 와 어떻게 만나는지 본다. 제안서는 모든 non-Sendable 값이 어떤 region 에 속하고, 그 region 은 actor 의 isolation domain 에 묶여 있거나, task 에 묶여 있거나, 어디에도 묶여 있지 않다고 정리한다. region 은 isolation 경계를 넘어 다른 곳으로 옮겨질 수 있지만, 동시에 두 곳에서 접근될 수는 없다. 그리고 한 region 이 actor 의 region 에 합쳐지면 그 region 은 그 actor 의 보호를 받게 되어, 다시는 경계를 넘길 수 없다.
경계를 넘는 호출 f(v) 에서 v 와 v 의 region 이 f 로 transfer 된다고 말한다. f 가 실행되는 동안 v 나 같은 region 의 값을 가리킬 수 있는 길은 f 의 매개변수뿐이어야 한다는 것이 이 말의 뜻이다. 제안서의 예에서 x 를 넘기면 x 와 같은 region 의 y 도 @MainActor 에 묶인다. transferToMainActor 의 구현이 x 를 main actor 의 어떤 상태에든 저장할 수 있기 때문이다. 그 뒤로 x 와 y 는 둘 다 사실상 main actor 의 값이어서, 밖에서 y 를 쓰는 것이 error 가 된다.
위에서 본 UseAfter.swift 가 이 규칙의 가장 짧은 예다. 6.4 진단이 줄마다 어디에 붙는지 그림으로 정리하면 이렇다.
고쳐야 하는 자리는 error 가 붙는 값을 넘기는 줄이다. 나중에 쓰는 줄은 “왜 넘기는 줄이 error 인가” 를 알려 주는 note 일 뿐이다. 이 note 를 따라가 보면 두 가지를 하게 된다. 넘긴 뒤에 쓰지 않도록 코드를 고치거나, 쓰는 쪽이 정말 필요하면 값을 넘기지 않고 복사해서 넘긴다.
진단 본문의 data races between A and B uses 는 두 isolation 의 이름을 알려 준다. 6.4 에서 본 조합은 다음과 같다.
| note 의 문구 | 의미 |
|---|---|
main actor-isolated and local nonisolated uses | main actor 로 넘겼는데 지금 이 함수(nonisolated)도 쓴다 |
actor-isolated and local nonisolated uses | 다른 actor 로 넘겼는데 지금 이 함수도 쓴다 |
main actor-isolated and 'self'-isolated uses | actor 의 상태에서 온 값을 main actor 로 넘기려 했다 |
main actor-isolated code and code in the current isolation context | task 에 묶인 값(함수 매개변수)을 main actor 로 넘기려 했다 |
제안서는 이 기본 보내기를 규칙으로 정한다. async 함수를 같은 isolation domain 안에서 부를 때는 해당되지 않고, 그때는 값이 넘어가지 않는다. 호출하는 쪽과 받는 쪽이 같은 방이면 문턱을 넘은 것이 아니기 때문이다. 호출이 같은 isolation 안에서 일어나도 값을 강제로 넘기려면, 뒤에서 보는 transferring(지금은 sending) 매개변수가 필요하다.
네 가지 region
값이 속한 region 이 어떤 종류인지에 따라 값을 넘길 수 있는지가 정해진다. 제안서는 네 종류로 나눈다.
- disconnected region: 어떤 isolation domain 에도 묶이지 않은 region 이다. 보낼 수 있는 것은 이 종류뿐이다. 함수 안에서
NonSendable()로 방금 만든 값이 여기 속한다. - actor-isolated region: 특정 actor 의 domain 에 단단히 묶인 region 이다. 한 번 묶인 값은 다른 domain 으로 절대 옮겨지지 않는다.
- task-isolated region: 특정 task 에 묶인 region 이다. nonisolated 함수의 매개변수가 여기 속한다.
- invalid region: 합칠 수 없는 region 들이 조건 분기로 합쳐진 결과다. 쓰는 것 자체가 error 다.
disconnected. 방금 본 Alias.swift 의 x 가 disconnected region 의 값이다. 넘긴 뒤에 쓰지 않으면 통과하고, 쓰면 error 다.
actor-isolated. actor 가 가진 non-Sendable 저장 프로퍼티와 거기서 파생된 값, 그리고 actor 메서드의 매개변수가 여기 속한다. global actor 의 경우에는 그 global actor 에 묶인 전역 변수, 그 global actor 에 묶인 타입의 인스턴스, 그리고 거기서 파생된 값이 한 region 이다. 아래 코드에서 첫 번째 transferToMainActor 호출은 지역 변수라 통과하고, 두 번째는 actor 의 저장 프로퍼티라 error 다.
1
2
3
4
5
6
7
8
actor MyActor {
var nonSendable = NonSendable()
func method() async {
let local = NonSendable()
await transferToMainActor(local) // disconnected 이라 보낼 수 있다
await transferToMainActor(nonSendable) // actor region 이라 보낼 수 없다
}
}
1
2
3
4
5
6
7
8
ActorRegion.swift:6:11: error: sending 'self.nonSendable' risks causing data races [#RegionIsolation::SendingRisksDataRace]
4 | let local = NonSendable()
5 | await transferToMainActor(local) // disconnected 이라 보낼 수 있다
6 | await transferToMainActor(nonSendable) // actor region 이라 보낼 수 없다
| |- error: sending 'self.nonSendable' risks causing data races [#RegionIsolation::SendingRisksDataRace]
| `- note: sending 'self'-isolated 'self.nonSendable' to main actor-isolated global function 'transferToMainActor' risks causing data races between main actor-isolated and 'self'-isolated uses
7 | }
8 | }
error 는 6 번째 줄 하나이고 5 번째 줄은 통과한다. note 는 'self'-isolated 라고 적어서, 이 값이 self 의 actor 에 묶여 있다는 것을 알려 준다.
actor 메서드의 매개변수도 같은 region 으로 취급한다. 호출하는 쪽이 actor 의 상태에서 꺼낸 값을 매개변수로 넘길 수 있기 때문이다.
1
2
3
4
5
actor MyActor {
func take(_ x: NonSendable) async {
await transferToMainActor(x) // actor 메서드의 parameter 는 actor region
}
}
1
2
3
4
5
6
7
8
ActorParam.swift:3:11: error: sending 'x' risks causing data races [#RegionIsolation::SendingRisksDataRace]
1 | actor MyActor {
2 | func take(_ x: NonSendable) async {
3 | await transferToMainActor(x) // actor 메서드의 parameter 는 actor region
| |- error: sending 'x' risks causing data races [#RegionIsolation::SendingRisksDataRace]
| `- note: sending 'self'-isolated 'x' to main actor-isolated global function 'transferToMainActor' risks causing data races between main actor-isolated and 'self'-isolated uses
4 | }
5 | }
제안서의 actorRegionExample 은 actor 밖에서 actor 의 프로퍼티를 읽는 코드다. 6.4 에서 돌리면 region 진단 단계까지 가지 않고 그 앞의 type check 단계에서 error 가 난다.
1
2
3
4
5
6
7
8
9
actor MyActor {
var nonSendable = NonSendable()
}
@MainActor func actorRegionExample() async {
let a = MyActor()
let x = await a.nonSendable
_ = x
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
ActorRegionRead.swift:7:19: error: non-Sendable type 'NonSendable' of property 'nonSendable' cannot exit actor-isolated context [#NonSendableExitingActor]
5 | @MainActor func actorRegionExample() async {
6 | let a = MyActor()
7 | let x = await a.nonSendable
| `- error: non-Sendable type 'NonSendable' of property 'nonSendable' cannot exit actor-isolated context [#NonSendableExitingActor]
8 | _ = x
9 | }
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 name = "ns"
3 | var integerField = 1
[#NonSendableExitingActor]: <https://docs.swift.org/compiler/documentation/diagnostics/getting-non-sendable-values-out-of-actors>
이 error 는 SIL 단계가 아니라 type check 단계에서 나온다. 같은 파일에 region 진단이 날 코드가 더 있어도, type check error 가 먼저 컴파일을 멈추기 때문에 SIL 단계의 region 진단은 나오지 않는다. actor 의 non-Sendable 상태를 밖으로 꺼내는 일은 region 규칙까지 가지 않고 앞 단계에서 막힌다는 뜻이다.
task-isolated. nonisolated async 함수의 매개변수가 여기 속한다. 이 함수를 부른 task 와 같은 task 에서 돌기 때문이다. 같은 task 의 다른 nonisolated 함수를 부르는 것은 경계를 넘는 것이 아니라서 문제가 없지만, 다른 isolation 으로 넘기려고 하면 error 다.
1
2
3
4
5
6
func nonIsolatedCallee(_ x: NonSendable) async {}
func nonIsolatedCaller(_ x: NonSendable) async {
await nonIsolatedCallee(x) // 같은 task, transfer 아님
await transferToMainActor(x) // error
}
1
2
3
4
5
6
7
8
TaskIsolated.swift:5:9: error: sending 'x' risks causing data races [#RegionIsolation::SendingRisksDataRace]
3 | func nonIsolatedCaller(_ x: NonSendable) async {
4 | await nonIsolatedCallee(x) // 같은 task, transfer 아님
5 | await transferToMainActor(x) // error
| |- error: sending 'x' risks causing data races [#RegionIsolation::SendingRisksDataRace]
| `- note: sending 'x' to main actor-isolated global function 'transferToMainActor' risks causing data races between main actor-isolated code and code in the current isolation context
6 | }
7 |
note 의 code in the current isolation context 는 이 함수를 부른 쪽을 가리킨다. x 는 호출한 쪽도 들고 있는 값일 수 있으니, 이 함수가 마음대로 다른 곳으로 넘길 수 없다.
task-isolated region 에 disconnected 값이 합쳐지면, 합쳐진 값도 task 에 묶인다.
1
2
3
4
5
func nonIsolated(_ arg: NonSendable) async {
let x = NonSendable()
arg.useNS(x) // x 가 arg 의 task region 에 합쳐진다
await transferToMainActor(x)
}
1
2
3
4
5
6
7
TaskMerge.swift:4:9: error: sending 'x' risks causing data races [#RegionIsolation::SendingRisksDataRace]
2 | let x = NonSendable()
3 | arg.useNS(x) // x 가 arg 의 task region 에 합쳐진다
4 | await transferToMainActor(x)
| |- error: sending 'x' risks causing data races [#RegionIsolation::SendingRisksDataRace]
| `- note: sending 'x' to main actor-isolated global function 'transferToMainActor' risks causing data races between main actor-isolated code and code in the current isolation context
5 | }
arg.useNS(x) 는 useNS 의 구현이 x 를 arg 안에 저장할 수 있으니 x 를 arg 의 region 에 합친다. 새로 만든 x 였는데도 이제 호출한 쪽의 값과 닿을 수 있어서 보낼 수 없다.
invalid. 두 actor 의 region 이 조건 분기로 합쳐지면, 어느 actor 에 묶였는지 컴파일 시점에 알 수 없게 된다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
actor A {
func useNS(_ x: NonSendable) {}
}
func mergeTwoActorRegions(_ flag: Bool) async {
let a1 = A()
let a2 = A()
let x = NonSendable()
if flag {
await a1.useNS(x)
} else {
await a2.useNS(x)
}
useValue(x)
}
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
Invalid.swift:10:14: error: sending 'x' risks causing data races [#RegionIsolation::SendingRisksDataRace]
8 | let x = NonSendable()
9 | if flag {
10 | await a1.useNS(x)
| |- error: sending 'x' risks causing data races [#RegionIsolation::SendingRisksDataRace]
| `- note: sending 'x' to actor-isolated instance method 'useNS' risks causing data races between actor-isolated and local nonisolated uses
11 | } else {
12 | await a2.useNS(x)
13 | }
14 | useValue(x)
| `- note: access can happen concurrently
15 | }
16 |
Invalid.swift:12:14: error: sending 'x' risks causing data races [#RegionIsolation::SendingRisksDataRace]
10 | await a1.useNS(x)
11 | } else {
12 | await a2.useNS(x)
| |- error: sending 'x' risks causing data races [#RegionIsolation::SendingRisksDataRace]
| `- note: sending 'x' to actor-isolated instance method 'useNS' risks causing data races between actor-isolated and local nonisolated uses
13 | }
14 | useValue(x)
| `- note: access can happen concurrently
15 | }
16 |
6.4 는 invalid region 이라는 낱말을 진단에 쓰지 않는다. 각 가지에서 x 를 보내는 두 줄에 error 가 붙고, 둘 다 분기 뒤의 useValue(x) 를 note 로 가리킨다. 제안서가 말하는 “분기 뒤에 x 를 쓰는 것은 error” 는 이 진단으로 나타난다.
region 이 합쳐질 때의 조합
region 이 서로 다른 종류일 때 합치면 어떻게 되는지 제안서가 정리한 표다. 종류별 설명은 위에서 본 예와 같다.
| 합치는 두 region | 결과 | 어디서 나오나 |
|---|---|---|
| disconnected + disconnected | 큰 disconnected region 하나 | 값 둘을 함께 쓰는 함수를 부를 때 |
| disconnected + actor-isolated | actor-isolated region 이 커진다. disconnected 의 값은 모두 그 actor 의 값이 된다 | actor 메서드를 부르거나 actor 의 field 에 대입할 때 |
| disconnected + task-isolated | task-isolated region 이 커진다 | nonisolated 함수의 매개변수에 값을 합칠 때 (TaskMerge.swift) |
| actor-isolated + actor-isolated | invalid | 조건 분기로만 생긴다 (Invalid.swift) |
| actor-isolated + task-isolated | invalid | 조건 분기로만 생긴다. 두 region 은 서로 동시에 돌 수 있기 때문이다 |
| task-isolated + task-isolated | 없다 | task-isolated region 은 매개변수에서만 생기므로 둘이 합쳐질 일이 없다 |
actor-isolated 와 task-isolated 는 한 번 묶이면 다른 곳으로 옮길 수 없으니, 둘이 합쳐지는 일은 “어느 쪽 가지로 왔는지 모르는” 분기에서만 일어난다. 그 결과가 invalid region 이다.
weak transfer 와 nonisolated 함수
경계를 넘기는 호출에서 값의 소유권이 정말로 옮겨 가는지는 별개의 문제다. Swift 의 async 함수 매개변수는 기본적으로 guaranteed 규약이다. 호출한 쪽이 값을 계속 쥐고 있고, 호출받는 쪽은 호출이 끝날 때까지 빌려 쓸 뿐이다. 호출한 쪽은 소유권을 넘긴 적이 없으므로, 호출이 끝난 뒤에도 값의 수명은 호출한 쪽에 있다. 제안서는 이 기본 상태를 weak transfer 라고 부른다. 소스 코드 위에서는 넘긴 값을 더 쓸 수 없지만, 객체를 붙들고 있는 참조는 호출한 쪽에 그대로 남는다.
반대편이 strong transfer 다. 호출한 쪽이 참조를 남기지 않고, 호출받는 쪽이 값을 소유한다. 소유권을 건네받는다는 것은 호출받는 쪽이 참조 개수(retain count)를 하나 더 얻는다는 뜻이다. 보통 이것을 “+1” 로 부른다. 건네받은 쪽은 쓰고 나면 그 하나를 반드시 돌려놓아야 한다.
둘의 차이는 deinit 이 도는 자리에서 보인다. 제안서의 예를 Tracker 로 바꿔서 실행해 봤다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
final class Tracker {
let id: Int
init(_ id: Int) { self.id = id }
deinit { print("deinit Tracker \(id)") }
}
@MainActor func takeOnMain(_ t: Tracker) async {
print("on main: \(t.id)")
}
func nonisolatedCallee(_ t: Tracker) async {
print("nonisolated callee: \(t.id)")
}
func caller() async {
let t = Tracker(1)
await takeOnMain(t)
print("after main actor callee")
_ = 0
}
func caller2() async {
let t = Tracker(2)
await nonisolatedCallee(t)
print("after nonisolated callee")
await takeOnMain(t)
print("after main actor callee 2")
}
@main struct App {
static func main() async {
await caller()
await caller2()
print("end")
}
}
1
2
3
4
5
6
7
8
9
on main: 1
after main actor callee
deinit Tracker 1
nonisolated callee: 2
after nonisolated callee
on main: 2
after main actor callee 2
deinit Tracker 2
end
caller() 는 t 를 main actor 로 넘기고도 after main actor callee 를 찍은 뒤에야 deinit Tracker 1 이 나온다. takeOnMain 은 t 를 빌려 썼을 뿐이어서, 객체는 호출한 쪽이 끝나는 곳에서 비로소 해제된다. 코드에서 t 를 더는 쓸 수 없는데도 객체의 수명은 호출한 쪽에 남는다. 이것이 weak transfer 다.
제안서가 strong transfer 를 기본으로 하지 않은 이유는 두 가지다. 하나는 모든 async 함수의 매개변수가 기본적으로 owned 가 되어야 하는데, 이것이 ABI 를 깨는 변경이고, async 함수의 본문을 readonly 나 readnone 으로 표시할 수 없게 만든다는 점이다. 매개변수를 소유하면 본문 끝에서 deinit 을 불러야 할 수 있고, deinit 은 부수 효과를 가질 수 있기 때문이다. 다른 하나는 ARC 비용이다. 함수 호출 경계를 넘는 복사가 inline 하지 않으면 없어지지 않아서 성능이 떨어지고, 그것을 줄이려고 inliner 를 공격적으로 돌리면 코드 크기가 커진다. strong transfer 가 꼭 필요한 곳은 transferring 이라는 명시적 매개변수 표시를 쓰도록 남겨 뒀다.
weak transfer 라서 얻는 것도 있다. nonisolated async 함수로 disconnected 값을 넘기면, 함수가 도는 동안 값은 함수의 task-isolated region 에 들어가고, 함수가 끝나면 다시 disconnected 가 된다. 제안서가 드는 근거는 둘이다. nonisolated 함수는 자기 소유의 isolation 상태를 따로 갖지 않아서, 값이 새어 들어갈 곳이 없다. 그리고 task-isolated region 의 매개변수는 영속적인 isolation 상태를 가진 다른 domain 으로 넘길 수 없다. 그래서 호출이 끝나면 값은 다시 쓸 수 있고 다시 넘길 수도 있다.
1
2
3
4
5
6
7
8
9
10
11
func nonIsolatedCallee(_ x: NonSendable) async {}
actor MyActor {
func example() async {
let x = NonSendable()
await nonIsolatedCallee(x)
useValue(x) // (1) ok
await transferToMainActor(x) // (2) ok
useValue(x) // (3) error
}
}
1
2
3
4
5
6
7
8
9
10
Reuse.swift:8:11: error: sending 'x' risks causing data races [#RegionIsolation::SendingRisksDataRace]
6 | await nonIsolatedCallee(x)
7 | useValue(x) // (1) ok
8 | await transferToMainActor(x) // (2) ok
| |- error: sending 'x' risks causing data races [#RegionIsolation::SendingRisksDataRace]
| `- note: sending 'x' to main actor-isolated global function 'transferToMainActor' risks causing data races between main actor-isolated and local actor-isolated uses
9 | useValue(x) // (3) error
| `- note: access can happen concurrently
10 | }
11 | }
6.4 진단은 (1) 의 useValue(x) 에는 아무것도 붙이지 않는다. nonIsolatedCallee 를 거친 x 가 다시 disconnected 라서 transferToMainActor 로 넘기는 것도 허용되고, 그 뒤의 (3) 만 문제가 된다. error 는 넘기는 8 번째 줄에 붙고, (3) 의 useValue(x) 가 note 로 따라온다.
closure 와 region
closure 는 주변의 값을 capture 한다. 그래서 closure 도 region 을 가진다. closure 의 region 은 capture 한 값들의 region 을 합친 것이다. 값 둘을 capture 한 closure 를 만들면 그 값 둘이 한 region 에 들어간다.
actor 의 상태를 capture 한 closure. actor 의 저장 프로퍼티를 읽는 closure 는 actor-isolated region 에 속한다. 이 closure 를 다른 곳으로 넘기면 actor 의 상태가 같이 새 나가기 때문이다.
1
2
3
4
5
6
7
actor MyActor {
var ns = NonSendable()
func doSomething() async {
let closure = { print(self.ns) }
await transferToMainActor(closure)
}
}
1
2
3
4
5
6
7
8
ClosureActor.swift:5:11: error: sending 'closure' risks causing data races [#RegionIsolation::SendingRisksDataRace]
3 | func doSomething() async {
4 | let closure = { print(self.ns) }
5 | await transferToMainActor(closure)
| |- error: sending 'closure' risks causing data races [#RegionIsolation::SendingRisksDataRace]
| `- note: sending 'self'-isolated 'closure' to main actor-isolated global function 'transferToMainActor' risks causing data races between main actor-isolated and 'self'-isolated uses
6 | }
7 | }
global actor 에 묶인 closure. closure 안에서 @MainActor 에 묶인 전역 변수를 쓰면 그 closure 는 main actor 에 묶인 closure 가 된다. 그리고 이 closure 가 capture 한 값은 closure 가 만들어지는 순간 main actor 로 넘어간 것으로 본다.
1
2
3
4
5
6
7
8
9
10
@MainActor var nonSendableGlobal = NonSendable()
func globalActorIsolatedClosure() {
let x = NonSendable()
let closure = { @MainActor in
nonSendableGlobal = x
}
_ = closure
useValue(x)
}
1
2
3
4
5
6
7
8
9
10
11
12
ClosureMain.swift:6:23: error: sending 'x' risks causing data races [#RegionIsolation::SendingRisksDataRace]
4 | let x = NonSendable()
5 | let closure = { @MainActor in
6 | nonSendableGlobal = x
| |- error: sending 'x' risks causing data races [#RegionIsolation::SendingRisksDataRace]
| `- note: 'x' is captured by a main actor-isolated closure. main actor-isolated uses in closure may race against later nonisolated uses
7 | }
8 | _ = closure
9 | useValue(x)
| `- note: access can happen concurrently
10 | }
11 |
error 는 capture 가 일어나는 6 번째 줄에 붙고, 그 뒤의 useValue(x) 가 note 로 따라온다. closure 를 호출하지 않아도 capture 한 시점에 이미 보낸 것으로 센다는 점이 눈에 띈다.
isolated closure 가 capture 한 값. 두 번째 리뷰에서 더해진 규칙이다. isolated closure 가 값을 capture 하는 것도 그 값을 closure 의 isolation 으로 넘기는 것으로 센다. 제안서의 예는 actor 메서드 안에서 actor 의 상태와 지역 값 x 를 함께 capture 하는 closure 다.
1
2
3
4
5
6
7
8
9
10
11
12
actor MyActor {
var field = NonSendable()
func example() {
let x = NonSendable()
let closure = {
self.field.doSomething()
x.doSomething()
}
_ = closure
useValue(x)
}
}
1
2
3
4
5
6
7
8
9
10
11
12
IsolatedCaptureActor.swift:7:9: error: sending 'x' risks causing data races [#RegionIsolation::SendingRisksDataRace]
5 | let closure = {
6 | self.field.doSomething()
7 | x.doSomething()
| |- error: sending 'x' risks causing data races [#RegionIsolation::SendingRisksDataRace]
| `- note: 'x' is captured by a actor-isolated closure. actor-isolated uses in closure may race against later actor-isolated uses
8 | }
9 | _ = closure
10 | useValue(x)
| `- note: access can happen concurrently
11 | }
12 | }
error 는 closure 안에서 x 를 capture 하는 7 번째 줄에 붙고, closure 를 만든 뒤에 x 를 다시 쓰는 useValue(x) 가 note 로 따라온다. x 가 actor 의 isolation 으로 넘어갔다고 세기 때문에, 넘어간 뒤에 쓴 줄이 문제가 된다.
같은 모양을 @MainActor 가 붙은 class 로 바꾸면 6.4 에서는 진단이 0개다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
@MainActor var nonSendableGlobal = NonSendable()
@MainActor final class Owner {
var field = NonSendable()
func example() {
let x = NonSendable()
let closure = {
self.field.doSomething()
x.doSomething()
}
_ = closure
useValue(x)
}
}
closure 를 다른 actor 로 넘길 때. closure 가 global actor 의 함수를 부르면 그 closure 는 형식상 그 global actor 에 isolated 된 것이 된다. 아래 두 함수를 6.4 에서 돌리면 둘 다 error 가 나온다.
1
2
3
4
5
6
7
8
9
10
11
12
@MainActor func mainActorUtility() {}
actor Other { func take(_ f: () -> Void) {} }
@MainActor func mainActorIsolatedClosure(_ o: Other) async {
let closure = { mainActorUtility() }
await o.take(closure)
}
@MainActor func plainClosure(_ o: Other) async {
let closure = { print("hello") }
await o.take(closure)
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
ClosureCallsMain.swift:6:11: error: sending 'closure' risks causing data races [#RegionIsolation::SendingRisksDataRace]
4 | @MainActor func mainActorIsolatedClosure(_ o: Other) async {
5 | let closure = { mainActorUtility() }
6 | await o.take(closure)
| |- error: sending 'closure' risks causing data races [#RegionIsolation::SendingRisksDataRace]
| `- note: sending main actor-isolated 'closure' to actor-isolated instance method 'take' risks causing data races between actor-isolated and main actor-isolated uses
7 | }
8 |
ClosureCallsMain.swift:11:11: error: sending 'closure' risks causing data races [#RegionIsolation::SendingRisksDataRace]
9 | @MainActor func plainClosure(_ o: Other) async {
10 | let closure = { print("hello") }
11 | await o.take(closure)
| |- error: sending 'closure' risks causing data races [#RegionIsolation::SendingRisksDataRace]
| `- note: sending main actor-isolated 'closure' to actor-isolated instance method 'take' risks causing data races between actor-isolated and main actor-isolated uses
12 | }
13 |
6.4 에서는 두 함수 모두 error 가 난다. 앞의 mainActorIsolatedClosure 는 closure 가 @MainActor 함수를 불러서 main actor 에 묶인 closure 가 된 경우다. 뒤의 plainClosure 는 main actor 를 부르는 코드가 하나도 없는데도 error 가 나는데, @MainActor 함수 안에서 만든 closure 라서 main actor 에 묶인 closure 로 세기 때문이다. 두 경우 모두 non-Sendable closure 를 Other actor 로 넘기려 한 것이다.
sync 와 async 매개변수. 제안서는 isolated closure 를 sync 매개변수로 넘기는 것은 error 이고, async 매개변수로 넘기는 것은 허용된다고 쓴다. async 매개변수라면 closure 를 부르는 쪽이 actor 로 hop 해서 부르는 얇은 wrapper 를 만들 수 있기 때문이다. 또 closure 자체가 async 이면 여러 번 넘겨도 된다. 6.4 에서 이 네 자리를 그대로 돌리면 네 자리 모두 같은 error 가 나온다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@MainActor func transferSync(_ f: () -> ()) async {}
@MainActor func transferAsync(_ f: () async -> ()) async {}
actor A {
func doSomething() {}
func syncClosure() async {
let closure: () -> () = { self.doSomething() }
await transferSync(closure)
}
func asyncParam() async {
let closure: () -> () = { self.doSomething() }
await transferAsync(closure)
}
func asyncClosure() async {
let closure: () async -> () = { self.doSomething() }
await transferAsync(closure)
await transferAsync(closure)
}
}
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
ClosureSyncAsync.swift:8:11: error: sending 'closure' risks causing data races [#RegionIsolation::SendingRisksDataRace]
6 | func syncClosure() async {
7 | let closure: () -> () = { self.doSomething() }
8 | await transferSync(closure)
| |- error: sending 'closure' risks causing data races [#RegionIsolation::SendingRisksDataRace]
| `- note: sending 'self'-isolated 'closure' to main actor-isolated global function 'transferSync' risks causing data races between main actor-isolated and 'self'-isolated uses
9 | }
10 | func asyncParam() async {
ClosureSyncAsync.swift:12:11: error: sending 'closure' risks causing data races [#RegionIsolation::SendingRisksDataRace]
10 | func asyncParam() async {
11 | let closure: () -> () = { self.doSomething() }
12 | await transferAsync(closure)
| |- error: sending 'closure' risks causing data races [#RegionIsolation::SendingRisksDataRace]
| `- note: sending 'self'-isolated 'closure' to main actor-isolated global function 'transferAsync' risks causing data races between main actor-isolated and 'self'-isolated uses
13 | }
14 | func asyncClosure() async {
ClosureSyncAsync.swift:16:11: error: sending 'closure' risks causing data races [#RegionIsolation::SendingRisksDataRace]
14 | func asyncClosure() async {
15 | let closure: () async -> () = { self.doSomething() }
16 | await transferAsync(closure)
| |- error: sending 'closure' risks causing data races [#RegionIsolation::SendingRisksDataRace]
| `- note: sending 'self'-isolated 'closure' to main actor-isolated global function 'transferAsync' risks causing data races between main actor-isolated and 'self'-isolated uses
17 | await transferAsync(closure)
18 | }
ClosureSyncAsync.swift:17:11: error: sending 'closure' risks causing data races [#RegionIsolation::SendingRisksDataRace]
15 | let closure: () async -> () = { self.doSomething() }
16 | await transferAsync(closure)
17 | await transferAsync(closure)
| |- error: sending 'closure' risks causing data races [#RegionIsolation::SendingRisksDataRace]
| `- note: sending 'self'-isolated 'closure' to main actor-isolated global function 'transferAsync' risks causing data races between main actor-isolated and 'self'-isolated uses
18 | }
19 | }
네 error 의 note 는 전부 sending 'self'-isolated 'closure' to main actor-isolated global function 'transferSync' 또는 'transferAsync' 로, 'self'-isolated uses 와 충돌한다고 말한다. 6.4 에서는 매개변수가 sync 든 async 든, closure 가 sync 든 async 든 actor 의 상태를 capture 한 closure 는 보내지 못한다.
non-Sendable closure 본문 안. non-Sendable closure 의 본문 안에서는 closure 자신과 capture 한 값이 모두 task-isolated region 에 있다. closure 를 어디서 부를지 알 수 없는 이상, 본문 안에서 capture 한 값을 마음대로 다른 곳으로 넘길 수 없다.
1
2
3
4
5
6
7
8
func example() {
let x = NonSendable()
var closure: () async -> () = {}
closure = {
await transferToMainActor(x)
}
_ = closure
}
1
2
3
4
5
6
7
8
ClosureBody.swift:5:11: error: sending 'x' risks causing data races [#RegionIsolation::SendingRisksDataRace]
3 | var closure: () async -> () = {}
4 | closure = {
5 | await transferToMainActor(x)
| |- error: sending 'x' risks causing data races [#RegionIsolation::SendingRisksDataRace]
| `- note: sending 'x' to main actor-isolated global function 'transferToMainActor' risks causing data races between main actor-isolated code and code in the current isolation context
6 | }
7 | _ = closure
note 가 code in the current isolation context 를 말하는 것은 TaskIsolated.swift 와 같다. 함수 매개변수와 비슷하게, closure 가 어디서 불릴지는 closure 를 만든 쪽의 사정이라서다.
assumeIsolated 의 구멍
isolation 을 컴파일러 대신 사람이 보증하는 API 가 있다. assumeIsolated 는 nonisolated 동기 함수 안에서 “지금 이 코드는 이 actor 위에서 돌고 있다” 고 선언하고, 그 actor 에 isolated 된 값을 closure 로 다룬다. SE-0423 에서 다룬 dynamic isolation 검사의 짝이 되는 API 다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
actor ContainsNonSendable {
var ns = NonSendable()
nonisolated func unsafeSet(_ ns: NonSendable) {
self.assumeIsolated { isolatedSelf in
isolatedSelf.ns = ns
}
}
nonisolated func get() -> NonSendable {
self.assumeIsolated { isolatedSelf in
return isolatedSelf.ns
}
}
}
assumeIsolated 로 isolation 을 가정하고 closure 실행하기
Actor.assumeIsolated(_:file:line:) 는 actor 의 executor 위에서 돌고 있다고 가정하고, actor 에 isolated 된 closure 를 동기로 실행하는 메서드다. 실제로 그 actor 위에서 돌고 있지 않으면 런타임에 멈춘다. MainActor.assumeIsolated(_:file:line:) 는 같은 일을 main actor 에 대해 하는 메서드로, 뒤에서 보는 stashIntoMainActor 예제가 쓴다.
이 두 메서드는 region 규칙에 구멍을 낸다. 첫 번째 unsafeSet 은 매개변수 ns 를 actor 의 저장 프로퍼티에 넣는다. nonisolated 함수의 매개변수는 task-isolated region 이고, 호출한 쪽도 그 값을 들고 있을 수 있다. 그런데 actor 의 상태에 합쳐지면, 호출한 쪽의 코드와 actor 가 같은 객체를 동시에 만질 수 있다. 두 번째 get 은 반대로 actor 의 상태를 반환값으로 꺼낸다. 호출한 쪽이 actor 의 ns 에 대한 참조를 actor 의 보호 밖에서 갖게 된다.
이 구멍은 첫 번째 리뷰에서 ellie20 이 지적했다. Actor1.get() 처럼 isolated 된 값을 반환하는 코드가 있으면 non-Sendable 값이 actor 밖으로 새어 나간다는 것이다(리뷰 #13). John_McCall 은 이 구멍을 세 가지 사실이 겹친 결과로 정리했다(리뷰 #21). 첫째, region based isolation 은 독립된(disconnected) region 에 있는 non-Sendable 값을 concurrency domain 사이로 옮길 수 있는 새 능력을 더한다. 둘째, nonisolated 함수가 non-Sendable 값에 미치는 영향은 제한적이라고 가정한다. 그런 함수는 값의 region 을 다른 non-Sendable 매개변수의 region 과 합칠 수는 있어도, actor 상태에서 그 값을 참조하게 만드는 식으로 actor 의 region 과 합치지는 못한다고 본다. 셋째, assumeIsolated 는 형식상 nonisolated 인 호출한 쪽과 isolated 인 closure 본문 사이의 non-Sendable 값 흐름을 제한하지 않아서, 임의의 region 이 actor 의 region 과 합쳐지게 한다. 첫째는 이 제안의 핵심이라 바꿀 수 없고, 둘째를 버리면 annotation 이 잔뜩 필요해지므로 셋째를 고치는 쪽이 낫다는 것이 그의 결론이다.
여기서 그가 말한 “rigid” region 은, 다른 rigid region 과 동등하게 합칠(peer-merge) 수 없는 region 을 뜻한다. actor 의 region 이 그렇다. 방금 만든 값처럼 독립된 region 은 rigid region 안으로 합쳐 넣을 수 있지만, rigid region 끼리는 합칠 수 없다. 잠금 API 도 같은 상황이다. OSAllocatedLock.withLock 이 안전한 이유는 넘기는 closure 가 Sendable 이어야 해서 non-Sendable 값이 그 closure 를 드나들 수 없기 때문이다. assumeIsolated 도 매개변수 closure 를 Sendable 로 제한하면 같은 방식으로 막힌다. 다만 그는 이 방법이 필요 이상으로 보수적이라, 일단 이렇게 시작하되 너무 막으면 Sendable 이 아니면서 Sendable 장벽 역할만 하는 표시를 따로 도입할 수 있다고 덧붙였다.
이 지적을 받아 hborla 는 첫 번째 리뷰를 “수정 요청” 으로 마무리했다(수정 요청 글을 다시 읽으면 이유가 둘로 정리되어 있다). 첫째, 언어에는 non-Sendable 값이 isolation 경계를 넘지 않는다고 가정하는 곳이 있다. isolated path component 가 있는 key path 와 non-Sendable 인 isolated 함수가 그 예인데, SE-0414 는 이들을 actor 의 region 의 일부로 정의하지 않았다. 둘째, sync nonisolated 함수의 매개변수 region 이 transfer 될 수 있어서, assumeIsolated 같은 API 로 non-Sendable 값이 actor 의 region 으로 새어 들어갈 수 있었다. 이 region 을 transfer 할 수 없게 막는 것이 수정안이다.
6.4 에서 AssumeIsolated.swift 를 Swift 6 모드로 돌리면 이렇게 나온다.
1
2
3
4
5
6
7
8
9
10
11
12
13
AssumeIsolated.swift:11:10: error: type 'NonSendable' does not conform to the 'Sendable' protocol
9 |
10 | nonisolated func get() -> NonSendable {
11 | self.assumeIsolated { isolatedSelf in
| `- error: type 'NonSendable' does not conform to the 'Sendable' protocol
12 | return isolatedSelf.ns
13 | }
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 name = "ns"
3 | var integerField = 1
get() 의 반환 타입이 NonSendable 이라서 막힌다. 두 번째 리뷰에서 나온 assumeIsolated 의 결과 타입이 Sendable 이어야 한다는 수정이 적용된 결과다. 이 error 는 type check 단계에서 나오기 때문에, 같은 파일의 6 번째 줄(isolatedSelf.ns = ns)에서 나올 region 진단은 이 error 에 가려진다. Swift 5 모드에서 -strict-concurrency=complete 로 돌리면 11:10 과 6:23 두 곳이 모두 warning 으로 나오고, -strict-concurrency=minimal 에서는 진단이 0개다.
수정 요청 뒤의 두 번째 리뷰에서 Michael_Gottesman 은 nonisolated 동기 함수의 매개변수가 다른 함수의 인자와 똑같이 합쳐지고, 그 함수 안에서 매개변수가 transfer 될 수 없다고 정리했다(리뷰 #7, #8). 그리고 hborla 는 sync actor init 도 매개변수를 transfer 한다는 점과, nonisolated 함수의 매개변수가 sync 든 async 든 task-isolated 라는 점을 확인했다(리뷰 #12).
unsafeSet 을 부르는 쪽에서는 이렇게 걸린다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
actor ContainsNonSendable {
var ns = NonSendable()
nonisolated func unsafeSet(_ ns: NonSendable) {
self.assumeIsolated { isolatedSelf in
isolatedSelf.ns = ns
}
}
}
func assumeIsolatedError(actor: ContainsNonSendable) async {
let x = NonSendable()
actor.unsafeSet(x)
useValue(x)
}
1
2
3
4
5
6
7
8
UnsafeSetCaller.swift:5:23: error: sending 'ns' risks causing data races [#RegionIsolation::SendingRisksDataRace]
3 | nonisolated func unsafeSet(_ ns: NonSendable) {
4 | self.assumeIsolated { isolatedSelf in
5 | isolatedSelf.ns = ns
| |- error: sending 'ns' risks causing data races [#RegionIsolation::SendingRisksDataRace]
| `- note: 'ns' is captured by a actor-isolated closure. actor-isolated uses in closure may race against code in the current isolation context
6 | }
7 | }
error 는 unsafeSet 안의 closure 가 ns 를 capture 하는 줄에 붙는다. 호출하는 쪽(assumeIsolatedError)이 아니라 구멍이 생기는 자리에서 막힌다는 점이 이 수정의 핵심이다. isolated closure 가 값을 capture 하는 것을 transfer 로 세고, task-isolated region 은 transfer 할 수 없게 했기 때문이다.
제안서의 Source compatibility 절은 이 영향을 받는 예를 stashIntoMainActor 로 보여 준다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@MainActor var globalNonSendable: NonSendable = .init()
nonisolated func stashIntoMainActor(ns: NonSendable) {
MainActor.assumeIsolated {
globalNonSendable = ns
}
}
func stashAndTransfer() -> NonSendable {
let ns = NonSendable()
stashIntoMainActor(ns: ns)
Task.detached {
print(ns)
}
return ns
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
Stash.swift:5:23: error: sending 'ns' risks causing data races [#RegionIsolation::SendingRisksDataRace]
3 | nonisolated func stashIntoMainActor(ns: NonSendable) {
4 | MainActor.assumeIsolated {
5 | globalNonSendable = ns
| |- 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
6 | }
7 | }
Stash.swift:12:8: error: sending value of non-Sendable type '() async -> ()' risks causing data races [#RegionIsolation::SendingRisksDataRace]
10 | let ns = NonSendable()
11 | stashIntoMainActor(ns: ns)
12 | Task.detached {
| |- 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 static method 'detached(name:priority:operation:)' risks causing races in between local and caller code
13 | print(ns)
14 | }
15 | return ns
| `- note: access can happen concurrently
16 | }
17 |
이 코드는 ns 를 main actor 의 전역 변수에 넣고, 같은 ns 를 Task.detached 와 반환값으로도 내보낸다. 세 곳이 같은 객체를 동시에 만질 수 있으니 data race 의 교과서적 예다. 5 번째 줄과 12 번째 줄 두 곳에 error 가 붙는다. 제안서는 이 코드를 -strict-concurrency=complete 에서는 warning 으로 먼저 알리고, Swift 6 모드에서 error 로 만든다고 적었다. Swift 5 모드의 complete 에서 6.4 로 돌리면 5:23 과 12:8 이 warning 이고, minimal 에서는 진단이 0개다.
수락 전에 assumeIsolated 에 한 가지가 더 있었다. 두 번째 리뷰에서 한 리뷰어가 수정안으로도 막히지 않는 구멍을 하나 더 찾았다. isolated 된 non-Sendable 값을 closure 의 결과로 내보내는 경우다. 수락 글은 assumeIsolated 의 타입 매개변수, 곧 closure 의 결과 타입이자 함수 전체의 결과 타입이 Sendable 을 따르도록 요구해서 이 구멍을 닫는다고 정리한다. 이 변경은 리뷰 스레드에서 충분히 논의가 되어서 Language Steering Group 이 추가 리뷰 없이 받아들였다. 방금 본 AssumeIsolated.swift 의 type check error 가 이 수정이다.
Task.detached 로 현재 context 를 잇지 않는 task 만들기
Task.detached(name:priority:operation:) 는 현재 actor 와 task-local 값을 이어받지 않는 새 task 를 만든다. operation closure 는 sending 으로 받으므로, closure 가 capture 한 값은 region 이 넘어가서 호출한 쪽이 이후에 쓸 수 없다.
KeyPath 의 region
key path 도 region 을 가진 값이다. 제안서는 isolation 에 묶이지 않은 key path 는 disconnected region 에 속하고, isolated 된 key path 는 그 actor 의 region 에 속하며, key path 의 region 은 capture 한 값의 region 과 합쳐진다고 정한다. 첫 번째 리뷰에서 hborla 는 isolated 된 component 를 가진 key path 는 항상 actor 의 region 에 있다고 답했다(리뷰 #18).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Person {
var name = "John Smith"
}
class Wrapper<Root: AnyObject> {
var root: Root
init(root: Root) { self.root = root }
func setKeyPath<T>(_ keyPath: ReferenceWritableKeyPath<Root, T>, to value: T) {
root[keyPath: keyPath] = value
}
}
func useNonIsolatedKeyPath() async {
let nonIsolated = Person()
let wrapper = Wrapper(root: nonIsolated)
let keyPath = \Person.name
await transferToMainActor(keyPath)
wrapper.setKeyPath(keyPath, to: "Jenny Smith")
}
ReferenceWritableKeyPath 로 참조 타입의 프로퍼티 쓰기
ReferenceWritableKeyPath 는 참조 타입(class) 인스턴스의 프로퍼티를 읽고 쓰는 key path 다. root[keyPath: keyPath] = value 처럼 root 가 let 이어도 쓸 수 있다.
제안서는 이 예에서 transferToMainActor(keyPath) 뒤의 setKeyPath 호출을 // Error! 로 표시한다. 보낸 key path 를 다시 쓰기 때문이다. 6.4 에서 이 코드를 모드별로 돌리면 결과가 갈린다.
| 모드 | 결과 |
|---|---|
| Swift 6 | 진단 0개 |
Swift 5, -strict-concurrency=complete | 17:9 warning, 18 번째 줄에 note |
Swift 5, complete + -enable-upcoming-feature InferSendableFromCaptures | 진단 0개 |
Swift 6 모드가 0개인 이유는 region 규칙이 아니라 SE-0418 이다. SE-0418 은 isolation 이 없는 key path literal 을 Sendable 로 추론하고, 이 추론은 Swift 6 모드에서 켜져 있다. \Person.name 이 Sendable 이면 보낸 뒤에 써도 data race 가 아니므로 region 검사가 끼어들 이유가 없다. 추론이 꺼진 Swift 5 complete 에서는 \Person.name 이 non-Sendable 로 남아서 region 검사가 걸리고, 진단은 이렇게 나온다.
1
2
3
4
5
6
7
8
9
10
KeyPath.swift:17:9: warning: sending 'keyPath' risks causing data races; this is an error in the Swift 6 language mode [#RegionIsolation::SendingRisksDataRace]
15 | let wrapper = Wrapper(root: nonIsolated)
16 | let keyPath = \Person.name
17 | await transferToMainActor(keyPath)
| |- warning: sending 'keyPath' risks causing data races; this is an error in the Swift 6 language mode [#RegionIsolation::SendingRisksDataRace]
| `- note: sending 'keyPath' to main actor-isolated global function 'transferToMainActor' risks causing data races between main actor-isolated and local nonisolated uses
18 | wrapper.setKeyPath(keyPath, to: "Jenny Smith")
| `- note: access can happen concurrently
19 | }
20 |
여기에 InferSendableFromCaptures 를 켜면 0개로 돌아간다. 제안서가 // Error! 로 적은 것은 SE-0418 의 추론이 없던 시점의 결과다.
actor 에 묶인 key path 는 다르게 본다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@MainActor final class MainActorIsolatedKlass {
var name = "John Smith"
}
actor Setter {
func set<Root, T: Sendable>(_ root: Root, _ keyPath: ReferenceWritableKeyPath<Root, T>, to value: T) {
root[keyPath: keyPath] = value
}
}
@MainActor func useKeyPath(_ s: Setter) async {
let k = MainActorIsolatedKlass()
let keyPath = \MainActorIsolatedKlass.name
await s.set(k, keyPath, to: "value")
}
이 코드는 6.4 에서 진단이 0개다. 그런데 그 이유를 “k 와 keyPath 가 같은 main actor region 이고 T: Sendable 이라 안전해서” 라고 읽으면 틀린다. T: Sendable 을 지워도 결과는 여전히 0개다. 6.4 는 \MainActorIsolatedKlass.name literal 을 매번 새로 만든 disconnected 값으로 취급해서, 보내는 시점에 keyPath 가 어느 actor 에도 묶여 있지 않다고 본다. 이 해석은 보낸 뒤의 사용에서 드러난다. 보낸 keyPath 를 이후에 다시 쓰면 “between actor-isolated and local main actor-isolated uses” 라는 error 가 나고, 먼저 g = keyPath 로 main actor 상태에 합쳐 둔 뒤에 보내면 “sending main actor-isolated ‘keyPath’” error 가 난다. 위 예제는 보낸 뒤에 keyPath 를 쓰지 않아서 0개일 뿐이다. 이것은 6.4 가 key path literal 을 다루는 방식이고, 앞의 hborla 답변(리뷰 #18)과는 별개의 사실이다.
async let 의 region
async let 은 오른쪽 식을 새 child task 에서 돌린다. 제안서는 이 식이 쓰는 값이 async let 이 끝날 때까지 task-isolated region 에 있고, await 으로 결과를 받으면 다시 disconnected 가 된다고 정한다. 식 안에서 값이 actor 에 넘어갔다면 그 값은 계속 넘어간 채로 남는다. 두 binding 이 같은 값을 쓰는 것도 error 이고, actor-isolated region 의 값은 async let 에서 쓸 수 없다.
1
2
3
4
5
6
7
8
9
10
11
12
func nonIsolatedCallee(_ x: NonSendable) async -> Int { 5 }
actor MyActor {
func example() async {
let x = NonSendable()
async let value = nonIsolatedCallee(x) + x.integerField
useValue(x)
_ = await value
useValue(x)
await transferToMainActor(x)
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
AsyncLet.swift:6:23: error: sending 'x' risks causing data races [#RegionIsolation::SendingRisksDataRace]
4 | func example() async {
5 | let x = NonSendable()
6 | async let value = nonIsolatedCallee(x) + x.integerField
| |- error: sending 'x' risks causing data races [#RegionIsolation::SendingRisksDataRace]
| `- note: sending 'x' into async let risks causing data races between async let uses and local uses
7 | useValue(x)
| `- note: access can happen concurrently
8 | _ = await value
9 | useValue(x)
AsyncLet.swift:6:23: error: sending 'x' risks causing data races [#RegionIsolation::SendingRisksDataRace]
4 | func example() async {
5 | let x = NonSendable()
6 | async let value = nonIsolatedCallee(x) + x.integerField
| |- error: sending 'x' risks causing data races [#RegionIsolation::SendingRisksDataRace]
| `- note: sending 'x' into async let risks causing data races between async let uses and local uses
7 | useValue(x)
8 | _ = await value
async let 이 도는 동안 쓰는 첫 번째 useValue(x)(7 번째 줄)가 문제다. 이 줄을 지우면 같은 코드가 진단 0개로 통과한다. await value 로 결과를 받은 뒤의 두 번째 useValue(x)(9 번째 줄)는 x 가 다시 disconnected 가 되므로 문제가 없다. 6.4 는 error 를 async let 이 시작되는 6 번째 줄에 붙이고, 그 동안 x 를 쓴 7 번째 줄을 note 로 알려 준다.
두 binding 이 한 값을 공유하면 이렇다.
1
2
3
4
5
func twoBindings() async {
let x = NonSendable()
async let y = x, z = x
_ = await (y, z)
}
1
2
3
4
5
6
7
8
9
AsyncLetTwo.swift:3:17: error: sending 'x' risks causing data races [#RegionIsolation::SendingRisksDataRace]
1 | func twoBindings() async {
2 | let x = NonSendable()
3 | async let y = x, z = x
| | `- note: access can happen concurrently
| |- error: sending 'x' risks causing data races [#RegionIsolation::SendingRisksDataRace]
| `- note: sending 'x' into async let risks causing data races between async let uses and local uses
4 | _ = await (y, z)
5 | }
y 와 z 는 서로 다른 child task 에서 돌기 때문에 같은 x 를 동시에 만질 수 있다. error 는 첫 번째 binding 에 붙고, 두 번째 binding 이 note 로 따라온다.
actor initializer 와 deinitializer
SE-0327 은 actor 의 initializer 와 deinitializer 에서 self 를 어디까지 쓸 수 있는지를 흐름에 따라 진단하는 규칙을 만들었다. SE-0414 는 이 규칙의 non-Sendable 부분을 region 모델의 말로 다시 설명한다. 다만 6.4 가 내는 진단 문구는 SE-0327 의 것이고, region 의 말(sending, risks causing data races)은 값을 다른 isolation 으로 보내는 줄에서만 나온다. SE-0327 은 actor initializer 의 isolation 을 다룬 제안서다.
모델은 이렇다. initializer 에서 self 는 strong transfer 된 non-Sendable 값으로 시작하고, self 가 밖으로 escape 하는 순간 Sendable 이 된다. async initializer 는 non-Sendable 매개변수를 transfer 로 받을 수 있다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
actor MyActor {
var x: NonSendable
init(_ arg: NonSendable) async {
self.x = arg
}
}
func makeActor() async -> MyActor {
let x = NonSendable()
let a = await MyActor(x)
return a
}
func makeActorThenUse() async -> MyActor {
let x = NonSendable()
let a = await MyActor(x)
x.doSomething()
return a
}
makeActor() 는 진단이 0개이고, makeActorThenUse() 는 x 를 넘긴 뒤 쓰기 때문에 error 다.
1
2
3
4
5
6
7
8
9
10
ActorInit.swift:16:17: error: sending 'x' risks causing data races [#RegionIsolation::SendingRisksDataRace]
14 | func makeActorThenUse() async -> MyActor {
15 | let x = NonSendable()
16 | let a = await MyActor(x)
| |- error: sending 'x' risks causing data races [#RegionIsolation::SendingRisksDataRace]
| `- note: sending 'x' to actor-isolated initializer 'init(_:)' risks causing data races between actor-isolated and local nonisolated uses
17 | x.doSomething()
| `- note: access can happen concurrently
18 | return a
19 | }
sync initializer 는 경우가 갈린다. 두 번째 리뷰에서 Nickolas_Pohilets 가 sync actor init 의 인자는 어떻게 되는지 물었고(리뷰 #11, 앞서 nonisolated sync 함수의 인자가 어느 region 이냐고 물은 리뷰 #2 와 이어지는 질문이다), hborla 는 sync actor init 도 매개변수를 transfer 한다고 답했다(리뷰 #12). 6.4 에서 돌려 보면 이렇다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
actor MyActor {
var x: NonSendable
init(_ arg: NonSendable) {
self.x = arg
}
}
func makeActor() -> MyActor {
MyActor(NonSendable())
}
func makeActorShared(_ ns: NonSendable) async -> MyActor {
MyActor(ns)
}
1
2
3
4
5
6
7
ActorInitSync.swift:13:3: error: sending 'ns' risks causing data races [#RegionIsolation::SendingRisksDataRace]
11 |
12 | func makeActorShared(_ ns: NonSendable) async -> MyActor {
13 | MyActor(ns)
| |- error: sending 'ns' risks causing data races [#RegionIsolation::SendingRisksDataRace]
| `- note: sending 'ns' to actor-isolated initializer 'init(_:)' risks causing data races between actor-isolated code and code in the current isolation context
14 | }
makeActor() 는 새로 만든 값을 넘기니 진단이 0개이고, makeActorShared(_:) 는 task-isolated 인 매개변수를 actor 로 넘기려 해서 error 다. 제안서가 미래 방향으로 둔 transferring 매개변수가 있어야 이런 sync init 의 인자를 호출하는 쪽이 보내겠다고 약속할 수 있다.
self 를 쓰는 흐름에 대한 진단은 SE-0327 의 문구 그대로 나온다. self 를 써서 method 를 부른 뒤에는 nonisolated property 만 읽을 수 있다.
1
2
3
4
5
6
7
8
9
10
11
actor MyActor {
var nonSendableField: NonSendable
init() {
self.nonSendableField = NonSendable()
self.callMethod()
self.nonSendableField.doSomething()
}
nonisolated func callMethod() {}
}
1
2
3
4
5
6
7
8
9
ActorSelfInit.swift:7:10: error: cannot access property 'nonSendableField' here in nonisolated initializer
4 | init() {
5 | self.nonSendableField = NonSendable()
6 | self.callMethod()
| `- note: after calling instance method 'callMethod()', only nonisolated properties of 'self' can be accessed from this init
7 | self.nonSendableField.doSomething()
| `- error: cannot access property 'nonSendableField' here in nonisolated initializer
8 | }
9 |
callMethod() 를 부르는 순간 self 가 밖으로 나갈 수 있으니, 그 뒤로는 self 를 Sendable 로 취급해야 한다. non-Sendable 필드는 그래서 쓸 수 없다.
deinit 은 필드 종류에 따라 규칙이 갈린다. 제안서의 규칙은 이렇다(제안서의 “actor deinitializer” 예). actor 의 deinit 에서는 self 가 escape 하기 전에는 네 종류 필드를 모두 읽을 수 있고, escape 한 뒤에는 Sendable 인 let 필드만 읽을 수 있다. 이때 Sendable 인 var 필드도 “Must be immutable” 이라며 error 로 적혀 있다. global actor 에 묶인 class 는 escape 하기 전에도 non-Sendable 필드를 읽을 수 없다. 이 규칙을 담은 actor 로 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 escapeSelfIntoNonIsolated(_ a: AnyObject) {}
actor MyActor {
var mutableNonSendableField = NonSendable()
let immutableNonSendableField = NonSendable()
var mutableSendableField = 1
let immutableSendableField = 1
deinit {
_ = self.immutableSendableField
_ = self.mutableSendableField
_ = self.mutableNonSendableField
_ = self.immutableNonSendableField
escapeSelfIntoNonIsolated(self)
_ = self.immutableSendableField
_ = self.mutableSendableField
_ = self.mutableNonSendableField
_ = self.immutableNonSendableField
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
ActorDeinit.swift:12:7: error: cannot access property 'mutableNonSendableField' with a non-Sendable type 'NonSendable' from nonisolated deinit
7 | let immutableSendableField = 1
8 |
9 | deinit {
| `- note: add 'isolated' to run isolated to 'MyActor', which may be later than 'nonisolated deinit'
10 | _ = self.immutableSendableField
11 | _ = self.mutableSendableField
12 | _ = self.mutableNonSendableField
| `- error: cannot access property 'mutableNonSendableField' with a non-Sendable type 'NonSendable' from nonisolated deinit
13 | _ = self.immutableNonSendableField
14 |
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 name = "ns"
3 | var integerField = 1
ActorDeinit.swift:13:14: error: cannot access property 'immutableNonSendableField' with a non-Sendable type 'NonSendable' from nonisolated deinit
7 | let immutableSendableField = 1
8 |
9 | deinit {
| `- note: add 'isolated' to run isolated to 'MyActor', which may be later than 'nonisolated deinit'
10 | _ = self.immutableSendableField
11 | _ = self.mutableSendableField
12 | _ = self.mutableNonSendableField
13 | _ = self.immutableNonSendableField
| `- error: cannot access property 'immutableNonSendableField' with a non-Sendable type 'NonSendable' from nonisolated deinit
14 |
15 | escapeSelfIntoNonIsolated(self)
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 name = "ns"
3 | var integerField = 1
ActorDeinit.swift:19:7: error: cannot access property 'mutableNonSendableField' with a non-Sendable type 'NonSendable' from nonisolated deinit
7 | let immutableSendableField = 1
8 |
9 | deinit {
| `- note: add 'isolated' to run isolated to 'MyActor', which may be later than 'nonisolated deinit'
10 | _ = self.immutableSendableField
11 | _ = self.mutableSendableField
:
17 | _ = self.immutableSendableField
18 | _ = self.mutableSendableField
19 | _ = self.mutableNonSendableField
| `- error: cannot access property 'mutableNonSendableField' with a non-Sendable type 'NonSendable' from nonisolated deinit
20 | _ = self.immutableNonSendableField
21 | }
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 name = "ns"
3 | var integerField = 1
ActorDeinit.swift:20:14: error: cannot access property 'immutableNonSendableField' with a non-Sendable type 'NonSendable' from nonisolated deinit
7 | let immutableSendableField = 1
8 |
9 | deinit {
| `- note: add 'isolated' to run isolated to 'MyActor', which may be later than 'nonisolated deinit'
10 | _ = self.immutableSendableField
11 | _ = self.mutableSendableField
:
18 | _ = self.mutableSendableField
19 | _ = self.mutableNonSendableField
20 | _ = self.immutableNonSendableField
| `- error: cannot access property 'immutableNonSendableField' with a non-Sendable type 'NonSendable' from nonisolated deinit
21 | }
22 | }
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 name = "ns"
3 | var integerField = 1
ActorDeinit.swift:18:7: error: cannot access property 'mutableSendableField' here in deinitializer
13 | _ = self.immutableNonSendableField
14 |
15 | escapeSelfIntoNonIsolated(self)
| `- note: after making a copy of 'self', only nonisolated properties of 'self' can be accessed from a deinit
16 |
17 | _ = self.immutableSendableField
18 | _ = self.mutableSendableField
| `- error: cannot access property 'mutableSendableField' here in deinitializer
19 | _ = self.mutableNonSendableField
20 | _ = self.immutableNonSendableField
6.4 는 escape 하기 전인데도 12 번째 줄(mutableNonSendableField)과 13 번째 줄(immutableNonSendableField)의 non-Sendable 필드 접근에 error 를 낸다. escape 뒤에는 19, 20 번째 줄의 non-Sendable 필드와 18 번째 줄의 Sendable var 필드(mutableSendableField)가 error 이고, 17 번째 줄의 let Sendable 필드만 통과한다. 진단이 출력되는 순서는 12, 13, 19, 20, 18 번째 줄이다. 18 번째 줄의 note 는 after making a copy of 'self', only nonisolated properties of 'self' can be accessed from a deinit 이고, 12, 13, 19, 20 번째 줄의 note 는 add 'isolated' to run isolated to 'MyActor', which may be later than 'nonisolated deinit' 으로 deinit 을 isolated 로 바꾸는 길을 알려 준다. 이 문구는 SE-0327 이 만든 진단의 것이고, 이 길은 SE-0371 이 연 isolated deinit 이다.
Sendable 필드 읽기
non-Sendable 값을 weak transfer 로 넘긴 뒤에도 그 값의 Sendable 필드는 읽을 수 있다. 값이 넘어간 뒤 쓸 수 없는 것은 값의 mutable 상태이고, 값에 영원히 바뀌지 않는 부분은 동시에 읽어도 안전하기 때문이다. 제안서는 class 에서는 let 인 Sendable 필드만 안전하다고 한다. var 인 Sendable 필드는 넘겨받은 쪽이 바꿀 수 있기 때문이다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
final class Holder {
let letSendable: Int = 1
var varSendable: Int = 2
}
@MainActor func modifyOnMainActor(_ x: Holder) async {
x.varSendable = 3
}
func example() async {
let x = Holder()
await modifyOnMainActor(x)
_ = x.letSendable
_ = x.varSendable
}
1
2
3
4
5
6
7
8
9
10
11
SendableField.swift:12:9: error: sending 'x' risks causing data races [#RegionIsolation::SendingRisksDataRace]
10 | func example() async {
11 | let x = Holder()
12 | await modifyOnMainActor(x)
| |- error: sending 'x' risks causing data races [#RegionIsolation::SendingRisksDataRace]
| `- note: sending 'x' to main actor-isolated global function 'modifyOnMainActor' risks causing data races between main actor-isolated and local nonisolated uses
13 | _ = x.letSendable
14 | _ = x.varSendable
| `- note: access can happen concurrently
15 | }
16 |
note 는 x.varSendable 을 읽는 14 번째 줄에만 붙고, x.letSendable 을 읽는 13 번째 줄에는 붙지 않는다. let 필드는 넘어간 뒤에도 읽을 수 있다는 규칙이 나타난다.
value type 은 제안서가 따로 설명한다. let 으로 바인딩한 value type 은 값이 바뀌지 않으니 Sendable 필드를 읽어도 된다. var 로 바인딩한 value type 은 closure 가 reference 로 capture 하지 않았다면 읽어도 된다. closure 가 reference 로 capture 했다면 넘겨받은 쪽이 변수를 바꿀 수 있으니 읽을 수 없다.
기대 효과
region 모델의 득은 “안전한데도 막히던 코드” 가 통과한다는 데 있다. 지금까지 본 Motivation.swift 가 그런 코드다. 값을 새로 만들어 actor 로 보내고 보낸 뒤에는 쓰지 않았는데도 예전 규칙은 non-Sendable 이라는 이유만으로 막았다. region 모델은 이 코드를 통과시키고, 같은 값을 보낸 뒤 다시 쓰는 코드(UseAfter.swift)만 막는다.
@unchecked Sendable 로 눌러 두던 곳이 줄어든다. 제안서의 동기 절이 말하듯, non-Sendable 타입을 actor 로 보내려면 타입에 @unchecked Sendable 을 붙여 안전하다고 선언하는 길뿐이었다. 그 선언은 타입 전체에 대한 약속이라 사용하는 모든 곳에서 지켜져야 하는데, region 모델은 사용하는 곳마다 값의 흐름을 따져서 약속을 대신한다.
진단이 실제 접근 지점에 붙는다. Task.detached 안에서 non-Sendable 값을 capture 하는 두 함수를 6.4 에서 돌려 보면 차이가 보인다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public struct NotSendable {
var s: String
}
func test() async {
let s = NotSendable(s: "hi")
let task = Task.detached {
print(s)
}
await task.value
}
func testUseAfter() async {
let s = NotSendable(s: "hi")
let task = Task.detached {
print(s)
}
print(s)
await task.value
}
1
2
3
4
5
6
7
8
9
10
11
12
TaskDetached.swift:15:19: error: sending value of non-Sendable type '() async -> ()' risks causing data races [#RegionIsolation::SendingRisksDataRace]
13 | func testUseAfter() async {
14 | let s = NotSendable(s: "hi")
15 | let task = Task.detached {
| |- 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 static method 'detached(name:priority:operation:)' risks causing races in between local and caller code
16 | print(s)
17 | }
18 | print(s)
| `- note: access can happen concurrently
19 | await task.value
20 | }
test() 는 진단이 0개이고 testUseAfter() 만 걸린다. 첫 번째 리뷰에서 KeithBauerANZ 는 툴체인을 받아 비슷한 코드를 돌렸다가 경고를 받고, 이것이 버그인지 물었다(리뷰 #12). hborla 는 Task 가 @Sendable closure 를 받는다는 점, 그리고 transferring 매개변수라는 미래 방향이 필요하다는 점으로 답했다(리뷰 #16). 지금 test() 가 0개인 것은 그 미래 방향이 SE-0430 의 sending 으로 들어와서, Task.detached 의 operation 이 sending 을 받고 disconnected 인 값의 capture 를 허용하기 때문이다.
두 번째 리뷰에서 FranzBusch 가 든 iterator 와 TaskGroup 의 예는 이 모델이 error 를 어디에 붙이는지 보여 준다(리뷰 #14).
1
2
3
4
5
6
7
8
9
10
11
12
13
func bar() async {
let stream = AsyncStream<Int>.makeStream().stream
var iterator = stream.makeAsyncIterator()
let first = await iterator.next()
_ = first
await withTaskGroup(of: Void.self) { group in
group.addTask {
while let next = await iterator.next() {
_ = next
}
}
}
}
1
2
3
4
5
6
7
8
9
IteratorGroup.swift:7:11: error: passing closure as a 'sending' parameter risks causing data races between code in the current isolation context and concurrent execution of the closure [#RegionIsolation::SendingClosureRisksDataRace]
5 | _ = first
6 | await withTaskGroup(of: Void.self) { group in
7 | group.addTask {
| `- error: passing closure as a 'sending' parameter risks causing data races between code in the current isolation context and concurrent execution of the closure [#RegionIsolation::SendingClosureRisksDataRace]
8 | while let next = await iterator.next() {
| `- note: closure captures reference to mutable var 'iterator' which remains modifiable by code in the current isolation context
9 | _ = next
10 | }
6.4 는 이 경우에 위와 다른 진단 이름(SendingClosureRisksDataRace)을 쓰고, closure 가 mutable var 를 reference 로 capture 해서 호출한 쪽도 계속 바꿀 수 있다는 점을 note 로 짚는다. 같은 문서 sending-closure-risks-data-race 가 이 진단을 설명한다.
withTaskGroup 으로 child task 를 묶어 관리하기
withTaskGroup(of:returning:isolation:body:) 은 child task 를 묶어 관리하는 TaskGroup 을 만들어 body 에 넘기는 함수이고, TaskGroup.addTask(priority:operation:) 는 그 group 에 child task 를 하나 추가한다. 예제의 stream 인 AsyncStream 은 값을 비동기로 내보내는 AsyncSequence 이고, makeAsyncIterator() 가 non-Sendable 한 iterator 를 만든다.
다른 선택지는 왜 안 됐나
제안서의 Alternatives considered 는 둘이고, 리뷰는 그보다 많은 논의를 낳았다. 이 절은 둘을 먼저 보고, 리뷰에서 나온 쟁점과 미래 방향까지 이어서 정리한다.
모든 타입을 Sendable 로 감사하기
가장 단순한 대안은 non-Sendable 로 남아 있는 타입을 모두 Sendable 로 만드는 것이다. 제안서는 현실에서 이것이 되지 않는다고 본다. 어떤 타입은 본질적으로 한 곳에서만 쓰이도록 설계되어서 Sendable 로 만들 수 없고, 어떤 타입은 외부 라이브러리가 소유해서 사용자가 고칠 수 없다. 그래서 non-Sendable 타입이 남는 현실을 두고, 그 값이 안전하게 쓰이는 흐름을 컴파일러가 알아보게 하는 방향을 택했다. 첫 번째 리뷰에서 tgoyne 는 이 제안에 강하게 찬성하면서, 지금은 non-Sendable 타입이 사실상 @MainActor 함수에서만 쓸 수 있다고 적었다(리뷰 #5).
weak transfer 를 명시적으로 표시하기
다른 대안은 값이 isolation 경계를 넘는 호출마다 사용자가 transfer 를 명시하게 하는 것이다. 제안서는 이를 받아들이지 않는다. async, await, Task 같은 표시가 이미 값이 경계를 넘는 자리에 붙어 있으니, 같은 자리에 표시를 또 붙이는 것은 중복이기 때문이다.
이름 논쟁
첫 번째 리뷰의 가장 큰 화제는 의외로 제목이었다. Nevin 은 “Region based isolation” 이라는 이름이 지리적 locking 처럼 읽혀서 헷갈린다고 했고(리뷰 #2), 다른 이름으로 “Concurrency isolation regions” 를 제안했다(리뷰 #4). 대안 목록에는 첫 pitch 의 제목이던 “Safely sending non-Sendable values across isolation domains” 도 있었다(리뷰 #11). taylorswift 는 “Flow-sensitive Sendable checking” 을 제안했고(리뷰 #7), wadetregaskis 는 지금 제목이 괜찮다는 쪽이었다(리뷰 #8). hborla 는 region 이 학술 논문에서 온 용어로 프로그램의 object graph 안의 영역을 가리키며, 제안서의 제목이 TSPL 같은 문서에서 이 기능을 어떻게 가르칠지를 정하는 것은 아니라고 답했다(리뷰 #3). 제안서의 감사 절이 가리키는 논문이 PLDI 2022 의 “A Flexible Type System for Fearless Concurrency” 다.
결국 이름은 그대로 남았다. 진단 문구에 region 이라는 낱말이 거의 나오지 않는 것을 보면, 이 이름은 제안서와 컴파일러 내부의 용어로 자리 잡았다고 할 수 있다. 사용자가 만나는 쪽은 sending 이다.
무엇이 되는지 알기 어렵다는 걱정
KeithBauerANZ 는 어떤 코드가 되고 안 되는지 “직접 해 보지 않고” 어떻게 아느냐고 물었고(리뷰 #12), 공식 리뷰에서는 “spooky action at a distance” 처럼 멀리 떨어진 줄이 서로 영향을 준다고 우려했다(리뷰 #23). 이 걱정은 합쳐지는 규칙이 보수적이어서 어느 값이 어느 값과 같은 region 인지 눈으로 따라가기 어렵다는 데서 나온다.
Michael_Gottesman 은 두 번째 리뷰에서 진단 계획을 밝혔다. 먼저 warning 으로 문제를 알리고, 그다음 값이 task-isolated 라는 note 를 붙이고, 그다음 region 이 어떻게 합쳐졌는지 note 로 나열한다(리뷰 #8). region 을 설명하는 것은 warning 을 만났을 때뿐이고, 평소에 remark 로 region 을 보여 주지는 않는다는 계획이었다. FranzBusch 는 region 을 보여 주는 remark 를 요청했다(리뷰 #3). 지금 6.4 진단은 이 계획의 앞부분인, error 와 접근이 겹치는 줄의 note 를 보여 준다.
리뷰에서 막은 구멍
첫 번째 리뷰에서 나온 assumeIsolated 구멍은 위에서 봤다. 수정 요청과 두 번째 리뷰, 수락 글이 각각 어느 구멍을 막았는지 순서대로 다시 정리한다. hborla 의 수정 요청 글은 리뷰에서 구멍 두 개가 드러났다고 밝히고 수정을 요청했다. 그 수정은 isolation 이 있는 key path 와 non-Sendable isolated 함수를 actor region 에 포함시키고, sync nonisolated 함수의 매개변수 region 을 transfer 할 수 없게 했다. 두 번째 리뷰의 hborla 는 세 가지 변경을 요약한다. isolated closure 의 capture 가 actor region 에 합쳐지고, global actor 코드를 부르는 closure 는 형식상 isolated 이며, isolated key path 는 actor region 에 속한다(리뷰 #1). 수락 글은 assumeIsolated 의 결과 타입에 Sendable 을 요구하는 것을 더했다.
미래 방향
제안서가 미래 방향으로 남긴 것은 셋이다. 하나는 transferring 매개변수다. 매개변수에 transferring 을 쓰면 호출하는 쪽이 값을 완전히 넘기고 더는 쓰지 않겠다고 약속하고, 받는 함수는 값을 마음대로 다른 곳에 보낼 수 있다. 이 이름은 나중에 SE-0430 에서 sending 으로 정해졌다. 6.4 진단의 sending 이 이것이다. 둘째는 @returnsIsolated 로, 반환값이 어느 region 에 속하는지를 표시하는 방안이다. 셋째는 필드를 disconnected 로 표시하고 disconnect 연산자로 꺼내는 방안이다. 두 번째 리뷰의 Dmitriy_Ignatyev 와 Michael_Gottesman 이 disconnected 필드와 transferring 반환값을 주고받은 대목이 이 방향의 논의다(리뷰 #4, #9). 제안서는 세 방향 모두 문법이 예시일 뿐이라고 밝힌다.
마이그레이션
region 기반 isolation 은 Swift 6 언어 모드에서 기본으로 켜지고, RegionBasedIsolation upcoming feature 로 이름이 붙어 있다. Swift 5 모드에서 먼저 영향을 보려면 -strict-concurrency=complete 로 빌드해서 warning 을 본다. 이름을 명시해서 켜야 한다면 SwiftPM 에서는 이렇게 쓴다.
1
swiftSettings: [.enableUpcomingFeature("RegionBasedIsolation")]
대부분의 코드는 새 error 를 만나지 않는다. 이전에는 non-Sendable 이라 막히던 호출 중에서 disconnected 인 값을 넘기는 것이 통과하게 되는 쪽이 이 제안의 방향이기 때문이다. 새로 진단을 받는 코드는 두 부류다. 하나는 값을 보낸 뒤에 그 값을 다시 쓰는 코드이고, 다른 하나는 assumeIsolated 로 non-Sendable 결과를 꺼내던 코드다. 뒤쪽은 Sendable 결과 타입을 요구하는 수정 때문에 Swift 6 에서 error 가 된다. Stash 예제가 이 경우로, -strict-concurrency=complete 에서는 warning 으로 먼저 알려 준다.
제안서가 고치는 순서를 정해 두지는 않았다. 아래는 이 글의 필자가 진단을 정리하며 잡은 순서다. 먼저 warning 이 나오는 자리를 찾고, 값을 넘긴 뒤에 쓰는 코드를 순서만 바꿔서 정리한다. 그래도 정말 같은 값을 두 곳이 써야 한다면 값을 복사하거나, 그 값을 actor 안으로 옮기거나, 타입을 Sendable 로 만드는 길로 간다.
정리
- non-Sendable 값을 같은 isolation 안에서 쓰는 한 문제가 없고, 경계를 넘는 순간에만 region 을 따진다.
- region 은 함수 호출, 대입, closure capture, 조건 분기에서 합쳐지고, 한 번 합쳐진 것은 합류 뒤에도 합쳐진 채로 남는다.
- region 은 disconnected, actor-isolated, task-isolated, invalid 네 종류이고 disconnected 만 보낼 수 있다.
- 기본 전달은 weak transfer 라서 호출한 쪽이 객체의 수명을 계속 갖는다. 소유권을 넘기는 strong transfer 는
transferring으로 남겨 뒀다. - 6.4 진단은 값을 보내는 줄에 error 를, 나중에 쓰는 줄에 note 를 붙인다.
- 리뷰에서
assumeIsolated를 비롯한 구멍이 드러났고, 결과 타입에Sendable을 요구하는 수정으로 닫혔다. - actor 의 init 과 deinit 에서
self를 쓰는 흐름은 SE-0327 의 진단 문구로 나오고, 인자를 actor 로 보내는 줄은sending진단으로 나온다.
관련 글
- [SE-0337] Incremental migration to concurrency checking
- [SE-0412] Strict concurrency for global variables
- [SE-0411] Isolated default value expressions
- [SE-0401] Remove Actor Isolation Inference caused by Property Wrappers
- [SE-0423] Dynamic actor isolation enforcement from non-strict-concurrency contexts


