test_router_e2e_with_mockers.py 62.5 KB
Newer Older
1
2
3
4
5
6
7
# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

import asyncio
import json
import logging
import os
8
import random
9
import string
10
import tempfile
11
from typing import Any, Dict, Optional
12
13

import aiohttp
14
import nats
15
16
import pytest

17
from dynamo._core import DistributedRuntime, KvPushRouter, KvRouterConfig
Alec's avatar
Alec committed
18
from tests.utils.constants import ROUTER_MODEL_NAME
19
20
21
22
23
24
from tests.utils.managed_process import ManagedProcess

pytestmark = pytest.mark.pre_merge

logger = logging.getLogger(__name__)

25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44

@pytest.fixture
def file_storage_backend():
    """Fixture that sets up and tears down file storage backend.

    Creates a temporary directory for file-based KV storage and sets
    the DYN_FILE_KV environment variable. Cleans up after the test.
    """
    with tempfile.TemporaryDirectory() as tmpdir:
        old_env = os.environ.get("DYN_FILE_KV")
        os.environ["DYN_FILE_KV"] = tmpdir
        logger.info(f"Set up file storage backend in: {tmpdir}")
        yield tmpdir
        # Cleanup
        if old_env is not None:
            os.environ["DYN_FILE_KV"] = old_env
        else:
            os.environ.pop("DYN_FILE_KV", None)


Alec's avatar
Alec committed
45
MODEL_NAME = ROUTER_MODEL_NAME
46
NUM_MOCKERS = 2
47
BLOCK_SIZE = 16
48
49
50
51
SPEEDUP_RATIO = 10.0
NUM_REQUESTS = 100
PORT = 8090  # Starting port for mocker instances

52
53
54
55
56
57

def generate_random_suffix() -> str:
    """Generate a 10-character random alphabetic suffix for namespace isolation."""
    return "".join(random.choices(string.ascii_lowercase, k=10))


58
59
60
61
62
63
64
65
66
67
68
69
70
# Shared test payload for all tests
TEST_PAYLOAD: Dict[str, Any] = {
    "model": MODEL_NAME,
    "messages": [
        {
            "role": "user",
            "content": "In a quiet meadow tucked between rolling hills, a plump gray rabbit nibbled on clover beneath the shade of a gnarled oak tree. Its ears twitched at the faint rustle of leaves, but it remained calm, confident in the safety of its burrow just a few hops away. The late afternoon sun warmed its fur, and tiny dust motes danced in the golden light as bees hummed lazily nearby. Though the rabbit lived a simple life, every day was an adventure of scents, shadows, and snacks—an endless search for the tastiest patch of greens and the softest spot to nap.",
        }
    ],
    "stream": True,
    "max_tokens": 10,
}

71

72
73
74
class MockerProcess:
    """Manages multiple mocker engine instances with the same namespace"""

75
76
77
78
79
    def __init__(
        self,
        request,
        mocker_args: Optional[Dict[str, Any]] = None,
        num_mockers: int = 1,
80
        store_backend: str = "etcd",
81
    ):
82
83
84
85
86
87
88
        # Generate a unique namespace suffix shared by all mockers
        namespace_suffix = generate_random_suffix()
        self.namespace = f"test-namespace-{namespace_suffix}"
        self.endpoint = f"dyn://{self.namespace}.mocker.generate"
        self.num_mockers = num_mockers
        self.mocker_processes = []

89
90
91
92
        # Default mocker args if not provided
        if mocker_args is None:
            mocker_args = {}

93
94
95
96
97
98
99
100
101
102
        # Create multiple mocker processes with the same namespace
        for i in range(num_mockers):
            command = [
                "python",
                "-m",
                "dynamo.mocker",
                "--model-path",
                MODEL_NAME,
                "--endpoint",
                self.endpoint,
103
104
                "--store-kv",
                store_backend,
105
106
            ]

107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
            # Add individual CLI arguments from mocker_args
            if "speedup_ratio" in mocker_args:
                command.extend(["--speedup-ratio", str(mocker_args["speedup_ratio"])])
            if "block_size" in mocker_args:
                command.extend(["--block-size", str(mocker_args["block_size"])])
            if "num_gpu_blocks" in mocker_args:
                command.extend(
                    ["--num-gpu-blocks-override", str(mocker_args["num_gpu_blocks"])]
                )
            if "max_num_seqs" in mocker_args:
                command.extend(["--max-num-seqs", str(mocker_args["max_num_seqs"])])
            if "max_num_batched_tokens" in mocker_args:
                command.extend(
                    [
                        "--max-num-batched-tokens",
                        str(mocker_args["max_num_batched_tokens"]),
                    ]
                )
            if "enable_prefix_caching" in mocker_args:
                if mocker_args["enable_prefix_caching"]:
                    command.append("--enable-prefix-caching")
                else:
                    command.append("--no-enable-prefix-caching")
            if "enable_chunked_prefill" in mocker_args:
                if mocker_args["enable_chunked_prefill"]:
                    command.append("--enable-chunked-prefill")
                else:
                    command.append("--no-enable-chunked-prefill")
            if "watermark" in mocker_args:
                command.extend(["--watermark", str(mocker_args["watermark"])])
            if "dp_size" in mocker_args:
                command.extend(["--data-parallel-size", str(mocker_args["dp_size"])])

140
141
142
143
144
145
146
147
148
149
150
            process = ManagedProcess(
                command=command,
                timeout=60,
                display_output=True,
                health_check_ports=[],
                health_check_urls=[],
                log_dir=request.node.name,
                terminate_existing=False,
            )
            self.mocker_processes.append(process)
            logger.info(f"Created mocker instance {i} with endpoint: {self.endpoint}")
151

152
153
154
155
156
157
    def __enter__(self):
        """Start all mocker processes"""
        for i, process in enumerate(self.mocker_processes):
            logger.info(f"Starting mocker instance {i}")
            process.__enter__()
        return self
158

159
160
161
162
163
    def __exit__(self, exc_type, exc_val, exc_tb):
        """Stop all mocker processes"""
        for i, process in enumerate(self.mocker_processes):
            logger.info(f"Stopping mocker instance {i}")
            process.__exit__(exc_type, exc_val, exc_tb)
164
165
166
167
168


class KVRouterProcess(ManagedProcess):
    """Manages the KV router process using dynamo.frontend"""

169
    def __init__(self, request, frontend_port: int, store_backend: str = "etcd"):
170
171
172
173
        command = [
            "python",
            "-m",
            "dynamo.frontend",
174
175
            "--kv-cache-block-size",
            str(BLOCK_SIZE),
176
177
178
179
            "--router-mode",
            "kv",
            "--http-port",
            str(frontend_port),
180
181
            "--store-kv",
            store_backend,
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
        ]

        super().__init__(
            command=command,
            timeout=60,
            display_output=True,
            health_check_ports=[frontend_port],
            health_check_urls=[
                (f"http://localhost:{frontend_port}/v1/models", self._check_ready)
            ],
            log_dir=request.node.name,
            terminate_existing=False,
        )
        self.port = frontend_port

    def _check_ready(self, response):
        """Check if KV router is ready"""
        return response.status_code == 200

    def __exit__(self, exc_type, exc_val, exc_tb):
        super().__exit__(exc_type, exc_val, exc_tb)


