test_router_e2e_with_mockers.py 25.2 KB
Newer Older
1
2
3
4
# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
import logging
import os
5
from typing import Any, Dict, Optional
6
7
8

import pytest

9
from tests.router.common import (  # utilities
10
    _test_busy_threshold_endpoint,
11
12
13
    _test_python_router_bindings,
    _test_router_basic,
    _test_router_decisions,
14
    _test_router_decisions_disagg,
15
16
17
18
19
20
21
    _test_router_indexers_sync,
    _test_router_overload_503,
    _test_router_query_instance_id,
    _test_router_two_routers,
    generate_random_suffix,
    get_runtime,
)
Alec's avatar
Alec committed
22
from tests.utils.constants import ROUTER_MODEL_NAME
23
24
from tests.utils.managed_process import ManagedProcess

25
26
27
28
logger = logging.getLogger(__name__)

MODEL_NAME = ROUTER_MODEL_NAME

29
30
31
32
pytestmark = [
    pytest.mark.pre_merge,
    pytest.mark.gpu_0,
    pytest.mark.integration,
33
    pytest.mark.model(MODEL_NAME),
34
]
35
36
NUM_MOCKERS = 2
SPEEDUP_RATIO = 10.0
37
BASE_PORT = 9100  # Base port for all tests (high port to avoid conflicts)
38
NUM_REQUESTS = 100
39
BLOCK_SIZE = 16
40
41


42
def get_unique_ports(
43
44
45
46
    request,
    num_ports: int = 1,
    store_backend: str = "etcd",
    request_plane: str = "nats",
47
    registration_order: str = "prefill_first",
48
49
50
51
52
) -> list[int]:
    """Generate unique ports for parallel test execution.

    Ports are unique based on:
    - Test function name (each test gets a base offset)
53
    - Parametrization value (etcd=0, file=50; nats=0, tcp=25; prefill_first=0, decode_first=10)
54
55
56
57
58
59
    - Port index (for multi-port tests)

    Args:
        request: Pytest request fixture
        num_ports: Number of ports needed (1 for single router, 2 for two routers)
        store_backend: Storage backend parameter ("etcd" or "file")
60
        request_plane: Request plane parameter ("nats" or "tcp")
61
        registration_order: Registration order parameter ("prefill_first" or "decode_first")
62
63
64
65
66
67
68
69
70
71
72
73
74

    Returns:
        List of unique port numbers
    """
    # Get test name without parametrization suffix
    test_name = request.node.name.split("[")[0]

    # Base offsets per test function (ensures each test gets unique range)
    test_offsets = {
        "test_mocker_kv_router": 0,
        "test_mocker_two_kv_router": 100,
        "test_mocker_kv_router_overload_503": 200,
        "test_query_instance_id_returns_worker_and_tokens": 300,
75
        "test_router_decisions_disagg": 400,
76
        "test_busy_threshold_endpoint": 500,
77
78
79
80
    }

    base_offset = test_offsets.get(test_name, 0)

81
    # Parametrization offset (etcd=0, file=50; nats=0, tcp=25; prefill_first=0, decode_first=10)
82
83
    store_offset = 0 if store_backend == "etcd" else 50
    plane_offset = 0 if request_plane == "nats" else 25
84
    order_offset = 0 if registration_order == "prefill_first" else 10
85
86

    # Generate ports
87
    ports = [
88
        BASE_PORT + base_offset + store_offset + plane_offset + order_offset + i
89
90
        for i in range(num_ports)
    ]
91
92
93
    return ports


94
95
96
97
98
99
100
101
102
103
104
105
106
# 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,
}

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
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
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,
        "--store-kv",
        store_backend,
        "--num-workers",
        str(num_workers),
    ]

    # Add worker type flag for disaggregated mode
    if worker_type == "prefill":
        command.append("--is-prefill-worker")
    elif worker_type == "decode":
        command.append("--is-decode-worker")

    # 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"])])

    return command


180
class MockerProcess:
181
    """Manages mocker engine instances with shared tokio runtime via --num-workers."""
182

