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

4
5
6
7
8
9
# NOTE: These tests run reliably in serial but have encountered intermittent failures
# under pytest-xdist parallel execution (-n auto). Each test spawns its own
# DistributedRuntime with isolated etcd/NATS and unique namespaces, but the Rust
# runtime may use process-global state (e.g. lazy_static / OnceLock singletons for
# endpoint tables) that races under concurrent xdist workers. Do not add
# @pytest.mark.parallel until DRT endpoint registration is confirmed thread-safe.
10
11
12
13
14
15
#
# NOTE: TCP request plane is NOT tested here. These tests use --num-workers > 1 which spawns
# multiple workers in a single process sharing one TCP server. The shared TCP server uses
# endpoint_path (e.g., "generate") as the routing key, causing handler collisions when multiple
# workers register the same endpoint. This is a test-only limitation; production deployments
# with separate processes per worker work correctly with TCP.
16
17
import logging
import os
18
from typing import Any, Dict, Optional
19
20
21

import pytest

22
from tests.router.common import (
23
    _test_busy_threshold_endpoint,
24
25
26
    _test_python_router_bindings,
    _test_router_basic,
    _test_router_decisions,
27
    _test_router_decisions_disagg,
28
29
30
31
    _test_router_overload_503,
    _test_router_query_instance_id,
    _test_router_two_routers,
)
32
from tests.router.helper import generate_random_suffix, get_runtime
Alec's avatar
Alec committed
33
from tests.utils.constants import ROUTER_MODEL_NAME
34
from tests.utils.managed_process import ManagedProcess
35
from tests.utils.port_utils import allocate_ports, deallocate_ports
36

37
38
39
40
logger = logging.getLogger(__name__)

MODEL_NAME = ROUTER_MODEL_NAME

41
42
43
44
pytestmark = [
    pytest.mark.pre_merge,
    pytest.mark.gpu_0,
    pytest.mark.integration,
45
    pytest.mark.model(MODEL_NAME),
46
]
47
48
NUM_MOCKERS = 2
SPEEDUP_RATIO = 10.0
49
50
51
BASE_PORT = 9100  # Base port for general test allocations (frontend, system, etc.)
BASE_PORT_BOOTSTRAP = 10100  # Base port for disagg bootstrap rendezvous
BASE_PORT_ZMQ = 11100  # Base port for ZMQ KV event publishing
52
NUM_REQUESTS = 100
53
BLOCK_SIZE = 16
54
55


56
def get_unique_ports(
57
58
59
60
    request,
    num_ports: int = 1,
    store_backend: str = "etcd",
    request_plane: str = "nats",
61
    registration_order: str = "prefill_first",
62
) -> list[int]:
63
    """Allocate random free ports for xdist-safe router tests.
64

65
66
67
    This replaces the previous "test-name offset" scheme with the shared flock-backed
    allocator from `tests.utils.port_utils`, which avoids collisions across pytest-xdist
    worker processes.
68

69
70
71
72
    Notes:
    - The extra parameters are kept for call-site compatibility (they no longer affect
      the chosen ports).
    - Ports are released at the end of the test via a pytest finalizer.
73
    """
74
75
76
    _ = (store_backend, request_plane, registration_order)
    ports = allocate_ports(num_ports, BASE_PORT)
    request.addfinalizer(lambda: deallocate_ports(ports))
77
78
79
    return ports


80
81
82
83
84
85
86
87
88
89
90
91
92
# 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,
}

93

94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
def _build_mocker_command(
    endpoint: str,
    store_backend: str,
    num_workers: int,
    mocker_args: Dict[str, Any],
    worker_type: Optional[str] = None,
) -> list[str]:
    """Build the mocker CLI command with all arguments.

    Args:
        endpoint: The dynamo endpoint string
        store_backend: Storage backend ("etcd" or "file")
        num_workers: Number of workers to spawn (uses --num-workers flag)
        mocker_args: Dictionary of mocker arguments
        worker_type: Optional worker type ("prefill" or "decode") for disagg mode

    Returns:
        List of command arguments for subprocess
    """
    command = [
        "python",
        "-m",
        "dynamo.mocker",
        "--model-path",
        MODEL_NAME,
        "--endpoint",
        endpoint,
121
        "--discovery-backend",
122
123
124
125
126
127
128
        store_backend,
        "--num-workers",
        str(num_workers),
    ]

    # Add worker type flag for disaggregated mode
    if worker_type == "prefill":
