"docs/pages/performance/tuning.md" did not exist on "6f8c68c17f883e2aba9a78beb13634ddd509985b"
test_cancellation.py 10.5 KB
Newer Older
1
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
3
4
5
6
7
# SPDX-License-Identifier: Apache-2.0

import asyncio

import pytest

8
9
from dynamo.runtime import Context

10
11
12
13
14
pytestmark = [
    pytest.mark.gpu_0,
    pytest.mark.pre_merge,
    pytest.mark.unit,
]
15
16
17
18
19
20
21
22
23
24
25
26


class MockServer:
    """
    Test request handler that simulates a generate method with cancellation support
    """

    def __init__(self):
        self.context_is_stopped = False
        self.context_is_killed = False

    async def generate(self, request, context):
27
28
        print("################## generate called ######################")

29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
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
121
122
        self.context_is_stopped = False
        self.context_is_killed = False

        method_name = request
        assert hasattr(
            self, method_name
        ), f"Method '{method_name}' not found on {self.__class__.__name__}"
        method = getattr(self, method_name)
        async for response in method(request, context):
            yield response

    async def _generate_until_context_cancelled(self, request, context):
        """
        Generate method that yields numbers 0-999 every 0.1 seconds
        Checks for context.is_stopped() / context.is_killed() before each yield and raises
        CancelledError if stopped / killed
        """
        for i in range(1000):
            print(f"Processing iteration {i}")

            # Check if context is stopped
            if context.is_stopped():
                print(f"Context stopped at iteration {i}")
                self.context_is_stopped = True
                self.context_is_killed = context.is_killed()
                raise asyncio.CancelledError

            # Check if context is killed
            if context.is_killed():
                print(f"Context killed at iteration {i}")
                self.context_is_stopped = context.is_stopped()
                self.context_is_killed = True
                raise asyncio.CancelledError

            await asyncio.sleep(0.1)

            print(f"Sending iteration {i}")
            yield i

        assert (
            False
        ), "Test failed: generate_until_cancelled did not raise CancelledError"

    async def _generate_until_asyncio_cancelled(self, request, context):
        """
        Generate method that yields numbers 0-999 every 0.1 seconds
        """
        i = 0
        try:
            for i in range(1000):
                print(f"Processing iteration {i}")
                await asyncio.sleep(0.1)
                print(f"Sending iteration {i}")
                yield i
        except asyncio.CancelledError:
            print(f"Cancelled at iteration {i}")
            self.context_is_stopped = context.is_stopped()
            self.context_is_killed = context.is_killed()
            raise

        assert (
            False
        ), "Test failed: generate_until_cancelled did not raise CancelledError"

    async def _generate_and_cancel_context(self, request, context):
        """
        Generate method that yields numbers 0-1, and then cancel the context
        """
        for i in range(2):
            print(f"Processing iteration {i}")
            await asyncio.sleep(0.1)
            print(f"Sending iteration {i}")
            yield i

        context.stop_generating()

        self.context_is_stopped = context.is_stopped()
        self.context_is_killed = context.is_killed()

    async def _generate_and_raise_cancelled(self, request, context):
        """
        Generate method that yields numbers 0-1, and then raise asyncio.CancelledError
        """
        for i in range(2):
            print(f"Processing iteration {i}")
            await asyncio.sleep(0.1)
            print(f"Sending iteration {i}")
            yield i

        raise asyncio.CancelledError


@pytest.fixture
def namespace():
123
    """Namespace for this test file"""
124
    return "cancellation-unit-test"
125
126
127
128
129
130
131
132
133
134


@pytest.fixture
async def server(runtime, namespace):
    """Start a test server in the background"""

    handler = MockServer()

    async def init_server():
        """Initialize the test server component and serve the generate endpoint"""
135
        endpoint = runtime.endpoint(f"{namespace}.backend.generate")
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
        print("Started test server instance")

        # Serve the endpoint - this will block until shutdown
        await endpoint.serve_endpoint(handler.generate)

    # Start server in background task
    server_task = asyncio.create_task(init_server())

    # Give server time to start up
    await asyncio.sleep(0.5)

    yield server_task, handler

    # Cleanup - cancel server task
    if not server_task.done():
        server_task.cancel()
        try:
            await server_task
        except asyncio.CancelledError:
            pass


@pytest.fixture
async def client(runtime, namespace):
    """Create a client connected to the test server"""
    # Create client
162
    endpoint = runtime.endpoint(f"{namespace}.backend.generate")
163
164
165
166
    client = await endpoint.client()
    await client.wait_for_instances()

    return client
167
168
169
170


