test_launch_router.py 12.4 KB
Newer Older
Byron Hsu's avatar
Byron Hsu committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import multiprocessing
import time
import unittest
from types import SimpleNamespace


def terminate_process(process: multiprocessing.Process, timeout: float = 1.0) -> None:
    """Terminate a process gracefully, with forced kill as fallback.

    Args:
        process: The process to terminate
        timeout: Seconds to wait for graceful termination before forcing kill
    """
    if not process.is_alive():
        return

    process.terminate()
    process.join(timeout=timeout)
    if process.is_alive():
        process.kill()  # Force kill if terminate didn't work
        process.join()


class TestLaunchRouter(unittest.TestCase):
25
26
27
    def setUp(self):
        """Set up default arguments for router tests."""
        self.default_args = SimpleNamespace(
Byron Hsu's avatar
Byron Hsu committed
28
29
30
            host="127.0.0.1",
            port=30000,
            policy="cache_aware",
31
            worker_startup_timeout_secs=600,
32
            worker_startup_check_interval=10,
Byron Hsu's avatar
Byron Hsu committed
33
34
35
            cache_threshold=0.5,
            balance_abs_threshold=32,
            balance_rel_threshold=1.0001,
36
            eviction_interval_secs=60,
Byron Hsu's avatar
Byron Hsu committed
37
            max_tree_size=2**24,
38
            max_payload_size=256 * 1024 * 1024,  # 256MB
Byron Hsu's avatar
Byron Hsu committed
39
            verbose=False,
40
            log_dir=None,
41
            log_level=None,
42
43
44
45
            service_discovery=False,
            selector=None,
            service_discovery_port=80,
            service_discovery_namespace=None,
46
            dp_aware=False,
47
48
            prometheus_port=None,
            prometheus_host=None,
49
50
51
            request_timeout_secs=60,
            max_concurrent_requests=64,
            cors_allowed_origins=[],
52
            pd_disaggregation=False,
53
54
55
            prefill=None,
            decode=None,
            worker_urls=[],
56
57
58
59
60
61
62
63
64
65
66
            retry_max_retries=3,
            retry_initial_backoff_ms=100,
            retry_max_backoff_ms=10_000,
            retry_backoff_multiplier=2.0,
            retry_jitter_factor=0.1,
            cb_failure_threshold=5,
            cb_success_threshold=2,
            cb_timeout_duration_secs=30,
            cb_window_duration_secs=60,
            disable_retries=False,
            disable_circuit_breaker=False,
67
68
            model_path=None,
            tokenizer_path=None,
Byron Hsu's avatar
Byron Hsu committed
69
70
        )

71
72
73
74
75
76
77
78
79
    def create_router_args(self, **kwargs):
        """Create router arguments by updating default args with provided kwargs."""
        args_dict = vars(self.default_args).copy()
        args_dict.update(kwargs)
        return SimpleNamespace(**args_dict)

    def run_router_process(self, args):
        """Run router in a separate process and verify it starts successfully."""

Byron Hsu's avatar
Byron Hsu committed
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
        def run_router():
            try:
                from sglang_router.launch_router import launch_router

                router = launch_router(args)
                if router is None:
                    return 1
                return 0
            except Exception as e:
                print(e)
                return 1

        process = multiprocessing.Process(target=run_router)
        try:
            process.start()
            # Wait 3 seconds
            time.sleep(3)
            # Process is still running means router started successfully
            self.assertTrue(process.is_alive())
        finally:
            terminate_process(process)

102
103
104
105
106
107
    def test_launch_router_common(self):
        args = self.create_router_args(worker_urls=["http://localhost:8000"])
        self.run_router_process(args)

    def test_launch_router_with_empty_worker_urls(self):
        args = self.create_router_args(worker_urls=[])
108
109
110
        self.run_router_process(
            args
        )  # Should start successfully with empty worker list
111