129
        command.extend(["--disaggregation-mode", "prefill"])
130
    elif worker_type == "decode":
131
        command.extend(["--disaggregation-mode", "decode"])
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

    # 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")
158
159
    if "preemption_mode" in mocker_args:
        command.extend(["--preemption-mode", str(mocker_args["preemption_mode"])])
160
161
    if "dp_size" in mocker_args:
        command.extend(["--data-parallel-size", str(mocker_args["dp_size"])])
162
163
164
    # Use --durable-kv-events to enable JetStream mode (local indexer disabled)
    if mocker_args.get("durable_kv_events") is True:
        command.append("--durable-kv-events")
165
166
    if "bootstrap_ports" in mocker_args:
        command.extend(["--bootstrap-ports", mocker_args["bootstrap_ports"]])
167
168
    if "zmq_kv_events_ports" in mocker_args:
        command.extend(["--zmq-kv-events-ports", mocker_args["zmq_kv_events_ports"]])
169
170
    if "zmq_replay_ports" in mocker_args:
        command.extend(["--zmq-replay-ports", mocker_args["zmq_replay_ports"]])
171
172
173
174

    return command


175
class MockerProcess:
176
    """Manages mocker engine instances with shared tokio runtime via --num-workers."""
177

178
179
180
181
182
    def __init__(
        self,
        request,
        mocker_args: Optional[Dict[str, Any]] = None,
        num_mockers: int = 1,
183
        store_backend: str = "etcd",
184
        request_plane: str = "nats",
185
        zmq_kv_events: bool = False,
186
        model_name: str = "mocker",
187
        zmq_replay: bool = False,
188
    ):
189
190
        namespace_suffix = generate_random_suffix()
        self.namespace = f"test-namespace-{namespace_suffix}"
191
        self.component_name = "mocker"
192
        self.model_name = model_name
193
        self.endpoint = f"dyn://{self.namespace}.{self.component_name}.generate"
194
        self.num_workers = num_mockers
195
        self._zmq_kv_events_ports: list[int] = []
196
        self._zmq_replay_ports: list[int] = []
197
198
199
200
201
202
203
        self._request = request
        self._store_backend = store_backend
        self._request_plane = request_plane
        self._mocker_args_orig: Dict[str, Any] = (mocker_args or {}).copy()
        self.worker_id_to_zmq_ports: dict[int, dict[int, str]] = {}

        mocker_args = self._mocker_args_orig.copy()
204
205
        # Store dp_size for DP-aware test functions
        self.dp_size = mocker_args.get("dp_size")
206
207
        # Alias for consistency with vLLM/SGLang workers
        self.data_parallel_size = self.dp_size
208

209
210
211
212
213
214
215
216
217
218
        # Allocate ZMQ base ports for KV event publishing.
        # Each worker's DP ranks bind on base_port + dp_rank, so we need bases
        # spaced dp_size apart. Allocate num_mockers * dp_size ports total,
        # then pick every dp_size'th port as a base.
        if zmq_kv_events:
            dp_size = mocker_args.get("dp_size", 1)
            self._zmq_kv_events_ports = allocate_ports(
                num_mockers * dp_size, BASE_PORT_ZMQ
            )
            bases = [self._zmq_kv_events_ports[i * dp_size] for i in range(num_mockers)]
219
            mocker_args["zmq_kv_events_ports"] = ",".join(str(p) for p in bases)
220
221
222
223
224
            logger.info(
                f"Allocated ZMQ KV event ports {self._zmq_kv_events_ports} "
                f"(bases: {bases}) for {num_mockers} workers"
            )

225
226
227
228
229
230
231
232
233
        # Allocate ZMQ replay ports (same layout as event ports)
        if zmq_replay and zmq_kv_events:
            dp_size = mocker_args.get("dp_size", 1)
            self._zmq_replay_ports = allocate_ports(
                num_mockers * dp_size, BASE_PORT_ZMQ + 1000
            )
            replay_bases = [
                self._zmq_replay_ports[i * dp_size] for i in range(num_mockers)
            ]
234
            mocker_args["zmq_replay_ports"] = ",".join(str(p) for p in replay_bases)
