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

4
5
6
7
8
9
10
11
# Parallelization: Hermetic test (xdist-safe via dynamic ports).
# Tested on: Linux (Ubuntu 24.04 container), Intel(R) Core(TM) i9-14900K, 32 vCPU.
# Combined pre_merge wall time (this file + test_tensor_parameters.py):
# - Serialized: 87.48s.
# - Parallel (-n auto): 25.27s (62.21s saved, 3.46x).
# GPU Requirement: gpu_0 (CPU-only, echo worker does not use GPU)

"""gRPC tensor echo test with mocker worker."""
12
13
14
15
16

from __future__ import annotations

import logging
import os
17
import queue
18
import shutil
19
from functools import partial
20

21
import numpy as np
22
import pytest
23
24
25
26
27
28
29
30
31
32

try:
    import tritonclient.grpc as grpcclient
except ImportError:
    grpcclient = None

try:
    import triton_echo_client
except ImportError:
    triton_echo_client = None
33
34
35
36
37
38
39
40
41
42

from tests.utils.constants import QWEN
from tests.utils.managed_process import ManagedProcess

logger = logging.getLogger(__name__)

TEST_MODEL = QWEN


class MockWorkerProcess(ManagedProcess):
43
    def __init__(self, request, system_port: int, worker_id: str = "mocker-worker"):
44
        self.worker_id = worker_id
45
        self.system_port = system_port
46
47
48
49
50
51
52
53
54

        command = [
            "python3",
            os.path.join(os.path.dirname(__file__), "echo_tensor_worker.py"),
        ]

        env = os.environ.copy()
        env["DYN_LOG"] = "debug"
        env["DYN_SYSTEM_USE_ENDPOINT_HEALTH_STATUS"] = '["generate"]'
55
        env["DYN_SYSTEM_PORT"] = str(system_port)
56
57
58
59
60
61
62
63
64
65
66
67
68

        log_dir = f"{request.node.name}_{worker_id}"

        try:
            shutil.rmtree(log_dir)
        except FileNotFoundError:
            pass

        super().__init__(
            command=command,
            env=env,
            health_check_urls=[
                # gRPC doesn't expose endpoint for listing models, so skip this check
69
70
                # (f"http://localhost:{grpc_port}/v1/models", check_models_api),
                (f"http://localhost:{system_port}/health", self.is_ready),
71
72
73
            ],
            timeout=300,
            display_output=True,
74
            terminate_all_matching_process_names=False,
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
            stragglers=[],
            straggler_commands=["echo_tensor_worker.py"],
            log_dir=log_dir,
        )

    def is_ready(self, response) -> bool:
        try:
            status = (response.json() or {}).get("status")
        except ValueError:
            logger.warning("%s health response is not valid JSON", self.worker_id)
            return False

        is_ready = status == "ready"
        if is_ready:
            logger.info("%s status is ready", self.worker_id)
        else:
            logger.warning("%s status is not ready: %s", self.worker_id, status)
        return is_ready


95
96
97
@pytest.fixture(scope="function")
def start_services_with_echo_worker(request, start_services_with_grpc):
    """Start echo worker with the shared gRPC frontend.
98

99
100
101
102
103
104
105
106
    Function-scoped to allow parallel test execution.
    Each test gets its own gRPC frontend + echo worker on unique ports.
    No namespace conflicts because runtime_services_dynamic_ports provides isolated Etcd/NATS.
    """
    frontend_port, system_port = start_services_with_grpc
    with MockWorkerProcess(request, system_port):
        logger.info(f"gRPC Echo Worker started for test on port {frontend_port}")
        yield frontend_port
107
108
109


@pytest.mark.pre_merge
110
111
@pytest.mark.gpu_0  # Echo worker is CPU-only (no GPU required)
@pytest.mark.parallel
112
@pytest.mark.integration
113
@pytest.mark.model(TEST_MODEL)
114
115
116
117
118
119
def test_echo(start_services_with_echo_worker) -> None:
    frontend_port = start_services_with_echo_worker
    # Use a per-test client instance to avoid cross-test/global state issues.
    client = triton_echo_client.TritonEchoClient(grpc_port=frontend_port)
    client.check_health()
    client.run_infer()
