test_vllm.py 16.7 KB
Newer Older
1
2
3
# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

4
5
6
7
8
9
10
11
12
"""
Test Execution Times (Last Run: 2025-12-09):
- test_request_migration_vllm_worker_failure: ~90s (gpu_1)
- test_request_migration_vllm_graceful_shutdown: ~80s (gpu_1)
- test_no_request_migration_vllm_worker_failure: ~75s (gpu_1)
- test_no_request_migration_vllm_graceful_shutdown: ~75s (gpu_1)
- Total: 318.73s (0:05:18)
"""

13
14
15
16
17
18
19
20
21
import logging
import os
import shutil

import pytest

from tests.utils.constants import FAULT_TOLERANCE_MODEL_NAME
from tests.utils.managed_process import ManagedProcess, terminate_process_tree
from tests.utils.payloads import check_models_api
22
from tests.utils.port_utils import allocate_port, deallocate_port
23
24
25
26
27
28
29
30
31
32
33
34

# Import utilities from the refactored utils module
from .utils import (
    DynamoFrontendProcess,
    determine_request_receiving_worker,
    start_completion_request,
    validate_completion_response,
    verify_migration_occurred,
)

logger = logging.getLogger(__name__)

35
36
37
38
39
pytestmark = [
    pytest.mark.vllm,
    pytest.mark.gpu_1,
    pytest.mark.e2e,
    pytest.mark.model(FAULT_TOLERANCE_MODEL_NAME),
40
    pytest.mark.post_merge,  # post_merge to pinpoint failure commit
41
42
]

43
44
45
46

class DynamoWorkerProcess(ManagedProcess):
    """Process manager for Dynamo worker with vLLM backend"""

47
48
49
50
51
52
53
    def __init__(
        self,
        request,
        worker_id: str,
        frontend_port: int,
        migration_limit: int = 3,
    ):
54
        self.worker_id = worker_id
55
56
57
58
59
        self.frontend_port = frontend_port

        # Allocate system port for this worker
        system_port = allocate_port(9100)
        self.system_port = system_port
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75

        command = [
            "python3",
            "-m",
            "dynamo.vllm",
            "--model",
            FAULT_TOLERANCE_MODEL_NAME,
            "--enforce-eager",
            "--gpu-memory-utilization",
            "0.45",
            "--max-model-len",
            "8192",
            "--migration-limit",
            str(migration_limit),
        ]

76
        # Set environment variables
77
        env = os.environ.copy()
78
79
        env["DYN_REQUEST_PLANE"] = request.getfixturevalue("request_plane")

80
81
82
83
84
85
        env[
            "DYN_VLLM_KV_EVENT_PORT"
        ] = f"2008{worker_id[-1]}"  # TODO: use dynamic port allocation
        env[
            "VLLM_NIXL_SIDE_CHANNEL_PORT"
        ] = f"560{worker_id[-1]}"  # TODO: use dynamic port allocation
86

87
        env["DYN_LOG"] = "debug"
88
89
90
91
92
        # Disable canary health check - these tests expect full control over requests
        # sent to the workers where canary health check intermittently sends dummy
        # requests to workers interfering with the test process which may cause
        # intermittent failures
        env["DYN_HEALTH_CHECK_ENABLED"] = "false"
93
        env["DYN_SYSTEM_USE_ENDPOINT_HEALTH_STATUS"] = '["generate"]'
94
95
        env["DYN_SYSTEM_PORT"] = str(system_port)
        env["DYN_HTTP_PORT"] = str(frontend_port)
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112

        # TODO: Have the managed process take a command name explicitly to distinguish
        #       between processes started with the same command.
        log_dir = f"{request.node.name}_{worker_id}"

        # Clean up any existing log directory from previous runs
        try:
            shutil.rmtree(log_dir)
            logger.info(f"Cleaned up existing log directory: {log_dir}")
        except FileNotFoundError:
            # Directory doesn't exist, which is fine
            pass

        super().__init__(
            command=command,
            env=env,
            health_check_urls=[
113
114
                (f"http://localhost:{frontend_port}/v1/models", check_models_api),
                (f"http://localhost:{system_port}/health", self.is_ready),
115
116
117
118
119
120
121
122
123
            ],
            timeout=300,
            display_output=True,
            terminate_existing=False,
            stragglers=["VLLM::EngineCore"],
            straggler_commands=["-m dynamo.vllm"],
            log_dir=log_dir,
        )

