Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 11 additions & 8 deletions components/src/dynamo/trtllm/request_handlers/handler_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -906,12 +906,15 @@ def _request_has_multimodal(self, request: dict) -> bool:
return True
return False

def _normalize_request_format(self, request: dict) -> None:
@staticmethod
def _normalize_request_format(request: dict) -> None:
"""
Convert OpenAI request format to TRT-LLM internal format.

Moves fields from OpenAI locations to where TRT-LLM expects them:
- max_tokens: top-level → stop_conditions.max_tokens
- min_tokens: top-level → stop_conditions.min_tokens
- ignore_eos: top-level → stop_conditions.ignore_eos
- temperature: top-level → sampling_options.temperature

Note: The Rust frontend's PrefillRouter handles the *value* of max_tokens
Expand All @@ -924,17 +927,17 @@ def _normalize_request_format(self, request: dict) -> None:
# Ensure stop_conditions exists
if "stop_conditions" not in request:
request["stop_conditions"] = {}
if "max_tokens" in request and "max_tokens" not in request["stop_conditions"]:
request["stop_conditions"]["max_tokens"] = request.pop("max_tokens")
for field in ("max_tokens", "min_tokens", "ignore_eos"):
if field in request:
value = request.pop(field)
request["stop_conditions"].setdefault(field, value)

# Ensure sampling_options exists
if "sampling_options" not in request:
request["sampling_options"] = {}
if (
"temperature" in request
and "temperature" not in request["sampling_options"]
):
request["sampling_options"]["temperature"] = request.pop("temperature")
if "temperature" in request:
temperature = request.pop("temperature")
request["sampling_options"].setdefault("temperature", temperature)

async def _initiate_shutdown(self, error: Exception):
"""Initiate graceful shutdown after fatal error"""
Expand Down
25 changes: 25 additions & 0 deletions components/src/dynamo/trtllm/tests/test_trtllm_handler_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -211,6 +211,31 @@ def test_post_init_called_when_overriding(self):
mock_post_init.assert_called_once()


class TestNormalizeRequestFormat:
def test_moves_openai_stop_fields_without_overwriting_internal_values(self):
request = {
"max_tokens": 64,
"min_tokens": 32,
"ignore_eos": True,
"temperature": 0.5,
"stop_conditions": {"min_tokens": 16},
"sampling_options": {"temperature": 0.25},
}

HandlerBase._normalize_request_format(request)

assert request["stop_conditions"] == {
"max_tokens": 64,
"min_tokens": 16,
"ignore_eos": True,
}
assert "max_tokens" not in request
assert "min_tokens" not in request
assert "ignore_eos" not in request
assert request["sampling_options"] == {"temperature": 0.25}
assert "temperature" not in request


class TestGuidedDecodingFromToolChoice:
"""Tests that guided_decoding dicts from Rust are converted to GuidedDecodingParams.

Expand Down
41 changes: 20 additions & 21 deletions tests/fault_tolerance/cancellation/test_trtllm.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@

import logging
import os
import shutil
import time

