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

4
import json
5
6
7
8
9
10
11
12
import logging
import threading
import time

import pytest
import requests

from tests.utils.constants import FAULT_TOLERANCE_MODEL_NAME
13
14
15
from tests.utils.managed_process import (
    DynamoFrontendProcess as BaseDynamoFrontendProcess,
)
16
from tests.utils.managed_process import ManagedProcess, terminate_process_tree
17
18
19
20

logger = logging.getLogger(__name__)


21
22
class DynamoFrontendProcess(BaseDynamoFrontendProcess):
    """Fault-tolerance frontend wrapper (keeps env settings from the historical helper)."""
23

24
    def __init__(self, request, enforce_disagg: bool = False):
25
26
27
28
29
30
        extra_env = {
            "DYN_REQUEST_PLANE": request.getfixturevalue("request_plane"),
            # These tests expect full control over requests sent to workers. The canary
            # health check can inject extra requests and cause intermittent failures.
            "DYN_HEALTH_CHECK_ENABLED": "false",
        }
31
32
33
        extra_args = []
        if enforce_disagg:
            extra_args.append("--enforce-disagg")
34
        super().__init__(
35
36
37
            request,
            frontend_port=0,  # allocate a free port (xdist-safe)
            router_mode="round-robin",
38
            extra_args=extra_args if extra_args else None,
39
            extra_env=extra_env,
40
            terminate_all_matching_process_names=False,
41
            display_name="frontend",
42
43
        )

44

45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
def _parse_completion_sse_content(line: str) -> str | Exception | None:
    """
    Parse an SSE line from the completions API and extract the text content.

    Args:
        line: Raw SSE line string

    Returns:
        str: The text content if found
        Exception: If error event or parse error
        None: If no content (e.g., [DONE] or empty)
    """
    if line.startswith("event: error"):
        return Exception(f"SSE error event received: {line}")

    if not line.startswith("data: "):
        return None  # Skip non-data lines

    data_str = line[6:]  # Remove "data: " prefix
    if data_str == "[DONE]":
        return None

    try:
        chunk = json.loads(data_str)
        text = chunk["choices"][0].get("text")
        return text  # May be None if no text content
    except Exception as e:
        return Exception(f"Error parsing response chunk: {e}")


def start_completion_request(
    frontend_port: int, stream: bool, use_long_prompt: bool = False
) -> tuple:
78
79
80
    """
    Start a long-running completion request in a separate thread.

81
82
83
    Responses are processed internally to extract content. First entry is (None, start_time)
    to mark when request was sent. Subsequent entries contain extracted content or exceptions.

84
85
    Args:
        frontend_port: Port where the frontend is running
86
87
        stream: Whether to use streaming responses
        use_long_prompt: Whether to use a long prompt (~8000 tokens)
88

89
    Returns:
90
91
92
93
        tuple: (request_thread, response_list) where response_list contains
               (str | None | Exception, float) tuples.
               - For streaming: each entry is (content_word, timestamp)
               - For non-streaming: single entry is (full_content, timestamp)
94
    """
95
    response_list: list[tuple[str | None | Exception, float]] = []
96
97
98

    def send_request():
        prompt = "Tell me a long long long story about yourself?"
99
100
        if use_long_prompt:
            prompt += " Make sure it is" + " long" * 8000 + "!"
101
102
103
104
105
        timeout = 240  # Extended timeout for long request

        payload = {
            "model": FAULT_TOLERANCE_MODEL_NAME,
            "prompt": prompt,
106
            "stream": stream,
107
108
109
110
        }
        headers = {"Content-Type": "application/json"}

        logger.info(
111
            f"Sending completion request (stream={stream}) with prompt: '{prompt[:50]}...'"
112
113
        )

114
115
        response_list.append((None, time.time()))  # start timestamp

116
        try:
117
            with requests.post(
118
                f"http://localhost:{frontend_port}/v1/completions",
119
120
121
                headers=headers,
                json=payload,
                timeout=timeout,
122
123
124
125
126
127
128
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
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
                stream=stream,
            ) as response:
                logger.info(
                    f"Received response with status code: {response.status_code}"
                )
                if response.status_code != 200:
                    response_list.append(
                        (
                            Exception(
                                f"Request failed with status {response.status_code}: {response.text}"
                            ),
                            time.time(),
                        )
                    )
                    return

                if stream:
                    for line in response.iter_lines():
                        if line:
                            content = _parse_completion_sse_content(
                                line.decode("utf-8")
                            )
                            if content is not None:
                                response_list.append((content, time.time()))
                else:
                    try:
                        content = response.json()["choices"][0]["text"]
                        response_list.append((content, time.time()))
                    except Exception as e:
                        response_list.append(
                            (Exception(f"Error parsing response: {e}"), time.time())
                        )

        except Exception as e:
            logger.error(f"Request failed with error: {e}")
            response_list.append((e, time.time()))

    request_thread = threading.Thread(target=send_request, daemon=True)
    request_thread.start()

    return request_thread, response_list


def _parse_chat_completion_sse_content(line: str) -> str | Exception | None:
    """
    Parse an SSE line and extract the content.

    Args:
        line: Raw SSE line string

    Returns:
        str: The content delta if found
        Exception: If error event or parse error
        None: If no content (e.g., [DONE] or empty delta)
    """
    if line.startswith("event: error"):
        return Exception(f"SSE error event received: {line}")

    if not line.startswith("data: "):
        return None  # Skip non-data lines

    data_str = line[6:]  # Remove "data: " prefix
    if data_str == "[DONE]":
        return None

    try:
        chunk = json.loads(data_str)
        content = chunk["choices"][0]["delta"].get("content")
        return content  # May be None if delta has no content
    except Exception as e:
        return Exception(f"Error parsing response chunk: {e}")


def start_chat_completion_request(
    frontend_port: int, stream: bool, use_long_prompt: bool = False
) -> tuple:
    """
    Start a long-running chat completion request in a separate thread.

    Responses are processed internally to extract content. First entry is (None, start_time)
    to mark when request was sent. Subsequent entries contain extracted content or exceptions.

    Args:
        frontend_port: Port where the frontend is running
        stream: Whether to use streaming responses
        use_long_prompt: Whether to use a long prompt (~8000 tokens)

    Returns:
        tuple: (request_thread, response_list) where response_list contains
               (str | None | Exception, float) tuples.
               - For streaming: each entry is (content_word, timestamp)
               - For non-streaming: single entry is (full_content, timestamp)
    """
    response_list: list[tuple[str | None | Exception, float]] = []

    def send_request():
        prompt = "Tell me a long long long story about yourself?"
        if use_long_prompt:
            prompt += " Make sure it is" + " long" * 8000 + "!"
        timeout = 240  # Extended timeout for long request

        payload = {
            "model": FAULT_TOLERANCE_MODEL_NAME,
            "messages": [{"role": "user", "content": prompt}],
            "stream": stream,
        }
        headers = {"Content-Type": "application/json"}

        logger.info(
            f"Sending chat completion request (stream={stream}) with prompt: '{prompt[:50]}...'"
        )

        response_list.append((None, time.time()))  # start timestamp

        try:
            with requests.post(
                f"http://localhost:{frontend_port}/v1/chat/completions",
                headers=headers,
                json=payload,
                timeout=timeout,
                stream=stream,
            ) as response:
                logger.info(
                    f"Received response with status code: {response.status_code}"
                )
                if response.status_code != 200:
                    response_list.append(
                        (
                            Exception(
                                f"Request failed with status {response.status_code}: {response.text}"
                            ),
                            time.time(),
                        )
                    )
                    return

                if stream:
                    for line in response.iter_lines():
                        if line:
                            content = _parse_chat_completion_sse_content(
                                line.decode("utf-8")
                            )
                            if content is not None:
                                response_list.append((content, time.time()))
                else:
                    try:
                        content = response.json()["choices"][0]["message"]["content"]
                        response_list.append((content, time.time()))
                    except Exception as e:
                        response_list.append(
                            (Exception(f"Error parsing response: {e}"), time.time())
                        )