205
async def send_request_with_retry(url: str, payload: dict, max_retries: int = 8):
206
207
208
209
210
211
212
213
214
215
216
217
    """Send a single request with exponential backoff retry"""
    wait_time = 1  # Start with 1 second

    for attempt in range(max_retries + 1):
        await asyncio.sleep(wait_time)
        try:
            async with aiohttp.ClientSession() as session:
                async with session.post(url, json=payload) as response:
                    if response.status == 200:
                        # Read the response to ensure it's valid
                        async for _ in response.content:
                            pass
218
219
220
                        logger.debug(
                            f"First request succeeded on attempt {attempt + 1}"
                        )
221
222
223
224
225
226
227
228
229
230
231
232
233
234
                        return True
                    else:
                        logger.warning(
                            f"Attempt {attempt + 1} failed with status {response.status}"
                        )
        except Exception as e:
            logger.warning(f"Attempt {attempt + 1} failed with error: {e}")

        if attempt < max_retries:
            wait_time *= 2  # Double the wait time

    return False


235
def get_runtime(store_backend="etcd", request_plane="nats"):
236
    """Create a DistributedRuntime instance for testing.
237

238
239
    Args:
        store_backend: Storage backend to use ("etcd" or "file"). Defaults to "etcd".
240
        request_plane: How frontend talks to backend ("tcp", "http" or "nats). Defaults to "nats".
241
242
    """
    try:
243
244
245
246
247
248
        # Try to get running loop (works in async context)
        loop = asyncio.get_running_loop()
    except RuntimeError:
        # No running loop, create a new one (sync context)
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
249
    return DistributedRuntime(loop, store_backend, request_plane)
250
251
252
253
254
255
256
257


async def check_nats_consumers(namespace: str, expected_count: Optional[int] = None):
    """Check NATS consumers for the KV events stream.

    Args:
        namespace: The namespace to check consumers for
        expected_count: Optional expected number of consumers. If provided, logs an error if count doesn't match.
258

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
    Returns:
        List of consumer names
    """
    component_subject = f"namespace.{namespace}.component.mocker"
    slugified = component_subject.lower().replace(".", "-").replace("_", "-")
    stream_name = f"{slugified}-kv-events"
    logger.info(f"Checking consumers for stream: {stream_name}")

    nc = await nats.connect("nats://localhost:4222")
    try:
        js = nc.jetstream()
        consumer_infos = await js.consumers_info(stream_name)
        consumer_names = [info.name for info in consumer_infos]
        logger.info(f"Found {len(consumer_names)} consumers: {consumer_names}")

        # Log detailed consumer info
        for info in consumer_infos:
            logger.info(
                f"Consumer {info.name}: "
                f"num_pending={info.num_pending}, "
                f"num_ack_pending={info.num_ack_pending}, "
                f"ack_floor={info.ack_floor}, "
                f"delivered={info.delivered}"
            )

        if expected_count is not None:
            assert (
                len(consumer_names) == expected_count
            ), f"Expected {expected_count} durable consumers, found {len(consumer_names)}: {consumer_names}"
            logger.info(f"✓ Verified {expected_count} durable consumers exist")

        return consumer_names
    finally:
        await nc.close()
293
294


295
async def send_inflight_requests(urls: list, payload: dict, num_requests: int):
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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
    """Send multiple requests concurrently, alternating between URLs if multiple provided"""

    # First, send test requests with retry to ensure all systems are ready
    for i, url in enumerate(urls):
        logger.info(f"Sending initial test request to URL {i} ({url}) with retry...")
        if not await send_request_with_retry(url, payload):
            raise RuntimeError(f"Failed to connect to URL {i} after multiple retries")

    async def send_single_request(session: aiohttp.ClientSession, request_id: int):
        # Alternate between URLs based on request_id
        url = urls[request_id % len(urls)]
        url_index = request_id % len(urls)

        try:
            async with session.post(url, json=payload) as response:
                if response.status != 200:
                    logger.error(
                        f"Request {request_id} to URL {url_index} failed with status {response.status}"
                    )
                    return False

                # For streaming responses, read the entire stream
                chunks = []
                async for line in response.content:
                    if line:
                        chunks.append(line)

                logger.debug(
                    f"Request {request_id} to URL {url_index} completed with {len(chunks)} chunks"
                )
                return True

        except Exception as e:
            logger.error(
                f"Request {request_id} to URL {url_index} failed with error: {e}"
            )
            return False

    # Send all requests at once
    async with aiohttp.ClientSession() as session:
        tasks = [send_single_request(session, i) for i in range(num_requests)]
        results = await asyncio.gather(*tasks)

        successful = sum(1 for r in results if r)
        failed = sum(1 for r in results if not r)

        logger.info(f"Completed all requests: {successful} successful, {failed} failed")

    assert (
        successful == num_requests
    ), f"Expected {num_requests} successful requests, got {successful}"
    logger.info(f"All {num_requests} requests completed successfully")


350
351
352
353
354
355
356
357
358
359
360
361
async def send_request_via_python_kv_router(
    kv_python_router: KvPushRouter,
    token_ids: list,
    initial_wait: float,
    max_retries: int,
    stop_conditions: Optional[dict] = None,
    sampling_options: Optional[dict] = None,
    output_options: Optional[dict] = None,
    router_config_override: Optional[dict] = None,
    worker_id: Optional[
        int
    ] = None,  # If None, Router will select the best available worker
Yan Ru Pei's avatar
Yan Ru Pei committed
362
    dp_rank: Optional[int] = None,  # Data parallel rank (defaults to 0)
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
):
    """Send a request to the specified mocker instance.
    Returns True if mockers respond, otherwise raises or returns False.
    """

    wait_time = initial_wait

    log_message = (
        f"the mocker with worker_id={worker_id}"
        if worker_id is not None
        else "the best available mocker"
    )

    # Retry loop sending reuqest to mocker worker with exponential backoff
    for attempt in range(max_retries + 1):
        try:
379
            logger.debug(f"Sending request to {log_message} (attempt {attempt + 1})")
380
381
382
383
384
385
386
387

            stream = await kv_python_router.generate(
                token_ids=token_ids,
                model=MODEL_NAME,
                stop_conditions=stop_conditions,
                sampling_options=sampling_options,
                output_options=output_options,
                router_config_override=router_config_override,
388
                worker_id=worker_id,
Yan Ru Pei's avatar
Yan Ru Pei committed
389
                dp_rank=dp_rank,
390
391
392
            )

            if stream is not None:
393
                logger.debug(f"Request succeeded on attempt {attempt + 1}")
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
                break

        except Exception as e:
            logger.warning(f"Attempt {attempt + 1} failed with error: {e}")
            if attempt < max_retries:
                await asyncio.sleep(wait_time)
                wait_time *= 2
            else:
                raise RuntimeError(
                    f"Failed to connect to mockers after {max_retries + 1} attempts: {e}"
                )

    # Collect tokens from the SSE stream
    generated_tokens = []
    async for response in stream:
        if isinstance(response, dict):
            # Check if response has token_ids
            if "token_ids" in response:
                tokens = response["token_ids"]
                if isinstance(tokens, list):
                    generated_tokens.extend(tokens)
                    logger.debug(f"Received {len(tokens)} tokens: {tokens}")

            # Check for finish reason
            if "finish_reason" in response:
419
420
421
                logger.debug(
                    f"Stream finished with reason: {response['finish_reason']}"
                )
422
423

    # Verify if expected number of tokens are generated if max_tokens specified and ignore_eos is True
424
    logger.debug(f"Total generated tokens: {len(generated_tokens)}")