import pytest
Expand Down Expand Up @@ -65,6 +64,7 @@ def __init__(
request.addfinalizer(lambda port=system_port: deallocate_port(port))
self.system_port = system_port
self.frontend_port = frontend_port
tmp_path = request.getfixturevalue("tmp_path")

command = [
"python3",
Expand All @@ -80,16 +80,14 @@ def __init__(
"16384",
]
if mode != "agg":
with open("test_request_cancellation_trtllm_config.yaml", "w") as f:
config_file = tmp_path / f"trtllm_cancel_config_{system_port}.yaml"
with config_file.open("w") as f:
f.write(
"cache_transceiver_config:\n backend: DEFAULT\n max_tokens_in_buffer: 16384\n"
)
f.write("disable_overlap_scheduler: true\n")
f.write("kv_cache_config:\n max_tokens: 16384\n")
command += [
"--extra-engine-args",
"test_request_cancellation_trtllm_config.yaml",
]
command += ["--extra-engine-args", str(config_file)]

health_check_urls = [
(f"http://localhost:{frontend_port}/v1/models", check_models_api),
Expand All @@ -115,16 +113,7 @@ def __init__(
env["DYN_SYSTEM_USE_ENDPOINT_HEALTH_STATUS"] = '["generate"]'
env["DYN_SYSTEM_PORT"] = str(system_port)

# Set log directory based on worker type
log_dir = f"{request.node.name}_{mode}_worker"

# Clean up any existing log directory from previous runs
try:
shutil.rmtree(log_dir)
logger.info(f"Cleaned up existing log directory: {log_dir}")
except FileNotFoundError:
# Directory doesn't exist, which is fine
pass
log_dir = tmp_path / f"{mode}_worker"

super().__init__(
command=command,
Expand All @@ -133,7 +122,7 @@ def __init__(
timeout=300,
display_output=True,
terminate_all_matching_process_names=False,
log_dir=log_dir,
log_dir=str(log_dir),
)

self.mode = mode
Expand Down Expand Up @@ -346,7 +335,9 @@ def test_request_cancellation_trtllm_decode_cancel(
)


@pytest.mark.skip(reason="TRT-LLM prefill cancellation is disabled due to reliability")
@pytest.mark.skip(
reason="Cancellation does not reach TRT-LLM before prefill completes (1.3.0rc25)"
)
@pytest.mark.timeout(195) # 3x average
def test_request_cancellation_trtllm_prefill_cancel(
request, runtime_services_dynamic_ports, predownload_models
Expand Down Expand Up @@ -456,7 +447,6 @@ def test_request_cancellation_trtllm_prefill_cancel(
)


@pytest.mark.skip(reason="Test fails only on CI")
@pytest.mark.timeout(195) # 3x average
def test_request_cancellation_trtllm_kv_transfer_cancel(
request, runtime_services_dynamic_ports, predownload_models
Expand Down Expand Up @@ -527,6 +517,7 @@ def test_request_cancellation_trtllm_kv_transfer_cancel(
process=decode_worker,
pattern=f"Aborted Request ID: {request_id}",
log_offset=decode_log_offset,
max_wait_ms=10_000,
)

# Verify frontend log has kill message
Expand All @@ -541,15 +532,23 @@ def test_request_cancellation_trtllm_kv_transfer_cancel(

# Verify the workers are still functional
cancellable_req = send_cancellable_request(
frontend.frontend_port, "chat_completion_stream"
frontend.frontend_port,
"chat_completion_stream",
max_tokens=8,
timeout_s=30,
)
_, decode_log_offset = poll_for_pattern(
process=decode_worker,
pattern="Decode Request ID: ",
log_offset=decode_log_offset,
match_type="contains",
)
read_streaming_responses(cancellable_req, expected_count=5)
read_streaming_responses(
cancellable_req,
expected_count=1,
deadline_s=30,
drain=True,
)

logger.info(
"Workers are functional after cancellation during KV transfer"
Expand Down
5 changes: 2 additions & 3 deletions tests/fault_tolerance/cancellation/test_vllm.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,9 +51,8 @@
DECODE_CANCEL_TEST_TIMEOUT_S = 900

# The streaming read had no bound. STREAM_READ is the per-read socket timeout
# between chunks; BEHAVIORAL bounds the wait for the next chunk while the
# chunk-count goal is unmet. Neither caps total read time -- a late final chunk
# that completes the count still counts. See read_streaming_responses.
# between chunks; BEHAVIORAL caps total time spent reaching the chunk-count goal.
# See read_streaming_responses.
DECODE_CANCEL_STREAM_READ_TIMEOUT_S = 30
DECODE_CANCEL_BEHAVIORAL_ALLOWANCE_S = 90

Expand Down
117 changes: 94 additions & 23 deletions tests/fault_tolerance/cancellation/utils.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

import json
import logging
import re
import socket
Expand Down Expand Up @@ -281,17 +282,16 @@ def read_streaming_responses(
cancellable_req: CancellableRequest,
expected_count: int = 5,
deadline_s: float | None = None,
drain: bool = False,
) -> None:
"""Read a specific number of responses from a streaming request.

Args:
cancellable_req: The CancellableRequest object with an active stream
expected_count: Number of responses to read before returning
deadline_s: Budget for waiting on the next chunk, checked after each
arrival while the goal is unmet. A late chunk that completes
expected_count still counts, so this does not cap total read
time. The `timeout` passed to requests bounds a single read; this
bounds the sequence of them.
deadline_s: Absolute wall-clock budget for reading the required stream.
drain: Continue reading after expected_count until a successful terminal
response and ``[DONE]`` marker are received.

Raises:
pytest.fail if stream ends before expected_count responses
Expand All @@ -305,29 +305,100 @@ def read_streaming_responses(
)

response = cast(requests.Response, response_raw) # Type narrowing after checks
deadline = None if deadline_s is None else time.monotonic() + deadline_s
response_count = 0
for line in response.iter_lines():
response_count += 1
logger.info(
f"Received streaming response {response_count}: {line.decode()[:100]}"
)
if response_count >= expected_count:
logger.info(f"Successfully read {response_count} responses")
return
# Checked only while the goal is unmet. Moving this above the return
# would fail runs that received every chunk they needed.
if deadline is not None and time.monotonic() > deadline:
saw_finish_reason = False
saw_done = False
deadline = None if deadline_s is None else time.monotonic() + deadline_s
deadline_expired = threading.Event()
deadline_timer = None

if deadline_s is not None:

def expire_stream() -> None:
deadline_expired.set()
cancellable_req.cancel()

deadline_timer = threading.Timer(deadline_s, expire_stream)
deadline_timer.daemon = True
deadline_timer.start()

def fail_if_deadline_expired() -> None:
if deadline_expired.is_set() or (
deadline is not None and time.monotonic() >= deadline
):
cancellable_req.cancel()
pytest.fail(
f"Read only {response_count} of {expected_count} streaming responses "
f"within {deadline_s}s"
"Streaming response did not reach the required count and terminal "
f"state within {deadline_s}s; count={response_count}, "
f"expected={expected_count}"
)

# If we get here, stream ended too early
pytest.fail(
f"Stream ended after only {response_count} lines - expected to read at least {expected_count}"
)
try:
try:
for line in response.iter_lines():
fail_if_deadline_expired()
if not line:
continue
if not line.startswith(b"data:"):
logger.debug("Ignoring non-data SSE line: %s", line[:100])
continue

payload = line.removeprefix(b"data:").strip()
if payload == b"[DONE]":
saw_done = True
break

try:
event = json.loads(payload)
except (UnicodeDecodeError, json.JSONDecodeError) as error:
cancellable_req.cancel()
pytest.fail(f"Invalid JSON in streaming response: {error}")

if not isinstance(event, dict):
cancellable_req.cancel()
pytest.fail(
"Streaming response event must be a JSON object, "
f"got {type(event).__name__}"
)

if event.get("error") is not None:
cancellable_req.cancel()
pytest.fail(
f"Streaming response ended with an error: {event['error']}"
)

response_count += 1
Comment thread
tanmayv25 marked this conversation as resolved.
Resolved
saw_finish_reason = saw_finish_reason or any(
choice.get("finish_reason") is not None
for choice in event.get("choices", [])
)
logger.info(
"Received streaming response %s: %.100s", response_count, event
)
if response_count >= expected_count and not drain:
fail_if_deadline_expired()
logger.info(f"Successfully read {response_count} responses")
return
except Exception:
fail_if_deadline_expired()
raise

fail_if_deadline_expired()
if drain and not saw_done:
pytest.fail("Streaming response ended without a [DONE] marker")
if drain and not saw_finish_reason:
pytest.fail("Streaming response ended without a successful finish reason")
if response_count >= expected_count:
logger.info(f"Successfully drained {response_count} responses")
return

pytest.fail(
"Stream ended after only "
f"{response_count} lines - expected to read at least {expected_count}"
)
finally:
if deadline_timer is not None:
deadline_timer.cancel()


def _parse_frontend_cancellation_metric(
Expand Down
Loading
Loading