275
276
        except Exception as e:
            logger.error(f"Request failed with error: {e}")
277
            response_list.append((e, time.time()))
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300

    request_thread = threading.Thread(target=send_request, daemon=True)
    request_thread.start()

    return request_thread, response_list


def determine_request_receiving_worker(
    worker1: ManagedProcess, worker2: ManagedProcess, receiving_pattern: str
) -> tuple:
    """
    Determine which worker received the request using parallel polling.

    Args:
        worker1: First worker process
        worker2: Second worker process
        receiving_pattern: Log pattern indicating request receipt

    Returns:
        Tuple of (worker_with_request, name_of_worker_with_request)
    """
    worker1_results: list[bool] = []
    worker2_results: list[bool] = []
301
302
    # Event to signal all threads to exit when one finds the pattern
    found_event = threading.Event()
303
304
305
306
307
308
309
310

    # Poll both workers in parallel
    def poll_worker(worker: ManagedProcess, result_list: list[bool]):
        max_wait_ms = 500
        poll_interval_ms = 5
        max_iterations = max_wait_ms // poll_interval_ms
        iteration = 0

311
312
        while iteration < max_iterations and not found_event.is_set():
            # Check if the worker logs contain the pattern
313
314
315
316
317
            try:
                with open(worker.log_path, "r") as f:
                    log_content = f.read()
                    if receiving_pattern in log_content:
                        result_list.append(True)
318
                        found_event.set()  # Signal other thread to exit
319
320
321
322
323
324
325
326
327
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
                        return
            except Exception as e:
                logger.error(f"Could not read log file {worker.log_path}: {e}")
                return

            time.sleep(poll_interval_ms / 1000.0)
            iteration += 1

    # Look for which worker received the request
    thread1 = threading.Thread(
        target=poll_worker, args=(worker1, worker1_results), daemon=True
    )
    thread2 = threading.Thread(
        target=poll_worker, args=(worker2, worker2_results), daemon=True
    )
    thread1.start()
    thread2.start()
    thread1.join(timeout=1)
    thread2.join(timeout=1)

    # Get results from lists
    worker1_received = worker1_results[0] if worker1_results else False
    worker2_received = worker2_results[0] if worker2_results else False

    if worker1_received and not worker2_received:
        logger.info("Request was received by Worker 1")
        return worker1, "Worker 1"
    elif worker2_received and not worker1_received:
        logger.info("Request was received by Worker 2")
        return worker2, "Worker 2"
    elif worker1_received and worker2_received:
        pytest.fail("Both workers received the request")
    else:
        pytest.fail("Neither worker received the request")


355
356
357
358
def wait_for_response(
    response_list: list[tuple[str | None | Exception, float]],
    num_responses: int = 5,
    max_wait_time: float = 10.0,
359
360
) -> None:
    """
361
    Block until num_responses new responses are received or max_wait_time is reached.
362
363

    Args:
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
        response_list: List being populated by background thread
        num_responses: Number of new responses to wait for (default 5)
        max_wait_time: Maximum time to wait in seconds (default 10s)
    """
    initial_len = len(response_list)
    target_len = initial_len + num_responses
    poll_interval = 0.001  # 1ms
    elapsed = 0.0

    while elapsed < max_wait_time:
        if len(response_list) >= target_len:
            return
        time.sleep(poll_interval)
        elapsed += poll_interval

    logger.warning(
        f"Only received {len(response_list) - initial_len}/{num_responses} new responses within {max_wait_time}s"
    )


def validate_response(
    request_thread: threading.Thread,
    response_list: list[tuple[str | None | Exception, float]],
    validate_delay: bool = True,
) -> None:
    """
    Wait for and validate the response after migration.
    Checks that delay before each response is reasonable (covers both TTFT and TPOT).

    Args:
        request_thread: The thread running the request
        response_list: List of (content_string | None | Exception, timestamp) tuples.
                       Content is already parsed - no SSE format parsing needed.
        validate_delay: Whether to validate delay before each response.
398
399
    """
    request_thread.join(timeout=240)