425
426
427
428
429
430
431
432
433
434
435
436
    if (
        stop_conditions
        and "max_tokens" in stop_conditions
        and "ignore_eos" in stop_conditions
        and stop_conditions["ignore_eos"]
    ):
        max_tokens = int(stop_conditions["max_tokens"])
        assert len(generated_tokens) == max_tokens, (
            f"Expected exactly {max_tokens} tokens but got {len(generated_tokens)}. "
            f"Tokens: {generated_tokens}"
        )

437
        logger.debug(
438
439
440
441
442
443
444
            f"Successfully verified {max_tokens} tokens generated as expected via KvPushRouter with ignore_eos=True"
        )
        return True

    return False


445
446
447
448
449
450
451
452
453
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
async def wait_for_mockers_ready(
    endpoint, router: KvPushRouter, expected_num_workers: int = NUM_MOCKERS
) -> list[int]:
    """Wait for mocker workers to be ready and return their instance IDs.

    This function polls the endpoint's client for instance IDs until the expected
    number of workers are available, then sends a warmup request to verify they
    can handle requests.

    Args:
        endpoint: The endpoint object to get the client from
        router: The KvPushRouter to use for sending warmup requests
        expected_num_workers: Number of workers to wait for (default: NUM_MOCKERS)

    Returns:
        Sorted list of unique instance IDs (ints).

    Raises:
        AssertionError: If workers don't become ready or warmup request fails.
    """
    logger.info("Waiting for mockers to be ready")

    # Get the client from the endpoint
    client = await endpoint.client()

    # Poll for instance IDs until we have the expected number
    instance_ids: list[int] = []
    max_wait_time = 60  # seconds
    start_time = asyncio.get_event_loop().time()

    while len(instance_ids) < expected_num_workers:
        instance_ids = client.instance_ids()
        logger.info(f"Found {len(instance_ids)} instance(s): {instance_ids}")

        if len(instance_ids) >= expected_num_workers:
            break

        # Check timeout
        if asyncio.get_event_loop().time() - start_time > max_wait_time:
            raise AssertionError(
                f"Timeout waiting for workers. Found {len(instance_ids)} instance(s), expected {expected_num_workers}"
            )

        # Wait 1 second before polling again
        await asyncio.sleep(1.0)

    # Send a warmup request to verify workers can handle requests
    test_token_ids = [random.randint(1, 10000) for _ in range(4)]
    logger.info(f"Sending warmup request with {len(test_token_ids)} tokens")

    try:
        await send_request_via_python_kv_router(
            kv_python_router=router,
            token_ids=test_token_ids,
            initial_wait=1.0,
            max_retries=8,
            stop_conditions={
                "ignore_eos": True,
                "max_tokens": 2,
            },
        )
    except Exception as e:
        raise AssertionError(f"Warmup request failed: {e}")

    logger.info(f"All {len(instance_ids)} workers are ready")
    return sorted(instance_ids)


513
@pytest.mark.pre_merge
Alec's avatar
Alec committed
514
515
@pytest.mark.model(MODEL_NAME)
def test_mocker_kv_router(request, runtime_services, predownload_tokenizers):
516
517
518
519
520
521
522
523
    """
    Test KV router with multiple mocker engine instances.
    This test doesn't require GPUs and runs quickly for pre-merge validation.
    """

    # runtime_services starts etcd and nats
    logger.info("Starting mocker KV router test")

524
    # Create mocker args dictiona: FixtureRequestry: tuple[NatsServer, EtcdServer]: NoneType
525
    mocker_args = {"speedup_ratio": SPEEDUP_RATIO, "block_size": BLOCK_SIZE}
526
527
528
529
530
531
532
533
534

    try:
        # Start KV router (frontend)
        frontend_port = PORT
        logger.info(f"Starting KV router frontend on port {frontend_port}")

        kv_router = KVRouterProcess(request, frontend_port)
        kv_router.__enter__()

535
        # Start mocker instances with the new CLI interface
536
        logger.info(f"Starting {NUM_MOCKERS} mocker instances")
537
538
539
        mockers = MockerProcess(
            request, mocker_args=mocker_args, num_mockers=NUM_MOCKERS
        )
540
541
        logger.info(f"All mockers using endpoint: {mockers.endpoint}")
        mockers.__enter__()
542
543
544

        # Use async to send requests concurrently for better performance
        asyncio.run(
545
            send_inflight_requests(
546
547
548
                [
                    f"http://localhost:{frontend_port}/v1/chat/completions"
                ],  # Pass as list
549
                TEST_PAYLOAD,
550
551
552
553
554
555
556
557
558
559
560
                NUM_REQUESTS,
            )
        )

        logger.info(f"Successfully completed {NUM_REQUESTS} requests")

    finally:
        # Clean up
        if "kv_router" in locals():
            kv_router.__exit__(None, None, None)

561
562
        if "mockers" in locals():
            mockers.__exit__(None, None, None)
563
564


565
@pytest.mark.pre_merge
Alec's avatar
Alec committed
566
@pytest.mark.model(MODEL_NAME)
567
568
569
570
571
572
573
574
@pytest.mark.parametrize("store_backend", ["etcd", "file"])
def test_mocker_two_kv_router(
    request,
    runtime_services,
    predownload_tokenizers,
    file_storage_backend,
    store_backend,
):
575
576
577
    """
    Test with two KV routers and multiple mocker engine instances.
    Alternates requests between the two routers to test load distribution.
578
    Tests with both etcd and file storage backends.
579
580
581
    """

    # runtime_services starts etcd and nats
582
583
584
    logger.info(
        f"Starting mocker two KV router test with {store_backend} storage backend"
    )
585

586
    # Create mocker args dictionary: FixtureRequest: tuple[NatsServer, EtcdServer]: NoneType
587
588
589
590
591
592
593
594
595
596
    mocker_args = {"speedup_ratio": SPEEDUP_RATIO, "block_size": BLOCK_SIZE}

    kv_routers = []

    try:
        # Start two KV routers (frontend) on ports 8091 and 8092
        router_ports = [PORT + 1, PORT + 2]  # 8091 and 8092

        for port in router_ports:
            logger.info(f"Starting KV router frontend on port {port}")
597
            kv_router = KVRouterProcess(request, port, store_backend)
598
599
600
            kv_router.__enter__()
            kv_routers.append(kv_router)

601
        # Start mocker instances with the new CLI interface
602
        logger.info(f"Starting {NUM_MOCKERS} mocker instances")
603
        mockers = MockerProcess(
604
605
606
607
            request,
            mocker_args=mocker_args,
            num_mockers=NUM_MOCKERS,
            store_backend=store_backend,
608
        )
609
610
        logger.info(f"All mockers using endpoint: {mockers.endpoint}")
        mockers.__enter__()
611
612
613
614
615
616
617
618

        # Build URLs for both routers
        router_urls = [
            f"http://localhost:{port}/v1/chat/completions" for port in router_ports
        ]

        # Use async to send requests concurrently, alternating between routers
        asyncio.run(
619
            send_inflight_requests(
620
                router_urls,
621
                TEST_PAYLOAD,
622
623
624
625
626
627
628
629
                NUM_REQUESTS,
            )
        )

        logger.info(
            f"Successfully completed {NUM_REQUESTS} requests across {len(router_ports)} routers"
        )

630
631
632
633
        # Verify durable consumers lifecycle
        async def verify_consumer_lifecycle():
            logger.info("Verifying durable consumers lifecycle")

634
635
            # Check initial consumer count - should have 2 (one for each router process)
            await check_nats_consumers(mockers.namespace, expected_count=2)
636

637
638
639
            # Kill the first router process
            logger.info(f"Killing first router on port {router_ports[0]}")
            kv_routers[0].__exit__(None, None, None)