112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
    def test_launch_router_with_service_discovery(self):
        # Test router startup with service discovery enabled but no selectors
        args = self.create_router_args(
            worker_urls=[], service_discovery=True, selector=["app=test-worker"]
        )
        self.run_router_process(args)

    def test_launch_router_with_service_discovery_namespace(self):
        # Test router startup with service discovery enabled and namespace specified
        args = self.create_router_args(
            worker_urls=[],
            service_discovery=True,
            selector=["app=test-worker"],
            service_discovery_namespace="test-namespace",
        )
        self.run_router_process(args)

129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
    def test_launch_router_common_with_dp_aware(self):
        args = self.create_router_args(
            worker_urls=["http://localhost:8000"],
            dp_aware=True,
        )
        self.run_router_process(args)

    def test_launch_router_with_empty_worker_urls_with_dp_aware(self):
        args = self.create_router_args(
            worker_urls=[],
            dp_aware=True,
        )
        self.run_router_process(args)

    def test_launch_router_common_with_dp_aware_service_discovery(self):
        # Test launch router with bot srevice_discovery and dp_aware enabled
        # Should fail since service_discovery and dp_aware is conflict
        args = self.create_router_args(
            worker_urls=["http://localhost:8000"],
            dp_aware=True,
            service_discovery=True,
            selector=["app=test-worker"],
        )

        def run_router():
            try:
                from sglang_router.launch_router import launch_router

                router = launch_router(args)
                if router is None:
                    return 1
                return 0
            except Exception as e:
                print(e)
                return 1

        process = multiprocessing.Process(target=run_router)
        try:
            process.start()
            # Wait 3 seconds
            time.sleep(3)
            # Should fail since service_discovery and dp_aware is conflict
            self.assertFalse(process.is_alive())
        finally:
            terminate_process(process)

175
176
177
178
179
    def test_launch_router_pd_mode_basic(self):
        """Test basic PD router functionality without actually starting servers."""
        # This test just verifies the PD router can be created and configured
        # without actually starting it (which would require real prefill/decode servers)
        from sglang_router.launch_router import RouterArgs
180
        from sglang_router.router import PolicyType, Router
181
182
183
184

        # Test RouterArgs parsing for PD mode
        # Simulate the parsed args structure from argparse with action="append"
        args = self.create_router_args(
185
            pd_disaggregation=True,
186
187
188
189
190
191
192
193
194
195
196
197
198
            policy="power_of_two",  # PowerOfTwo is only valid in PD mode
            prefill=[
                ["http://prefill1:8080", "9000"],
                ["http://prefill2:8080", "none"],
            ],
            decode=[
                ["http://decode1:8081"],
                ["http://decode2:8081"],
            ],
            worker_urls=[],  # Empty for PD mode
        )

        router_args = RouterArgs.from_cli_args(args)
199
        self.assertTrue(router_args.pd_disaggregation)
200
201
202
203
204
205
206
207
208
209
210
        self.assertEqual(router_args.policy, "power_of_two")
        self.assertEqual(len(router_args.prefill_urls), 2)
        self.assertEqual(len(router_args.decode_urls), 2)

        # Verify the parsed URLs and bootstrap ports
        self.assertEqual(router_args.prefill_urls[0], ("http://prefill1:8080", 9000))
        self.assertEqual(router_args.prefill_urls[1], ("http://prefill2:8080", None))
        self.assertEqual(router_args.decode_urls[0], "http://decode1:8081")
        self.assertEqual(router_args.decode_urls[1], "http://decode2:8081")

        # Test Router creation in PD mode
211
        router = Router.from_args(router_args)
212
213
214
215
216
217
        self.assertIsNotNone(router)

    def test_policy_validation(self):
        """Test that policy validation works correctly for PD and regular modes."""
        from sglang_router.launch_router import RouterArgs, launch_router

218
        # Test 1: PowerOfTwo requires at least 2 workers
219
        args = self.create_router_args(
220
            pd_disaggregation=False,
221
            policy="power_of_two",
222
            worker_urls=["http://localhost:8000"],  # Only 1 worker
223
224
225
226
227
228
        )

        # Should raise error
        with self.assertRaises(ValueError) as cm:
            launch_router(args)
        self.assertIn(
229
            "Power-of-two policy requires at least 2 workers",
230
231
232
            str(cm.exception),
        )

