[SE-0470] Global-actor isolated conformances
이 글은 Swift Evolution 제안서 원문과 포럼 리뷰 스레드를 Claude Code 로 정리한 글이다. 코드는 Xcode 27 의 Swift 6.4 컴파일러로 빌드하고, 진단 메시지와 실행 결과는 실제로 컴파일하고 실행해서 나온 것을 옮겼다.
제안서 정보
- 번호: SE-0470
- 상태: Implemented (Swift 6.2)
- upcoming feature flag:
InferIsolatedConformances(Swift 7 언어 모드에서 기본으로 켜진다) - 저자: Doug Gregor
- 리뷰 매니저: Xiaodi Wu
- Vision: Improving the approachability of data-race safety
- pitch: Pre-pitch: Isolated conformances (2025-02-08 부터)
- 리뷰: Review (2025-03-21 부터 04-03 까지)
- 수락: Accepted (2025-04-09)
- 수정안 pitch: Pitch: Amend SE-0466 + SE-0470 to improve isolation inference (2025-05-13)
- 수정안 리뷰: Amendment: SE-0470 (2025-07-09 부터 07-15 까지, 신속 리뷰)
- 수정안 수락: Accepted amendment to SE-0470 (2025-07-16)
- 전제 제안서: SE-0414 (region based isolation), SE-0430 (
sending), SE-0449 (nonisolated문법) - 함께 읽을 제안서: SE-0466 (모듈 기본 isolation)
한 줄 요약
@MainActor 타입이 nonisolated 프로토콜을 따를 수 있게 하는 제안이다. 상속 목록에 class C: @MainActor P 처럼 isolation 을 적으면 그 conformance 는 main actor 안에서만 쓸 수 있는 “isolated conformance” 가 되고, 컴파일러가 세 규칙으로 그 conformance 가 main actor 밖으로 새어 나가는 길을 막는다. 이 글은 세 규칙을 컴파일러 진단으로 하나씩 확인하고, @MainActor 타입에서 이 철자를 자동으로 추론하는 upcoming feature InferIsolatedConformances 와 수정안의 추론 규칙까지 측정한다.
어떤 문제였나
SE-0466 글에서 본 것처럼 Swift 6 언어 모드에서 isolation 을 적지 않은 코드는 nonisolated 다. 그런데 앱 코드의 모델 타입은 @MainActor 인 경우가 많고, 표준 라이브러리의 프로토콜(Equatable, Hashable, Codable)과 직접 만든 프로토콜은 대부분 nonisolated 다. 이 둘이 만나는 자리가 이 제안이 풀려는 문제다.
이 글의 뼈대는 이렇다. 먼저 문제를 세 장면으로 본다. 컴파일러가 거부하는 장면, 거부를 피하려고 nonisolated 로 빼는 장면, MainActor.assumeIsolated 로 덮었다가 런타임에 죽는 장면이다. 그다음 바뀌는 것을 철자, 세 규칙, 동적 캐스트, 추론, 기본 MainActor 모드, 빌드 설정의 순서로 측정한다. 이어서 포럼 스레드 여섯 개를 따라가고, 소스 호환과 마이그레이션을 정리한다.
앞 글들의 내용은 짧게 짚고 간다.
- SE-0414 글: region based isolation. 값이 어느 “region” 에 속하는지를 따라서 non-
Sendable값을 다른 isolation 으로 넘겨도 되는지 판단한다. 이 글의 Rule 3 이 이 위에 서 있다 - SE-0430 글:
sending매개변수와 결과. 값이 호출 뒤에 호출자 쪽에서 다시 쓰이지 않음을 약속한다 - SE-0449 글:
nonisolated를 타입과 extension 에 붙이는 문법. 이 글에서는 conformance 앞에 붙는nonisolated가 나온다 - SE-0466 글: 모듈의 기본 isolation 을
@MainActor로 바꾸는 옵션. 이 글의 추론 기능이 그 모드와 함께 켜진다 - SE-0423 글:
MainActor.assumeIsolated같은 동적 isolation 검사 - SE-0337 글:
@preconcurrency로 검사를 런타임으로 미루는 길
conformance란?
이 글의 모든 이야기가 conformance 라는 낱말 위에 있어서 먼저 풀어 둔다. 프로토콜은 “이런 메서드와 속성을 갖춰라” 라는 요구사항 목록이고, conformance 는 “이 타입이 그 목록을 갖췄다” 는 선언이다. struct Point: Equatable 이라고 쓰면 Point 와 Equatable 짝에 대한 conformance 가 하나 생긴다. 이때 요구사항을 실제로 채우는 구현을 witness 라고 부른다. Equatable 의 요구사항은 == 이고, Point 안에 쓴(또는 컴파일러가 합성한) == 가 그 witness 다.
컴파일러는 conformance 마다 “요구사항별로 어느 구현을 부르는가” 를 적은 표를 만들어 둔다. 제네릭 함수 func isEqual<T: Equatable>(_ a: T, _ b: T) 는 T 가 무엇인지 모르는 채로 컴파일된다. 호출하는 쪽이 T = Point 를 정하면서 Point: Equatable conformance 를 같이 넘기고, 함수 안의 a == b 는 그 표를 거쳐 Point.== 로 간다. 비유하면 conformance 는 “이 사람은 운전할 수 있다” 는 면허증이고, 제네릭 함수는 면허증만 보고 운전을 맡기는 대리 기사 호출 앱이다. 면허증은 호출한 쪽에서 앱으로 넘어가고, 앱은 그 면허증을 가지고 어디서든 운전을 시킬 수 있다.
문제는 이 면허증을 어디서든 쓸 수 있다는 가정이다. witness 가 @MainActor 의 상태를 읽는다면, main actor 밖에서 그 witness 를 부르는 순간 data race 가 된다. 이 제안은 그 면허증에 “main actor 안에서만 유효” 라는 도장을 찍고, 도장이 찍힌 면허증이 새어 나가지 못하게 하는 규칙을 정한다.
@MainActor 타입과 프로토콜의 충돌
제안서 Introduction 의 예제다. @MainActor 클래스가 Equatable 을 따르게 하려는 가장 평범한 코드다.
emit-sil 로 SIL 단계까지 진단받기
이 글의 진단은 모두 -emit-sil 로 뽑았다. -emit-sil 은 타입 검사 뒤 SIL(컴파일러 중간 표현) 단계까지 컴파일해서 그 단계의 진단까지 낸다. 타입 검사까지만 하는 -typecheck 는 SIL 단계의 진단(초기화 검사, region 검사)을 빼먹는다. -o /dev/null 은 결과 파일을 버리고, -parse-as-library 는 최상위 코드가 없는 일반 소스 파일로 다루라는 옵션이며, -wmo 는 모든 파일을 한 모듈로 같이 컴파일하게 한다. 이 옵션들의 자세한 이야기는 SE-0423 글에 있다. 컴파일러는 Apple Swift version 6.4 (swiftlang-6.4.0.34.1) 이다.
1
xcrun swiftc -emit-sil -o /dev/null -parse-as-library -wmo -swift-version 6 Motivation.swift
이 글에서 “기본” 이라고 하면 이 명령처럼 Swift 6 언어 모드에 아무 옵션도 더하지 않은 판이다. 다른 판은 옵션을 앞에 더해서 부른다. 이 글의 진단 실험은 대부분 파일 하나를 이 명령으로 컴파일한 것이다. 그 밖에 -print-ast 로 AST 를 찍거나, 실행 파일을 만들어 돌리거나, lldb 와 swift build 를 쓰는 곳에서는 그 명령을 따로 적는다. 진단 아래의 [#...] 줄은 컴파일러가 진단 끝에 붙이는 문서 링크이고, [exit N] 은 컴파일러의 종료 코드다.
Motivation.swift
1
2
3
4
5
6
7
8
9
10
11
12
@MainActor
class MyModelType: Equatable {
var name: String
init(name: String) {
self.name = name
}
static func ==(lhs: MyModelType, rhs: MyModelType) -> Bool {
lhs.name == rhs.name
}
}
MyModelType 은 @MainActor 클래스이고 Equatable 을 따른다. == 는 클래스를 따라 @MainActor 이고 name 을 읽는다. 기본 Swift 6 모드의 진단이다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Motivation.swift:2:20: error: conformance of 'MyModelType' to protocol 'Equatable' crosses into main actor-isolated code and can cause data races [#ConformanceIsolation]
1 | @MainActor
2 | class MyModelType: Equatable {
| |- error: conformance of 'MyModelType' to protocol 'Equatable' crosses into main actor-isolated code and can cause data races [#ConformanceIsolation]
| |- note: isolate this conformance to the main actor with '@MainActor'
| `- note: turn data races into runtime errors with '@preconcurrency'
3 | var name: String
4 |
:
7 | }
8 |
9 | static func ==(lhs: MyModelType, rhs: MyModelType) -> Bool {
| |- note: main actor-isolated operator function '==' cannot satisfy nonisolated requirement
| `- note: mark operator function '==' 'nonisolated'
10 | lhs.name == rhs.name
11 | }
[#ConformanceIsolation]: <https://docs.swift.org/compiler/documentation/diagnostics/conformance-isolation>
[exit 1]
오류 문장은 “MyModelType 의 Equatable conformance 가 main actor 격리 코드로 넘어가서 data race 가 날 수 있다” 이다. Equatable 은 nonisolated 프로토콜이라서 요구사항 == 도 nonisolated 인데, 이 타입의 == 는 @MainActor 라서 요구사항을 만족시킬 수 없다는 것이 세 번째 note 이고, 네 번째 note 는 그 == 를 nonisolated 로 빼라는 고치는 법이다.
주목할 것은 note 의 순서다. 첫 번째 note 가 바로 이 제안서의 철자 @MainActor 를 고칠 방법으로 내놓는다. 두 번째는 @preconcurrency 로 검사를 런타임으로 미루는 길이고(SE-0337 글), 세 번째 note 는 해법이 아니라 왜 안 되는지를 설명하고, 네 번째가 == 를 nonisolated 로 빼는 길이다. 6.4 컴파일러에서 이 제안의 철자는 가장 먼저 권하는 해법이다.
nonisolated 로 빼는 우회
이 제안이 나오기 전의 대표적인 해법은 note 의 마지막 길이다. == 를 nonisolated 로 만들면 요구사항과 isolation 이 같아진다. SE-0449 글이 다룬 nonisolated 문법을 멤버에 붙이는 것이다.
Workaround.swift
1
2
3
4
5
6
7
8
9
10
11
12
@MainActor
class MyModelType: Equatable {
var name: String
init(name: String) {
self.name = name
}
nonisolated static func ==(lhs: MyModelType, rhs: MyModelType) -> Bool {
lhs.name == rhs.name
}
}
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
Workaround.swift:10:9: error: main actor-isolated property 'name' can not be referenced from a nonisolated context
1 | @MainActor
2 | class MyModelType: Equatable {
3 | var name: String
| `- note: property declared here
4 |
5 | init(name: String) {
:
8 |
9 | nonisolated static func ==(lhs: MyModelType, rhs: MyModelType) -> Bool {
10 | lhs.name == rhs.name
| `- error: main actor-isolated property 'name' can not be referenced from a nonisolated context
11 | }
12 | }
Workaround.swift:10:21: error: main actor-isolated property 'name' can not be referenced from a nonisolated context
1 | @MainActor
2 | class MyModelType: Equatable {
3 | var name: String
| `- note: property declared here
4 |
5 | init(name: String) {
:
8 |
9 | nonisolated static func ==(lhs: MyModelType, rhs: MyModelType) -> Bool {
10 | lhs.name == rhs.name
| `- error: main actor-isolated property 'name' can not be referenced from a nonisolated context
11 | }
12 | }
[exit 1]
nonisolated 가 되면 == 는 main actor 가 아닌 곳에서도 불릴 수 있어야 하니, main actor 에 묶인 name 을 읽을 수 없다. 컴파일러는 두 군데를 모두 오류로 낸다(10:9 와 10:21, 좌변 lhs.name 과 우변 rhs.name). name 을 nonisolated(unsafe) 로 바꾸거나 Sendable 한 별도 값으로 복사해 두는 식으로 돌아갈 수는 있다. 어느 쪽이든 모델 타입의 설계를 바꿔야 하고, 동시성을 쓰려던 적이 없는 사람이 마주치기에는 무거운 변경이다.
assumeIsolated 로 덮는 우회
nonisolated 로 뺀 == 가 main actor 의 상태를 읽어야 한다면 남는 길은 “나는 지금 main actor 에 있다” 고 컴파일러에게 약속하는 것이다. SE-0423 글에서 본 MainActor.assumeIsolated 가 그 약속이다.
AssumeIsolated.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
@MainActor
final class MyModelType: Equatable {
var name: String
init(name: String) {
self.name = name
}
nonisolated static func ==(lhs: MyModelType, rhs: MyModelType) -> Bool {
MainActor.assumeIsolated {
lhs.name == rhs.name
}
}
}
@main
struct Program {
static func main() async {
let a = MyModelType(name: "a")
let b = MyModelType(name: "a")
print("on main:", a == b)
let r = await Task.detached { a == b }.value
print("detached:", r)
}
}
MyModelType 에는 이제 conformance 에 isolation 표시가 없다. == 는 nonisolated 이고, 본문에서 MainActor.assumeIsolated 로 main actor 안이라고 가정한 채 name 을 읽는다. main 에서 a == b 를 한 번 비교하고, Task.detached 안에서 한 번 더 비교한다. 컴파일은 오류 없이 된다.
MainActor.assumeIsolated로 main actor 가정하기
MainActor.assumeIsolated(_:file:line:) 는 지금 실행 중인 코드가 main actor 에서 돌고 있다고 가정하고, 클로저를 main actor isolation 으로 실행한다. 클로저가 돌려주는 값을 그대로 돌려준다. 컴파일러는 가정을 믿어 주고, 대신 실행 시점에 정말 main actor 인지를 확인해서 아니면 프로그램을 멈춘다. assumeIsolated 를 호출하는 함수의 호출자가 isolation 을 지켜 줘야 하는데, 그 약속은 타입에 적히지 않는다.
Task.detached로 새 Task 만들기
Task.detached(name:priority:operation:) 는 부모 Task 의 isolation 과 우선순위를 물려받지 않는 새 Task 를 만든다. 위 코드에서는 main actor 밖에서 a == b 를 부르는 길을 만들려고 썼다.
컴파일 결과 실행 파일을 ~/se470/assume 으로 만들고 lldb 로 돌렸다. 실행 파일 만들기는 이렇다.
1
xcrun swiftc -parse-as-library -swift-version 6 AssumeIsolated.swift -o ~/se470/assume
크래시하는 프로그램은 lldb 의 batch 모드로 backtrace 까지 본다.
1
timeout 20 xcrun lldb --batch -o run -k bt -k quit ~/se470/assume
출력에서 주소가 붙은 디스어셈블 줄과 빈 줄, libdispatch.dylib 의 레이블 줄은 줄이고 나머지는 그대로 옮긴다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
(lldb) target create "/Users/dongik/se470/assume"
Current executable set to '/Users/dongik/se470/assume' (arm64).
(lldb) run
on main: true
Process 51247 launched: '/Users/dongik/se470/assume' (arm64)
Process 51247 stopped
* thread #4, name = 'Task 2', queue = 'com.apple.root.default-qos.cooperative', stop reason = EXC_BREAKPOINT (code=1, subcode=0x19188ea84)
frame #0: 0x000000019188ea84 libdispatch.dylib`_dispatch_assert_queue_fail + 120
Target 0: (assume) stopped.
(lldb) bt
* thread #4, name = 'Task 2', queue = 'com.apple.root.default-qos.cooperative', stop reason = EXC_BREAKPOINT (code=1, subcode=0x19188ea84)
* frame #0: 0x000000019188ea84 libdispatch.dylib`_dispatch_assert_queue_fail + 120
frame #1: 0x000000019188f510 libdispatch.dylib`dispatch_assert_queue$V2.cold.1 + 116
frame #2: 0x000000019185c108 libdispatch.dylib`dispatch_assert_queue + 108
frame #3: 0x00000002be35edc8 libswift_Concurrency.dylib`_swift_task_checkIsolatedSwift + 48
frame #4: 0x00000002be30e400 libswift_Concurrency.dylib`swift_task_isCurrentExecutorWithFlagsImpl(swift::SerialExecutorRef, swift::swift_task_is_current_executor_flag) + 356
frame #5: 0x0000000100001108 assume`static MainActor.assumeIsolated(_:file:line:) + 88
frame #6: 0x0000000100000ec0 assume`static MyModelType.== infix(_:_:) + 164
frame #7: 0x0000000100001a94 assume`closure #1 in static Program.main() + 52
frame #8: 0x0000000100001bac assume`partial apply for closure #1 in static Program.main()
frame #9: 0x00000001000027e4 assume`(1) await resume partial function for reabstraction thunk helper <τ_0_0, τ_0_1 where τ_0_0: Swift.Sendable, τ_0_1 == Swift.Never> from @escaping @isolated(any) @callee_guaranteed @async () -> (@out τ_0_0) to @escaping @callee_guaranteed @async () -> (@out τ_0_0, @error @owned Swift.Error)
frame #10: 0x0000000100002934 assume`(1) await resume partial function for partial apply forwarder for reabstraction thunk helper <τ_0_0, τ_0_1 where τ_0_0: Swift.Sendable, τ_0_1 == Swift.Never> from @escaping @isolated(any) @callee_guaranteed @async () -> (@out τ_0_0) to @escaping @callee_guaranteed @async () -> (@out τ_0_0, @error @owned Swift.Error)
(lldb) quit
첫 비교는 on main: true 로 끝났고, Task.detached 안의 두 번째 비교에서 프로세스가 EXC_BREAKPOINT 로 멈췄다. 멈춘 스레드는 cooperative 큐의 Task 2 다. backtrace 를 아래에서 위로 읽으면 closure #1 in static Program.main() 이 MyModelType.== 를 부르고, 그 안의 MainActor.assumeIsolated 가 swift_task_isCurrentExecutorWithFlagsImpl 로 지금 executor 가 main actor 인지 묻고, 아니라서 dispatch_assert_queue 가 실패한다. 제안서 Motivation 이 말한 그대로다. 정적으로는 통과하고, main 밖에서 불리는 순간 런타임에서 죽는다.
세 장면을 한 줄로 줄이면 이렇다. 그대로 쓰면 컴파일러가 거부하고, nonisolated 로 빼면 상태를 못 읽고, assumeIsolated 로 덮으면 런타임에 죽는다. 이 제안은 “이 conformance 는 main actor 안에서만 쓴다” 를 타입 시스템에 올려서 세 번째 장면의 크래시를 컴파일 오류로 앞당긴다.
무엇이 바뀌나
제안의 핵심은 두 가지다. 하나는 conformance 를 선언할 때 프로토콜 앞에 isolation 을 적을 수 있다는 것(class C: @MainActor P)이고, 다른 하나는 그렇게 만든 isolated conformance 가 isolation 도메인 밖으로 새어 나가지 못하게 컴파일러가 세 규칙으로 막는다는 것이다. 이어서 이 철자를 컴파일러가 알아서 붙여 주는 추론 규칙(upcoming feature)과 수정안이 바뀌는 순서로 하나씩 돌려 본다.
@MainActor conformance
제안서가 첫 번째로 보여 주는 코드다. Motivation 의 MyModelType 에서 상속 목록의 Equatable 앞에 @MainActor 를 붙였다. 나머지는 그대로다.
Explicit.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
@MainActor
class MyModelType: @MainActor Equatable {
var name: String
init(name: String) {
self.name = name
}
static func ==(lhs: MyModelType, rhs: MyModelType) -> Bool {
lhs.name == rhs.name
}
}
@MainActor
func hasMatchingOnMain(_ value: MyModelType, in modelValues: [MyModelType]) -> Bool {
modelValues.contains(value)
}
nonisolated func hasMatching(_ value: MyModelType, in modelValues: [MyModelType]) -> Bool {
modelValues.contains(value)
}
MyModelType: @MainActor Equatable 이 isolated conformance 선언이다. 읽는 법은 “MyModelType 은 Equatable 을 따르는데, 그 conformance 는 main actor 에 isolated 되어 있다” 이다. 타입이 @MainActor 인 것과 conformance 가 @MainActor 인 것은 따로 적는 두 가지다. 아래 OtherIsolation.swift 에서 보듯 타입이 @MainActor 가 아니어도 conformance 만 main actor 에 묶을 수 있다.
Sequence.contains로 원소 포함 여부 확인하기
Sequence.contains(_:) 는 원소가 Equatable 일 때 시퀀스 안에 같은 값이 있는지 == 로 비교해서 Bool 을 돌려준다. == 가 곧 Equatable conformance 의 witness 라서, 이 호출은 conformance 를 쓰는 대표적인 자리다.
hasMatchingOnMain 은 @MainActor 함수라서 modelValues.contains(value) 가 conformance 를 쓰는 것이 문제 없다. 그런데 nonisolated func hasMatching 도 같은 contains 호출을 하는데, 이 파일을 컴파일한 결과는 이렇다.
1
[exit 0]
진단이 하나도 없고 종료 코드는 0 이다. 6.4 에서 Array.contains 는 Sequence.Element: Equatable 요구사항을 associated type 을 거쳐 쓰는 경로라서, 이 호출에는 진단이 붙지 않는다. 이 글 뒤의 “Rule 1” 절에서 같은 호출을 실행해 본다. 이 자리에서는 contains 를 지우고 제네릭 함수에 직접 conformance 를 넘기는 경로로 바꿔서 규칙이 작동하는지 본다.
Use.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
@MainActor
class MyModelType: @MainActor Equatable {
var name: String
init(name: String) { self.name = name }
static func ==(lhs: MyModelType, rhs: MyModelType) -> Bool { lhs.name == rhs.name }
}
func isEqual<T: Equatable>(_ a: T, _ b: T) -> Bool { a == b }
nonisolated func hasMatching(_ value: MyModelType, in modelValues: [MyModelType]) -> Bool {
modelValues.contains(value)
}
nonisolated func direct(_ a: MyModelType, _ b: MyModelType) -> Bool {
isEqual(a, b)
}
nonisolated func erase(_ a: MyModelType) -> any Equatable {
a
}
isEqual<T: Equatable> 는 일반 제네릭 함수이고, direct 는 nonisolated 함수에서 그것을 부른다. erase 는 MyModelType 값을 any Equatable 로 지운다. 둘 다 isolated conformance 를 nonisolated 코드로 가져가는 길이다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Use.swift:15:3: error: main actor-isolated conformance of 'MyModelType' to 'Equatable' cannot be used in nonisolated context [#IsolatedConformances]
13 |
14 | nonisolated func direct(_ a: MyModelType, _ b: MyModelType) -> Bool {
15 | isEqual(a, b)
| `- error: main actor-isolated conformance of 'MyModelType' to 'Equatable' cannot be used in nonisolated context [#IsolatedConformances]
16 | }
17 |
Use.swift:19:3: error: main actor-isolated conformance of 'MyModelType' to 'Equatable' cannot be used in nonisolated context [#IsolatedConformances]
17 |
18 | nonisolated func erase(_ a: MyModelType) -> any Equatable {
19 | a
| `- error: main actor-isolated conformance of 'MyModelType' to 'Equatable' cannot be used in nonisolated context [#IsolatedConformances]
20 | }
21 |
[#IsolatedConformances]: <https://docs.swift.org/compiler/documentation/diagnostics/isolated-conformances>
[exit 1]
두 곳이 오류다. 하나는 direct 안의 isEqual(a, b) 호출(15:3), 하나는 erase 의 a 를 any Equatable 로 바꾸는 자리(19:3)다. 문구는 같다. “main actor 에 isolated 된 conformance 는 nonisolated 컨텍스트에서 쓸 수 없다” 는 뜻이다. 같은 파일의 hasMatching 에는 진단이 없다는 점에서 contains 경로가 이 규칙에 걸리지 않는 6.4 의 동작이 다시 보인다.
진단 줄 끝의 [#IsolatedConformances] 는 컴파일러의 진단 그룹 이름이고, 아래 같은 이름의 링크 줄이 그 설명 문서다. 이 이름은 이 글 내내 나오는데, @MainActor conformance 의 규칙을 어긴 오류는 IsolatedConformances 이고, 프로토콜과 witness 사이의 isolation 불일치는 ConformanceIsolation 이다.
이번에는 같은 호출을 @MainActor 함수 안의 Task.detached 로 옮겨 본다. 호출 자리가 main actor 안에서 시작하더라도 클로저가 main actor 밖에서 돌면 막혀야 한다.
ExplicitDetached.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
@MainActor
final class MyModelType: @MainActor Equatable {
var name: String
init(name: String) {
self.name = name
}
static func ==(lhs: MyModelType, rhs: MyModelType) -> Bool {
lhs.name == rhs.name
}
}
func isEqual<T: Equatable>(_ a: T, _ b: T) -> Bool { a == b }
@MainActor
func compare() async {
let a = MyModelType(name: "a")
let b = MyModelType(name: "a")
print(isEqual(a, b))
let r = await Task.detached { isEqual(a, b) }.value
print(r)
}
1
2
3
4
5
6
7
8
9
10
ExplicitDetached.swift:21:33: error: main actor-isolated conformance of 'MyModelType' to 'Equatable' cannot be used in @concurrent context [#IsolatedConformances]
19 | let b = MyModelType(name: "a")
20 | print(isEqual(a, b))
21 | let r = await Task.detached { isEqual(a, b) }.value
| `- error: main actor-isolated conformance of 'MyModelType' to 'Equatable' cannot be used in @concurrent context [#IsolatedConformances]
22 | print(r)
23 | }
[#IsolatedConformances]: <https://docs.swift.org/compiler/documentation/diagnostics/isolated-conformances>
[exit 1]
print(isEqual(a, b)) 는 main actor 함수 본문에서 부르는 것이라 통과하고, Task.detached 클로저 안의 isEqual(a, b) 는 21:33 에서 막힌다. 오류 문장의 컨텍스트 이름이 nonisolated 가 아니라 @concurrent 로 바뀐 것을 볼 수 있다. Task.detached 의 클로저는 어떤 actor 에도 묶이지 않고 동시에 실행되는 컨텍스트이기 때문이다. SE-0461 글에서 본 @concurrent 와 같은 낱말이다.
마지막으로 @MainActor 타입이 아닌 곳에서도 이 철자를 쓸 수 있는지 본다. 제안서는 actor 나 struct 도 @MainActor conformance 를 가질 수 있다고 쓴다.
OtherIsolation.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
protocol P {
func f()
}
actor MyActor: @MainActor P {
nonisolated func f() {}
}
struct MyStruct: @MainActor P {
@MainActor func f() {}
}
struct Plain: @MainActor P {
func f() {}
}
actor BadActor: @MainActor P {
func f() {}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
OtherIsolation.swift:17:28: error: conformance of 'BadActor' to protocol 'P' involves isolation mismatches and can cause data races [#ConformanceIsolation]
15 | }
16 |
17 | actor BadActor: @MainActor P {
| `- error: conformance of 'BadActor' to protocol 'P' involves isolation mismatches and can cause data races [#ConformanceIsolation]
18 | func f() {}
| |- note: actor-isolated instance method 'f()' cannot satisfy nonisolated requirement
| `- note: mark instance method 'f()' 'nonisolated'
19 | }
20 |
[#ConformanceIsolation]: <https://docs.swift.org/compiler/documentation/diagnostics/conformance-isolation>
[exit 1]
MyActor, MyStruct, Plain 은 통과하고, 오류는 BadActor 하나다. 네 타입을 비교하면 규칙이 보인다.
MyActor: actor 타입이다. witnessf()가nonisolated라서 요구사항(nonisolated)과 isolation 이 맞는다MyStruct:@MainActorconformance 이고 witness 도@MainActor다. conformance 가 main actor 에 묶여 있으니 main actor 의 witness 가 요구사항을 채운다Plain: witness 에 아무것도 안 붙었다. 이 witness 는nonisolated로 남고 conformance 만@MainActor다. 요구사항도nonisolated이니 isolation 이 맞는다BadActor:f()가 actor 자기 자신의 isolation 을 가진다. conformance 는 main actor 에 묶여 있는데 witness 는BadActor인스턴스에 묶여 있으니 둘이 맞지 않고, 컴파일러가nonisolated로 빼라는 note 를 낸다
Plain 의 witness 가 정말 nonisolated 로 남는지는 변형 파일로 확인한다. nonisolated 함수에서 witness f() 를 직접 부른다.
PlainWitness.swift
1
2
3
4
5
6
7
8
9
10
11
protocol P {
func f()
}
struct Plain: @MainActor P {
func f() {}
}
nonisolated func callDirect(_ p: Plain) {
p.f()
}
1
[exit 0]
진단이 없고 종료 코드는 0 이다. -print-ast 로 보면 f() 에는 isolation 표시가 없다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
internal protocol P {
func f()
}
internal struct Plain : @MainActor P {
internal func f() {
}
internal init() {
}
}
nonisolated internal func callDirect(_ p: Plain) {
p.f()
}
@MainActor P 는 conformance 에만 붙고(Plain : @MainActor P), f() 는 internal func f() { 그대로다. conformance 의 isolation 과 witness 의 isolation 은 별개라서, witness 가 conformance 의 isolation 을 물려받지는 않는다.
BadActor 가 막히는 이유가 제안서 Future Directions 의 주제다. 요구사항이 actor 인스턴스의 isolation 에 묶인 conformance(isolated P)는 “어느 인스턴스인지” 를 conformance 가 들고 다녀야 해서 data flow 분석이 필요하고, 이번 제안에서는 다루지 않는다.
데이터 레이스가 생기는 길
isolated conformance 를 도입하면 새로 열리는 data race 의 길이 있다. 제안서는 이 길을 Data-race safety issues 절에서 정리한다. 요지는 이렇다. conformance 는 값처럼 여기저기 넘겨진다. 제네릭 함수로 넘어가기도 하고, any P 속에 들어가기도 하고, key path 에 담기기도 한다. 그렇게 넘겨진 conformance 가 main actor 밖에서 호출되면 data race 가 난다. 그래서 제안은 conformance 가 새어 나가는 길마다 규칙을 하나씩 둔다.
맨 왼쪽 상자가 @MainActor conformance 를 가진 타입이고, 오른쪽으로 갈수록 conformance 가 main actor 에서 멀어진다. 타입을 제네릭 함수에 넘기고, 그 함수가 값을 Task.detached 같은 곳으로 main 밖에 보내고, 마지막에 main 밖에서 실제로 호출하는 길이다. main actor 안에서 제네릭 함수에 넘기는 것 자체는 막히지 않는다. 규칙 표지는 이음선마다 하나씩 붙어서, 길을 따라 Rule 2, Rule 3, Rule 1 순서다. 이 글은 번호 순서(Rule 1 부터 3)로 6.4 컴파일러로 확인한다. 세 규칙의 정확한 문구는 이렇다.
- Rule 1: isolated conformance 는 그 isolation 과 같은 도메인 안에서만 쓸 수 있다.
nonisolated와@concurrent컨텍스트, 다른 actor 에서는 쓸 수 없다 - Rule 2:
Sendable이나SendableMetatype제약이 붙은 제네릭 타입 매개변수에는 isolated conformance 를 쓸 수 없다. 제약이 붙은 자리는 “다른 isolation 으로 보낼 수 있는 값” 을 받겠다는 뜻이기 때문이다 - Rule 3: isolated conformance 에 기대는 값은 그 conformance 의 global actor region 에 속한다. 그래서
sending으로 다른 isolation 에 넘길 수 없다
Rule 1 isolation 도메인 안에서의 사용
Rule 1 은 가장 직관적이다. main actor 의 conformance 는 main actor 에서만 쓴다. 제안서의 예제를 그대로 옮긴 파일이다.
Rule1.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
protocol P {
func f()
}
struct S: @MainActor P {
func f() {}
}
struct WrapsP<T: P>: P {
var value: T
init(_ value: T) { self.value = value }
func f() { value.f() }
}
func badFunc() -> WrapsP<S> { WrapsP(S()) }
func badFunc2() -> any P {
S()
}
func acceptsP<T: P>(_ value: T) { }
func badFunc3() {
acceptsP(S())
}
@MainActor func goodFunc() -> any P {
S()
}
protocol P2 {
associatedtype A: P
}
struct S2: P2 {
typealias A = S
}
struct S: @MainActor P 의 conformance 가 여러 자리에서 어떻게 쓰이는지 본다. WrapsP<T: P> 는 제네릭 wrapper 이고, badFunc, badFunc2, badFunc3 은 각각 wrapper 를 만들고, any P 로 지우고, 제네릭 함수에 넘긴다. goodFunc 는 @MainActor 함수다. 마지막 P2 와 S2 는 associated type 이 S: P 를 요구하고 S2 가 A = S 로 채우는 구조다.
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
Rule1.swift:35:12: error: conformance of 'S2' to protocol 'P2' crosses into main actor-isolated code and can cause data races [#ConformanceIsolation]
33 | }
34 |
35 | struct S2: P2 {
| | |- error: conformance of 'S2' to protocol 'P2' crosses into main actor-isolated code and can cause data races [#ConformanceIsolation]
| | `- note: isolate this conformance to the main actor with '@MainActor'
| `- note: conformance depends on main actor-isolated conformance of 'S' to protocol 'P'
36 | typealias A = S
37 | }
Rule1.swift:15:31: error: main actor-isolated conformance of 'S' to 'P' cannot be used in nonisolated context [#IsolatedConformances]
13 | }
14 |
15 | func badFunc() -> WrapsP<S> { WrapsP(S()) }
| `- error: main actor-isolated conformance of 'S' to 'P' cannot be used in nonisolated context [#IsolatedConformances]
16 |
17 | func badFunc2() -> any P {
Rule1.swift:18:3: error: main actor-isolated conformance of 'S' to 'P' cannot be used in nonisolated context [#IsolatedConformances]
16 |
17 | func badFunc2() -> any P {
18 | S()
| `- error: main actor-isolated conformance of 'S' to 'P' cannot be used in nonisolated context [#IsolatedConformances]
19 | }
20 |
Rule1.swift:24:3: error: main actor-isolated conformance of 'S' to 'P' cannot be used in nonisolated context [#IsolatedConformances]
22 |
23 | func badFunc3() {
24 | acceptsP(S())
| `- error: main actor-isolated conformance of 'S' to 'P' cannot be used in nonisolated context [#IsolatedConformances]
25 | }
26 |
[#ConformanceIsolation]: <https://docs.swift.org/compiler/documentation/diagnostics/conformance-isolation>
[#IsolatedConformances]: <https://docs.swift.org/compiler/documentation/diagnostics/isolated-conformances>
[exit 1]
진단은 네 개이고 순서가 소스 순이 아니다. 컴파일러가 conformance 선언 쪽 진단(ConformanceIsolation)을 먼저 내고 사용 쪽 진단(IsolatedConformances)을 낸다.
- 35:12
S2: P2:S2의 conformance 가S의 main actor conformance 에 기댄다.S2도@MainActor로 isolate 하라는 note 가 달린다. associated type 으로 conformance 가 전파되는 경로다 - 15:31
badFunc: 시그니처가 아니라 본문의WrapsP(S())에서 난다 - 18:3
badFunc2:S()를any P로 돌려주는 자리 - 24:3
badFunc3:acceptsP(S())의 제네릭 인자
goodFunc 는 진단이 없다. 첫 번째 진단의 note 두 줄이 흥미롭다. “이 conformance 도 main actor 로 isolate 하라” 는 note 는 이 제안의 철자가 해법으로 다시 나온 것이고, “conformance 가 S 의 main actor conformance 에 의존한다” 는 note 는 컴파일러가 의존 관계를 추적한다는 뜻이다.
any P로 conformance 를 값에 담아 넘기기
any P 는 existential 타입이다. S 값을 any P 로 감싸면 S: P conformance 도 같이 박스 안에 들어가서, 박스를 받은 쪽이 그 conformance 를 쓰게 된다. @MainActor func goodFunc() -> any P 처럼 함수에 붙이는 @MainActor 는 함수 본문을 main actor isolation 으로 돌리므로, 이 안에서는 main actor conformance 를 쓸 수 있다.
key path 에서도 같은 규칙이 적용되는지 본다. key path 는 요구사항 name 을 프로토콜 요구사항으로 가리키므로 conformance 를 쓴다.
Rule1KeyPath.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
protocol HasName {
var name: String { get }
}
@MainActor final class Named: @MainActor HasName {
var name: String = "n"
}
@MainActor
func useName() {
let named = Named()
Task.detached {
_ = named[keyPath: \HasName.name]
}
}
keyPath 서브스크립트로 key path 가 가리키는 값 읽기
value[keyPath: \T.name] 은 KeyPath 가 가리키는 속성을 값에서 읽는 서브스크립트다. \HasName.name 처럼 프로토콜 요구사항을 가리키는 key path 는 읽을 때 그 프로토콜의 conformance 로 name 을 찾아간다.
1
2
3
4
5
6
7
8
9
10
Rule1KeyPath.swift:13:9: error: main actor-isolated conformance of 'Named' to 'HasName' cannot be used in @concurrent context [#IsolatedConformances]
11 | let named = Named()
12 | Task.detached {
13 | _ = named[keyPath: \HasName.name]
| `- error: main actor-isolated conformance of 'Named' to 'HasName' cannot be used in @concurrent context [#IsolatedConformances]
14 | }
15 | }
[#IsolatedConformances]: <https://docs.swift.org/compiler/documentation/diagnostics/isolated-conformances>
[exit 1]
named[keyPath: \HasName.name] 의 13:9 에서 막힌다. Task.detached 클로저 안이라 @concurrent 컨텍스트이고, \HasName.name 이 HasName 요구사항을 가리키는 key path 라서 conformance 를 쓴다. SE-0418 글이 다룬 key path 의 Sendable 추론과는 별개의 길이지만, key path 도 conformance 를 들고 있다는 점은 같은 맥락이다.
앞에서 지나간 contains 경로로 돌아온다. Explicit 파일에서 hasMatching 은 진단이 없었다. 비슷한 경로를 몇 가지 더 모았다.
Contains.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
@MainActor
class MyModelType: @MainActor Equatable {
var name: String
init(name: String) { self.name = name }
static func ==(lhs: MyModelType, rhs: MyModelType) -> Bool { lhs.name == rhs.name }
}
func whereClause<S: Sequence>(_ s: S, _ e: S.Element) -> Bool where S.Element: Equatable {
s.contains(e)
}
struct Box<T> { var value: T }
extension Box where T: Equatable {
func same(_ other: T) -> Bool { value == other }
}
nonisolated func viaWhere(_ value: MyModelType, in modelValues: [MyModelType]) -> Bool {
whereClause(modelValues, value)
}
nonisolated func viaExtension(_ box: Box<MyModelType>, _ v: MyModelType) -> Bool {
box.same(v)
}
nonisolated func viaContains(_ value: MyModelType, in modelValues: [MyModelType]) -> Bool {
modelValues.contains(value)
}
1
2
3
4
5
6
7
8
9
10
Contains.swift:22:7: error: main actor-isolated conformance of 'MyModelType' to 'Equatable' cannot be used in nonisolated context [#IsolatedConformances]
20 |
21 | nonisolated func viaExtension(_ box: Box<MyModelType>, _ v: MyModelType) -> Bool {
22 | box.same(v)
| `- error: main actor-isolated conformance of 'MyModelType' to 'Equatable' cannot be used in nonisolated context [#IsolatedConformances]
23 | }
24 |
[#IsolatedConformances]: <https://docs.swift.org/compiler/documentation/diagnostics/isolated-conformances>
[exit 1]
whereClause 는 where S.Element: Equatable 제약 속에서 contains 를 부르고, viaWhere 가 거기에 MyModelType 을 넘긴다. Box 의 extension Box where T: Equatable 는 viaExtension 이 부른다. viaContains 는 Array.contains 를 바로 부른다. 오류는 하나이고 22:7 의 box.same(v) 다. extension 의 where T: Equatable 제약은 conformance 를 직접 받는 자리라서 막히지만, whereClause 와 Array.contains 는 associated type Element 를 거치는 제약이라 6.4 컴파일러가 이 경로에서는 오류를 내지 않는다.
그렇다면 그 경로에서 실제로 무슨 일이 일어나는지 실행해 본다. == 가 불릴 때 어느 스레드에서 도는지 출력하게 했다.
ContainsRun.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
import Foundation
@MainActor
final class MyModelType: @MainActor Equatable {
var name: String
init(name: String) { self.name = name }
static func ==(lhs: MyModelType, rhs: MyModelType) -> Bool {
print("==", Thread.isMainThread ? "main" : "not main")
return lhs.name == rhs.name
}
}
nonisolated func viaContains(_ value: MyModelType, in modelValues: [MyModelType]) -> Bool {
modelValues.contains(value)
}
@main
struct Program {
static func main() async {
let a = MyModelType(name: "a")
let list = [MyModelType(name: "b"), a]
print("main:", viaContains(a, in: list))
let r = await Task.detached { viaContains(a, in: list) }.value
print("detached:", r)
}
}
실행 파일은 xcrun swiftc -parse-as-library -swift-version 6 ContainsRun.swift -o ~/se470/containsrun 으로 만들었다.
Thread.isMainThread로 현재 스레드 확인하기
Thread.isMainThread 는 지금 코드가 main 스레드에서 돌고 있으면 true 인 Foundation 의 타입 속성이다. 위 코드는 == 가 불릴 때마다 그 값을 찍어서, == 가 어느 스레드에서 도는지 출력으로 보이게 한다.
1
2
3
4
5
6
7
== main
== main
main: true
== not main
== not main
detached: true
[exit 0]
처음 print("main:", ...) 는 main 에서 == 가 두 번 돌고 결과 true 다. 두 번째 Task.detached 안의 viaContains 는 == not main 을 두 번 찍고 detached: true 를 낸다. 6.4 에서는 이 경로가 진단 없이 main 밖에서 돈다. 컴파일러가 막는 경로와 막지 않는 경로가 같은 파일 안에 같이 있는 것이다.
Rule 2 Sendable 제약과 isolated conformance
Rule 1 은 “쓰는 곳” 을 막는다. 그런데 제네릭 함수 안에서는 쓰는 곳이 호출자 쪽에서 정해지지 않는다. 제네릭 함수가 conformance 를 받아서 Task.detached 같은 데로 보내 버리면 어떻게 될까. 이 질문이 Rule 2 다. 먼저 제안서의 예다.
Rule2Generic.swift
1
2
3
4
5
6
7
8
9
protocol Q {
static func g()
}
nonisolated func callQGElsewhere<T: Q>(_: T.Type) {
Task.detached {
T.g()
}
}
callQGElsewhere<T: Q> 는 T 의 타입 객체를 받고, Task.detached 클로저에서 T.g() 를 부른다. T.g() 는 Q conformance 의 정적 요구사항을 부르므로 conformance 가 클로저로 건너간다. 만약 호출자가 T 에 @MainActor conformance 를 넘기면, 클로저가 main actor 밖에서 그 conformance 의 g() 를 부르게 된다.
1
2
3
4
5
6
7
8
9
10
Rule2Generic.swift:7:5: warning: capture of non-Sendable type 'T.Type' in an isolated closure [#SendableMetatypes]
5 | nonisolated func callQGElsewhere<T: Q>(_: T.Type) {
6 | Task.detached {
7 | T.g()
| `- warning: capture of non-Sendable type 'T.Type' in an isolated closure [#SendableMetatypes]
8 | }
9 | }
[#SendableMetatypes]: <https://docs.swift.org/compiler/documentation/diagnostics/sendable-metatypes>
[exit 0]
오류가 아니라 warning 이다. 종료 코드는 0 이다. 진단 문구는 “T.Type 이라는 non-Sendable 타입을 isolated closure 에서 캡처했다” 다. 컴파일러는 T.Type(제네릭 T 의 타입 객체)이 다른 isolation 으로 건너갈 수 없다고 본다. 모드별로 돌려 본다.
1
2
3
4
5
=== Rule2Generic.swift [-swift-version 5]
=== Rule2Generic.swift [-swift-version 5 -strict-concurrency=complete]
Rule2Generic.swift:7:5: warning: capture of non-Sendable type 'T.Type' in an isolated closure; this is an error in the Swift 6 language mode [#SendableMetatypes]
=== Rule2Generic.swift [-swift-version 6]
Rule2Generic.swift:7:5: warning: capture of non-Sendable type 'T.Type' in an isolated closure [#SendableMetatypes]
Swift 5 기본은 아무것도 없다. strict concurrency 를 complete 로 올린 5 는 warning 에 “Swift 6 언어 모드에서는 오류” 를 붙이고, Swift 6 은 warning 이다. 6.4 컴파일러에서 이 모양은 Swift 6 모드에서도 warning 으로 나온다.
SendableMetatype이란?
이 warning 의 열쇠는 T.Type 이 Sendable 하지 않다는 사실이다. T.Type 은 제네릭 타입 T 의 타입 값이다. 값이 다른 isolation 으로 건너가도 되는지는 그 타입이 Sendable 이냐로 정해진다. 그런데 metatype(T.Type)은 conformance 를 들고 있으므로, 건너가도 안전한지는 “conformance 가 isolated 인가” 에 달려 있다.
SendableMetatype 는 이 질문의 답을 표시하는 marker protocol 이다. 규칙은 이렇다.
T: SendableMetatype이면T.Type은Sendable이다. metatype 을 다른 isolation 으로 보내도 된다는 뜻이다Sendable은SendableMetatype을 상속한다. 그래서T: Sendable도T.Type을 보낼 수 있다- 구체 타입은 모두 암묵적으로
SendableMetatype이다. isolated conformance 가 아닌 한T.Type을 보내도 안전하기 때문이다 - 그 대신
T: SendableMetatype자리에는 isolated conformance 를 가진 타입을 넣을 수 없다. isolated conformance 를 가진 metatype 은 보낼 수 없기 때문이다
리뷰 중에 이 규칙의 모양이 바뀌었다. 제안서 Revision History 에 따르면 리뷰에 올라온 초안은 제네릭 함수 안에서 구체적인 conformance 를 isolated 일 수 있는 것으로 따지는 모델이었다. 리뷰에서 “제네릭 매개변수의 metatype 이 Sendable 한가” 를 기준으로 삼는 모델로 바꿨고, 이 모델은 이전 초안에서 쓰던 것으로 되돌아간 것이다(리뷰 #13 Doug, PR #2763). 이 글의 진단 문구가 T.Type 의 non-Sendable 을 말하는 것이 그 결과다. 제네릭 함수 안에서 Task.detached 가 T.g() 를 캡처하면, 컴파일러는 T.Type 이 Sendable 인지로 판단한다.
그러면 callQGElsewhere 를 어떻게 고치는가. 제안서의 답은 T: Q & SendableMetatype 으로 제약을 명시하는 것이다. 그러면 함수 안에서는 T.Type 이 Sendable 이 되고, 호출자는 isolated conformance 를 가진 타입을 넘길 수 없게 된다.
Rule2Fixed.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
protocol Q {
static func g()
}
nonisolated func callQGElsewhere<T: Q & SendableMetatype>(_: T.Type) {
Task.detached {
T.g()
}
}
struct MyTypeThatConformsToQ: Q {
static func g() {}
}
func use() {
callQGElsewhere(MyTypeThatConformsToQ.self)
}
@MainActor final class C: @MainActor Q {
static func g() {}
}
@MainActor func isolationWithStatics() {
callQGElsewhere(C.self)
}
callQGElsewhere<T: Q & SendableMetatype> 으로 바꿨다. 구체 타입 MyTypeThatConformsToQ 는 일반 conformance 라서 use() 에서 문제없이 넘어간다. C 는 @MainActor Q 이고, isolationWithStatics 가 callQGElsewhere(C.self) 를 부른다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Rule2Fixed.swift:24:3: error: main actor-isolated conformance of 'C' to 'Q' cannot satisfy conformance requirement for a 'Sendable' type parameter [#IsolatedConformances]
3 | }
4 |
5 | nonisolated func callQGElsewhere<T: Q & SendableMetatype>(_: T.Type) {
| `- note: 'callQGElsewhere' declared here
6 | Task.detached {
7 | T.g()
:
22 |
23 | @MainActor func isolationWithStatics() {
24 | callQGElsewhere(C.self)
| `- error: main actor-isolated conformance of 'C' to 'Q' cannot satisfy conformance requirement for a 'Sendable' type parameter [#IsolatedConformances]
25 | }
26 |
[#IsolatedConformances]: <https://docs.swift.org/compiler/documentation/diagnostics/isolated-conformances>
[exit 1]
함수 쪽(callQGElsewhere)은 통과하고, 호출 쪽(24:3)에서 막힌다. 진단 문장이 흥미롭다. “isolated conformance 는 'Sendable' 타입 매개변수의 요구사항을 만족시킬 수 없다” 라고 말한다. 우리가 적은 제약은 SendableMetatype 인데 문구에는 Sendable 이 나온다. Sendable 이 SendableMetatype 을 상속하기 때문에 같은 진단으로 묶여 있는 것이다. 문장의 Sendable 뒤에 공백이 두 칸인 것도 컴파일러가 낸 그대로다.
호출자 쪽 규칙을 따로 모은 파일이다. 제안서가 호출자 쪽 예로 든 모양이다.
Rule2Caller.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
protocol P {
func f()
}
struct S: @MainActor P {
func f() {}
}
func acceptsP<T: P>(_ value: T) { }
func acceptsSendableMetatypeP<T: SendableMetatype & P>(_ value: T) { }
func acceptsAny<T>(_ value: T) { }
func acceptsSendableMetatype<T: SendableMetatype>(_ value: T) { }
@MainActor func passIsolated(s: S) {
acceptsP(s)
acceptsSendableMetatypeP(s)
acceptsAny(s)
acceptsSendableMetatype(s)
}
@MainActor func isolatedAnyGood(s: S) {
let a: any P = s
_ = a
}
@MainActor func isolatedAnyBad(s: S) {
let a: any SendableMetatype & P = s
_ = a
}
@MainActor func returnIsolatedSomeGood(s: S) -> some P {
return s
}
@MainActor func returnIsolatedSomeBad(s: S) -> some SendableMetatype & P {
return s
}
S: @MainActor P 에 대해 acceptsP(제약 P만), acceptsSendableMetatypeP(SendableMetatype & P), acceptsAny(제약 없음), acceptsSendableMetatype(SendableMetatype 만)를 각각 부른다. 마지막 네 함수는 any P 와 some P 로 지우는 길이다. isolatedAnyGood 은 any P, isolatedAnyBad 는 any SendableMetatype & P, returnIsolatedSomeGood 은 some P, returnIsolatedSomeBad 는 some SendableMetatype & P 다.
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
Rule2Caller.swift:16:3: error: main actor-isolated conformance of 'S' to 'P' cannot satisfy conformance requirement for a 'Sendable' type parameter [#IsolatedConformances]
8 |
9 | func acceptsP<T: P>(_ value: T) { }
10 | func acceptsSendableMetatypeP<T: SendableMetatype & P>(_ value: T) { }
| `- note: 'acceptsSendableMetatypeP' declared here
11 | func acceptsAny<T>(_ value: T) { }
12 | func acceptsSendableMetatype<T: SendableMetatype>(_ value: T) { }
:
14 | @MainActor func passIsolated(s: S) {
15 | acceptsP(s)
16 | acceptsSendableMetatypeP(s)
| `- error: main actor-isolated conformance of 'S' to 'P' cannot satisfy conformance requirement for a 'Sendable' type parameter [#IsolatedConformances]
17 | acceptsAny(s)
18 | acceptsSendableMetatype(s)
Rule2Caller.swift:36:10: error: main actor-isolated conformance of 'S' to 'P' cannot satisfy conformance requirement for a 'Sendable' type parameter [#IsolatedConformances]
33 | }
34 |
35 | @MainActor func returnIsolatedSomeBad(s: S) -> some SendableMetatype & P {
| `- note: 's' declared here
36 | return s
| `- error: main actor-isolated conformance of 'S' to 'P' cannot satisfy conformance requirement for a 'Sendable' type parameter [#IsolatedConformances]
37 | }
38 |
[#IsolatedConformances]: <https://docs.swift.org/compiler/documentation/diagnostics/isolated-conformances>
[exit 1]
오류는 둘이다. 16:3 은 acceptsSendableMetatypeP(s) 이고, 36:10 은 some SendableMetatype & P 를 돌려주는 return s 다. 18:3 acceptsSendableMetatype(s) 는 conformance 가 없는 타입 인자를 쓰는 것이라 통과한다. acceptsP, acceptsAny, any P, some P 도 통과한다. 반면 let a: any SendableMetatype & P = s(isolatedAnyBad)는 진단이 없다. 제약이 some 이면 막히고 any 이면 막히지 않는 것이 6.4 의 측정 결과다.
제안서가 Rule 2 를 설명하며 보여 주는 활용 예가 병렬 contains 다. Equatable & Sendable 제약을 건 parallelContains 는 각 원소를 다른 isolation 으로 보낼 수 있다는 약속이므로, isolated conformance 가 거기 들어가면 안 된다.
Parallel.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@MainActor
final class MyModelType: @MainActor Equatable, Sendable {
let name: String
init(name: String) { self.name = name }
static func ==(lhs: MyModelType, rhs: MyModelType) -> Bool { lhs.name == rhs.name }
}
extension Sequence {
func parallelContains(_ element: Element) -> Bool where Element: Equatable & Sendable {
contains(element)
}
}
@MainActor
func parallelHasMatching(_ value: MyModelType, in modelValues: [MyModelType]) -> Bool {
modelValues.parallelContains(value)
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Parallel.swift:16:15: error: main actor-isolated conformance of 'MyModelType' to 'Equatable' cannot satisfy conformance requirement for a 'Sendable' type parameter [#IsolatedConformances]
7 |
8 | extension Sequence {
9 | func parallelContains(_ element: Element) -> Bool where Element: Equatable & Sendable {
| `- note: 'parallelContains' declared here
10 | contains(element)
11 | }
:
14 | @MainActor
15 | func parallelHasMatching(_ value: MyModelType, in modelValues: [MyModelType]) -> Bool {
16 | modelValues.parallelContains(value)
| `- error: main actor-isolated conformance of 'MyModelType' to 'Equatable' cannot satisfy conformance requirement for a 'Sendable' type parameter [#IsolatedConformances]
17 | }
18 |
[#IsolatedConformances]: <https://docs.swift.org/compiler/documentation/diagnostics/isolated-conformances>
[exit 1]
MyModelType 은 Equatable 과 Sendable 둘 다 따르고, parallelHasMatching 은 @MainActor 함수다. main actor 안에서 부르는데도 16:15 에서 막힌다. 호출 자리가 main actor 인 것은 상관이 없고, parallelContains 가 Element: Equatable & Sendable 을 요구한다는 것이 이유다. 함수 본문이 정말 병렬 실행을 하지 않더라도, 시그니처가 약속하는 것이 “다른 isolation 으로 보내도 된다” 라서 컴파일러는 막는다.
이 절에서 Rule 2 가 막는 길은 제네릭 제약이다. 이제 제네릭 제약이 아닌 경로를 본다. any Sendable & P 로 지우는 경로다.
AnyBad.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
protocol P {
func f()
}
struct S: @MainActor P {
func f() {}
}
@MainActor func isolatedAnyBad(s: S) {
let a: any SendableMetatype & P = s
_ = a
}
@MainActor func isolatedAnySendable(s: S) {
let a: any Sendable & P = s
Task.detached { a.f() }
}
1
[exit 0]
let a: any SendableMetatype & P = s 도, any Sendable & P 로 지운 값을 Task.detached 안에서 쓰는 것도 진단이 없다. 이 any Sendable & P 값이 정말 main 밖에서 어떻게 도는지 실행한다.
AnyBadRun.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import Foundation
protocol P { func f() }
struct S: @MainActor P {
func f() { print("f", Thread.isMainThread ? "main" : "not main") }
}
@MainActor func make(s: S) -> any Sendable & P {
let a: any Sendable & P = s
return a
}
@main struct Program {
static func main() async {
let a = await make(s: S())
await Task.detached { a.f() }.value
}
}
xcrun swiftc -parse-as-library -swift-version 6 AnyBadRun.swift -o ~/se470/anybadrun 으로 빌드했다. 빌드할 때 나온 warning 은 await make(s: S()) 에 대한 것이다. make 가 @MainActor 함수라서 await 가 필요 없는 자리가 있다는 뜻이고 이 글의 주제와는 무관하다.
1
2
f not main
[exit 0]
f not main 이다. S 의 @MainActor conformance 로 만든 any Sendable & P 를 Task.detached 가 받아서 f() 를 main 밖에서 불렀다. 6.4 에서 any Sendable & P 로 지우는 경로는 컴파일러의 진단 없이 이렇게 돈다. 클래스 인스턴스에 같은 경로를 쓰면 어떻게 되는지도 본다.
BadReturn.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import Foundation
protocol P {
func f()
}
@MainActor
final class C: @MainActor P {
var count = 0
func f() {
count += 1
print("f", Thread.isMainThread ? "main" : "not main")
}
}
@MainActor func badReturn(c: C) -> any Sendable & P {
c
}
@MainActor func sendMe<T: Sendable & P>(_ value: T) {
Task.detached {
value.f()
}
}
@MainActor func doSend(c: C) {
sendMe(c)
}
badReturn(c:) 는 C 를 any Sendable & P 로 돌려주고, sendMe 와 doSend 는 제네릭 제약 쪽이다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
BadReturn.swift:27:3: error: main actor-isolated conformance of 'C' to 'P' cannot satisfy conformance requirement for a 'Sendable' type parameter [#IsolatedConformances]
18 | }
19 |
20 | @MainActor func sendMe<T: Sendable & P>(_ value: T) {
| `- note: 'sendMe' declared here
21 | Task.detached {
22 | value.f()
:
25 |
26 | @MainActor func doSend(c: C) {
27 | sendMe(c)
| `- error: main actor-isolated conformance of 'C' to 'P' cannot satisfy conformance requirement for a 'Sendable' type parameter [#IsolatedConformances]
28 | }
29 |
[#IsolatedConformances]: <https://docs.swift.org/compiler/documentation/diagnostics/isolated-conformances>
[exit 1]
badReturn 에는 진단이 없고, doSend 의 sendMe(c) 에서 27:3 오류가 난다. 같은 Sendable & P 라도 제네릭 매개변수 제약일 때는 막히고 존재 타입으로 돌려줄 때는 막히지 않는다. 이것이 Rule 2 의 6.4 범위다. 실행도 해 본다.
BadReturnRun.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
import Foundation
protocol P {
func f()
}
@MainActor
final class C: @MainActor P {
var count = 0
func f() {
count += 1
print("f", Thread.isMainThread ? "main" : "not main")
}
}
@MainActor func badReturn(c: C) -> any Sendable & P {
c
}
@main
struct Program {
static func main() async {
let anyP = badReturn(c: C())
await Task.detached {
anyP.f()
}.value
print("done")
}
}
xcrun swiftc -parse-as-library -swift-version 6 BadReturnRun.swift -o ~/se470/badreturnrun 으로 빌드한다.
1
2
3
f not main
done
[exit 0]
f not main 과 done 이 찍힌다. f() 는 count += 1 로 main actor 의 저장 속성을 고치는데 이 호출이 main 밖에서 돌았다. 정리하면 any Sendable & P 로 지우는 경로(앞의 AnyBadRun 과 이 BadReturnRun)는 6.4 에서 진단 없이 main 밖으로 나간다.
Rule 3 global actor 의 region
Rule 1 과 2 가 conformance 를 막는 규칙이라면, Rule 3 은 conformance 에 기대는 값을 막는다. any P 같은 존재 타입 값은 안에 conformance 를 들고 있으므로, 그 값을 다른 isolation 으로 보내면 conformance 도 같이 가 버린다. 그래서 Rule 3 은 이런 값을 global actor 의 region 에 묶는다. 값을 isolation 사이로 보낼 때 쓰는 sending 이 그 region 을 따진다(SE-0414 글과 SE-0430 글).
먼저 sending 이 main actor 의 callee 로 넘어가는 경우다.
Rule3.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
protocol P {
func f()
}
final class C: @MainActor P {
@MainActor func f() {}
}
struct WrapsP<T: P> {
var value: T
init(_ value: T) { self.value = value }
}
@MainActor func acceptSending(_ value: sending any P) { }
@MainActor func acceptSendingWrap(_ value: sending WrapsP<C>) { }
@MainActor func acceptSendingC(_ value: sending C) { }
@MainActor func passSending() {
let c1 = C()
let ap1: any P = c1
acceptSending(ap1)
let c2 = C()
let wp2 = WrapsP(c2)
acceptSendingWrap(wp2)
let c3 = C()
acceptSendingC(c3)
}
@MainActor func badSendingReturn() -> sending any P {
C()
}
1
[exit 0]
acceptSending, acceptSendingWrap, acceptSendingC 는 모두 @MainActor 함수라서 값이 main actor 에서 main actor 로 건너간다. 진단이 없다. 그런데 badSendingReturn() -> sending any P { C() } 에는 “main 에서 main 으로” 와는 다른 이유로 진단이 없다. 본문의 C() 는 이름 없이 새로 만든 값이라 새 region 에 놓이고, main actor 에 묶인 값이 아니기 때문이다. 이름을 붙이면 달라지는지 변형 파일로 본다.
BadSendRet.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
protocol P {
func f()
}
final class C: @MainActor P {
@MainActor func f() {}
}
@MainActor func badSendingReturn() -> sending any P {
C()
}
@MainActor func badSendingReturnNamed() -> sending any P {
let c: any P = C()
return c
}
nonisolated func caller() async {
let p = await badSendingReturn()
_ = p
}
1
2
3
4
5
6
7
8
9
10
11
BadSendRet.swift:15:10: error: returning main actor-isolated 'c' as a 'sending' result risks causing data races; 'c' is accessible to code in the current isolation context [#RegionIsolation]
13 | @MainActor func badSendingReturnNamed() -> sending any P {
14 | let c: any P = C()
15 | return c
| |- error: returning main actor-isolated 'c' as a 'sending' result risks causing data races; 'c' is accessible to code in the current isolation context [#RegionIsolation]
| `- note: returning main actor-isolated 'c' risks causing data races since the caller assumes that 'c' can be safely sent to other isolation domains, but 'c' is accessible to code in the current isolation context
16 | }
17 |
[#RegionIsolation]: <https://docs.swift.org/compiler/documentation/diagnostics/region-isolation>
[exit 1]
오류는 하나이고 15:10 의 return c 다. badSendingReturnNamed 는 let c: any P = C() 로 이름을 붙인 값을 돌려주는데, c 는 이 함수 안에서 계속 접근할 수 있는 main actor 의 값으로 취급되어 sending 결과가 될 수 없다는 문장이다. 이름 없는 C() 를 바로 돌려주는 badSendingReturn(9행)은 같은 파일 안에서 진단이 없다. 이 둘의 차이는 값에 이름이 있느냐다. region 이 문제가 되는 것은 callee 가 nonisolated 일 때다. callee 를 nonisolated 로 바꾼 두 파일이 있다. 먼저 기준선이 되는 non-Sendable 클래스를 함께 둔 쪽이다.
Rule3b.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
protocol P {
func f()
}
final class C: @MainActor P {
@MainActor func f() {}
}
final class NS {}
@MainActor var mainNS = NS()
func acceptSending(_ value: sending any P) { }
func acceptSendingNS(_ value: sending NS) { }
@MainActor func baseline() {
acceptSendingNS(mainNS)
}
@MainActor func passSending() {
let c1 = C()
let ap1: any P = c1
acceptSending(ap1)
}
@MainActor func useBadSendingReturn() {
let anyP: any P = C()
Task.detached {
_ = anyP
}
}
NS 는 isolated conformance 와 관계없는 평범한 non-Sendable 클래스이고, mainNS 는 @MainActor 전역 변수다. baseline() 은 mainNS 를 nonisolated callee 에 sending 으로 넘긴다. passSending() 은 C() 를 any P 로 지워서 acceptSending 에 넘기고, useBadSendingReturn() 은 any P 값을 Task.detached 가 캡처하게 한다.
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
Rule3b.swift:16:3: error: sending value of non-Sendable type 'NS' risks causing data races [#RegionIsolation::SendingRisksDataRace]
14 |
15 | @MainActor func baseline() {
16 | acceptSendingNS(mainNS)
| |- error: sending value of non-Sendable type 'NS' risks causing data races [#RegionIsolation::SendingRisksDataRace]
| `- note: Passing main actor-isolated value of non-Sendable type 'NS' as a 'sending' parameter to global function 'acceptSendingNS' risks causing races inbetween main actor-isolated uses and uses reachable from 'acceptSendingNS'
17 | }
18 |
Rule3b.swift:22:3: warning: sending 'ap1' risks causing data races [#RegionIsolation::SendingRisksDataRace]
19 | @MainActor func passSending() {
20 | let c1 = C()
21 | let ap1: any P = c1
| `- note: isolated conformance to protocol 'P' can be introduced here
22 | acceptSending(ap1)
| |- warning: sending 'ap1' risks causing data races [#RegionIsolation::SendingRisksDataRace]
| `- note: main actor-isolated 'ap1' is passed as a 'sending' parameter; Uses in callee may race with later main actor-isolated uses
23 | }
24 |
Rule3b.swift:27:8: error: passing closure as a 'sending' parameter risks causing data races between main actor-isolated code and concurrent execution of the closure [#RegionIsolation::SendingClosureRisksDataRace]
24 |
25 | @MainActor func useBadSendingReturn() {
26 | let anyP: any P = C()
| `- note: isolated conformance to protocol 'P' can be introduced here
27 | Task.detached {
| `- error: passing closure as a 'sending' parameter risks causing data races between main actor-isolated code and concurrent execution of the closure [#RegionIsolation::SendingClosureRisksDataRace]
28 | _ = anyP
| `- note: closure captures 'anyP' which is accessible to main actor-isolated code
29 | }
30 | }
[#RegionIsolation]: <https://docs.swift.org/compiler/documentation/diagnostics/region-isolation>
[#SendingClosureRisksDataRace]: <https://docs.swift.org/compiler/documentation/diagnostics/sending-closure-risks-data-race>
[#SendingRisksDataRace]: <https://docs.swift.org/compiler/documentation/diagnostics/sending-risks-data-race>
[exit 1]
세 진단이 이어진다.
- 16:3
baseline(): 오류. main actor 에 묶인 non-Sendable 값mainNS를sending으로 보낼 수 없다는 기준선 진단이다. isolated conformance 가 전혀 없어도 region 규칙은 이렇게 작동한다 - 22:3
passSending(): warning.ap1이 main actor 에 isolated 된 값이라sending으로 넘기는 것이 위험하다는 문장이다. 이 진단의 note 두 줄이 Rule 3 의 설명이다. 21 행의isolated conformance to protocol 'P' can be introduced here는 이 값이 main actor 에 묶이는 이유를 가리키고, 22 행의 note 는 callee 에서의 사용이 이후 main actor 에서의 사용과 race 할 수 있다고 말한다 - 27:8
Task.detached: 오류. 클로저가anyP를 캡처하는데anyP가 main actor 에서 접근 가능하다는 이유다. 역시isolated conformance to protocol 'P' can be introduced herenote 가 붙는다
기준선(16:3)과 22:3 은 문장이 비슷하지만 문구가 다르다. 16:3 은 sending value of non-Sendable type 'NS' 이고 22:3 은 sending 'ap1' 이다. 이 차이는 any P 가 non-Sendable 이냐에서 오는 것이 아니다(any P 도 non-Sendable 이다). 값에 이름이 있느냐에서 온다. mainNS 를 바로 넘기는 16:3 은 이름 없는 값이라 타입 이름이 문구에 나오고, 지역 변수 ap1 에 담아 넘기는 22:3 은 변수 이름이 나온다. 평범한 NS 도 지역 변수에 담으면 같은 문구가 되는지 변형 파일로 본다.
NamedNS.swift
1
2
3
4
5
6
7
8
9
final class NS {}
@MainActor var mainNS = NS()
func acceptSendingNS(_ value: sending NS) { }
@MainActor func namedLocal() {
let x = mainNS
acceptSendingNS(x)
}
1
2
3
4
5
6
7
8
9
10
11
12
NamedNS.swift:8:3: error: sending 'x' risks causing data races [#RegionIsolation::SendingRisksDataRace]
6 | @MainActor func namedLocal() {
7 | let x = mainNS
8 | acceptSendingNS(x)
| |- error: sending 'x' risks causing data races [#RegionIsolation::SendingRisksDataRace]
| `- note: main actor-isolated 'x' is passed as a 'sending' parameter; Uses in callee may race with later main actor-isolated uses
9 | }
10 |
[#RegionIsolation]: <https://docs.swift.org/compiler/documentation/diagnostics/region-isolation>
[#SendingRisksDataRace]: <https://docs.swift.org/compiler/documentation/diagnostics/sending-risks-data-race>
[exit 1]
let x = mainNS 로 이름을 붙이니 sending 'x' 로 8:3 에서 오류가 난다. 문구의 차이는 named 와 unnamed 의 차이다. 심각도는 다르다. 평범한 NS 는 오류이고, isolated conformance 가 값을 묶은 22:3 은 warning 이다. 반대쪽, 즉 callee 가 @MainActor 이면 이름이 있어도 진단이 없다.
MainToMain.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
final class NS {}
@MainActor var mainNS = NS()
@MainActor func acceptSendingNS(_ value: sending NS) { }
@MainActor func baselineMain() {
acceptSendingNS(mainNS)
}
@MainActor func namedMain() {
let x = mainNS
acceptSendingNS(x)
}
1
[exit 0]
종료 코드 0 이고 진단이 없다. 값이 main actor 에서 main actor 로 건너가는 것이라서 앞의 Rule3.swift 의 파라미터 쪽 결과와 같다. 이제 대조군이 있는 파일로 확인한다.
Rule3c.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
protocol P {
func f()
}
final class C: @MainActor P {
@MainActor func f() {}
}
final class D: P {
func f() {}
}
func acceptSending(_ value: sending any P) { }
@MainActor func passIsolated() {
let c1 = C()
let ap1: any P = c1
acceptSending(ap1)
}
@MainActor func passPlain() {
let d1 = D()
let ap1: any P = d1
acceptSending(ap1)
}
@MainActor func captureIsolated() {
let anyP: any P = C()
Task.detached {
_ = anyP
}
}
@MainActor func capturePlain() {
let anyP: any P = D()
Task.detached {
_ = anyP
}
}
@MainActor func captureUnerased() {
let c = C()
Task.detached {
_ = c
}
}
D 는 일반 P conformance 이고 C 는 @MainActor P 다. passIsolated 와 passPlain 은 any P 를 sending 으로 넘기고, captureIsolated 와 capturePlain 은 Task.detached 가 any P 를 캡처한다. captureUnerased 는 any P 로 지우지 않고 C 를 그대로 캡처한다.
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
Rule3c.swift:18:3: warning: sending 'ap1' risks causing data races [#RegionIsolation::SendingRisksDataRace]
15 | @MainActor func passIsolated() {
16 | let c1 = C()
17 | let ap1: any P = c1
| `- note: isolated conformance to protocol 'P' can be introduced here
18 | acceptSending(ap1)
| |- warning: sending 'ap1' risks causing data races [#RegionIsolation::SendingRisksDataRace]
| `- note: main actor-isolated 'ap1' is passed as a 'sending' parameter; Uses in callee may race with later main actor-isolated uses
19 | }
20 |
Rule3c.swift:29:8: error: passing closure as a 'sending' parameter risks causing data races between main actor-isolated code and concurrent execution of the closure [#RegionIsolation::SendingClosureRisksDataRace]
26 |
27 | @MainActor func captureIsolated() {
28 | let anyP: any P = C()
| `- note: isolated conformance to protocol 'P' can be introduced here
29 | Task.detached {
| `- error: passing closure as a 'sending' parameter risks causing data races between main actor-isolated code and concurrent execution of the closure [#RegionIsolation::SendingClosureRisksDataRace]
30 | _ = anyP
| `- note: closure captures 'anyP' which is accessible to main actor-isolated code
31 | }
32 | }
[#RegionIsolation]: <https://docs.swift.org/compiler/documentation/diagnostics/region-isolation>
[#SendingClosureRisksDataRace]: <https://docs.swift.org/compiler/documentation/diagnostics/sending-closure-risks-data-race>
[#SendingRisksDataRace]: <https://docs.swift.org/compiler/documentation/diagnostics/sending-risks-data-race>
[exit 1]
진단은 두 개뿐이다. passIsolated 의 18:3 은 warning, captureIsolated 의 29:8 은 오류다. 대조군(passPlain, capturePlain, captureUnerased)에는 진단이 없다. captureUnerased 는 C 를 지우지 않은 채 캡처하는데 C 의 conformance 를 쓰지 않으니, C 자신이 non-Sendable 클래스여도 이 파일에서는 진단 대상이 아니다. any P 로 지우는 순간 conformance 가 값에 따라붙어서 region 이 정해진다.
세 모드의 차이도 본다.
1
2
3
4
5
6
7
=== Rule3c.swift [-swift-version 5]
=== Rule3c.swift [-swift-version 5 -strict-concurrency=complete]
Rule3c.swift:18:3: warning: sending 'ap1' risks causing data races; this is an error in the Swift 6 language mode [#RegionIsolation::SendingRisksDataRace]
Rule3c.swift:29:8: warning: passing closure as a 'sending' parameter risks causing data races between main actor-isolated code and concurrent execution of the closure; this is an error in the Swift 6 language mode [#RegionIsolation::SendingClosureRisksDataRace]
=== Rule3c.swift [-swift-version 6]
Rule3c.swift:18:3: warning: sending 'ap1' risks causing data races [#RegionIsolation::SendingRisksDataRace]
Rule3c.swift:29:8: error: passing closure as a 'sending' parameter risks causing data races between main actor-isolated code and concurrent execution of the closure [#RegionIsolation::SendingClosureRisksDataRace]
Swift 5 기본은 진단이 없고, strict concurrency complete 에서는 둘 다 warning 이고 “Swift 6 에서 오류” 가 붙는다. Swift 6 에서는 18:3 은 여전히 warning 이고 29:8 이 오류가 된다. sending 인자로 넘기는 쪽(18:3)이 warning 인 것은 6.4 의 측정 결과다.
동적 캐스트
conformance 가 값에 따라붙으면 as? 같은 동적 캐스트도 영향을 받는다. value as? any P 는 런타임에 value 의 타입이 P 를 따르는지 찾아본다. 이때 P conformance 가 isolated 이면 호출한 곳의 isolation 이 맞아야 쓸 수 있다. 제안서는 “캐스트가 지금 실행 중인 executor 를 확인해서 isolated conformance 를 쓸 수 있을 때만 성공한다” 고 쓴다.
DynamicCast.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import Foundation
protocol P {
func f()
}
@MainActor
final class C: @MainActor P {
func f() { print(" f() on", Thread.isMainThread ? "main" : "not main") }
}
final class D: P, Sendable {
func f() { print(" f() on", Thread.isMainThread ? "main" : "not main") }
}
nonisolated func tryP(_ label: String, _ value: Any) {
if let p = value as? any P {
print(label, "as? any P succeeded")
p.f()
} else {
print(label, "as? any P failed")
}
}
@main
struct Program {
static func main() async {
let c: any Sendable = C()
let d: any Sendable = D()
tryP("main C", c)
tryP("main D", d)
await Task.detached {
tryP("detached C", c)
tryP("detached D", d)
}.value
}
}
C 는 @MainActor P, D 는 일반 P 이면서 Sendable 이다. 두 값을 any Sendable 로 들고 있다가 main 에서 한 번, Task.detached 안에서 한 번 tryP 로 캐스트한다. Thread.isMainThread 로 f() 가 어느 스레드에서 도는지도 찍는다. 빌드는 xcrun swiftc -parse-as-library -swift-version 6 DynamicCast.swift -o ~/se470/dynamiccast 이다.
1
2
3
4
5
6
7
8
main C as? any P succeeded
f() on main
main D as? any P succeeded
f() on main
detached C as? any P failed
detached D as? any P succeeded
f() on not main
[exit 0]
네 번의 캐스트가 이렇게 갈린다.
- main 에서
C의as? any P: 성공하고f()가 main 에서 돈다 - main 에서
D의as? any P: 성공 Task.detached에서C의as? any P: 실패. 캐스트가 지금 main actor 가 아니라는 것을 알고 isolated conformance 를 쓰지 않았다Task.detached에서D의as? any P: 성공하고f()가 main 이 아닌 곳에서 돈다. 일반 conformance 는 어디서든 쓸 수 있다
같은 C 값, 같은 as? any P 인데 호출한 곳의 isolation 에 따라 결과가 갈린다. 제안서가 말하는 “동적 캐스트의 isolation 확인” 이 이것이다. 동적 캐스트에 관련해 제안서가 따로 설명하는 것이 있다. 옛 런타임에서는 캐스트가 isolation 을 확인하지 않아서 항상 성공한다. ABI 절에서 한 문장으로 다시 만난다.
제안서에는 value is any Sendable & P 라는 예도 있다. 이 모양을 그대로 컴파일해 본다.
DynamicCastSendable.swift
1
2
3
4
5
6
7
protocol P {
func f()
}
nonisolated func trySendableP(_ value: Any) -> Bool {
value is any Sendable & P
}
1
2
3
4
5
6
7
8
DynamicCastSendable.swift:6:9: error: marker protocol 'Sendable' cannot be used in a conditional cast
4 |
5 | nonisolated func trySendableP(_ value: Any) -> Bool {
6 | value is any Sendable & P
| `- error: marker protocol 'Sendable' cannot be used in a conditional cast
7 | }
8 |
[exit 1]
6.4 에서는 이 꼴이 컴파일되지 않는다. Sendable 이 marker protocol 이라서 조건부 캐스트의 대상이 될 수 없다는 오류다(6:9). 스레드에서 Nickolas_Pohilets 가 같은 오류 문구를 인용한 것을 이 글의 스레드 절에서 볼 수 있다.
conformance isolation 추론
지금까지는 @MainActor 를 직접 적었다. 그런데 @MainActor 타입 안에서 모든 conformance 에 @MainActor 를 적는 것은 번거롭고, 제안서는 이 부분을 upcoming feature InferIsolatedConformances 로 덜어 준다. @MainActor 타입(또는 다른 global actor 타입)이 nonisolated 프로토콜을 따를 때, 컴파일러가 그 conformance 를 같은 global actor 에 isolate 한다. 명시적으로 nonisolated 라고 쓰면 추론하지 않는다.
여기에 수정안(2025-07 에 수락)이 규칙 두 개를 더했다. 아래 두 경우에는 @MainActor 가 아니라 nonisolated 로 추론한다.
- 프로토콜이
SendableMetatype을 상속한다(Sendable을 거쳐 간접적으로 상속하는 경우도 포함). isolated conformance 는 이런 프로토콜에서 쓸 수 없으니 추론할 이유가 없다 - conformance 의 요구사항을 채우는 witness 가 전부
nonisolated다. 요구사항이 아예 없는 프로토콜과@Observable이 만드는 conformance 도 여기에 든다
그림은 컴파일러가 conformance 마다 위에서 아래로 내려가며 처음 맞는 단계의 결과를 쓰는 순서다. 직접 적은 isolation 이 가장 우선이고, SendableMetatype 상속과 모든 witness 가 nonisolated 인 경우가 nonisolated 로 가며, 그 밖의 모든 경우가 @MainActor 로 추론된다. 이 순서를 한 파일에 담았다.
Infer.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
protocol P {
func f()
}
protocol Q {
static func g()
}
protocol SP: Sendable {
func h()
}
@MainActor
final class MyModelType: P {
func f() {}
}
@MainActor
final class OptOut: nonisolated Q {
nonisolated static func g() {}
}
@MainActor
final class AllNonisolated: Q {
nonisolated static func g() {}
}
@MainActor
final class SendableProto: SP {
nonisolated func h() {}
}
nonisolated func useP(_ m: MyModelType) -> any P { m }
nonisolated func useQ(_ t: OptOut.Type) -> any Q.Type { t }
nonisolated func useQ2(_ t: AllNonisolated.Type) -> any Q.Type { t }
nonisolated func useSP(_ s: SendableProto) -> any SP { s }
프로토콜 세 개와 타입 네 개다. P 와 Q 는 일반 프로토콜이고, SP 는 Sendable 을 상속한다. MyModelType: P 는 아무것도 적지 않았고 witness f() 는 @MainActor 다. OptOut: nonisolated Q 는 conformance 에 nonisolated 를 적었고(SE-0449 글이 다룬 문법을 conformance 에 쓴 것이다), AllNonisolated: Q 는 아무것도 안 적었지만 witness g() 가 nonisolated 다. SendableProto: SP 는 Sendable 을 상속하는 프로토콜을 따른다. 아래 네 use 함수는 각 conformance 를 nonisolated 함수에서 쓴다.
nonisolated 로 conformance 의 isolation 추론 막기
nonisolated Q 처럼 프로토콜 앞에 붙은 nonisolated 는 conformance 가 isolation 에 묶이지 않는다는 표시다. 타입이나 멤버에 붙이던 nonisolated 와 같은 낱말이지만 conformance 에도 쓴다. Q 의 static func g() 는 정적 요구사항이고, 이 요구사항의 witness 는 nonisolated static func 으로 적었다.
먼저 기본 Swift 6 모드에서 컴파일한다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Infer.swift:14:26: error: conformance of 'MyModelType' to protocol 'P' crosses into main actor-isolated code and can cause data races [#ConformanceIsolation]
12 |
13 | @MainActor
14 | final class MyModelType: P {
| |- error: conformance of 'MyModelType' to protocol 'P' crosses into main actor-isolated code and can cause data races [#ConformanceIsolation]
| |- note: isolate this conformance to the main actor with '@MainActor'
| `- note: turn data races into runtime errors with '@preconcurrency'
15 | func f() {}
| |- note: main actor-isolated instance method 'f()' cannot satisfy nonisolated requirement
| `- note: mark instance method 'f()' 'nonisolated'
16 | }
17 |
[#ConformanceIsolation]: <https://docs.swift.org/compiler/documentation/diagnostics/conformance-isolation>
[exit 1]
기본 모드에서는 MyModelType: P 에서 오류가 난다(14:26). Motivation 에서 본 것과 같은 모양이다. 이번에는 upcoming feature 를 켠다.
1
xcrun swiftc -emit-sil -o /dev/null -parse-as-library -wmo -swift-version 6 -enable-upcoming-feature InferIsolatedConformances Infer.swift
1
2
3
4
5
6
7
8
9
10
Infer.swift:33:52: error: main actor-isolated conformance of 'MyModelType' to 'P' cannot be used in nonisolated context [#IsolatedConformances]
31 | }
32 |
33 | nonisolated func useP(_ m: MyModelType) -> any P { m }
| `- error: main actor-isolated conformance of 'MyModelType' to 'P' cannot be used in nonisolated context [#IsolatedConformances]
34 | nonisolated func useQ(_ t: OptOut.Type) -> any Q.Type { t }
35 | nonisolated func useQ2(_ t: AllNonisolated.Type) -> any Q.Type { t }
[#IsolatedConformances]: <https://docs.swift.org/compiler/documentation/diagnostics/isolated-conformances>
[exit 1]
14:26 의 오류가 사라지고 대신 useP 의 33:52 에서 오류가 난다. MyModelType: P 의 conformance 가 @MainActor 로 추론되어 선언 쪽은 통과하고, 그 conformance 를 nonisolated func useP 에서 쓰는 자리가 Rule 1 에 걸린 것이다. 나머지 useQ, useQ2, useSP 는 통과한다.
OptOut: 직접nonisolated를 적었으니 적은 대로 따른다AllNonisolated: witness 가 모두nonisolated라서nonisolated로 추론한다SendableProto:SP가Sendable을 상속하니nonisolated로 추론한다
enable-upcoming-feature 로 upcoming feature 켜기
-enable-upcoming-feature InferIsolatedConformances 는 이 글의 중심 옵션이다. 컴파일러에 upcoming feature 의 이름을 주면 그 기능이 켜진다. 기능이 켜지는 것은 이 컴파일 한 번에 한해서이고, 소스는 그대로다. 프로젝트에 적용하는 법은 뒤의 “SwiftPM 과 Xcode 설정” 절에서 본다.
컴파일러가 추론한 isolation 이 소스에 보이는 것은 아니다. -print-ast 로 AST 를 찍어 본다.
1
xcrun swiftc -print-ast -swift-version 6 -enable-upcoming-feature InferIsolatedConformances InferAst.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
internal protocol P {
func f()
}
internal protocol Q {
static func g()
}
internal protocol SP : Sendable {
func h()
}
@MainActor final internal class MyModelType : P {
@MainActor final internal func f() {
}
@objc deinit {
}
nonisolated internal init() {
}
}
@MainActor final internal class OptOut : @nonisolated Q {
nonisolated internal static func g() {
}
@objc deinit {
}
nonisolated internal init() {
}
}
@MainActor final internal class AllNonisolated : Q {
nonisolated internal static func g() {
}
@objc deinit {
}
nonisolated internal init() {
}
}
@MainActor final internal class SendableProto : SP {
nonisolated final internal func h() {
}
@objc deinit {
}
nonisolated internal init() {
}
}
직접 nonisolated 를 적은 OptOut 은 @nonisolated Q 로 찍힌다. 반면 MyModelType : P, AllNonisolated : Q, SendableProto : SP 는 모두 표시 없이 : P 꼴로 나와서, 추론으로 정해진 conformance 의 isolation 은 AST 에 드러나지 않는다. 그 결과가 눈에 보이는 곳은 컴파일러 진단이고, 실행 시점에는 앞 절의 as? 캐스트가 같은 결과를 쓴다.
InferIsolatedConformances 는 소스를 고치지 않고 컴파일러 옵션으로 켜는 기능이다. 같은 파일을 -default-isolation MainActor(SE-0466 글의 옵션)로 컴파일하면 어떻게 되는지도 본다.
1
xcrun swiftc -emit-sil -o /dev/null -parse-as-library -wmo -swift-version 6 -default-isolation MainActor Infer.swift
1
[exit 0]
진단이 없다. 모듈 기본이 @MainActor 이면 P 프로토콜 자체가 @MainActor 가 되어서 MyModelType: P 는 처음부터 isolation 이 일치하기 때문이다. 이 이야기는 아래 “기본 MainActor 모드와 함께” 에서 이어진다.
수정안이 막은 경우를 본다. 수정안 피치에서 Doug 는 Sendable 을 상속하는 프로토콜은 nonisolated conformance 로 추론해야 한다고 하고(isolated conformance 를 쓸 수 있는 곳이 없기 때문이다), witness 가 전부 nonisolated 인 경우도 nonisolated 로 추론하자고 했다. 후자의 이유는 둘이다(수정안 피치 #1). 첫째, Observable 같은 매크로는 요구사항을 채우려고 nonisolated 멤버를 만드는데, 매크로는 확장하는 타입이 actor isolated 인지 모르고 conformance 가 nonisolated 여야 한다는 기대로 쓰였다. 둘째, 틀린 isolation 이 추론되면 그 영향이 문제가 생긴 곳에서 멀리 떨어진 곳, 이를테면 다른 모듈이나 패키지에서 드러난다. 피치가 든 예는 InferIsolatedConformances 를 켠 상태의 class D: Q 이고, 기본 MainActor 모드의 이야기가 아니다. 위 AllNonisolated 와 SendableProto 가 이 두 규칙의 코드다. 이제 Sendable 을 상속하는 프로토콜에 @MainActor 를 직접 적으면 어떻게 되는지 본다.
SendableConf.swift
1
2
3
4
5
protocol SP: Sendable { func h() }
@MainActor final class B: @MainActor SP {
func h() {}
}
1
2
3
4
5
6
7
8
9
10
SendableConf.swift:3:24: error: cannot form main actor-isolated conformance of 'B' to SendableMetatype-inheriting protocol 'SP' [#IsolatedConformances]
1 | protocol SP: Sendable { func h() }
2 |
3 | @MainActor final class B: @MainActor SP {
| `- error: cannot form main actor-isolated conformance of 'B' to SendableMetatype-inheriting protocol 'SP' [#IsolatedConformances]
4 | func h() {}
5 | }
[#IsolatedConformances]: <https://docs.swift.org/compiler/documentation/diagnostics/isolated-conformances>
[exit 1]
오류다(3:24). “SendableMetatype 을 상속하는 프로토콜 SP 에 대해 main actor 에 isolated 된 conformance 를 만들 수 없다” 는 문장이다. 수정안 리뷰에서 Andropov 가 “SendableMetatype 을 상속하는 프로토콜은 isolated conformance 를 쓸 수 없는데, 명시적으로 쓰는 것을 아예 금지해야 하지 않느냐” 고 물었고(수정안 리뷰 #3), 리뷰 매니저가 이후 빌드가 이 사용을 warning 으로 진단한다고 전했다(수정안 리뷰 #6). 이 글의 6.4 컴파일러 측정에서는 같은 코드가 오류로 나온다.
@Observable 은 어떨까. 이 매크로가 만드는 Observable conformance 가 이 규칙들과 어떻게 만나는지 본다.
ObservableConf.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import Observation
@Observable @MainActor
final class Model {
var count = 0
}
nonisolated func isObservable<T: Observable>(_ t: T.Type) -> Bool { true }
nonisolated func check() -> Bool {
isObservable(Model.self)
}
protocol Empty {}
@MainActor final class Plain: Empty {}
nonisolated func useEmpty(_ p: Plain) -> any Empty { p }
Model 은 @Observable @MainActor 클래스이고, isObservable<T: Observable> 은 nonisolated 제네릭 함수다. check() 가 Model.self 를 넘긴다. 아래 Plain 과 Empty 는 요구사항이 아예 없는 프로토콜의 경우다. 이 코드는 기본 모드와 upcoming feature 를 켠 모드, -default-isolation MainActor 모드 모두에서 진단이 없다. 왜 Model 의 Observable conformance 가 nonisolated 함수로 건너갈 수 있는지는 매크로가 만든 코드를 보면 알 수 있다.
1
xcrun swiftc -emit-sil -o /dev/null -parse-as-library -wmo -swift-version 6 -Xfrontend -dump-macro-expansions ObservableConf.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
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
@__swiftmacro_4null5Model10ObservablefMm_.swift
------------------------------
@ObservationIgnored private let _$observationRegistrar = Observation.ObservationRegistrar()
internal nonisolated func access<$s4null5Model10ObservablefMm_6MemberfMu_>(
keyPath: KeyPath<Model, $s4null5Model10ObservablefMm_6MemberfMu_>
) {
_$observationRegistrar.access(self, keyPath: keyPath)
}
internal nonisolated func withMutation<$s4null5Model10ObservablefMm_6MemberfMu0_, $s4null5Model10ObservablefMm_14MutationResultfMu_>(
keyPath: KeyPath<Model, $s4null5Model10ObservablefMm_6MemberfMu0_>,
_ mutation: () throws -> $s4null5Model10ObservablefMm_14MutationResultfMu_
) rethrows -> $s4null5Model10ObservablefMm_14MutationResultfMu_ {
try _$observationRegistrar.withMutation(of: self, keyPath: keyPath, mutation)
}
private nonisolated func shouldNotifyObservers<$s4null5Model10ObservablefMm_6MemberfMu1_>(_ lhs: $s4null5Model10ObservablefMm_6MemberfMu1_, _ rhs: $s4null5Model10ObservablefMm_6MemberfMu1_) -> Bool {
true
}
private nonisolated func shouldNotifyObservers<$s4null5Model10ObservablefMm_6MemberfMu2_: Equatable>(_ lhs: $s4null5Model10ObservablefMm_6MemberfMu2_, _ rhs: $s4null5Model10ObservablefMm_6MemberfMu2_) -> Bool {
lhs != rhs
}
private nonisolated func shouldNotifyObservers<$s4null5Model10ObservablefMm_6MemberfMu3_: AnyObject>(_ lhs: $s4null5Model10ObservablefMm_6MemberfMu3_, _ rhs: $s4null5Model10ObservablefMm_6MemberfMu3_) -> Bool {
lhs !== rhs
}
private nonisolated func shouldNotifyObservers<$s4null5Model10ObservablefMm_6MemberfMu4_: Equatable & AnyObject>(_ lhs: $s4null5Model10ObservablefMm_6MemberfMu4_, _ rhs: $s4null5Model10ObservablefMm_6MemberfMu4_) -> Bool {
lhs != rhs
}
------------------------------
@__swiftmacro_4null5ModelC5count10ObservablefMr_.swift
------------------------------
@ObservationTracked
------------------------------
@__swiftmacro_4null5ModelC5count18ObservationTrackedfMp_.swift
------------------------------
@ObservationIgnored
private var _count = 0
------------------------------
@__swiftmacro_4null5ModelC5count18ObservationTrackedfMa_.swift
------------------------------
{
@storageRestrictions(initializes: _count)
init(initialValue) {
_count = initialValue
}
get {
access(keyPath: \.count)
return _count
}
set {
guard shouldNotifyObservers(_count, newValue) else {
_count = newValue
return
}
withMutation(keyPath: \.count) {
_count = newValue
}
}
_modify {
access(keyPath: \.count)
_$observationRegistrar.willSet(self, keyPath: \.count)
defer {
_$observationRegistrar.didSet(self, keyPath: \.count)
}
yield &_count
}
}
------------------------------
@__swiftmacro_4null5ModelC6_count33_93CBD60CA8FA275B60259EC7D30F5506LL18ObservationIgnoredfMa_.swift
------------------------------
------------------------------
@__swiftmacro_4null5Model10ObservablefMe_.swift
------------------------------
extension Model: nonisolated Observation.Observable {
}
------------------------------
@__swiftmacro_4null5ModelC22_$observationRegistrar33_93CBD60CA8FA275B60259EC7D30F5506LL18ObservationIgnoredfMa_.swift
------------------------------
------------------------------
[exit 0]
출력이 길지만 이 글에서 볼 곳은 아래쪽 @__swiftmacro_4null5Model10ObservablefMe_.swift 의 한 줄이다. 매크로가 extension Model: nonisolated Observation.Observable {} 을 만들었다. Observable 매크로가 nonisolated conformance 를 직접 적어 주는 것이다. 이 글 뒤의 스레드 절에서 볼 수정안 피치의 이유, 즉 매크로가 만드는 멤버는 nonisolated 라서 매크로 쪽이 conformance 에 nonisolated 를 적어야 한다는 이야기가 코드로 확인되는 모습이다.
Observable 매크로로 변경 관찰 코드 만들기
@Observable 는 클래스에 붙이면 저장 속성의 접근과 변경을 추적하는 코드를 확장해 주는 매크로다. 위 출력처럼 access(keyPath:), withMutation(keyPath:_:) 같은 nonisolated 멤버와 속성별 getter, setter 가 생성되고, Observable 프로토콜의 conformance 도 매크로가 붙인다.
ObservationRegistrar로 관찰 기록 관리하기
ObservationRegistrar 는 어떤 속성을 누가 읽었고 언제 바뀌었는지를 기록하는 타입이다. 매크로가 만든 _$observationRegistrar 저장 속성이 이것이고, 생성된 access 와 withMutation 이 이 기록기를 부른다.
요구사항이 없는 protocol Empty 는 upcoming feature 를 켜도 nonisolated 로 추론된다. “모든 witness 가 nonisolated 다” 라는 규칙에서 witness 가 하나도 없는 경우다. useEmpty 가 nonisolated 함수에서 any Empty 를 만드는데도 진단이 없는 것이 그 결과다.
마지막으로 피치 단계에서 버려진 isolated 철자를 컴파일러에 넣어 본다.
Spelling.swift
1
2
3
4
5
protocol P { func f() }
@MainActor final class A: isolated P {
func f() {}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Spelling.swift:3:27: error: conformance of 'A' to protocol 'P' crosses into main actor-isolated code and can cause data races [#ConformanceIsolation]
1 | protocol P { func f() }
2 |
3 | @MainActor final class A: isolated P {
| |- error: conformance of 'A' to protocol 'P' crosses into main actor-isolated code and can cause data races [#ConformanceIsolation]
| |- note: isolate this conformance to the main actor with '@MainActor'
| `- note: turn data races into runtime errors with '@preconcurrency'
4 | func f() {}
| |- note: main actor-isolated instance method 'f()' cannot satisfy nonisolated requirement
| `- note: mark instance method 'f()' 'nonisolated'
5 | }
6 |
[#ConformanceIsolation]: <https://docs.swift.org/compiler/documentation/diagnostics/conformance-isolation>
[exit 1]
class A: isolated P 는 구문 오류가 나지 않는다. 그런데 오류 내용과 note 가 아무것도 안 적은 A: P 일 때(Infer 의 기본 모드)와 같다. 즉 isolated 는 파서가 받아 주지만 conformance 를 isolate 하는 효과가 없다. 피치 초기에는 class C: isolated P 로 쓰자는 안이었고, Doug 가 “더 일반적이고 더 명확하다” 며 @MainActor P 로 바꿨다(피치 스레드 #29). 이 글에서 쓴 철자는 모두 @MainActor P 이다.
기본 MainActor 모드와 함께
SE-0466 에서 본 -default-isolation MainActor 모드는 모듈의 모든 선언에 @MainActor 를 암묵적으로 붙인다. 이 제안은 그 모드와 함께 쓰이도록 설계되었다. 피치 스레드에서 Doug 가 이렇게 정리했다(#36).
- 기본 MainActor 모드만 있을 때:
class MyClass: SomeProtocol이@MainActor class MyClass와@MainActor func satisfiesRequirement...로 해석된다.SomeProtocol의 요구사항이nonisolated라면 컴파일되지 않는다 - 이 제안의 추론과 함께: 같은 코드가
@MainActor class MyClass: @MainActor SomeProtocol로 해석된다. conformance 를 main actor 코드 밖에서 쓰지 않는 한 문제가 없고, 모듈의 코드가 모두 기본 main actor 이니 대부분 괜찮다
이 상황을 코드로 본다. 프로토콜은 nonisolated 로 명시했고, 클래스에는 아무것도 붙이지 않았다.
DefaultMain.swift
1
2
3
4
5
6
7
8
9
nonisolated protocol P {
func f()
}
final class MyModelType: P {
func f() {}
}
nonisolated func useP(_ m: MyModelType) -> any P { m }
기본 모드에서는 이 파일이 문제없이 컴파일된다.
1
[exit 0]
진단이 없다. MyModelType 은 기본으로 nonisolated 이고 f() 도 nonisolated 라서 nonisolated conformance 다. 이번에는 -default-isolation MainActor 로 컴파일한다.
1
xcrun swiftc -emit-sil -o /dev/null -parse-as-library -wmo -swift-version 6 -default-isolation MainActor DefaultMain.swift
1
2
3
4
5
6
7
8
9
DefaultMain.swift:9:52: error: main actor-isolated conformance of 'MyModelType' to 'P' cannot be used in nonisolated context [#IsolatedConformances]
7 | }
8 |
9 | nonisolated func useP(_ m: MyModelType) -> any P { m }
| `- error: main actor-isolated conformance of 'MyModelType' to 'P' cannot be used in nonisolated context [#IsolatedConformances]
10 |
[#IsolatedConformances]: <https://docs.swift.org/compiler/documentation/diagnostics/isolated-conformances>
[exit 1]
오류다(9:52). MyModelType 이 @MainActor 가 되고 f() 도 @MainActor 가 되어 conformance 가 @MainActor 로 추론되었고, nonisolated func useP 에서 그것을 쓰는 곳이 Rule 1 에 걸린다. nonisolated protocol P 라서 프로토콜은 main actor 로 따라가지 않는다. upcoming feature 를 켜지 않았는데도 isolated conformance 가 생겼다는 점이 눈에 띈다. 일부러 끄면 어떻게 되는지도 본다.
1
xcrun swiftc -emit-sil -o /dev/null -parse-as-library -wmo -swift-version 6 -default-isolation MainActor -disable-upcoming-feature InferIsolatedConformances DefaultMain.swift
1
2
3
4
5
6
7
8
9
DefaultMain.swift:9:52: error: main actor-isolated conformance of 'MyModelType' to 'P' cannot be used in nonisolated context [#IsolatedConformances]
7 | }
8 |
9 | nonisolated func useP(_ m: MyModelType) -> any P { m }
| `- error: main actor-isolated conformance of 'MyModelType' to 'P' cannot be used in nonisolated context [#IsolatedConformances]
10 |
[#IsolatedConformances]: <https://docs.swift.org/compiler/documentation/diagnostics/isolated-conformances>
[exit 1]
결과가 같다. -default-isolation MainActor 는 InferIsolatedConformances 를 따로 켜지 않아도 이 추론을 켠다. SE-0466 글에서 본 Xcode 27 의 새 앱 템플릿이 SWIFT_APPROACHABLE_CONCURRENCY = YES 를 넣는 것도 같은 맥락이다. 바로 다음 절 “SwiftPM 과 Xcode 설정” 에서 Xcode 설정을 본다.
이 파일에서 nonisolated protocol P 를 일부러 쓴 이유가 있다. 모듈 기본이 @MainActor 이면 protocol P 에 아무것도 안 적어도 P 자신이 main actor 가 된다. 이런 프로토콜은 제안과 상관없이 요구사항이 @MainActor 이므로 conformance 도 @MainActor 로 일치한다. isolated conformance 가 필요한 경우는 프로토콜이 다른 모듈에서 오거나 nonisolated 로 적힌 경우다.
SwiftPM 과 Xcode 설정
upcoming feature 를 실제 프로젝트에 켜는 방법이다. SwiftPM 패키지 쪽부터 본다.
Package.swift 는 tools-version 6.2, macOS 15 이상, 실행 타깃 App 하나이고, swiftSettings 에 .enableUpcomingFeature("InferIsolatedConformances") 를 둔다.
Pkg/Package.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
// swift-tools-version: 6.2
import PackageDescription
let package = Package(
name: "Pkg",
platforms: [.macOS(.v15)],
targets: [
.executableTarget(
name: "App",
swiftSettings: [.enableUpcomingFeature("InferIsolatedConformances")]
),
]
)
swiftSettings 로 타깃에 컴파일러 설정 더하기
swiftSettings 는 타깃 선언의 매개변수로, 그 타깃의 Swift 컴파일에만 쓰이는 설정 목록을 받는다.
enableUpcomingFeature 로 upcoming feature 켜기
.enableUpcomingFeature(_:_:) 는 이름으로 지정한 upcoming feature 를 타깃에 켠다. 컴파일러에는 -enable-upcoming-feature 옵션으로 전달된다.
Sources/App/main.swift 는 @MainActor 클래스 Counter 가 Describable 을 따르고, 제네릭 show<T: Describable> 이 그것을 부른다.
Pkg/Sources/App/main.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
protocol Describable {
func describe() -> String
}
@MainActor
final class Counter: Describable {
var count = 0
func describe() -> String { "count = \(count)" }
}
func show<T: Describable>(_ value: T) -> String { value.describe() }
let counter = Counter()
counter.count = 3
print(show(counter))
먼저 swift build 로 빌드한다.
1
swift build
1
2
3
4
Building for debugging...
[2 / 6] App-product
Build complete! (0.36초)
[exit 0]
빌드 로그다. [2 / 6] App-product 는 진행 표시이고 Build complete! 와 [exit 0] 이 성공을 말한다. 걸린 시간은 실행할 때마다 다르다. 이어서 실행한다.
1
swift run App
1
2
3
4
5
count = 3
Building for debugging...
[2 / 6] App-product
Build complete! (0.35초)
[exit 0]
swift run 은 빌드 로그를 stderr 로, 프로그램의 출력을 stdout 으로 내보낸다. 위 블록은 stdout 뒤에 stderr 를 이어 붙인 것이라서 count = 3 이 먼저 보이고 빌드 로그가 뒤에 온다. 둘을 따로 받으면 stdout 은 count = 3 한 줄이고 stderr 가 빌드 로그다.
빌드에 성공하고 count = 3 이 나온다. show(counter) 는 최상위 코드(@MainActor)에서 부르는 것이라 Counter 의 conformance 가 main actor 안에서 쓰인다. 설정이 컴파일러까지 전달되는지는 swift build -v 로 확인한다. 컴파일 줄에서 이 설정과 관련된 옵션만 뽑았다.
1
2
3
-enable-upcoming-feature InferIsolatedConformances
-swift-version 6
-target arm64-apple-macos15.0
-enable-upcoming-feature InferIsolatedConformances 가 컴파일 줄에 들어간다. 설정을 Package.swift 에서 빼면 어떻게 될까. 같은 소스를 옵션 없이 Swift 6 모드로 컴파일한다.
1
xcrun swiftc -emit-sil -o /dev/null -swift-version 6 Sources/App/main.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Sources/App/main.swift:6:22: error: conformance of 'Counter' to protocol 'Describable' crosses into main actor-isolated code and can cause data races [#ConformanceIsolation]
4 |
5 | @MainActor
6 | final class Counter: Describable {
| |- error: conformance of 'Counter' to protocol 'Describable' crosses into main actor-isolated code and can cause data races [#ConformanceIsolation]
| |- note: isolate this conformance to the main actor with '@MainActor'
| `- note: turn data races into runtime errors with '@preconcurrency'
7 | var count = 0
8 | func describe() -> String { "count = \(count)" }
| |- note: main actor-isolated instance method 'describe()' cannot satisfy nonisolated requirement
| `- note: mark instance method 'describe()' 'nonisolated'
9 | }
10 |
[#ConformanceIsolation]: <https://docs.swift.org/compiler/documentation/diagnostics/conformance-isolation>
[exit 1]
Counter 의 conformance 가 main actor 로 넘어간다는 오류가 난다. count 를 읽는 describe() 가 @MainActor 인데 Describable 의 요구사항은 nonisolated 이기 때문이다. 설정 한 줄이 이 오류를 없앤다.
Xcode 프로젝트에서는 빌드 설정으로 켠다. Xcode 27 의 컴파일러 스펙(Swift.xcspec)에 SWIFT_UPCOMING_FEATURE_INFER_ISOLATED_CONFORMANCES 라는 설정이 있다. 정의는 이렇다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
{
Name = "SWIFT_UPCOMING_FEATURE_INFER_ISOLATED_CONFORMANCES";
Type = Enumeration;
Values = (
YES,
MIGRATE,
NO,
);
DefaultValue = "$(SWIFT_APPROACHABLE_CONCURRENCY)";
CommandLineArgs = {
YES = ( "-enable-upcoming-feature", "InferIsolatedConformances" );
MIGRATE = ( "-enable-upcoming-feature", "InferIsolatedConformances:migrate" );
NO = ();
};
DisplayName = "Infer Isolated Conformances";
Category = "Upcoming Features";
Description = "Infer conformances of global-actor isolated types as isolated to the same actor unless isolation is explicitly specified as `nonisolated`.";
},
값은 YES, MIGRATE, NO 셋이다. YES 는 앞의 SwiftPM 설정이 만든 컴파일러 옵션과 같은 -enable-upcoming-feature InferIsolatedConformances 를 넣고, MIGRATE 는 :migrate 를 붙인다. 기본값이 $(SWIFT_APPROACHABLE_CONCURRENCY) 이므로 이 값을 따로 정하지 않으면 “Approachable Concurrency” 설정을 따라간다.
SWIFT_APPROACHABLE_CONCURRENCY 는 Boolean 이고 기본값이 NO 다. 정의에는 조건이 하나 붙어 있다(Swift.xcspec 568 행).
1
Condition = "$(EFFECTIVE_SWIFT_VERSION) == '4' || $(EFFECTIVE_SWIFT_VERSION) == '4.2' || $(EFFECTIVE_SWIFT_VERSION) == '5'";
이 조건은 실제로 적용되는 언어 버전이 4, 4.2, 5 일 때만 참이다. 즉 이 설정은 Swift 4 와 5 언어 모드에서만 쓰이고 Swift 6 모드에서는 대상이 아니다.
설정의 나머지 내용은 이렇다. 설명은 “더 다가가기 쉬운 Swift Concurrency 로 가는 기능들을 한꺼번에 켠다” 이고, 포함되는 기능은 DisableOutwardActorInference, GlobalActorIsolatedTypesUsability, InferIsolatedConformances, InferSendableFromCaptures, NonisolatedNonsendingByDefault 다섯 가지다. SE-0466 글에서 본 Xcode 27 새 앱 템플릿이 이 설정을 YES 로 넣는다. 그 템플릿으로 만든 프로젝트에서는 이 글의 추론이 이미 켜져 있다.
스레드에서 오간 이야기
이 제안은 Swift Forums 에서 스레드 여섯 개를 거쳤다. 본 제안의 피치(77726, 글 51개), 리뷰(78704, 17개), 수락 공지(79189, 2개), 그리고 추론 규칙을 고친 수정안의 피치(79854), 리뷰(80999, 7개), 수락 공지(81144)다. 아래에서는 논쟁이 갈린 곳을 주제별로 묶고, 인용은 (스레드 #번호, 글쓴이) 로 적는다.
이름과 기본값
피치 초반에는 이름과 기본값을 놓고 이야기가 오갔다. AlexanderM 은 “Actor-isolated conformances” 라는 이름을 제안했다(피치 #2, AlexanderM). Jon_Shier 는 isolated conformance 가 기본이면 안 되는지, 그리고 isolated 타입이 nonisolated 프로토콜을 올바르게 따를 수 있는 경우가 있는지 물었다(피치 #3, Jon_Shier).
Doug 의 답은 두 갈래였다. 기본으로 삼으면 isolation 이 눈에 보이지 않게 되어 적절하지 않고, 또 isolated 타입이라도 불변 상태에 기대는 conformance 는 문제가 없다는 것이다. 예로 든 것이 nonisolated let recordID 를 가진 Person 이다(피치 #4, Doug). 이 “기본으로 하지 말고, 필요하면 추론으로 돕자” 는 구도가 뒤에 InferIsolatedConformances 가 upcoming feature 로 들어온 배경이다.
리뷰 중에 Doug 는 이름이 NonisolatedConformances 였다면 더 정확했을 것이라고 적었다(리뷰 #7, Doug). 같은 글에서 그는 non-sendable metatype 모델을 선호한다고 밝히고, Swift Testing 코드로 시험했다고 전했다.
Sendable 과의 관계
가장 오래 이어진 이야기는 Rule 2 의 멘탈 모델이다. Andropov 는 두 번 어렵다고 적었고(피치 #11, #13, Andropov), 이어서 “global actor 로 isolate 된 타입은 Sendable 인데 conformance 가 sendable 이 아니라는 것이 말이 되는가” 를 물었다(#15, Andropov). vns 는 foo 안에서 타입이 지워지면 isolation 을 들고 다닐 것이 없다고 짚었다(#12, vns). Nickolas_Pohilets 는 Sendable conformance 를 isolated 와 nonisolated 요구사항을 가르는 문법으로 쓰는 것에 의문을 제기하면서, vision 문서의 T: isolated P 와 T: nonisolated P 를 인용했다(#16, #18, Nickolas_Pohilets).
Doug 는 이렇게 정리했다. T: P 는 T: SendableMetatype 이나 T: Sendable 이 아니면 isolated conformance 로 채울 수 있다. 이미 Sendable 제약을 더하면 호출부가 깨지는 것은 지금도 그렇다. 이 내용을 Alternatives Considered 에 더하겠다고 했다(#20, Doug). 이 글의 “Rule 2” 절에서 본 규칙이 이 문장에 해당한다.
리뷰 단계에서는 John_McCall 이 판을 바꾸는 제안을 했다. SendableMetatype 이 하는 일은 이제 isolated conformance 를 넘겨주지 못하게 막는 것뿐이니, where T: nonisolated P 를 도입하고 타입이 Sendable 이면 nonisolated 를 암묵적으로 두자는 것이다. 클라이언트가 nonisolated 요구사항을 isolated conformance 로 채우지 못하게 해야 한다는 점도 말했다(리뷰 #2, John_McCall). 8675309 가 같은 혼란에 동의했다(리뷰 #3, 8675309).
Doug 는 이 제안의 일부를 받아 모델을 고쳤다. 리뷰 #13 에서 “metatype T.Type 은 T: MetatypeSendable 일 때만 Sendable” 로 바꾸는 PR #2763 을 알렸고, 그 결과가 이 글의 “SendableMetatype이란?” 에서 본 모양이다. 한편 수락 공지는 nonisolated 를 제네릭 요구사항에 쓰는 대안에 열린 질문이 있다는 점을 적고, 지금의 더 좁은 SendableMetatype 접근을 따르되 이후 패치를 허용하기로 했다(수락 공지 #1, xwu).
철자
처음 제안서는 class C: isolated P 였다. 8675309 는 isolated XYZ 가 nonisolated 프로토콜을 따르는 것이 혼란스럽다고 했고(피치 #24, 8675309), Nickolas_Pohilets 는 길더라도 @MainActor S: nonisolated P 가 낫다고 했다(#26, Nickolas_Pohilets). Doug 는 2025-03-11 에 isolated P 를 @MainActor P 로 바꿨다(#29, Doug). Nickolas_Pohilets 가 두 철자가 공존해도 되지 않느냐고 물었지만(#32), Doug 는 문법을 둘 두고 싶지 않다고 답했다(#33, Doug). 이 글의 Spelling.swift 에서 isolated P 가 파서를 통과하지만 효과가 없는 것은 이 결정의 흔적이다.
여러 isolation 이 섞이는 경우도 나왔다. AlexisQapa 가 conformance 마다 isolation 이 다른 경우를 물었고(#28), bbrk24 는 한 타입이 nonisolated 인 P 와 서로 다른 isolation 의 Q, R 을 가질 수 있느냐고 물었다. Doug 는 된다고 답했다(#49, bbrk24, #51, Doug).
actor 인스턴스에 isolate 되는 conformance 도 물었다. bbrk24 는 self-isolated actor conformance 를 물었고(#30), Doug 는 이것이 Future Directions 이고 type-check 하는 방법을 아직 모른다고 했다(#31, Doug). 그래서 제안서의 Future Directions 에는 actor-instance isolated conformance 가 isolated P 로 남아 있다.
추론을 어떻게 켤 것인가
추론은 이 제안에서 가장 의견이 많았던 부분이다. Andropov 는 @MainActor 가 추론될 때 isolated 도 추론하는 미래 방향을 짚었다(피치 #25, Andropov). xwu 는 같은 소스가 플래그에 따라 다른 의미가 되는 것이 frozen 과 non-frozen enum 의 경우와 비슷하다고 했다(#35, xwu). Doug 는 이것이 SE-0466 에 이미 있는 성질이라고 답하고 MyClass 예제를 들었다(#36, Doug). 이 글의 “기본 MainActor 모드와 함께” 가 그 예제를 코드로 옮긴 것이다.
bjhomer 는 기본으로 추론하고 nonisolated SomeProtocol 로 빠져나오는 방식을 요청했다(#37, bjhomer). Doug 는 upcoming feature 로 단계를 나눠야 한다고 답하면서, 지금 있는 conformance 대부분은 @preconcurrency 나 assumeIsolated 로 덮여 있을 것이라고 추측했다(#38, Doug). hborla 는 불일치가 오류일 때만, 그리고 불일치한 witness 가 모두 같은 global actor 일 때만 추론하자는 좁은 안을 냈고 단점도 적었다(#39, hborla). Slava_Pestov 는 다른 파일을 봐야 하는 비용을 우려했고(#40), Doug 는 연관 conformance 와의 재귀 때문에 witness 에서 추론하지 않는다고 답했다(#41, Doug). 컴파일러가 스스로 추론한 것을 두고 불평하면 성가실 것이라는 이야기도 있었다(#42, Andropov, #43, Doug).
수정안 피치에서 Doug 는 항목을 이렇게 나열했다(수정안 피치 #1, Doug).
Sendable을 상속하는 프로토콜은 nonisolated conformance 로 추론한다- SE-0466 의 추론이
Sendable을 상속하는 프로토콜을 따른다고 선언한 타입에@MainActor를 붙이지 않도록 한다 - witness 가 전부
nonisolated이면 nonisolated conformance 로 추론한다. 이유는@Observable같은 매크로가nonisolated멤버를 만든다는 점과, 틀린 추론의 영향이 원인에서 멀리 떨어진 곳에서 나타난다는 점이다 - global actor 타입의
Equatable,Hashable,Codable합성 멤버가 추론된 isolation 을 갖게 해서@MainActor class C: Codable이 isolated conformance 를 얻게 한다
Andropov 는 nonisolated P 를 명시하게 하고 오류와 fix-it 를 주자고 했고(수정안 피치 #2, Andropov), Doug 가 답했다(#3). 이 글의 ObservableConf 와 SendableConf 가 이 항목들에 해당하는 코드다.
수정안 리뷰에서 xwu 가 의미 있는 문제를 짚었다. 라이브러리 A 의 v1.1 이 기본 구현이 있는 새 요구사항 destroy() 를 더하는데 MyType.destroy() 가 @MainActor 라면 conformance 가 @MainActor 로 바뀐다. 대안은 둘이다. nonisolated 명시를 필수로 하거나, 기본 구현이 없는 요구사항만 보는 것이다. xwu 는 뒤쪽에 기울었다(수정안 리뷰 #4, xwu). Doug 는 두 번째 안이 AsyncIteratorProtocol 의 next() 와 next(isolation:) 처럼 서로를 기본 구현으로 삼는 대체 요구사항에서 깨진다고 답했다(#5, Doug). 수정안 수락 공지는 요구사항이 늘면 추론된 isolation 이 바뀔 수 있고 깨끗한 휴리스틱이 없다는 점을 적고 원안대로 받아들였다(수정안 수락 공지 #1, xwu). 제안서의 Alternatives Considered 가 이 점을 단점으로 적는다.
동적 캐스트
xwu 는 existential 을 열 때는 어떻게 되는지 물었고(피치 #44, xwu), Doug 는 as? 에 검사가 둘 있다고 답했다. 현재 executor 와, 프로토콜이 SendableMetatype 을 함의하지 않는지다(#45, Doug). Nickolas_Pohilets 가 isIsolatingCurrentContext() 를 물었고(#48), Doug 는 커스텀 executor 와 SerialExecutor 의 isIsolated 제안을 들어 답했다(#51, Doug).
리뷰에서는 Nickolas_Pohilets 가 두 가지를 보였다. 하나는 배포 대상과 런타임 버전, 커스텀 executor 와 assumeIsolated() 의 조합을 표로 정리한 것이고(리뷰 #5), 다른 하나는 제네릭 함수를 거치면 Sendable 캐스트 제한을 우회할 수 있다는 것이다(#6). Doug 는 back-deployment 는 범위 밖이고 구현은 오래된 런타임에서 캐스트를 항상 허용하며, 택하지 않은 대안이 assumeIsolated {} 를 끼워 넣는 것이었다고 답했다(#8, Doug). 런타임은 any P 와 any P & Sendable 을 구분하지 못하므로 marker protocol 캐스트 문제는 고치지 않는다고도 했다(#10, Doug). 이 글의 “동적 캐스트” 절에서 본 DynamicCastSendable 이 그 지점이다.
수락 공지(#1, xwu)는 세 항목을 적었다.
nonisolated를 제네릭 요구사항에 쓰는 대안에 열린 질문이 있고, 더 좁은SendableMetatype접근을 따르되 패치는 가능하다- 이 기능 이전의 런타임에서 캐스트는 틀리게 성공하거나 틀리게 실패한다. 운영 그룹은 “성공” 을 올바른 방향으로의 순이동으로 보고, 도구가 opt-in 진단을 줄 것을 기대한다
- 제안은 isolated conformance 를 가진 구체 타입을
any Sendable & P로 캐스트하는 것을 거부한다. 제네릭 함수를 거치면Sendable이 얽힌 런타임 캐스트가 성공하는 기존 문제가 있다. 이것은 Sendable conformance 가 런타임 메타데이터에 기록되어야 닫을 수 있고, 이 제안의 범위 밖이며 승인을 막는다고 보지 않는다
이 글 “동적 캐스트” 절의 두 실행 결과는 이 문장들을 읽을 때 옆에 두고 볼 만하다.
그 밖의 이야기
- Doug 는 이것을 “real pitch” 로 선언하고 문서를 갱신했고(피치 #21), toolchain 을 공지했다(#34). xwu 가 리뷰로 넘겼다(#50)
- grynspan 은 Swift Testing 의 관점에서 환영했다(피치 #23). 리뷰에서는
@Test와@Suite매크로의 source break 를 걱정하며 opt-out 이 있는지 물었다(리뷰 #4, grynspan). Doug 가 Swift Testing 코드로 시험했고SendableMetatype상속이 프로토콜이 빠져나오는 방법이라고 답했다(리뷰 #7) - rayx 가 async 함수와의 관계를(피치 #7), OneSadCookie 가 KeyPath 를(#10) 물었다. KeyPath 는 이 글의 Rule1KeyPath 에서 다뤘다
- 리뷰 #12 에서 Doug 는 실험 플래그 세 개를 나열했다.
IsolatedConformances,InferIsolatedConformances,StrictSendableMetatypes다 - 8675309 가 actor 에 global actor conformance 를 줄 수 있느냐고 물었고(리뷰 #14), Doug 는 어느 타입이든 가질 수 있다고 답했다(#15)
- 수락 후 vanvoorden 이
SendableMetatype과 관련해 말이 되지 않는 warning 이 있다며 swiftlang/swift#82116 를 가리키고 6.2 가 나오기 전에 지침을 요청했다(수락 공지 #2, vanvoorden)
기대 효과
데이터 레이스를 컴파일 시점에 막으면서 main actor 타입의 conformance 가 자연스러워진다. 구체적으로는 이렇다.
@MainActor클래스가nonisolated프로토콜을 따를 때nonisolatedwitness 를 억지로 만들거나assumeIsolated로 덮지 않아도 된다- 그 conformance 를 main actor 밖에서 쓰는 곳은 대부분 컴파일러가 막아 주므로, 안전하지 않은 호출이 런타임 크래시가 아니라 빌드 오류가 된다. 모든 길을 막는 것은 아니다. 앞 절에서 본
contains를 거치는 길(ContainsRun)과any Sendable & P로 캐스트하는 길(AnyBad)은 main actor 밖에서 실행해도 진단 없이 컴파일되었다 InferIsolatedConformances를 켜면 conformance 마다@MainActor를 적지 않아도 된다-default-isolation MainActor와 함께 쓰면 모듈 대부분의 코드가 별다른 표기 없이 main actor 안에서 consistent 하게 동작한다
다른 선택지는 왜 안 됐나
제안서가 검토한 대안과 이유를 정리한다.
Sendable대신 “Non-Sendable conformance” 라는 용어를 쓰는 안. region 기반 isolation 은 non-Sendable 값을 건네게 하지만 isolated conformance 는 건널 수 없고, global actor 타입은 보통 Sendable 이며, opt-in 방향이 거꾸로이고, 진단이 isolation 용어로 나오며, 정착된 철자도 없다T: isolated P와T: nonisolated P요구사항을 두는 안. 나중에 일반화할 수 있다. 이 제안에서는T: SendableMetatype을 nonisolated P 로, 나머지를 isolated P 로 읽는다. 단점은 복잡도다- 추론하지 않고
nonisolated를 필수로 쓰게 하는 안. 소스 호환성과@Observable같은 매크로를 생각하면 추론이 필요하다. 단점은 프로토콜에 기본 구현이 있는 요구사항이 늘면 추론된 isolation 이 바뀔 수 있다는 것이고, 이는 이후 언어 모드에서 deprecate 할 수 있다
Swift 6 모드와 마이그레이션
소스 호환성은 두 갈래로 나뉜다. 새 문법으로 isolated conformance 를 직접 쓴 코드는 기존 소스가 아니므로 깨질 것이 없다. 그 코드가 Rule 1 을 어기면 Swift 5 모드에서는 warning, Swift 6 모드에서는 error 다. Rule 2 를 어긴 Rule2Generic 은 Swift 6 모드에서도 warning 으로 나온다. 반면 기존 소스의 의미를 바꾸는 것은 InferIsolatedConformances 를 켰을 때뿐이다. 같은 @MainActor class C: P 가 nonisolated conformance 에서 @MainActor conformance 로 바뀐다. 먼저 새 문법의 Rule 1 위반을 모드별로 컴파일해 본다.
Swift5.swift
1
2
3
4
5
6
7
protocol P { func f() }
@MainActor final class A: @MainActor P {
func f() {}
}
func use(_ a: A) -> any P { a }
1
2
3
4
5
6
=== Swift5.swift [-swift-version 5]
Swift5.swift:7:29: warning: main actor-isolated conformance of 'A' to 'P' cannot be used in nonisolated context; this is an error in the Swift 6 language mode [#IsolatedConformances]
=== Swift5.swift [-swift-version 5 -strict-concurrency=complete]
Swift5.swift:7:29: warning: main actor-isolated conformance of 'A' to 'P' cannot be used in nonisolated context; this is an error in the Swift 6 language mode [#IsolatedConformances]
=== Swift5.swift [-swift-version 6]
Swift5.swift:7:29: error: main actor-isolated conformance of 'A' to 'P' cannot be used in nonisolated context [#IsolatedConformances]
Swift 5 모드에서도 7:29 에 “Swift 6 언어 모드에서는 오류다” 라는 warning 이 나오고, Swift 6 모드에서는 같은 자리가 오류다. strict concurrency 를 켜지 않은 plain Swift 5 에서도 warning 이 나온다. 이 파일은 Rule 1 의 예이고, Rule 2 는 이 표에 나오지 않는다.
ABI 는 깨지지 않는다. isolated conformance 정보는 기존 런타임 메타데이터로 확장되고, 오래된 런타임에서는 as? 가 항상 성공한다. 오래된 런타임에서 캐스트가 틀리게 성공하는 경우는 위 수락 공지의 두 번째 항목이 다룬 것이다.
InferIsolatedConformances 를 켤 때 기존 코드의 동작을 어떻게 지킬지는 :migrate 가 돕는다. 이 upcoming feature 는 migratable 이다. 컴파일러가 알려 주는 기능 목록에서 이 줄을 확인한다.
1
xcrun swiftc -print-supported-features
1
{ "name": "InferIsolatedConformances", "migratable": true, "categories": ["IsolatedConformances"], "enabled_in": "7" }
"migratable": true 라서 :migrate 가 되고, "enabled_in": "7" 이므로 Swift 7 언어 모드에서는 기본으로 켜진다.
Migrate.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
protocol Describable {
func describe() -> String
}
@MainActor
final class Counter: Describable {
let id = 1
nonisolated func describe() -> String { "Counter" }
}
protocol Named {
var name: String { get }
}
@MainActor
final class Item: Named {
nonisolated let name = "item"
}
nonisolated func show(_ d: any Describable) -> String { d.describe() }
nonisolated func useElsewhere(_ c: Counter) -> String { show(c) }
기본 모드에서 컴파일한다.
1
[exit 0]
진단이 없다. Counter 와 Item 은 지금 nonisolated conformance 다. 이제 기능만 켜서 컴파일한다.
1
xcrun swiftc -emit-sil -o /dev/null -parse-as-library -wmo -swift-version 6 -enable-upcoming-feature InferIsolatedConformances Migrate.swift
1
[exit 0]
이것도 진단이 없다. witness 가 모두 nonisolated 라서 추론 결과가 nonisolated 이고, 기능을 켜도 의미가 바뀌지 않기 때문이다. 이제 migrate 모드로 컴파일한다.
1
xcrun swiftc -emit-sil -o /dev/null -parse-as-library -wmo -swift-version 6 -enable-upcoming-feature InferIsolatedConformances:migrate Migrate.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Migrate.swift:6:22: warning: conformance of 'Counter' to 'Describable' should be marked 'nonisolated' to retain its behavior with upcoming feature 'InferIsolatedConformances' [#IsolatedConformances]
4 |
5 | @MainActor
6 | final class Counter: Describable {
| `- warning: conformance of 'Counter' to 'Describable' should be marked 'nonisolated' to retain its behavior with upcoming feature 'InferIsolatedConformances' [#IsolatedConformances]
7 | let id = 1
8 | nonisolated func describe() -> String { "Counter" }
Migrate.swift:16:19: warning: conformance of 'Item' to 'Named' should be marked 'nonisolated' to retain its behavior with upcoming feature 'InferIsolatedConformances' [#IsolatedConformances]
14 |
15 | @MainActor
16 | final class Item: Named {
| `- warning: conformance of 'Item' to 'Named' should be marked 'nonisolated' to retain its behavior with upcoming feature 'InferIsolatedConformances' [#IsolatedConformances]
17 | nonisolated let name = "item"
18 | }
[#IsolatedConformances]: <https://docs.swift.org/compiler/documentation/diagnostics/isolated-conformances>
[exit 0]
warning 이 둘 나온다(6:22 의 Counter/Describable, 16:19 의 Item/Named). 위의 기능만 켠 결과와 비교하면 :migrate 는 보수적이다. 추론 결과가 nonisolated 가 되는 경우에도, 앞으로 추론 규칙이 바뀌어도 지금 동작이 유지되도록 nonisolated 를 적으라고 안내한다. nonisolated 를 적고 나서 upcoming feature 를 켜면 소스 동작이 그대로 유지된다.
추론을 켜면 실제로 동작이 바뀌는 코드는 이쪽이다. witness 가 @MainActor 인 Counter 가 nonisolated 프로토콜을 따르고, 이를 nonisolated 함수에서 쓴다. Swift 6 모드에서는 선언 쪽 warning 이 이미 오류라서, 변화를 단계별로 보려고 Swift 5 모드로 컴파일한다.
MigrateS5.swift
1
2
3
4
5
6
7
8
9
10
11
12
protocol Describable {
func describe() -> String
}
@MainActor
final class Counter: Describable {
var count = 1
func describe() -> String { "Counter \(count)" }
}
nonisolated func show(_ d: any Describable) -> String { d.describe() }
nonisolated func useElsewhere(_ c: Counter) -> String { show(c) }
Swift 5 모드에서 기능 없이 컴파일하면, 지금은 nonisolated conformance 라서 사용처에는 진단이 없고 6:22 에 선언 쪽 warning 만 나온다.
1
xcrun swiftc -emit-sil -o /dev/null -parse-as-library -wmo -swift-version 5 MigrateS5.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
MigrateS5.swift:6:22: warning: conformance of 'Counter' to protocol 'Describable' crosses into main actor-isolated code and can cause data races; this is an error in the Swift 6 language mode [#ConformanceIsolation]
4 |
5 | @MainActor
6 | final class Counter: Describable {
| |- warning: conformance of 'Counter' to protocol 'Describable' crosses into main actor-isolated code and can cause data races; this is an error in the Swift 6 language mode [#ConformanceIsolation]
| |- note: isolate this conformance to the main actor with '@MainActor'
| `- note: turn data races into runtime errors with '@preconcurrency'
7 | var count = 1
8 | func describe() -> String { "Counter \(count)" }
| |- note: main actor-isolated instance method 'describe()' cannot satisfy nonisolated requirement
| `- note: mark instance method 'describe()' 'nonisolated'
9 | }
10 |
[#ConformanceIsolation]: <https://docs.swift.org/compiler/documentation/diagnostics/conformance-isolation>
[exit 0]
기능을 켜면 conformance 가 @MainActor 로 추론되고, 선언 쪽 warning 은 사라지는 대신 사용처인 12:62 에 새 warning 이 생긴다. 같은 소스의 의미가 바뀐 것이다.
1
xcrun swiftc -emit-sil -o /dev/null -parse-as-library -wmo -swift-version 5 -enable-upcoming-feature InferIsolatedConformances MigrateS5.swift
1
2
3
4
5
6
7
8
9
MigrateS5.swift:12:62: warning: main actor-isolated conformance of 'Counter' to 'Describable' cannot be used in nonisolated context; this is an error in the Swift 6 language mode [#IsolatedConformances]
10 |
11 | nonisolated func show(_ d: any Describable) -> String { d.describe() }
12 | nonisolated func useElsewhere(_ c: Counter) -> String { show(c) }
| `- warning: main actor-isolated conformance of 'Counter' to 'Describable' cannot be used in nonisolated context; this is an error in the Swift 6 language mode [#IsolatedConformances]
13 |
[#IsolatedConformances]: <https://docs.swift.org/compiler/documentation/diagnostics/isolated-conformances>
[exit 0]
:migrate 로 켜면 기능 없이 컴파일한 6:22 warning 에 더해 같은 자리에 “nonisolated 로 표시해서 동작을 유지하라” 는 warning 이 하나 더 나온다.
1
xcrun swiftc -emit-sil -o /dev/null -parse-as-library -wmo -swift-version 5 -enable-upcoming-feature InferIsolatedConformances:migrate MigrateS5.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
MigrateS5.swift:6:22: warning: conformance of 'Counter' to protocol 'Describable' crosses into main actor-isolated code and can cause data races; this is an error in the Swift 6 language mode [#ConformanceIsolation]
4 |
5 | @MainActor
6 | final class Counter: Describable {
| |- warning: conformance of 'Counter' to protocol 'Describable' crosses into main actor-isolated code and can cause data races; this is an error in the Swift 6 language mode [#ConformanceIsolation]
| |- note: isolate this conformance to the main actor with '@MainActor'
| `- note: turn data races into runtime errors with '@preconcurrency'
7 | var count = 1
8 | func describe() -> String { "Counter \(count)" }
| |- note: main actor-isolated instance method 'describe()' cannot satisfy nonisolated requirement
| `- note: mark instance method 'describe()' 'nonisolated'
9 | }
10 |
MigrateS5.swift:6:22: warning: conformance of 'Counter' to 'Describable' should be marked 'nonisolated' to retain its behavior with upcoming feature 'InferIsolatedConformances' [#IsolatedConformances]
4 |
5 | @MainActor
6 | final class Counter: Describable {
| `- warning: conformance of 'Counter' to 'Describable' should be marked 'nonisolated' to retain its behavior with upcoming feature 'InferIsolatedConformances' [#IsolatedConformances]
7 | var count = 1
8 | func describe() -> String { "Counter \(count)" }
[#ConformanceIsolation]: <https://docs.swift.org/compiler/documentation/diagnostics/conformance-isolation>
[#IsolatedConformances]: <https://docs.swift.org/compiler/documentation/diagnostics/isolated-conformances>
[exit 0]
정리
@MainActor class C: @MainActor P처럼 conformance 가 global actor 에 isolate 된다. 그 isolation 도메인 안에서만 쓸 수 있다- 규칙은 셋이다. isolation 도메인 안에서만 쓴다(Rule 1),
Sendable과SendableMetatype제약에는 쓸 수 없다(Rule 2), isolated conformance 에 기댄 값은 그 global actor 의 region 에 묶인다(Rule 3) as?는 런타임에 현재 executor 를 확인한다InferIsolatedConformances는@MainActor타입의 conformance 를@MainActor로 추론한다.SendableMetatype을 상속하는 프로토콜이나 witness 가 모두nonisolated인 경우는nonisolated로 추론한다-default-isolation MainActor는 이 추론을 켠다. Xcode 의 Approachable Concurrency 가 같은 설정을 한꺼번에 켠다- 새 문법의 Rule 1 위반은 Swift 5 모드에서 warning, Swift 6 모드에서 error 이고, Rule 2 위반은 6.4 에서 Swift 6 모드에서도 warning 이다. 기존 소스의 의미를 바꾸는 것은
InferIsolatedConformances를 켤 때뿐이고,:migrate가nonisolated를 적을 곳을 알려 준다
관련 글
- [SE-0337] Incremental migration to concurrency checking
- [SE-0414] Region based Isolation
- [SE-0418] Inferring Sendable for methods and key path literals
- [SE-0423] Dynamic actor isolation enforcement from non-strict-concurrency contexts
- [SE-0430] sending parameter and result values
- [SE-0434] Usability of global-actor-isolated types
- [SE-0449] Allow nonisolated to prevent global actor inference
- [SE-0461] Run nonisolated async functions on the caller’s actor by default
- [SE-0466] Control default actor isolation inference