235
236
237
238
239
            logger.info(
                f"Allocated ZMQ replay ports {self._zmq_replay_ports} "
                f"(bases: {replay_bases}) for {num_mockers} workers"
            )

240
241
242
243
244
        command = _build_mocker_command(
            endpoint=self.endpoint,
            store_backend=store_backend,
            num_workers=num_mockers,
            mocker_args=mocker_args,
245
246
        )

247
248
        env = os.environ.copy()
        env["DYN_REQUEST_PLANE"] = request_plane
249

250
251
252
253
        self._process = ManagedProcess(
            command=command,
            env=env,
            timeout=60,
254
            display_output=True,
255
            health_check_ports=[],
256
            health_check_urls=[],
257
            log_dir=request.node.name,
258
259
260
            terminate_all_matching_process_names=False,
        )
        logger.info(
261
            f"Created mocker process with {num_mockers} worker(s), endpoint: {self.endpoint}"
262
        )
263
264
265
266
267

    def __enter__(self):
        logger.info(f"Starting mocker process with {self.num_workers} worker(s)")
        self._process.__enter__()
        return self
268

269
    def __exit__(self, exc_type, exc_val, exc_tb):
270
        logger.info("Stopping mocker process")
271
272
        if self._process is not None:
            self._process.__exit__(exc_type, exc_val, exc_tb)
273
274
275
276
        if self._zmq_kv_events_ports:
            deallocate_ports(self._zmq_kv_events_ports)
            logger.info(f"Deallocated ZMQ KV event ports {self._zmq_kv_events_ports}")
            self._zmq_kv_events_ports = []
277
278
279
280
        if self._zmq_replay_ports:
            deallocate_ports(self._zmq_replay_ports)
            logger.info(f"Deallocated ZMQ replay ports {self._zmq_replay_ports}")
            self._zmq_replay_ports = []
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300


class DisaggMockerProcess:
    """Manages prefill or decode mocker instances for disaggregated serving.

    Uses --num-workers for shared tokio runtime. For disaggregated serving:
    - Prefill workers: worker_type="prefill", endpoint is namespace.prefill.generate
    - Decode workers: worker_type="decode", endpoint is namespace.backend.generate

    Both prefill and decode workers should share the same namespace for proper discovery.
    """

    def __init__(
        self,
        request,
        namespace: str,
        worker_type: str,
        mocker_args: Optional[Dict[str, Any]] = None,
        num_mockers: int = 1,
        store_backend: str = "etcd",
301
        request_plane: str = "nats",
302
        enable_bootstrap: bool = False,
303
304
305
306
    ):
        if worker_type not in ("prefill", "decode"):
            raise ValueError(
                f"worker_type must be 'prefill' or 'decode', got {worker_type}"
307
            )
308
309
310
311

        self.namespace = namespace
        self.worker_type = worker_type
        self.num_workers = num_mockers
312
        self._bootstrap_ports: list[int] = []
313
314
315
316
317
318
319
320
321

        # Set component name and endpoint based on worker type
        if worker_type == "prefill":
            self.component_name = "prefill"
            self.endpoint = f"dyn://{self.namespace}.prefill.generate"
        else:
            self.component_name = "backend"
            self.endpoint = f"dyn://{self.namespace}.backend.generate"

322
323
324
325
        mocker_args = (mocker_args or {}).copy()

        # Allocate bootstrap ports for prefill workers if enabled (one per worker)
        if enable_bootstrap and worker_type == "prefill":
326
            self._bootstrap_ports = allocate_ports(num_mockers, BASE_PORT_BOOTSTRAP)
327
328
329
330
331
332
            mocker_args["bootstrap_ports"] = ",".join(
                str(p) for p in self._bootstrap_ports
            )
            logger.info(
                f"Allocated bootstrap ports {self._bootstrap_ports} for {num_mockers} prefill workers"
            )
333
334
335
336
337
338
339
340
341

        command = _build_mocker_command(
            endpoint=self.endpoint,
            store_backend=store_backend,
            num_workers=num_mockers,
            mocker_args=mocker_args,
            worker_type=worker_type,
        )

342
343
344
        env = os.environ.copy()
        env["DYN_REQUEST_PLANE"] = request_plane