124
125
126
127
128
129
130
131
132
    def __exit__(self, exc_type, exc_val, exc_tb):
        """Release allocated port when worker exits."""
        try:
            # system_port is always allocated in __init__
            deallocate_port(self.system_port)
        except Exception as e:
            logging.warning(f"Failed to release vLLM worker port: {e}")

        return super().__exit__(exc_type, exc_val, exc_tb)
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148

    def is_ready(self, response) -> bool:
        """Check the health of the worker process"""
        try:
            data = response.json()
            if data.get("status") == "ready":
                logger.info(f"{self.worker_id} status is ready")
                return True
            logger.warning(
                f"{self.worker_id} status is not ready: {data.get('status')}"
            )
        except ValueError:
            logger.warning(f"{self.worker_id} health response is not valid JSON")
        return False


149
@pytest.mark.timeout(290)  # 3x average
150
151
152
153
154
155
156
157
158
159
160
@pytest.mark.parametrize(
    "request_plane",
    [
        "nats",
        pytest.param(
            "tcp",
            marks=pytest.mark.xfail(reason="Multi-worker TCP unstable", strict=False),
        ),
    ],
    indirect=True,
)
161
def test_request_migration_vllm_worker_failure(
162
    request, runtime_services_dynamic_ports, set_ucx_tls_no_mm, predownload_models
163
164
165
166
167
168
169
):
    """
    End-to-end test for worker fault tolerance with migration support.

    This test verifies that when a worker is killed during request processing,
    the system can handle the failure gracefully and migrate the request to
    another worker.
170
171
172
173
174

    Timing (Last Run: 2025-12-09): ~90s total
    - Engine initialization: ~40s (Worker1: 20s, Worker2: 20s)
    - Test execution (request + migration): ~48s
    - Teardown: ~2s
175
176
    """

177
    # Step 1: Start the frontend (allocates its own frontend_port)
178
179
180
    with DynamoFrontendProcess(request) as frontend:
        logger.info("Frontend started successfully")

181
182
        # Step 2: Start 2 workers sequentially (each allocates its own system_port)
        with DynamoWorkerProcess(request, "worker1", frontend.frontend_port) as worker1:
183
184
            logger.info(f"Worker 1 PID: {worker1.get_pid()}")

185
186
187
            with DynamoWorkerProcess(
                request, "worker2", frontend.frontend_port
            ) as worker2:
188
189
190
                logger.info(f"Worker 2 PID: {worker2.get_pid()}")

                # Step 3: Send the request
191
192
193
                request_thread, response_list = start_completion_request(
                    frontend.frontend_port
                )
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212

                # Step 4: Use polling to determine which worker received the request
                worker, worker_name = determine_request_receiving_worker(
                    worker1, worker2, receiving_pattern="Decode Request ID: "
                )

                # Step 5: Kill the worker that has the request
                logger.info(
                    f"Killing {worker_name} with PID {worker.get_pid()} processing the request"
                )
                terminate_process_tree(worker.get_pid(), immediate_kill=True, timeout=0)

                # Step 6: Validate the completion response
                validate_completion_response(request_thread, response_list)

                # Step 7: Verify migration occurred
                verify_migration_occurred(frontend)


213
@pytest.mark.timeout(280)  # 3x average
214
215
216
217
218
219
220
221
222
223
224
@pytest.mark.parametrize(
    "request_plane",
    [
        "nats",
        pytest.param(
            "tcp",
            marks=pytest.mark.xfail(reason="Multi-worker TCP unstable", strict=False),
        ),
    ],
    indirect=True,
)
225
def test_request_migration_vllm_graceful_shutdown(
226
    request, runtime_services_dynamic_ports, set_ucx_tls_no_mm, predownload_models
227
228
229
230
231
232
233
234
235
):
    """
    End-to-end test for worker fault tolerance with graceful shutdown and migration support.

    This test verifies that when a worker receives a graceful shutdown signal (SIGTERM)
    during request processing, the system can handle the shutdown gracefully and migrate
    the request to another worker. Unlike the abrupt kill test, this simulates a more
    controlled shutdown scenario where the worker has time to clean up and notify the
    system about its shutdown.
236
237
238
239
240

    Timing (Last Run: 2025-12-09): ~80s total
    - Engine initialization: ~40s (Worker1: 20s, Worker2: 20s)
    - Test execution (graceful shutdown + migration): ~38s
    - Teardown: ~2s
241
242
    """

