Skip to content

Commit ed6663c

Browse files
committed
[TRTLLM-17268][test] Pin gpt-oss chat parity with chat_harmony and the new serving-extension hooks
tests/unittest/serve/extensions/test_gpt_oss_chat_path.py builds gpt-oss servers through the real constructor and sends the same request bodies through openai_chat and the legacy chat_harmony handler (mounted on a second route for the comparison): every rejection answers with the same status and body (the pairs include the two features checked before rendering), the engine receives the same harmony prompt token ids and sampling parameters for non-streaming and streaming requests, a null stream field reaches the engine as streaming=False on both paths, the structured-output constraint sits on the final channel, and only the listed capabilities differ (cache_salt, the preprocess hook, prompt_token_ids_b64 from any client, the engine-failure answer, the type of unexpected and over-length errors). The switch, /health_generate on both paths, DISABLE_HARMONY_ADAPTER=1, the startup check, the hook guard and the CLI wiring of the gpt_oss alias (reaches launch_server as parser_aliases, never the parser arguments; rejected with --grpc) are pinned too. The serving-extension tests cover the defaults of the two new hooks, the gpt-oss declarations, the CLI alias registry and the generic chat path; the router test compares the KV-aware router's harmony tokens with what the default handler sends; the disaggregated placement test gains a gpt-oss worker built through the real constructor; the post-processor-hook guard test passes the output mode. Signed-off-by: JunyiXu-nv <219237550+JunyiXu-nv@users.noreply.github.com>
1 parent 0a3c243 commit ed6663c

6 files changed

Lines changed: 1247 additions & 31 deletions

File tree

‎tests/unittest/disaggregated/test_openai_disagg_service.py‎

Lines changed: 53 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -27,8 +27,10 @@
2727
import torch
2828
from aiohttp import web
2929
from aiohttp.test_utils import TestServer
30+
from llmapi.apps.render_helpers import use_harmony_vocab
3031
from openai.types.responses import ResponseErrorEvent, ResponseFailedEvent, ResponseStatus
3132
from starlette.requests import Request
33+
from test_common.serve.app_factory import AggConfig, isolated_serve_env
3234