345
346
        self._process = ManagedProcess(
            command=command,
347
            env=env,
348
349
350
351
352
            timeout=60,
            display_output=True,
            health_check_ports=[],
            health_check_urls=[],
            log_dir=request.node.name,
353
            terminate_all_matching_process_names=False,
354
355
356
357
358
        )
        logger.info(
            f"Created {worker_type} mocker process with {num_mockers} worker(s), "
            f"endpoint: {self.endpoint}"
        )
359

360
361
362
363
364
    @property
    def bootstrap_ports(self) -> list[int]:
        """Return the allocated bootstrap ports, if any."""
        return self._bootstrap_ports

365
    def __enter__(self):
366
367
368
369
        logger.info(
            f"Starting {self.worker_type} mocker process with {self.num_workers} worker(s)"
        )
        self._process.__enter__()
370
        return self
371

372
    def __exit__(self, exc_type, exc_val, exc_tb):
373
374
        logger.info(f"Stopping {self.worker_type} mocker process")
        self._process.__exit__(exc_type, exc_val, exc_tb)
375
376
377
378
379
        # Deallocate bootstrap ports if we allocated any
        if self._bootstrap_ports:
            deallocate_ports(self._bootstrap_ports)
            logger.info(f"Deallocated bootstrap ports {self._bootstrap_ports}")
            self._bootstrap_ports = []
380
381


382
@pytest.mark.timeout(120)  # bumped for xdist contention (was 42s; ~13.80s serial avg)
383
@pytest.mark.parametrize(
384
385
386
387
388
389
390
391
392
393
394
    "router_mode,durable_kv_events",
    [
        pytest.param("kv", False, id="kv-nondurable"),
        pytest.param("kv", True, id="kv-durable"),
        pytest.param("round-robin", False, id="roundrobin"),
        pytest.param("random", False, id="random"),
    ],
    indirect=["durable_kv_events"],
)
@pytest.mark.parametrize("request_plane", ["nats", "tcp"], indirect=True)
def test_mocker_router(
395
396
397
    request,
    runtime_services_dynamic_ports,
    predownload_tokenizers,
398
    router_mode,
399
    request_plane,
400
    durable_kv_events,
401
):
402
    """Test router with multiple mocker engine instances across all router modes.
403

404
405
    Covers kv, round-robin, and random routing. Tests both NATS and TCP request planes.
    """
406
    # runtime_services starts etcd and optionally nats based on request_plane
407
408
409
    logger.info(
        f"Starting mocker router test: router_mode={router_mode}, request_plane={request_plane}"
    )
410

411
412
413
414
    # Create mocker args dictionary - use local indexer (NATS Core mode)
    mocker_args = {
        "speedup_ratio": SPEEDUP_RATIO,
        "block_size": BLOCK_SIZE,
415
        "durable_kv_events": durable_kv_events,
416
    }
417

418
419
420
421
422
423
    with MockerProcess(
        request,
        mocker_args=mocker_args,
        num_mockers=NUM_MOCKERS,
        request_plane=request_plane,
    ) as mockers:
424
        # Start mocker instances with the new CLI interface
425
426
        logger.info(f"Starting {NUM_MOCKERS} mocker instances")
        logger.info(f"All mockers using endpoint: {mockers.endpoint}")
427

428
        # Get unique port for this test
429
430
431
        frontend_port = get_unique_ports(
            request, num_ports=1, request_plane=request_plane
        )[0]
432
433

        # Run basic router test (starts router internally and waits for workers to be ready)
434
435
436
437
        _test_router_basic(
            engine_workers=mockers,
            block_size=BLOCK_SIZE,
            request=request,
438
            frontend_port=frontend_port,
439
440
            test_payload=TEST_PAYLOAD,
            num_requests=NUM_REQUESTS,
441
            request_plane=request_plane,
442
            router_mode=router_mode,
443
444
445
        )


446
@pytest.mark.parametrize("store_backend", ["etcd", "file"])
447
@pytest.mark.parametrize(
448
    "durable_kv_events", [False], ids=["nondurable"], indirect=True
449
)  # Use NATS Core (local indexer)
450
@pytest.mark.timeout(180)  # bumped for xdist contention (was 60s; ~19.86s serial avg)
451
452
def test_mocker_two_kv_router(
    request,
453
    runtime_services_dynamic_ports,
454
455
456
    predownload_tokenizers,
    file_storage_backend,
    store_backend,
457
    durable_kv_events,
458
):
459
460
461
    """
    Test with two KV routers and multiple mocker engine instances.
    Alternates requests between the two routers to test load distribution.
462
    Tests with both etcd and file storage backends.
463
464
465
    """

    # runtime_services starts etcd and nats