183
184
185
186
187
    def __init__(
        self,
        request,
        mocker_args: Optional[Dict[str, Any]] = None,
        num_mockers: int = 1,
188
        store_backend: str = "etcd",
189
        request_plane: str = "nats",
190
    ):
191
192
        namespace_suffix = generate_random_suffix()
        self.namespace = f"test-namespace-{namespace_suffix}"
193
194
        self.component_name = "mocker"
        self.endpoint = f"dyn://{self.namespace}.{self.component_name}.generate"
195
196
197
198
199
200
201
202
203
204
205
        self.num_workers = num_mockers

        mocker_args = mocker_args or {}

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

206
207
208
        env = os.environ.copy()
        env["DYN_REQUEST_PLANE"] = request_plane

209
210
        self._process = ManagedProcess(
            command=command,
211
            env=env,
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
            timeout=60,
            display_output=True,
            health_check_ports=[],
            health_check_urls=[],
            log_dir=request.node.name,
            terminate_existing=False,
        )
        logger.info(
            f"Created mocker process with {num_mockers} worker(s), endpoint: {self.endpoint}"
        )

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

    def __exit__(self, exc_type, exc_val, exc_tb):
        logger.info("Stopping mocker process")
        self._process.__exit__(exc_type, exc_val, exc_tb)


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",
    ):
        if worker_type not in ("prefill", "decode"):
            raise ValueError(
                f"worker_type must be 'prefill' or 'decode', got {worker_type}"
255
            )
256
257
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

        self.namespace = namespace
        self.worker_type = worker_type
        self.num_workers = num_mockers

        # 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"

        mocker_args = mocker_args or {}

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

        self._process = ManagedProcess(
            command=command,
            timeout=60,
            display_output=True,
            health_check_ports=[],
            health_check_urls=[],
            log_dir=request.node.name,
            terminate_existing=False,
        )
        logger.info(
            f"Created {worker_type} mocker process with {num_mockers} worker(s), "
            f"endpoint: {self.endpoint}"
        )
292

293
    def __enter__(self):
294
295
296
297
        logger.info(
            f"Starting {self.worker_type} mocker process with {self.num_workers} worker(s)"
        )
        self._process.__enter__()
298
        return self
299

300
    def __exit__(self, exc_type, exc_val, exc_tb):
301
302
        logger.info(f"Stopping {self.worker_type} mocker process")
        self._process.__exit__(exc_type, exc_val, exc_tb)
303
304


305
@pytest.mark.parallel
306
def test_mocker_kv_router(request, runtime_services_session, predownload_tokenizers):
307
308
309
310
311
312
313
314
    """
    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")

315
    # Create mocker args dictiona: FixtureRequestry: tuple[NatsServer, EtcdServer]: NoneType
316
    mocker_args = {"speedup_ratio": SPEEDUP_RATIO, "block_size": BLOCK_SIZE}
317
318

    try:
319
        # Start mocker instances with the new CLI interface
320
        logger.info(f"Starting {NUM_MOCKERS} mocker instances")
321
322
323
        mockers = MockerProcess(
            request, mocker_args=mocker_args, num_mockers=NUM_MOCKERS
        )
324
325
        logger.info(f"All mockers using endpoint: {mockers.endpoint}")
        mockers.__enter__()
326

327
328
329
330
        # Get unique port for this test
        frontend_port = get_unique_ports(request, num_ports=1)[0]

        # Run basic router test (starts router internally and waits for workers to be ready)
331
332
333
334
        _test_router_basic(
            engine_workers=mockers,
            block_size=BLOCK_SIZE,
            request=request,
335
            frontend_port=frontend_port,
336
337
            test_payload=TEST_PAYLOAD,
            num_requests=NUM_REQUESTS,
338
339
340
        )

    finally:
341
342
        if "mockers" in locals():
            mockers.__exit__(None, None, None)
343
344


345
@pytest.mark.parallel
346
347
348
@pytest.mark.parametrize("store_backend", ["etcd", "file"])
def test_mocker_two_kv_router(
    request,
349
    runtime_services_session,
350
351
352
353
    predownload_tokenizers,
    file_storage_backend,
    store_backend,
):
354
355
356
    """
    Test with two KV routers and multiple mocker engine instances.
    Alternates requests between the two routers to test load distribution.