640

641
642
            # Wait for cleanup to happen (consumer deletion is triggered by etcd watch)
            await asyncio.sleep(1)
643

644
645
646
647
648
            # Verify only 1 consumer remains
            await check_nats_consumers(mockers.namespace, expected_count=1)
            logger.info(
                "✓ Verified 1 durable consumer remains after killing first router"
            )
649

650
651
652
            # Kill the second router process
            logger.info(f"Killing second router on port {router_ports[1]}")
            kv_routers[1].__exit__(None, None, None)
653

654
655
            # Wait for cleanup to happen
            await asyncio.sleep(1)
656

657
658
659
660
661
            # Verify no consumers remain
            await check_nats_consumers(mockers.namespace, expected_count=0)
            logger.info(
                "✓ Verified 0 durable consumers remain after killing both routers"
            )
662
663
664
665
666
667
668

        # Run consumer lifecycle verification
        asyncio.run(verify_consumer_lifecycle())

        # Clear the kv_routers list since we've already cleaned them up
        kv_routers = []

669
    finally:
670
        # Clean up any remaining routers (in case of error before consumer verification)
671
672
673
674
        for kv_router in kv_routers:
            kv_router.__exit__(None, None, None)

        # Clean up mockers
675
676
        if "mockers" in locals():
            mockers.__exit__(None, None, None)
677
678


679
@pytest.mark.pre_merge
Alec's avatar
Alec committed
680
@pytest.mark.model(MODEL_NAME)
681
@pytest.mark.skip(reason="Flaky, temporarily disabled")
Alec's avatar
Alec committed
682
683
684
def test_mocker_kv_router_overload_503(
    request, runtime_services, predownload_tokenizers
):
685
686
687
688
    """
    Test that KV router returns 503 when all workers are busy.
    This test uses limited resources to intentionally trigger the overload condition.
    """
689

690
691
    # runtime_services starts etcd and nats
    logger.info("Starting mocker KV router overload test for 503 status")
692
    # Create mocker args dictionary with limited resources
693
694
695
696
697
    mocker_args = {
        "speedup_ratio": 10,
        "block_size": 4,  # Smaller block size
        "num_gpu_blocks": 64,  # Limited GPU blocks to exhaust quickly
    }
698

699
700
701
702
703
704
    try:
        # Start KV router (frontend) with limited block size
        frontend_port = PORT + 10  # Use different port to avoid conflicts
        logger.info(
            f"Starting KV router frontend on port {frontend_port} with limited resources"
        )
705

706
707
708
709
710
711
712
713
714
715
716
717
718
719
        # Custom command for router with limited block size
        command = [
            "python",
            "-m",
            "dynamo.frontend",
            "--busy-threshold",
            "0.2",
            "--kv-cache-block-size",
            "4",  # Match the mocker's block size
            "--router-mode",
            "kv",
            "--http-port",
            str(frontend_port),
        ]
720

721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
        kv_router = ManagedProcess(
            command=command,
            timeout=60,
            display_output=True,
            health_check_ports=[frontend_port],
            health_check_urls=[
                (
                    f"http://localhost:{frontend_port}/v1/models",
                    lambda r: r.status_code == 200,
                )
            ],
            log_dir=request.node.name,
            terminate_existing=False,
        )
        kv_router.__enter__()
736

737
        # Start single mocker instance with limited resources using the new CLI interface
738
        logger.info("Starting single mocker instance with limited resources")
739
        mockers = MockerProcess(request, mocker_args=mocker_args, num_mockers=1)
740
741
        logger.info(f"Mocker using endpoint: {mockers.endpoint}")
        mockers.__enter__()
742

743
        url = f"http://localhost:{frontend_port}/v1/chat/completions"
744

745
746
747
748
749
        # Custom payload for 503 test with more tokens to consume resources
        test_payload_503 = {
            **TEST_PAYLOAD,
            "max_tokens": 50,  # Longer output to consume more blocks
        }
750

751
752
        # First, send one request with retry to ensure system is ready
        logger.info("Sending initial request to ensure system is ready...")
753
        asyncio.run(send_inflight_requests([url], test_payload_503, 1))
754

755
756
        # Now send 50 concurrent requests to exhaust resources, then verify 503
        logger.info("Sending 50 concurrent requests to exhaust resources...")
757

758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
        async def exhaust_resources_and_verify_503():
            async with aiohttp.ClientSession() as session:
                # Start 50 long-running requests concurrently
                tasks = []
                for i in range(50):
                    # Create unique shuffled content for each request
                    content_words = TEST_PAYLOAD["messages"][0]["content"].split()
                    random.shuffle(content_words)
                    shuffled_content = " ".join(content_words)

                    # Create unique payload for this request
                    unique_payload = {
                        **TEST_PAYLOAD,
                        "max_tokens": 50,
                        "messages": [
                            {**TEST_PAYLOAD["messages"][0], "content": shuffled_content}
                        ],
                    }

                    async def send_long_request(req_id, payload):
                        try:
                            async with session.post(url, json=payload) as response:
                                if response.status == 200:
                                    # Don't read the response fully, just hold the connection
                                    await asyncio.sleep(
                                        10
                                    )  # Hold connection for 10 seconds
                                    return True
                                else:
                                    logger.info(
                                        f"Request {req_id} got status {response.status}"
                                    )
                                    return False
                        except Exception as e:
                            logger.info(f"Request {req_id} failed: {e}")
                            return False

                    tasks.append(
                        asyncio.create_task(send_long_request(i, unique_payload))
                    )
798

799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
                # Wait briefly to ensure requests are in-flight
                await asyncio.sleep(0.2)

                # Now send one more request that should get 503
                logger.info("Sending additional request that should receive 503...")
                try:
                    async with session.post(url, json=test_payload_503) as response:
                        status_code = response.status
                        if status_code == 503:
                            body = await response.json()
                            logger.info(f"Got expected 503 response: {body}")
                            assert "Service temporarily unavailable" in body.get(
                                "error", ""
                            ) or "All workers are busy" in body.get(
                                "error", ""
                            ), f"Expected service overload error message, got: {body}"
                            return True
                        else:
                            logger.error(f"Expected 503 but got {status_code}")
                            if status_code == 200:
                                logger.error(
                                    "Request unexpectedly succeeded when it should have been rejected"
                                )
                            return False
                except Exception as e:
                    logger.error(f"Failed to send overload test request: {e}")
                    return False
                finally:
                    # Cancel all background tasks
                    for task in tasks:
                        task.cancel()
                    await asyncio.gather(*tasks, return_exceptions=True)
831

832
833
834
835
836
837
838
839
840
841
842
        # Run the test
        success = asyncio.run(exhaust_resources_and_verify_503())
        assert success, "Failed to verify 503 response when resources are exhausted"

        logger.info("Successfully verified 503 response when all workers are busy")

    finally:
        # Clean up
        if "kv_router" in locals():
            kv_router.__exit__(None, None, None)

843
844
        if "mockers" in locals():
            mockers.__exit__(None, None, None)
845

846
847

@pytest.mark.pre_merge
Alec's avatar
Alec committed
848
849
@pytest.mark.model(MODEL_NAME)
def test_kv_push_router_bindings(request, runtime_services, predownload_tokenizers):
850
851
852
853
854
855
856
857
858
    """
    Test KvPushRouter Python bindings with mocker engines.
    This test creates KvPushRouter as a Python object and verifies
    token streaming with ignore_eos=True and max_tokens=20.
    """

    # runtime_services starts etcd and nats
    logger.info("Starting KvPushRouter bindings test")

