포스트

[SE-0461] Run nonisolated async functions on the caller's actor by default

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


제안서 정보


한 줄 요약

actor 에 묶이지 않은 async 함수는 지금까지 부른 쪽 actor 를 떠나 전역 executor 에서 돌았다. 이 제안은 그 기본값을 뒤집어서, upcoming feature NonisolatedNonsendingByDefault 를 켜면 부른 쪽 actor 에서 그대로 돌게 한다. 기본값이 어떻게 바뀌든 쓸 수 있는 명시 철자가 둘 생겼다. 부른 쪽에서 돌게 하는 nonisolated(nonsending) 과, 항상 전역 executor 로 옮겨 가게 하는 @concurrent 다.


어떤 문제였나

Swift 5.5 에서 async 함수가 들어온 뒤로, actor 에 묶이지 않은 async 함수가 어디서 도는지는 한 번 바뀌었다. 처음에는 부른 쪽의 actor 에서 돌았고, SE-0338 이 그것을 “부른 쪽을 떠나 전역 executor 에서 돈다” 로 바꿨다. 이 제안은 그 SE-0338 의 결정을 되돌리는 것이라서, 먼저 SE-0338 이 무엇을 정했고 왜 그랬는지부터 짚는다.

이 글의 뼈대는 이렇다. 문제를 네 가지로 나눠서 보고, 바뀌는 것을 nonisolated(nonsending), @concurrent 와 몇 가지 규칙(#isolation, Task, 클로저, 함수 변환, region)으로 나눠 측정하고, 철자가 어떻게 정해졌는지를 포럼 스레드로 따라간 뒤, 소스 호환과 ABI 와 마이그레이션을 본다.

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

  • SE-0414 글: non-Sendable 값을 같은 region 으로 묶어서 다른 isolation 으로 보내도 되는지 컴파일러가 판단하는 방식
  • SE-0430 글: 함수 경계를 넘어 값을 통째로 넘기는 sending
  • SE-0420 글: nonisolated async 함수가 부른 쪽 actor 를 떠나는 이유와, 그 사실을 우회하는 isolation: isolated (any Actor)? = #isolation 관용구. 그 글 끝에서 SE-0461 이 그 관용구를 어떻게 대체하는지도 다룬다
  • SE-0431 글: 함수 타입에 isolation 을 값으로 남기는 @isolated(any)

SE-0338 이 정한 규칙

actor 의 메서드는 actor 위에서 돈다. 그 메서드가 await 로 actor 에 묶이지 않은 async 함수를 부르면 어디서 돌까. 이 질문에 대한 답이 바뀌어 왔다.

Swift 5.5 에서 async 함수가 처음 나왔을 때는 부른 쪽의 executor 에서 돌았다. 이 모델에서는 actor 안의 non-Sendable 값을 actor 에 묶이지 않은 async 함수에 넘겨도, 그 함수가 같은 actor 위에서 돌기 때문에 안전한 것처럼 보였다. 그런데 이 방식은 data race 를 완전히 막지 못했다고 리뷰 스레드에서 저자가 설명한다(리뷰 #35, hborla). SE-0338 은 의미를 바꿔서, actor 에 묶이지 않은 async 함수는 항상 actor 의 executor 를 떠나 돌게 했다. 그러면 부른 쪽 actor 의 상태와 이 함수가 겹쳐서 도는 일이 없어서 안전해지고, ABI 를 바꾸지 않고도 의미를 안전하게 만들 수 있었다. 제안서 Motivation 은 이 결정이 actor 를 불필요하게 직렬화하고 경합시키는 일을 줄이려는 것이었다고 정리한다. 일을 main actor 에서 빼내면 UI 응답성에 유리하다는 이점이 따라왔다.

같은 질문의 답을 지금 Swift 6.4 컴파일러가 어떻게 말하는지는 아래 코드에서 보인다. 제안서가 인용하는 형태 그대로다.

이 글의 공통 코드

이 글의 모든 예제는 아래 non-Sendable 클래스를 같이 컴파일한다. NotSendable 이라는 이름은 Sendable 을 채택하지 않은 참조 타입이라는 뜻이다. 참조 타입이라서 같은 인스턴스를 두 곳에서 만지면 data race 가 날 수 있다.

Common.swift

1
2
3
4
class NotSendable {
  var value = 0
  init() {}
}

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

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

기능을 켠 판은 같은 명령에 -enable-upcoming-feature NonisolatedNonsendingByDefault 만 더한다.

1
xcrun swiftc -emit-sil -o /dev/null -parse-as-library -wmo -swift-version 6 -enable-upcoming-feature NonisolatedNonsendingByDefault Common.swift Motivation.swift

이 글에서 “기본” 이라고 하면 Swift 6 언어 모드에 아무 feature 도 켜지 않은 판이고, “feature 를 켠 판” 이라고 하면 위 명령처럼 NonisolatedNonsendingByDefault 를 켠 판이다. 컴파일러는 Apple Swift version 6.4 (swiftlang-6.4.0.34.1) 이다.


sync 와 async 의 nonisolated 불일치

제안서 Motivation 의 첫 번째 문제는 nonisolated 가 이해하기 어렵다는 것이다. actor 에 묶이지 않은 함수 두 개를 나란히 놓으면 보인다.

Motivation.swift

1
2
3
4
5
6
7
8
9
10
11
12
13
14
extension NotSendable {
  func performSync() {}
  func performAsync() async {}
}

actor MyActor {
  let x = NotSendable()

  func call() async {
    x.performSync() // okay

    await x.performAsync()
  }
}

performSync() 와 performAsync() 는 둘 다 actor 에 묶이지 않았다. MyActor.call() 은 actor 안에서 돌고 x 는 이 actor 의 상태다. 동기 함수 performSync() 는 부른 쪽 actor 에서 그대로 돌아서 x 를 넘겨도 아무 문제가 없다. 그런데 await 가 붙는 performAsync() 는 다르다. 기본 Swift 6 모드의 진단이다.

1
2
3
4
5
6
7
8
9
10
11
12
Motivation.swift:12:13: error: sending 'self.x' risks causing data races [#RegionIsolation::SendingRisksDataRace]
10 |     x.performSync() // okay
11 | 
12 |     await x.performAsync()
   |             |- error: sending 'self.x' risks causing data races [#RegionIsolation::SendingRisksDataRace]
   |             `- note: sending 'self'-isolated 'self.x' to @concurrent instance method 'performAsync()' risks causing data races between @concurrent and 'self'-isolated uses
13 |   }
14 | }

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

12:13 은 x 를 넘기는 await x.performAsync() 에서 performAsync 의 첫 글자다. 오류는 이 호출이 x 를 보낸다고 말한다. note 가 이유를 말한다. self 에 묶인 self.x 를 @concurrent 인스턴스 메서드 performAsync() 에 보내면 @concurrent 쪽 사용과 self 쪽 사용이 겹쳐서 data race 가 날 수 있다는 것이다.

여기서 눈에 띄는 것이 note 의 @concurrent 다. performAsync() 에는 아무 철자도 붙이지 않았는데 6.4 컴파일러는 기본 모드에서 이 메서드를 @concurrent instance method 라고 부른다. 이 글에서 앞으로 보겠지만 @concurrent 는 “항상 전역 executor 로 옮겨 가는 nonisolated async 함수” 를 가리키는 철자이고, 지금 기본값이 바로 그 동작이기 때문이다.

같은 코드를 NonisolatedNonsendingByDefault 를 켜고 컴파일하면 진단이 없다.

1
[exit 0]

세 언어 모드로도 돌려 봤다. 이 글 전체에서 쓰는 modes.sh 는 Swift 5, Swift 5 에 -strict-concurrency=complete, Swift 6 을 차례로 돌려서 error 와 warning 줄만 모아 준다.

모드결과
Swift 5진단 없음
Swift 5, -strict-concurrency=completewarning: sending 'self.x' risks causing data races; this is an error in the Swift 6 language mode
Swift 6error: sending 'self.x' risks causing data races
Swift 6, NonisolatedNonsendingByDefault진단 없음
Swift 5, NonisolatedNonsendingByDefault진단 없음

기본값이 같은 코드를 한 가지로 만든다는 것이 이 글의 첫 번째 대조군이다. 같은 nonisolated 인데 동기 함수는 부른 쪽에서 돌고 async 함수는 부른 쪽을 떠난다. 그래서 Sendable 검사도 async 함수에만 걸린다. 제안서는 이것을 두고 nonisolated 의 뜻을 이해하기 어렵게 만드는 비대칭이라고 말한다.


isolated 파라미터로 우회하기

두 번째 문제는 부른 쪽 actor 에서 도는 async 함수를 쓰고 싶을 때 쓸 수 있는 방법이 장황하다는 것이다. SE-0420 이 도입한 isolated parameter 관용구를 쓴다.

IsolatedParam.swift

1
2
3
4
5
6
7
8
9
10
11
12
13
extension NotSendable {
  func performAsync(
    isolation: isolated (any Actor)? = #isolation
  ) async {}
}

actor MyActor {
  let x = NotSendable()

  func call() async {
    await x.performAsync() // okay
  }
}

isolation: isolated (any Actor)? = #isolation 은 “이 함수는 isolation 으로 받은 actor 위에서 돈다” 는 뜻의 parameter 다. #isolation 은 부른 쪽의 isolation 으로 펼쳐지는 매크로이고, 기본 인자로 두면 호출하는 쪽이 아무것도 안 적어도 자기 actor 가 들어간다. 이 코드는 기본 모드와 feature 를 켠 판 모두에서 진단이 없다.

1
[exit 0]

이 방법은 두 가지로 불편하다. 하나는 모든 함수에 이 parameter 를 직접 적어야 하는 boilerplate 다. 다른 하나는 이 메서드를 함수 값으로 꺼내 쓰는 순간 기본 인자가 사라진다는 것이다. 제안서는 higher-order 로 쓰면 기본 인자를 잃는다고 적는다. 직접 확인했다.

IsolatedParamHigherOrder.swift

1
2
3
4
5
6
7
8
9
10
11
12
13
14
extension NotSendable {
  func performAsync(
    isolation: isolated (any Actor)? = #isolation
  ) async {}
}

actor MyActor {
  let x = NotSendable()

  func call() async {
    let f = x.performAsync
    await f()
  }
}

기본 모드의 진단이다.

1
2
3
4
5
6
7
8
9
10
IsolatedParamHigherOrder.swift:12:13: error: missing argument for parameter #1 in call
 9 | 
10 |   func call() async {
11 |     let f = x.performAsync
   |         `- note: 'f' declared here
12 |     await f()
   |             `- error: missing argument for parameter #1 in call
13 |   }
14 | }
[exit 1]

함수 값 f 의 타입은 (isolated (any Actor)?) async -> () 가 되어서 isolation 인자를 요구한다. 기본 인자는 선언에 붙은 것이라서 함수 값에는 남지 않는다. 같은 코드를 feature 를 켜고 돌려도 같은 오류가 같은 자리에 나온다. 이 우회로를 쓴 함수는 NonisolatedNonsendingByDefault 와 상관없이 처음부터 이 모양이다. SE-0461 이 nonisolated(nonsending) 으로 대체하려는 대상이 이 관용구이고, 철자가 대체하는 방법은 뒤의 절에서 본다.


함수를 받는 async API

세 번째와 네 번째 문제는 같이 본다. async 클로저를 받는 higher-order API 를 쓰는 것과 쓰는 것이 모두 어렵다는 것이다. 제안서 Motivation 의 예는 withResource 인데, 먼저 더 작은 형태로 문제를 만든다. 제안서는 함수 값 쪽의 Sendable 검사가 “자주 false positive 의 원인” 이라고 말한다.

HigherOrderHalf.swift

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
nonisolated(nonsending)
func runState(
  _ ns: NotSendable,
  _ body: (NotSendable) async -> Void
) async {
  await body(ns)
}

actor MyActor {
  let state = NotSendable()

  func use() async {
    await runState(state) { ns in
      ns.value += 1
    }
  }
}

runState 는 nonisolated(nonsending) 으로 적어서 부른 쪽 actor 에서 돈다. 그 함수가 body 에 ns 를 넘긴다. 이 body 는 아무 철자도 붙이지 않은 async 함수 타입이다. 기본 모드의 진단이다.

1
2
3
4
5
6
7
8
9
10
11
12
HigherOrderHalf.swift:6:9: error: sending 'ns' risks causing data races [#RegionIsolation::SendingRisksDataRace]
 4 |   _ body: (NotSendable) async -> Void
 5 | ) async {
 6 |   await body(ns)
   |         |- error: sending 'ns' risks causing data races [#RegionIsolation::SendingRisksDataRace]
   |         `- note: sending 'ns' to @concurrent callee risks causing data races between @concurrent code and code in the current isolation context
 7 | }
 8 | 

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

오류는 runState 선언 쪽에서 난다. runState 자신은 부른 쪽 actor 에서 도는데, parameter 로 받은 body 는 기본이 @concurrent 다. 그래서 ns 를 body 에 넘기는 일이 “@concurrent 코드와 현재 isolation 컨텍스트 사이” 의 data race 가 된다. API 를 쓰는 쪽이 아니라 API 를 만드는 쪽에서 막힌다. 제안서가 말하는 “higher-order async API 를 쓰기 어렵다” 가 이 모양이다.

feature 를 켠 판에서는 진단이 없다.

1
[exit 0]

세 모드로 돌려 보면 Swift 5 는 진단이 없고, -strict-concurrency=complete 는 warning: sending 'ns' risks causing data races; this is an error in the Swift 6 language mode, Swift 6 은 같은 자리 6:9 의 error 다. 이 대조군에서 feature 가 함수 선언뿐 아니라 함수 타입의 기본값도 바꾼다는 것을 알 수 있다. body 의 타입에는 아무 것도 적지 않았는데 feature 를 켜자 body 가 부른 쪽 actor 에서 도는 함수 타입으로 읽혔다. 제안서의 Source compatibility 절이 이 기능이 함수 선언과 함수 값 모두에 적용된다고 적은 것과 맞다.

이번에는 runState 자체에도 아무 철자를 안 붙이고 actor 에서 클로저를 넘겨 본다.

HigherOrderBody.swift

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
func run(_ body: (NotSendable) async -> Void) async {
  await body(NotSendable())
}

func runState(_ ns: NotSendable, _ body: (NotSendable) async -> Void) async {
  await body(ns)
}

actor MyActor {
  let state = NotSendable()

  func use() async {
    await runState(state) { ns in
      ns.value += 1
    }
  }
}

기본 모드의 진단이다.

1
2
3
4
5
6
7
8
9
10
11
12
HigherOrderBody.swift:13:11: error: sending 'self.state' risks causing data races [#RegionIsolation::SendingRisksDataRace]
11 | 
12 |   func use() async {
13 |     await runState(state) { ns in
   |           |- error: sending 'self.state' risks causing data races [#RegionIsolation::SendingRisksDataRace]
   |           `- note: sending 'self'-isolated 'self.state' to @concurrent global function 'runState' risks causing data races between @concurrent and 'self'-isolated uses
14 |       ns.value += 1
15 |     }

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

이쪽은 사용하는 쪽의 오류다. actor 의 상태 self.state 를 @concurrent 전역 함수 runState 에 보내서 같은 오류가 난다. feature 를 켜면 진단이 없고, 세 모드 결과는 앞의 HigherOrderHalf 와 같은 모양이다(Swift 5 는 진단 없음, complete 는 warning, Swift 6 은 error).

runState 와 body 타입 모두에 nonisolated(nonsending) 을 적으면 feature 의 켜짐과 상관없이 같은 뜻이 된다.

HigherOrderNonsending.swift

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
nonisolated(nonsending)
func runState(
  _ ns: NotSendable,
  _ body: nonisolated(nonsending) (NotSendable) async -> Void
) async {
  await body(ns)
}

actor MyActor {
  let state = NotSendable()

  func use() async {
    await runState(state) { ns in
      ns.value += 1
    }
  }
}

기본 모드와 feature 를 켠 판 모두 진단이 없다.

1
[exit 0]

반대로 함수 타입에 @concurrent 를 적으면 feature 를 켜도 옛 동작이다.

HigherOrderConcurrentBody.swift

1
2
3
4
5
6
7
nonisolated(nonsending)
func runState(
  _ ns: NotSendable,
  _ body: @concurrent (NotSendable) async -> Void
) async {
  await body(ns)
}

기본 모드와 feature 를 켠 판의 진단이 같다.

1
2
3
4
5
6
7
8
9
10
11
12
HigherOrderConcurrentBody.swift:6:9: error: sending 'ns' risks causing data races [#RegionIsolation::SendingRisksDataRace]
4 |   _ body: @concurrent (NotSendable) async -> Void
5 | ) async {
6 |   await body(ns)
  |         |- error: sending 'ns' risks causing data races [#RegionIsolation::SendingRisksDataRace]
  |         `- note: sending 'ns' to @concurrent callee risks causing data races between @concurrent code and code in the current isolation context
7 | }
8 | 

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

세 번의 실험이 가리키는 것을 표로 모은다. 열은 body 의 타입이고 칸은 runState 안에서 await body(ns) 가 막히는지다.

body 의 타입기본 Swift 6feature 를 켠 판
아무것도 안 붙임error통과
nonisolated(nonsending)통과통과
@concurrenterrorerror

제안서의 withResource 예는 이 문제를 isolated parameter 로 푼 형태라서 그대로 돌리면 통과한다.

HigherOrder.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
public struct Resource {
  internal init() {}
  internal mutating func close() async {}
}

public func withResource<Return>(
  isolation: isolated (any Actor)? = #isolation,
  _ body: (inout Resource) async -> Return
) async -> Return {
  var resource = Resource()
  let result = await body(&resource)
  await resource.close()
  return result
}

actor MyActor {
  let state = NotSendable()

  func use() async {
    let value = await withResource { _ in
      state
    }
    print(value.value)
  }
}

기본 모드와 feature 를 켠 판 모두 진단이 없다.

1
[exit 0]

withResource 는 isolation: isolated (any Actor)? = #isolation 으로 부른 쪽 actor 에서 돌고, body 가 돌려주는 state 는 부른 쪽 actor 의 값이라 region 이 맞는다. 제안서도 이 예가 disconnected region 의 값을 넘기는 특별한 경우라서 통과한다고 설명한다. 그래서 이 글에서는 이 예를 문제 예제로 쓰지 않고, 같은 문제를 더 직접 보여 주는 HigherOrderHalf 와 HigherOrderBody 를 주로 썼다. withResource 같은 API 를 쓰려면 모든 higher-order 함수에 isolation parameter 를 이 순서로 얹고, body 쪽의 Sendable 규칙이 거짓 양성으로 막히는 자리를 하나하나 피해야 한다. 제안서는 이것이 쓰는 사람에게 너무 복잡하다고 말한다.

지금까지의 문제를 합친다. nonisolated 의 뜻이 sync 와 async 에서 어긋나고, 부른 쪽에서 도는 async 를 표현하는 길이 장황하고 함수 값에서 깨지고, higher-order API 는 만드는 쪽과 쓰는 쪽 모두 막힌다. 제안서는 SE-0338 의 결정이 UI 응답성을 위해 쓰기 편한 정도를 내준 선택이라고 요약한다. Introduction 은 Swift 의 일반 철학이 성능보다 안전과 사용 편의를 앞에 둔다고 하고, 지금 동작은 main actor 의 응답성을 얻는 대신 사용성을 내준다고 쓴다.


무엇이 바뀌나

제안의 뼈대는 세 가지다. feature flag 를 켜면 철자 없는 nonisolated async 함수가 부른 쪽 actor 에서 돈다. nonisolated(nonsending) 은 그 새 동작의 명시 철자이고, @concurrent 는 옛 동작의 명시 철자다. 두 철자는 feature 의 켜짐과 상관없이 쓸 수 있어서, 코드를 한 번 적어 두면 build setting 에 흔들리지 않는다.


기본값이 호출자 actor 로

먼저 네 종류의 함수가 어디서 도는지를 한 번에 본다. @main 에서 main actor 를 거쳐 네 함수를 차례로 부르고, 각 함수가 자기가 도는 dispatch 큐의 이름과 #isolation 을 찍는다.

Where.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
import Dispatch

func queue() -> String {
  String(cString: __dispatch_queue_get_label(nil))
}

func plainAsync() async {
  print("plainAsync()       \(queue())  #isolation = \(String(describing: #isolation))")
}

nonisolated(nonsending) func nonsendingAsync() async {
  print("nonsendingAsync()  \(queue())  #isolation = \(String(describing: #isolation))")
}

@concurrent func concurrentAsync() async {
  print("concurrentAsync()  \(queue())  #isolation = \(String(describing: #isolation))")
}

func plainSync() {
  print("plainSync()        \(queue())  #isolation = \(String(describing: #isolation))")
}

@main
struct Program {
  static func main() async {
    await plainAsync()
    await nonsendingAsync()
    await concurrentAsync()
    plainSync()
  }
}

C 함수 dispatch_queue_get_label 에 nil 을 넘기면 지금 코드가 돌고 있는 dispatch 큐의 이름이 돌아온다(Swift 에서 보이는 이름은 __dispatch_queue_get_label). 큐 이름이 com.apple.main-thread 면 main 큐이고 com.apple.root.default-qos.cooperative 면 Swift concurrency 의 cooperative thread pool 이다. #isolation 은 이 함수가 돌고 있는 isolation 을 (any Actor)? 로 펼치는 매크로이고, nil 은 어떤 actor 에도 묶이지 않았다는 뜻이다.

처음에는 pthread_main_np() 로 main 스레드인지 찍었다. 그런데 명령줄 프로그램의 async main 에서는 첫 await 뒤에는 main actor 위에서도 0 이 나와서 스레드 대신 큐 이름을 찍는 쪽으로 바꿨다. 아래 결과는 큐 이름만 말하고, dispatch 내부가 어떻게 돌아가는지는 말하지 않는다.

컴파일은 기본과 feature 를 켠 판 두 가지다. 실행 파일 이름은 where, where-feat 다.

1
xcrun swiftc -parse-as-library -swift-version 6 Common.swift Where.swift -o where
1
xcrun swiftc -parse-as-library -swift-version 6 -enable-upcoming-feature NonisolatedNonsendingByDefault Common.swift Where.swift -o where-feat

기본 Swift 6 의 실행 결과다.

1
2
3
4
plainAsync()       com.apple.root.default-qos.cooperative  #isolation = nil
nonsendingAsync()  com.apple.main-thread  #isolation = Optional(Swift.MainActor)
concurrentAsync()  com.apple.root.default-qos.cooperative  #isolation = nil
plainSync()        com.apple.main-thread  #isolation = nil

feature 를 켠 판의 실행 결과다.

1
2
3
4
plainAsync()       com.apple.main-thread  #isolation = Optional(Swift.MainActor)
nonsendingAsync()  com.apple.main-thread  #isolation = Optional(Swift.MainActor)
concurrentAsync()  com.apple.root.default-qos.cooperative  #isolation = nil
plainSync()        com.apple.main-thread  #isolation = nil

기본 Swift 6 에서는 철자 없는 async 함수가 cooperative pool 로 떠나고, NonisolatedNonsendingByDefault 를 켜면 main 큐에 남는다. 나머지 세 함수는 두 열이 같다

두 결과를 겹치면 바뀌는 줄은 plainAsync() 하나뿐이다. 기본에서는 cooperative pool 큐에서 #isolation 이 nil 이고, feature 를 켜면 main 큐에서 Optional(Swift.MainActor) 다. nonsendingAsync() 는 두 판 모두 main 큐이고 #isolation 이 main actor 다. concurrentAsync() 는 두 판 모두 cooperative pool 이고 nil 이다. 철자를 직접 적은 함수는 build setting 과 상관없이 같은 곳에서 돈다. 이것이 두 철자가 존재하는 이유다.

plainSync() 는 두 판 모두 main 큐에서 돌지만 #isolation 은 nil 이다. 동기 nonisolated 함수는 처음부터 부른 쪽에서 도는데, 암시적 isolated parameter 가 없어서 #isolation 이 펼칠 값이 없기 때문이다. 부른 쪽에서 돈다는 것과 #isolation 이 그 actor 를 가리킨다는 것은 같은 말이 아니다. 이 차이는 뒤의 #isolation 절에서 다시 본다.


nonisolated(nonsending)

nonisolated(nonsending) 은 “이 async 함수는 부른 쪽 actor 에서 돈다” 는 철자다. 이름에서 nonsending 은 이 함수를 부를 때 non-Sendable 인자와 결과가 isolation 경계를 건너 보내지지 않는다는 뜻이다. 제안서는 구현이 암시적으로 optional actor parameter 를 하나 더 받는 방식이라고 설명한다. 앞에서 손으로 적던 isolation: isolated (any Actor)? = #isolation 이 컴파일러가 대신 넣어 주는 것이다.

Nonsending.swift

1
2
3
4
5
6
7
8
9
10
11
12
extension NotSendable {
  nonisolated(nonsending)
  func performAsync() async {}
}

actor MyActor {
  let x = NotSendable()

  func call() async {
    await x.performAsync() // okay
  }
}

앞의 Motivation.swift 에서 error 였던 performAsync() 에 철자만 붙였다. 기본 모드와 feature 를 켠 판 모두 진단이 없다.

1
[exit 0]

세 언어 모드(Swift 5, Swift 5 complete, Swift 6) 모두 진단이 없다. 이 철자는 feature flag 없이 어느 언어 모드에서나 쓴다. 코드에 적어 두면 build setting 이 바뀌어도 의미가 같은 이유다.

명시 철자가 함수 타입으로 따라가는지도 확인했다. 제안서에는 nonisolated(nonsending) 함수를 함수 값으로 꺼냈을 때의 타입을 보여 주는 예가 있다.

CallSendable.swift

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@MainActor let global: NotSendable = .init()

nonisolated(nonsending)
func runOnActor(ns: NotSendable) async {}

@MainActor
func callSendableClosure() async {
  let closure = runOnActor(ns:)
  print(type(of: closure))

  let ns = NotSendable()
  await closure(ns) // okay
  await closure(global) // okay
}

CallSendableRun.swift

1
2
3
4
5
6
@main
struct Program {
  static func main() async {
    await callSendableClosure()
  }
}

type(of:) 는 값의 실제 타입을 돌려준다. 실행하면 이렇게 찍힌다.

1
xcrun swiftc -parse-as-library -swift-version 6 Common.swift CallSendable.swift CallSendableRun.swift -o callsendable
1
nonisolated(nonsending) @Sendable (NotSendable) async -> ()

함수 선언에 적은 철자가 함수 타입으로 그대로 따라온다. 기본 모드와 feature 를 켠 판 모두 컴파일 진단이 없고, main actor 의 전역 non-Sendable 값 global 을 넘기는 줄까지 통과한다. 출력에서 @Sendable 은 nonisolated(nonsending) 뒤에 찍힌다.

nonisolated(nonsending) 에는 쓸 수 없는 자리가 있다. 한 파일에 모아서 돌려 봤다.

NonsendingRestrict.swift

1
2
3
4
5
6
7
8
9
10
11
nonisolated(nonsending) func syncFunction() {}

@MainActor nonisolated(nonsending) func onMain() async {}

actor A {
  nonisolated(nonsending) func method() async {}
}

@concurrent nonisolated(nonsending) func both() async {}

nonisolated(nonsending) func withIsolatedParam(isolation: isolated (any Actor)?) async {}

기본 모드의 진단이다.

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
NonsendingRestrict.swift:1:1: error: cannot use 'nonisolated(nonsending)' on non-async global function 'syncFunction()'
 1 | nonisolated(nonsending) func syncFunction() {}
   | `- error: cannot use 'nonisolated(nonsending)' on non-async global function 'syncFunction()'
 2 | 
 3 | @MainActor nonisolated(nonsending) func onMain() async {}

NonsendingRestrict.swift:3:41: error: global function 'onMain()' has multiple actor-isolation attributes (@MainActor and 'nonisolated(nonsending)')
 1 | nonisolated(nonsending) func syncFunction() {}
 2 | 
 3 | @MainActor nonisolated(nonsending) func onMain() async {}
   |                                         `- error: global function 'onMain()' has multiple actor-isolation attributes (@MainActor and 'nonisolated(nonsending)')
 4 | 
 5 | actor A {

NonsendingRestrict.swift:9:1: error: global function 'both()' has multiple actor-isolation attributes (@concurrent and 'nonisolated(nonsending)')
 7 | }
 8 | 
 9 | @concurrent nonisolated(nonsending) func both() async {}
   | `- error: global function 'both()' has multiple actor-isolation attributes (@concurrent and 'nonisolated(nonsending)')
10 | 
11 | nonisolated(nonsending) func withIsolatedParam(isolation: isolated (any Actor)?) async {}

NonsendingRestrict.swift:11:1: error: cannot use 'nonisolated(nonsending)' on global function 'withIsolatedParam(isolation:)' because it has an isolated parameter: 'isolation'
 9 | @concurrent nonisolated(nonsending) func both() async {}
10 | 
11 | nonisolated(nonsending) func withIsolatedParam(isolation: isolated (any Actor)?) async {}
   | `- error: cannot use 'nonisolated(nonsending)' on global function 'withIsolatedParam(isolation:)' because it has an isolated parameter: 'isolation'
12 | 
[exit 1]

네 가지 오류와 통과하는 한 줄을 표로 정리한다. feature 를 켠 판도 같은 결과였다.

선언결과이유
nonisolated(nonsending) func syncFunction() {}error (1:1)동기 함수에는 쓸 수 없다
@MainActor nonisolated(nonsending) func onMain() async {}error (3:41)global actor 와 같이 못 쓴다
actor 안 nonisolated(nonsending) func method() async {}통과actor 안의 메서드에는 쓸 수 있다
@concurrent nonisolated(nonsending) func both() async {}error (9:1)@concurrent 와 같이 못 쓴다
isolation: isolated (any Actor)? parameter 가 있는 함수error (11:1)이미 isolated parameter 가 있다

한 가지 철자 순서도 확인했다. nonisolated(nonsending) @concurrent func 처럼 nonisolated(...) 를 attribute 앞에 쓰면 9:25: error: expected declaration 이라는 파싱 오류가 난다. attribute(@concurrent)는 modifier(nonisolated(...)) 앞에 와야 한다.


@concurrent

@concurrent 는 옛 동작의 명시 철자다. 이 함수는 항상 부른 쪽 actor 를 떠나 전역 executor 로 옮겨 가서 돈다. 제안서는 이것이 여러 일이 isolation 을 공유하지 않는다는 것을 보장하는 유일한 isolation 지정이라서 concurrent 라는 이름을 붙였다고 한다.

Concurrent.swift

1
2
3
4
5
6
7
8
9
10
11
12
extension NotSendable {
  @concurrent
  func alwaysSwitch() async {}
}

actor MyActor {
  let x = NotSendable()

  func call() async {
    await x.alwaysSwitch()
  }
}

actor 안의 상태 x 를 @concurrent 메서드에 보낸다. 기본 모드와 feature 를 켠 판 모두 같은 진단이 나온다.

1
2
3
4
5
6
7
8
9
10
11
12
Concurrent.swift:10:13: error: sending 'self.x' risks causing data races [#RegionIsolation::SendingRisksDataRace]
 8 | 
 9 |   func call() async {
10 |     await x.alwaysSwitch()
   |             |- error: sending 'self.x' risks causing data races [#RegionIsolation::SendingRisksDataRace]
   |             `- note: sending 'self'-isolated 'self.x' to @concurrent instance method 'alwaysSwitch()' risks causing data races between @concurrent and 'self'-isolated uses
11 |   }
12 | }

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

앞의 Motivation.swift 와 똑같은 오류이고 note 의 @concurrent 가 이제 직접 적은 철자다. 세 모드로 돌리면 Swift 5 는 진단 없음, complete 는 warning, Swift 6 은 error 이고, feature 를 켜도 error 가 그대로다. 아무 철자 없는 함수의 기본값을 바꾸는 feature 가 @concurrent 를 건드리지 않는다는 대조군이다.

제안서의 예는 non-Sendable 인자를 넘길 때다.

ConcurrentArg.swift

1
2
3
4
5
6
7
8
9
10
11
12
13
@concurrent
func alwaysSwitch(ns: NotSendable) async {}

actor MyActor {
  let ns: NotSendable = .init()

  func callConcurrent() async {
    await alwaysSwitch(ns: ns)

    let disconnected = NotSendable()
    await alwaysSwitch(ns: disconnected) // okay
  }
}

기본 모드와 feature 를 켠 판 모두 같은 진단이다.

1
2
3
4
5
6
7
8
9
10
11
12
ConcurrentArg.swift:8:11: error: sending 'self.ns' risks causing data races [#RegionIsolation::SendingRisksDataRace]
 6 | 
 7 |   func callConcurrent() async {
 8 |     await alwaysSwitch(ns: ns)
   |           |- error: sending 'self.ns' risks causing data races [#RegionIsolation::SendingRisksDataRace]
   |           `- note: sending 'self'-isolated 'self.ns' to @concurrent global function 'alwaysSwitch(ns:)' risks causing data races between @concurrent and 'self'-isolated uses
 9 | 
10 |     let disconnected = NotSendable()

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

actor 의 상태 self.ns 를 넘기는 8번째 줄만 막히고, 방금 만든 disconnected 를 넘기는 11번째 줄은 통과한다. 이 진단 하나만 나왔다는 것이 disconnected 줄이 통과했다는 뜻이다. 어느 actor 의 region 에도 들어 있지 않은 값은 @concurrent 에 넘겨도 되고, actor 가 아직 쥐고 있는 값은 안 된다. 이 규칙은 SE-0414 글의 region 규칙 그대로이고, @concurrent 는 sync nonisolated 에 쓰는 Sendable 검사를 그대로 받는다.

@concurrent 만 적으면 nonisolated 도 함께 뜻한다. 이것은 재리뷰에서 정해졌고, 철자 변천 절에서 다시 다룬다.

ConcurrentActor.swift

1
2
3
4
5
6
7
8
9
10
11
actor MyActor {
  var value = 0

  @concurrent
  func isolatedToSelf() async {
    value += 1
  }

  @concurrent
  nonisolated func canRunAnywhere() async {}
}

기본 모드와 feature 를 켠 판 모두 같은 진단이다.

1
2
3
4
5
6
7
8
9
10
11
12
13
ConcurrentActor.swift:6:5: error: actor-isolated property 'value' can not be mutated from a nonisolated context
 1 | actor MyActor {
 2 |   var value = 0
   |       `- note: mutation of this property is only permitted within the actor
 3 | 
 4 |   @concurrent
 5 |   func isolatedToSelf() async {
 6 |     value += 1
   |     |- error: actor-isolated property 'value' can not be mutated from a nonisolated context
   |     `- note: consider declaring an isolated method on 'MyActor' to perform the mutation
 7 |   }
 8 | 
[exit 1]

@concurrent 만 적은 isolatedToSelf() 는 nonisolated 라서 actor 의 value 를 바꾸지 못한다. 반면 @concurrent nonisolated func canRunAnywhere() 는 같이 적어도 받아들여진다. 이 진단은 isolatedToSelf() 한 곳에서만 나왔다. 제안서는 @concurrent 가 nonisolated 를 함의하고, 함께 적는 것도 선택이라고 적는다.

@concurrent 가 쓸 수 없는 자리도 한 파일에 모았다.

ConcurrentRestrict.swift

1
2
3
4
5
6
7
8
9
10
11
@MainActor @concurrent func runsOnMainActor() async {}

@concurrent func runsSomewhere(isolation: isolated (any Actor)?) async {}

func longCompute(fn: @concurrent @isolated(any) () async -> Void) async {}

@concurrent func syncFunction() {}

@concurrent func withSending(_ ns: sending NotSendable) async {}

let sendableFn: @Sendable @concurrent () async -> Void = {}

기본 모드의 진단이다.

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
ConcurrentRestrict.swift:1:29: error: global function 'runsOnMainActor()' has multiple actor-isolation attributes (@MainActor and @concurrent)
 1 | @MainActor @concurrent func runsOnMainActor() async {}
   |                             `- error: global function 'runsOnMainActor()' has multiple actor-isolation attributes (@MainActor and @concurrent)
 2 | 
 3 | @concurrent func runsSomewhere(isolation: isolated (any Actor)?) async {}

ConcurrentRestrict.swift:3:1: error: cannot use @concurrent on global function 'runsSomewhere(isolation:)' because it has an isolated parameter: 'isolation'
 1 | @MainActor @concurrent func runsOnMainActor() async {}
 2 | 
 3 | @concurrent func runsSomewhere(isolation: isolated (any Actor)?) async {}
   | `- error: cannot use @concurrent on global function 'runsSomewhere(isolation:)' because it has an isolated parameter: 'isolation'
 4 | 
 5 | func longCompute(fn: @concurrent @isolated(any) () async -> Void) async {}

ConcurrentRestrict.swift:5:23: error: cannot use '@concurrent' together with '@isolated(any)'
 3 | @concurrent func runsSomewhere(isolation: isolated (any Actor)?) async {}
 4 | 
 5 | func longCompute(fn: @concurrent @isolated(any) () async -> Void) async {}
   |                       `- error: cannot use '@concurrent' together with '@isolated(any)'
 6 | 
 7 | @concurrent func syncFunction() {}

ConcurrentRestrict.swift:7:1: error: cannot use @concurrent on non-async global function 'syncFunction()'
 5 | func longCompute(fn: @concurrent @isolated(any) () async -> Void) async {}
 6 | 
 7 | @concurrent func syncFunction() {}
   | `- error: cannot use @concurrent on non-async global function 'syncFunction()'
 8 | 
 9 | @concurrent func withSending(_ ns: sending NotSendable) async {}
[exit 1]

feature 를 켠 판도 같은 네 가지 오류다.

선언결과이유
@MainActor @concurrent func runsOnMainActor() async {}error (1:29)global actor 와 같이 못 쓴다
@concurrent func runsSomewhere(isolation: isolated (any Actor)?) async {}error (3:1)isolated parameter 가 있다
@concurrent @isolated(any) () async -> Voiderror (5:23)@isolated(any) 와 같이 못 쓴다
@concurrent func syncFunction() {}error (7:1)동기 함수에는 쓸 수 없다
@concurrent func withSending(_ ns: sending NotSendable) async {}통과sending 과는 쓸 수 있다
@Sendable @concurrent () async -> Void통과@Sendable 과는 쓸 수 있다

nonisolated(nonsending) 의 제약과 모양이 같다. 둘 다 global actor 와 isolated parameter 와 같이 못 쓰고 동기 함수에는 쓸 수 없고, 둘이 서로 같이 쓸 수도 없다. 동기 함수에는 쓸 수 없다는 제약은 제안서가 인위적인 제한이라서 나중에 풀 수도 있다고 적은 것이다. @concurrent 가 쓸 수 있는 것은 @Sendable 과 sending 이다. 재리뷰 #8 에서 hborla 가 accessor 에도 쓸 수 있다고 정리한 것도 있다. get 앞에 쓴다.

1
2
3
4
5
6
var x: Int {
  @concurrent
  get async {
    ...
  }
}

호출하는 쪽의 제약은 이렇다. @concurrent 함수를 actor 위에서 부를 수 있는 컨텍스트에서 부르면 인자와 결과가 Sendable 이거나 disconnected 여야 한다. 위 Concurrent.swift 와 ConcurrentArg.swift 의 진단이 그 제약이 걸린 모습이다.


#isolation 이 가리키는 것

앞의 Where.swift 실행 결과에는 #isolation 열이 따로 있었다. 철자별로 #isolation 이 무엇으로 펼쳐지는지를 정리한다.

함수#isolation6.4 의 Where 측정
nonisolated(nonsending) async암시적 isolated parameterOptional(Swift.MainActor)
철자 없는 async, 기본nilnil
철자 없는 async, feature 를 켠 판암시적 isolated parameterOptional(Swift.MainActor)
@concurrent asyncnilnil
동기 nonisolatednilnil

제안서는 nonsending 함수 안의 #isolation 이 암시적 isolated parameter 로 펼쳐지고, 동기 nonisolated 함수와 @concurrent 함수 안에서는 nil 이라고 적는다. 제안서의 예는 nonisolated func printIsolation() async 가 feature 를 켠 판에서 Optional(Swift.MainActor) 를 찍는다는 것인데, 위 표의 세 번째 줄이 그 측정이다. 동기 함수가 nil 인 것은 앞에서 본 대로 암시적 isolated parameter 가 없어서다.

이 암시적 parameter 가 옛 isolated #isolation API 로 흘러 들어가는 것이 중요해진다. 리뷰 #37(ktoso)는 @execution(caller) 함수 안의 #isolation 을 옛 isolated #isolation API 로 넘기면 nil 로 찍혀서 isolation 이 사라지고, 그 뒤 “Incorrect actor executor assumption” 이 난다고 보고했다. 리뷰 #38(hborla)은 이것이 컴파일러 버그일 뿐이라고 답했다. #isolation 이 암시적 actor parameter 가 추가되기 전에 펼쳐진 것이고, SILGen 에서 펼치도록 고친다고 한다. 6.4 에서 측정하면 위 표대로 nonsendingAsync() 의 #isolation 이 Optional(Swift.MainActor) 다.


Task 의 isolation 상속 여부

nonsending 함수가 부른 쪽 actor 에서 돈다고 해서 그 안에서 만든 Task {} 가 같은 actor 를 물려받는 것은 아니다. 제안서는 어떤 nonisolated 함수(동기, nonsending, @concurrent)에서든 비구조적 Task {} 가 isolation 을 물려받지 않는다고 적는다. 동기 nonisolated 함수와 같은 규칙이고, isolated parameter 를 가진 메서드가 그 parameter 를 캡처하지 않을 때와도 같다.

TaskInherit.swift

1
2
3
4
5
6
nonisolated(nonsending)
func createTask(ns: NotSendable) async {
  Task {
    ns.value += 1
  }
}

기본 모드와 feature 를 켠 판 모두 같은 진단이다.

1
2
3
4
5
6
7
8
9
10
11
12
13
TaskInherit.swift:3:3: error: passing closure as a 'sending' parameter risks causing data races between code in the current isolation context and concurrent execution of the closure [#RegionIsolation::SendingClosureRisksDataRace]
1 | nonisolated(nonsending)
2 | func createTask(ns: NotSendable) async {
3 |   Task {
  |   `- error: passing closure as a 'sending' parameter risks causing data races between code in the current isolation context and concurrent execution of the closure [#RegionIsolation::SendingClosureRisksDataRace]
4 |     ns.value += 1
  |     `- note: closure captures 'ns' which is accessible to code in the current isolation context
5 |   }
6 | }

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

Task 의 operation 은 sending parameter 라서(SE-0430), 클로저가 캡처한 ns 가 호출한 쪽의 isolation 컨텍스트에서 아직 접근 가능한 값이면 넘길 수 없다. 함수가 부른 쪽 actor 에서 돌더라도 안에서 만든 Task 는 그 actor 를 이어받지 않기 때문에 ns 를 보내는 것으로 취급된다. 두 판의 진단이 같으므로 이 규칙은 feature 와 상관없다.


클로저의 isolation 추론

제안서는 클로저의 isolation 추론 규칙을 처음 문서로 적는다고 설명한다. 새 규칙이 아니라 이미 컴파일러가 하던 일을 글로 남긴 것이다. 피치 #1(hborla)도 클로저 isolation 추론과 함수 변환 규칙이 어디에도 문서로 쓰여 있지 않다고 말한다. 규칙은 세 줄이다.

  1. 클로저의 contextual type 이 @Sendable 도 sending 도 아니면 클로저는 둘러싼 컨텍스트의 isolation 을 가진다.
  2. contextual type 이 @Sendable 이거나 sending 이면 클로저는 nonisolated 다.
  3. 둘러싼 컨텍스트에 isolated parameter 가 있고(self 포함) 클로저가 그것을 명시적으로 캡처하지 않으면 클로저는 nonisolated 다. 보이지 않는 캡처와 참조 순환을 막으려는 것이다.

먼저 컴파일 진단으로 본다.

Closures.swift

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
@MainActor
func closureOnMain(ns: NotSendable) async {
  let syncClosure: () -> Void = {
    print(ns)
  }
  syncClosure()

  let asyncClosure: (NotSendable) async -> Void = {
    print($0)
  }
  await asyncClosure(ns)
}

@MainActor
func sendableClosure(ns: NotSendable) async {
  let closure: @Sendable () async -> Void = {
    print(ns)
  }
  await closure()
}

기본 모드의 진단이다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Closures.swift:17:11: error: capture of 'ns' with non-Sendable type 'NotSendable' in a '@Sendable' closure [#SendableClosureCaptures]
15 | func sendableClosure(ns: NotSendable) async {
16 |   let closure: @Sendable () async -> Void = {
17 |     print(ns)
   |           `- error: capture of 'ns' with non-Sendable type 'NotSendable' in a '@Sendable' closure [#SendableClosureCaptures]
18 |   }
19 |   await closure()

Common.swift:1:7: note: class 'NotSendable' does not conform to the 'Sendable' protocol
1 | class NotSendable {
  |       `- note: class 'NotSendable' does not conform to the 'Sendable' protocol
2 |   var value = 0
3 |   init() {}

[#SendableClosureCaptures]: <https://docs.swift.org/compiler/documentation/diagnostics/sendable-closure-captures>
[exit 1]

feature 를 켠 판도 같다. @MainActor 함수 안에서 @Sendable 이 아닌 두 클로저(동기, async)는 통과하고 main actor 의 isolation 을 가진다. non-Sendable 인 ns 를 캡처할 수 있기 때문이다. @Sendable 클로저만 17번째 줄에서 막힌다. 오류가 이 한 줄뿐이라는 것이 앞 두 클로저가 통과했다는 뜻이다.

컴파일만으로는 “어느 isolation 으로 추론됐는지” 가 안 보여서, 클로저 안에서 #isolation 을 찍어 확인했다.

ClosureIso.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
func show(_ label: String, _ isolation: (any Actor)?) {
  print("\(label)  #isolation = \(String(describing: isolation))")
}

@MainActor
func closureIsolation() async {
  let syncClosure: () -> Void = {
    show("sync closure     ", #isolation)
  }
  syncClosure()

  let asyncClosure: () async -> Void = {
    show("async closure    ", #isolation)
  }
  await asyncClosure()

  let sendableClosure: @Sendable () async -> Void = {
    show("@Sendable closure", #isolation)
  }
  await sendableClosure()
}

@main
struct Program {
  static func main() async {
    await closureIsolation()
  }
}
1
xcrun swiftc -parse-as-library -swift-version 6 Common.swift ClosureIso.swift -o closureiso

기본 Swift 6 의 실행 결과다.

1
2
3
sync closure       #isolation = Optional(Swift.MainActor)
async closure      #isolation = Optional(Swift.MainActor)
@Sendable closure  #isolation = nil

NonisolatedNonsendingByDefault 를 켠 판(closureiso-feat)의 실행 결과다.

1
2
3
sync closure       #isolation = Optional(Swift.MainActor)
async closure      #isolation = Optional(Swift.MainActor)
@Sendable closure  #isolation = Optional(Swift.MainActor)

두 판의 바뀐 줄은 세 번째 하나다. 제안서의 규칙 2 대로 @Sendable 클로저는 nonisolated 로 추론되어 기본에서 nil 이다. feature 를 켜면 그 클로저의 타입이 철자 없는 async 함수 타입이라서 nonsending 으로 읽히고, nonsending 함수 안의 #isolation 은 암시적 actor parameter 이므로 부른 쪽 actor 인 main actor 가 찍힌다. 클로저가 nonisolated 로 추론되는 것과 그 클로저가 부른 쪽 actor 에서 도는 것은 서로 다른 이야기라는 점이 이 두 측정으로 분리된다. 앞의 두 클로저는 두 판 모두 main actor 이므로 규칙 1 이 feature 에 영향받지 않는 쪽이다.


함수 변환

isolation 이 다른 함수 타입끼리 바꿔 넣는 변환에도 규칙이 있다. 제안서는 변환을 “새 isolation 을 가진 클로저가 원래 함수를 await 로 부르는 것” 으로 생각하라고 설명한다. 그러면 isolation 이 바뀌는 변환은 두 isolation 의 경계를 건너는 호출이 되고, 경계를 건너려면 인자와 결과가 Sendable 이거나 disconnected 여야 하고 도착 쪽이 async 여야 한다.

제안서의 변환 표 13줄을 그대로 옮긴다. 동기 nonisolated 와 nonisolated(nonsending) 은 표에서 한 줄로 합쳐 “Nonisolated” 로 쓴다.

기존 isolation새 isolation경계를 넘는가
NonisolatedActor isolated아니오
Nonisolated@isolated(any)아니오
Nonisolated@concurrent아니오
Actor isolatedActor isolated예
Actor isolated@isolated(any)아니오
Actor isolatedNonisolated예
Actor isolated@concurrent예
@isolated(any)Actor isolated예
@isolated(any)Nonisolated예
@isolated(any)@concurrent예
@concurrentActor isolated예
@concurrent@isolated(any)아니오
@concurrentNonisolated예

첫 줄이 눈에 띈다. nonisolated 함수를 actor isolated 함수 타입으로 바꾸는 것이 경계를 넘지 않는다. nonsending 함수는 부른 쪽 actor 에서 도니까, 새 isolation 이 actor 라면 그 actor 에서 그대로 돌 뿐이다. 반대로 “Actor isolated 에서 Nonisolated” 는 경계를 넘는다고 적혀 있다. 이 줄은 아래 ConversionsClosure 에서 본다.

여섯 가지를 직접 돌려 봤다. 먼저 경계를 넘지 않는 첫 줄이다.

ConversionsOK.swift

1
2
3
4
5
6
7
8
9
nonisolated(nonsending)
func performAsync(_ ns: NotSendable) async {}

@MainActor
func convert(ns: NotSendable) async {
  let runOnMain: @MainActor (NotSendable) async -> Void = performAsync

  await runOnMain(ns)
}

nonisolated(nonsending) 함수를 @MainActor 함수 타입으로 바꾸고 main actor 에서 non-Sendable ns 를 넘긴다. 기본 모드와 feature 를 켠 판 모두 진단이 없다.

1
[exit 0]

경계를 넘지 않으니 non-Sendable 인자를 넘겨도 된다는 것이 확인된다. 이 변환은 새 isolation 이 main actor 라서 await runOnMain(ns) 가 main actor 에서 부르는 것과 같다.

제안서는 경계를 넘는 예로 actor 의 메서드를 nonisolated 함수 타입으로 꺼내는 것을 든다.

Conversions.swift

1
2
3
4
5
6
7
8
9
10
11
actor MyActor {
  var ns = NotSendable()

  func getState() -> NotSendable { ns }
}

func invalidResult(a: MyActor) async -> NotSendable {
  let grabActorState: nonisolated(nonsending) () async -> NotSendable = a.getState

  return await grabActorState()
}

기본 모드의 진단이다.

1
2
3
4
5
6
7
8
Conversions.swift:8:75: error: actor-isolated instance method 'getState()' can not be partially applied
 6 | 
 7 | func invalidResult(a: MyActor) async -> NotSendable {
 8 |   let grabActorState: nonisolated(nonsending) () async -> NotSendable = a.getState
   |                                                                           `- error: actor-isolated instance method 'getState()' can not be partially applied
 9 | 
10 |   return await grabActorState()
[exit 1]

feature 를 켠 판도 같은 줄에 같은 오류다. 다른 actor 인스턴스의 메서드를 부분 적용으로 꺼내는 것 자체가 막혀서, 변환 규칙까지 가지 못한다. 같은 일을 클로저로 쓰면 변환 규칙이 만드는 오류가 나온다.

ConversionsClosure.swift

1
2
3
4
5
6
7
8
9
10
11
12
13
actor MyActor {
  var ns = NotSendable()

  func getState() -> NotSendable { ns }
}

func invalidResult(a: MyActor) async -> NotSendable {
  let grabActorState: nonisolated(nonsending) () async -> NotSendable = {
    await a.getState()
  }

  return await grabActorState()
}

기본 모드의 진단이다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
ConversionsClosure.swift:9:13: error: non-Sendable 'NotSendable'-typed result can not be returned from actor-isolated instance method 'getState()' to caller isolation inheriting-isolated context [#RegionIsolation]
 7 | func invalidResult(a: MyActor) async -> NotSendable {
 8 |   let grabActorState: nonisolated(nonsending) () async -> NotSendable = {
 9 |     await a.getState()
   |             `- error: non-Sendable 'NotSendable'-typed result can not be returned from actor-isolated instance method 'getState()' to caller isolation inheriting-isolated context [#RegionIsolation]
10 |   }
11 | 

Common.swift:1:7: note: class 'NotSendable' does not conform to the 'Sendable' protocol
1 | class NotSendable {
  |       `- note: class 'NotSendable' does not conform to the 'Sendable' protocol
2 |   var value = 0
3 |   init() {}

[#RegionIsolation]: <https://docs.swift.org/compiler/documentation/diagnostics/region-isolation>
[exit 1]

feature 를 켠 판의 진단이다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
ConversionsClosure.swift:9:13: error: non-Sendable 'NotSendable'-typed result can not be returned from actor-isolated instance method 'getState()' to nonisolated context [#RegionIsolation]
 7 | func invalidResult(a: MyActor) async -> NotSendable {
 8 |   let grabActorState: nonisolated(nonsending) () async -> NotSendable = {
 9 |     await a.getState()
   |             `- error: non-Sendable 'NotSendable'-typed result can not be returned from actor-isolated instance method 'getState()' to nonisolated context [#RegionIsolation]
10 |   }
11 | 

Common.swift:1:7: note: class 'NotSendable' does not conform to the 'Sendable' protocol
1 | class NotSendable {
  |       `- note: class 'NotSendable' does not conform to the 'Sendable' protocol
2 |   var value = 0
3 |   init() {}

[#RegionIsolation]: <https://docs.swift.org/compiler/documentation/diagnostics/region-isolation>
[exit 1]

오류가 나는 줄과 칸은 두 판이 같고 도착 지점을 부르는 문구만 다르다. 기본 모드는 “to caller isolation inheriting-isolated context” 라고, feature 를 켠 판은 “to nonisolated context” 라고 부른다. 두 문구가 가리키는 곳은 같은 클로저 안이다. 변환의 결과를 보면, actor 의 getState() 가 돌려준 non-Sendable 값을 nonsending 클로저가 돌려보내려는 것이다. actor 에 묶인 ns 가 invalidResult 를 부른 쪽으로 나가므로, 제안서가 이 예를 “invalid” 라고 부른 이유와 맞는다. 표의 “Actor isolated 에서 Nonisolated” 가 경계를 넘는 변환이라는 줄이 오류로 나타난 장면이다.

제안서는 non-@Sendable 함수의 변환을 region 으로 검사한다고 말한다. 같은 클래스의 변환을 valid 와 invalid 로 나눈 예가 있다.

ConversionsRegion.swift

1
2
3
4
5
6
7
8
9
10
11
12
nonisolated(nonsending)
func convert(closure: () -> Void) async {
  let ns = NotSendable()
  let disconnectedClosure = {
    ns.value += 1
  }
  let valid: @MainActor () -> Void = disconnectedClosure // okay
  await valid()

  let invalid: @MainActor () -> Void = closure
  await invalid()
}

제안서는 7번째 줄을 okay 로, 10번째 줄을 invalid 로 적는다. 기본 모드와 feature 를 켠 판의 진단이 같다.

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
ConversionsRegion.swift:7:38: error: converting non-Sendable function value to '@MainActor @Sendable () -> Void' may introduce data races
 5 |     ns.value += 1
 6 |   }
 7 |   let valid: @MainActor () -> Void = disconnectedClosure // okay
   |                                      `- error: converting non-Sendable function value to '@MainActor @Sendable () -> Void' may introduce data races
 8 |   await valid()
 9 | 

ConversionsRegion.swift:10:40: error: using non-Sendable parameter 'closure' in a context expecting a '@Sendable' closure
 1 | nonisolated(nonsending)
 2 | func convert(closure: () -> Void) async {
   |              `- note: parameter 'closure' is implicitly non-Sendable
 3 |   let ns = NotSendable()
 4 |   let disconnectedClosure = {
   :
 8 |   await valid()
 9 | 
10 |   let invalid: @MainActor () -> Void = closure
   |                                        `- error: using non-Sendable parameter 'closure' in a context expecting a '@Sendable' closure
11 |   await invalid()
12 | }

ConversionsRegion.swift:10:40: error: using non-escaping parameter 'closure' in a context expecting an '@escaping' closure
 1 | nonisolated(nonsending)
 2 | func convert(closure: () -> Void) async {
   |              `- note: parameter 'closure' is implicitly non-escaping
 3 |   let ns = NotSendable()
 4 |   let disconnectedClosure = {
   :
 8 |   await valid()
 9 | 
10 |   let invalid: @MainActor () -> Void = closure
   |                                        `- error: using non-escaping parameter 'closure' in a context expecting an '@escaping' closure
11 |   await invalid()
12 | }
[exit 1]

세 가지 오류가 나왔다. 7번째 줄에서 오류가 난다. 오류 문구가 목적지 타입을 @MainActor @Sendable () -> Void 로 부른다. 10번째 줄에는 오류가 둘이다. non-Sendable parameter closure 를 @Sendable 클로저가 기대되는 자리에 썼다는 것과, non-escaping parameter 를 @escaping 이 기대되는 자리에 썼다는 것이다. 두 줄은 region 검사에 앞서 Sendable 검사와 escaping 검사에서 걸렸다. 목적지 타입이 @MainActor @Sendable 로 읽혔다는 것이 측정된 사실이고, @MainActor 가 붙은 함수 타입이 어떤 Sendable 규칙을 갖는지는 SE-0434 글에서 다뤘다.

두 번째 변환 예는 @concurrent 에서 @MainActor 로 바꾸는 것이다.

ConversionsConcurrent.swift

1
2
3
4
5
6
7
8
9
10
11
nonisolated(nonsending)
func convert(
    fn1: @escaping @concurrent () async -> Void,
) async {
    let fn2: @MainActor () async -> Void = fn1

    await withDiscardingTaskGroup { group in
      group.addTask { await fn2() }
      group.addTask { await fn2() }
    }
}

withDiscardingTaskGroup 은 자식 task 의 결과를 모으지 않고 버리는 task group 이고, addTask 로 같은 fn2 를 두 task 가 동시에 부른다. 제안서는 이 변환을 오류로 든다. fn1 은 @concurrent 라서 부르려면 main actor 를 떠나야 하는데 @Sendable 이 아니어서, 두 자식 task 가 fn2 를 거쳐 fn1 을 동시에 부를 수 있기 때문이다. 기본 모드와 feature 를 켠 판의 진단이 같다.

1
2
3
4
5
6
7
8
9
10
11
ConversionsConcurrent.swift:5:44: error: using non-Sendable parameter 'fn1' in a context expecting a '@Sendable' closure
 1 | nonisolated(nonsending)
 2 | func convert(
 3 |     fn1: @escaping @concurrent () async -> Void,
   |     `- note: parameter 'fn1' is implicitly non-Sendable
 4 | ) async {
 5 |     let fn2: @MainActor () async -> Void = fn1
   |                                            `- error: using non-Sendable parameter 'fn1' in a context expecting a '@Sendable' closure
 6 | 
 7 |     await withDiscardingTaskGroup { group in
[exit 1]

오류는 fn1 이 @Sendable 이 아니라는 것이고 5번째 줄 한 곳이다. 위 ConversionsRegion 과 같은 이유로, 변환의 목적지 @MainActor () async -> Void 가 @Sendable 을 기대하는 자리로 읽힌다. 이 오류만 나온 것은 Sendable 검사가 먼저 걸리기 때문이다.

마지막 예는 actor 에 묶인 함수를 non-@Sendable nonisolated 함수로 바꾸는 것이다. 제안서는 이 변환이 허용되고, 변환된 함수가 그 actor 의 region 으로 합쳐진다고 설명한다.

ConversionsOnActor.swift

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@MainActor class C {
  var ns: NotSendable = NotSendable()

  func getState() -> NotSendable { ns }
}

func call(_ closure: () -> NotSendable) -> NotSendable {
  return closure()
}

@MainActor func onMain(c: C) {
  let result = call(c.getState)
  print(result.value)
}

call 은 non-Sendable 인 closure 를 부르는 동기 nonisolated 함수다. main actor 의 c.getState 가 그 자리에 들어간다. 기본 모드와 feature 를 켠 판 모두 진단이 없다.

1
[exit 0]

변환된 클로저가 @Sendable 이 아니라서 call 이 그것을 main actor 밖으로 보내지 않고, 결과 result 는 c 와 같은 region 이라서 main actor 위에서 result.value 를 읽을 수 있다. 앞의 ConversionsClosure 에서는 actor 의 상태가 non-Sendable 결과로 actor 밖에 나갔고, 이 예에서는 변환된 함수와 결과가 모두 main actor 의 region 에 머문다. 같은 “actor isolated 에서 nonisolated” 변환이 앞에서는 막히고 여기서는 통과하는 차이가 이것이다.


region 규칙

nonsending 함수는 암시적 isolated parameter 가 있는데, 이 parameter 를 가진 함수와 region 규칙은 다르다. 제안서는 nonisolated 함수와 같은 규칙을 쓴다고 정한다. 인자와 결과가 하나의 region 으로 합쳐지고, 그 region 이 actor 의 region 에 합쳐지는 것은 인자 중 하나가 이미 actor 의 region 에 있을 때뿐이다. 리뷰 #36 에서 hborla 가 이 규칙을 identity 예로 설명한 것을 제안서가 링크한다.

Region.swift

1
2
3
4
5
6
7
8
9
10
11
nonisolated(nonsending)
func identity<T>(_ t: T) async -> T {
  return t
}

actor MyActor {
  func isolatedToSelf() async -> sending NotSendable {
    let ns = NotSendable()
    return await identity(ns)
  }
}

isolatedToSelf() 는 actor 안에서 방금 만든 ns 를 identity 에 넘기고, 결과를 sending 으로 돌려준다. ns 는 어느 actor 의 region 에도 없는 disconnected 값이다. nonisolated 함수처럼 인자와 결과만 하나의 region 으로 합칠 뿐 actor 의 region 에 합치지 않으므로, 결과도 disconnected 이고 sending 으로 돌려줄 수 있다. 기본 모드와 feature 를 켠 판 모두 진단이 없다.

1
[exit 0]

제안서는 identity 가 isolated parameter 를 받았다면 이 코드는 invalid 라고 적는다. 같은 identity 를 SE-0420 방식의 isolation: isolated (any Actor)? = #isolation 으로 바꿔서 돌려 봤다.

RegionIsolatedParam.swift

1
2
3
4
5
6
7
8
9
10
func identity<T>(_ t: T, isolation: isolated (any Actor)? = #isolation) async -> T {
  return t
}

actor MyActor {
  func isolatedToSelf() async -> sending NotSendable {
    let ns = NotSendable()
    return await identity(ns)
  }
}

기본 모드의 진단이다.

1
2
3
4
5
6
7
8
9
10
RegionIsolatedParam.swift:8:5: error: task or actor-isolated value cannot be sent [#RegionIsolation]
 6 |   func isolatedToSelf() async -> sending NotSendable {
 7 |     let ns = NotSendable()
 8 |     return await identity(ns)
   |     `- error: task or actor-isolated value cannot be sent [#RegionIsolation]
 9 |   }
10 | }

[#RegionIsolation]: <https://docs.swift.org/compiler/documentation/diagnostics/region-isolation>
[exit 1]

feature 를 켠 판도 같다. isolated parameter 를 받는 함수는 인자와 결과가 actor 의 region 으로 합쳐지고, 그 결과를 sending 으로 돌려주는 8번째 줄이 막힌다. 앞의 Region.swift 와 이 파일의 차이는 identity 가 isolated parameter 를 받는가 하나뿐이다. nonsending 은 암시적 actor parameter 를 쓰더라도 region 규칙은 nonisolated 쪽을 따른다는 것이 이 대조에서 보인다. 제안서는 #isolation 을 isolated (any Actor)? parameter 에 그대로 넘길 수는 있다고 적는다.

그렇다면 actor 의 상태를 넘기면 어떻게 되는가.

RegionActorState.swift

1
2
3
4
5
6
7
8
9
10
11
12
nonisolated(nonsending)
func identity<T>(_ t: T) async -> T {
  return t
}

actor MyActor {
  let state = NotSendable()

  func leak() async -> sending NotSendable {
    return await identity(state)
  }
}

기본 모드의 진단이다.

1
2
3
4
5
6
7
8
9
10
RegionActorState.swift:10:5: error: task or actor-isolated value cannot be sent [#RegionIsolation]
 8 | 
 9 |   func leak() async -> sending NotSendable {
10 |     return await identity(state)
   |     `- error: task or actor-isolated value cannot be sent [#RegionIsolation]
11 |   }
12 | }

[#RegionIsolation]: <https://docs.swift.org/compiler/documentation/diagnostics/region-isolation>
[exit 1]

feature 를 켠 판도 같다. state 는 actor 의 region 에 있는 값이라서, nonsending 함수를 거쳐 돌아온 결과도 같은 region 에 남는다. 그것을 sending 으로 돌려주려는 10번째 줄이 막힌다. 앞의 Region.swift 가 disconnected ns 를 넘겨 통과한 것과 대조된다. 규칙은 하나다. 결과가 actor 의 region 에 합쳐지는 것은 인자 중 하나가 이미 그 region 에 있을 때뿐이다.


실행기 전환과 task executor preference

이 절은 제안서 설명을 옮긴 것이다. nonisolated async 함수가 어디서 돌지는 선언한 철자로 결정된다.

  • @concurrent 함수는 부르는 순간 generic executor 로 옮겨 간다.
  • nonisolated(nonsending) 함수는 암시적 isolated parameter 로 받은 actor 의 executor 로 옮겨 간다(이미 그 actor 위에 있으면 옮겨 갈 필요가 없다).
  • task executor preference 는 여전히 적용될 수 있다. 부르는 쪽이 custom executor 를 가진 actor 일 때를 제외한다.

리뷰 #20(FranzBusch)이 이 결정을 의사결정 순서로 정리한 것이 읽기 쉽다. 먼저 isolation 을 확인하고, 그다음 custom executor 를 보고, task executor preference 를 보고, 마지막으로 전역 기본 executor 를 쓴다는 순서다. 같은 글은 task executor preference 가 버려지는 것이 아니라 평가되지 않는 것이라고도 설명한다. 이 순서 설명은 SE-0417 의 task executor preference 와 맞물려 있으니, 그 제안서를 읽었다면 이 절은 짧게 지나가도 된다.


동적 isolation API

nonsending 함수는 부른 쪽 actor 위에서 도니까, 그 위에서 isolation 을 단언하는 API 가 의미를 갖는다. 제안서는 Actor 와 MainActor 의 assertIsolated, assumeIsolated, preconditionIsolated 에서 noasync 를 없앤다고 적는다. nonsending 함수가 async 이면서 부른 쪽 actor 를 알기 때문이다. 먼저 preconditionIsolated 를 실행해 본다.

AssumeIsolated.swift

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
nonisolated(nonsending) func check() async {
  MainActor.preconditionIsolated()
  print("check(): on the main actor")
}

@concurrent func checkConcurrent() async {
  MainActor.preconditionIsolated()
  print("never printed")
}

@main
struct Program {
  static func main() async {
    await check()
    if CommandLine.arguments.count > 1 {
      await checkConcurrent()
    }
  }
}

MainActor.preconditionIsolated() 는 지금 코드가 main actor 위에서 돌고 있는지 단언하고, 아니면 프로그램을 멈춘다. 컴파일은 진단 없이 끝난다.

1
xcrun swiftc -parse-as-library -swift-version 6 Common.swift AssumeIsolated.swift -o assume

인자 없이 실행하면 check() 만 부른다.

1
2
check(): on the main actor
[exit 0]

nonisolated(nonsending) 인 check() 안에서 preconditionIsolated() 가 통과했다. check() 가 main actor 에서 부른 쪽 isolation 으로 돌고 있다는 뜻이다. 인자를 하나 주면 @concurrent 인 checkConcurrent() 도 부르고, 이 함수는 전역 executor 위에 있으니 단언이 실패한다.

1
bash -c './assume crash; echo $?'
1
2
bash: line 1: 88825 Trace/BPT trap: 5       ./assume crash
133

프로세스가 Trace/BPT trap: 5 로 죽고 종료 코드는 133 이다. 이 실행에서는 check() 의 출력 줄이 보이지 않는다. stdout 이 pipe 라서 buffer 에 있던 줄이 crash 와 함께 버려졌기 때문이고, 터미널에서 직접 돌리면 trap 앞에 check(): on the main actor 가 찍힌다. 두 실행의 차이는 checkConcurrent() 를 부르는가 하나뿐이다. nonisolated(nonsending) 인 check() 는 main actor 에서 부르면 preconditionIsolated() 가 통과하고, @concurrent 인 checkConcurrent() 는 같은 단언에서 프로그램을 멈춘다는 구분을 이 실행이 보여 준다.

assumeIsolated 도 nonsending 함수 안에서 쓸 수 있는지 확인했다.

AssumeIsolatedAsync.swift

1
2
3
4
5
nonisolated(nonsending) func check() async {
  MainActor.assumeIsolated {
    print("assumeIsolated")
  }
}

기본 모드와 feature 를 켠 판의 진단이 같다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
AssumeIsolatedAsync.swift:2:13: error: static method 'assumeIsolated' is unavailable from asynchronous contexts; await the call to the @MainActor closure directly
1 | nonisolated(nonsending) func check() async {
2 |   MainActor.assumeIsolated {
  |             `- error: static method 'assumeIsolated' is unavailable from asynchronous contexts; await the call to the @MainActor closure directly
3 |     print("assumeIsolated")
4 |   }

_Concurrency.MainActor.assumeIsolated:3:22: note: 'assumeIsolated(_:file:line:)' declared here
1 | actor MainActor {
2 | @available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
3 |   public static func assumeIsolated<T>(_ operation: @MainActor () throws -> T, file: StaticString = #fileID, line: UInt = #line) rethrows -> T where T : Sendable}
  |                      `- note: 'assumeIsolated(_:file:line:)' declared here
4 | 
[exit 1]

preconditionIsolated 는 같은 async 함수 안에서 컴파일되지만, SDK 의 assumeIsolated 에는 @_unavailableFromAsync 가 붙어 있어서 async 컨텍스트에서 쓸 수 없다. 1차 리뷰 뒤 수정 수락 때 붙은 수정 사항 네 가지 중 하나가 이 계열 API 의 noasync 제거였다.


Objective-C 에서 가져온 async 함수

이 절도 제안서 설명이다. Objective-C 함수가 SE-0297 의 heuristic 에 맞으면 async 함수로 가져와지는데, 이 함수는 nonisolated(nonsending) 으로 가져온다. 이 변경은 NonisolatedNonsendingByDefault 뒤에 있지 않다. 이미 Objective-C 의 async 함수는 부른 쪽 actor 에서 이어서 돌고 있었고, 이 변경은 불필요한 진단을 없애는 것이라서 feature 에 묶을 이유가 없다는 것이 제안서의 설명이다.


철자는 어떻게 정해졌나

이 제안의 본체는 동작보다 철자였다. 같은 동작을 가리키는 이름이 피치에서 재리뷰까지 두 번 바뀌었고, 포럼 글의 상당 부분이 철자 이야기다. 먼저 흐름을 한 장으로 본다.

철자가 피치의 @concurrent 에서 1차 리뷰의 @execution 둘을 거쳐 최종 @concurrent 와 nonisolated(nonsending) 으로 정해진 과정과 각 단계의 날짜

단계시기옛 동작을 가리키는 철자새 동작을 가리키는 철자
pitch2024-09-22@concurrent철자 없음 (피치 초안은 flag 없이 기본값 자체를 바꾸는 안이었다)
피치 뒤 개정1차 리뷰 때의 제안서@execution(concurrent)@execution(caller)
1차 리뷰 뒤 개정2025-03-28 수정 수락@concurrentnonisolated(nonsending)
재리뷰2025-04-04 까지@concurrentnonisolated(nonsending)
최종 수락2025-04-05@concurrent (nonisolated 를 함의)nonisolated(nonsending)

피치 때의 철자는 @concurrent 하나였고, 피치 뒤 개정에서 제안서가 @execution(concurrent) 와 @execution(caller) 를 만들어 두 동작에 같은 base attribute 를 줬다. 이때 upcoming feature flag 도 붙었고(당시 이름은 AsyncCallerExecution, 지금의 NonisolatedNonsendingByDefault), 함수 값의 기본값도 바뀌도록 했으며, “isolation 을 물려받는다” 는 표현을 제안서에서 뺐다. 1차 리뷰 뒤에 철자가 @concurrent 와 nonisolated(nonsending) 으로 갈렸다.


피치의 반응

피치는 hborla 의 #1 로 2024-09-22 23:38 UTC 에 올라왔고, 제목은 Pitch: Inherit isolation by default for async functions 다. #131 이 빠져 있어서 글은 175개다. 첫 글은 현재 동작이 main actor 의 응답성을 얻는 대신 사용성을 내준다고 요약하고, 클로저 isolation 추론과 함수 변환 규칙이 어디에도 글로 적혀 있지 않다고 쓴다. 이 두 줄이 제안서 Introduction 과 클로저, 함수 변환 절의 출발점이다.

반응은 크게 세 갈래였다.

기본값을 뒤집으면 위험하다는 쪽. Jumhyn(#2, 2024-09-23)은 SE-0338 에 기대서 async 함수를 썼다고 말하면서, 기본값을 뒤집으면 위험하다고 했다. 이 규칙이 cooperative thread pool 로 일을 내보내는 매우 편한 방법이었다는 것이다. 중단점(suspension point)이 있으면서 무거운 계산을 하는 함수가 SE-0338 에 기대고 있는지는 가려낼 방법이 바로 떠오르지 않는다는 점이 더 걱정된다고 했다. nkbelov(#55)는 SE-0338 을 기본값으로 유지하자는 쪽이었다. 자기 앱 코드의 90% 가 그 규칙에 기대고 있다고 하면서, actor 안의 cache 나 queue 에 필요한 “제3의 모드” 가 빈다는 점과, isolation: ... 쪽의 ergonomics 가 불균형하다는 점도 썼다. jhammer(#58)는 선언만 보고 지역적으로 추론할 수 있는 성질이 좋다고 했다. saagarjha(#4)는 +1 을 쓰면서도 @concurrent 라는 키워드가 너무 많은 뜻으로 쓰인다는 이유로 -0.25 를 줬고, 이 변화의 결과를 “이제 정의된 컨텍스트에서 돈다” 와 “프로덕션에서 나는 race condition” 의 비교로 설명했다.

기본값이 놀랍다는 쪽. tclementdev(#19)는 호출자의 isolation 을 떠나는 동작이 개발자들에게 지금까지도 충격이라고 썼다. 실제 앱에서 어떤 함수가 async 인 이유는 다른 async 함수를 await 하기 때문일 뿐인 경우가 많다고 하면서, Task 도 현재 isolation 을 재사용해야 한다고 했다. 마이그레이션 도구가 @concurrent 를 붙여 줄 수 있느냐고도 물었다. 이 질문은 제안서의 마이그레이션 도구 이야기로 이어졌다.

실행 모델을 짚는 쪽. John_McCall(#52)은 대부분의 계산이 cooperative thread pool 위에 있어야 하고, 임의로 스레드를 더 만들어서는 안 되며, 긴 계산은 주기적으로 양보해야 한다고 썼다. hborla(#66)는 upcoming feature 로 게이트하는 것을 한 가지 선택지로 꺼냈고, 어느 쪽이든 마이그레이션 도구가 필요하며, cooperative pool 로 편하게 offload 하는 수단은 async 보다 명시적인 annotation 으로 남겨야 한다고 답했다.

철자 이야기도 피치에서 시작됐다. Jon_Shier(#14)는 @concurrent 가 너무 일반적이라서 async(global) 같은 쪽이 낫다고 제안했다. juanarzola(#56)는 unspecified 를 제안했고, John_McCall(#57)은 그 이름이 actor 와 아무 관계가 있다는 것을 말해 주지 않는다고 썼다. #60 에서는 이 함수에서 무엇이 unspecified 인가를 되물으며, 살릴 수는 있지만 다른 키워드가 필요하다고 말했다.


1차 리뷰의 철자 논의

1차 리뷰는 2025-03-02 에 끝났다. 리뷰 스레드의 번호는 #1 부터 #66 까지인데, #12 와 #16 은 지워져 없고 #66 은 비어 있어서 내용이 있는 글은 63개다. 첫 글의 시각(2025-04-11)은 글이 나중에 편집된 시각이고, 글이 이어진 기간은 2025-02-20(#2)부터 2025-03-28(#65)까지다.

철자 논의의 흐름을 따라간다.

  • #2 MPLewis(2025-02-20): 제안서의 두 번째 @execution(caller) 는 concurrent 의 오타라고 짚고, nonisolated 가 no-op 이 되는지, 그렇다면 왜 deprecate 하지 않느냐고 물었다.
  • #20 FranzBusch: 목표에는 +1 이다. 처음의 의미가 맞았고 SE-0338 은 성능을 이유로 한 잘못된 tradeoff 였다고 평가한다. @execution 은 isolation 과 execution 을 섞어서 싫다고 한다. 실행 결정을 isolation 확인, custom executor, task executor preference, 전역 기본 executor 순서로 정리하고, @isolated(caller) 와 @isolated(non) 을 제안했다.
  • #21 xwu(리뷰 매니저 모자를 벗고): nonisolated(eager) 와 nonisolated(lazy) 를 제안했다.
  • #35 hborla: caller isolation 은 overload resolution 에 영향을 줄 수 없다고 설명했다. Task.detached 로 손이 가는 사람이 많으니, @execution(concurrent) 를 받는 runConcurrently 같은 API 를 만들자는 아이디어도 냈다. get async 프로퍼티에도 철자를 붙일 수 있느냐는 질문에는 “Yes!” 라고 썼다. FranzBusch 에게는 Swift 5.5 의 async 함수가 data-race safe 가 아니었다고 설명했다. SE-0338 이 ABI 를 바꾸지 않고 의미를 안전하게 만들었는데 결국 그것은 잘못된 tradeoff 였고, 다만 ABI 변경을 단계적으로 들여오는 데에도 실제 비용이 있다고 했다.
  • #59 hborla: Jumhyn 의 #45 가 낸 “특정 executor 로 옮기는 것은 덧붙이는 단계” 라는 논거를 매우 설득력 있다고 보고, 앞에서 다른 사람이 낸 @executor(concurrent) 나 @executor(global) 을 다시 꺼냈다.
  • #62 John_McCall(2025-03-12): 생각이 바뀌었다고 썼다. @execution(caller) 는 한계가 있는 과도기 attribute 이고, @execution 이나 @executor 는 실수라는 것이다. @concurrent 를 너무 성급히 버렸는지도 모른다고 하면서, 필요하다면 @isolated(caller) 가 어울린다고 했다.
  • #63 Douglas_Gregor(2025-03-17): 동의한다. executor 를 이름에서 빼서 개념을 점진적으로 공개하자고 하고, @isolated(caller) 가 좋은 철자라고 했다. SE-0461 이전 컴파일러도 지원해야 하는 코드가 upcoming feature 로 한 번에 넘어가지 않고 #isolation 트릭을 조금씩 걷어 낼 수 있다는 점도 썼다.
  • #64 Arma(2025-03-26): NetworkService.fooEndpoint 같은 예를 직접 써 보고 UI 응답성이 떨어질까 걱정했다. runtime 이 알아서 고르기를 바라고, 더 제어하려면 @execution(concurrent) 나 @execution(caller) 를 쓸 수 있으면 좋겠다고 썼다.

리뷰에서 가장 길게 이어진 논점은 @execution 이 executor 와 thread 라는 낮은 층위의 모델을 떠올리게 한다는 것이었다. John_McCall(#62)과 Douglas_Gregor(#63)가 거기서 방향을 틀었고, 제안서의 @executor 절이 같은 이유를 쓴다. @executor(global) 이어도 task executor preference 로 다른 executor 에서 돌 수 있다는 것이다.


두 번의 수락 공지

xwu 는 2025-03-28 에 수정 수락과 재리뷰를 함께 공지했다(#1). 수정 사항은 네 가지였다.

  1. region isolation 규칙을 제안서에 명시한다.
  2. assertIsolated, assumeIsolated, preconditionIsolated 의 noasync 를 없앤다.
  3. feature flag 가 없을 때의 무조건 경고를 없앤다.
  4. @execution(concurrent) 를 @concurrent 로 되돌린다.

@execution(caller) 에 대해서는 철자에 합의가 없었다고 공지가 쓴다. 두 철자가 정확히 대칭일 필요는 없다고 보았고, 저자들이 nonisolated(nonsending) 을 제안했다. 이 한 가지만 재리뷰에 부쳤다.

재리뷰는 2025-04-04 까지였고 글은 아홉 개다(#10 은 비어 있다). 첫 글의 시각(2025-04-11)은 편집 시각이다. 눈에 띄는 글은 다음과 같다.

  • #2 hborla: 제안서의 alternatives considered 절에 철자 논의가 길게 정리되어 있다고 알렸다.
  • #3 Nickolas_Pohilets: +1. nonisolated(...) 는 과도기 상태로서 말이 되고, nonisolated(nonsending) 은 다른 아쉬운 대안들보다 낫다고 썼다. 다만 sending 인자가 있는 함수에서는 nonisolated(nonsending) 이 어색해 보인다고 했다. actor 와 global-actor-isolated 타입의 함수에서 @concurrent 와 nonisolated 를 둘 다 적어야 하는 것이 중복처럼 보이니, @concurrent 만으로 nonisolated 를 함의하게 하자고 제안했다.
  • #4 hborla: 동의했다. @execution 이 두 동작의 base attribute 일 때는 nonisolated 를 함의하지 않는 것이 중요하다고 강하게 느꼈는데, 두 철자가 갈린 지금은 @concurrent 만으로 충분하지 않을 이유가 없다는 것이다.
  • #5 anreitersimon: nonsending 을 nonsensing, 곧 nonsense 와 닮았다고 읽었다.
  • #6 jameesbrown: +1. @concurrent 와 nonisolated 를 같이 적을 때와 동기 함수에 @concurrent 를 적을 때 나올 오류와 fix-it 을 예로 적어 보이고, nonisolated 와 같이 쓰는 것은 허용해도 되지 않겠느냐고 했다.
  • #7 JJJ: async getter 에서 @concurrent 를 어디에 쓰는지 물었다. #8 hborla 가 get 앞에 쓴다고 보였다(@concurrent 절).
  • #9 xwu: 위 수정을 반영해 수락한다고 공지했다.

2025-04-05 의 최종 공지는 nonisolated(nonsending) 을 수락하면서, @concurrent 만으로 nonisolated 를 함의하도록 한 재리뷰의 제안을 반영한다고 한다. 재리뷰의 반응은 가볍지만 비교적 긍정적이었다고 요약한다.


제안서가 검토한 대안

제안서의 Alternative syntax choices 절은 “완벽한 철자는 없다” 는 말로 시작한다. 두 철자가 목적이 다르다는 것이 앞의 정리다. @concurrent 는 함수와 클로저를 actor 에서 빼내는 장기적인 올바른 방법이다. nonisolated(nonsending) 은 새 동작으로 옮겨 가는 데 필요하지만 오래 남을 철자가 아니며, 이상적인 종착점은 이것이 기본 동작이 되는 것이다.

각 대안과 거절 이유를 한 번에 본다.

대안거절 이유
명시 철자 없음과도기에는 어떤 async 함수인지 소스만 봐서는 알기 어렵다. build setting 과 무관한 철자는 macro 와 코드 생성기, 포럼 snippet 에도 필요하다
@executor(global), @execution(...)executor 와 thread 라는 낮은 층위로 생각하게 만들고, isolation 이 executor 요청에 그대로 대응하지 않으며, task executor preference 로 다른 executor 에서 돌 수 있다
@isolated(caller) 를 nonisolated 와 같이 쓰기@isolated(caller) nonisolated 가 장황하고 모순적이다
@isolated(caller) 가 nonisolated 를 함의두 가지 문법을 배워야 하고, 전역 또는 인스턴스 actor isolation 이 추론되는 자리에서는 철자를 지웠을 때 동작이 바뀔 수 있다
nonisolated 를 deprecate 하고 @isolated(caller) 로 통일code churn 이 크고 nonisolated 가 더 쓰기 좋다
nonisolated(nosend)nonsending 이 기존 Swift 이름 규칙과 더 일관된다
nonisolated(caller)“caller 에 isolated 되지 않았다” 로 읽혀서 반대 뜻처럼 보인다
nonisolated(nonconcurrent)함수 구현이 안에서 동시성 일을 할 수 있어서 “동시에 돌지 않는다” 가 정확하지 않다
nonisolated(static)static 을 “컴파일 시점” 이라는 뜻으로 쓴 적이 없고, nonisolated static func 와 모양이 너무 비슷하다

@concurrent 라는 이름에 대한 반론도 제안서가 직접 답한다. 반론은 두 가지였다. @concurrent 만이 동시성의 원인은 아니라는 것, 그리고 @concurrent 함수의 실행은 현재 task 의 지역적 관점에서는 동시적이지 않다는 것이다. 제안서는 동시성이 생기려면 서로 다른 isolation 에서 도는 여러 “impetus”(task 나 이벤트 소스)가 있어야 하지만, 대체로 여러 impetus 가 있다고 가정할 수 있다고 답한다. 그 impetus 들이 isolation 을 공유할 수도 있는데 @concurrent 는 이 제안에서 공유하지 않음을 보장해 동시성을 강제하는 유일한 isolation 지정이다. 프로그래머가 @concurrent 를 찾는 이유가 바로 그것이라는 설명이다.


6.4 에 남은 옛 철자

1차 리뷰 때 제안서에 있던 @execution 철자는 6.4 컴파일러에 남아 있지 않다.

OldSpelling.swift

1
2
@execution(caller) func caller() async {}
@execution(concurrent) func concurrent() async {}

기본 모드의 진단이다.

1
2
3
4
5
6
7
8
9
10
11
12
OldSpelling.swift:1:2: error: unknown attribute 'execution'
1 | @execution(caller) func caller() async {}
  |  `- error: unknown attribute 'execution'
2 | @execution(concurrent) func concurrent() async {}
3 | 

OldSpelling.swift:2:2: error: unknown attribute 'execution'
1 | @execution(caller) func caller() async {}
2 | @execution(concurrent) func concurrent() async {}
  |  `- error: unknown attribute 'execution'
3 | 
[exit 1]

feature 를 켠 판도 같다. 두 줄 모두 unknown attribute 'execution' 이다. 리뷰 중에 포럼 snippet 에 쓰던 철자는 지금 컴파일되지 않는다는 뜻이고, 최종 철자가 @concurrent 와 nonisolated(nonsending) 이라는 것은 앞의 Where.swift 와 ConcurrentRestrict.swift 에서 이미 돌아갔다.


기대 효과

기본값이 바뀌면 코드에서 달라지는 것을 제안서의 문제 네 가지와 맞춰 본다.

  • nonisolated 의 의미가 sync 와 async 에서 같아진다. 앞의 Where.swift 에서 plainSync() 가 부른 쪽에서 돌던 것을 plainAsync() 가 feature 를 켜면 따라 한다. 같은 이름의 철자가 한 가지 뜻을 갖게 된다.
  • 부른 쪽 actor 에서 도는 async 함수를 쓰려고 isolation: isolated (any Actor)? = #isolation 을 적던 boilerplate 가 사라진다. 함수 값으로 꺼내도 기본 인자를 잃지 않는다.
  • 잘못된 async API 를 쓰기 어려워진다. 제안서는 동시성 라이브러리 자신도 이 실수를 했다며 SE-0421 을 든다. SE-0421 글이 다룬 AsyncSequence 의 isolation 이 그 예다.
  • higher-order async API 를 쓰고 만드는 일이 쉬워진다. HigherOrderHalf.swift 와 HigherOrderBody.swift 가 기본 Swift 6 에서 error 였고 feature 를 켜면 통과한 것이 그 예다.

대가도 있다. 기본값이 바뀐다는 것은 앞에서 cooperative pool 로 나가던 async 함수가 main actor 에 남는다는 뜻이다. 제안서는 이것이 UI 응답성을 떨어뜨릴 수 있고, 그런 함수에는 @concurrent 를 붙여야 한다고 말한다. 리뷰 #64 의 Arma 와 피치 #2 의 Jumhyn 이 걱정한 것이 이 대가다. 이 기능은 SE-0338 이 얻으려던 UI 응답성보다 안전과 사용 편의를 앞에 두기로 한 선택이다.


다른 선택지는 왜 안 됐나

철자 후보는 앞의 절에서 다뤘다. 그 밖에 제안서에는 두 가지 대안이 더 있다.

isolated parameter 를 암시적으로 캡처하기. 지금 isolation 추론은 둘러싼 컨텍스트에 isolated parameter 가 있을 때 클로저를 nonisolated 로 본다. 이 동작은 data race 안전성 면에서 놀라울 때가 많지만, 규칙을 바꾸면 이미 있는 코드에서 메모리 누수를 조용히 만들 수 있다. 제안서는 현재 규칙을 유지하고, data race 오류가 날 때 actor 를 캡처하라는 fix-it 을 주는 타협을 제안한다. 그래서 위의 클로저의 isolation 추론 절의 세 번째 규칙이 그대로 남아 있다.

nonisolated 로 옛 동작까지 표현하기. 새 attribute 없이 nonisolated 만으로 async 함수의 실행 위치를 조절하는 방법이다. 두 가지 이유로 안 된다. 하나는 nonisolated 의 의미가 sync 와 async 에서 같다는 목표를 달성하지 못한다는 것이다. 다른 하나는 나중에 동기 함수에도 @concurrent 를 허용할 수 있는 방향을 막는다는 것이다. 앞에서 @concurrent func syncFunction() {} 가 막힌 것이 지금의 제한이다.


Swift 6 모드와 마이그레이션

이 변화는 같은 코드의 뜻을 바꾸므로 소스 호환, 마이그레이션 도구, ABI 순서로 본다.


소스 호환

제안서는 이 변화가 소스 호환에 미치는 영향이 작다고 쓴다. 구현이 non-Sendable 상태를 actor 의 region 에 둔 채 @concurrent 함수를 부를 때만 문제가 생긴다. 성능이 나빠질 수도 있다. 어떤 async 함수가 main actor 에서 불렸을 때 밖에서 도는 것에 기대서 UI 응답성을 유지하고 있었다면, 같은 코드가 main actor 에 남는다.

그래서 이 변화는 upcoming feature flag 뒤에 있다. 다른 upcoming feature 와 다른 점이 하나 있다. 이 변화는 flag 의 켜짐과 상관없이 유효하면서 서로 다른 뜻을 갖는 코드를 허용한다. SE-0338 의 의미를 몸에 익힌 사람이 많은데 몇 해 뒤에 이 변화를 넣으니, 모듈의 build setting 을 모르면 nonisolated async 함수의 의미를 알 수 없는 어색한 중간 상태가 생긴다고 제안서는 인정한다. 그래서 두 가지 장치를 둔다. SourceKit 이 암시된 nonisolated(nonsending) 이나 @concurrent 를 Xcode 의 Quick Help 와 VSCode 의 Hover 같은 IDE 기능에 드러내고, 마이그레이션 도구가 동작을 보존하는 fix-it(@concurrent 붙이기)을 준다. 도구의 이야기는 Pitch: Adoption tooling for upcoming features 에 있다.

같은 코드를 세 언어 모드에서 기본과 feature 판으로 돌린 결과다. Motivation.swift 를 돌렸다.

모드기본NonisolatedNonsendingByDefault
Swift 5진단 없음진단 없음
Swift 5, -strict-concurrency=complete12:13 warning진단 없음
Swift 612:13 error진단 없음

HigherOrderBody.swift 와 HigherOrderHalf.swift 도 같은 모양이었다. Swift 5 모드에서도 feature 를 켤 수 있고, complete 검사에서 나던 warning 이 사라진다. feature 를 켜도 명시 철자만 쓴 코드는 달라지지 않는다.


마이그레이션 모드

feature 이름 뒤에 :migrate 를 붙이면 동작을 바꾸지 않고 바뀔 곳만 warning 으로 알려 준다.

Migrate.swift

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
func plainAsync() async {}

struct S {
  func method() async {}
  nonisolated(nonsending) func already() async {}
  @concurrent func concurrent() async {}
}

func takes(_ fn: () async -> Void) async {
  await fn()
}

@MainActor func onMain() async {}

func sync() {}
1
xcrun swiftc -emit-sil -o /dev/null -parse-as-library -wmo -swift-version 6 -enable-upcoming-feature NonisolatedNonsendingByDefault:migrate Common.swift Migrate.swift

진단은 warning 넷이고 종료 코드는 0 이다.

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
Migrate.swift:1:6: warning: feature 'NonisolatedNonsendingByDefault' will cause nonisolated async global function 'plainAsync' to run on the caller's actor; use '@concurrent' to preserve behavior [#NonisolatedNonsendingByDefault]
 1 | func plainAsync() async {}
   |      `- warning: feature 'NonisolatedNonsendingByDefault' will cause nonisolated async global function 'plainAsync' to run on the caller's actor; use '@concurrent' to preserve behavior [#NonisolatedNonsendingByDefault]
 2 | 
 3 | struct S {

Migrate.swift:4:8: warning: feature 'NonisolatedNonsendingByDefault' will cause nonisolated async instance method 'method' to run on the caller's actor; use '@concurrent' to preserve behavior [#NonisolatedNonsendingByDefault]
 2 | 
 3 | struct S {
 4 |   func method() async {}
   |        `- warning: feature 'NonisolatedNonsendingByDefault' will cause nonisolated async instance method 'method' to run on the caller's actor; use '@concurrent' to preserve behavior [#NonisolatedNonsendingByDefault]
 5 |   nonisolated(nonsending) func already() async {}
 6 |   @concurrent func concurrent() async {}

Migrate.swift:9:18: warning: feature 'NonisolatedNonsendingByDefault' will cause nonisolated async function type to be treated as specified to run on the caller's actor; use '@concurrent' to preserve behavior [#NonisolatedNonsendingByDefault]
 7 | }
 8 | 
 9 | func takes(_ fn: () async -> Void) async {
   |                  `- warning: feature 'NonisolatedNonsendingByDefault' will cause nonisolated async function type to be treated as specified to run on the caller's actor; use '@concurrent' to preserve behavior [#NonisolatedNonsendingByDefault]
10 |   await fn()
11 | }

Migrate.swift:9:6: warning: feature 'NonisolatedNonsendingByDefault' will cause nonisolated async global function 'takes' to run on the caller's actor; use '@concurrent' to preserve behavior [#NonisolatedNonsendingByDefault]
 7 | }
 8 | 
 9 | func takes(_ fn: () async -> Void) async {
   |      `- warning: feature 'NonisolatedNonsendingByDefault' will cause nonisolated async global function 'takes' to run on the caller's actor; use '@concurrent' to preserve behavior [#NonisolatedNonsendingByDefault]
10 |   await fn()
11 | }

[#NonisolatedNonsendingByDefault]: <https://docs.swift.org/compiler/documentation/diagnostics/nonisolated-nonsending-by-default>
[exit 0]

warning 이 나온 자리는 네 곳이다. 철자 없는 전역 async 함수 plainAsync(1:6), 철자 없는 인스턴스 메서드 method(4:8), takes 의 parameter 타입 () async -> Void(9:18), 그리고 takes 자신(9:6)이다. 이미 철자를 적은 already 와 concurrent, @MainActor 인 onMain, 동기 함수 sync 에는 warning 이 없다. 철자를 이미 적은 코드는 바뀌지 않기 때문이다. 함수 선언뿐 아니라 함수 타입도 대상이라서, 9:18 이 함수 값 fn 의 타입에서 나온다. 이 warning 이 가리키는 처방이 @concurrent 를 붙여 옛 동작을 지키는 것이다.


ABI 와 adoption

제안서는 기존 nonisolated async 함수를 caller 의 actor 에서 도는 것으로 바꾸는 일이 ABI 변경이라고 적는다. 부른 쪽 actor 를 parameter 로 넘겨야 하기 때문이다. 동시성 라이브러리의 여러 API 가 isolated parameter 와 #isolation 으로 같은 변화를 단계적으로 들여왔고, resilient 라이브러리를 위해 이 변환을 자동으로 하는 도구를 낼 수도 있다고 한다. 예로 든 컴파일러의 두 진입점 방식은 이렇다.

1
2
3
4
5
6
7
8
9
10
11
12
13
@_alwaysEmitIntoClient
public func myAsyncFunc() async {
  // original implementation
}

@concurrent
@_silgen_name(...) // to preserve the original symbol name
@usableFromInline
internal func abi_myAsyncFunc() async {
  // existing compiled code will continue to always run calls to this function
  // on the generic executor.
  await myAsyncFunc()
}

@_alwaysEmitIntoClient 는 함수 본문을 호출하는 쪽 바이너리에 내보내는 속성이다. 새로 컴파일하는 쪽은 원래 구현(부른 쪽 actor 에서 도는 새 의미)을 받고, 이미 컴파일된 쪽은 원래 심볼 이름을 유지한 abi_myAsyncFunc 가 @concurrent 라서 옛 동작으로 계속 간다. 이 방식은 원래 함수가 inlinable 로 만들어질 수 있을 때만 된다고 제안서는 덧붙인다.

adoption 에서의 의미도 하나 있다. nonisolated(nonsending) 함수는 암시적 actor parameter 를 받는다. 그래서 actor isolated 함수에 nonisolated(nonsending) 을 붙이거나, @concurrent 를 nonisolated(nonsending) 으로 바꾸는 것은 resilient 한 변경이 아니다.


정리

  • upcoming feature NonisolatedNonsendingByDefault 를 켜면 철자 없는 nonisolated async 함수가 부른 쪽 actor 에서 돈다. 네 함수 중 바뀌는 것은 plainAsync() 하나이고, nonisolated(nonsending) 과 @concurrent 는 build setting 과 상관없이 각각 main 큐와 cooperative pool 이었다.
  • nonisolated(nonsending) 은 암시적 actor parameter 를 받는 새 동작의 철자이고, @concurrent 는 옛 동작의 철자다. 둘 다 동기 함수, global actor, isolated parameter 와는 같이 쓰지 못하고 서로도 같이 쓰지 못한다. @concurrent 는 nonisolated 를 함의한다. sending 과 @Sendable 과는 같이 쓸 수 있다.
  • nonsending 함수 안의 #isolation 은 부른 쪽 actor 이고, 동기 nonisolated 와 @concurrent 안에서는 nil 이다. 안에서 만든 Task {} 는 isolation 을 물려받지 않는다.
  • 함수 타입에도 같은 기본값이 적용된다. body: (NotSendable) async -> Void 는 기본에서 @concurrent 처럼, feature 를 켜면 nonsending 처럼 읽혀서 higher-order API 의 오류가 사라진다. 함수 타입에 @concurrent 를 적으면 feature 를 켜도 그대로 옛 동작이다.
  • region 규칙은 nonisolated 함수와 같다. disconnected 값은 nonsending 함수를 거쳐도 sending 으로 돌려줄 수 있고, actor 의 상태는 그럴 수 없다. isolated parameter 를 직접 받는 함수는 그렇지 않다.
  • 변환 예 몇 개는 region 검사에 닿기 전에 다른 검사에서 먼저 막힌다. @MainActor 로의 변환 두 예는 @Sendable 검사 오류이고, assumeIsolated 는 async 컨텍스트에서 쓸 수 없다.
  • 철자는 피치의 @concurrent 에서 1차 리뷰의 @execution(concurrent) 와 @execution(caller) 를 거쳐, @concurrent 와 nonisolated(nonsending) 으로 정해졌다. 2025-04-05 에 최종 수락됐고, @concurrent 만으로 nonisolated 를 함의하게 했다.
  • 같은 코드가 build setting 에 따라 다르게 도는 중간 상태가 생기므로, 마이그레이션은 NonisolatedNonsendingByDefault:migrate 가 알려 주는 자리에 @concurrent 를 붙이는 것으로 시작할 수 있다. 이미 컴파일된 resilient 라이브러리의 ABI 는 이 변경으로 바뀐다.

관련 글


참고자료

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