357
    Tests with both etcd and file storage backends.
358
359
360
    """

    # runtime_services starts etcd and nats
361
362
363
    logger.info(
        f"Starting mocker two KV router test with {store_backend} storage backend"
    )
364

365
    # Create mocker args dictionary
366
367
368
    mocker_args = {"speedup_ratio": SPEEDUP_RATIO, "block_size": BLOCK_SIZE}

    try:
369
        # Start mocker instances with the new CLI interface
370
        logger.info(f"Starting {NUM_MOCKERS} mocker instances")
371
        mockers = MockerProcess(
372
373
374
375
            request,
            mocker_args=mocker_args,
            num_mockers=NUM_MOCKERS,
            store_backend=store_backend,
376
        )
377
378
        logger.info(f"All mockers using endpoint: {mockers.endpoint}")
        mockers.__enter__()
379

380
381
382
383
384
        # Get unique ports for this test (2 ports for two routers)
        router_ports = get_unique_ports(
            request, num_ports=2, store_backend=store_backend
        )

385
386
387
388
389
        # 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,
390
            router_ports=router_ports,
391
392
393
            test_payload=TEST_PAYLOAD,
            num_requests=NUM_REQUESTS,
            store_backend=store_backend,
394
395
396
        )

    finally:
397
398
        if "mockers" in locals():
            mockers.__exit__(None, None, None)
399
400


401
@pytest.mark.parallel
402
@pytest.mark.skip(reason="Flaky, temporarily disabled")
Alec's avatar
Alec committed
403
def test_mocker_kv_router_overload_503(
404
    request, runtime_services_session, predownload_tokenizers
Alec's avatar
Alec committed
405
):
406
    """Test that KV router returns 503 when mocker workers are overloaded."""
407
    logger.info("Starting mocker KV router overload test for 503 status")
408
    # Create mocker args dictionary with limited resources
409
410
411
412
413
    mocker_args = {
        "speedup_ratio": 10,
        "block_size": 4,  # Smaller block size
        "num_gpu_blocks": 64,  # Limited GPU blocks to exhaust quickly
    }
414

415
    try:
416
        # Start single mocker instance with limited resources
417
        logger.info("Starting single mocker instance with limited resources")
418
        mockers = MockerProcess(request, mocker_args=mocker_args, num_mockers=1)
419
420
        logger.info(f"Mocker using endpoint: {mockers.endpoint}")
        mockers.__enter__()
421

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

425
426
427
428
429
430
431
        # 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,
432
            blocks_threshold=0.2,
433
        )
434
435

    finally:
436
437
        if "mockers" in locals():
            mockers.__exit__(None, None, None)
438

439

440
@pytest.mark.parallel
441
442
443
def test_kv_push_router_bindings(
    request, runtime_services_session, predownload_tokenizers
):
444
    """Test KvPushRouter Python bindings with mocker engines."""
445
446
447
448
    logger.info("Starting KvPushRouter bindings test")
    mocker_args = {"speedup_ratio": SPEEDUP_RATIO, "block_size": BLOCK_SIZE}

    try:
449
        # Start mocker instances
450
        logger.info(f"Starting {NUM_MOCKERS} mocker instances")
451
452
453
        mockers = MockerProcess(
            request, mocker_args=mocker_args, num_mockers=NUM_MOCKERS
        )
454
455
        logger.info(f"All mockers using endpoint: {mockers.endpoint}")
        mockers.__enter__()
456

457
458
459
        # Get runtime and create endpoint
        runtime = get_runtime()
        namespace = runtime.namespace(mockers.namespace)
460
        component = namespace.component(mockers.component_name)
461
462
        endpoint = component.endpoint("generate")

463
464
465
        # Run Python router bindings test
        _test_python_router_bindings(
            engine_workers=mockers,
466
467
            endpoint=endpoint,
            block_size=BLOCK_SIZE,
468
469
            model_name=MODEL_NAME,
            num_workers=NUM_MOCKERS,
470
        )
471
472

    finally:
473
474
475
476
        if "mockers" in locals():
            mockers.__exit__(None, None, None)


477
478
479
@pytest.mark.parametrize("store_backend", ["etcd", "file"])
def test_indexers_sync(
    request,
480
    runtime_services_session,
481
482
483
484
    predownload_tokenizers,
    file_storage_backend,
    store_backend,
):
485
486
487
    """
    Test that two KV routers have synchronized indexer states after processing requests.
    This test verifies that both routers converge to the same internal state.