120
    client.run_stream_infer()
121
    client.get_config()
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227


@pytest.mark.e2e
@pytest.mark.pre_merge
@pytest.mark.gpu_0  # Echo tensor worker is CPU-only (no GPU required)
@pytest.mark.parallel
@pytest.mark.parametrize(
    "request_params",
    [
        {"malformed_response": True},
        {"raise_exception": True},
    ],
    ids=["malformed_response", "raise_exception"],
)
def test_model_infer_failure(start_services_with_echo_worker, request_params):
    """Test gRPC request-level parameters are echoed through tensor models.

    The worker acts as an identity function: echoes input tensors unchanged and
    returns all request parameters plus a "processed" flag to verify the complete
    parameter flow through the gRPC frontend.
    """
    frontend_port = start_services_with_echo_worker
    client = grpcclient.InferenceServerClient(f"localhost:{frontend_port}")

    input_data = np.array([1.0, 2.0, 3.0, 4.0], dtype=np.float32)
    inputs = [grpcclient.InferInput("INPUT", input_data.shape, "FP32")]
    inputs[0].set_data_from_numpy(input_data)

    # expect exception during inference
    with pytest.raises(Exception) as excinfo:
        client.infer("echo", inputs=inputs, parameters=request_params)
    if "malformed_response" in request_params:
        assert "missing field `data_type`" in str(excinfo.value).lower()
    elif "raise_exception" in request_params:
        assert "intentional exception" in str(excinfo.value).lower()


@pytest.mark.e2e
@pytest.mark.pre_merge
@pytest.mark.gpu_0  # Echo tensor worker is CPU-only (no GPU required)
@pytest.mark.parallel
@pytest.mark.parametrize(
    "request_params",
    [
        {"malformed_response": True},
        {"raise_exception": True},
        {"data_mismatch": True},
    ],
    ids=["malformed_response", "raise_exception", "data_mismatch"],
)
def test_model_stream_infer_failure(start_services_with_echo_worker, request_params):
    """Test gRPC request-level parameters are echoed through tensor models.

    The worker acts as an identity function: echoes input tensors unchanged and
    returns all request parameters plus a "processed" flag to verify the complete
    parameter flow through the gRPC frontend.
    """
    frontend_port = start_services_with_echo_worker
    client = grpcclient.InferenceServerClient(f"localhost:{frontend_port}")

    input_data = np.array([1.0, 2.0, 3.0, 4.0], dtype=np.float32)
    inputs = [grpcclient.InferInput("INPUT", input_data.shape, "FP32")]
    inputs[0].set_data_from_numpy(input_data)

    class UserData:
        def __init__(self):
            self._completed_requests: queue.Queue[
                grpcclient.InferResult | Exception
            ] = queue.Queue()

    # Define the callback function. Note the last two parameters should be
    # result and error. InferenceServerClient would povide the results of an
    # inference as grpcclient.InferResult in result. For successful
    # inference, error will be None, otherwise it will be an object of
    # tritonclientutils.InferenceServerException holding the error details
    def callback(user_data, result, error):
        print("Received callback")
        if error:
            user_data._completed_requests.put(error)
        else:
            user_data._completed_requests.put(result)

    user_data = UserData()
    client.start_stream(
        callback=partial(callback, user_data),
    )

    client.async_stream_infer(
        model_name="echo",
        inputs=inputs,
        parameters=request_params,
    )

    # For stream infer, the exception and error will pass to the callback but not
    # raised
    with pytest.raises(Exception) as excinfo:
        data_item = user_data._completed_requests.get(timeout=5)
        if isinstance(data_item, Exception):
            print("Raising exception received from stream infer callback")
            raise data_item
    if "malformed_response" in request_params:
        assert "missing field `data_type`" in str(excinfo.value).lower()
    elif "data_mismatch" in request_params:
        assert "shape implies" in str(excinfo.value).lower()
    elif "raise_exception" in request_params:
        assert "intentional exception" in str(excinfo.value).lower()