[SE-0528] Continuation: Safe and Performant Async Continuations
이 글은 Swift Evolution 제안서 원문과 포럼 리뷰 스레드를 Claude Code 로 정리한 글이다. 코드는 Xcode 27 의 Swift 6.4 컴파일러로 빌드하고, 진단 메시지와 실행 결과는 실제로 컴파일하고 실행해서 나온 것을 옮겼다.
제안서 정보
- 번호: SE-0528
- 상태: Implemented (Swift 6.4)
- 저자: Fabian Fett, Konrad Malawski
- 리뷰 매니저: Joe Groff
- 구현: swiftlang/swift#88182
- 선행 제안: SE-0300 Continuations for interfacing async tasks with synchronous code, SE-0390 Noncopyable structs and enums, SE-0413 Typed throws
- 리뷰에 올라간 판: as reviewed
- 제안서 머리의 pitch 링크: Pitch: RigidArray and UniqueArray (2026-03-19 부터 04-10). 이 스레드는
RigidArray와UniqueArray를 다루고Continuation은 나오지 않는다 - 리뷰: SE-0528: Non-Copyable Continuation (2026-04-15 시작, 04-28 까지, 마지막 글은 05-06)
- 수락: Accepted: SE-0528 Non-Copyable Continuation (2026-05-06, 라벨 이름을 고쳐서 수락)
한 줄 요약
Continuation<Success, Failure> 는 ~Copyable 인 continuation 타입이다. resume 메서드가 consuming 이라서 같은 continuation 을 두 번 resume 하는 코드는 컴파일이 되지 않고, 한 번도 resume 하지 않고 버리면 deinit 에서 런타임에 멈춘다. 이 글은 두 실수를 각각 컴파일하고 실행해서 어디서 잡히는지 보고, CheckedContinuation 으로 바꿔서 쓰는 길과 100만 번 resume 의 속도 차이까지 정리한다.
어떤 문제였나
이 절은 먼저 continuation 이 무엇인지 설명하고, 지금까지 있던 두 가지 선택지가 무엇을 주고 무엇을 잃는지 본다. 그다음 이 제안이 기대는 ~Copyable 을 풀어 쓴다.
Continuation이란?
completion handler 를 받는 오래된 API 는 일을 시켜 놓고 결과를 나중에 클로저로 돌려준다. async 함수는 결과를 await 자리에서 바로 돌려받는다. 둘 사이를 이어 주는 것이 continuation 이다.
식당의 진동벨에 비유할 수 있다. 주문하면(await 로 멈추면) 벨을 받고 자리에 앉는다. 음식이 나오면(callback 이 불리면) 벨이 울리고(resume) 내 task 가 깨어나 다음 줄을 실행한다. 벨은 정확히 한 번 울려야 한다. 두 번 울리면 같은 손님을 두 번 부르는 것이고, 한 번도 울리지 않으면 손님은 영원히 앉아 있다.
SE-0300 이 이 벨을 두 종류로 만들었다.
UnsafeContinuation: 검사가 없다. 제안서는 두 번 resume 하면 undefined behavior 이고 한 번도 resume 하지 않으면 기다리는 task 가 조용히 멈춘다고 쓴다. 두 실수를 실제로 돌린 결과는 아래 변환 절에 있다CheckedContinuation: 런타임에 두 실수를 검사한다. 대신 제안서의 표 기준으로 할당과 atomic 연산이 붙는다
제안서가 보는 문제는 이 둘 사이가 비어 있다는 것이다. 검사를 원하면 런타임 비용을 내야 하고, 비용을 아끼면 검사를 버려야 한다. 그런데 continuation 은 “정확히 한 번 쓰는 값” 이다. 한 번만 쓰는 값은 Swift 가 이미 타입 시스템으로 다루는 종류가 있다.
한 번만 쓰는 값과 ~Copyable
~Copyable 은 “복사할 수 없다” 를 뜻하는 표시다. 이런 타입의 값은 다른 변수에 대입하면 원래 자리가 비어 버린다(옮겨 가는 것이다). 값을 가져가 버리는 메서드는 consuming 으로 적는다. consuming 메서드를 한 번 부르면 그 값은 사라진 것으로 취급되고, 같은 이름으로 다시 쓰면 컴파일러가 막는다. SE-0390 이 이 기반을 만들었다.
~Copyable 타입에 deinit 을 두면 값이 소비되지 않은 채 범위를 벗어날 때 그 deinit 이 불린다. Continuation 은 이 deinit 에서 fatalError 를 부른다. 정상적으로 resume 하는 쪽은 메서드 끝에서 discard self 를 써서 이 deinit 을 건너뛴다(그렇지 않으면 resume 할 때마다 멈출 것이다). 이 두 장치가 합쳐져 “두 번은 컴파일 에러, 한 번도 안 하면 런타임 trap” 이라는 비대칭이 나온다. 아래 그림이 이 글 전체의 지도다.
Continuation 칸의 두 값은 Double.swift 와 Drop.swift 로, CheckedContinuation 칸의 두 값은 Convert.swift 와 CheckedMissing.swift 로, UnsafeContinuation 칸의 두 값은 UnsafeDouble.swift 와 UnsafeMissing.swift 로 직접 돌려서 확인했다. Unsafe 칸을 보면 두 번 resume 은 진단 없이 컴파일되고 실행 때 crash 하며 그 모양이 실행마다 다르고, 한 번도 resume 하지 않으면 아무 메시지 없이 기다리는 쪽만 멈춘다. 측정은 변환 절의 UnsafeContinuation 항목에 있다.
무엇이 바뀌나
새 타입 하나와 그것을 얻는 함수 하나가 추가된다. 이 절은 선언의 모양부터 보고, 한 번 resume 하는 가장 단순한 사용, callback 에 넘기려 할 때 만나는 벽, 두 실수가 각각 어디서 잡히는지, actor 에 보관하는 모양, CheckedContinuation 으로 바꾸는 길, 속도 순으로 측정한다.
선언의 모양
6.4 SDK 의 _Concurrency interface 에서 선언부만 옮겼다(모듈 접두사는 줄였다).
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
@available(anyAppleOS 27.0, *)
@safe @frozen public struct Continuation<Success, Failure> : ~Copyable, @unchecked Sendable
where Failure : Error, Success : ~Copyable {
deinit
public consuming func resume(returning value: consuming sending Success) where Failure == Never
public consuming func resume(returning value: consuming sending Success)
public consuming func resume(throwing error: __owned Failure)
public consuming func resume(with result: consuming sending Result<Success, Failure>)
public consuming func resume() where Success == ()
}
@available(anyAppleOS 27.0, *)
nonisolated(nonsending) public func withContinuation<Success, Failure>(
of: Success.Type = Success.self,
throwing: Failure.Type,
_ body: (consuming Continuation<Success, Failure>) -> Void
) async throws(Failure) -> sending Success where Failure : Error, Success : ~Copyable
@available(anyAppleOS 27.0, *)
nonisolated(nonsending) public func withContinuation<Success>(
of: Success.Type = Success.self,
_ body: (consuming Continuation<Success, Never>) -> Void
) async -> sending Success where Success : ~Copyable
extension CheckedContinuation {
public init(_ continuation: consuming Continuation<T, E>, function: String = #function)
}
extension UnsafeContinuation {
public init(_ continuation: consuming Continuation<T, E>)
}
읽을 곳이 여섯 군데 있다.
- 타입은
@frozen이고 interface 에서 저장 프로퍼티는context: Builtin.RawUnsafeContinuation하나뿐이다. 수락 공지가 “single pointer to the suspended task” 라고 쓴 것이 이것이다. 크기도 쟀다(Layout.swift).Continuation8 바이트,UnsafeContinuation8 바이트,Optional<Continuation>도 8 바이트가 나온다 resume은 전부consuming이고, 값은consuming sending으로 받는다.~Copyable값도 넘길 수 있고Sendable이 아닌 값도 task 경계를 넘겨 보낼 수 있다(SE-0430 글의sending)resume(throwing:)은Failure타입 그대로 받는다.Failure는Error를 따르는 타입이고Never도 들어간다withContinuation은throws(Failure)를 쓰는 함수 하나다.Never면try가 필요 없고, 구체 타입이면 그 타입만 던지고,any Error면 예전의 untyped throws 와 같다. SE-0300 이withCheckedContinuation과withCheckedThrowingContinuation두 함수로 갈라야 했던 이유가 SE-0413 으로 사라진 것이다of:에는 기본값Success.self가 있어서, closure 파라미터에 타입을 적으면of:를 생략할 수 있다- 둘 다
nonisolated(nonsending)이다. 호출한 쪽의 actor 에서 body 가 돈다(SE-0461 글). 6.4 의withCheckedContinuation도 interface 에서 같은nonisolated(nonsending)이라 이 성질이 새 타입만의 것은 아니다. 아래 actor 절에서 본다
callback 에 넘기기 어려운 이유
completion handler 는 @escaping 이라서 그 안에서 c 를 resume 하려면 c 를 캡처해야 한다. 이렇게 쓰면 어떻게 될까.
Escaping.swift
1
2
3
4
5
6
7
8
9
struct NetworkError: Error {}
func legacyFetch(completion: @escaping @Sendable (Result<String, NetworkError>) -> Void) { completion(.success("x")) }
func fetch() async throws(NetworkError) -> String {
try await withContinuation(of: String.self, throwing: NetworkError.self) { c in
legacyFetch { result in c.resume(with: result) }
}
}
@main struct M { static func main() async { _ = try? await fetch() } }
1
bash diag.sh Escaping.swift
1
2
3
4
5
6
7
8
Escaping.swift:6:29: error: noncopyable 'c' cannot be consumed when captured by an escaping closure or borrowed by a non-Escapable type
4 | func fetch() async throws(NetworkError) -> String {
5 | try await withContinuation(of: String.self, throwing: NetworkError.self) { c in
6 | legacyFetch { result in c.resume(with: result) }
| `- error: noncopyable 'c' cannot be consumed when captured by an escaping closure or borrowed by a non-Escapable type
7 | }
8 | }
[exit 1]
컴파일러는 클로저가 몇 번 불릴지 알지 못해서, 캡처한 noncopyable 값을 클로저 안에서 소비하는 것을 허락하지 않는다. @escaping 이라서 막히는 것이 아니다. 같은 일을 non-escaping 클로저를 바로 한 번 부르는 모양으로 해도 똑같이 막힌다.
NonEscaping.swift
1
2
3
4
5
6
7
func callNow(_ f: () -> Void) { f() }
func g() async -> Int {
await withContinuation(of: Int.self) { c in
callNow { c.resume(returning: 1) }
}
}
@main struct M { static func main() async { print(await g()) } }
1
bash diag.sh NonEscaping.swift
1
2
3
4
5
6
7
8
9
10
NonEscaping.swift:3:42: error: noncopyable 'c' cannot be consumed when captured by an escaping closure or borrowed by a non-Escapable type
1 | func callNow(_ f: () -> Void) { f() }
2 | func g() async -> Int {
3 | await withContinuation(of: Int.self) { c in
| `- error: noncopyable 'c' cannot be consumed when captured by an escaping closure or borrowed by a non-Escapable type
4 | callNow { c.resume(returning: 1) }
| `- note: consumed here
5 | }
6 | }
[exit 1]
callNow 의 파라미터는 @escaping 이 아닌데도 진단 문구는 “escaping closure” 라고 말한다. 이 문구는 원인을 가리키는 것으로 읽으면 오해하기 쉽다. 실제 조건은 “클로저 안에서 캡처한 noncopyable 값을 소비하는가” 이다. 가장 흔한 모양인 “callback 하나에서 resume” 이 이 제안의 가장 큰 걸림돌이다. 제안서도 called once 클로저가 생기면 이런 사용이 Continuation 으로 옮겨 올 수 있다고 쓴다.
단순한 사용과 Mutex 로 감싼 우회
6.4 에서 이 벽을 지나가는 방법은 continuation 을 Mutex 안의 Optional 로 감싸 callback 이 꺼내 가게 하는 것이다. 한 파일에서 단순한 경우들과 그 우회를 같이 돌렸다.
Basic.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
import Foundation
import Synchronization
struct NetworkError: Error { let code: Int }
func legacyFetch(_ ok: Bool, completion: @escaping @Sendable (Result<String, NetworkError>) -> Void) {
DispatchQueue.global().asyncAfter(deadline: .now() + .milliseconds(10)) {
completion(ok ? .success("payload") : .failure(NetworkError(code: 404)))
}
}
func fetch(_ ok: Bool) async throws(NetworkError) -> String {
try await withContinuation(of: String.self, throwing: NetworkError.self) { c in
let slot = ContinuationSlot(c)
legacyFetch(ok) { result in slot.take()?.resume(with: result) }
}
}
final class ContinuationSlot<S, F: Error>: Sendable {
let m: Mutex<Continuation<S, F>?>
init(_ c: consuming Continuation<S, F>) { m = Mutex(c) }
func take() -> Continuation<S, F>? { m.withLock { $0.take() } }
}
struct FileHandleBox: ~Copyable { let fd: Int32 }
@main struct M {
static func main() async {
let a = await withContinuation(of: Int.self) { c in c.resume(returning: 1) }
print("never:", a)
await withContinuation(of: Void.self) { c in c.resume() }
print("void resume()")
let b = await withContinuation { (c: consuming Continuation<Int, Never>) in c.resume(returning: 2) }
print("of omitted:", b)
do { print(try await fetch(true)) } catch { print("unreachable") }
do { _ = try await fetch(false) } catch { print("typed catch:", error.code) }
do {
_ = try await withContinuation(of: Int.self, throwing: (any Error).self) { c in
c.resume(throwing: CocoaError(.fileNoSuchFile))
}
} catch { print("any Error:", type(of: error)) }
let box = await withContinuation(of: FileHandleBox.self) { c in c.resume(returning: FileHandleBox(fd: 3)) }
print("noncopyable success fd:", box.fd)
}
}
1
2
3
bash diag.sh Basic.swift
xcrun swiftc -parse-as-library -swift-version 6 Basic.swift -o basic
./basic
1
2
3
4
5
6
7
8
[exit 0]
never: 1
void resume()
of omitted: 2
payload
typed catch: 404
any Error: NSError
noncopyable success fd: 3
진단 없이 컴파일되고 일곱 줄이 나온다.
never: 1:Failure가Never인 형태다.of: Int.self만 적고try없이await한다void resume():Success == Void일 때만 있는resume()이다of omitted: 2: closure 파라미터를consuming Continuation<Int, Never>로 적으면of:없이도Success가 정해진다payload와typed catch: 404:throwing: NetworkError.self를 주면fetch가throws(NetworkError)가 되어서,catch안의error가NetworkError로 읽힌다(error.code를 바로 쓴다)any Error: NSError:throwing: (any Error).self는 예전withCheckedThrowingContinuation과 같다. 던진CocoaError는 Foundation 이 정의한 에러 타입인데,any Error로 담겨 돌아오면 Darwin 에서NSError로 브리지되어type(of:)가NSError를 찍는다. 순수 Swift 에러 타입이라면 원래 타입 이름이 나온다noncopyable success fd: 3:Success가~Copyable인 타입도 된다(SE-0427 의 noncopyable generics 가 받쳐 주는 부분이다). 기존 continuation 은Success가 복사 가능해야 했다.CheckedNC.swift로withCheckedContinuation에 같은 타입을 넣어 보면 이렇게 나온다
CheckedNC.swift
1
2
3
4
5
6
7
struct FileHandleBox: ~Copyable { let fd: Int32 }
func f() async -> FileHandleBox {
await withCheckedContinuation { (c: CheckedContinuation<FileHandleBox, Never>) in
c.resume(returning: FileHandleBox(fd: 3))
}
}
@main struct M { static func main() async { print(await f().fd) } }
1
bash diag.sh CheckedNC.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
CheckedNC.swift:3:39: error: type 'FileHandleBox' does not conform to protocol 'Copyable'
1 | struct FileHandleBox: ~Copyable { let fd: Int32 }
2 | func f() async -> FileHandleBox {
3 | await withCheckedContinuation { (c: CheckedContinuation<FileHandleBox, Never>) in
| `- error: type 'FileHandleBox' does not conform to protocol 'Copyable'
4 | c.resume(returning: FileHandleBox(fd: 3))
5 | }
CheckedNC.swift:3:9: error: global function 'withCheckedContinuation(function:_:)' requires that 'FileHandleBox' conform to 'Copyable'
1 | struct FileHandleBox: ~Copyable { let fd: Int32 }
2 | func f() async -> FileHandleBox {
3 | await withCheckedContinuation { (c: CheckedContinuation<FileHandleBox, Never>) in
| `- error: global function 'withCheckedContinuation(function:_:)' requires that 'FileHandleBox' conform to 'Copyable'
4 | c.resume(returning: FileHandleBox(fd: 3))
5 | }
_Concurrency.withCheckedContinuation:3:48: note: 'where T: Copyable' is implicit here
1 | @available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
2 | @abi(nonisolated(nonsending) func withCheckedContinuationNonisolatedNonsending<T>(function: String, _ body: (CheckedContinuation<T, Never>) -> Void) async -> sending T)
3 | @inlinable nonisolated(nonsending) public func withCheckedContinuation<T>(function: String = #function, _ body: (CheckedContinuation<T, Never>) -> Void) async -> sending T
| `- note: 'where T: Copyable' is implicit here
[exit 1]
withCheckedContinuation 은 T 에 Copyable 을 요구해서 두 error 가 난다. 이 note 의 선언에도 nonisolated(nonsending) 이 보인다.
Mutex 로 continuation 한 번만 꺼내기
ContinuationSlot 이 위 벽의 우회다. 클래스 안 Mutex 에 Continuation? 을 넣는다. Mutex 는 값에 한 번에 한 스레드만 접근하게 해 주는 잠금 상자이고, withLock 이 잠근 채로 클로저를 실행해서 안의 값에 inout 으로 접근하게 한다. Optional.take() 는 값을 꺼내고 그 자리를 nil 로 남기는 메서드다. 그래서 callback 이 두 번 불려도 두 번째는 nil 이 나와서 ?.resume 이 아무것도 하지 않는다.
callback 이 @Sendable 이라 Mutex 를 가진 final class 로 Sendable 을 맞췄다. 이 우회에는 Optional 과 take() 가 끼므로, 리뷰에서 KeithBauerANZ 가 지적한 것처럼 runtime 에서 확인하는 부분이 늘어난다. 스레드 절에서 이 이야기를 다시 본다.
이 우회의 값도 쟀다. callback 이 두 번 불리는 twiceCallback 으로 돌린 SlotTwice.swift 는 twice callback -> 1 을 찍고 exit 0 으로 끝난다. 두 번째 호출은 take() 가 nil 을 돌려주어서 소리 없이 버려진다. 즉 Mutex 우회에서는 두 번 resume 이 컴파일 에러가 아니라 조용히 무시된다. 반대로 callback 이 한 번도 불리지 않는 neverCallback 으로 돌리면(인자를 준 실행) ContinuationSlot 이 해제될 때 deinit 의 trap 이 나서 exit 133 이다.
DispatchQueue 로 일을 미루기
DispatchQueue.global().asyncAfter(deadline:execute:) 는 백그라운드 큐에서 10ms 뒤에 클로저를 실행해서, 오래된 callback API 를 흉내 낸다. 이 글의 목적은 continuation 이라서 callback 쪽은 단순히 결과만 돌려준다.
두 번 resume 은 컴파일 에러
이 제안이 새로 막는 것이다. 한 continuation 에 resume 을 두 번 부른다.
Double.swift
1
2
3
4
5
6
7
func twice() async -> String {
await withContinuation(of: String.self) { c in
c.resume(returning: "a")
c.resume(returning: "b")
}
}
@main struct M { static func main() async { print(await twice()) } }
1
bash diag.sh Double.swift
1
2
3
4
5
6
7
8
9
10
11
Double.swift:2:45: error: 'c' consumed more than once
1 | func twice() async -> String {
2 | await withContinuation(of: String.self) { c in
| `- error: 'c' consumed more than once
3 | c.resume(returning: "a")
| `- note: consumed here
4 | c.resume(returning: "b")
| `- note: consumed again here
5 | }
6 | }
[exit 1]
error 는 c 가 선언된 closure 파라미터에 걸리고, 소비된 두 자리를 note 가 각각 consumed here 와 consumed again here 로 가리킨다. Swift 5 모드로 같은 파일을 돌려도 같은 error 가 나온다.
1
bash diag.sh -swift-version 5 Double.swift
1
2
3
4
5
6
7
8
9
10
11
Double.swift:2:45: error: 'c' consumed more than once
1 | func twice() async -> String {
2 | await withContinuation(of: String.self) { c in
| `- error: 'c' consumed more than once
3 | c.resume(returning: "a")
| `- note: consumed here
4 | c.resume(returning: "b")
| `- note: consumed again here
5 | }
6 | }
[exit 1]
~Copyable 은 언어 모드와 상관없이 항상 켜져 있는 검사라서 모드를 낮춰도 error 가 사라지지 않는다.
비교 대상은 CheckedContinuation 이다. 같은 실수가 런타임에 잡힌다. 뒤의 Convert.swift 가 그 출력을 보여 준다.
resume 을 빠뜨리면 런타임 trap
반대쪽 실수는 컴파일러가 잡지 못한다. 두 가지 모양으로 돌렸다. 하나는 body 가 아무것도 하지 않고 끝나는 경우이고, 다른 하나는 if 의 한 가지에서만 resume 하는 경우다.
Drop.swift
1
2
3
4
5
6
7
8
9
10
11
12
import Foundation
func forget() async -> Int {
await withContinuation(of: Int.self) { c in
print("body returns without resuming")
}
}
@main struct M {
static func main() async {
setvbuf(stdout, nil, _IONBF, 0)
print(await forget())
}
}
Branch.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import Foundation
func pick(_ flag: Bool) async -> Int {
await withContinuation(of: Int.self) { c in
if flag {
c.resume(returning: 1)
} else {
print("else branch: no resume")
}
}
}
@main struct M {
static func main() async {
setvbuf(stdout, nil, _IONBF, 0)
print(await pick(true))
print(await pick(false))
}
}
1
2
bash diag.sh Drop.swift
bash diag.sh Branch.swift
1
2
[exit 0]
[exit 0]
두 파일 모두 진단이 없다. 둘을 빌드해서 돌린다.
1
2
3
4
xcrun swiftc -parse-as-library -swift-version 6 Drop.swift -o drop
./drop; echo "[exit $?]"
xcrun swiftc -parse-as-library -swift-version 6 Branch.swift -o branch
./branch; echo "[exit $?]"
1
2
3
4
5
6
7
body returns without resuming
_Concurrency/Continuation.swift:56: Fatal error: Continuation was deinitialized without being resumed.
[exit 133]
1
else branch: no resume
_Concurrency/Continuation.swift:56: Fatal error: Continuation was deinitialized without being resumed.
[exit 133]
둘 다 같은 줄에서 멈춘다. Branch.swift 에서는 pick(true) 가 1 을 돌려주고, pick(false) 에서 else 가지의 print 뒤에 멈춘다. exit 133 은 128 에 SIGTRAP(5)을 더한 값이다. setvbuf 는 stdout 을 버퍼 없이 쓰게 해서 멈추기 직전의 print 가 파이프에서도 보이게 하려고 넣었다.
compiler 는 c 가 closure 끝에서 소비되지 않은 채 사라지는 것을 알고 거기에 deinit 호출을 넣는다. 그래서 Drop.swift 의 멈춤은 forget 의 body 가 끝나는 자리에서 일어난다. -g 로 빌드해 lldb 로 보면 frame 5 가 forget 의 closure 이고 줄 번호는 Drop.swift:5:3 이다. 4 행의 print 다음, 곧 closure 를 닫는 5 행 } 의 자리다. 이 모양을 컴파일 에러로 바꾸자는 것이 제안서의 Future Directions 에 있는 ~Discardable 이다. 6.4 에는 없다. 그래서 진단이 하나도 나오지 않는다.
lldb 로 멈춘 자리 보기
멈춘 호출 스택이 어디를 가리키는지 -g 로 빌드해서 lldb 로 봤다. 리뷰에서 이 스택이 쓸모 있느냐가 쟁점이었다.
1
2
xcrun swiftc -g -parse-as-library -swift-version 6 Branch.swift -o BranchG
timeout 20 xcrun lldb --batch -o run -k bt -k quit -- ./BranchG
1
2
3
4
5
6
7
8
9
10
11
(lldb) bt
* thread #3, name = 'Task 1', queue = 'com.apple.root.default-qos.cooperative', stop reason = Fatal error: Continuation was deinitialized without being resumed.
frame #0: 0x00000001a5fa11a8 libswiftCore.dylib`_swift_runtime_on_report
frame #1: 0x00000001a60bbaec libswiftCore.dylib`_swift_stdlib_reportFatalErrorInFile + 204
frame #2: 0x00000001a60e58c8 libswiftCore.dylib`closure #1 in _assertionFailure(_:_:file:line:flags:) + 300
frame #3: 0x00000001a60e4d4c libswiftCore.dylib`_assertionFailure(_:_:file:line:flags:) + 216
frame #4: 0x00000002be37a6c0 libswift_Concurrency.dylib`destroy value witness for Swift.Continuation + 92
* frame #5: 0x0000000100000e40 BranchG`closure #1 in pick(c=(context = e0 eb 65 00 01 00 00 00), flag=false) at Branch.swift:0
frame #8: 0x0000000100000cd0 BranchG`pick(flag=false) at Branch.swift:3:9
frame #9: 0x0000000100001330 BranchG`static M.main() at Branch.swift:15:17
frame #11: 0x00000001000015f4 BranchG`async_MainTQ0_ at <compiler-generated>:0
frame 5 가 pick(flag=false) 의 closure 이고 인자에 flag=false 가 보인다. 그 위로 destroy value witness for Swift.Continuation 이 fatalError 를 부른다. 버린 closure 와 그 인자가 스택에 그대로 남는다. ktoso 가 리뷰에서 noncopyable 타입의 deinit 은 버린 바로 그 자리에서 일어나니 크래시가 정확한 메서드를 가리킨다고 한 말(#11)과 맞는다. 다만 줄 번호는 Branch.swift:0 으로 나온다. 이 frame 을 frame select 5 로 열면 lldb 가 이렇게 말한다.
1
note: This address is not associated with a specific line of code. This may be due to compiler optimizations.
이 주소는 특정 줄에 대응하지 않는다는 뜻이다. 소스 줄이 아니라 closure 가 끝나며 들어간 deinit 호출이라서 줄이 없다. Drop.swift 쪽은 같은 방법으로 Drop.swift:5:3 이 나왔으니, 줄이 나오느냐는 코드 모양에 따라 달랐다.
리뷰에서는 반대 경우도 나왔다. dmt 는 6.3 에서 ~Copyable 구조체의 deinit 에 fatalError() 를 두고 @escaping 클로저에 캡처해 Task 안에서 버리는 재현을 만들었는데, 스택이 어느 closure 에서 어디서 버렸는지 뚜렷하지 않았다고 했다(#18, 04-19). 같은 모양을 Continuation 으로 돌려 보았다. completion 을 다른 queue 에서 호출하지 않고 버리는 SlotDroppedElsewhere.swift 를 -g 로 빌드해 lldb 로 본 스택은 이렇다.
SlotDroppedElsewhere.swift 의 핵심은 이 두 줄이다.
1
2
3
func legacyDrop(_ completion: @escaping @Sendable (Int) -> Void) {
DispatchQueue.global().async { _ = completion }
}
1
2
3
4
5
6
7
8
frame #4: 0x00000002be37a6c0 libswift_Concurrency.dylib`destroy value witness for Swift.Continuation + 92
* frame #5: 0x0000000100001fd4 SDG`outlined destroy of Mutex<Continuation<A, B>?>() at <compiler-generated>:0
frame #6: 0x00000001000010d4 SDG`ContinuationSlot.deinit() at SlotDroppedElsewhere.swift:0
frame #7: 0x0000000100001114 SDG`ContinuationSlot.__deallocating_deinit() at SlotDroppedElsewhere.swift:0
frame #13: 0x00000001000020e0 SDG`block_destroy_helper at <compiler-generated>:0
frame #16: 0x00000001918725a0 libdispatch.dylib`_dispatch_client_callout + 16
frame #18: 0x000000019186ac08 libdispatch.dylib`_dispatch_root_queue_drain + 708
frame #19: 0x0000000191a15f60 libsystem_pthread.dylib`_pthread_wqthread + 232
이 스택에는 ContinuationSlot.deinit 만 보이고 fetch 도, 오래된 함수 legacyDrop 도 없다. 버려진 곳이 다른 queue 의 worker thread 이기 때문이다. 만든 쪽 코드는 스택에 남지 않는다. 대비를 위해 같은 ContinuationSlot 을 쓰는 SlotTwice.swift 를 인자를 주고 돌린 스택에서는 frame 10 이 closure #2 in static M.main(...) 의 SlotTwice.swift:20:7 이고 ContinuationSlot.deinit 이 컨테이너를 알려 준다. ActorTake.swift 를 인자를 주고 돌리면 frame 7 이 LegacyBridge.cancel() at ActorTake.swift:14:23 으로 버린 메서드와 줄이 나온다. 이 둘이 John_McCall 이 말한 “컨테이너가 식별된다” 와 맞는 경우이고, 다른 queue 에서 버리는 경우는 만든 쪽이 안 보인다.
CheckedContinuation 으로 같은 실수 해 보기
같은 “resume 을 안 하고 끝나는” 실수를 CheckedContinuation 으로 하면 어떻게 되는지도 돌렸다. 제안서 표는 “런타임 경고” 라고 쓴다.
CheckedMissing.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import Foundation
func forget() async -> Int {
await withCheckedContinuation { (c: CheckedContinuation<Int, Never>) in
print("body returns without resuming")
}
}
@main struct M {
static func main() async {
setvbuf(stdout, nil, _IONBF, 0)
let t = Task { await forget() }
try? await Task.sleep(for: .milliseconds(200))
print("main still running, task cancelled? \(t.isCancelled)")
}
}
1
2
xcrun swiftc -parse-as-library -swift-version 6 CheckedMissing.swift -o checkedmissing
./checkedmissing; echo "[exit $?]"
1
2
3
4
body returns without resuming
SWIFT TASK CONTINUATION MISUSE: forget() leaked its continuation without resuming it. This may cause tasks waiting on it to remain suspended forever.
main still running, task cancelled? false
[exit 0]
경고 한 줄을 출력하고 프로그램은 계속 돈다. 기다리던 task 는 깨어나지 못한 채 남고, exit 0 이다. 기다리는 쪽이 main 이면 어떻게 되는지는 CheckedHang.swift(위 forget() 을 task 없이 print(await forget()) 로 바로 기다린다)로 봤다. 같은 경고가 나온 뒤 프로그램이 끝나지 않아 timeout 5 로 잘랐다(exit 124). 같은 실수를 Continuation 은 즉시 멈추게 하고 CheckedContinuation 은 경고만 남긴다. 이 차이를 두고 리뷰에서 한 번 더 길게 논쟁이 있었다(스레드 절의 ellie20, FranzBusch).
Task.sleep 으로 기다리기
Task.sleep(for:) 는 지정한 시간만큼 현재 task 를 멈춘다. 여기서는 forget() 을 돌리는 task 가 경고를 낼 시간을 주려고 200ms 를 기다렸다. 취소되면 던지는 함수라서 try? 로 받았다.
actor 에 보관하기
continuation 을 나중에 resume 하려고 actor 의 저장 프로퍼티에 넣어 두는 모양은 흔하다. 저장 프로퍼티를 Optional 로 두고 if let 으로 풀어 resume 하는 모양을 먼저 돌렸다.
ProposalActor.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
actor LegacyBridge {
var continuation: Continuation<String, Never>?
func store(_ continuation: consuming Continuation<String, Never>) {
self.continuation = consume continuation
}
func complete(with value: String) {
if let continuation {
continuation.resume(returning: value)
}
}
}
@main struct M { static func main() async {} }
1
bash diag.sh ProposalActor.swift
1
2
3
4
5
6
7
8
ProposalActor.swift:9:5: error: noncopyable 'unknown' cannot be consumed when captured by an escaping closure or borrowed by a non-Escapable type
7 |
8 | func complete(with value: String) {
9 | if let continuation {
| `- error: noncopyable 'unknown' cannot be consumed when captured by an escaping closure or borrowed by a non-Escapable type
10 | continuation.resume(returning: value)
11 | }
[exit 1]
'unknown' 이라는 이름은 진단이 actor 의 저장 프로퍼티를 이름으로 가리키지 못해서 나온 표시다. 문구도 앞의 “escaping closure” 와 같은 틀이라 원인으로 읽기 어렵다. 어떤 모양에서 막히는지 IfLetKinds.swift 로 세 가지를 나란히 놓았다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
final class C {
var continuation: Continuation<String, Never>?
func complete(with value: String) {
if let continuation { continuation.resume(returning: value) }
}
}
struct S: ~Copyable {
var continuation: Continuation<String, Never>?
mutating func complete(with value: String) {
if let continuation { continuation.resume(returning: value) }
}
}
func local(_ c: consuming Continuation<String, Never>?) {
if let c { c.resume(returning: "x") }
}
1
bash diag.sh IfLetKinds.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
IfLetKinds.swift:4:5: error: cannot consume noncopyable stored property 'self.continuation' of a class
2 | var continuation: Continuation<String, Never>?
3 | func complete(with value: String) {
4 | if let continuation { continuation.resume(returning: value) }
| `- error: cannot consume noncopyable stored property 'self.continuation' of a class
5 | }
6 | }
IfLetKinds.swift:9:17: error: missing reinitialization of inout parameter 'self' after consume
7 | struct S: ~Copyable {
8 | var continuation: Continuation<String, Never>?
9 | mutating func complete(with value: String) {
| `- error: missing reinitialization of inout parameter 'self' after consume
10 | if let continuation { continuation.resume(returning: value) }
| `- note: consumed here
11 | }
12 | }
[exit 1]
class 의 저장 프로퍼티는 cannot consume noncopyable stored property 'self.continuation' of a class 로, ~Copyable 구조체의 mutating 메서드는 missing reinitialization of inout parameter 'self' after consume 으로 막히고, 지역 Optional 인 local 은 진단이 없다. 그러니 걸리는 본질은 if let 이 아니라 참조 타입의 저장 프로퍼티를 소비하려는 것이다. actor 도 참조 타입이라 같은 부류이고, 6.4 에서 되는 모양은 Optional.take() 로 꺼내는 것이다. store 와 complete 는 그대로 두고 wait() 와 cancel() 을 붙였다. wait() 안에서 withContinuation 을 불러 바로 store 하도록 했다.
ActorTake.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
import Foundation
actor LegacyBridge {
var continuation: Continuation<String, Never>?
func store(_ continuation: consuming Continuation<String, Never>) {
self.continuation = consume continuation
}
func complete(with value: String) {
continuation.take()?.resume(returning: value)
}
func cancel() {
self.continuation = nil
}
func wait() async -> String {
await withContinuation(of: String.self) { c in
self.store(c)
}
}
}
@main struct M {
static func main() async {
setvbuf(stdout, nil, _IONBF, 0)
let bridge = LegacyBridge()
async let v = bridge.wait()
try? await Task.sleep(for: .milliseconds(20))
await bridge.complete(with: "done")
print(await v)
if CommandLine.arguments.count > 1 {
async let w = bridge.wait()
try? await Task.sleep(for: .milliseconds(20))
print("cancel without resume")
await bridge.cancel()
print(await w)
}
}
}
1
2
3
4
bash diag.sh ActorTake.swift
xcrun swiftc -parse-as-library -swift-version 6 ActorTake.swift -o actortake
./actortake; echo "[exit $?]"
./actortake x; echo "[exit $?]"
1
2
3
4
5
6
7
[exit 0]
done
[exit 0]
done
cancel without resume
_Concurrency/Continuation.swift:56: Fatal error: Continuation was deinitialized without being resumed.
[exit 133]
진단 없이 컴파일된다. 인자 없이 돌리면 wait() 가 기다리다가 complete 로 resume 되어 done 이 나온다. 인자를 주면 두 번째 wait() 가 걸린 상태에서 cancel() 이 self.continuation = nil 로 continuation 을 resume 하지 않고 버려서 trap 이 난다. 제안서의 Missing-resume 예제와 같은 모양이다. 저장된 continuation 을 nil 로 덮어쓰는 순간 deinit 이 불린다.
self.store(c) 가 await 없이 동기로 불린 점을 보자. body 는 동기 closure 라서 안에서 await 를 쓸 수 없고, withContinuation 이 nonisolated(nonsending) 이라 body 가 wait() 를 부른 actor 위에서 돌기 때문에 동기 호출이 된다. 이 성질은 새 타입만의 이점이 아니다. 6.4 의 withCheckedContinuation 도 nonisolated(nonsending) 이어서(CheckedNC.swift 의 note 에 선언이 보인다) 기존 CheckedContinuation 을 actor 안에서 동기로 보관해도 된다.
CheckedActorSync.swift
1
2
3
4
5
6
7
8
9
10
actor LegacyBridge {
var continuation: CheckedContinuation<String, Never>?
func store(_ c: CheckedContinuation<String, Never>) { continuation = c }
func complete(with value: String) { continuation.take()?.resume(returning: value) }
func wait() async -> String {
await withCheckedContinuation { c in
self.store(c)
}
}
}
진단 없이 컴파일되고([exit 0]) 돌리면 done 이 나온다. 이 글의 Continuation 이 새로 주는 것은 이 동기 보관이 아니라 앞의 두 번 resume 의 컴파일 타임 검사다.
consume 과 async let 과 CommandLine.arguments
self.continuation = consume continuation 의 consume 은 이 지점이 변수의 마지막 사용이라고 컴파일러에게 알리는 연산자다. 값은 self.continuation 으로 옮겨 가고 원래 변수는 이후에 쓸 수 없다. async let v = bridge.wait() 는 wait() 를 자식 task 로 시작해 두고, 결과는 뒤의 await v 에서 받는 문법이다. CommandLine.arguments 는 프로그램을 실행할 때 준 인자의 배열이고 첫 원소가 실행 파일 이름이라서, count > 1 이면 인자를 준 것이다. 이 파일들은 인자 유무로 실패 경로를 켜고 끈다.
take 로 Optional 에서 꺼내기
Optional.take() 는 이 Optional 이 가진 값을 꺼내고 자기는 nil 이 되는 메서드다. continuation.take()?.resume(returning: value) 는 꺼낸 값이 있을 때만 resume 하고, 이미 꺼내 갔다면 아무 일도 하지 않는다. 같은 continuation 을 두 번 resume 하는 길을 막는 보관 방식이다.
CheckedContinuation 이나 UnsafeContinuation 으로 바꾸기
callback 이 둘이고 그중 하나만 불리는 라이브러리를 생각해 보자. Continuation 하나를 두 클로저가 나눠 쓸 수 없다. 이럴 때를 위해 Continuation 을 CheckedContinuation 이나 UnsafeContinuation 으로 바꾸는 이니셜라이저가 있다. 바꾼 뒤에는 복사가 가능하니 클로저에 넣을 수 있고, 안전은 런타임 검사에 맡긴다.
Convert.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
import Foundation
final class SomeLib: @unchecked Sendable {
var success: ((Int) -> Void)?
var failure: ((any Error) -> Void)?
func onSuccess(_ f: @escaping (Int) -> Void) { success = f }
func onFailure(_ f: @escaping (any Error) -> Void) { failure = f }
func fire() { success?(7) }
}
@main struct M {
static func main() async throws {
setvbuf(stdout, nil, _IONBF, 0)
let someLib = SomeLib()
let v = try await withContinuation(of: Int.self, throwing: (any Error).self) { c in
let checked = CheckedContinuation(c)
someLib.onSuccess { checked.resume(returning: $0) }
someLib.onFailure { checked.resume(throwing: $0) }
someLib.fire()
}
print("checked:", v)
let u = await withContinuation(of: Int.self) { c in
let unsafe = UnsafeContinuation(c)
unsafe.resume(returning: 8)
}
print("unsafe:", u)
if CommandLine.arguments.count > 1 {
_ = await withContinuation(of: Int.self) { c in
let checked = CheckedContinuation(c)
checked.resume(returning: 1)
checked.resume(returning: 2)
}
}
}
}
1
2
3
4
bash diag.sh Convert.swift
xcrun swiftc -parse-as-library -swift-version 6 Convert.swift -o convert
./convert; echo "[exit $?]"
./convert x; echo "[exit $?]"
1
2
3
4
5
6
7
8
9
[exit 0]
checked: 7
unsafe: 8
[exit 0]
checked: 7
unsafe: 8
_Concurrency/CheckedContinuation.swift:172: Fatal error: SWIFT TASK CONTINUATION MISUSE: main() tried to resume its continuation more than once, returning 2!
[exit 133]
CheckedContinuation(c) 로 바꾼 뒤에는 두 callback 에 걸어도 컴파일된다. checked: 7 과 unsafe: 8 이 나온다. 인자를 줘서 같은 checked continuation 을 두 번 resume 하면, Continuation 이 컴파일 에러로 막던 실수가 이번에는 런타임에 SWIFT TASK CONTINUATION MISUSE 로 멈춘다. 그림의 CheckedContinuation 칸이다. 이 변환은 변환하는 순간 Continuation 을 소비하므로 변환 뒤 원래의 c 를 쓸 수 없다.
ConvertTwice.swift
1
2
3
4
5
6
7
8
func f() async -> Int {
await withContinuation(of: Int.self) { c in
let checked = CheckedContinuation(c)
c.resume(returning: 1)
checked.resume(returning: 2)
}
}
@main struct M { static func main() async { print(await f()) } }
1
bash diag.sh ConvertTwice.swift
1
2
3
4
5
6
7
8
9
10
11
ConvertTwice.swift:2:42: error: 'c' consumed more than once
1 | func f() async -> Int {
2 | await withContinuation(of: Int.self) { c in
| `- error: 'c' consumed more than once
3 | let checked = CheckedContinuation(c)
| `- note: consumed here
4 | c.resume(returning: 1)
| `- note: consumed again here
5 | checked.resume(returning: 2)
6 | }
[exit 1]
변환 이니셜라이저가 consuming 파라미터를 받는 것을 컴파일러가 소비로 센다. 바꾼 쪽으로 일을 넘긴 뒤에도 원래 이름으로 resume 하려는 실수가 컴파일 에러로 남는다.
제안서는 이 때문에 CheckedContinuation 과 UnsafeContinuation 이 deprecated 되지 않는다고 쓴다. 수락 공지도 Continuation 이 어려운 자리에서는 CheckedContinuation 을 계속 쓰면 된다고 했다.
UnsafeContinuation 으로 같은 실수 해 보기
그림의 오른쪽 칸을 채우려고 UnsafeContinuation 에도 두 실수를 했다. 먼저 두 번 resume 이다.
UnsafeDouble.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import Foundation
func twice() async -> String {
await withUnsafeContinuation { (c: UnsafeContinuation<String, Never>) in
c.resume(returning: "a")
c.resume(returning: "b")
}
}
@main struct M {
static func main() async {
setvbuf(stdout, nil, _IONBF, 0)
print(await twice())
print("after twice")
}
}
1
2
3
4
5
bash diag.sh UnsafeDouble.swift
xcrun swiftc -Onone -parse-as-library -swift-version 6 UnsafeDouble.swift -o unsafedouble
./unsafedouble; echo "[exit $?]"
xcrun swiftc -O -parse-as-library -swift-version 6 UnsafeDouble.swift -o unsafedoubleO
./unsafedoubleO; echo "[exit $?]"
진단은 [exit 0] 한 줄이다. -Onone 으로 열 번 돌리면 매번 exit 134 이고 stderr 에 freed pointer was not the last allocation 이 나온다. stdout 은 실행마다 달랐다. 열 번 중 b 와 after twice 가 둘 다 나온 것이 세 번, b 만 나온 것이 다섯 번, 아무것도 안 나온 것이 두 번이다. 기다리던 쪽이 받은 값은 두 번째로 resume 한 b 였다. -O 로 빌드하면 세 번 모두 exit 139(SIGSEGV)로 끝났고, b 만 찍은 것이 두 번, after twice 까지 찍은 것이 한 번이다. 그림의 칸이 “진단 없음, crash” 이고 모양이 실행마다 다르다고 한 근거다.
UnsafeContinuation(c) 로 변환한 뒤 두 번 resume 하는 ConvertUnsafeDouble.swift 도 같다. -Onone 은 출력 없이 같은 메시지와 exit 134 로 세 번 모두 abort 했고, -O 는 네 번 모두 unsafe twice: 2 를 찍은 뒤 같은 메시지로 exit 134 였다. 변환해서 복사 가능해지면 Continuation 이 막아 주던 실수가 도로 열린다.
다음은 한 번도 resume 하지 않는 경우다. UnsafeMissing.swift 는 CheckedMissing.swift 의 withCheckedContinuation 만 withUnsafeContinuation 으로 바꿨다.
1
2
3
body returns without resuming
main still running, task cancelled? false
[exit 0]
경고 줄이 없다. CheckedMissing 과 다른 점은 그 한 줄뿐이다. 같은 body 를 task 없이 바로 기다리는 UnsafeHang.swift 는 body returns without resuming 만 찍고 끝나지 않아 timeout 5 가 끊었다(exit 124). 앞의 CheckedHang.swift 는 같은 모양에서 경고 한 줄이 먼저 나온 뒤에 똑같이 멈추니, 두 타입의 차이는 경고가 있느냐 없느냐다.
100만 번 resume 의 속도
제안서의 마지막 줄은 “런타임 오버헤드 없음” 이다. -O 로 같은 일을 100만 번 하는 파일을 세 번 돌렸다.
Bench.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
let n = 1_000_000
func viaNew() async -> Int { var s = 0; for i in 0..<n { s &+= await withContinuation(of: Int.self) { c in c.resume(returning: i) } }; return s }
func viaChecked() async -> Int { var s = 0; for i in 0..<n { s &+= await withCheckedContinuation { (c: CheckedContinuation<Int, Never>) in c.resume(returning: i) } }; return s }
func viaUnsafe() async -> Int { var s = 0; for i in 0..<n { s &+= await withUnsafeContinuation { (c: UnsafeContinuation<Int, Never>) in c.resume(returning: i) } }; return s }
@main struct M {
static func main() async {
let clock = ContinuousClock()
for (name, f) in [("Continuation", viaNew), ("CheckedContinuation", viaChecked), ("UnsafeContinuation", viaUnsafe)] as [(String, () async -> Int)] {
var r = 0
let d = await clock.measure { r = await f() }
print(name, d, r)
}
}
}
1
2
xcrun swiftc -O -parse-as-library -swift-version 6 Bench.swift -o bench
./bench
1
2
3
Continuation 0.094881042 seconds 499999500000
CheckedContinuation 0.212261167 seconds 499999500000
UnsafeContinuation 0.088073833 seconds 499999500000
같은 명령을 세 번 돌린 값이다.
| 회차 | Continuation | CheckedContinuation | UnsafeContinuation |
|---|---|---|---|
| 1 | 0.0949 초 | 0.2123 초 | 0.0881 초 |
| 2 | 0.0958 초 | 0.2159 초 | 0.0889 초 |
| 3 | 0.0942 초 | 0.2095 초 | 0.0894 초 |
Continuation 은 UnsafeContinuation 보다 세 번 모두 0.005 에서 0.007 초 느리지만 거의 같고, CheckedContinuation 은 두 배를 넘는다. 이 숫자는 이 기계에서 한 번 resume 하는 가장 단순한 경로를 반복해서 잰 것이라서, 기계와 일 내용에 따라 값이 달라진다. 의미 있는 것은 상대적인 순서다. 검사를 컴파일 타임과 deinit 으로 옮겼더니 resume 당 부담이 UnsafeContinuation 쪽에 가깝다.
ContinuousClock 으로 시간 재기
ContinuousClock 의 measure 는 받은 클로저가 도는 시간을 Duration 으로 돌려준다. 시스템 sleep 에도 흐르는 시계라서 벽시계 시간을 재기 좋다. 결과값 r 을 같이 출력하는 이유는 최적화가 루프 전체를 지워 버리지 않게 하려는 것이다.
스레드에서 오간 이야기
제안서 머리의 pitch 링크는 RigidArray 와 UniqueArray 의 pitch 를 가리키고, 그 스레드에 Continuation 이야기는 없다. 아래는 리뷰 스레드(2026-04-15 부터)와 수락 스레드를 시간순으로 따라간 것이다. 수락 공지는 “In response to pitch feedback” 이라고 써서 pitch 단계에서 source location 을 뺀 사실을 알려 준다.
리뷰 첫날: 좋은 생각이지만 아직 (2026-04-15)
Joe_Groff 가 리뷰를 열었다(#1, 04-15, 04-28 까지). 첫 의견은 KeithBauerANZ 였다(#2). 아이디어는 좋지만 세 가지를 걸었다. 첫째, ~Discardable 은 “컴파일러에게 늘 소비한다고 증명” 하는 것과 “동적으로 늘 소비한다” 가 달라서 Continuation 이 나중에 채택하기 어렵다. 둘째, UniqueArray(SE-0527)가 승인되어야 continuation 을 모아 둘 stdlib 타입이 생긴다. 셋째, Mutex.withLock 이 한 번만 부르는 클로저를 받기 전까지는 Optional(continuation) 과 take()! 같은 우회를 써야 한다. 그래서 CheckedContinuation 보다 runtime 검사가 오히려 늘고, 지금은 “yes, but not yet” 이라고 썼다. 앞에서 ContinuationSlot 이 바로 이 우회다.
ktoso 는 UniqueArray 만이 아니라 call-once 클로저도 필요하겠지만 그것이 도입을 막을 이유는 아니고, 타입 시스템이 나아지면서 쓰임이 점점 넓어질 것이며 그래서 복사 가능한 continuation 으로의 변환이 있다고 답했다(#3). ~Discardable 은 현실적으로 가능성이 낮고 future directions 는 “하겠다” 가 아니라 열린 아이디어일 뿐이며, 동적 crash 는 좋은 절충이라고도 했다(#4). Joe_Groff 는 ~Discardable 을 프로토콜로 모델링하지 않더라도 Continuation 같은 타입을 소비하지 않고 버린 뻔한 경우를 컴파일 타임에 warning 으로 알려 주는 방향을 생각해 볼 수 있다고 했다(#5). KeithBauerANZ 는 ~Discardable 이 실제로는 어렵다고 보면 future directions 에 둘 필요가 있느냐고 물었다(#6).
이름과 stdlib 에 넣을 자격 (2026-04-16 부터 04-21)
NotTheNHK 는 _Concurrency 와 async-algorithms 에 큰 개선이라며 환영했다. 다만 이 타입이 생기면 continuation 이 다섯 종류가 되는 것이 걸린다고 했다(#7). dmt 는 -1 쪽으로 기울었다(#8). stdlib API 를 깔끔하게 두자는 것, 이 구현이 stdlib 에만 있을 이유가 없고 패키지로도 된다는 것, stdlib 타입의 deinit 안 fatalError 는 가장 불투명한 crash 중 하나라는 것, ~Discardable 을 먼저 탐구해야 한다는 것이 이유였다. 그리고 Continuation 이라는 이름이 타협된 구현에 쓰기에는 너무 좋은 이름이라는 점도 들었다. 이어서(#9) 같은 사람이 call-once 클로저가 들어와도 통합 문제는 풀리지 않는다고 덧붙였다(#9). 레거시 콜백 API 가 그 주석을 달 가능성이 낮다는 이유였다. 대안으로 클로저 캡처에서 변경 가능한 var 캡처와 클로저에 붙는 deinit 블록을 제안했다.
ktoso 의 답은 이 타입을 외부 패키지에서는 구현할 수 없다는 것이었다(#10). 비복사 값을 지원하려면 builtin 에 직접 접근해야 하고 compiler 의 builtin 을 바꿔야 했다는 것이다. 또 기존 continuation 을 typed throws 와 비복사 값으로 확장하는 일은 더 무거운 작업이지만 여전히 목표라고 했고(“still a goal”), 기존 타입 자체를 ~Copyable 로 만들 수는 없다고 했다. 이 타입은 “절반만 된 것” 이 아니라 이런 종류의 타입을 정확히 이렇게 쓰고 싶은 모양이라고 했다. 이어서 crash 가 정확한 메서드를 가리킨다고 했는데(#11), 앞의 lldb 스택이 이 말과 맞는다(로컬에서 버린 경우다). call-once 클로저는 “사용처에서 주석을 달고 동적 검사를 넣는” 식으로 풀 수도 있겠다고 추측했다(#12).
dnadoba 는 ~Copyable 이 모자란 곳이 더 있어도 이 제안을 막아서는 안 되고 오히려 그 문제를 고칠 동기가 된다고 했다(#14). 그러면서 CheckedContinuation 은 malloc stack logging 으로 생성 지점의 backtrace 를 얻고 #function 이름을 남겼는데 새 타입이 만들어진 자리를 복원할 정보를 저장하느냐고 물었다. fclout 은 찬성하는 쪽이었다. 새 타입을 쓸 사람은 API 경계에서 Continuation 을 써야 하고, ~Discardable 이 아예 나오지 않을 수 있다는 가정에서 평가해야 한다고 했다(#15). 근거로 “CheckedContinuation 이 deinit 에서 trap 한다” 고 썼는데, 앞의 CheckedMissing.swift 측정에서는 경고 한 줄과 exit 0 이었다. Dmitriy_Ignatyev 는 ~Copyable continuation 을 참조 타입으로 감싸 Array 에 저장하는 우회를 제시했고(#16), stdlib 이 아니라 AsyncAlgorithms 에 두거나 실험 기능으로 하자고도 했다(#17). FranzBusch 는 자신이 직접 이 타입을 써 보려다 builtin 이 필요해서 막힌 경험을 들며 찬성했다(#19, 04-20). ~Discardable 은 ~Copyable 이나 ~Escapable 급의 큰 기능이라고 보았고, async-algorithms 의 MultiProducerSingleConsumer 같은 곳에 ~Copyable 을 지원할 수 있게 된다고 썼다. jeremyabannister 는 더 구체적인 이름으로 먼저 내고, ~Discardable 이 결정되면 typealias 로 Continuation 이라는 이름을 줄지 말지를 정하자고 했다(#20, 04-21).
죽을 것인가 경고할 것인가 (2026-04-22)
ellie20 은 deinit 이 프로그램을 crash 시키는 것은 전례가 없으니 경고만 남기자고 했다(#21). deinit 은 자원을 정리하는 곳이고 눈에 띄는 부작용을 갖지 않는 것이 관례라는 것, ~Copyable 이 없던 시절에 “복사하면 crash 하는 copy constructor” 를 둔 것과 같다는 것, 버려진 continuation 은 자원 낭비일 뿐 심각한 신호가 아니라는 것이다. 그리고 “특정 API 가 값을 버리지 않는다는 것에 사람들이 기대게 되는” Hyrum’s law 를 걱정했다. FranzBusch 는 leak 이 undefined behavior 는 아니어도 프로그램의 일부가 진행하지 못하는 상태이니 해롭지 않은 것이 아니고, 자기라면 서비스가 멈추기보다 crash 하는 편이 낫다고 반박했다(#22). hbaker 는 멈추는 것도 crash 도 둘 다 나쁜 경험이라며, 가장 단순한 경우(배열 안이 아닌 경우)만이라도 Continuation 에 한정해 컴파일 타임에 진단하자고 했다(#23).
라벨 이름 (2026-04-26)
NotTheNHK 가 failure 타입의 라벨을 throws 가 아니라 throwing 으로 하자고 했다. _Concurrency 의 다른 이름과 일관되게 하자는 것이었다(#24). 수락 때 바로 이 수정이 적용되었다. 리뷰 때의 throws: 로는 지금 컴파일되지 않는다는 것을 아래 마이그레이션 절에서 본다.
리뷰가 끝난 뒤의 source location (2026-05-05)
John_McCall 이 withContinuation 호출의 source location 을 crash 에 담지 않는다는 판단에 동의했다(#25). 올바르게 쓰는 사람에게 부담을 지우는 비용이 있고, 비복사 타입에서 잘못이 있는 쪽은 resume 하거나 소유권을 넘기지 않은 코드이니 deinit 이 불린 자리의 스택이 잘못한 쪽을 알려 준다는 것이다. 컨테이너에 들어 있어 간접적인 경우에도 스택이 컨테이너를 식별하고, 디버거는 resume 되지 않은 continuation 에서 멈춘 task 의 전체 스택을 보여 줄 수 있어야 한다는 것도 이유였다. 앞 lldb 절의 측정으로는 로컬 변수나 컨테이너(ActorTake, SlotTwice)가 버려지는 경우에는 이 말이 맞고, 다른 queue 에서 버려지면 만든 쪽은 스택에 보이지 않았다.
수락 (2026-05-06)
Joe_Groff 는 수락 공지(#1)에서 라벨 이름을 withContinuation(of:throwing:) 으로 바꾸는 수정을 붙여 수락했다. 이어서 우려 네 가지에 대한 답을 적었다. 이 글에서 풀어 쓴 요지만 옮긴다.
- 비복사 타입의 제약으로 쓰기 어렵다는 우려: 비복사 타입은 계속 발전 중이고, 어려운 자리는
CheckedContinuation으로 대신하면 된다 ~Discardable을 막게 된다는 우려: LSG 는 가까운 시일에 그 기능을 시작할 것으로 보지 않으며, 비복사 타입이 단일 소유와 단일 resume 을 강제하는 것만으로도 큰 개선이다. 나중에 생겨도 더 엄격한 제약이라~Copyable때처럼 여러 해에 걸친 전환이 필요할 것이고, 명백한 오용만 진단하는 제한된 진단을Continuation이 그대로 채택할 수 있다- source location 을 뺀 것: 타입을 포인터 하나로 가볍게 두는 것이 옳은 절충이다. 충돌 지점의 맥락이 더 중요하고, 디버거에서는 멈춘 task 의 위치로 시작 지점도 찾을 수 있다
deinit이 crash 해야 하느냐 leak 하고 경고만 하느냐: crash 가 맞다. 개발 중에 실수를 일찍 잡고, 나중에deinit을 막는 기능이 생길 때 leak 에 기대는 코드가 생겨 Hyrum’s law 가 걸림돌이 되는 일을 줄인다
jeremyabannister 가 같은 날 다시 이름 문제를 물었다(#2). 수락 근거가 “후회하는 것은 몇 년 뒤” 처럼 들린다며 이름을 임시로 바꾸는 방법이 안 되느냐는 것이었다. Joe_Groff 는 같은 이름 아래에 새 타입을 바꿔 넣어야 하면 @abi 같은 기능도 있고, 이미 비복사이고 deinit 에서 멈추는 타입이면 올바른 기존 코드가 그 deinit 에 도달하지 않으므로 ~Discardable 로 옮기는 것이 크게 걱정되지 않는다고 답했다(#3). 정적으로 Discardable 이 필요한 자리에서만 경고하는 중간 단계를 두면 된다는 것이다. j-f1 은 ~Discardable 이 non-Sendable 처럼 새 타입은 처음부터 컴파일 타임으로 강제하고 이전 타입은 낮은 언어 모드에서 경고와 런타임 trap 으로 남는 식으로 갈 수 있겠다고 덧붙였다(#4, 05-07).
수락 뒤: availability (2026-11-02 부터 11-03)
반년 뒤 bobko 가 이 API 가 @available(anyAppleOS 27.0, *) 라서 자기 프로젝트에서 stdlib 과 같은 것을 다시 만들어야 했다고 썼다(#5, 11-02). 언어 기능 위에 만든 것인데 런타임에 27 이 필요한 이유를 모르겠다는 것이다. benlings 는 같은 질문에 다른 스레드에서 받은 답이라며 Alejandro 의 말을 인용했다(#6). 곧 back deploy 될 가능성이 있고, Doug 가 만드는 swiftlang/swift#93430 가 그 일이라는 내용이다. benlings 는 이유가 고유한 type metadata 심볼이 필요한 것에 있을 것이라고 보았고 이 PR 의 목록에 Continuation 이 없다고 지적했다. Douglas_Gregor 가 Continuation 과 TaskID 를 그 PR 에 추가했다고 답했다(#7, 11-03).
기대 효과
- 같은 continuation 을 두 번 resume 하는 코드가 컴파일되지 않는다. 앞의
'c' consumed more than once가 그 출력이고 Swift 5 모드에서도 같다. 진단 없이 실행 때 crash 하던UnsafeContinuation(UnsafeDouble.swift)과CheckedContinuation의 런타임 검사가 하던 일을 컴파일 타임으로 올린 것이다 - resume 을 빠뜨리면 조용히 멈춘 채 남는 대신(
CheckedHang.swift,UnsafeHang.swift는 timeout 까지 끝나지 않았다) 그 자리에서Continuation was deinitialized without being resumed.로 멈춘다. 로컬에서 버리면 lldb 스택에 버린 closure 와 그 인자가 남는다 - 제안서는 할당과 atomic 연산이 없다고 쓴다. interface 에서도
withContinuation의 body 는@_alwaysEmitIntoClient로Builtin.withUnsafeContinuation { body(Continuation($0)) }한 번이고 저장 프로퍼티는context하나이며,Layout.swift는 8 바이트를 보여 준다. 100만 번 resume 은UnsafeContinuation(약 0.089 초)보다 0.005 에서 0.007 초 느린 약 0.095 초이고CheckedContinuation은 약 0.21 초다 Failure를throws(Failure)로 그대로 쓰는 한 함수라서 typed throws 가 자연스럽게 이어진다.fetch의catch에서error.code를 바로 읽은 것이 그 예다Success가~Copyable이어도 된다(FileHandleBox).withCheckedContinuation은 같은 타입을Copyable요구로 거절한다(CheckedNC.swift)- 이 타입을 쓰기 어려운 자리는
CheckedContinuation(c)로 바꿔 가면 된다. 빠져나갈 길이 막혀 있지 않다
다른 선택지는 왜 안 됐나
기존 continuation 에 검사만 더하기
CheckedContinuation 과 UnsafeContinuation 자체를 비복사 타입으로 바꾸는 길은 ktoso 가 불가능하다고 답했다(#10). 기존 타입의 복사 가능이라는 성질을 깰 수 없기 때문이다. 그래서 새 타입을 두고, 두 타입은 남겨 변환으로 이어 준다.
stdlib 이 아니라 패키지로 두기
dmt(#8)와 Dmitriy_Ignatyev(#17)가 제안했다. ktoso 는 비복사 값을 지원하는 이 타입은 builtin 에 직접 접근해야 하고 compiler 의 builtin 변경이 필요해서 stdlib 밖에서는 정확히 같은 타입을 만들 수 없다고 답했고(#10), dmt 는 이 점을 diff 에서 확인하지 않고 썼다며 사과했다(#18, 04-19). FranzBusch 도 자신이 같은 한계에 부딪혔다고 했다(#19).
먼저 ~Discardable 을 만들고 그 위에 올리기
KeithBauerANZ(#2), dmt(#8, #9), jeremyabannister(#20)가 이 쪽이었다. LSG 는 가까운 시일에 시작할 일이 아니라며 단일 소유와 단일 resume 의 정적 강제만으로도 큰 개선이라고 했다(수락 공지). Joe_Groff 는 이름을 같게 두고 @abi 같은 기능이나 경고 중심의 중간 단계로 옮길 수 있다고 했다(#3, 수락 스레드).
deinit 에서 경고만 남기기
ellie20 이 제안했다(#21). FranzBusch 는 leak 된 서비스가 진행하지 못하는 채로 있느니 crash 가 낫다고 했고(#22), 수락 공지는 crash 가 개발 중에 실수를 일찍 잡고 Hyrum’s law 로 leak 에 기대는 코드가 생기는 것을 줄인다는 이유로 crash 를 택했다. 앞의 CheckedMissing.swift 가 경고만 남기는 쪽의 모습이다. 프로그램은 끝까지 돌지만 기다리던 task 는 남는다. 기다리는 쪽이 main 이면 CheckedHang.swift 처럼 경고 뒤에 timeout 까지 멈춰 있다.
생성 위치를 담기
dnadoba 가 물은 것처럼 CheckedContinuation 은 #function 으로 생성 함수 이름을 갖는다(#14). Continuation 은 포인터 하나만 갖는다. John_McCall(#25)과 수락 공지는 비용과, 크래시 지점의 스택이 더 유용하다는 점으로 설명한다.
이름과 라벨
jeremyabannister 의 더 구체적인 이름(#20)은 채택되지 않았다. 라벨은 throws 에서 throwing 으로 바뀌었다(#24, 수락 공지).
함수를 둘로 나누기
제안서는 withContinuation 과 withThrowingContinuation 두 함수로 나누면 Never 와 any Error 만 덮고, withNetworkContinuation 같은 구체 에러 타입 API 를 표현할 수 없다고 쓴다. 앞의 typed catch: 404 가 구체 타입이 호출 지점까지 흐르는 모양이다.
Swift 6 모드와 마이그레이션
이 제안은 순수 추가라서 소스 호환성과 ABI 에 영향이 없다. Basic.swift 를 Swift 5 와 Swift 6 로 컴파일했다.
1
2
bash diag.sh -swift-version 5 Basic.swift
bash diag.sh -swift-version 6 Basic.swift
1
2
[exit 0]
[exit 0]
두 모드 모두 진단이 없다. Double.swift 의 consumed more than once 는 Swift 5 모드에서도 error 라는 것을 앞에서 봤다.
Continuation 은 흔한 이름이라 이미 같은 이름을 쓰는 코드가 있을 수 있다. 사용자가 Continuation 구조체와 withContinuation 함수를 직접 정의해도 소스는 그대로 컴파일된다.
UserNamed.swift
1
2
3
struct Continuation { let name: String }
func withContinuation(_ f: (Continuation) -> Void) { f(Continuation(name: "mine")) }
@main struct M { static func main() async { withContinuation { print($0.name) } } }
진단은 [exit 0] 이고 실행하면 mine 이 나온다. 자기 모듈에서 정의한 이름이 stdlib 의 이름보다 먼저 잡힌다.
availability
Continuation 과 withContinuation 은 anyAppleOS 27.0 이다. macOS 26 을 타깃으로 하면 이렇게 나온다.
1
xcrun swiftc -emit-sil -o /dev/null -parse-as-library -wmo -swift-version 6 -target arm64-apple-macos26 Avail.swift
1
2
3
4
5
6
7
8
Avail.swift:2:9: error: 'withContinuation(of:_:)' is only available in macOS 27.0 or newer
1 | func f() async -> Int {
| `- note: add '@available' attribute to enclosing global function
2 | await withContinuation(of: Int.self) { c in c.resume(returning: 1) }
| |- error: 'withContinuation(of:_:)' is only available in macOS 27.0 or newer
| `- note: add 'if #available' version check
3 | }
4 | @main struct M { static func main() async { print(await f()) } }
이전 OS 를 지원하는 앱은 if #available 로 갈라서 withCheckedContinuation 쪽과 둘을 같이 둬야 한다.
AvailGate.swift
1
2
3
4
5
6
7
8
func f() async -> Int {
if #available(macOS 27, *) {
return await withContinuation(of: Int.self) { c in c.resume(returning: 1) }
} else {
return await withCheckedContinuation { (c: CheckedContinuation<Int, Never>) in c.resume(returning: 2) }
}
}
@main struct M { static func main() async { print(await f()) } }
-target arm64-apple-macos26 로 컴파일하면 진단이 없이 [exit 0] 이다. 이 기계의 macOS 27 에서 돌리면 1 이 나온다. 스레드 절에서 본 것처럼 back deploy 는 swiftlang/swift#93430 이 Continuation 을 목록에 넣어 다루는 중이고, 6.4 SDK 에서 이 글이 돌린 availability 는 위 error 가 말하는 27.0 이다.
라벨 이름
리뷰에 올라간 이름이었던 throws: 로 호출해 본다.
OldLabel.swift
1
2
3
4
5
struct E: Error {}
func f() async throws(E) -> Int {
try await withContinuation(of: Int.self, throws: E.self) { c in c.resume(returning: 1) }
}
@main struct M { static func main() async { _ = try? await f() } }
1
bash diag.sh OldLabel.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
OldLabel.swift:3:60: error: extra trailing closure passed in call
1 | struct E: Error {}
2 | func f() async throws(E) -> Int {
3 | try await withContinuation(of: Int.self, throws: E.self) { c in c.resume(returning: 1) }
| `- error: extra trailing closure passed in call
4 | }
5 | @main struct M { static func main() async { _ = try? await f() } }
OldLabel.swift:3:52: error: cannot convert value of type 'E.Type' to expected argument type '(consuming Continuation<Int, Never>) -> Void'
1 | struct E: Error {}
2 | func f() async throws(E) -> Int {
3 | try await withContinuation(of: Int.self, throws: E.self) { c in c.resume(returning: 1) }
| `- error: cannot convert value of type 'E.Type' to expected argument type '(consuming Continuation<Int, Never>) -> Void'
4 | }
5 | @main struct M { static func main() async { _ = try? await f() } }
throws: 라벨은 인식되지 않는다. 컴파일러는 throws: 를 못 찾고 Never 판으로 풀려 해서 이렇게 엉뚱한 진단이 나온다. 앞의 Basic.swift 가 쓰는 throwing: 으로 적는다.
옮기는 길
제안서의 매핑을 따라 기계적으로 바꾼다.
| 지금 | 바꾼 뒤 |
|---|---|
withCheckedContinuation { ... } | withContinuation(of: T.self) { ... } |
withCheckedThrowingContinuation { ... } | withContinuation(of: T.self, throwing: (any Error).self) { ... } |
CheckedContinuation<T, E> | Continuation<T, E> |
옮기다가 막히는 곳은 두 군데다. 클로저가 continuation 을 캡처하는 모양은 앞의 Escaping.swift 의 error 로 막히니 ContinuationSlot 같은 Mutex 우회를 쓰거나 CheckedContinuation(c) 로 바꾼다. actor 의 저장 프로퍼티에서 if let 으로 푸는 모양은 ProposalActor.swift 의 error 로 막히니 take() 로 꺼낸다. CheckedContinuation 이 알려 주던 “한 번도 resume 하지 않음” 은 경고에서 즉시 trap 으로 강해지므로, 옮긴 뒤 테스트가 그 경로를 지난다면 이제 멈춘다는 점도 알아야 한다.
정리
Continuation<Success, Failure>는~Copyable이고resume이consuming이라서 같은 continuation 을 두 번 resume 하면 컴파일 error('c' consumed more than once)가 난다. Swift 5 모드에서도 같다- resume 하지 않고 버리면 컴파일러는 알려 주지 않고, 실행 때
Continuation was deinitialized without being resumed.로 멈춘다(exit 133). 로컬에서 버리면 스택에 버린 closure 가 남고 다른 queue 에서 버리면 만든 쪽이 안 보인다.CheckedContinuation은 같은 실수에 경고만 남기고,UnsafeContinuation은 두 번 resume 이 진단 없이 crash 하고 한 번도 안 하면 조용히 멈춘다 - 100만 번 resume 은
Continuation이 약 0.095 초,UnsafeContinuation약 0.089 초,CheckedContinuation약 0.21 초다(이 기계에서 세 번 같은 순서) withContinuation(of:throwing:)은 typed throws 를 쓰는 함수 하나이고,of:에는 기본값이 있어 closure 파라미터에 타입을 적으면 생략된다. 리뷰 때의throws:라벨은throwing:으로 바뀌어 수락되었다- callback 클로저가 캡처한
Continuation을 소비할 수 없어(@escaping이라서가 아니라 클로저가 몇 번 불릴지 모르기 때문이다) 바로 넣을 수 없고, 6.4 에서는Mutex로 감싸take()하거나CheckedContinuation(c)/UnsafeContinuation(c)로 바꾼다. 두 타입은 deprecated 되지 않는다 - 참조 타입(class, actor)의 저장 프로퍼티는
if let으로 소비할 수 없어take()로 꺼내야 한다. actor 안에서self.store(c)가 동기로 되는 것은nonisolated(nonsending)덕분이고withCheckedContinuation도 같다 - availability 는
anyAppleOS 27.0이고, 이전 OS 는if #available로 갈라야 한다. back deploy 는swiftlang/swift#93430에Continuation이 추가되었다
관련 글
- [SE-0430] sending parameter and result values:
resume(returning:)의consuming sending과withContinuation의sending Success가 쓰는 규칙 - [SE-0461] Run nonisolated async functions on the caller’s actor by default:
withContinuation이nonisolated(nonsending)이라 actor 안에서 body 가 바로 도는 이유 - [SE-0530] Async Result Support: 같은 묶음에서 typed throws 와 비동기 API 를 다룬 글
참고자료
- SE-0427: Noncopyable generics:
Success : ~Copyable이 가능한 근거