488
    Tests with both etcd and file storage backends.
489
490
491
    """

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

494
    # Create mocker args dictionary
495
496
497
    mocker_args = {"speedup_ratio": SPEEDUP_RATIO, "block_size": BLOCK_SIZE}

    try:
498
        # Start mocker instances
499
        logger.info(f"Starting {NUM_MOCKERS} mocker instances")
500
        mockers = MockerProcess(
501
502
503
504
            request,
            mocker_args=mocker_args,
            num_mockers=NUM_MOCKERS,
            store_backend=store_backend,
505
        )
506
507
508
        logger.info(f"All mockers using endpoint: {mockers.endpoint}")
        mockers.__enter__()

509
510
511
512
513
514
515
516
517
        # Use the common test implementation (creates its own runtimes for each router)
        # Note: Consumer verification is done inside _test_router_indexers_sync while routers are alive
        _test_router_indexers_sync(
            engine_workers=mockers,
            block_size=BLOCK_SIZE,
            model_name=MODEL_NAME,
            num_workers=NUM_MOCKERS,
            store_backend=store_backend,
        )
518
519
520
521
522
523

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

    finally:
        if "mockers" in locals():
            mockers.__exit__(None, None, None)
524

525

526
@pytest.mark.parallel
Alec's avatar
Alec committed
527
def test_query_instance_id_returns_worker_and_tokens(
528
    request, runtime_services_session, predownload_tokenizers
Alec's avatar
Alec committed
529
):
530
    """Test query_instance_id annotation with mocker engines."""
531
532
533
534
535
    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:
536
        # Start mocker instances
537
        logger.info(f"Starting {NUM_MOCKERS} mocker instances")
538
539
540
        mockers = MockerProcess(
            request, mocker_args=mocker_args, num_mockers=NUM_MOCKERS
        )
541
542
        logger.info(f"All mockers using endpoint: {mockers.endpoint}")
        mockers.__enter__()
543

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

547
548
549
550
551
552
553
554
        # 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,
        )
555
556

    finally:
557
558
        if "mockers" in locals():
            mockers.__exit__(None, None, None)
559
560


561
@pytest.mark.parallel
562
def test_router_decisions(request, runtime_services_session, predownload_tokenizers):
563
    """Validate KV cache prefix reuse and dp_rank routing by sending progressive requests with overlapping prefixes."""
564
565
566
567

    # 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
568
569
570
571
572
573
    # Create mocker args dictionary with dp_size=4
    mocker_args = {
        "speedup_ratio": SPEEDUP_RATIO,
        "block_size": BLOCK_SIZE,
        "dp_size": 4,
    }
574
575

    try:
Yan Ru Pei's avatar
Yan Ru Pei committed
576
577
        logger.info(
            "Starting 2 mocker instances with dp_size=4 each (8 total dp ranks)"
578
        )
Yan Ru Pei's avatar
Yan Ru Pei committed
579
        mockers = MockerProcess(request, mocker_args=mocker_args, num_mockers=2)
580
        logger.info(f"All mockers using endpoint: {mockers.endpoint}")
581

582
583
584
585
586
587
588
589
590
591
        # 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")

592
593
        _test_router_decisions(
            mockers, endpoint, MODEL_NAME, request, test_dp_rank=True
594
595
596
597
598
        )

    finally:
        if "mockers" in locals():
            mockers.__exit__(None, None, None)
599
600


601
@pytest.mark.parallel
602
@pytest.mark.parametrize("registration_order", ["prefill_first", "decode_first"])
603
def test_router_decisions_disagg(
604
    request, runtime_services_session, predownload_tokenizers, registration_order
605
606
607
608
609
):
    """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.