400
    assert not request_thread.is_alive(), "Request did not complete within 240 seconds"
401

402
403
404
    assert len(response_list) > 0, "Missing first entry with start timestamp"
    assert response_list[0][0] is None, "First entry should be start timestamp only"
    prev_timestamp = response_list[0][1]
405

406
407
408
409
410
411
412
413
414
    response_words: list[str] = []
    for res, timestamp in response_list[1:]:
        delay = timestamp - prev_timestamp
        if delay > 2.0 and validate_delay:
            # Cold workers can take longer on first token - only warn but don't fail
            logger.warning(f"Delay before response: {delay:.3f} secs")
            # Capture cases like migration is blocked by engine graceful shutdown
            assert delay <= 6.0, f"Delay before response > 6 secs, got {delay:.3f} secs"
        prev_timestamp = timestamp
415

416
417
418
        assert res is not None, "Response entry should not be None"
        if isinstance(res, Exception):
            raise res
419

420
421
        # Content is already parsed - just collect it
        response_words.append(res)
422
423

    logger.info(
424
        f"Received {len(response_words)} response(s): {''.join(response_words)[:100]}..."
425
426
427
428
429
430
431
432
433
434
435
    )


def verify_migration_occurred(frontend_process: DynamoFrontendProcess) -> None:
    """
    Verify that migration occurred by checking frontend logs for stream disconnection message.

    Args:
        frontend_process: The frontend process to check logs for
    """
    log_path = frontend_process.log_path
436
437
438
439
440
441
442
443
444
445
446
447
    log_content = ""
    for i in range(10):
        try:
            with open(log_path, "r") as f:
                log_content = f.read()
        except Exception as e:
            pytest.fail(f"Could not read frontend log file {log_path}: {e}")
        # Make sure this message is captured if any with the polling
        if "Cannot recreate stream: " in log_content:
            break
        time.sleep(0.005)

448
449
450
451
452
453
    assert (
        "Stream disconnected... recreating stream..." in log_content
    ), "'Stream disconnected... recreating stream...' message not found in logs"
    assert (
        "Cannot recreate stream: " not in log_content
    ), "'Cannot recreate stream: ...' error found in logs"
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537


def _parse_migration_metric(
    metrics_text: str, model_name: str, migration_type: str
) -> int:
    """
    Parse the migration metric value from Prometheus metrics text.

    Args:
        metrics_text: Raw Prometheus metrics text
        model_name: The model name label value
        migration_type: The migration_type label value ("ongoing_request" or "new_request")

    Returns:
        The metric count, or 0 if not found
    """
    import re

    # Match pattern like:
    # dynamo_frontend_model_migration_total{migration_type="ongoing_request",model="Qwen/Qwen3-0.6B"} 1
    # Labels can be in any order
    pattern = rf'dynamo_frontend_model_migration_total\{{[^}}]*migration_type="{migration_type}"[^}}]*model="{re.escape(model_name)}"[^}}]*\}}\s+(\d+)'
    match = re.search(pattern, metrics_text)

    if match:
        return int(match.group(1))

    # Try with labels in reverse order
    pattern = rf'dynamo_frontend_model_migration_total\{{[^}}]*model="{re.escape(model_name)}"[^}}]*migration_type="{migration_type}"[^}}]*\}}\s+(\d+)'
    match = re.search(pattern, metrics_text)

    if match:
        return int(match.group(1))

    return 0