@pytest.mark.forked
@pytest.mark.asyncio
171
@pytest.mark.parametrize("request_plane", ["nats", "tcp"], indirect=True)
172
async def test_client_context_cancel(temp_file_store, server, client):
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
    _, handler = server
    context = Context()
    stream = await client.generate("_generate_until_context_cancelled", context=context)

    iteration_count = 0
    async for annotated in stream:
        number = annotated.data()
        print(f"Received iteration: {number}")

        # Verify received valid number
        assert number == iteration_count

        # Break after receiving 2 responses
        if iteration_count >= 2:
            print("Cancelling after 2 responses...")
            context.stop_generating()
            break

        iteration_count += 1

    # Give server a moment to process the cancellation
    await asyncio.sleep(0.2)

    # Verify server detected the cancellation
    assert handler.context_is_stopped
    assert not handler.context_is_killed

    # TODO: Test with _generate_until_asyncio_cancelled server handler


@pytest.mark.forked
@pytest.mark.asyncio
205
@pytest.mark.parametrize("request_plane", ["nats", "tcp"], indirect=True)
206
async def test_client_loop_break(temp_file_store, server, client):
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
    _, handler = server
    stream = await client.generate("_generate_until_context_cancelled")

    iteration_count = 0
    async for annotated in stream:
        number = annotated.data()
        print(f"Received iteration: {number}")

        # Verify received valid number
        assert number == iteration_count

        # Break after receiving 2 responses
        if iteration_count >= 2:
            print("Cancelling after 2 responses...")
            break

        iteration_count += 1

    # Give server a moment to process the cancellation
    await asyncio.sleep(0.2)

    # TODO: Implicit cancellation is not yet implemented, so the server context will not
    #       show any cancellation.
    assert not handler.context_is_stopped
    assert not handler.context_is_killed

    # TODO: Test with _generate_until_asyncio_cancelled server handler


@pytest.mark.forked
@pytest.mark.asyncio
238
@pytest.mark.parametrize("request_plane", ["nats", "tcp"], indirect=True)
239
async def test_server_context_cancel(temp_file_store, server, client):
240
241
242
243
244
245
246
247
248
249
250
251
252
253
    _, handler = server
    stream = await client.generate("_generate_and_cancel_context")

    iteration_count = 0
    try:
        async for annotated in stream:
            number = annotated.data()
            print(f"Received iteration: {number}")
            assert number == iteration_count
            iteration_count += 1
        assert False, "Stream completed without cancellation"
    except ValueError as e:
        # Verify the expected cancellation exception is received
        # TODO: Should this be a asyncio.CancelledError?
254
255
256
        assert str(e).startswith(
            "Disconnected: Stream ended before generation completed"
        )
257
258
259
260
261
262
263
264

    # Verify server context cancellation status
    assert handler.context_is_stopped
    assert not handler.context_is_killed


@pytest.mark.forked
@pytest.mark.asyncio
265
@pytest.mark.parametrize("request_plane", ["nats", "tcp"], indirect=True)
266
async def test_server_raise_cancelled(temp_file_store, server, client):
267
268
269
270
271
272
273
274
275
276
277
278
279
280
    _, handler = server
    stream = await client.generate("_generate_and_raise_cancelled")

    iteration_count = 0
    try:
        async for annotated in stream:
            number = annotated.data()
            print(f"Received iteration: {number}")
            assert number == iteration_count
            iteration_count += 1
        assert False, "Stream completed without cancellation"
    except ValueError as e:
        # Verify the expected cancellation exception is received
        # TODO: Should this be a asyncio.CancelledError?
281
282
        assert "CancelledError" in str(e)
        assert "BackendCancelled" in str(e)
283
284
285
286
287

    # Verify server context cancellation status
    # TODO: Server to gracefully stop the stream?
    assert not handler.context_is_stopped
    assert not handler.context_is_killed
288
289
290
291


@pytest.mark.forked
@pytest.mark.asyncio
292
@pytest.mark.parametrize("request_plane", ["nats", "tcp"], indirect=True)
293
async def test_client_context_already_cancelled(temp_file_store, server, client):
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
    _, handler = server
    context = Context()
    context.stop_generating()
    # TODO: (DIS-830) The outgoing call should raise if context is cancelled
    stream = await client.generate("_generate_until_context_cancelled", context=context)

    async for _ in stream:
        raise AssertionError(
            "Request should be cancelled before any responses are generated"
        )

    # Give server a moment to update status
    await asyncio.sleep(0.2)

    # Verify server context cancellation status
    assert handler.context_is_stopped
    assert not handler.context_is_killed


@pytest.mark.forked
@pytest.mark.asyncio
315
@pytest.mark.parametrize("request_plane", ["nats", "tcp"], indirect=True)
316
317
318
async def test_client_context_cancel_before_await_request(
    temp_file_store, server, client
):
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
    _, handler = server
    context = Context()
    request = client.generate("_generate_until_context_cancelled", context=context)
    context.stop_generating()
    # TODO: (DIS-830) The outgoing call should raise if context is cancelled
    stream = await request

    async for _ in stream:
        raise AssertionError(
            "Request should be cancelled before any responses are generated"
        )

    # Give server a moment to update status
    await asyncio.sleep(0.2)

    # Verify server context cancellation status
    assert handler.context_is_stopped
    assert not handler.context_is_killed