466
467
468
    logger.info(
        f"Starting mocker two KV router test with {store_backend} storage backend"
    )
469

470
471
472
473
    # Create mocker args dictionary - use local indexer (NATS Core mode)
    mocker_args = {
        "speedup_ratio": SPEEDUP_RATIO,
        "block_size": BLOCK_SIZE,
474
        "durable_kv_events": durable_kv_events,
475
    }
476

477
478
479
480
481
482
    with MockerProcess(
        request,
        mocker_args=mocker_args,
        num_mockers=NUM_MOCKERS,
        store_backend=store_backend,
    ) as mockers:
483
        # Start mocker instances with the new CLI interface
484
485
        logger.info(f"Starting {NUM_MOCKERS} mocker instances")
        logger.info(f"All mockers using endpoint: {mockers.endpoint}")
486

487
488
489
490
491
        # Get unique ports for this test (2 ports for two routers)
        router_ports = get_unique_ports(
            request, num_ports=2, store_backend=store_backend
        )

492
493
494
495
496
        # Run two-router test (starts KV routers internally and manages their lifecycle)
        _test_router_two_routers(
            engine_workers=mockers,
            block_size=BLOCK_SIZE,
            request=request,
497
            router_ports=router_ports,
498
499
500
            test_payload=TEST_PAYLOAD,
            num_requests=NUM_REQUESTS,
            store_backend=store_backend,
501
            skip_consumer_verification=not durable_kv_events,  # Skip JetStream checks in NATS Core mode
502
503
504
        )


505
@pytest.mark.skip(reason="Flaky, temporarily disabled")
506
@pytest.mark.parametrize(
507
    "durable_kv_events", [False], ids=["nondurable"], indirect=True
508
)  # Use NATS Core (local indexer)
509
@pytest.mark.timeout(60)  # ~3x average (~19.86s), rounded up (when enabled)
Alec's avatar
Alec committed
510
def test_mocker_kv_router_overload_503(
511
    request, runtime_services_dynamic_ports, predownload_tokenizers, durable_kv_events
Alec's avatar
Alec committed
512
):
513
    """Test that KV router returns 503 when mocker workers are overloaded."""
514
    logger.info("Starting mocker KV router overload test for 503 status")
515
    # Create mocker args dictionary with limited resources - use local indexer (NATS Core mode)
516
517
518
519
    mocker_args = {
        "speedup_ratio": 10,
        "block_size": 4,  # Smaller block size
        "num_gpu_blocks": 64,  # Limited GPU blocks to exhaust quickly
520
        "durable_kv_events": durable_kv_events,
521
    }
522

523
    with MockerProcess(request, mocker_args=mocker_args, num_mockers=1) as mockers:
524
        # Start single mocker instance with limited resources
525
526
        logger.info("Starting single mocker instance with limited resources")
        logger.info(f"Mocker using endpoint: {mockers.endpoint}")
527

528
529
530
        # Get unique port for this test
        frontend_port = get_unique_ports(request, num_ports=1)[0]

531
532
533
534
535
536
537
        # Run overload 503 test
        _test_router_overload_503(
            engine_workers=mockers,
            block_size=4,  # Match the mocker's block size
            request=request,
            frontend_port=frontend_port,
            test_payload=TEST_PAYLOAD,
538
            blocks_threshold=0.2,
539
        )
540

541

542
@pytest.mark.timeout(90)  # bumped for xdist contention (was 22s; ~7.10s serial avg)
543
@pytest.mark.parametrize("request_plane", ["nats", "tcp"], indirect=True)
544
@pytest.mark.parametrize(
545
    "durable_kv_events", [False], ids=["nondurable"], indirect=True
546
)  # Use NATS Core (local indexer)
547
def test_kv_router_bindings(
548
549
550
551
    request,
    runtime_services_dynamic_ports,
    predownload_tokenizers,
    request_plane,
552
    durable_kv_events,
553
):
554
555
    """Test KvRouter Python bindings with mocker engines."""
    logger.info("Starting KvRouter bindings test")