859
    # Create mocker args dictionary
860
861
862
    mocker_args = {"speedup_ratio": SPEEDUP_RATIO, "block_size": BLOCK_SIZE}

    try:
863
        # Start mocker instances with the new CLI interface
864
        logger.info(f"Starting {NUM_MOCKERS} mocker instances")
865
866
867
        mockers = MockerProcess(
            request, mocker_args=mocker_args, num_mockers=NUM_MOCKERS
        )
868
869
        logger.info(f"All mockers using endpoint: {mockers.endpoint}")
        mockers.__enter__()
870

871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
        # Get runtime and create endpoint
        runtime = get_runtime()
        # Use the namespace from the mockers
        namespace = runtime.namespace(mockers.namespace)
        component = namespace.component("mocker")
        endpoint = component.endpoint("generate")

        # Create KvRouterConfig with default settings
        kv_router_config = KvRouterConfig()

        # Create KvPushRouter Python object
        kv_push_router = KvPushRouter(
            endpoint=endpoint,
            block_size=BLOCK_SIZE,
            kv_router_config=kv_router_config,
        )
887

888
        logger.info("Created KvPushRouter Python object")
889

890
891
        # Wait for mockers to be ready
        asyncio.run(wait_for_mockers_ready(endpoint, kv_push_router))
892

893
894
895
        # Generate random token IDs (100 to 200 tokens)
        num_input_tokens = random.randint(100, 200)
        token_ids = [random.randint(1, 10000) for _ in range(num_input_tokens)]
896

897
898
899
900
901
        # Set up override parameters
        router_config_override = {
            "overlap_score_weight": 0.5,  # Override the default weight
            "router_temperature": 0.5,  # Override the default temperature
        }
902

903
        logger.info(f"Generated {num_input_tokens} random token IDs")
904

905
906
907
908
909
910
911
        # Test with full overrides
        logger.info(
            f"Testing with full router config overrides: {router_config_override}"
        )
        asyncio.run(
            send_request_via_python_kv_router(
                kv_python_router=kv_push_router,
912
                token_ids=token_ids,
913
914
915
916
917
918
919
920
921
922
923
                initial_wait=1.0,
                max_retries=8,
                stop_conditions={
                    "ignore_eos": True,  # Don't stop on EOS token
                    "max_tokens": 20,  # Generate exactly 20 tokens
                },
                sampling_options={"temperature": 0.7, "top_p": 0.9},
                output_options={
                    "include_input_tokens": False,
                    "return_full_text": False,
                },
924
925
                router_config_override=router_config_override,
            )
926
        )
927

928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
        # Test without overrides
        logger.info("Testing without router config overrides")
        asyncio.run(
            send_request_via_python_kv_router(
                kv_python_router=kv_push_router,
                token_ids=token_ids[:50],  # Use fewer tokens for second test,
                initial_wait=1.0,
                max_retries=8,
                stop_conditions={
                    "ignore_eos": True,  # Don't stop on EOS token
                    "max_tokens": 10,  # Generate exactly 10 tokens for the second test
                },
                sampling_options={"temperature": 0.7, "top_p": 0.9},
                output_options={
                    "include_input_tokens": False,
                    "return_full_text": False,
                },
945
946
                # No router_config_override this time
            )
947
        )
948

949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
        # Test with partial override (only temperature)
        partial_override = {"router_temperature": 0.1}
        logger.info(f"Testing with partial router config overrides: {partial_override}")
        asyncio.run(
            send_request_via_python_kv_router(
                kv_python_router=kv_push_router,
                token_ids=token_ids[:30],  # Use fewer tokens for third test,
                initial_wait=1.0,
                max_retries=8,
                stop_conditions={
                    "ignore_eos": True,  # Don't stop on EOS token
                    "max_tokens": 5,  # Generate exactly 5 tokens for the third test
                },
                sampling_options={"temperature": 0.7, "top_p": 0.9},
                output_options={
                    "include_input_tokens": False,
                    "return_full_text": False,
                },
967
968
                router_config_override=partial_override,
            )
969
        )
970
971
972
973
974

        logger.info("KvPushRouter bindings test completed successfully")

    finally:
        # Clean up mockers
975
976
977
978
979
        if "mockers" in locals():
            mockers.__exit__(None, None, None)


@pytest.mark.pre_merge
Alec's avatar
Alec committed
980
@pytest.mark.model(MODEL_NAME)
981
982
983
984
985
986
987
988
@pytest.mark.parametrize("store_backend", ["etcd", "file"])
def test_indexers_sync(
    request,
    runtime_services,
    predownload_tokenizers,
    file_storage_backend,
    store_backend,
):
989
990
991
    """
    Test that two KV routers have synchronized indexer states after processing requests.
    This test verifies that both routers converge to the same internal state.
992
    Tests with both etcd and file storage backends.
993
994
995
    """

    # runtime_services starts etcd and nats
996
    logger.info(f"Starting indexers sync test with {store_backend} storage backend")
997

998
    # Create mocker args dicti: FixtureRequestonary: tuple[NatsServer, EtcdServer]: NoneType
999
1000
1001
    mocker_args = {"speedup_ratio": SPEEDUP_RATIO, "block_size": BLOCK_SIZE}

    try:
1002
        # Start mocker instances with the new CLI interface
1003
        logger.info(f"Starting {NUM_MOCKERS} mocker instances")
1004
        mockers = MockerProcess(
1005
1006
1007
1008
            request,
            mocker_args=mocker_args,
            num_mockers=NUM_MOCKERS,
            store_backend=store_backend,
1009
        )
1010
        logger.info(f"All mockers using endpoint: {mockers.endpoint}")
1011
        # Initialize mockers
1012
1013
        mockers.__enter__()

1014
        # Use async to manage the test flow
1015
        async def test_sync():
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
            # Create SEPARATE runtimes for each router to ensure independence
            # This is especially important for file storage backend where connection_id
            # would otherwise be shared between routers
            runtime1 = get_runtime(store_backend)
            runtime2 = get_runtime(store_backend)

            # Use the namespace from the mockers for both runtimes
            namespace1 = runtime1.namespace(mockers.namespace)
            component1 = namespace1.component("mocker")
            endpoint1 = component1.endpoint("generate")

            namespace2 = runtime2.namespace(mockers.namespace)
            component2 = namespace2.component("mocker")
            endpoint2 = component2.endpoint("generate")
1030

1031
            # Create KvRouterConfig with lower snapshot threshold for testing
1032
            kv_router_config = KvRouterConfig(router_snapshot_threshold=20)
1033
1034
1035
1036
1037
1038

            async def send_requests_to_router(router, num_requests, router_name):
                # Now send the actual requests
                tasks = []
                for i in range(num_requests):
                    # Generate random token IDs for each request
1039
                    logger.debug(
1040
1041
1042
1043
                        f"Sending request {i + 1}/{num_requests} to {router_name}"
                    )

                    # Generate 30 random tokens
1044
1045
                    request_tokens = [random.randint(1, 10000) for _ in range(30)]

1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
                    # Send request to mocker via the router
                    tasks.append(
                        asyncio.create_task(
                            send_request_via_python_kv_router(
                                kv_python_router=router,
                                token_ids=request_tokens,
                                initial_wait=1.0,
                                max_retries=8,
                                stop_conditions={
                                    "ignore_eos": True,  # Don't stop on EOS token
                                    "max_tokens": 10,  # Generate exactly 10 tokens
                                },
1058
                            )
1059
1060
                        )
                    )