243
    # Step 1: Start the frontend (allocates its own frontend_port)
244
245
246
    with DynamoFrontendProcess(request) as frontend:
        logger.info("Frontend started successfully")

247
248
        # Step 2: Start 2 workers sequentially (each allocates its own system_port)
        with DynamoWorkerProcess(request, "worker1", frontend.frontend_port) as worker1:
249
250
            logger.info(f"Worker 1 PID: {worker1.get_pid()}")

251
252
253
            with DynamoWorkerProcess(
                request, "worker2", frontend.frontend_port
            ) as worker2:
254
255
256
                logger.info(f"Worker 2 PID: {worker2.get_pid()}")

                # Step 3: Send the request
257
258
259
                request_thread, response_list = start_completion_request(
                    frontend.frontend_port
                )
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280

                # Step 4: Use polling to determine which worker received the request
                worker, worker_name = determine_request_receiving_worker(
                    worker1, worker2, receiving_pattern="Decode Request ID: "
                )

                # Step 5: Gracefully shutdown the worker that has the request
                logger.info(
                    f"Gracefully shutting down {worker_name} with PID {worker.get_pid()} processing the request"
                )
                terminate_process_tree(
                    worker.get_pid(), immediate_kill=False, timeout=10
                )

                # Step 6: Validate the completion response
                validate_completion_response(request_thread, response_list)

                # Step 7: Verify migration occurred during graceful shutdown
                verify_migration_occurred(frontend)


281
@pytest.mark.timeout(150)  # 3x average
282
283
284
285
286
287
288
289
290
291
292
@pytest.mark.parametrize(
    "request_plane",
    [
        "nats",
        pytest.param(
            "tcp",
            marks=pytest.mark.xfail(reason="Multi-worker TCP unstable", strict=False),
        ),
    ],
    indirect=True,
)
293
def test_no_request_migration_vllm_worker_failure(
294
    request, runtime_services_dynamic_ports, set_ucx_tls_no_mm, predownload_models
295
296
297
298
299
300
301
):
    """
    End-to-end test for worker fault tolerance with migration disabled.

    This test verifies that when migration is disabled (migration_limit=0) and a worker
    is killed during request processing, the request fails as expected without migration.
    This is the opposite behavior of test_request_migration_vllm_worker_failure.
302
303
304
305
306

    Timing (Last Run: 2025-12-09): ~75s total
    - Engine initialization: ~40s (Worker1: 20s, Worker2: 20s)
    - Test execution (failure validation): ~33s
    - Teardown: ~2s
307
308
    """

309
    # Step 1: Start the frontend (allocates its own frontend_port)
310
311
312
    with DynamoFrontendProcess(request) as frontend:
        logger.info("Frontend started successfully")

313
314
315
316
        # Step 2: Start 2 workers sequentially with migration disabled (each allocates its own system_port)
        with DynamoWorkerProcess(
            request, "worker1", frontend.frontend_port, migration_limit=0
        ) as worker1:
317
318
            logger.info(f"Worker 1 PID: {worker1.get_pid()}")

319
320
321
            with DynamoWorkerProcess(
                request, "worker2", frontend.frontend_port, migration_limit=0
            ) as worker2:
322
323
324
                logger.info(f"Worker 2 PID: {worker2.get_pid()}")

                # Step 3: Send the request