def verify_migration_metrics(
    frontend_port: int,
    expected_ongoing_request_count: int = 0,
    expected_new_request_count: int = 0,
) -> None:
    """
    Verify migration metrics by querying the frontend's /metrics endpoint.

    Args:
        frontend_port: Port where the frontend is running
        expected_ongoing_request_count: Expected count of ongoing_request migrations
        expected_new_request_count: Expected count of new_request migrations
    """
    metrics_url = f"http://localhost:{frontend_port}/metrics"

    try:
        response = requests.get(metrics_url, timeout=1)
        response.raise_for_status()
    except requests.RequestException as e:
        pytest.fail(f"Failed to fetch metrics from {metrics_url}: {e}")

    metrics_text = response.text
    logger.info(f"Fetched metrics from {metrics_url}")

    # Parse metrics to find migration counts
    ongoing_count = _parse_migration_metric(
        metrics_text, FAULT_TOLERANCE_MODEL_NAME, "ongoing_request"
    )
    new_request_count = _parse_migration_metric(
        metrics_text, FAULT_TOLERANCE_MODEL_NAME, "new_request"
    )

    logger.info(
        f"Migration metrics - ongoing_request: {ongoing_count}, new_request: {new_request_count}"
    )

    if expected_ongoing_request_count > 0:
        assert ongoing_count >= expected_ongoing_request_count, (
            f"Expected at least {expected_ongoing_request_count} ongoing_request migrations, "
            f"but got {ongoing_count}"
        )

    if expected_new_request_count > 0:
        assert new_request_count >= expected_new_request_count, (
            f"Expected at least {expected_new_request_count} new_request migrations, "
            f"but got {new_request_count}"
        )
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619


def run_migration_test(
    frontend: DynamoFrontendProcess,
    worker1: ManagedProcess,
    worker2: ManagedProcess,
    receiving_pattern: str,
    migration_limit: int,
    immediate_kill: bool,
    use_chat_completion: bool,
    stream: bool,
    use_long_prompt: bool = False,
    wait_for_new_response_before_stop: bool = False,
) -> None:
    """
    Run the common migration test flow after frontend and workers are started.

    Args:
        frontend: The frontend process
        worker1: First worker process
        worker2: Second worker process
        receiving_pattern: Log pattern to identify which worker received the request
        migration_limit: Migration limit setting (0 = disabled)
        immediate_kill: True for immediate kill, False for graceful shutdown
        use_chat_completion: Whether to use chat completion API (True) or completion API (False)
        stream: Whether to use streaming responses
        use_long_prompt: Whether to use long prompt (for prefill tests)
        wait_for_new_response_before_stop: Whether to wait for response before stopping (for decode tests)
    """
    # Step 1: Send the request
    if use_chat_completion:
        request_thread, response_list = start_chat_completion_request(
            frontend.frontend_port, stream=stream, use_long_prompt=use_long_prompt
        )
    else:
        request_thread, response_list = start_completion_request(
            frontend.frontend_port, stream=stream, use_long_prompt=use_long_prompt
        )

    # Step 2: Determine which worker received the request
    worker, worker_name = determine_request_receiving_worker(
        worker1, worker2, receiving_pattern=receiving_pattern
    )

    # Step 3: Optionally wait for new response before stop (for decode tests)
    if wait_for_new_response_before_stop:
        wait_for_response(response_list)

    # Step 4: Stop the worker (kill or graceful shutdown)
    if immediate_kill:
        logger.info(f"Killing {worker_name} with PID {worker.get_pid()}")
        terminate_process_tree(worker.get_pid(), immediate_kill=True, timeout=0)
    else:
        logger.info(
            f"Gracefully shutting down {worker_name} with PID {worker.get_pid()}"
        )
        terminate_process_tree(worker.get_pid(), immediate_kill=False, timeout=10)

    # Step 5: Validate response based on migration setting
    if migration_limit > 0:
        validate_response(request_thread, response_list, validate_delay=stream)
        verify_migration_occurred(frontend)
        verify_migration_metrics(
            frontend.frontend_port, expected_ongoing_request_count=1
        )
    else:
        try:
            validate_response(request_thread, response_list, validate_delay=stream)
            pytest.fail("Request succeeded unexpectedly when migration was disabled")
        except Exception as e:
            # Request failed as expected - verify it's a known error type
            error_str = str(e)
            assert (
                "SSE error event received:" in error_str
                or "Request failed with status" in error_str
            ), f"Unexpected error: {e}"

        try:
            verify_migration_occurred(frontend)
            pytest.fail("Migration unexpectedly occurred when disabled")
        except AssertionError as e:
            assert "'Cannot recreate stream: ...' error found in logs" in str(e)