Skip to content

Commit 90c1be8

Browse files
pblazejclaude
andauthored
Benchmarks (#925)
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
1 parent adcf813 commit 90c1be8

19 files changed

Lines changed: 1022 additions & 74 deletions

.github/workflows/benchmark.yaml

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
name: Benchmarks
2+
3+
permissions:
4+
contents: read
5+
6+
on:
7+
workflow_dispatch:
8+
schedule:
9+
- cron: '0 0 * * *'
10+
11+
jobs:
12+
benchmark:
13+
name: Benchmark
14+
runs-on: macos-latest
15+
timeout-minutes: 60
16+
env:
17+
LK_BENCHMARK: 1
18+
# LIVEKIT_URL: ${{ secrets.BENCHMARK_URL }}
19+
# LIVEKIT_API_KEY: ${{ secrets.BENCHMARK_API_KEY }}
20+
# LIVEKIT_API_SECRET: ${{ secrets.BENCHMARK_API_SECRET }}
21+
steps:
22+
- uses: actions/checkout@v6
23+
24+
- name: Install dependencies
25+
run: brew install livekit jemalloc swiftly && swiftly init --quiet-shell-followup --skip-install -y
26+
27+
- name: Run LiveKit Server
28+
run: livekit-server --dev &
29+
30+
- uses: maxim-lobanov/setup-xcode@v1
31+
with:
32+
xcode-version: latest
33+
34+
- name: Run Benchmarks
35+
working-directory: Benchmarks
36+
run: |
37+
swiftly run +xcode swift package --disable-sandbox \
38+
benchmark baseline update current
39+
40+
- name: Benchmark Report
41+
working-directory: Benchmarks
42+
run: |
43+
swiftly run +xcode swift package --disable-sandbox \
44+
benchmark baseline read current \
45+
--format markdown \
46+
| tee -a "$GITHUB_STEP_SUMMARY"

AGENTS.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,12 @@ xcodebuild build -scheme LiveKit -destination 'platform=macOS'
1212
# Run tests (requires local server: livekit-server --dev, install via brew install livekit)
1313
xcodebuild test -scheme LiveKit -only-testing LiveKitCoreTests -destination 'platform=macOS'
1414

15+
# Build benchmarks
16+
cd Benchmarks && swiftly run +xcode swift build
17+
18+
# Run benchmarks (requires local server: livekit-server --dev)
19+
cd Benchmarks && LK_BENCHMARK=1 swiftly run +xcode swift package --disable-sandbox benchmark
20+
1521
# List available simulators for platform-specific builds
1622
xcrun simctl list devices
1723
```
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
/*
2+
* Copyright 2026 LiveKit
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
import Foundation
18+
19+
/// Configuration for benchmark runs, read from environment variables.
20+
struct BenchmarkConfig {
21+
let url: String
22+
let apiKey: String
23+
let apiSecret: String
24+
let mode: InfrastructureMode
25+
26+
enum InfrastructureMode {
27+
case local
28+
case cloud(region: String?)
29+
}
30+
31+
/// Read benchmark configuration from environment variables.
32+
///
33+
/// Falls back to local defaults (`ws://localhost:7880`, `devkey`/`secret`)
34+
/// when environment variables are not set.
35+
///
36+
/// Override with:
37+
/// - `LIVEKIT_URL`: WebSocket URL (e.g., `wss://my-project.livekit.cloud`)
38+
/// - `LIVEKIT_API_KEY`: API key for token generation
39+
/// - `LIVEKIT_API_SECRET`: API secret for token generation
40+
/// - `LIVEKIT_BENCHMARK_REGION`: Server region (only used for cloud)
41+
static func fromEnvironment() -> BenchmarkConfig {
42+
let url = ProcessInfo.processInfo.environment["LIVEKIT_URL"] ?? "ws://localhost:7880"
43+
let apiKey = ProcessInfo.processInfo.environment["LIVEKIT_API_KEY"] ?? "devkey"
44+
let apiSecret = ProcessInfo.processInfo.environment["LIVEKIT_API_SECRET"] ?? "secret"
45+
46+
// Auto-detect mode from URL
47+
let mode: InfrastructureMode = if url.hasPrefix("ws://") || url.contains("localhost") {
48+
.local
49+
} else {
50+
.cloud(region: ProcessInfo.processInfo.environment["LIVEKIT_BENCHMARK_REGION"])
51+
}
52+
53+
return BenchmarkConfig(
54+
url: url,
55+
apiKey: apiKey,
56+
apiSecret: apiSecret,
57+
mode: mode
58+
)
59+
}
60+
}
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
/*
2+
* Copyright 2026 LiveKit
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
import Foundation
18+
import LiveKit
19+
20+
/// A ``Tracing`` implementation that retains completed spans for benchmark analysis.
21+
///
22+
/// The default ``LoggingTracer`` logs spans when they end. This implementation
23+
/// keeps them so benchmarks can extract timing data after operations complete.
24+
///
25+
/// Inject via `LiveKitSDK.setTracing()` before running benchmarks.
26+
27+
extension Span {
28+
/// All events as label → milliseconds relative to `start`.
29+
var splitMilliseconds: [String: Int64] {
30+
var result = [String: Int64]()
31+
for entry in entries {
32+
result[entry.label] = Int64((entry.time - start) * 1000)
33+
}
34+
return result
35+
}
36+
}
37+
38+
final class BenchmarkTracer: Tracing, @unchecked Sendable {
39+
private let _completedSpans = StateSync<[String: Span]>([:])
40+
41+
@discardableResult
42+
func beginSpan(_ name: String) -> Span {
43+
let span = Span(label: name)
44+
span.onEnd = { [weak self] span in
45+
self?._completedSpans.mutate { $0[name] = span }
46+
}
47+
return span
48+
}
49+
50+
/// Retrieve the most recently completed span with the given name.
51+
func completedSpan(_ name: String) -> Span? {
52+
_completedSpans.read { $0[name] }
53+
}
54+
55+
/// Clear all completed spans.
56+
func reset() {
57+
_completedSpans.mutate { $0.removeAll() }
58+
}
59+
}
Lines changed: 111 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,111 @@
1+
/*
2+
* Copyright 2026 LiveKit
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
import Foundation
18+
import LiveKit
19+
20+
/// A second SDK instance that acts as an echo participant for
21+
/// data channel and RPC benchmarks.
22+
///
23+
/// Connects to the same room and echoes:
24+
/// - Data channel messages back to the sender
25+
/// - RPC calls back with the same payload
26+
///
27+
/// Records its own processing timestamps for overhead decomposition.
28+
final class EchoParticipant: Sendable {
29+
let room: Room
30+
31+
/// Processing timestamps: (receive time, echo sent time) in microseconds
32+
/// relative to an arbitrary monotonic epoch.
33+
struct ProcessingTimestamp {
34+
let receiveUs: Int64
35+
let echoSentUs: Int64
36+
var overheadUs: Int64 { echoSentUs - receiveUs }
37+
}
38+
39+
private let _timestamps = StateSync<[ProcessingTimestamp]>([])
40+
// Strong reference to keep the delegate alive (MulticastDelegate uses weak references)
41+
private nonisolated(unsafe) var _echoDelegate: AnyObject?
42+
43+
var processingTimestamps: [ProcessingTimestamp] {
44+
_timestamps.copy()
45+
}
46+
47+
init() {
48+
room = Room()
49+
}
50+
51+
/// Connect to the specified room and set up echo handlers.
52+
func connect(url: String, token: String) async throws {
53+
try await room.connect(url: url, token: token)
54+
}
55+
56+
/// Register the echo RPC handler.
57+
///
58+
/// - Parameter delay: Optional delay in nanoseconds to simulate processing (for BM-RPC-003)
59+
func registerEchoRpc(delay: UInt64 = 0) async throws {
60+
try await room.registerRpcMethod("echo") { data in
61+
if delay > 0 {
62+
try await Task.sleep(nanoseconds: delay)
63+
}
64+
return data.payload
65+
}
66+
}
67+
68+
/// Set up data echo handler that echoes received data back to the sender.
69+
func setupDataEcho() {
70+
let delegate = DataEchoDelegate(room: room, timestamps: _timestamps)
71+
_echoDelegate = delegate
72+
room.delegates.add(delegate: delegate)
73+
}
74+
75+
func disconnect() async {
76+
await room.disconnect()
77+
}
78+
79+
func clearTimestamps() {
80+
_timestamps.mutate { $0.removeAll() }
81+
}
82+
}
83+
84+
/// Delegate that echoes data channel messages.
85+
private final class DataEchoDelegate: NSObject, RoomDelegate, @unchecked Sendable {
86+
private let room: Room
87+
private let timestamps: StateSync<[EchoParticipant.ProcessingTimestamp]>
88+
89+
init(room: Room, timestamps: StateSync<[EchoParticipant.ProcessingTimestamp]>) {
90+
self.room = room
91+
self.timestamps = timestamps
92+
super.init()
93+
}
94+
95+
func room(_: Room, participant _: RemoteParticipant?, didReceiveData data: Data, forTopic topic: String, encryptionType _: EncryptionType) {
96+
let recvTime = Int64(ProcessInfo.processInfo.systemUptime * 1_000_000)
97+
Task {
98+
try? await room.localParticipant.publish(
99+
data: data,
100+
options: .init(topic: topic)
101+
)
102+
let sentTime = Int64(ProcessInfo.processInfo.systemUptime * 1_000_000)
103+
timestamps.mutate {
104+
$0.append(EchoParticipant.ProcessingTimestamp(
105+
receiveUs: recvTime,
106+
echoSentUs: sentTime
107+
))
108+
}
109+
}
110+
}
111+
}
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
/*
2+
* Copyright 2026 LiveKit
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
import Foundation
18+
import LiveKitUniFFI
19+
20+
/// Generates LiveKit access tokens for benchmark participants.
21+
///
22+
/// Uses LiveKitUniFFI's `tokenGenerate` function, which provides the same
23+
/// HMAC-SHA256 JWT signing as the server SDKs.
24+
struct TokenGenerator {
25+
let apiKey: String
26+
let apiSecret: String
27+
28+
/// Generate a LiveKit access token.
29+
///
30+
/// - Parameters:
31+
/// - roomName: Room to grant access to
32+
/// - identity: Participant identity
33+
/// - canPublish: Whether the participant can publish tracks
34+
/// - canSubscribe: Whether the participant can subscribe to tracks
35+
/// - ttl: Token time-to-live in seconds (default: 300s / 5 minutes)
36+
func generate(
37+
roomName: String,
38+
identity: String,
39+
canPublish: Bool = true,
40+
canSubscribe: Bool = true,
41+
ttl: TimeInterval = 300
42+
) -> String {
43+
let grants = VideoGrants(
44+
roomCreate: false,
45+
roomList: false,
46+
roomRecord: false,
47+
roomAdmin: false,
48+
roomJoin: true,
49+
room: roomName,
50+
destinationRoom: "",
51+
canPublish: canPublish,
52+
canSubscribe: canSubscribe,
53+
canPublishData: true,
54+
canPublishSources: [],
55+
canUpdateOwnMetadata: false,
56+
ingressAdmin: false,
57+
hidden: false,
58+
recorder: false
59+
)
60+
61+
let options = TokenOptions(
62+
ttl: ttl,
63+
videoGrants: grants,
64+
identity: identity,
65+
name: identity
66+
)
67+
68+
let credentials = ApiCredentials(
69+
key: apiKey,
70+
secret: apiSecret
71+
)
72+
73+
do {
74+
return try tokenGenerate(options: options, credentials: credentials)
75+
} catch {
76+
fatalError("Failed to generate token: \(error)")
77+
}
78+
}
79+
}

0 commit comments

Comments
 (0)