233
        # Test 2: PowerOfTwo with sufficient workers should succeed
234
        args = self.create_router_args(
235
236
237
            pd_disaggregation=False,
            policy="power_of_two",
            worker_urls=["http://localhost:8000", "http://localhost:8001"],  # 2 workers
238
        )
239
        # This should not raise an error (validation passes)
240

241
        # Test 3: All policies now work in both modes
242
243
        # Regular mode with RoundRobin
        args = self.create_router_args(
244
            pd_disaggregation=False,
245
246
247
            policy="round_robin",
            worker_urls=["http://localhost:8000"],
        )
248
        # This should not raise validation error
249

250
        # PD mode with RoundRobin (now supported!)
251
        args = self.create_router_args(
252
            pd_disaggregation=True,
253
            policy="round_robin",
254
255
256
257
            prefill=[["http://prefill1:8080", "9000"]],
            decode=[["http://decode1:8081"]],
            worker_urls=[],
        )
258
        # This should not raise validation error
259

260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
    def test_pd_service_discovery_args_parsing(self):
        """Test PD service discovery CLI argument parsing."""
        import argparse

        from sglang_router.launch_router import RouterArgs

        parser = argparse.ArgumentParser()
        RouterArgs.add_cli_args(parser)

        args = parser.parse_args(
            [
                "--pd-disaggregation",
                "--service-discovery",
                "--prefill-selector",
                "app=sglang",
                "component=prefill",
                "--decode-selector",
                "app=sglang",
                "component=decode",
                "--service-discovery-port",
                "8000",
                "--service-discovery-namespace",
                "production",
                "--policy",
                "cache_aware",
            ]
        )

        router_args = RouterArgs.from_cli_args(args)

        self.assertTrue(router_args.pd_disaggregation)
        self.assertTrue(router_args.service_discovery)
        self.assertEqual(
            router_args.prefill_selector, {"app": "sglang", "component": "prefill"}
        )
        self.assertEqual(
            router_args.decode_selector, {"app": "sglang", "component": "decode"}
        )
        self.assertEqual(router_args.service_discovery_port, 8000)
        self.assertEqual(router_args.service_discovery_namespace, "production")

    def test_regular_service_discovery_args_parsing(self):
        """Test regular mode service discovery CLI argument parsing."""
        import argparse

        from sglang_router.launch_router import RouterArgs

        parser = argparse.ArgumentParser()
        RouterArgs.add_cli_args(parser)

        args = parser.parse_args(
            [
                "--service-discovery",
                "--selector",
                "app=sglang-worker",
                "environment=staging",
                "--service-discovery-port",
                "8000",
                "--policy",
                "round_robin",
            ]
        )

        router_args = RouterArgs.from_cli_args(args)

        self.assertFalse(router_args.pd_disaggregation)
        self.assertTrue(router_args.service_discovery)
        self.assertEqual(
            router_args.selector, {"app": "sglang-worker", "environment": "staging"}
        )
        self.assertEqual(router_args.prefill_selector, {})
        self.assertEqual(router_args.decode_selector, {})

333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
    def test_empty_worker_urls_args_parsing(self):
        """Test that router accepts no worker URLs and defaults to empty list."""
        import argparse

        from sglang_router.launch_router import RouterArgs

        parser = argparse.ArgumentParser()
        RouterArgs.add_cli_args(parser)

        # Test with no --worker-urls argument at all
        args = parser.parse_args(["--policy", "random", "--port", "30000"])
        router_args = RouterArgs.from_cli_args(args)
        self.assertEqual(router_args.worker_urls, [])

        # Test with explicit empty --worker-urls
        args = parser.parse_args(["--worker-urls", "--policy", "random"])
        router_args = RouterArgs.from_cli_args(args)
        self.assertEqual(router_args.worker_urls, [])

Byron Hsu's avatar
Byron Hsu committed
352
353
354

if __name__ == "__main__":
    unittest.main()