Skip to content
Merged
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@
from tensorrt_llm.executor.result import GenerationResult
from tensorrt_llm.executor.utils import RequestError
from tensorrt_llm.llmapi import DisaggregatedParams as LlmDisaggregatedParams
from tensorrt_llm.llmapi.disagg_utils import get_global_disagg_request_id
from tensorrt_llm.llmapi.llm import SamplingParams
from tensorrt_llm.sampling_params import GuidedDecodingParams
from tensorrt_llm.scheduling_params import SchedulingParams
Expand Down Expand Up @@ -61,6 +60,7 @@
from dynamo.trtllm.utils.disagg_utils import (
DisaggregatedParams,
DisaggregatedParamsCodec,
get_compatible_global_disagg_request_id,
)
from dynamo.trtllm.utils.request_utils import (
apply_stop_conditions_to_sampling_params,
Expand Down Expand Up @@ -728,7 +728,7 @@ def _setup_disaggregated_params_for_mode(
else:
disaggregated_params = LlmDisaggregatedParams(
request_type="context_only",
disagg_request_id=get_global_disagg_request_id(
disagg_request_id=get_compatible_global_disagg_request_id(
self.disagg_machine_id
),
)
Expand All @@ -737,8 +737,8 @@ def _setup_disaggregated_params_for_mode(
# ep_disaggregated_params, so the PYTHON transceiver can track
# requests across prefill/decode workers.
if disaggregated_params.disagg_request_id is None:
disaggregated_params.disagg_request_id = get_global_disagg_request_id(
self.disagg_machine_id
disaggregated_params.disagg_request_id = (
get_compatible_global_disagg_request_id(self.disagg_machine_id)
)

# AGGREGATED (prefill_and_decode) mode with encoder disaggregation:
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

from unittest.mock import patch

import pytest
import torch

# Pytest applies marker selection after importing test modules. Importing
# disagg_utils loads TensorRT-LLM bindings, which require libcuda even though
# these tests do not execute CUDA kernels, so skip collection on CPU runners.
if not torch.cuda.is_available():
pytest.skip(
"CUDA/GPU not available, but tensorrt_llm import requires CUDA.",
allow_module_level=True,
)

from dynamo.trtllm.utils import disagg_utils

pytestmark = [
pytest.mark.unit,
pytest.mark.trtllm,
pytest.mark.core,
pytest.mark.pre_merge,
pytest.mark.gpu_1,
]


def test_rc22_machine_id_is_split_losslessly():
with (
patch.object(disagg_utils, "_TRTLLM_DISAGG_ID_HAS_PROCESS_ID", True),
patch.object(
disagg_utils,
"_trtllm_get_global_disagg_request_id",
return_value=123,
) as generate,
):
result = disagg_utils.get_compatible_global_disagg_request_id(1020)

assert result == 123
generate.assert_called_once_with(15, 60)


def test_rc22_all_dynamo_machine_ids_are_in_range_and_unique():
pairs = {
divmod(machine_id, disagg_utils._TRTLLM_PROCESS_ID_SPACE)
for machine_id in range(disagg_utils._DYNAMO_DISAGG_MACHINE_ID_SPACE)
}

assert len(pairs) == disagg_utils._DYNAMO_DISAGG_MACHINE_ID_SPACE
assert all(
0 <= node_id < disagg_utils._TRTLLM_NODE_ID_SPACE for node_id, _ in pairs
)
assert all(
0 <= process_id < disagg_utils._TRTLLM_PROCESS_ID_SPACE
for _, process_id in pairs
)


def test_rc21_keeps_legacy_machine_id():
with (
patch.object(disagg_utils, "_TRTLLM_DISAGG_ID_HAS_PROCESS_ID", False),
patch.object(
disagg_utils,
"_trtllm_get_global_disagg_request_id",
return_value=456,
) as generate,
):
result = disagg_utils.get_compatible_global_disagg_request_id(1020)

assert result == 456
generate.assert_called_once_with(1020)


@pytest.mark.parametrize("machine_id", [-1, 1021])
def test_invalid_dynamo_machine_id_fails_fast(machine_id):
with pytest.raises(ValueError, match="machine_id must be in range"):
disagg_utils.get_compatible_global_disagg_request_id(machine_id)
46 changes: 46 additions & 0 deletions components/src/dynamo/trtllm/utils/disagg_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,55 @@

import base64
import dataclasses
import inspect

from tensorrt_llm.executor.result import Logprob
from tensorrt_llm.llmapi import DisaggregatedParams
from tensorrt_llm.llmapi.disagg_utils import (
get_global_disagg_request_id as _trtllm_get_global_disagg_request_id,
)

# This compatibility shim intentionally relies on the public helper retaining
# its name while TRT-LLM distinguishes the two known APIs by the ``process_id``
# parameter added in rc22.
# Dynamo maps its distributed-runtime connection ID into TRT-LLM's historical
# 10-bit machine-ID space with ``connection_id % 1021``. TRT-LLM rc22 split
# that field into an 8-bit node ID and a 6-bit process ID. Preserve Dynamo's
# existing 10-bit worker slot and encode it losslessly into the new pair.
_TRTLLM_DISAGG_ID_HAS_PROCESS_ID = (
"process_id" in inspect.signature(_trtllm_get_global_disagg_request_id).parameters
)
_TRTLLM_PROCESS_ID_SPACE = 1 << 6
_TRTLLM_NODE_ID_SPACE = 1 << 8
_DYNAMO_DISAGG_MACHINE_ID_SPACE = 1021


def get_compatible_global_disagg_request_id(machine_id: int) -> int:
"""Generate a global TRT-LLM disaggregation request ID across API versions.

TRT-LLM <= rc21 accepts a 10-bit ``machine_id``. TRT-LLM >= rc22 accepts
an 8-bit ``node_id`` plus a 6-bit ``process_id``. Dynamo's existing
machine ID is in ``[0, 1021)``; splitting that value with ``divmod(64)``
produces a unique, in-range pair without changing Dynamo's collision
characteristics.
"""

if not 0 <= machine_id < _DYNAMO_DISAGG_MACHINE_ID_SPACE:
raise ValueError(
"Dynamo disagg machine_id must be in range "
f"[0, {_DYNAMO_DISAGG_MACHINE_ID_SPACE}), got {machine_id}"
)

if _TRTLLM_DISAGG_ID_HAS_PROCESS_ID:
node_id, process_id = divmod(machine_id, _TRTLLM_PROCESS_ID_SPACE)
if node_id >= _TRTLLM_NODE_ID_SPACE:
raise ValueError(
"Dynamo disagg machine_id maps outside TRT-LLM's 8-bit "
f"node_id space: machine_id={machine_id}, node_id={node_id}"
)
return _trtllm_get_global_disagg_request_id(node_id, process_id)

return _trtllm_get_global_disagg_request_id(machine_id)


class DisaggregatedParamsCodec:
Expand Down
140 changes: 138 additions & 2 deletions lib/llm/src/kv_router/prefill_router/admission.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ use super::{PrefillCompletion, PrefillError, PrefillRouter};
use crate::{
kv_router::KvPushRouter,
protocols::common::{
llm_backend::{LLMEngineOutput, PreprocessedRequest},
llm_backend::{FinishReason, LLMEngineOutput, PreprocessedRequest},
timing::RequestTracker,
},
session_affinity::{AffinityTarget, SessionAffinityPushRouter},
Expand Down Expand Up @@ -110,6 +110,23 @@ impl PrefillRouter {
tokio::spawn(async move { while prefill_response.next().await.is_some() {} });
}

// A CTX request that reaches EOS/stop during its one-token prefill step
// is already complete and does not establish a KV-cache handoff. The
// prefill protocol carries this classification on the first output's
// data; a data-less first output is rejected below. A missing finish
// reason is equivalent to TRT-LLM's "not_finished", while Length still
// requires the normal GEN handoff.
let is_terminal = first_output
.data
.as_ref()
.and_then(|output| output.finish_reason.as_ref())
.is_some_and(|reason| !matches!(reason, FinishReason::Length));
if is_terminal {
return Ok(PrefillCompletion::Terminal {
output: Box::new(first_output),
});
}
Comment thread
krishung5 marked this conversation as resolved.
Resolved

let Some(output) = &first_output.data else {
return Err(PrefillError::NoDisaggregatedParams(
"Prefill router output has no data field".to_string(),
Expand All @@ -120,8 +137,27 @@ impl PrefillRouter {
"Prefill router output missing disaggregated_params".to_string(),
));
};
// TRT-LLM serializes ctx_request_id as null for a terminal context
// response. Terminal responses returned above do not need a handoff;
// any non-terminal response that explicitly carries a null ID cannot
// be decoded safely. Refuse it here instead of dispatching GEN and
// failing later inside the backend. Other backends do not expose this
// TRT-LLM-specific field and are unaffected.
let ctx_request_id = disaggregated_params.get("ctx_request_id");
let is_trtllm_context_handoff = disaggregated_params
.get("request_type")
.and_then(serde_json::Value::as_str)
== Some("context_only");
if ctx_request_id.is_some_and(serde_json::Value::is_null)
|| (is_trtllm_context_handoff && ctx_request_id.is_none())
{
return Err(PrefillError::NoDisaggregatedParams(
"Prefill router output has no usable ctx_request_id for a non-terminal handoff"
.to_string(),
));
}

Ok(PrefillCompletion {
Ok(PrefillCompletion::Handoff {
result: crate::protocols::common::preprocessor::PrefillResult {
disaggregated_params,
prompt_tokens_details,
Expand Down Expand Up @@ -203,4 +239,104 @@ mod tests {
assert!(result.is_err());
assert!(!tracker.record_prefill_complete());
}

#[tokio::test]
async fn terminal_finish_reasons_without_handoff_are_returned_to_caller() {
for finish_reason in [
FinishReason::EoS,
FinishReason::Stop,
FinishReason::Cancelled,
FinishReason::Error("prefill failed".to_string()),
FinishReason::ContentFilter,
] {
let output = LLMEngineOutput {
token_ids: vec![2],
finish_reason: Some(finish_reason.clone()),
..Default::default()
};
let result = PrefillRouter::consume_prefill_stream(
prefill_stream(vec![Annotated::from_data(output)]),
None,
)
.await
.unwrap();

let PrefillCompletion::Terminal { output } = result else {
panic!("expected terminal prefill completion for {finish_reason:?}");
};
let output = *output;
assert_eq!(
output.data.and_then(|data| data.finish_reason),
Some(finish_reason)
);
}
}

#[tokio::test]
async fn length_limited_prefill_still_requires_handoff() {
let output = LLMEngineOutput {
finish_reason: Some(FinishReason::Length),
disaggregated_params: Some(json!({"ctx_request_id": 42})),
..Default::default()
};
let result = PrefillRouter::consume_prefill_stream(
prefill_stream(vec![Annotated::from_data(output)]),
None,
)
.await
.unwrap();

let PrefillCompletion::Handoff { result, .. } = result else {
panic!("expected prefill handoff");
};
assert_eq!(result.disaggregated_params, json!({"ctx_request_id": 42}));
}

#[tokio::test]
async fn unfinished_prefill_still_requires_handoff() {
let output = LLMEngineOutput {
finish_reason: None,
disaggregated_params: Some(json!({"ctx_request_id": 42})),
..Default::default()
};
let result = PrefillRouter::consume_prefill_stream(
prefill_stream(vec![Annotated::from_data(output)]),
None,
)
.await
.unwrap();

let PrefillCompletion::Handoff { result, .. } = result else {
panic!("expected prefill handoff");
};
assert_eq!(result.disaggregated_params, json!({"ctx_request_id": 42}));
}

#[tokio::test]
async fn non_terminal_prefill_without_usable_ctx_request_id_fails_before_decode() {
for disaggregated_params in [
json!({"ctx_request_id": null}),
json!({"request_type": "context_only"}),
] {
let output = LLMEngineOutput {
finish_reason: None,
disaggregated_params: Some(disaggregated_params),
..Default::default()
};
let result = PrefillRouter::consume_prefill_stream(
prefill_stream(vec![Annotated::from_data(output)]),
None,
)
.await;
let Err(error) = result else {
panic!("expected a missing ctx_request_id to reject the handoff");
};

assert!(matches!(
error,
PrefillError::NoDisaggregatedParams(message)
if message.contains("no usable ctx_request_id")
));
}
}
}
Loading
Loading