[SE-0428] Resolve DistributedActor protocols
이 글은 Swift Evolution 제안서 원문과 포럼 리뷰 스레드를 Claude Code 로 정리한 글이다. 코드는 Xcode 27 의 Swift 6.4 컴파일러로 빌드하고, 진단 메시지와 실행 결과는 실제로 컴파일하고 실행해서 나온 것을 옮겼다.
제안서 정보
- 제안서: SE-0428 Resolve DistributedActor protocols
- 작성자: Konrad ‘ktoso’ Malawski, Pavel Yaskevich
- 리뷰 매니저: Freddy Kellison-Linn (Jumhyn)
- 상태: Implemented (Swift 6.0)
- 일정: Pitch 는 2024년 2월 9일부터, 리뷰는 2024년 3월 13일부터 4월 2일까지, 수락 공지는 2024년 4월 20일
- 포럼: Pitch, Review, Acceptance
한 줄 요약
@Resolvable 매크로를 DistributedActor 프로토콜에 붙이면 컴파일러가 $Greeter 같은 stub 타입을 만들어 준다. 클라이언트는 서버의 구체 actor 타입을 모른 채 프로토콜만으로 원격 actor 를 찾아 쓸 수 있다.
어떤 문제였나
distributed actor 는 다른 프로세스나 다른 기기에 있는 actor 를 같은 문법으로 부르게 해 주는 기능이다. 그런데 원격 actor 를 가리키는 참조를 만들려면 resolve(id:using:) 에 구체 actor 타입을 넘겨야 했다.
서버와 클라이언트를 따로 만드는 앱에서 이 점이 걸린다. 서버 쪽 EnglishGreeter 의 구현은 서버 모듈 안에 있고, 클라이언트는 그 구현을 보고 싶지 않다. 클라이언트가 알고 싶은 것은 “greet(name:) 을 부를 수 있는 무언가” 라는 약속, 곧 프로토콜뿐이다. 하지만 프로토콜 이름으로는 resolve 를 부를 수 없었다.
먼저 매크로 없이 프로토콜만 두었을 때 컴파일러가 뭐라고 하는지 확인했다.
1
2
3
4
5
6
7
8
9
10
11
12
import Distributed
protocol Greeter: DistributedActor where ActorSystem: DistributedActorSystem<any Codable> {
distributed func greet(name: String) -> String
}
func client(id: LocalTestingActorID, system: LocalTestingDistributedActorSystem) throws {
let a = try $Greeter.resolve(id: id, using: system)
let b = try Greeter.resolve(id: id, using: system)
let c: any Greeter = try .resolve(id: id, using: system)
_ = (a, b, c)
}
1
2
3
4
5
NoMacro.swift:8:15: error: cannot find '$Greeter' in scope
NoMacro.swift:9:15: error: static member 'resolve' cannot be used on protocol metatype '(any Greeter).Type'
NoMacro.swift:10:29: error: static member 'resolve' cannot be used on protocol metatype '(any Greeter).Type'
resolve 는 프로토콜 이름으로도, any Greeter 로도 부를 수 없었다. $Greeter 라는 이름은 아직 없다. 이 이름이 아래에서 매크로가 만들어 주는 stub 타입이다.
이 코드에 나온 API
- DistributedActor:
distributed actor가 따르는 프로토콜이다. 프로토콜에: DistributedActor를 적어 두면 이 프로토콜을 따르는 타입은 distributed actor 여야 한다. - DistributedActorSystem: actor 의 id 를 나눠 주고, 원격 호출을 실제로 전달하는 객체의 프로토콜이다.
<any Codable>은 이 system 이Codable로 인자를 주고받는다는 뜻이다. LocalTestingDistributedActorSystem: 한 프로세스 안에서 시험할 때 쓰는 Apple 의 기본 system 이다.
무엇이 바뀌나
@Resolvable 은 프로토콜 선언에 붙이는 매크로다. 이 매크로가 두 가지를 만든다.
$를 앞에 붙인 이름의 stub 타입 (protocol Greeter면$Greeter)- 프로토콜 요구사항마다 기본 구현이 들어 있는 extension
매크로가 만드는 코드
Swift 6.4 컴파일러에서 -Xfrontend -dump-macro-expansions 로 펼친 결과를 확인했다.
1
2
3
4
5
6
import Distributed
@Resolvable
protocol Greeter: DistributedActor where ActorSystem: DistributedActorSystem<any Codable> {
distributed func greet(name: String) -> String
}
1
2
3
4
5
6
distributed actor $Greeter<ActorSystem>: Greeter,
Distributed._DistributedActorStub
where ActorSystem: DistributedActorSystem<any Codable>
{
}
1
2
3
4
5
6
7
8
9
extension Greeter where Self: Distributed._DistributedActorStub {
distributed func greet(name: String) -> String {
if #available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *) {
Distributed._distributedStubFatalError()
} else {
fatalError()
}
}
}
만들어진 $Greeter 는 본문이 비어 있는 distributed actor 다. ActorSystem 이 제네릭 파라미터로 열려 있어서, 어떤 system 으로 resolve 하느냐에 따라 $Greeter<InProcSystem> 처럼 타입이 정해진다. 메서드 몸체는 extension 쪽에 있고, 호출하면 곧바로 멈추는 _distributedStubFatalError() 다. stub 은 원격 참조로만 쓰라는 타입이므로 몸체가 실행될 일이 없어야 한다.
두 가지를 눈여겨볼 만하다. 하나는 _DistributedActorStub 에 밑줄이 붙어 있다는 점이다. 6.4 SDK 의 인터페이스 파일에서 이 이름은 public protocol _DistributedActorStub 이다. public 이기는 하지만 밑줄이 붙어 있어서 직접 쓰라고 내놓은 API 는 아니고, 매크로 결과물이 따르는 표식이다. 다른 하나는 stub 에도 init(actorSystem:) 이 열려 있다는 점이다. nm 으로 API 모듈의 라이브러리를 보면 API.$Greeter.init(actorSystem:) 이 내보내진다. 이 init 으로 stub 을 직접 만들면 어떻게 되는지는 아래 “stub 을 직접 만들면” 에서 다뤘다.
이 코드에 나온 API
- Distributed 모듈:
distributed actor와 system 을 담은 Apple 모듈이다. @Resolvable:@attached(peer, names: prefixed(`$`))와@attached(extension, names: arbitrary)두 역할을 겸한 매크로다. peer 가 stub 타입을, extension 이 기본 구현을 만든다. SDK 의 인터페이스 파일에서 이 선언을 확인했다._distributedStubFatalError(function:): stub 의 메서드 몸체가 호출되면 실행을 멈추는 함수다. macOS 15 이상에서 쓸 수 있다.
서버와 클라이언트가 만나는 모습
이제 $Greeter 로 resolve 해서 실제로 호출해 봤다. Apple 의 LocalTestingDistributedActorSystem 은 stub 을 resolve 하지 못해서(아래에서 확인한다), 호출을 JSON 으로 바꿔 서버 쪽으로 넘기는 작은 system 을 직접 만들었다. 한 프로세스 안에 “server” 와 “client” 두 system 을 두는 방식이다. system 의 전체 코드는 샘플 저장소의 System.swift 에 있다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import Distributed
import Foundation
// API 쪽: 프로토콜만 안다
@Resolvable
protocol Greeter: DistributedActor where ActorSystem: DistributedActorSystem<any Codable> {
distributed func greet(name: String) -> String
}
// Server 쪽: 구체 actor
distributed actor EnglishGreeter: Greeter {
typealias ActorSystem = InProcSystem
distributed func greet(name: String) -> String {
"Hello, \(name)!"
}
}
// Client 쪽: 구체 타입 이름을 쓰지 않는다
func callGreeter(_ g: some Greeter) async throws -> String {
try await g.greet(name: "Caplin")
}
@main
struct Main {
static func main() async throws {
setvbuf(stdout, nil, _IOLBF, 0)
let serverSystem = InProcSystem(name: "server")
let clientSystem = InProcSystem(name: "client", peer: serverSystem)
let english = EnglishGreeter(actorSystem: serverSystem)
print("server actor id:", english.id)
let greeter = try $Greeter.resolve(id: english.id, using: clientSystem)
print("resolved type:", type(of: greeter), "isRemote:", __isRemoteActor(greeter))
let reply = try await greeter.greet(name: "Caplin")
print("reply:", reply)
print("via some Greeter:", try await callGreeter(greeter))
// 대조: 구체 타입으로 resolve 하면 target 이 구체 메서드 이름이다
let concrete = try EnglishGreeter.resolve(id: english.id, using: clientSystem)
print("concrete reply:", try await concrete.greet(name: "Caplin"))
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
server actor id: server-1
[client] resolve(id: server-1, as: $Greeter<InProcSystem>)
resolved type: $Greeter<InProcSystem> isRemote: true
[client] remoteCall on $Greeter<InProcSystem> target: $s6remote8$GreeterC5greet4nameS2S_tYaKFTE
[server] executeDistributedTarget on EnglishGreeter
[server] generic substitutions: ["6remote8$GreeterCyAA12InProcSystemCG"]
[server] decode argument 0 as String
reply: Hello, Caplin!
[client] remoteCall on $Greeter<InProcSystem> target: $s6remote8$GreeterC5greet4nameS2S_tYaKFTE
[server] executeDistributedTarget on EnglishGreeter
[server] generic substitutions: ["6remote8$GreeterCyAA12InProcSystemCG"]
[server] decode argument 0 as String
via some Greeter: Hello, Caplin!
[client] resolve(id: server-1, as: EnglishGreeter)
[client] remoteCall on EnglishGreeter target: $s6remote14EnglishGreeterC5greet4nameS2S_tYaKFTE
[server] executeDistributedTarget on EnglishGreeter
[server] generic substitutions: []
[server] decode argument 0 as String
concrete reply: Hello, Caplin!
10번 반복해서 돌려 봤고 출력은 매번 같았다. 출력에서 읽을 수 있는 것은 세 가지다.
resolve의 결과 타입이$Greeter<InProcSystem>이고isRemote: true다. 이 참조는 원격 참조다.- 클라이언트가 보낸 target 이름은
$s6remote8$GreeterC5greet...이고, 이 이름을 풀어 보면distributed thunk remote.$Greeter.greet(name:)이다. 곧$Greeter의 메서드를 가리킨다. 그런데 받는 쪽의executeDistributedTarget은on EnglishGreeter로 실행했고,decode argument 0 as String을 거쳐Hello, Caplin!이 돌아왔다. 서버는 이름이$Greeter로 적혀 온 호출을 구체 actor 의 같은 메서드로 이어 줬다. - 대조군으로 구체 타입
EnglishGreeter로 resolve 했을 때는 target 이$s6remote14EnglishGreeterC5greet...였다. 프로토콜로 부르든 구체 타입으로 부르든 결과 문자열은 같았다. 달랐던 것은 클라이언트가 보낸 이름과, 서버가 받은 generic substitutions 다. stub 으로 부르면["6remote8$GreeterCyAA12InProcSystemCG"]가 같이 갔고, 구체 타입으로 부르면[]였다.
some Greeter 를 받는 함수에 $Greeter 참조를 그대로 넘길 수 있었다는 점도 확인됐다. 클라이언트 코드의 나머지 부분은 stub 인지 진짜 actor 인지 따지지 않는다.
이 코드에 나온 API
resolve(id:using:): 이미 있는 actor 의 id 로 참조를 만든다. system 이 로컬에서 찾지 못하면 원격 참조를 돌려준다. 이 글의 예에서는InProcSystem이 항상 로컬에 없다고 답해서 원격 참조를 만들게 했다.executeDistributedTarget(on:target:invocationDecoder:handler:): 서버 쪽 system 이 받은 호출 정보를 풀어 실제 actor 의 메서드를 실행하는 함수다.- RemoteCallTarget: 클라이언트가 서버에 “이 메서드를 불러 달라” 고 보낼 때 쓰는 이름표다. 출력의
$s6remote8$Greeter...가 이 이름표의identifier다. __isRemoteActor(_:): 참조가 원격인지 알려 주는 표준 라이브러리 함수다. 이름에 밑줄이 있는 내부용 함수라서 이 글에서는 측정할 때만 썼다.
세 모듈로 나눠 빌드하면
실제 쓰임새는 API, Server, Client 모듈이 따로 있는 구성이다. 샘플도 그렇게 나눠 빌드했다. API 모듈에는 프로토콜과 시험용 InProcSystem 을 두고, Server 모듈의 구체 actor 는 internal 로 가렸다.
1
2
3
4
5
6
7
import Distributed
// API 모듈: 서버가 내놓을 API 표면만 적는다
@Resolvable
public protocol Greeter: DistributedActor where ActorSystem: DistributedActorSystem<any Codable> {
distributed func greet(name: String) -> String
}
API 모듈은 System.swift 와 함께 빌드했다. InProcSystem 은 이 파일에 있다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import Distributed
import API
// Server 모듈: 구체 actor 는 모듈 밖에 보이지 않는다 (internal)
distributed actor EnglishGreeter: Greeter {
typealias ActorSystem = InProcSystem
distributed func greet(name: String) -> String {
"Hello, \(name)! (from EnglishGreeter)"
}
}
nonisolated(unsafe) var keepAlive: [EnglishGreeter] = []
public func startServer(on system: InProcSystem) -> String {
let g = EnglishGreeter(actorSystem: system)
keepAlive.append(g)
return g.id
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import Distributed
import Foundation
import API
import Server
@main
struct Client {
static func main() async throws {
setvbuf(stdout, nil, _IOLBF, 0)
let serverSystem = InProcSystem(name: "server")
let clientSystem = InProcSystem(name: "client", peer: serverSystem)
let id = startServer(on: serverSystem)
// 클라이언트는 EnglishGreeter 라는 이름을 모른다
let greeter: any Greeter = try $Greeter.resolve(id: id, using: clientSystem)
print(try await greeter.greet(name: "Caplin"))
}
}
1
2
3
4
5
6
[client] resolve(id: server-1, as: $Greeter<InProcSystem>)
[client] remoteCall on $Greeter<InProcSystem> target: $s3API8$GreeterC5greet4nameS2S_tYaKFTE
[server] executeDistributedTarget on EnglishGreeter
[server] generic substitutions: ["3API8$GreeterCyAA12InProcSystemCG"]
[server] decode argument 0 as String
Hello, Caplin! (from EnglishGreeter)
이 샘플에서 Client 는 startServer 를 부르려고 Server 모듈을 import 했다. 그래도 EnglishGreeter 는 internal 이라 Client 코드에서 보이지 않는다. 시험 삼아 Client 쪽에서 EnglishGreeter.resolve(id:using:) 를 부르게 하면 다음 오류가 난다.
1
ClientConcrete.swift:6:15: error: cannot find 'EnglishGreeter' in scope
target 이름은 API.$Greeter 에서 시작했다 ($s3API8$GreeterC5greet..., 풀면 distributed thunk API.$Greeter.greet(name:)). $Greeter 는 API 모듈이 만든 타입이라 이 이름이 Client 와 Server 사이의 공통 언어가 된다. nm -gU libAPI.dylib 로 API 라이브러리가 내보내는 심볼도 확인했는데, static API.$Greeter.resolve(id:using:) 와 $Greeter 가 Greeter, _DistributedActorStub 를 따른다는 선언, 그리고 Greeter extension 의 greet(name:) thunk 가 들어 있었다. 이름에 GreeterC 가 들어간 심볼은 23 개였다.
프로퍼티와 반환값 없는 메서드
프로퍼티(distributed var)와 반환값이 없는 메서드(remoteCallVoid)도 같은 길로 전달됐다. 샘플의 RemoteMore.swift 를 돌린 결과다.
1
2
3
4
5
6
7
8
[client] remoteCall on $Greeter<InProcSystem> target: $s4more8$GreeterC8languageSSyYaKFTE
[server] executeDistributedTarget on KoreanGreeter
...
language: ko
[client] remoteCallVoid on $Greeter<InProcSystem> target: $s4more8$GreeterC4pingyyYaKFTE
[server] executeDistributedTarget on KoreanGreeter
...
(server) ping
값을 돌려주는 호출은 remoteCall, 돌려주지 않는 호출은 remoteCallVoid 로 갔다. 각각의 target 은 more.$Greeter.language() async throws -> Swift.String 과 more.$Greeter.ping() async throws -> () 로 풀렸다.
stub 을 직접 만들면
stub 에도 init(actorSystem:) 이 열려 있다는 앞의 관찰을 이어서, $Greeter 를 직접 만들어 봤다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import Distributed
import Foundation
@Resolvable
protocol Greeter: DistributedActor where ActorSystem: DistributedActorSystem<any Codable> {
distributed func greet(name: String) -> String
}
@main
struct Main {
static func main() async throws {
setvbuf(stdout, nil, _IOLBF, 0)
let system = LocalTestingDistributedActorSystem()
let local = $Greeter(actorSystem: system)
print("made local stub:", type(of: local), "isRemote:", __isRemoteActor(local))
print(try await local.greet(name: "Caplin"))
}
}
1
2
made local stub: $Greeter<LocalTestingDistributedActorSystem> isRemote: false
Distributed/DistributedActor.swift:463: Fatal error: Unexpected invocation of distributed method 'greet(name:)' stub!
컴파일은 통과했고, 만들어진 stub 은 isRemote: false 인 로컬 actor 였다. 메서드를 부르는 순간 Unexpected invocation of distributed method 'greet(name:)' stub! 이라는 메시지와 함께 멈췄다. 5번 돌려 5번 모두 exit 133 이었다. stub 은 resolve 로 만든 원격 참조로만 쓸 수 있고, 이 init 으로 만든 로컬 stub 의 메서드는 호출할 수 없다.
Apple 의 LocalTesting system 으로는
앞에서 직접 system 을 만든 까닭은 다음 실행에서 나왔다.
1
2
3
4
5
6
7
8
9
10
11
// 구체 타입으로 resolve
do {
let g = try EnglishGreeter.resolve(id: server.id, using: system)
print(try await g.greet(name: "Caplin"))
} catch { print("EnglishGreeter.resolve error:", error) }
// stub 으로 resolve
do {
let g = try $Greeter.resolve(id: server.id, using: system)
print(try await g.greet(name: "Caplin"))
} catch { print("$Greeter.resolve error:", error) }
위 코드는 샘플 Local.swift 에서 resolve 부분만 발췌했다.
1
2
3
4
server id: LocalTestingActorID(id: "1")
EnglishGreeter.resolve: EnglishGreeter remote: false
Hello, Caplin!
$Greeter.resolve error: LocalTestingDistributedActorSystemError(message: "Failed to resolve id \'LocalTestingActorID(id: \"1\")\' as $Greeter<LocalTestingDistributedActorSystem>.Type")
구체 타입으로는 resolve 가 됐고 Hello, Caplin! 이 나왔다. $Greeter 로는 등록된 actor 가 EnglishGreeter 인데 요청한 타입이 $Greeter<LocalTestingDistributedActorSystem> 라서, resolve 가 Failed to resolve id 를 던졌다. 그래서 이 글에서는 stub 을 resolve 할 수 있는 system 을 직접 만들어 썼다.
제네릭 distributed actor 와 remoteCall 의 요구사항
DistributedActorSystem 에는 SerializationRequirement 라는 primary associated type 이 있어서 DistributedActorSystem<any Codable> 이라고 적을 수 있고, ActorSystem 을 제네릭 파라미터로 받는 distributed actor 도 선언할 수 있다. $Greeter<ActorSystem> 이 그런 모양이다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
distributed actor DistributedAsyncSequence<Element, ActorSystem>
where Element: Sendable & Codable,
ActorSystem: DistributedActorSystem<any Codable> {
var elements: [Element]
init(elements: [Element], actorSystem: ActorSystem) {
self.elements = elements
self.actorSystem = actorSystem
}
distributed func exampleNextElement() async throws -> Element? {
elements.isEmpty ? nil : elements.removeFirst()
}
}
1
2
DistributedAsyncSequence<Int, LocalTestingDistributedActorSystem> -> Optional(1)
DistributedAsyncSequence<String, InProcSystem> -> Optional("x")
같은 actor 선언이 LocalTestingDistributedActorSystem 과 직접 만든 InProcSystem 에서 모두 돌았다.
이 코드에 나온 API
DistributedActorSystem<SerializationRequirement>: 프로토콜 선언은 macOS 13 부터다.<any Codable>표기는 macOS 13 을 대상으로 빌드해도 오류가 나지 않았다.remoteCall과remoteCallVoid요구사항은 macOS 15 부터다. SDK 인터페이스 파일과-target빌드로 확인했다.
컴파일러가 막아 주는 것
매크로가 무엇을 받아들이고 무엇을 거절하는지 몇 가지를 확인했다.
where 절이 없으면. ActorSystem 이 무엇인지 정해지지 않아서 stub 이 만들어지지 않는다.
1
2
3
4
@Resolvable
protocol Greeter: DistributedActor {
distributed func greet(name: String) -> String
}
1
2
3
4
5
6
7
8
macro expansion @Resolvable:1:19: error: distributed actor '$Greeter' does not declare ActorSystem it can be used with
`- NoSerial.swift:6:2: note: expanded code originates here
note: you can provide a module-wide default actor system by declaring:
typealias DefaultDistributedActorSystem = <#ConcreteActorSystem#>
macro expansion @Resolvable:1:19: error: type '$Greeter' does not conform to protocol 'DistributedActor'
macro expansion @Resolvable:1:19: error: type '$Greeter' does not conform to protocol 'Identifiable'
오류가 세 개 나오고, 끝에 protocol requires nested type 'ActorSystem' 같은 설명이 따라붙는다. 첫 오류 아래의 note 가 모듈 전체의 기본 system 을 선언하라고 알려 주는데, 이 방법은 아래에서 따로 확인했다.
where ActorSystem: DistributedActorSystem 만 적으면. primary associated type 을 빼고 적으면 매크로 자리에서는 오류가 없다. Name 이라는 Codable 이 아닌 타입을 구체 actor 의 인자로 쓰면 구체 actor 쪽에서 parameter 'name' of type 'Name' in distributed instance method does not conform to serialization requirement 'Codable' 오류가 난다. 클라이언트에서 stub 을 쓰는 코드는 컴파일을 통과한다. 직접 만든 InProcSystem 으로 실행해 봤다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import Distributed
import Foundation
struct Name { var value: String }
// ActorSystem 에 SerializationRequirement 를 적지 않았다
@Resolvable
protocol Greeter: DistributedActor where ActorSystem: DistributedActorSystem {
distributed func greet(name: Name) -> String
}
@main
struct Main {
static func main() async {
setvbuf(stdout, nil, _IOLBF, 0)
let server = InProcSystem(name: "server")
let client = InProcSystem(name: "client", peer: server)
do {
let g = try $Greeter.resolve(id: "server-1", using: client)
print("resolved:", type(of: g))
print(try await g.greet(name: Name(value: "Caplin")))
} catch {
print("error:", error)
}
}
}
1
2
[client] resolve(id: server-1, as: $Greeter<InProcSystem>)
resolved: $Greeter<InProcSystem>
출력이 여기서 끊기고 [client] remoteCall 줄이 나오지 않았다. 5번 중 5번 exit 139 였다. lldb 로 보면 dispatch thunk of Encodable.encode(to:) 안의 EXC_BAD_ACCESS 였고, 클라이언트가 인자를 인코딩하는 중에 멈춘 것이다. 이 결과는 직접 만든 InProcSystem 에서 쟀다. 그래서 where 절에는 DistributedActorSystem<any Codable> 처럼 직렬화 요구사항까지 적어 두는 쪽이 안전하다.
Codable 이 아닌 인자. 요구사항을 적었다면 컴파일러가 인자 타입을 검사한다.
1
2
3
4
5
6
struct Name { var value: String }
@Resolvable
protocol Greeter: DistributedActor where ActorSystem: DistributedActorSystem<any Codable> {
distributed func greet(name: Name) -> String
}
1
2
3
4
NonCodable.swift:7:20: error: parameter 'name' of type 'Name' in distributed instance method does not conform to serialization requirement 'Codable'
macro expansion @Resolvable:2:20: error: parameter 'name' of type 'Name' in distributed instance method does not conform to serialization requirement 'Codable'
`- NonCodable.swift:8:2: note: expanded code originates here
같은 오류가 프로토콜 선언과 매크로가 만든 extension 두 곳에서 나왔다.
distributed 가 아닌 요구사항. 프로토콜에 func localOnly() -> Int 를 적는 것 자체는 통과한다. 하지만 원격일 수 있는 참조에서 부르면 막힌다.
1
2
3
4
5
func client(id: LocalTestingActorID, system: LocalTestingDistributedActorSystem) async throws {
let g = try $Greeter.resolve(id: id, using: system)
_ = await g.localOnly()
_ = await g.whenLocal { $0.localOnly() }
}
1
2
3
LocalOnlyCall.swift:11:15: error: only 'distributed' instance methods can be called on a potentially remote distributed actor
LocalOnlyCall.swift:11:7: warning: no 'async' operations occur within 'await' expression [#UnnecessaryEffectMarker]
오류 하나와 함께 await 가 필요 없다는 경고도 나온다. whenLocal 로 감싼 줄은 통과했다. 참조가 로컬일 때만 클로저가 실행된다.
프로토콜이 아닌 곳에 붙이면. @Resolvable 을 actor 나 struct 에 붙이면 '@Resolvable' can only be applied to 'protocol', but was attached to 'actor' 오류가 난다.
associatedtype 이 있으면. 프로토콜에 associatedtype Element: Sendable & Codable 이 있으면 stub 이 그 타입을 정하지 못한다.
1
macro expansion @Resolvable:1:19: error: type '$DistributedAsyncSequence<ActorSystem>' does not conform to protocol 'DistributedAsyncSequence'
note 에는 protocol requires nested type 'Element' 가 붙는다. 매크로 없이 같은 프로토콜을 선언하면 통과하므로, 막힌 것은 stub 이다.
제네릭 메서드 요구사항. distributed func echo<T: Codable & Sendable>(_ value: T) -> T 요구사항은 컴파일은 통과했다. 실행 결과는 구체 타입과 stub 이 갈렸다.
직접 만든 InProcSystem 에서 구체 타입과 stub 을 나란히 불러 봤다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Resolvable
protocol Echo: DistributedActor where ActorSystem: DistributedActorSystem<any Codable> {
distributed func echo<T: Codable & Sendable>(_ value: T) -> T
}
distributed actor EchoServer: Echo {
typealias ActorSystem = InProcSystem
distributed func echo<T: Codable & Sendable>(_ value: T) -> T { value }
}
// main 에서
let concrete = try EchoServer.resolve(id: server.id, using: clientSystem)
print("concrete echo:", try await concrete.echo(42))
let stub = try $Echo.resolve(id: server.id, using: clientSystem)
print("stub echo:", try await stub.echo(42))
1
2
3
4
5
6
7
8
9
10
11
[client] resolve(id: server-1, as: EchoServer)
[client] remoteCall on EchoServer target: $s5gcall10EchoServerC4echoyxxYaKSeRzSERzlFTE
[server] executeDistributedTarget on EchoServer
[server] generic substitutions: ["Si"]
[server] decode argument 0 as Int
concrete echo: 42
[client] resolve(id: server-1, as: $Echo<InProcSystem>)
[client] remoteCall on $Echo<InProcSystem> target: $s5gcall5$EchoC4echoyqd__qd__YaKSeRd__SERd__lFTE
[server] executeDistributedTarget on EchoServer
[server] generic substitutions: ["5gcall5$EchoCyAA12InProcSystemCG", "Si"]
[server] decode argument 0 as Int
stub 으로 부른 쪽은 decode argument 0 as Int 까지 찍은 뒤 5번 중 5번 exit 139 로 멈췄다. lldb 에서는 swift_retain 안의 EXC_BAD_ACCESS 가 보였다. 이 결과는 직접 만든 InProcSystem 의 decodeGenericSubstitutions 구현에 묶여 있다. stub 쪽은 target 과 substitution 이 구체 타입과 다르게 서버에 닿았다. 같은 요구사항을 제네릭 없이 적으면 위의 greet(name:) 처럼 동작한다.
이 코드에 나온 API
whenLocal(_:): 참조가 로컬 actor 일 때만 클로저를 실행하고, 원격이면nil을 돌려주는 메서드다.
상속, 같은 system, 모듈 기본 system
프로토콜이 다른 프로토콜을 상속하면 부모와 자식 모두에 @Resolvable 을 붙이고, 자식에도 where 절을 다시 적어야 했다.
1
2
3
4
5
6
7
8
9
@Resolvable
protocol Named: DistributedActor where ActorSystem: DistributedActorSystem<any Codable> {
distributed var name: String { get }
}
@Resolvable
protocol Greeter: Named where ActorSystem: DistributedActorSystem<any Codable> {
distributed func greet(name: String) -> String
}
이 구성은 오류 없이 $Named<ActorSystem> 과 $Greeter<ActorSystem> 을 만들었고, $Named 에는 distributed var name 의 stub getter 가 생겼다. 반대로 확인한 세 가지가 있다.
- 부모에
@Resolvable이 없으면 앞의where절 없음 오류 세 개에type '$Greeter' does not conform to protocol 'Named'가 더해져 네 개가 난다. - 부모에 붙였어도 자식에서
where를 빼면 앞의where절 없음 오류 세 개가 그대로 난다. - 부모에
@Resolvable이 없고 자식에만where를 적으면type '$Greeter<ActorSystem>' does not conform to protocol 'Named'하나가 난다.
매크로는 프로토콜 자신의 where 절만 읽는다. 상속받은 쪽의 where 는 읽지 않는다.
where ActorSystem == LocalTestingDistributedActorSystem 처럼 한 system 으로 못 박으면 stub 이 제네릭이 아니게 된다. 펼친 결과는 distributed actor $Greeter: Greeter, Distributed._DistributedActorStub { typealias ActorSystem = LocalTestingDistributedActorSystem } 였다.
모듈 전체에 typealias DefaultDistributedActorSystem = LocalTestingDistributedActorSystem 을 선언하면 where 절이 없어도 오류가 나지 않고 비제네릭 $Greeter 가 만들어졌다. 다만 이 선언은 제네릭 distributed actor 와 부딪쳤다.
1
2
3
4
5
6
7
8
9
10
typealias DefaultDistributedActorSystem = LocalTestingDistributedActorSystem
distributed actor Worker<ActorSystem> where ActorSystem: DistributedActorSystem<any Codable> {
distributed func work() -> String { "done" }
}
func make(_ system: InProcSystem) -> String {
let w = Worker(actorSystem: system)
return "\(type(of: w)) \(type(of: w.actorSystem))"
}
1
2
3
GenericDefault.swift:10:11: error: generic parameter 'ActorSystem' could not be inferred
GenericDefault.swift:10:31: error: cannot convert value of type 'InProcSystem' to expected argument type 'DefaultDistributedActorSystem' (aka 'LocalTestingDistributedActorSystem')
모듈에 기본 system 이 있으면 Worker<InProcSystem>(actorSystem:) 처럼 타입을 명시해도 같은 변환 오류가 났고, Worker<LocalTestingDistributedActorSystem> 만 통과했다. 기본 system 선언이 없으면 같은 코드는 그대로 통과한다. @Resolvable 의 stub 에도 같은 영향이 있었다. where 절이 있어도 모듈에 기본 system 이 선언돼 있으면 $Greeter.resolve(id:using:) 에 InProcSystem 을 넘길 때 변환 오류가 났다. 그래서 여러 system 을 쓰는 모듈에서는 모듈 기본 system 을 선언하지 않고 where 절만 쓰는 쪽이 낫다.
스레드에서 오간 이야기
제안은 2024년 2월의 pitch 에서 시작해 3월의 리뷰를 거쳐 4월에 수락됐다. 오간 이야기를 시간 순서로 따라갔다.
Pitch: @DistributedProtocol 로 시작
2024년 2월 9일의 Pitch 에서 ktoso 가 @DistributedProtocol 이라는 이름의 매크로를 내놓았다. 예제로 PolishGreeter 가 “Dzień dobry, Caplin!” 라고 인사했다.
- Jeehut(#2)이 손으로 짜던 클라이언트 서버 통신(API 문서, JSON 인코딩과 디코딩)이 없어지느냐고 물었고, ktoso(#3)가 그렇다고 답했다.
- ksluder(#4)는 90년대 후반의 DCOM 과 CORBA 가 떠오른다고 했다. jaleel(#5)은 다른 언어와의 연동, 그리고 모놀리스와 API 분산 중 어느 쪽을 겨냥하느냐고 물었다.
- ktoso(#6)는 공개 API 라면 Swift OpenAPI 를 쓰는 편이 맞고, 이 제안은 프로세스 간 통신(IPC)과 기기에서 클라우드로 가는 경로를 겨냥한다고 답했다. 구글의 논문 “Towards Modern Development of Cloud Applications” 도 근거로 들었다.
- #8 에서 ktoso 는 OpenAPI 와 이어 보는 일은 살펴볼 만하지만 이 pitch 와는 별개라고 했다. greggwon(#10)은 Jini 와 River 를 떠올렸다.
Review: 매크로냐 언어 기능이냐
리뷰는 3월 13일에 Jumhyn 이 열었다(#1). 맨 처음에는 도구 체인 얘기가 많았다. Joannis_Orlandos(#2)가 macOS 용 도구 체인이 내려받아지지 않는다고 했고, ktoso(#3)는 curl 이나 wget 으로 이어받기를 쓰면 된다고 답하면서 매크로를 찾지 못하는 문제도 있다고 했다. #15 에서 ktoso 는 rintaro 가 고친 PR 72629 와, 그 도구 체인에 -Xfrontend -load-plugin-library 를 넘기는 방법을 알렸고, Jumhyn(#16)이 리뷰를 4월 2일까지 늘렸다.
논점의 중심은 매크로로 두는 것이 맞느냐였다.
- cal(#4)은
distributed protocol이라는 철자를 제안했다. Douglas_Gregor(#7)는 매크로가 만드는 코드는 소스에서@나#로 드러나야 하고, 유연함과 펼친 결과를 들여다볼 수 있다는 점에서 매크로 방식이 낫다고 썼다. ktoso(#8)도distributed protocol이 솔깃하지만 펼친 결과를 볼 수 있고, 나중에@DistributedProtocol(version: .v10)같은 인자가 더 생길 것 같다고 답했다. - wes1(#6)이
Codable이 아닌 직렬화를 물었고, ktoso(#9)는 직렬화는 actor 가 아니라 actor system 에 묶이고, 같은 프로세스 안의 actor 는 직렬화하지 않는다고 답했다. - stevapple(#10, #12)은 특별한 ABI 가 필요하니 매크로보다 언어 기능이어야 한다고 주장했다. Vision for Macros 의 “When is a language feature better than a macro?” 대목을 인용하며
@DistributedProtocol distributed protocol같은 꼴도 제안했다.
4월 4일에 jaleel(#17)이 직접 써 보고 같은 system 에 서로 다른 인스턴스를 둔 경우와, 두 system 을 따로 둔 경우를 시험했다고 알렸다. 같은 날 Douglas_Gregor(#19)가 이름을 문제 삼았다. 분산 프로토콜은 이미 존재하는데 @DistributedProtocol 이라는 이름은 마치 프로토콜 자체를 분산시키는 것처럼 읽히고, 실제로 하는 일은 클라이언트용 stub 타입을 만드는 것이라서 @RemoteStubs, @ClientStubs, @RemoteClient 같은 이름이 낫겠다고 했다. 이튿날 ktoso(#20)가 @Resolvable 을 제안했다. 이 이름이면 $MyProtocol.resolve() 라는 쓰임이 자연스럽고, 나중에 @Resolvable(stableName:) 같은 확장도 생각할 수 있다고 했다. jaleel(#21)도 Resolvable 이 잘 맞는다고 했다. 다만 무엇을 resolve 하는지가 헷갈릴 수 있다는 단서를 달았다.
Acceptance: 이름을 바꿔 수락
2024년 4월 20일 수락 공지에서 Jumhyn 은 제안을 수정을 붙여 수락했다(#1). 수정은 @DistributedProtocol 을 @Resolvable (또는 @Distributed.Resolvable)로 바꾸는 것이다. Language Steering Group 은 매크로로 코드를 만드는 접근이 매크로의 설계 철학에 맞는다고 봤고, 이름이 넓은 뜻을 가진 점은 Distributed 를 import 해야만 보이는 이름이고, 필요하면 @Distributed.Resolvable 로 구분해 쓸 수 있어서 받아들였다. ktoso(#2)가 4월 21일에 수정과 구현이 이어질 거라고 답했고, mackoj(#3)는 6월 12일에 Swift 6.0 에 들어가느냐고 물었다.
Swift 6.4 컴파일러에서 옛 이름을 써 봤다.
1
2
3
4
5
6
7
8
9
@DistributedProtocol
protocol A: DistributedActor where ActorSystem: DistributedActorSystem<any Codable> {
distributed func greet(name: String) -> String
}
@Distributed.Resolvable
protocol B: DistributedActor where ActorSystem: DistributedActorSystem<any Codable> {
distributed func greet(name: String) -> String
}
1
OldName.swift:3:2: error: unknown attribute 'DistributedProtocol'
@DistributedProtocol 은 알 수 없는 속성이고 @Distributed.Resolvable 은 통과했다.
기대 효과
- 클라이언트 모듈이 서버의 구체 actor 타입을 몰라도 된다. 클라이언트는 API 모듈이 내놓는 프로토콜과
$Greeter만 안다. - 손으로 짜던 클라이언트 서버 통신 코드(API 문서, JSON 인코딩과 디코딩)가 줄어든다. 프로토콜에 적은 요구사항이 stub 과 호출 이름표로 그대로 이어진다.
- 매크로 결과가 소스에서
@Resolvable로 드러나고-dump-macro-expansions로 펼쳐 볼 수 있어서, 무엇이 만들어졌는지 확인하기 쉽다. some Greeter나any Greeter를 받는 함수처럼 프로토콜 기반 코드에 원격 참조를 그대로 넘길 수 있다.- 제안서는 앞으로
@Resolvable(deprecatedName:)같은 프로토콜 진화 지원, 호출 target 메타데이터 맞춤 설정, swift-inspect 로 점검하는 일을 미래 방향으로 적어 두었다.
다른 선택지는 왜 안 됐나
제안서가 검토한 대안은 두 가지다.
- 피어 투 피어로 한정하기. 제안서가 짚은 논점은 이렇다. OpenAPI 나 gRPC 같은 소스 생성 방식이 맞지 않는 영역, 곧 같은 팀이 함께 관리하는 긴밀한 IPC 와 저수준 시스템이 있다. 그 영역에서도 소스 생성 도구 없이 언어 안에서 프로세스 경계를 다루게 하려고, 서버와 클라이언트 구성을 막지 않았다.
- 컴파일러가
.resolve에서 stub 을 만들어 주기.let g: any Greeter = try .resolve(...)처럼 쓰는 방식이다. 앞에서 확인한 대로 지금은static member 'resolve' cannot be used on protocol metatype '(any Greeter).Type'오류가 난다. 제안서는 이 방식이 호출 지점마다 익명 선언을 만들어 내는 컴파일러의 특수 경로가 되어 언어를 복잡하게 하고 distributed actor 에 특권을 준다는 이유로 접었고, stub 타입을 매크로가 눈에 보이게 만드는 쪽을 골랐다.
스레드에서 나온 대안은 distributed protocol 이라는 새 철자, 다른 매크로 이름, 언어 기능이었다. 이름은 수락 공지에서 @Resolvable 로 정리됐고, 나머지는 위 스레드 절의 논의대로 매크로로 남았다. 제안서 개정 이력에도 1.2 에서 #resolve 매크로를 뺀 일이 적혀 있다.
Swift 6 모드와 마이그레이션
System.swift 와 Remote.swift 를 modes.sh 로 Swift 5, Swift 5 에 -strict-concurrency=complete, Swift 6 세 모드에서 빌드했고, 세 모드 모두 오류와 경고가 나오지 않았다.
배포 대상 OS 는 이 제안을 쓸 때 가장 눈여겨볼 부분이다. -target arm64-apple-macosx14.0 으로 빌드하면 매크로 확장 안에서 오류가 난다.
1
macro expansion @Resolvable:1:43: error: '_DistributedActorStub' is only available in macOS 15.0 or newer
note 에는 add '@available' attribute to enclosing extension 이 따라붙었다. macOS 13 을 대상으로 해도 같은 오류가 하나 났고, macOS 12 는 DistributedActor 와 DistributedActorSystem 이 macOS 13 이상이라는 오류까지 합쳐 8개가 나왔다. macOS 15 대상은 오류가 없었다. 프로토콜에 @available(macOS 15.0, *) 를 직접 붙이면 macOS 14 대상에서도 통과했고, 매크로는 이 @available 을 $Greeter 와 extension 양쪽에 그대로 복사했다. 즉 macOS 15 이전을 대상으로 한다면 프로토콜에 @available 을 붙이는 방식으로 풀어야 했다.
정리
@Resolvable매크로가$Greeter같은 stub 타입과, 요구사항마다 기본 구현이 있는 extension 을 만든다. 6.4 에서 stub 은Distributed._DistributedActorStub을 따르고, 이 타입은 public 이지만 밑줄이 붙어 직접 쓰라고 내놓은 API 는 아니다.$Greeter.resolve(id:using:)가 원격 참조를 만들고, 클라이언트는 구체 actor 의 이름 없이 호출했다. 호출 target 은$Greeter의 메서드를 가리키고, 서버의executeDistributedTarget이 구체 actor 의 메서드로 이어 줬다.- 3모듈 빌드에서도 구체 actor 는
internal로 가려진 채 호출이 끝까지 갔다. where ActorSystem: DistributedActorSystem<any Codable>이 필요하다. 직렬화 요구사항을 빼면 컴파일은 되지만, 직접 만든InProcSystem에서 클라이언트가 인자를 인코딩하다 멈췄다.Codable이 아닌 인자, associatedtype, 프로토콜 아닌 대상은 컴파일 오류다.- Apple 의 LocalTesting system 은 stub 을 resolve 하지 못했고, stub 을
init으로 직접 만들어 메서드를 부르면 실행이 멈췄다. - 제네릭 distributed 메서드 요구사항을 직접 만든
InProcSystem에서 stub 으로 부르면 5번 중 5번 실행이 멈췄다. - 대상 OS 가 macOS 15 미만이면 프로토콜에
@available을 붙여야 한다. - 이름은 리뷰 중에
@DistributedProtocol에서@Resolvable로 바뀌었다.
| 측정한 것 | 결과 |
|---|---|
| stub 으로 resolve 후 호출 (Remote.swift, 10회) | 매번 같은 출력, Hello, Caplin! |
| 세 모듈 빌드 | 구체 actor 이름 없이 호출 성공 |
where 절 없음 | 컴파일 오류 3개 |
직렬화 요구사항 없는 where | 컴파일 통과, 실행 exit 139 (5/5) |
stub 을 init 으로 생성 후 호출 | exit 133 (5/5) |
| 제네릭 메서드 요구사항 (stub) | exit 139 (5/5) |
| macOS 14 이하 대상 | _DistributedActorStub 오류 |
관련 글
- [SE-0420] Inheritance of actor isolation:
isolateddistributed actor 와asLocalActor를 다룬 글이다.