325
326
327
                request_thread, response_list = start_completion_request(
                    frontend.frontend_port
                )
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362

                # Step 4: Use polling to determine which worker received the request
                worker, worker_name = determine_request_receiving_worker(
                    worker1, worker2, receiving_pattern="Decode Request ID: "
                )

                # Step 5: Kill the worker that has the request
                logger.info(
                    f"Killing {worker_name} with PID {worker.get_pid()} processing the request"
                )
                terminate_process_tree(worker.get_pid(), immediate_kill=True, timeout=0)

                # Step 6: Validate the completion response - should fail without migration
                try:
                    validate_completion_response(request_thread, response_list)
                    pytest.fail(
                        "Request succeeded unexpectedly when migration was disabled"
                    )
                except AssertionError as e:
                    assert "Request failed with status 500: " in str(
                        e
                    ), f"Unexpected request error message: {e}"

                # Step 7: Verify migration did NOT occur - should fail
                try:
                    verify_migration_occurred(frontend)
                    pytest.fail(
                        "Migration verification unexpectedly passed when migration was disabled"
                    )
                except AssertionError as e:
                    assert "'Cannot recreate stream: ...' error found in logs" in str(
                        e
                    ), f"Unexpected migration message: {e}"


363
@pytest.mark.timeout(140)  # 3x average
364
365
366
367
368
369
370
371
372
373
374
@pytest.mark.parametrize(
    "request_plane",
    [
        "nats",
        pytest.param(
            "tcp",
            marks=pytest.mark.xfail(reason="Multi-worker TCP unstable", strict=False),
        ),
    ],
    indirect=True,
)
375
def test_no_request_migration_vllm_graceful_shutdown(
376
    request, runtime_services_dynamic_ports, set_ucx_tls_no_mm, predownload_models
377
378
379
380
381
382
383
384
):
    """
    End-to-end test for worker fault tolerance with graceful shutdown and migration disabled.

    This test verifies that when migration is disabled (migration_limit=0) and a worker
    receives a graceful shutdown signal (SIGTERM) during request processing, the request
    fails as expected without migration. This is the opposite behavior of
    test_request_migration_vllm_graceful_shutdown.
385
386
387
388
389

    Timing (Last Run: 2025-12-09): ~75s total
    - Engine initialization: ~40s (Worker1: 20s, Worker2: 20s)
    - Test execution (graceful shutdown validation): ~33s
    - Teardown: ~2s
390
391
    """

392
    # Step 1: Start the frontend (allocates its own frontend_port)
393
394
395
    with DynamoFrontendProcess(request) as frontend:
        logger.info("Frontend started successfully")

396
397
398
399
        # Step 2: Start 2 workers sequentially with migration disabled (each allocates its own system_port)
        with DynamoWorkerProcess(
            request, "worker1", frontend.frontend_port, migration_limit=0
        ) as worker1:
400
401
            logger.info(f"Worker 1 PID: {worker1.get_pid()}")

402
403
404
            with DynamoWorkerProcess(
                request, "worker2", frontend.frontend_port, migration_limit=0
            ) as worker2:
405
406
407
                logger.info(f"Worker 2 PID: {worker2.get_pid()}")

                # Step 3: Send the request
408
409
410
                request_thread, response_list = start_completion_request(
                    frontend.frontend_port
                )
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445

                # Step 4: Use polling to determine which worker received the request
                worker, worker_name = determine_request_receiving_worker(
                    worker1, worker2, receiving_pattern="Decode Request ID: "
                )

                # Step 5: Gracefully shutdown the worker that has the request
                logger.info(
                    f"Gracefully shutting down {worker_name} with PID {worker.get_pid()} processing the request"
                )
                terminate_process_tree(
                    worker.get_pid(), immediate_kill=False, timeout=10
                )

                # Step 6: Validate the completion response - should fail without migration
                try:
                    validate_completion_response(request_thread, response_list)
                    pytest.fail(
                        "Request succeeded unexpectedly when migration was disabled"
                    )
                except AssertionError as e:
                    assert "Request failed with status 500: " in str(
                        e
                    ), f"Unexpected request error message: {e}"

                # Step 7: Verify migration did NOT occur - should fail
                try:
                    verify_migration_occurred(frontend)
                    pytest.fail(
                        "Migration verification unexpectedly passed when migration was disabled"
                    )
                except AssertionError as e:
                    assert "'Cannot recreate stream: ...' error found in logs" in str(
                        e
                    ), f"Unexpected migration message: {e}"