3335
from tensorrt_llm._torch.pyexecutor.scheduler.adp_router import (
3436
ConversationAwareADPRouter,
@@ -509,11 +511,15 @@ async def generation_response(*args, **kwargs):
509511
@pytest.mark.asyncio
510512
@pytest.mark.parametrize("schedule_style", ["context_first", "generation_first"])
511513
@pytest.mark.parametrize("scope", ["context", "both"])
512-
@pytest.mark.parametrize("handler_name", ["openai_chat", "chat_harmony"])
514+
# threadleak is off: the gpt-oss workers are built through the real constructor,
515+
# whose input-processor pool is shut down without waiting at environment exit.
516+
@pytest.mark.threadleak(enabled=False)
517+
@pytest.mark.parametrize("handler_name", ["openai_chat", "chat_harmony", "openai_chat_gpt_oss"])
513518
@pytest.mark.parametrize("affinity_enabled", [False, True])
514519
@pytest.mark.parametrize("configured_role", [False, True])
515520
async def test_subagent_affinity_http_worker_adp_placement(
516521
monkeypatch: pytest.MonkeyPatch,
522+
tmp_path,
517523
schedule_style: str,
518524
scope: str,
519525
handler_name: str,
@@ -524,8 +530,14 @@ async def test_subagent_affinity_http_worker_adp_placement(
524530
525531
Only model execution/tokenization and response postprocessing are stubbed;
526532
the service, HTTP client, worker chat handler and ADP router execute normally.
527-
Rank states are deterministic CPU fixtures, not a GPU execution test.
533+
Rank states are deterministic CPU fixtures, not a GPU execution test. The
534+
``openai_chat_gpt_oss`` case runs the default handler of a gpt-oss worker
535+
built through the real constructor, with the harmony hooks on.
528536
"""
537+
gpt_oss_worker = handler_name == "openai_chat_gpt_oss"
538+
if gpt_oss_worker:
539+
use_harmony_vocab(monkeypatch)
540+
gpt_oss_env = None
529541
monkeypatch.delenv("TRTLLM_DISAGG_BENCHMARK_GEN_ONLY", raising=False)
530542
monkeypatch.setattr("tensorrt_llm.serve.openai_client.ClientMetricsCollector", mock.Mock())
531543

@@ -569,36 +581,48 @@ def generate(**kwargs):
569581
)
570582
return SimpleNamespace(prompt_token_ids=[1, 2, 3])
571583

572-
server = object.__new__(OpenAIServer)
573-
server.server_role = role if configured_role else None
574-
server._internal_disagg_auth_key = auth_key
575-
server.allow_request_chat_template = False
576-
server.generator = SimpleNamespace(
577-
args=SimpleNamespace(
578-
num_postprocess_workers=0,
579-
gather_generation_logits=False,
580-
reasoning_parser=None,
581-
backend="pytorch",
582-
cache_transceiver_config={"backend": "UCX"},
583-
),
584-
generate_async=generate,
585-
)
586-
server.model_config = SimpleNamespace(model_type="llama", vocab_size=1000)
587-
server.tokenizer = SimpleNamespace(tokenizer=SimpleNamespace(vocab_size=1000))
588-
server.multimodal_server_config = None
589-
server.tool_parser = None
590-
server.tool_call_id_type = "random"
591-
server.chat_template = None
592-
server.harmony_adapter = mock.Mock()
593-
server.harmony_adapter.get_stop_tokens.return_value = [999]
594-
server.await_disconnected = AsyncMock()
595-
596584
async def postprocess(promise, postproc_params, raw_request, disaggregated_params):
597585
return _make_chat_response(
598586
"length" if role == ServerRole.CONTEXT else "stop",
599587
disagg_request_id=disaggregated_params.disagg_request_id,
600588
)
601589

590+
if gpt_oss_worker:
591+
# The real constructor on a fake gpt-oss checkpoint: use_harmony and
592+
# the gpt-oss hooks come from _init_llm. Only what the hand-built
593+
# workers below set is overridden.
594+
server = gpt_oss_env.build_openai_server(
595+
AggConfig(model_type="gpt_oss", role=role if configured_role else None)
596+
)
597+
server._internal_disagg_auth_key = auth_key
598+
server.generator.args.cache_transceiver_config = {"backend": "UCX"}
599+
server.generator.generate_async = generate
600+
handler = server.openai_chat
601+
else:
602+
server = object.__new__(OpenAIServer)
603+
server.server_role = role if configured_role else None
604+
server._internal_disagg_auth_key = auth_key
605+
server.allow_request_chat_template = False
606+
server.generator = SimpleNamespace(
607+
args=SimpleNamespace(
608+
num_postprocess_workers=0,
609+
gather_generation_logits=False,
610+
reasoning_parser=None,
611+
backend="pytorch",
612+
cache_transceiver_config={"backend": "UCX"},
613+
),
614+
generate_async=generate,
615+
)
616+
server.model_config = SimpleNamespace(model_type="llama", vocab_size=1000)
617+
server.tokenizer = SimpleNamespace(tokenizer=SimpleNamespace(vocab_size=1000))
618+
server.multimodal_server_config = None
619+
server.tool_parser = None
620+
server.tool_call_id_type = "random"
621+
server.chat_template = None
622+
server.harmony_adapter = mock.Mock()
623+
server.harmony_adapter.get_stop_tokens.return_value = [999]
624+
handler = getattr(server, handler_name)
625+
server.await_disconnected = AsyncMock()
602626
server._create_chat_response = postprocess
603627

604628
async def handle(http_request: web.Request) -> web.Response:
@@ -610,7 +634,7 @@ async def handle(http_request: web.Request) -> web.Response:
610634
== DisaggScheduleStyle[schedule_style.upper()]
611635
)
612636
raw_request = Request({"type": "http", "headers": http_request.raw_headers})
613-
response = await getattr(server, handler_name)(request, raw_request)
637+
response = await handler(request, raw_request)
614638
return web.Response(
615639
body=response.body, status=response.status_code, content_type="application/json"
616640
)
@@ -620,6 +644,8 @@ async def handle(http_request: web.Request) -> web.Response:
620644
return app
621645

622646
async with AsyncExitStack() as stack:
647+
if gpt_oss_worker:
648+
gpt_oss_env = stack.enter_context(isolated_serve_env(tmp_path))
623649
session = await stack.enter_async_context(aiohttp.ClientSession())
624650
for role, instance_router, client_attr in (
625651
(ServerRole.CONTEXT, service._ctx_router, "_ctx_client"),

‎tests/unittest/disaggregated/test_router.py‎

Lines changed: 124 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
import asyncio
55
import base64
66
import copy
7+
import json
78
import os
89
import random
910
import threading
@@ -2667,6 +2668,129 @@ def model_dump(self) -> dict[str, object]:
26672668
message=str(original_error), err_type="internal_error")
26682669

26692670

2671+
@pytest.mark.threadleak(enabled=False)
2672+
def test_gpt_oss_router_tokens_match_openai_chat_server_input(
2673+
monkeypatch: pytest.MonkeyPatch, tmp_path) -> None:
2674+
"""KV-cache routing must hash the same Harmony tokens the default handler uses."""
2675+
use_harmony_vocab(monkeypatch)
2676+
from test_common.serve.app_factory import AggConfig, isolated_serve_env
2677+
2678+
from tensorrt_llm.serve.chat_tokenization import \
2679+
tokenize_harmony_chat_request
2680+
2681+
router = KvCacheAwareRouter(server_role=None,
2682+
servers=["server1"],
2683+
use_tokens=False,
2684+
max_batch_size=32,
2685+
tokens_per_block=32,
2686+
model_path="/models/gpt-oss-checkpoint")
2687+
router_tokenizer = _mock_tokenizer(token_ids=[900, 901, 902])
2688+
body = {
2689+
"model":
2690+
"fake-model",
2691+
"messages": [{
2692+
"role": "developer",
2693+
"content": "Use tools when useful."
2694+
}, {
2695+
"role": "user",
2696+
"content": "weather in Paris?"
2697+
}],
2698+
"tools": [_get_weather_tool().model_dump()],
2699+
"tool_choice":
2700+
"auto",
2701+
"reasoning_effort":
2702+
"medium",
2703+
"max_completion_tokens":
2704+
1,
2705+
}
2706+
harmony_tokens = tokenize_harmony_chat_request(
2707+
ChatCompletionRequest(**body))
2708+
2709+
with mock.patch.object(router,
2710+
"_get_tokenizer",
2711+
return_value=router_tokenizer), mock.patch(
2712+
"tensorrt_llm.serve.router_utils."
2713+
"resolve_model_type_from_config",
2714+
return_value="gpt_oss"):
2715+
router._server_info = {
2716+
"server1": {
2717+
"render_fingerprint":
2718+
router._render_resources("fake-model").fingerprint()
2719+
}
2720+
}
2721+
router_request = ChatCompletionRequest(**body)
2722+
router_token_ids = router._tokenize(router_request)[0]
2723+
2724+
with isolated_serve_env(tmp_path) as env:
2725+
server = env.build_openai_server(AggConfig(model_type="gpt_oss"))
2726+
client = env.client(server.app)
2727+
response = client.post("/v1/chat/completions", json=body)
2728+
assert response.status_code == 200, response.text
2729+
# The handler runs the engine's preprocess on the prompt; the ids are
2730+
# what preprocess received.
2731+
server_token_ids = list(
2732+
server.generator.preprocess_calls[0].inputs["prompt_token_ids"])
2733+
2734+
assert router_token_ids == server_token_ids
2735+
assert router_request.prompt_token_ids == harmony_tokens
2736+
assert server_token_ids == harmony_tokens
2737+
router_tokenizer.apply_chat_template.assert_not_called()
2738+
2739+
2740+
@pytest.mark.threadleak(enabled=False)
2741+
def test_openai_chat_preserves_original_tool_conversion_error_for_gpt_oss(
2742+
tmp_path) -> None:
2743+
"""The first tool dump that fails is the answer; nothing re-runs it."""
2744+
from test_common.serve.app_factory import AggConfig, isolated_serve_env
2745+
2746+
original_error = RuntimeError("original tool conversion failure")
2747+
2748+
class FailingTool:
2749+
2750+
def __init__(self) -> None:
2751+
self.calls = 0
2752+
2753+
def model_dump(self, *args, **kwargs) -> dict[str, object]:
2754+
self.calls += 1
2755+
raise original_error if self.calls == 1 else RuntimeError(
2756+
"diagnostic tool conversion failure")
2757+
2758+
failing_tool = FailingTool()
2759+
request = ChatCompletionRequest(
2760+
model="fake-model",
2761+
messages=[{
2762+
"role": "user",
2763+
"content": "weather in Paris?"
2764+
}],
2765+
)
2766+
object.__setattr__(request, "tools", [failing_tool])
2767+
2768+
with isolated_serve_env(tmp_path) as env:
2769+
server = env.build_openai_server(AggConfig(model_type="gpt_oss"))
2770+
response = asyncio.run(
2771+
server.openai_chat(request, _synthetic_chat_request()))
2772+
2773+
body = json.loads(response.body)
2774+
assert (response.status_code, body["type"],
2775+
body["message"]) == (400, "BadRequestError", str(original_error))
2776+
assert failing_tool.calls == 1
2777+
2778+
2779+
def _synthetic_chat_request():
2780+
"""A Request for an in-process handler call: no client connection behind it."""
2781+
from starlette.requests import Request
2782+
2783+
return Request({
2784+
"type": "http",
2785+
"method": "POST",
2786+
"path": "/v1/chat/completions",
2787+
"headers": [],
2788+
"state": {
2789+
"no_client_connection": True
2790+
},
2791+
})
2792+
2793+
26702794
@pytest.mark.parametrize("router_class",
26712795
[KvCacheAwareRouter, ConversationRouter])
26722796
def test_tokenize_forwards_tools_and_chat_template_kwargs(router_class):

‎tests/unittest/executor/test_postprocessor_hook.py‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -310,11 +310,12 @@ def test_harmony_model_rejects_post_processor_hook():
310310
text-based hook, so the server refuses the combination at startup.
311311
"""
312312
from tensorrt_llm.serve.openai_server import OpenAIServer
313+
from tensorrt_llm.serve.serving_extensions import OutputMode
313314

314315
guard = OpenAIServer._ensure_post_processor_hook_supported
315316
with pytest.raises(ValueError, match="not supported with harmony"):
316-
guard(use_harmony=True, post_processor_hook="my_pkg.guardrail.Hook")
317+
guard(OutputMode.HARMONY_TOKENS, post_processor_hook="my_pkg.guardrail.Hook")
317318
# Every other combination is allowed.
318-
guard(use_harmony=False, post_processor_hook="my_pkg.guardrail.Hook")
319-
guard(use_harmony=True, post_processor_hook=None)
320-
guard(use_harmony=False, post_processor_hook=None)
319+
guard(OutputMode.TEXT, post_processor_hook="my_pkg.guardrail.Hook")
320+
guard(OutputMode.HARMONY_TOKENS, post_processor_hook=None)
321+
guard(OutputMode.TEXT, post_processor_hook=None)

0 commit comments

Comments
 (0)