1061

1062
                # Wait for all requests to complete
1063
1064
1065
1066
1067
1068
1069
                results = await asyncio.gather(*tasks)
                successful = sum(1 for r in results if r)
                logger.info(
                    f"Completed {successful}/{num_requests} requests for {router_name}"
                )
                return successful

1070
            # Launch first router
1071
1072
            logger.info("Creating first KV router")
            kv_push_router1 = KvPushRouter(
1073
                endpoint=endpoint1,
1074
1075
1076
1077
                block_size=BLOCK_SIZE,
                kv_router_config=kv_router_config,
            )

1078
            # Wait for mockers to be ready
1079
            await wait_for_mockers_ready(endpoint1, kv_push_router1)
1080
1081

            # Send 25 requests to first router
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
            logger.info("Sending 25 requests to first router")

            # Send requests to first router
            successful1 = await send_requests_to_router(kv_push_router1, 25, "Router 1")
            assert (
                successful1 == 25
            ), f"Expected 25 successful requests to router 1, got {successful1}"

            # Wait for a second before creating the second router
            logger.info("Waiting for 1 second before creating second router")
1092
            await asyncio.sleep(2)
1093

1094
1095
            # Launch second router - will automatically sync with the first router's state
            logger.info("Creating second KV router")
1096
            kv_push_router2 = KvPushRouter(
1097
                endpoint=endpoint2,
1098
                block_size=BLOCK_SIZE,
1099
                kv_router_config=kv_router_config,
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
            )

            # Send 25 requests to second router with initial retry loop
            logger.info("Sending 25 requests to second router")
            successful2 = await send_requests_to_router(kv_push_router2, 25, "Router 2")
            assert (
                successful2 == 25
            ), f"Expected 25 successful requests to router 2, got {successful2}"

            # Wait for all requests to complete (they should already be complete from gather)
            # Wait another 1 second for internal synchronization
            logger.info("Waiting for final synchronization")
            await asyncio.sleep(1)

1114
1115
1116
            # Check NATS consumers to verify both routers have separate consumers
            await check_nats_consumers(mockers.namespace, expected_count=2)

1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
            # Verify NATS object store bucket was created with snapshot
            # Mirror the Rust bucket naming logic from subscriber.rs:
            # component.subject() -> "namespace.{ns}.component.{comp}"
            # then slugify (convert dots to dashes, lowercase, etc) and append "-radix-bucket"
            component_subject = f"namespace.{mockers.namespace}.component.mocker"
            slugified = component_subject.lower().replace(".", "-").replace("_", "-")
            expected_bucket = f"{slugified}-radix-bucket"
            expected_file = "radix-state"

            logger.info(f"Verifying NATS object store bucket exists: {expected_bucket}")
            snapshot_verified = False
            try:
1129
1130
1131
1132
1133
                # Connect to NATS and check object store
                nc = await nats.connect("nats://localhost:4222")
                try:
                    js = nc.jetstream()
                    obj_store = await js.object_store(expected_bucket)
1134

1135
1136
1137
                    # Try to get the expected file
                    try:
                        result = await obj_store.get(expected_file)
1138
                        logger.info(
1139
1140
                            f"✓ Snapshot file '{expected_file}' found in bucket '{expected_bucket}' "
                            f"(size: {len(result.data) if result.data else 0} bytes)"
1141
1142
                        )
                        snapshot_verified = True
1143
                    except Exception as e:
1144
                        logger.error(
1145
                            f"Snapshot file '{expected_file}' not found in bucket '{expected_bucket}': {e}"
1146
                        )
1147
1148
                finally:
                    await nc.close()
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
            except Exception as e:
                logger.error(f"Error checking NATS object store: {e}")

            # Assert that snapshot was created (threshold=20, sent 25 requests)
            if not snapshot_verified:
                assert False, (
                    f"Expected snapshot to be created in bucket '{expected_bucket}' with file '{expected_file}'. "
                    f"Router sent 25 requests with snapshot_threshold=20, so snapshot should have been triggered."
                )

1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
            # Dump states from both routers
            logger.info("Dumping states from both routers")
            state1_json = await kv_push_router1.dump_events()
            state2_json = await kv_push_router2.dump_events()

            # Parse JSON strings for comparison
            state1 = json.loads(state1_json)
            state2 = json.loads(state2_json)

            # Sort both states for comparison (order might differ due to HashMap iteration and sharding)
            def sort_key(event):
                data = event["event"]["data"]["stored"]
                blocks = data["blocks"]
                first_block = blocks[0]
                return (
                    event["worker_id"],
                    first_block["tokens_hash"],
                    data["parent_hash"],
                )

            sorted_state1 = sorted(state1, key=sort_key)
            sorted_state2 = sorted(state2, key=sort_key)

            # Verify they are equal
            logger.info(f"Router 1 has {len(sorted_state1)} events")
            logger.info(f"Router 2 has {len(sorted_state2)} events")

            # Compare states one by one and only show differences
            if len(sorted_state1) != len(sorted_state2):
                logger.error(
                    f"Router 1 has {len(sorted_state1)} events, Router 2 has {len(sorted_state2)} events"
                )
                assert False, "Router states have different numbers of events"

            differences = []
            for i, (state1_item, state2_item) in enumerate(
                zip(sorted_state1, sorted_state2)
            ):
                # Create copies without event_id for comparison
                item1_compare = state1_item.copy()
                item2_compare = state2_item.copy()

                # Remove event_id from the nested event structure
                if "event" in item1_compare and "event_id" in item1_compare["event"]:
                    del item1_compare["event"]["event_id"]
                if "event" in item2_compare and "event_id" in item2_compare["event"]:
                    del item2_compare["event"]["event_id"]

                if item1_compare != item2_compare:
                    differences.append(
                        {
                            "index": i,
                            "router1_state": state1_item,
                            "router2_state": state2_item,
                        }
                    )
1215
            # If there are differences, format them for easier debugging
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
            if differences:
                error_msg = f"Router states are not equal. Found {len(differences)} differences:\n"
                for diff in differences:
                    error_msg += f"\nDifference at index {diff['index']}:\n"
                    error_msg += (
                        f"Router 1: {json.dumps(diff['router1_state'], indent=2)}\n"
                    )
                    error_msg += (
                        f"Router 2: {json.dumps(diff['router2_state'], indent=2)}\n"
                    )
                    error_msg += "-" * 80 + "\n"

                assert False, error_msg

            logger.info("Successfully verified that both router states are equal")

        # Run the async test
        asyncio.run(test_sync())

        logger.info("Indexers sync test completed successfully")

    finally:
        # Clean up mockers
        if "mockers" in locals():
            mockers.__exit__(None, None, None)
1241

1242
1243