556
557
558
559
    # Use local indexer (NATS Core mode)
    mocker_args = {
        "speedup_ratio": SPEEDUP_RATIO,
        "block_size": BLOCK_SIZE,
560
        "durable_kv_events": durable_kv_events,
561
    }
562

563
564
565
566
567
568
    with MockerProcess(
        request,
        mocker_args=mocker_args,
        num_mockers=NUM_MOCKERS,
        request_plane=request_plane,
    ) as mockers:
569
        # Start mocker instances
570
571
        logger.info(f"Starting {NUM_MOCKERS} mocker instances")
        logger.info(f"All mockers using endpoint: {mockers.endpoint}")
572

573
        # Get runtime and create endpoint
574
        runtime = get_runtime(request_plane=request_plane)
575
576
577
        endpoint = runtime.endpoint(
            f"{mockers.namespace}.{mockers.component_name}.generate"
        )
578

579
580
581
        # Run Python router bindings test
        _test_python_router_bindings(
            engine_workers=mockers,
582
583
            endpoint=endpoint,
            block_size=BLOCK_SIZE,
584
585
            model_name=MODEL_NAME,
            num_workers=NUM_MOCKERS,
586
        )
587

588

589
@pytest.mark.timeout(120)  # bumped for xdist contention (was 42s; ~13.80s serial avg)
590
@pytest.mark.parametrize(
591
    "durable_kv_events", [False], ids=["nondurable"], indirect=True
592
)  # Use NATS Core (local indexer)
Alec's avatar
Alec committed
593
def test_query_instance_id_returns_worker_and_tokens(
594
    request, runtime_services_dynamic_ports, predownload_tokenizers, durable_kv_events
Alec's avatar
Alec committed
595
):
596
    """Test query_instance_id annotation with mocker engines."""
597
    logger.info("Starting KV router query_instance_id annotation test")
598
599
600
601
    # Use local indexer (NATS Core mode)
    mocker_args = {
        "speedup_ratio": SPEEDUP_RATIO,
        "block_size": BLOCK_SIZE,
602
        "durable_kv_events": durable_kv_events,
603
    }
604

605
606
607
    with MockerProcess(
        request, mocker_args=mocker_args, num_mockers=NUM_MOCKERS
    ) as mockers:
608
        # Start mocker instances
609
610
        logger.info(f"Starting {NUM_MOCKERS} mocker instances")
        logger.info(f"All mockers using endpoint: {mockers.endpoint}")
611

612
613
614
        # Get unique port for this test
        frontend_port = get_unique_ports(request, num_ports=1)[0]

615
616
617
618
619
620
621
622
        # Run query_instance_id annotation test
        _test_router_query_instance_id(
            engine_workers=mockers,
            block_size=BLOCK_SIZE,
            request=request,
            frontend_port=frontend_port,
            test_payload=TEST_PAYLOAD,
        )
623

624

625
@pytest.mark.timeout(300)  # bumped for xdist contention (was 29s; ~9.55s serial avg)
Yan Ru Pei's avatar
Yan Ru Pei committed
626
@pytest.mark.parametrize("request_plane", ["tcp"], indirect=True)
627
@pytest.mark.parametrize(
628
    "durable_kv_events,use_kv_events,zmq_kv_events",
629
    [
630
631
632
        (True, True, False),  # JetStream mode with KV events
        (False, True, False),  # NATS Core mode with local indexer (default)
        (False, False, False),  # Approximate mode (--no-kv-events) - no KV events
633
    ],
634
    ids=["jetstream", "nats_core", "no_kv_events"],
635
    indirect=["durable_kv_events"],
636
)
637
def test_router_decisions(
638
639
640
    request,
    runtime_services_dynamic_ports,
    predownload_tokenizers,
641
    durable_kv_events,
642
    use_kv_events,
643
    request_plane,
644
    zmq_kv_events,
645
646
647
):
    """Validate KV cache prefix reuse and dp_rank routing by sending progressive requests with overlapping prefixes.

648
    Parameterized to test:
649
650
    - JetStream mode: KV events via NATS JetStream (durable)
    - NATS Core mode (default): KV events via NATS Core with local indexer on workers
651
652
    - Approximate mode (--no-kv-events): No KV events, router predicts cache state
      based on routing decisions with TTL-based expiration and pruning
653
    """