610
611
612
613

    Parameterized to test both registration orders:
    - prefill_first: prefill workers register before decode workers
    - decode_first: decode workers register before prefill workers
614
    """
615
616
617
618
    logger.info(
        f"Starting disaggregated router prefix reuse test "
        f"(registration_order={registration_order})"
    )
619
620
621
622
623
624
625
626
627
628
629
630

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

    # Create mocker args
    mocker_args = {"speedup_ratio": SPEEDUP_RATIO, "block_size": BLOCK_SIZE}

    prefill_workers = None
    decode_workers = None

    try:
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
        if registration_order == "prefill_first":
            # Start prefill workers first
            logger.info("Starting 4 prefill mocker instances (first)")
            prefill_workers = DisaggMockerProcess(
                request,
                namespace=shared_namespace,
                worker_type="prefill",
                mocker_args=mocker_args,
                num_mockers=4,
            )
            prefill_workers.__enter__()
            logger.info(f"Prefill workers using endpoint: {prefill_workers.endpoint}")

            # Then start decode workers
            logger.info("Starting 4 decode mocker instances (second)")
            decode_workers = DisaggMockerProcess(
                request,
                namespace=shared_namespace,
                worker_type="decode",
                mocker_args=mocker_args,
                num_mockers=4,
            )
            decode_workers.__enter__()
            logger.info(f"Decode workers using endpoint: {decode_workers.endpoint}")
        else:
            # Start decode workers first
            logger.info("Starting 4 decode mocker instances (first)")
            decode_workers = DisaggMockerProcess(
                request,
                namespace=shared_namespace,
                worker_type="decode",
                mocker_args=mocker_args,
                num_mockers=4,
            )
            decode_workers.__enter__()
            logger.info(f"Decode workers using endpoint: {decode_workers.endpoint}")

            # Then start prefill workers
            logger.info("Starting 4 prefill mocker instances (second)")
            prefill_workers = DisaggMockerProcess(
                request,
                namespace=shared_namespace,
                worker_type="prefill",
                mocker_args=mocker_args,
                num_mockers=4,
            )
            prefill_workers.__enter__()
            logger.info(f"Prefill workers using endpoint: {prefill_workers.endpoint}")
679
680

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

        # Run disagg routing test
686
        _test_router_decisions_disagg(
687
688
689
690
691
692
693
694
695
696
697
698
699
            prefill_workers=prefill_workers,
            decode_workers=decode_workers,
            block_size=BLOCK_SIZE,
            request=request,
            frontend_port=frontend_port,
            test_payload=TEST_PAYLOAD,
        )

    finally:
        if decode_workers is not None:
            decode_workers.__exit__(None, None, None)
        if prefill_workers is not None:
            prefill_workers.__exit__(None, None, None)
700
701


702
@pytest.mark.parallel
703
@pytest.mark.parametrize("request_plane", ["nats", "tcp"], indirect=True)
704
def test_busy_threshold_endpoint(
705
    request, runtime_services_session, predownload_tokenizers, request_plane
706
707
708
709
710
711
712
713
714
715
):
    """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.
    """
716
717
718
    logger.info(
        f"Starting busy_threshold endpoint test with request_plane={request_plane}"
    )
719
720
721
722
723
724

    mocker_args = {"speedup_ratio": SPEEDUP_RATIO, "block_size": BLOCK_SIZE}

    try:
        logger.info(f"Starting {NUM_MOCKERS} mocker instances")
        mockers = MockerProcess(
725
726
727
728
            request,
            mocker_args=mocker_args,
            num_mockers=NUM_MOCKERS,
            request_plane=request_plane,
729
730
731
732
        )
        logger.info(f"All mockers using endpoint: {mockers.endpoint}")
        mockers.__enter__()

733
734
735
        frontend_port = get_unique_ports(
            request, num_ports=1, request_plane=request_plane
        )[0]
736
737
738
739
740
741
742

        _test_busy_threshold_endpoint(
            engine_workers=mockers,
            block_size=BLOCK_SIZE,
            request=request,
            frontend_port=frontend_port,
            test_payload=TEST_PAYLOAD,
743
            request_plane=request_plane,
744
745
746
747
748
        )

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