@pytest.mark.pre_merge
Alec's avatar
Alec committed
1244
1245
1246
1247
@pytest.mark.model(MODEL_NAME)
def test_query_instance_id_returns_worker_and_tokens(
    request, runtime_services, predownload_tokenizers
):
1248
1249
1250
1251
1252
1253
1254
    """
    Test that the KV router correctly handles query_instance_id annotation.

    When a request includes 'nvext.annotations': ['query_instance_id'], the router should:
    1. NOT route the request to a worker immediately
    2. Return worker_instance_id as an SSE event
    3. Return token_data as an SSE event containing the request tokens
1255
    4. Term: FixtureRequestinate the stream w: tuple[NatsServer, EtcdServer]ith [DONE]: NoneType
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279

    This tests the specific code block:
        if query_instance_id {
            let instance_id_str = instance_id.to_string();
            let response = Annotated::from_annotation("worker_instance_id", &instance_id_str)?;
            let response_tokens = Annotated::from_annotation("token_data", &request.token_ids)?;
            let stream = stream::iter(vec![response, response_tokens]);
            return Ok(ResponseStream::new(Box::pin(stream), stream_context));
        }
    """

    logger.info("Starting KV router query_instance_id annotation test")

    mocker_args = {"speedup_ratio": SPEEDUP_RATIO, "block_size": BLOCK_SIZE}
    os.makedirs(request.node.name, exist_ok=True)

    try:
        # Start KV router (frontend)
        frontend_port = PORT + 30  # Use unique port to avoid conflicts
        logger.info(f"Starting KV router frontend on port {frontend_port}")
        kv_router = KVRouterProcess(request, frontend_port)
        kv_router.__enter__()

        # Start multiple mocker engines to ensure worker selection logic
1280
        logger.info(f"Starting {NUM_MOCKERS} mocker instances")
1281
1282
1283
        mockers = MockerProcess(
            request, mocker_args=mocker_args, num_mockers=NUM_MOCKERS
        )
1284
1285
        logger.info(f"All mockers using endpoint: {mockers.endpoint}")
        mockers.__enter__()
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427

        url = f"http://localhost:{frontend_port}/v1/chat/completions"

        # Send a warming request first to ensure system is ready
        logger.info("Sending warming request without annotations...")
        asyncio.run(send_request_with_retry(url, TEST_PAYLOAD))

        # Test payload with query_instance_id annotation
        annotated_payload = {
            **TEST_PAYLOAD,
            "nvext": {"annotations": ["query_instance_id"]},
        }

        async def test_annotation_response():
            """Send request with query_instance_id and validate response structure"""
            async with aiohttp.ClientSession() as session:
                logger.info("Sending request with query_instance_id annotation...")

                async with session.post(url, json=annotated_payload) as response:
                    assert (
                        response.status == 200
                    ), f"Expected 200 but got {response.status}"

                    # Collect all response chunks
                    response_chunks = []
                    async for chunk in response.content:
                        if chunk:
                            chunk_str = chunk.decode("utf-8", errors="replace")
                            response_chunks.append(chunk_str)

                    full_response = "".join(response_chunks)
                    logger.info(
                        f"Full SSE response ({len(full_response)} bytes):\n{full_response}"
                    )

                    # Parse and validate the response structure
                    events = []

                    sse_parts = full_response.split("\n\n")

                    for part in sse_parts:
                        part = part.strip()
                        if not part:
                            continue

                        if part.startswith("event:"):
                            lines = part.split("\n")
                            event_line = next(
                                (line for line in lines if line.startswith("event:")),
                                None,
                            )
                            data_line = next(
                                (
                                    line
                                    for line in lines
                                    if line.startswith("data:") or line.startswith(":")
                                ),
                                None,
                            )

                            if event_line and data_line:
                                event_type = event_line.split(":", 1)[1].strip()
                                if data_line.startswith("data:"):
                                    data_value = data_line.split(":", 1)[1].strip()
                                else:
                                    data_value = data_line.split(":", 1)[1].strip()
                                events.append((event_type, data_value))
                        elif part.startswith("data:"):
                            data_value = part.split(":", 1)[1].strip()

                    logger.info(f"Parsed events: {events}")

                    # Validate worker_instance_id event
                    worker_event = next(
                        (e for e in events if e[0] == "worker_instance_id"), None
                    )
                    assert (
                        worker_event is not None
                    ), f"Missing worker_instance_id event in: {events}"

                    # Validate token_data event
                    token_event = next(
                        (e for e in events if e[0] == "token_data"), None
                    )
                    assert (
                        token_event is not None
                    ), f"Missing token_data event in: {events}"

                    token_data_str = token_event[1].strip('"')
                    try:
                        token_list = json.loads(token_data_str)
                    except json.JSONDecodeError as e:
                        raise AssertionError(
                            f"token_data is not valid JSON: {token_data_str}, error: {e}"
                        )

                    assert isinstance(
                        token_list, list
                    ), f"token_data should be a list, got: {type(token_list)}"
                    assert (
                        len(token_list) > 0
                    ), f"token_data should not be empty: {token_list}"
                    assert all(
                        isinstance(token, int) for token in token_list
                    ), f"All tokens should be integers: {token_list}"

                    logger.info(
                        f"Valid token_data with {len(token_list)} tokens: {token_list[:10]}{'...' if len(token_list) > 10 else ''}"
                    )

                    # Validate that no actual generation happened (should only be metadata)
                    # This proves the early return worked correctly
                    generation_indicators = [
                        "choices",
                        "content",
                        "delta",
                        "finish_reason",
                    ]
                    for indicator in generation_indicators:
                        assert (
                            indicator not in full_response.lower()
                        ), f"Found generation indicator '{indicator}' - request should not have been routed to worker"

                    logger.info(
                        "No generation content found - early return worked correctly"
                    )

                    return {
                        "worker_instance_id": worker_event[1].strip('"'),
                        "token_count": len(token_list),
                        "tokens": token_list,
                    }

        result = asyncio.run(test_annotation_response())

        logger.info("Successfully validated query_instance_id annotation response:")
        logger.info(f"Worker ID: {result['worker_instance_id']}")
        logger.info(f"Token count: {result['token_count']}")

    finally:
        if "kv_router" in locals():
            kv_router.__exit__(None, None, None)
1428
1429
        if "mockers" in locals():
            mockers.__exit__(None, None, None)
1430
1431
1432
1433
1434


@pytest.mark.pre_merge
@pytest.mark.model(MODEL_NAME)
def test_router_decisions(request, runtime_services, predownload_tokenizers):
Yan Ru Pei's avatar
Yan Ru Pei committed
1435
    """Validate KV cache prefix reuse and dp_rank routing by sending progressive requests with overlapping prefixes.
1436
1437

    Flow:
Yan Ru Pei's avatar
Yan Ru Pei committed
1438
      - Start two mocker workers, each with dp_size=4 (8 total dp ranks).
1439
1440
      - Wait for workers to be ready.
      - Send 4 progressive requests, each extending the previous tokens:
Yan Ru Pei's avatar
Yan Ru Pei committed
1441
1442
1443
1444
        * Request 1: BLOCK_SIZE random tokens (forced to specific worker_id and dp_rank=1)
        * Request 2: Request 1 tokens + BLOCK_SIZE new random tokens (naturally routed)
        * Request 3: Request 2 tokens + BLOCK_SIZE new random tokens (naturally routed)
        * Request 4: Request 3 tokens + BLOCK_SIZE new random tokens (naturally routed)
1445
      - Dump events from router and verify:
Yan Ru Pei's avatar
Yan Ru Pei committed
1446
1447
1448
        * All but one (worker_id, dp_rank) should have no events (due to prefix reuse)
        * The (worker_id, dp_rank) with events should have exactly 4 events (one per request)
        * All events should be on the forced (worker_id, dp_rank=1) (verifying forced routing and prefix reuse)
1449
1450
1451
1452
1453
    """

    # runtime_services starts etcd and nats
    logger.info("Starting test router prefix reuse and KV events synchronization")

Yan Ru Pei's avatar
Yan Ru Pei committed
1454
1455
1456
1457
1458
1459
    # Create mocker args dictionary with dp_size=4
    mocker_args = {
        "speedup_ratio": SPEEDUP_RATIO,
        "block_size": BLOCK_SIZE,
        "dp_size": 4,
    }