654
    # runtime_services_dynamic_ports handles NATS and etcd startup
655
    logger.info(
656
        f"Starting test router decisions: durable_kv_events={durable_kv_events}, use_kv_events={use_kv_events}"
657
    )
658

Yan Ru Pei's avatar
Yan Ru Pei committed
659
    # Create mocker args dictionary with dp_size=4
660
    # durable_kv_events=True enables JetStream mode; False (default) uses NATS Core with local indexer
Yan Ru Pei's avatar
Yan Ru Pei committed
661
662
    mocker_args = {
        "speedup_ratio": SPEEDUP_RATIO,
663
        "block_size": 8,
Yan Ru Pei's avatar
Yan Ru Pei committed
664
        "dp_size": 4,
665
        "durable_kv_events": durable_kv_events and use_kv_events,
Yan Ru Pei's avatar
Yan Ru Pei committed
666
    }
667

668
669
670
671
672
    with MockerProcess(
        request,
        mocker_args=mocker_args,
        num_mockers=2,
        request_plane=request_plane,
673
        zmq_kv_events=zmq_kv_events,
674
        model_name=MODEL_NAME,
675
    ) as mockers:
676
        logger.info(f"All mockers using endpoint: {mockers.endpoint}")
677

678
679
        # Initialize mockers
        # Get runtime and create endpoint
680
        runtime = get_runtime(request_plane=request_plane)
681
        # Use the namespace from the mockers
682
        endpoint = runtime.endpoint(f"{mockers.namespace}.mocker.generate")
683

684
        _test_router_decisions(
685
686
687
688
689
690
            mockers,
            endpoint,
            MODEL_NAME,
            request,
            test_dp_rank=True,
            use_kv_events=use_kv_events,
691
            durable_kv_events=durable_kv_events,
692
693
        )

694

695
@pytest.mark.parametrize("registration_order", ["prefill_first", "decode_first"])
696
697
698
@pytest.mark.parametrize(
    "enable_disagg_bootstrap", [False, True], ids=["no_bootstrap", "with_bootstrap"]
)
699
@pytest.mark.timeout(180)  # bumped for xdist contention (was 59s; ~19.51s serial avg)
700
def test_router_decisions_disagg(
701
702
703
704
    request,
    runtime_services_dynamic_ports,
    predownload_tokenizers,
    registration_order,
705
    enable_disagg_bootstrap,
706
707
708
709
710
):
    """Validate KV cache prefix reuse in disaggregated prefill-decode setup.

    Tests that progressive requests with overlapping prefixes are routed to the
    same prefill worker due to KV cache reuse.
711

712
713
714
    Parameterized to test:
    - registration_order: prefill_first vs decode_first
    - enable_disagg_bootstrap: without vs with bootstrap rendezvous
715
    """
716
    # runtime_services_dynamic_ports handles NATS and etcd startup
717
718
    logger.info(
        f"Starting disaggregated router prefix reuse test "
719
        f"(registration_order={registration_order}, bootstrap={enable_disagg_bootstrap})"
720
    )
721
722
723
724
725

    # Generate shared namespace for prefill and decode workers
    namespace_suffix = generate_random_suffix()
    shared_namespace = f"test-namespace-{namespace_suffix}"

726
    # Create mocker args - use NATS Core with local indexer (default mode)
727
728
729
    mocker_args = {
        "speedup_ratio": SPEEDUP_RATIO,
        "block_size": BLOCK_SIZE,
730
        # durable_kv_events defaults to False (NATS Core mode)
731
    }
732

733
734
735
736
737
738
739
740
741
742
743
744
    if registration_order == "prefill_first":
        # Start prefill workers first
        logger.info("Starting 4 prefill mocker instances (first)")
        with DisaggMockerProcess(
            request,
            namespace=shared_namespace,
            worker_type="prefill",
            mocker_args=mocker_args,
            num_mockers=4,
            request_plane="nats",
            enable_bootstrap=enable_disagg_bootstrap,
        ) as prefill_workers:
745
746
747
748
            logger.info(f"Prefill workers using endpoint: {prefill_workers.endpoint}")

            # Then start decode workers
            logger.info("Starting 4 decode mocker instances (second)")