1460
1461

    try:
Yan Ru Pei's avatar
Yan Ru Pei committed
1462
1463
1464
        # Start 2 mocker instances, each with dp_size=4 (8 total dp ranks)
        logger.info(
            "Starting 2 mocker instances with dp_size=4 each (8 total dp ranks)"
1465
        )
Yan Ru Pei's avatar
Yan Ru Pei committed
1466
        mockers = MockerProcess(request, mocker_args=mocker_args, num_mockers=2)
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
        logger.info(f"All mockers using endpoint: {mockers.endpoint}")
        # Initialize mockers
        mockers.__enter__()

        # Get runtime and create endpoint
        runtime = get_runtime()
        # Use the namespace from the mockers
        namespace = runtime.namespace(mockers.namespace)
        component = namespace.component("mocker")
        endpoint = component.endpoint("generate")

        # Create KvRouterConfig with lower snapshot threshold for testing
        kv_router_config = KvRouterConfig(router_snapshot_threshold=20)
        kv_push_router = KvPushRouter(
            endpoint=endpoint,
            block_size=BLOCK_SIZE,
            kv_router_config=kv_router_config,
        )

        # Use async to manage the test flow
        async def test_sync():
            # Wait for workers to be ready and get their instance IDs
Yan Ru Pei's avatar
Yan Ru Pei committed
1489
1490
1491
            mocker_worker_ids = await wait_for_mockers_ready(
                endpoint, kv_push_router, expected_num_workers=2
            )
1492
1493
            logger.info(f"Workers ready: {mocker_worker_ids}")

Yan Ru Pei's avatar
Yan Ru Pei committed
1494
1495
1496
1497
1498
1499
1500
1501
            # Use the first worker_id for forced routing
            forced_worker_id = mocker_worker_ids[0]
            forced_dp_rank = 1

            logger.info(
                f"Will force first request to worker_id={forced_worker_id}, dp_rank={forced_dp_rank}"
            )

1502
1503
1504
1505
1506
1507
1508
1509
            # Send 4 progressive requests with overlapping prefixes
            cumulative_tokens = []

            for i in range(4):
                # Add BLOCK_SIZE new random tokens
                new_tokens = [random.randint(1, 10000) for _ in range(BLOCK_SIZE)]
                cumulative_tokens.extend(new_tokens)

Yan Ru Pei's avatar
Yan Ru Pei committed
1510
1511
1512
1513
                # Force first request to specific worker_id and dp_rank=1, let subsequent requests follow naturally
                worker_id_override = forced_worker_id if i == 0 else None
                dp_rank_override = forced_dp_rank if i == 0 else None

1514
1515
1516
                logger.info(
                    f"Sending request {i + 1}/4 with {len(cumulative_tokens)} tokens "
                    f"(added {len(new_tokens)} new tokens)"
Yan Ru Pei's avatar
Yan Ru Pei committed
1517
                    f"{f' - FORCING worker_id={worker_id_override}, dp_rank={dp_rank_override}' if worker_id_override is not None else ''}"
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
                )

                await send_request_via_python_kv_router(
                    kv_python_router=kv_push_router,
                    token_ids=cumulative_tokens.copy(),
                    initial_wait=1.0,
                    max_retries=8,
                    stop_conditions={
                        "ignore_eos": True,  # Don't stop on EOS token
                        "max_tokens": 2,  # Generate exactly 2 tokens
                    },
Yan Ru Pei's avatar
Yan Ru Pei committed
1529
1530
                    worker_id=worker_id_override,
                    dp_rank=dp_rank_override,
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
                )

                # Wait a bit between requests
                await asyncio.sleep(0.5)

            # Wait for final synchronization
            await asyncio.sleep(1)

            # Dump events from the router
            events_json = await kv_push_router.dump_events()
Yan Ru Pei's avatar
Yan Ru Pei committed
1541
            return events_json, forced_worker_id, forced_dp_rank
1542
1543

        # Run the async test
Yan Ru Pei's avatar
Yan Ru Pei committed
1544
        events_json, expected_worker_id, expected_dp_rank = asyncio.run(test_sync())
1545

Yan Ru Pei's avatar
Yan Ru Pei committed
1546
        # Parse events and count by (worker_id, dp_rank)
1547
        events = json.loads(events_json)
Yan Ru Pei's avatar
Yan Ru Pei committed
1548
        events_by_worker_dp: dict[tuple[int, int], list[Any]] = {}
1549
1550
1551

        for event in events:
            worker_id = event.get("worker_id")
Yan Ru Pei's avatar
Yan Ru Pei committed
1552
1553
1554
1555
1556
1557
            # Extract dp_rank from the event's KvCacheEvent
            dp_rank = event.get("event", {}).get("dp_rank", 0)
            key = (worker_id, dp_rank)
            if key not in events_by_worker_dp:
                events_by_worker_dp[key] = []
            events_by_worker_dp[key].append(event)
1558
1559

        logger.info(
Yan Ru Pei's avatar
Yan Ru Pei committed
1560
            f"Events by (worker_id, dp_rank): {[(key, len(evts)) for key, evts in events_by_worker_dp.items()]}"
1561
1562
        )

Yan Ru Pei's avatar
Yan Ru Pei committed
1563
        # Verify: All but one (worker_id, dp_rank) should have no events
1564
        workers_with_events = [
Yan Ru Pei's avatar
Yan Ru Pei committed
1565
            key for key, evts in events_by_worker_dp.items() if len(evts) > 0
1566
1567
1568
        ]

        assert len(workers_with_events) == 1, (
Yan Ru Pei's avatar
Yan Ru Pei committed
1569
1570
            f"Expected exactly 1 (worker_id, dp_rank) to have events (due to prefix reuse), "
            f"but found {len(workers_with_events)} with events: {workers_with_events}"
1571
1572
        )

Yan Ru Pei's avatar
Yan Ru Pei committed
1573
1574
1575
        # Verify: The (worker_id, dp_rank) with events should have exactly 4 events
        active_worker_dp = workers_with_events[0]
        num_events = len(events_by_worker_dp[active_worker_dp])
1576
1577

        assert num_events == 4, (
Yan Ru Pei's avatar
Yan Ru Pei committed
1578
            f"Expected (worker_id, dp_rank) {active_worker_dp} to have exactly 4 events, "
1579
1580
1581
            f"but found {num_events} events"
        )

Yan Ru Pei's avatar
Yan Ru Pei committed
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
        # Verify: Both worker_id and dp_rank should match the forced values
        active_worker_id = active_worker_dp[0]
        active_dp_rank = active_worker_dp[1]

        assert active_worker_id == expected_worker_id, (
            f"Expected all events to have worker_id={expected_worker_id} (forced in first request), "
            f"but found worker_id={active_worker_id}"
        )

        assert active_dp_rank == expected_dp_rank, (
            f"Expected all events to have dp_rank={expected_dp_rank} (forced in first request), "
            f"but found dp_rank={active_dp_rank}"
        )

1596
        logger.info(
Yan Ru Pei's avatar
Yan Ru Pei committed
1597
1598
            f"Successfully verified: Worker {active_worker_id} dp_rank {active_dp_rank} handled all 4 requests with prefix reuse. "
            f"All events correctly routed to worker_id={expected_worker_id}, dp_rank={expected_dp_rank} as expected. "
1599
1600
1601
1602
1603
1604
1605
            f"KV events synchronized correctly."
        )

    finally:
        # Clean up mockers
        if "mockers" in locals():
            mockers.__exit__(None, None, None)