749
            with DisaggMockerProcess(
750
751
752
753
754
                request,
                namespace=shared_namespace,
                worker_type="decode",
                mocker_args=mocker_args,
                num_mockers=4,
755
                request_plane="nats",
756
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
            ) as decode_workers:
                logger.info(f"Decode workers using endpoint: {decode_workers.endpoint}")

                # Get unique port for this test
                frontend_port = get_unique_ports(
                    request, num_ports=1, registration_order=registration_order
                )[0]

                # Run disagg routing test
                _test_router_decisions_disagg(
                    prefill_workers=prefill_workers,
                    decode_workers=decode_workers,
                    block_size=BLOCK_SIZE,
                    request=request,
                    frontend_port=frontend_port,
                    test_payload=TEST_PAYLOAD,
                    request_plane="nats",
                )
    else:
        # Start decode workers first
        logger.info("Starting 4 decode mocker instances (first)")
        with DisaggMockerProcess(
            request,
            namespace=shared_namespace,
            worker_type="decode",
            mocker_args=mocker_args,
            num_mockers=4,
            request_plane="nats",
        ) as decode_workers:
785
786
787
788
            logger.info(f"Decode workers using endpoint: {decode_workers.endpoint}")

            # Then start prefill workers
            logger.info("Starting 4 prefill mocker instances (second)")
789
            with DisaggMockerProcess(
790
791
792
793
794
                request,
                namespace=shared_namespace,
                worker_type="prefill",
                mocker_args=mocker_args,
                num_mockers=4,
795
796
                request_plane="nats",
                enable_bootstrap=enable_disagg_bootstrap,
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
            ) as prefill_workers:
                logger.info(
                    f"Prefill workers using endpoint: {prefill_workers.endpoint}"
                )

                # Get unique port for this test
                frontend_port = get_unique_ports(
                    request, num_ports=1, registration_order=registration_order
                )[0]

                # Run disagg routing test
                _test_router_decisions_disagg(
                    prefill_workers=prefill_workers,
                    decode_workers=decode_workers,
                    block_size=BLOCK_SIZE,
                    request=request,
                    frontend_port=frontend_port,
                    test_payload=TEST_PAYLOAD,
                    request_plane="nats",
                )
817
818


819
@pytest.mark.parametrize("request_plane", ["nats", "tcp"], indirect=True)
820
@pytest.mark.parametrize(
821
    "durable_kv_events", [False], ids=["nondurable"], indirect=True
822
)  # Use NATS Core (local indexer)
823
@pytest.mark.timeout(120)  # bumped for xdist contention (was 39s; ~12.84s serial avg)
824
def test_busy_threshold_endpoint(
825
826
827
828
    request,
    runtime_services_dynamic_ports,
    predownload_tokenizers,
    request_plane,
829
    durable_kv_events,
830
831
832
833
834
835
836
837
838
839
):
    """Test that the /busy_threshold endpoint can be hit and responds correctly.

    TODO: This doesn't actually test any e2e rejection for now. A proper test would:
    1. Set a very low threshold
    2. Send enough requests to exceed the threshold
    3. Verify that subsequent requests are rejected with 503

    For now, this test only verifies the endpoint is accessible and returns valid responses.
    """
840
    # runtime_services_dynamic_ports handles NATS and etcd startup
841
842
843
    logger.info(
        f"Starting busy_threshold endpoint test with request_plane={request_plane}"
    )
844

845
846
847
848
    # Use local indexer (NATS Core mode)
    mocker_args = {
        "speedup_ratio": SPEEDUP_RATIO,
        "block_size": BLOCK_SIZE,
849
        "durable_kv_events": durable_kv_events,
850
    }
851

852
853
854
855
856
857
    with MockerProcess(
        request,
        mocker_args=mocker_args,
        num_mockers=NUM_MOCKERS,
        request_plane=request_plane,
    ) as mockers:
858
859
860
        logger.info(f"Starting {NUM_MOCKERS} mocker instances")
        logger.info(f"All mockers using endpoint: {mockers.endpoint}")

861
862
863
        frontend_port = get_unique_ports(
            request, num_ports=1, request_plane=request_plane
        )[0]
864
865
866
867
868
869
870

        _test_busy_threshold_endpoint(
            engine_workers=mockers,
            block_size=BLOCK_SIZE,
            request=request,
            frontend_port=frontend_port,
            test_payload=TEST_PAYLOAD,
871
            request_plane=request_plane,
872
        )