diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index ee619f1a9a52..0452e36a3fea 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -371,6 +371,7 @@ /cpp/tensorrt_llm/thop/*lysses* @NVIDIA/trt-llm-torch-visual-gen-devs /cpp/tensorrt_llm/kernels/ulysses* @NVIDIA/trt-llm-torch-visual-gen-devs /tensorrt_llm/media @NVIDIA/trt-llm-torch-visual-gen-devs +/tensorrt_llm/serve/api/visual_gen @NVIDIA/trt-llm-torch-visual-gen-devs /tensorrt_llm/visual_gen @NVIDIA/trt-llm-torch-visual-gen-devs @NVIDIA/trt-llm-runtime-devs /tests/integration/defs/examples/visual_gen @NVIDIA/trt-llm-torch-visual-gen-devs /tests/integration/defs/visual_gen @NVIDIA/trt-llm-torch-visual-gen-devs diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index c2166e7bb04b..cc5ed6b59e1d 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -417,6 +417,12 @@ common-files: &common_files | tensorrt_llm/scaffolding/worker.py | tensorrt_llm/scheduling_params.py | tensorrt_llm/serve/__init__.py | + tensorrt_llm/serve/_base/msgspec_route.py | + tensorrt_llm/serve/_base/serving.py | + tensorrt_llm/serve/api/visual_gen/media.py | + tensorrt_llm/serve/api/visual_gen/protocol.py | + tensorrt_llm/serve/api/visual_gen/serving_base.py | + tensorrt_llm/serve/api/visual_gen/serving_images.py | tensorrt_llm/serve/chat_utils.py | tensorrt_llm/serve/cluster_storage.py | tensorrt_llm/serve/disagg_auto_scaling.py | @@ -1144,6 +1150,12 @@ legacy-files: &legacy_files | tensorrt_llm/scaffolding/worker.py | tensorrt_llm/scheduling_params.py | tensorrt_llm/serve/__init__.py | + tensorrt_llm/serve/_base/msgspec_route.py | + tensorrt_llm/serve/_base/serving.py | + tensorrt_llm/serve/api/visual_gen/media.py | + tensorrt_llm/serve/api/visual_gen/protocol.py | + tensorrt_llm/serve/api/visual_gen/serving_base.py | + tensorrt_llm/serve/api/visual_gen/serving_images.py | tensorrt_llm/serve/chat_utils.py | tensorrt_llm/serve/cluster_storage.py | tensorrt_llm/serve/disagg_auto_scaling.py | @@ -1620,6 +1632,7 @@ repos: # Run mypy with no explicit paths so it type-checks the set declared in # pyproject.toml [tool.mypy] `files` (single source of truth). This # `files:` pattern only decides when the hook triggers — any change under - # the sampler source/test dirs. + # the sampler source/test dirs or the serving frontends. A PR that adds + # a typed module elsewhere extends this pattern in the same PR. pass_filenames: false - files: ^(tensorrt_llm/_torch/pyexecutor/sampler/|tests/unittest/_torch/sampler/) + files: ^(tensorrt_llm/_torch/pyexecutor/sampler/|tests/unittest/_torch/sampler/|tensorrt_llm/serve/|tensorrt_llm/commands/serve_cli/) diff --git a/jenkins/L0_MergeRequest.groovy b/jenkins/L0_MergeRequest.groovy index fed051af26b2..541ec1cb7626 100644 --- a/jenkins/L0_MergeRequest.groovy +++ b/jenkins/L0_MergeRequest.groovy @@ -1948,6 +1948,10 @@ def getMultiGpuFileChanged(pipeline, testFilter, globalVars) "tensorrt_llm/models/llama/", "tensorrt_llm/parameter.py", "tensorrt_llm/serve/__init__.py", + // _MsgspecRoute decodes the disaggregated frontend's msgpack bodies. + "tensorrt_llm/serve/_base/", + // /health is the disaggregated readiness probe. + "tensorrt_llm/serve/api/ops/", "tensorrt_llm/serve/cluster_storage.py", "tensorrt_llm/serve/disagg_auto_scaling.py", "tensorrt_llm/serve/extensions/", diff --git a/jenkins/scripts/cbts/README.md b/jenkins/scripts/cbts/README.md index 36101ef18186..ad5952118f8e 100644 --- a/jenkins/scripts/cbts/README.md +++ b/jenkins/scripts/cbts/README.md @@ -41,14 +41,15 @@ filter chain. ## Rules -Nine rules, registered in `cbts/command/main.py::RULE_CLASSES`: +Eleven rules, registered in `cbts/command/main.py::RULE_CLASSES`: | Rule | Scope | Files | |---|---|---| +| `PythonFormattingRule` | `noop` | Python files whose patch is a verified pure reformat: identical complete ASTs (docstrings and type comments included) and unchanged comments | | `WaivesRule` | `waiveonly` | `tests/integration/test_lists/waives.txt` | | `TestsDefRule` | `testdefonly` | `tests/**/*` (.py via AST; data files via dir walk-up) | | `TestListRule` | `testlistonly` | `tests/integration/test_lists/test-db/*.yml` | -| `VisualGenRule` | `visualgenonly` | VG source and the exact VG serve schema; public VG/media changes also keep full CPU and shared serving tests, package sanity, and performance sanity; missing required validation forces fallback | +| `VisualGenRule` | `visualgenonly` | VG source (`examples/visual_gen/**`, `scripts/visualgen_eval/**`, `tensorrt_llm/_torch/visual_gen/**`, `tensorrt_llm/media/**`, `tensorrt_llm/serve/api/visual_gen/**`, `tensorrt_llm/visual_gen/**`; excl. docs) and the exact VG serve schema; public VG/media changes also keep full CPU and shared serving tests, package sanity, and performance sanity; missing required validation forces fallback | | `SpecDecRule` | `specdeconly` | `tensorrt_llm/_torch/speculative/**`, `tensorrt_llm/models/{eagle,medusa,redrafter}/**`, `examples/{eagle,medusa,redrafter,draft_target_model,ngram}/**`, `examples/llm-api/llm_speculative_decoding.py` (excl. docs; other suffixes incl. images kept as potential test fixtures) | | `ModelingV2Rule` | `modelingv2only` | `tensorrt_llm/_torch/_experimental/modeling_v2/**`, `cpp/tensorrt_llm/modeling_v2/**`, `cpp/cmake/modules/modeling_v2.cmake` (excl. docs); per model node for changes under `models/` | | `AgentFlowRule` | `agentflowonly` | `agent-flow/**` (excl. docs and out-of-scope metadata) | @@ -65,7 +66,7 @@ See `cbts/rules/README.md` for per-rule logic. | `waiveonly` | `WaivesRule` fired solo: PR only edits `waives.txt`. | | `testdefonly` | `TestsDefRule` fired solo: PR only edits files under `tests/**/*`. | | `testlistonly` | `TestListRule` fired solo: PR only adds entries under `tests/integration/test_lists/test-db/*.yml`. | -| `visualgenonly` | `VisualGenRule` fired solo. Internal VG changes select VG test entries; schema changes also retain schema validation. Public VG/media changes additionally retain the complete CPU suite, shared serving integration tests, package sanity, and performance sanity. Missing required validation forces `null` fallback. | +| `visualgenonly` | `VisualGenRule` fired solo. Internal VG changes (`examples/visual_gen/**`, `scripts/visualgen_eval/**`, `tensorrt_llm/_torch/visual_gen/**`, `tensorrt_llm/serve/api/visual_gen/**`) select VG test entries; schema changes also retain schema validation. Public VG/media changes additionally retain the complete CPU suite, shared serving integration tests, package sanity, and performance sanity. Missing required validation forces `null` fallback. The serving package counts as internal because nothing outside it imports it (`tests/unittest/llmapi/apps/visual_gen/test_serve_visual_gen_isolation.py`). | | `specdeconly` | `SpecDecRule` fired solo: PR only touches speculative-decoding source paths (`tensorrt_llm/_torch/speculative/**`, `tensorrt_llm/models/{eagle,medusa,redrafter}/**`, `examples/{eagle,medusa,redrafter,draft_target_model,ngram}/**`, `examples/llm-api/llm_speculative_decoding.py`; excl. docs). Narrows to blocks containing spec-dec test entries (eagle / medusa / redrafter / ngram / draft-target-model / MTP). | | `modelingv2only` | `ModelingV2Rule` fired solo: PR only touches modeling_v2 code -- the subtree (`tensorrt_llm/_torch/_experimental/modeling_v2/**`, each family's native code in its `csrc/` included: one torch-op library per model family) or what the family libraries share (`cpp/tensorrt_llm/modeling_v2/**`, `cpp/cmake/modules/modeling_v2.cmake`); excl. docs, which are a fifth of the Python subtree — every catalog entry carries a contract document. A change under `models/` selects its model node's unit tests and target accuracy gates, plus whole-tree checks; shared code or an unreadable routing tree selects every modeling_v2 entry. No outward-facing fallback is needed: nothing beyond the resolver module is imported, and no family library is loaded, unless `LLM(modeling_v2=...)` is on; the CPU checks that keep this true run in every scope. The callers outside the subtree (`_torch/pyexecutor/model_loader.py`, `_torch/models/modeling_auto.py`) are left unclaimed, so touching them falls back to baseline. | | `agentflowonly` | `AgentFlowRule` fired solo: PR only touches `agent-flow/**` source or test files (excl. docs). Runs `CPU-AgentFlow-UnitTest`. | diff --git a/jenkins/scripts/cbts/cbts/rules/README.md b/jenkins/scripts/cbts/cbts/rules/README.md index e24659f25102..548ce1ba4022 100644 --- a/jenkins/scripts/cbts/cbts/rules/README.md +++ b/jenkins/scripts/cbts/cbts/rules/README.md @@ -15,7 +15,7 @@ for the overall CBTS architecture. | `waives.py` | `WaivesRule` | `waiveonly` | `tests/integration/test_lists/waives.txt` | | `tests_def.py` | `TestsDefRule` | `testdefonly` | `tests/**/*` (any file under tests/) | | `test_list.py` | `TestListRule` | `testlistonly` | `tests/integration/test_lists/test-db/*.yml` | -| `visual_gen.py` | `VisualGenRule` | `visualgenonly` | `examples/visual_gen/**`, `scripts/visualgen_eval/**`, `tensorrt_llm/_torch/visual_gen/**`, `tensorrt_llm/media/**`, `tensorrt_llm/visual_gen/**` (each excl. docs), and the exact VisualGen serve schema | +| `visual_gen.py` | `VisualGenRule` | `visualgenonly` | `examples/visual_gen/**`, `scripts/visualgen_eval/**`, `tensorrt_llm/_torch/visual_gen/**`, `tensorrt_llm/media/**`, `tensorrt_llm/serve/api/visual_gen/**`, `tensorrt_llm/visual_gen/**` (each excl. docs), and the exact VisualGen serve schema | | `spec_dec.py` | `SpecDecRule` | `specdeconly` | `tensorrt_llm/_torch/speculative/**`, `tensorrt_llm/models/{eagle,medusa,redrafter}/**`, `examples/{eagle,medusa,redrafter,draft_target_model,ngram}/**`, `examples/llm-api/llm_speculative_decoding.py` (each excl. docs) | | `modeling_v2.py` | `ModelingV2Rule` | `modelingv2only` | `tensorrt_llm/_torch/_experimental/modeling_v2/**`, `cpp/tensorrt_llm/modeling_v2/**`, `cpp/cmake/modules/modeling_v2.cmake` (excl. docs); per model node for changes under `models/` | | `agent_flow.py` | `AgentFlowRule` | `agentflowonly` | `agent-flow/**` (excl. docs and out-of-scope metadata) → the single `CPU-AgentFlow-UnitTest` stage; not test-db-driven | @@ -217,7 +217,8 @@ Outcomes: Path-only rule. Claims source files under `examples/visual_gen/`, `scripts/visualgen_eval/`, `tensorrt_llm/_torch/visual_gen/`, -`tensorrt_llm/media/`, and `tensorrt_llm/visual_gen/` (excluding documentation, +`tensorrt_llm/media/`, `tensorrt_llm/serve/api/visual_gen/`, and +`tensorrt_llm/visual_gen/` (excluding documentation, which `DocsRule` handles). It also claims the exact generated schema `tensorrt_llm/schemas/trtllm-serve-visual-gen-config.schema.json`. Fused-DiT paths stay unclaimed: @@ -258,11 +259,23 @@ pre-merge multi-GPU stages cannot satisfy this requirement. Missing or filtered required validation keeps `scope=None`. Public changes therefore get a wider test set than internal VG changes without requiring all unrelated GPU tests. +Internal serving package: `tensorrt_llm/serve/api/visual_gen/`, the VisualGen +HTTP serving package, is internal rather than shared. No module outside it +imports it except the trtllm-serve composition root for the VISUAL_GEN role, +the routing table's module-path string, the lazy re-export in +`tensorrt_llm.serve.openai_protocol` and the VisualGen benchmark client, so a +change under it narrows like the other internal paths. +`tests/unittest/llmapi/apps/visual_gen/test_serve_visual_gen_isolation.py` +asserts this (the static import graph, a runtime check per serving role and +CLI entry point, and the placement of VisualGen tests under `visual_gen/` +paths); if it fails, the prefix can no longer be treated as internal. + Outcomes: - No VG source files in the diff → rule returns `None`. - VG source touched, all internal (`examples/visual_gen/**`, - `scripts/visualgen_eval/**`, or `tensorrt_llm/_torch/visual_gen/**`) + `scripts/visualgen_eval/**`, `tensorrt_llm/_torch/visual_gen/**`, or + `tensorrt_llm/serve/api/visual_gen/**`) → `scope=visualgenonly`; sanity off (VG changes don't affect wheel sanity); perfsanity on iff a matched block lives in `l0_perf` or `*perf_sanity*`. diff --git a/jenkins/scripts/cbts/cbts/rules/visual_gen.py b/jenkins/scripts/cbts/cbts/rules/visual_gen.py index 22af6b89859b..ba114f53ad8e 100644 --- a/jenkins/scripts/cbts/cbts/rules/visual_gen.py +++ b/jenkins/scripts/cbts/cbts/rules/visual_gen.py @@ -15,8 +15,9 @@ VisualGen is a self-contained subsystem under `tensorrt_llm/_torch/visual_gen/` (Flux / LTX-2 / Wan diffusion models) -plus the public API surface at `tensorrt_llm/visual_gen/` and the media -helpers at `tensorrt_llm/media/`. +plus the public API surface at `tensorrt_llm/visual_gen/`, the media +helpers at `tensorrt_llm/media/` and the HTTP serving package at +`tensorrt_llm/serve/api/visual_gen/`. Block selection — entry-pattern based only: VisualGen does NOT have its own `condition.terms.backend`; VG test @@ -29,6 +30,15 @@ Their changes keep the complete CPU suite, shared serving integration tests, and package/performance sanity checks in addition to VG entries. Missing API, schema, lazy-import, or serving validation keeps the baseline fallback. + +Internal serving package: +`tensorrt_llm/serve/api/visual_gen/` is internal, not shared: no module +outside it imports it except the trtllm-serve composition root for the +VISUAL_GEN role, the routing table's module-path string, the lazy +re-export in `tensorrt_llm.serve.openai_protocol` and the VisualGen +benchmark client, so a change under it narrows like the other internal +VG paths. `tests/unittest/llmapi/apps/visual_gen/test_serve_visual_gen_isolation.py` +asserts this; if it fails, claiming this prefix is no longer safe. """ from __future__ import annotations @@ -57,6 +67,7 @@ "scripts/visualgen_eval/", "tensorrt_llm/_torch/visual_gen/", "tensorrt_llm/media/", + "tensorrt_llm/serve/api/visual_gen/", "tensorrt_llm/visual_gen/", ) @@ -64,6 +75,8 @@ _SCHEMA_TEST_TARGET = "unittest/llmapi/test_trtllm_serve_config_schemas.py" # These packages expose shared protocol and media dependencies to serving. +# `tensorrt_llm/serve/api/visual_gen/` is not listed: it is internal (see the +# module docstring). _VG_OUTWARD_PREFIXES: tuple[str, ...] = ( "tensorrt_llm/media/", "tensorrt_llm/visual_gen/", diff --git a/legacy-files.txt b/legacy-files.txt index 9850e7c810b4..1c47500e9708 100644 --- a/legacy-files.txt +++ b/legacy-files.txt @@ -409,6 +409,12 @@ tensorrt_llm/scaffolding/task_collection.py tensorrt_llm/scaffolding/worker.py tensorrt_llm/scheduling_params.py tensorrt_llm/serve/__init__.py +tensorrt_llm/serve/_base/msgspec_route.py +tensorrt_llm/serve/_base/serving.py +tensorrt_llm/serve/api/visual_gen/media.py +tensorrt_llm/serve/api/visual_gen/protocol.py +tensorrt_llm/serve/api/visual_gen/serving_base.py +tensorrt_llm/serve/api/visual_gen/serving_images.py tensorrt_llm/serve/chat_utils.py tensorrt_llm/serve/cluster_storage.py tensorrt_llm/serve/disagg_auto_scaling.py diff --git a/pyproject.toml b/pyproject.toml index 60e243d984b0..d308848f2590 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -474,6 +474,12 @@ exclude = [ "tensorrt_llm/scaffolding/worker.py", "tensorrt_llm/scheduling_params.py", "tensorrt_llm/serve/__init__.py", + "tensorrt_llm/serve/_base/msgspec_route.py", + "tensorrt_llm/serve/_base/serving.py", + "tensorrt_llm/serve/api/visual_gen/media.py", + "tensorrt_llm/serve/api/visual_gen/protocol.py", + "tensorrt_llm/serve/api/visual_gen/serving_base.py", + "tensorrt_llm/serve/api/visual_gen/serving_images.py", "tensorrt_llm/serve/chat_utils.py", "tensorrt_llm/serve/cluster_storage.py", "tensorrt_llm/serve/disagg_auto_scaling.py", @@ -862,6 +868,11 @@ files = [ "tensorrt_llm/_torch/pyexecutor/sampler/token_ban.py", "tensorrt_llm/_torch/pyexecutor/sampler/ops/flashinfer.py", "tensorrt_llm/_torch/pyexecutor/sampler/ops/vanilla.py", + "tensorrt_llm/serve/_base/routing.py", + "tensorrt_llm/serve/api/ops/system/api_router.py", + "tensorrt_llm/serve/api/ops/system/serving.py", + "tensorrt_llm/serve/api/visual_gen/api_router.py", + "tensorrt_llm/serve/api/visual_gen/errors.py", "tests/unittest/_torch/sampler/test_torch_sampler.py", "tests/unittest/_torch/sampler/test_token_ban.py", "tests/unittest/_torch/sampler/test_beam_search.py", diff --git a/ruff-legacy.toml b/ruff-legacy.toml index dab55b4d0434..9740f210aa0e 100644 --- a/ruff-legacy.toml +++ b/ruff-legacy.toml @@ -426,6 +426,12 @@ include = [ "tensorrt_llm/scaffolding/worker.py", "tensorrt_llm/scheduling_params.py", "tensorrt_llm/serve/__init__.py", + "tensorrt_llm/serve/_base/msgspec_route.py", + "tensorrt_llm/serve/_base/serving.py", + "tensorrt_llm/serve/api/visual_gen/media.py", + "tensorrt_llm/serve/api/visual_gen/protocol.py", + "tensorrt_llm/serve/api/visual_gen/serving_base.py", + "tensorrt_llm/serve/api/visual_gen/serving_images.py", "tensorrt_llm/serve/chat_utils.py", "tensorrt_llm/serve/cluster_storage.py", "tensorrt_llm/serve/disagg_auto_scaling.py", diff --git a/tensorrt_llm/bench/benchmark/visual_gen.py b/tensorrt_llm/bench/benchmark/visual_gen.py index bc29527ad865..80e221e4f9a0 100644 --- a/tensorrt_llm/bench/benchmark/visual_gen.py +++ b/tensorrt_llm/bench/benchmark/visual_gen.py @@ -336,9 +336,10 @@ def _run_benchmark( Each per-request ``latency`` window covers ``generate()`` plus a ``save()`` to a per-run temp directory. The save mirrors what the - serving path (``openai_video_routes.py`` / ``openai_server.py``) does - inside its own ``latency`` window: encode and write to a persisted - location. The directory is cleaned up at the end of the run. + serving path (``serve/api/visual_gen/serving_videos.py`` / + ``serving_images.py``) does inside its own ``latency`` window: encode + and write to a persisted location. The directory is cleaned up at the + end of the run. """ import asyncio diff --git a/tensorrt_llm/commands/AGENTS.md b/tensorrt_llm/commands/AGENTS.md new file mode 100644 index 000000000000..35fcf993bc1a --- /dev/null +++ b/tensorrt_llm/commands/AGENTS.md @@ -0,0 +1,6 @@ + + +Rules for the trtllm-serve CLI (`commands/serve.py`) are in `tensorrt_llm/serve/AGENTS.md`. diff --git a/tensorrt_llm/commands/CLAUDE.md b/tensorrt_llm/commands/CLAUDE.md new file mode 100644 index 000000000000..40c6cf85d526 --- /dev/null +++ b/tensorrt_llm/commands/CLAUDE.md @@ -0,0 +1,2 @@ +# In ./CLAUDE.md +@AGENTS.md diff --git a/tensorrt_llm/serve/AGENTS.md b/tensorrt_llm/serve/AGENTS.md new file mode 100644 index 000000000000..668944a3228e --- /dev/null +++ b/tensorrt_llm/serve/AGENTS.md @@ -0,0 +1,105 @@ + + +# AGENTS.md - tensorrt_llm/serve + +Scope: `tensorrt_llm/serve/` and everything under it. Supplements the repo-root `AGENTS.md` +and `tests/AGENTS.md`; `tensorrt_llm/commands/AGENTS.md` points here for the serve CLI. +Where a check enforces a rule, the rule names it; a failing check says what to change. +Name files and symbols here, never line numbers. + +## Where code goes + +- New endpoint: a router and a serving class under `serve/api///` + (`api_router.py` + `serving.py`). Create the router with `make_router()` + (`serve/_base/routing.py`) and add a `RouterSpec` to `ROUTERS`. Never add a method or a + route to `OpenAIServer`. Check: `tests/unittest/api_stability/test_serve_routes.py`. +- Attach a router with `app.include_router(router)` and no `prefix=`; give the prefix to + `make_router(prefix=...)` instead. The composition root sets each serving object on + `app.state._serving_` before attaching; routers read it from + `request.app.state`, never from a closure. +- Model-specific behavior: a hook on `ServingExtension` (`serve/serving_extensions.py`, + `serve/extensions/`). Do not branch on a model name in a handler. +- Prompt rendering: `serve/render/` only. Handlers do not call `apply_chat_template`. +- Request and response models: a new field needs a row in + `tests/unittest/api_stability/references/trtllm_serve_api.yaml`. + Check: `tests/unittest/api_stability/test_serve_api.py`. +- Routes: every server configuration's routes (path, method, route class, and the order of + routes that can match the same request) are pinned in + `tests/unittest/api_stability/references/trtllm_serve_routes.yaml`. A route change + regenerates it and needs the API review committee. + Check: `tests/unittest/api_stability/test_serve_routes.py`. +- Middleware order matters: `add_middleware` inserts at the front, so the last one added is + outermost. Do not reorder. Check: `tests/unittest/serve/test_middleware_order.py`. +- Import directions between layers are tests; a PR that creates a package adds its contract. + Check: `tests/unittest/serve/test_layering.py`. +- VisualGen serving: `serve/api/visual_gen/` (`ImageServing` and `VideoServing` on + `VisualGenBaseServing`; routes in `api_router.py`, one `RouterSpec`). The composition root + loads the package only for the VISUAL_GEN role; the only other references from outside it + are the routing table's module path, the lazy re-export in `tensorrt_llm.serve.openai_protocol` + and the VisualGen benchmark client, which is what lets CI run only VisualGen tests for + changes under the package. + Check: `tests/unittest/llmapi/apps/visual_gen/test_serve_visual_gen_isolation.py` (import + isolation and test location). +- VisualGen serve tests live under a path that contains `visual_gen/` + (`tests/unittest/serve/api/visual_gen/`), or CI selection misses them. + +## Moving code + +- A move PR only moves code: no reformatting, no logic change. +- A move PR is redone on the latest `main` right before merge instead of being rebased, + and its PR body lists every moved definition with its old and new location, and every + definition the PR changes on purpose. +- In the same PR update the multi-GPU file list (`getMultiGpuFileChanged` in + `jenkins/L0_MergeRequest.groovy`), `.github/CODEOWNERS` and `legacy-files.txt`. A new file + takes the formatting group of the file its code comes from. +- Old import paths: a move deletes the old module (or the moved names) without a shim and + rewrites every import of it in the repository, tests included; module paths written as + strings (patch targets, subprocess command lines, `_LAZY_ATTRS` in `serve/__init__.py`) are + fixed by hand. The PR body lists "old path → new path" for the release notes. Only five old + paths keep a shim, because code outside the repository imports them: + `tensorrt_llm/llmapi/reasoning_parser.py`, `serve/tool_parser/`, + `serve/openai_disagg_server.py`, `serve/openai_server.py` and `commands/serve.py`. A shim + re-exports public names only, lists them in `__all__` (or `_LAZY_NAMES` in + `commands/serve.py`), warns once with `FutureWarning`, and has its rows in + `tests/unittest/serve/test_shim_identity.py`. +- `mock.patch("old.module.name")` does not follow moved code. Grep the tests for every moved + name, including `monkeypatch.setattr(module, "name", ...)` and dotted paths split across lines. + +## Tests + +- Register every new test file in a CI list in the same PR (`tests/AGENTS.md`). Serve tests + that need no GPU go in `tests/integration/test_lists/test-db/l0_cpu.yml` and must contain + `pytest.mark.cpu_only`, or the CPU stage collects nothing from them. +- New serve tests mirror the package: `tests/unittest/serve/` for `tensorrt_llm/serve/`. +- Build servers with the factory and fake generators in `tests/test_common/serve/` + (`isolated_serve_env`), never `object.__new__(OpenAIServer)` or + `object.__new__(OpenAIDisaggServer)`. Check: `tests/unittest/serve/test_no_object_new.py`. +- List an app's routes with `effective_routes()` from `tests/test_common/serve/routes.py`, not + `app.routes`: FastAPI 0.139 keeps included routers as objects without `.path`. +- The harmony tests guard whole files with try-imports. After renaming anything they import, + run them with `pytest -rs` and check that nothing is skipped as "not importable": a green run + can mean every test was skipped. + +## Checklists + +- Endpoint: package under `serve/api/`; `RouterSpec` in `ROUTERS`; regenerate the route + snapshot (API review); multi-GPU list entry if it runs on the disaggregated path; CPU test + registered in `tests/integration/test_lists/test-db/l0_cpu.yml`. + +## Commands + +- All serve CPU tests (the runner exits when `LLM_MODELS_ROOT` is unset): + `LLM_MODELS_ROOT=/path/to/models PYTHONPATH=tests python3 -m test_common.serve.cpu_tests` +- Route snapshot: `pytest -m cpu_only tests/unittest/api_stability/test_serve_routes.py tests/unittest/serve/api/visual_gen/test_routes_visual_gen.py` +- Regenerate the route snapshot: `PYTHONPATH=tests python3 -m test_common.serve.routes --write` +- API gates: `pytest tests/unittest/api_stability/test_serve_api.py tests/unittest/api_stability/test_serve_cli.py` +- Extensions and parsers: `pytest tests/unittest/llmapi/apps/test_serving_extensions.py tests/unittest/llmapi/apps/test_tool_parsers.py` +- Disaggregated router and coordinator (CPU): `pytest tests/unittest/disaggregated -m cpu_only -q` +- Which CI stage runs a test: `python scripts/test_to_stage_mapping.py --tests ""`. It + matches the text of list entries and does not expand directories: a file listed through its + directory maps only when you pass the directory entry, e.g. `--tests "unittest/serve"` for + anything under `tests/unittest/serve/`. +- Tests that load model files need `LLM_MODELS_ROOT` (the harmony tests' autouse fixture does). diff --git a/tensorrt_llm/serve/CLAUDE.md b/tensorrt_llm/serve/CLAUDE.md new file mode 100644 index 000000000000..40c6cf85d526 --- /dev/null +++ b/tensorrt_llm/serve/CLAUDE.md @@ -0,0 +1,2 @@ +# In ./CLAUDE.md +@AGENTS.md diff --git a/tensorrt_llm/serve/_base/__init__.py b/tensorrt_llm/serve/_base/__init__.py new file mode 100644 index 000000000000..0256eaf43af3 --- /dev/null +++ b/tensorrt_llm/serve/_base/__init__.py @@ -0,0 +1,15 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Shared serving infrastructure with no dependency on endpoint packages.""" diff --git a/tensorrt_llm/serve/_base/msgspec_route.py b/tensorrt_llm/serve/_base/msgspec_route.py new file mode 100644 index 000000000000..a7eaf33acc64 --- /dev/null +++ b/tensorrt_llm/serve/_base/msgspec_route.py @@ -0,0 +1,36 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Request and route classes that decode msgpack request bodies from the +disaggregated frontend.""" + +import json + +import msgspec + +from tensorrt_llm.serve.kv_hints import KvHintsRequest, KvHintsRoute + +_msgpack_decoder = msgspec.msgpack.Decoder() + + +class _MsgspecRequest(KvHintsRequest): + """Request that decodes X-TRTLLM-Msgpack bodies with msgspec.""" + + async def json(self): + if not hasattr(self, "_json_body"): + body = await self.body() + if not body: + self._json_body = {} + elif self.headers.get("x-trtllm-msgpack") == "1": + try: + self._json_body = _msgpack_decoder.decode(body) + except msgspec.DecodeError as e: + raise json.JSONDecodeError(f"msgpack: {e}", "", 0) from e + else: + self._json_body = json.loads(body) + return self.filter_kv_hints(self._json_body) + + +class _MsgspecRoute(KvHintsRoute): + """Parse msgpack/JSON and apply hint trust policy before model validation.""" + + request_type = _MsgspecRequest diff --git a/tensorrt_llm/serve/_base/routing.py b/tensorrt_llm/serve/_base/routing.py new file mode 100644 index 000000000000..25cfa59b7115 --- /dev/null +++ b/tensorrt_llm/serve/_base/routing.py @@ -0,0 +1,106 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Router creation and role-based attachment for trtllm-serve.""" + +from __future__ import annotations + +import enum +import importlib +from dataclasses import dataclass +from typing import Any, Callable, Optional + +from fastapi import APIRouter, FastAPI + +from tensorrt_llm.llmapi.disagg_utils import ServerRole +from tensorrt_llm.serve._base.msgspec_route import _MsgspecRoute + + +class RoleGroup(enum.Enum): + LLM = "llm" + MM_ENCODER = "mm_encoder" + EMBEDDING = "embedding" + VISUAL_GEN = "visual_gen" + + +ALL_ROLE_GROUPS: frozenset[RoleGroup] = frozenset(RoleGroup) + + +def role_group_of(role: Optional[ServerRole]) -> RoleGroup: + """None, CONTEXT and GENERATION serve the LLM routes, as the dispatch in OpenAIServer does.""" + if role is ServerRole.MM_ENCODER: + return RoleGroup.MM_ENCODER + if role is ServerRole.EMBEDDING: + return RoleGroup.EMBEDDING + if role is ServerRole.VISUAL_GEN: + return RoleGroup.VISUAL_GEN + return RoleGroup.LLM + + +@dataclass(frozen=True) +class ServerCapabilities: + """What the composition root decides once at startup; routers are attached from it.""" + + role: Optional[ServerRole] + role_group: RoleGroup + + @classmethod + def for_role(cls, role: Optional[ServerRole]) -> ServerCapabilities: + return cls(role=role, role_group=role_group_of(role)) + + +def _always(caps: ServerCapabilities) -> bool: + return True + + +@dataclass(frozen=True) +class RouterSpec: + """One router module and the roles and capabilities that mount it.""" + + module: str # full dotted path of the api_router module + roles: frozenset[RoleGroup] + when: Callable[[ServerCapabilities], bool] = _always + + +# Attach order is registration order. Keep the route snapshot's conflict-relevant +# order: a router that registers GET /metrics must come before the Prometheus mount. +ROUTERS: tuple[RouterSpec, ...] = ( + RouterSpec("tensorrt_llm.serve.api.ops.system.api_router", roles=ALL_ROLE_GROUPS), + RouterSpec( + "tensorrt_llm.serve.api.visual_gen.api_router", roles=frozenset({RoleGroup.VISUAL_GEN}) + ), +) + + +def make_router(**kwargs: Any) -> APIRouter: + """The only way to create a trtllm-serve router: every route decodes msgpack bodies. + + The disaggregated frontend sends worker requests as msgpack; a route of a plain + APIRouter keeps APIRoute and rejects them. + """ + if "route_class" in kwargs: + raise TypeError( + "make_router() always uses _MsgspecRoute; do not pass route_class. " + "A plain APIRoute breaks msgpack request bodies from the disaggregated frontend." + ) + return APIRouter(route_class=_MsgspecRoute, **kwargs) + + +def attach_routers( + app: FastAPI, caps: ServerCapabilities, routers: tuple[RouterSpec, ...] = ROUTERS +) -> None: + """Import and attach only the routers this role needs.""" + for spec in routers: + if caps.role_group in spec.roles and spec.when(caps): + importlib.import_module(spec.module).attach_router(app) diff --git a/tensorrt_llm/serve/_base/serving.py b/tensorrt_llm/serve/_base/serving.py new file mode 100644 index 000000000000..25e30be6bc53 --- /dev/null +++ b/tensorrt_llm/serve/_base/serving.py @@ -0,0 +1,38 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Base class of the serving classes under ``tensorrt_llm/serve/api/``.""" + +from http import HTTPStatus +from typing import Union + +from fastapi.responses import JSONResponse, Response + +from tensorrt_llm.executor.utils import (CONTEXT_LENGTH_EXCEEDED_CODE, + is_context_length_exceeded_message) +from tensorrt_llm.serve.openai_protocol import ErrorResponse + + +class BaseServing: + """Base of every serving class. + + Holds only what all serving classes share; each subclass receives its + dependencies as explicit constructor arguments, never by reading the + server object. + """ + + @staticmethod + def create_error_response( + message: str, + err_type: str = "BadRequestError", + status_code: HTTPStatus = HTTPStatus.BAD_REQUEST) -> Response: + # Over-length prompts are detected from the message text because they + # cross the executor IPC boundary as plain strings (RequestError), so + # no exception type survives to here. + code: Union[int, str] = status_code.value + if is_context_length_exceeded_message(message): + code = CONTEXT_LENGTH_EXCEEDED_CODE + error_response = ErrorResponse(message=message, + type=err_type, + code=code) + return JSONResponse(content=error_response.model_dump(), + status_code=status_code.value) diff --git a/tensorrt_llm/serve/api/__init__.py b/tensorrt_llm/serve/api/__init__.py new file mode 100644 index 000000000000..e5636921d165 --- /dev/null +++ b/tensorrt_llm/serve/api/__init__.py @@ -0,0 +1,15 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Endpoint packages. Do not import routers here: attach_routers imports them by role.""" diff --git a/tensorrt_llm/serve/api/ops/__init__.py b/tensorrt_llm/serve/api/ops/__init__.py new file mode 100644 index 000000000000..1c18ed58c923 --- /dev/null +++ b/tensorrt_llm/serve/api/ops/__init__.py @@ -0,0 +1,15 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Operational endpoints (health, version, model listing).""" diff --git a/tensorrt_llm/serve/api/ops/system/__init__.py b/tensorrt_llm/serve/api/ops/system/__init__.py new file mode 100644 index 000000000000..18515e1ab013 --- /dev/null +++ b/tensorrt_llm/serve/api/ops/system/__init__.py @@ -0,0 +1,15 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""/health, /version and /v1/models, served for every server role.""" diff --git a/tensorrt_llm/serve/api/ops/system/api_router.py b/tensorrt_llm/serve/api/ops/system/api_router.py new file mode 100644 index 000000000000..2bece7f2519f --- /dev/null +++ b/tensorrt_llm/serve/api/ops/system/api_router.py @@ -0,0 +1,60 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The system router: /health, /version and /v1/models for every server role.""" + +from __future__ import annotations + +from fastapi import FastAPI, Request, Response +from fastapi.responses import JSONResponse + +from tensorrt_llm.serve._base.routing import make_router +from tensorrt_llm.serve.api.ops.system.serving import SystemServing + +APP_STATE_KEY = "ops_serving_system" +_UNAVAILABLE = "LLM is unavailable. Please check the server logs for more details." + +router = make_router() + + +def _serving(raw_request: Request) -> SystemServing: + # No app.state default: wiring bugs fail loudly. + serving: SystemServing = raw_request.app.state.ops_serving_system + return serving + + +@router.get("/health") +async def health(raw_request: Request) -> Response: + if _serving(raw_request).is_healthy(): + return Response(status_code=200) + return Response(status_code=503, content=_UNAVAILABLE) + + +@router.get("/version") +async def version(raw_request: Request) -> JSONResponse: + return JSONResponse(content=_serving(raw_request).version()) + + +@router.get("/v1/models") +async def get_model(raw_request: Request) -> JSONResponse: + return JSONResponse(content=_serving(raw_request).models().model_dump()) + + +def attach_router(app: FastAPI) -> None: + if not hasattr(app.state, APP_STATE_KEY): + raise RuntimeError( + f"app.state.{APP_STATE_KEY} (a SystemServing) must be set before attaching " + "tensorrt_llm.serve.api.ops.system; the composition root sets it." + ) + app.include_router(router) diff --git a/tensorrt_llm/serve/api/ops/system/serving.py b/tensorrt_llm/serve/api/ops/system/serving.py new file mode 100644 index 000000000000..c6a204580df5 --- /dev/null +++ b/tensorrt_llm/serve/api/ops/system/serving.py @@ -0,0 +1,44 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""/health, /version and /v1/models for every server role.""" + +from __future__ import annotations + +from typing import Callable + +from tensorrt_llm.serve.openai_protocol import ModelCard, ModelList +from tensorrt_llm.version import __version__ as VERSION + + +class SystemServing: + """Answers the system endpoints from values the composition root injects. + + The health probe stays on the composition root (it reads executor state and + may raise SIGINT); this class only calls it. + """ + + def __init__(self, *, model: str, health_probe: Callable[[], bool]) -> None: + self._model = model + self._health_probe = health_probe + + def is_healthy(self) -> bool: + return self._health_probe() + + def version(self) -> dict[str, str]: + return {"version": VERSION} + + def models(self) -> ModelList: + # Built per request: ModelCard.created is the request time, as today. + return ModelList(data=[ModelCard(id=self._model)]) diff --git a/tensorrt_llm/serve/api/visual_gen/__init__.py b/tensorrt_llm/serve/api/visual_gen/__init__.py new file mode 100644 index 000000000000..4d3a40bee9b0 --- /dev/null +++ b/tensorrt_llm/serve/api/visual_gen/__init__.py @@ -0,0 +1,18 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""VisualGen HTTP serving: request and response models, handlers and routers. + +Kept empty on purpose: importing one submodule must not load the others. +""" diff --git a/tensorrt_llm/serve/api/visual_gen/api_router.py b/tensorrt_llm/serve/api/visual_gen/api_router.py new file mode 100644 index 000000000000..d9bd49606165 --- /dev/null +++ b/tensorrt_llm/serve/api/visual_gen/api_router.py @@ -0,0 +1,159 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The VisualGen router: the image and video endpoints of the VISUAL_GEN role. + +The handlers live on :class:`ImageServing` and :class:`VideoServing`. The +composition root builds both with :func:`init_serving_state` inside its +VISUAL_GEN branch and attaches this router after its role switch. +""" + +from __future__ import annotations + +from pathlib import Path +from typing import TYPE_CHECKING + +from fastapi import FastAPI, Request, Response + +from tensorrt_llm.serve._base.routing import make_router +from tensorrt_llm.serve.api.visual_gen.errors import render_visual_gen_validation_error +from tensorrt_llm.serve.api.visual_gen.media import _resolve_media_dir +from tensorrt_llm.serve.api.visual_gen.protocol import ImageGenerationRequest +from tensorrt_llm.serve.api.visual_gen.serving_images import ImageServing +from tensorrt_llm.serve.api.visual_gen.serving_videos import VideoServing + +if TYPE_CHECKING: + from starlette.datastructures import State + + from tensorrt_llm._utils import AdjustedSteadyClock + from tensorrt_llm.visual_gen.visual_gen import VisualGen + +__all__ = [ + "APP_STATE_KEYS", + "attach_router", + "init_serving_state", + "render_visual_gen_validation_error", + "router", +] + +# Route class _MsgspecRoute: every route decodes msgpack request bodies. +router = make_router() + +# The serving objects init_serving_state puts on app.state; attach_router checks them. +APP_STATE_KEYS = ("visual_gen_serving_images", "visual_gen_serving_videos") + + +def _images(raw_request: Request) -> ImageServing: + # No app.state default: a missing serving object is a wiring bug and fails loudly. + serving: ImageServing = raw_request.app.state.visual_gen_serving_images + return serving + + +def _videos(raw_request: Request) -> VideoServing: + serving: VideoServing = raw_request.app.state.visual_gen_serving_videos + return serving + + +async def openai_image_generation( + request: ImageGenerationRequest, raw_request: Request +) -> Response: + return await _images(raw_request).openai_image_generation(request, raw_request) + + +async def openai_image_edit(raw_request: Request) -> Response: + return await _images(raw_request).openai_image_edit(raw_request) + + +async def get_image_content(image_id: str, raw_request: Request, i: int = 0) -> Response: + return await _images(raw_request).get_image_content(image_id, raw_request, i) + + +async def openai_video_generation_async(raw_request: Request) -> Response: + return await _videos(raw_request).openai_video_generation_async(raw_request) + + +async def openai_video_generation_sync(raw_request: Request) -> Response: + return await _videos(raw_request).openai_video_generation_sync(raw_request) + + +async def list_videos(raw_request: Request) -> Response: + return await _videos(raw_request).list_videos(raw_request) + + +async def get_video_metadata(video_id: str, raw_request: Request) -> Response: + return await _videos(raw_request).get_video_metadata(video_id, raw_request) + + +async def get_video_content(video_id: str, raw_request: Request) -> Response: + return await _videos(raw_request).get_video_content(video_id, raw_request) + + +async def delete_video(video_id: str, raw_request: Request) -> Response: + return await _videos(raw_request).delete_video(video_id, raw_request) + + +# Image generation endpoints (OpenAI compatible), in registration order. +router.add_api_route("/v1/images/generations", openai_image_generation, methods=["POST"]) +router.add_api_route("/v1/images/edits", openai_image_edit, methods=["POST"]) +router.add_api_route("/v1/images/{image_id}/content", get_image_content, methods=["GET"]) +# Video generation endpoints (extended OpenAI API). +# Asynchronous video generation (returns immediately with job metadata, OpenAI API). +router.add_api_route("/v1/videos", openai_video_generation_async, methods=["POST"]) +# Synchronous video generation (waits for completion, extended API). +router.add_api_route("/v1/videos/sync", openai_video_generation_sync, methods=["POST"]) +# Deprecated alias of /v1/videos/sync, retained for upstream back-compat after +# the rename; both hit the same sync handler. +router.add_api_route( + "/v1/videos/generations", openai_video_generation_sync, methods=["POST"], deprecated=True +) +# Video management endpoints. +router.add_api_route("/v1/videos", list_videos, methods=["GET"]) +router.add_api_route("/v1/videos/{video_id}", get_video_metadata, methods=["GET"]) +router.add_api_route("/v1/videos/{video_id}/content", get_video_content, methods=["GET"]) +router.add_api_route("/v1/videos/{video_id}", delete_video, methods=["DELETE"]) + + +def attach_router(app: FastAPI) -> None: + for key in APP_STATE_KEYS: + if not hasattr(app.state, key): + raise RuntimeError( + f"app.state.{key} is not set: call init_serving_state(app.state, ...) for the " + "VISUAL_GEN role before attaching tensorrt_llm.serve.api.visual_gen.api_router " + "(the composition root attaches routers after its role switch)." + ) + app.include_router(router) + + +def init_serving_state( + state: State, *, generator: VisualGen, model: str, adjusted_clock: AdjustedSteadyClock +) -> Path: + """Build the VisualGen serving objects of one server and put them on ``state``. + + Resolves the media directory once and gives the same directory to the + image and the video serving object. Returns that directory. + """ + media_storage_path = _resolve_media_dir() + state.visual_gen_serving_images = ImageServing( + generator=generator, + model=model, + media_storage_path=media_storage_path, + adjusted_clock=adjusted_clock, + ) + state.visual_gen_serving_videos = VideoServing( + generator=generator, + model=model, + media_storage_path=media_storage_path, + adjusted_clock=adjusted_clock, + ) + return media_storage_path diff --git a/tensorrt_llm/serve/api/visual_gen/errors.py b/tensorrt_llm/serve/api/visual_gen/errors.py new file mode 100644 index 000000000000..4e265eb3631d --- /dev/null +++ b/tensorrt_llm/serve/api/visual_gen/errors.py @@ -0,0 +1,60 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The VisualGen 422 renderer. + +Shared by the route-level (``RequestValidationError``) and handler-level +(``ValidationError``) entry points. Internal to the VisualGen serving package. +""" + +from http import HTTPStatus +from typing import Callable, Union + +from fastapi.exceptions import RequestValidationError +from fastapi.responses import Response +from pydantic import ValidationError + + +def render_visual_gen_validation_error( + exc: Union[RequestValidationError, ValidationError], + create_error_response: Callable[..., Response], +) -> Response: + """Render a VisualGen request validation failure as the 422 error envelope. + + Both entry points produce the same body: FastAPI's RequestValidationError + when a route's declared request model rejects the JSON body, and pydantic's + ValidationError when a handler builds its own request model (multipart, + image edit, video). ``create_error_response`` is the server's error-response + factory, so the body and the context-length code rule stay in one place. + """ + parts: list[str] = [] + for err in exc.errors(): + loc = ".".join(str(seg) for seg in err.get("loc", ()) if seg != "body") + etype = err.get("type", "") + msg = err.get("msg", "") + if etype == "extra_forbidden": + parts.append( + f"Unknown request field {loc!r}. Pass model-specific " + "parameters via 'extra_params' instead." + ) + elif loc: + parts.append(f"{loc}: {msg}") + else: + parts.append(msg) + message = "; ".join(parts) if parts else str(exc) + return create_error_response( + message=message, + err_type="BadRequestError", + status_code=HTTPStatus.UNPROCESSABLE_ENTITY, + ) diff --git a/tensorrt_llm/serve/api/visual_gen/media.py b/tensorrt_llm/serve/api/visual_gen/media.py new file mode 100644 index 000000000000..f20b2356f909 --- /dev/null +++ b/tensorrt_llm/serve/api/visual_gen/media.py @@ -0,0 +1,49 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +import os +import tempfile +from datetime import datetime +from pathlib import Path + + +def _new_media_dir(root: Path) -> Path: + """Create a directory under ``root`` stamped with the current time. + + ``mkdir`` without ``exist_ok`` is what makes this safe: the kernel either + creates the directory or raises, so two servers starting in the same + second take separate names instead of sharing one. + """ + stamp = datetime.now().strftime("%y%m%d-%H%M%S") + root.mkdir(parents=True, exist_ok=True) + n = 1 + while True: + candidate = root / (stamp if n == 1 else f"{stamp}-{n}") + try: + candidate.mkdir() + return candidate + except FileExistsError: + n += 1 + + +def _resolve_media_dir() -> Path: + """Create and return the directory to store generated media in. + + ``TRTLLM_MEDIA_STORAGE_PATH`` names the directory outright, empty meaning + unset. Otherwise it goes beside the working directory, and where that + cannot be written it goes to a private temporary one: a shared ``/tmp`` + holds directories owned by other users, so the fallback takes a name + nobody else can hold rather than a fixed one. + """ + explicit = os.getenv("TRTLLM_MEDIA_STORAGE_PATH") + if explicit: + path = Path(explicit) + path.mkdir(parents=True, exist_ok=True) + return path + try: + return _new_media_dir(Path.cwd() / "trtllm_generated") + except OSError: + # OSError rather than PermissionError: a read-only mount raises + # EROFS, which is not one. + stamp = datetime.now().strftime("%y%m%d-%H%M%S") + return Path(tempfile.mkdtemp(prefix=f"trtllm_generated-{stamp}-")) diff --git a/tensorrt_llm/serve/visual_gen_metrics.py b/tensorrt_llm/serve/api/visual_gen/metrics.py similarity index 100% rename from tensorrt_llm/serve/visual_gen_metrics.py rename to tensorrt_llm/serve/api/visual_gen/metrics.py diff --git a/tensorrt_llm/serve/api/visual_gen/protocol.py b/tensorrt_llm/serve/api/visual_gen/protocol.py new file mode 100644 index 000000000000..bcdabe5d08ee --- /dev/null +++ b/tensorrt_llm/serve/api/visual_gen/protocol.py @@ -0,0 +1,441 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Adapted from +# https://github.com/vllm-project/vllm/blob/4db5176d9758b720b05460c50ace3c01026eb158/vllm/entrypoints/openai/protocol.py +"""Request and response models of the VisualGen endpoints. + +Image generation, image edit and video. ``tensorrt_llm.serve.openai_protocol`` +re-exports them lazily under their old names. +""" + +import time +from typing import Any, Dict, List, Literal, Optional, Union + +from fastapi import UploadFile +from pydantic import AliasChoices, Field, field_validator, model_validator + +from tensorrt_llm.serve.openai_protocol import OpenAIBaseModel +from tensorrt_llm.visual_gen.params import MediaRole + + +class ImageGenerationRequest(OpenAIBaseModel): + """OpenAI-compatible image generation request. + + Universal per-request fields map 1:1 to :class:`VisualGenParams`. + Model-specific knobs (``stg_scale``, ``guidance_rescale``, …) + travel through ``extra_params``; the executor validates each + key against the loaded pipeline's + ``extra_param_specs``. Unknown top-level fields are rejected + with HTTP 422 via the inherited ``extra="forbid"`` policy. + """ + + # Prompt + transport (OpenAI-standard, always honored) + prompt: str + response_format: Literal["url", "b64_json", "path"] = "url" + format: Literal["png", "webp", "jpeg", "safetensors", "pt"] = Field( + default="png", + description=( + "Generation content encoding format. Image encoders write " + "``png``/``webp``/``jpeg``; tensor encoders write " + "``safetensors``/``pt`` for programmatic post-processing."), + ) + seed: Optional[int] = Field(default=None, + ge=0, + description="Random seed for reproducibility.") + + # Resolution. ``size`` is OpenAI-shaped; ``width`` + ``height`` are an + # equivalent structured alternative. Exactly one of width/height is + # rejected by the paired validator below. Numeric fields use + # ``gt=0`` as a safety net so zero / negative inputs are rejected + # with HTTP 422 before reaching the pipeline. + size: Optional[str] = Field(default=None, pattern=r"^(\d+x\d+|auto)$") + width: Optional[int] = Field(default=None, gt=0) + height: Optional[int] = Field(default=None, gt=0) + + # TRT-LLM-supported per-request params (1:1 with VisualGenParams fields) + num_inference_steps: Optional[int] = Field(default=None, gt=0) + guidance_scale: Optional[float] = Field(default=None, gt=0) + max_sequence_length: Optional[int] = Field(default=None, gt=0) + negative_prompt: Optional[str] = None + n: Optional[int] = Field( + default=None, + gt=0, + le=10, + description=("Number of images to generate. Capped at 10 to match the " + "OpenAI images API and to bound GPU memory / disk usage."), + ) + + # Model-specific overflow + extra_params: Optional[Dict[str, Any]] = Field( + default=None, + description=( + "Model-specific parameters forwarded to the underlying pipeline. " + "See per-model docs for accepted keys."), + ) + + # Accepted-but-ignored OpenAI-shaped fields. The conversion no-ops; the + # server logs WARNING when a client sets ``quality`` or ``style``, and + # WARNING-on-mismatch for ``model``. Kept in the schema so OpenAI-SDK + # clients don't trip ``extra="forbid"``. + model: Optional[str] = None + quality: Optional[Literal["standard", "hd"]] = None + style: Optional[Literal["vivid", "natural"]] = None + user: Optional[str] = None + + @model_validator(mode="after") + def _check_paired_dimensions(self): + """Reject sending exactly one of ``width`` / ``height``. + + Either both are sent (structured resolution wins over ``size``) + or neither is sent (``size`` or pipeline default applies). + """ + if (self.width is None) != (self.height is None): + raise ValueError( + "width and height must be sent together; got width=" + f"{self.width!r}, height={self.height!r}") + return self + + +class ImageEditRequest(OpenAIBaseModel): + """OpenAI-compatible image editing request. + + The server accepts the OpenAI multipart shape and a JSON/base64 + shape for tests and non-SDK clients. Model-specific knobs travel + through ``extra_params`` and are validated by the loaded visual + generation pipeline. + """ + + prompt: str + image: Union[str, UploadFile, List[Union[str, UploadFile]]] = Field( + description="Input image or images to edit.") + mask: Optional[Union[str, UploadFile]] = Field( + default=None, + description= + "Optional edit mask. Currently accepted for compatibility but unsupported.", + ) + response_format: Literal["url", "b64_json", "path"] = "url" + output_format: Literal["png", "webp", "jpeg"] = Field( + default="png", + validation_alias=AliasChoices("output_format", "format"), + description="Edited image content encoding format.", + ) + seed: Optional[int] = Field(default=None, + ge=0, + description="Random seed for reproducibility.") + + size: Optional[str] = Field(default=None, pattern=r"^(\d+x\d+|auto)$") + width: Optional[int] = Field(default=None, gt=0) + height: Optional[int] = Field(default=None, gt=0) + + num_inference_steps: Optional[int] = Field(default=None, gt=0) + guidance_scale: Optional[float] = Field(default=None, gt=0) + max_sequence_length: Optional[int] = Field(default=None, gt=0) + negative_prompt: Optional[str] = None + n: Optional[int] = Field( + default=None, + gt=0, + le=10, + description=("Number of edited images to generate. Capped at 10 to " + "match the OpenAI images API."), + ) + + extra_params: Optional[Dict[str, Any]] = Field( + default=None, + description=( + "Model-specific parameters forwarded to the underlying pipeline. " + "See per-model docs for accepted keys."), + ) + + model: Optional[str] = None + quality: Optional[Literal["standard", "hd"]] = None + user: Optional[str] = None + + @model_validator(mode="after") + def _check_paired_dimensions(self): + if isinstance(self.image, list) and not self.image: + raise ValueError("image must contain at least one input image") + if (self.width is None) != (self.height is None): + raise ValueError( + "width and height must be sent together; got width=" + f"{self.width!r}, height={self.height!r}") + return self + + +class ImageObject(OpenAIBaseModel): + """Generated image object in the response.""" + b64_json: Optional[str] = None + url: Optional[str] = None + path: Optional[str] = None + revised_prompt: Optional[str] = None + + +class ImageGenerationResponse(OpenAIBaseModel): + """Response from image generation endpoint. + + ``output_format`` reports the encoding actually applied to the + returned bytes / files so clients can decode or label the payload + correctly. Image encoders are ``"png"``/``"webp"``/``"jpeg"``; + tensor formats are ``"safetensors"``/``"pt"``. + """ + + created: int = Field(default_factory=lambda: int(time.time())) + data: List[ImageObject] + output_format: Literal["png", "webp", "jpeg", "safetensors", "pt"] = "png" + quality: Literal["low", "medium", "high"] = "medium" + size: Optional[str] = None + + +class MediaReferenceItem(OpenAIBaseModel): + """One media reference (image / video / audio) for conditioning (mirrors ``MediaRef``). + + ``format`` declares how to read ``content``; it is required, so no wire form + is ever guessed. The request field it sits in (``image_reference`` / + ``video_reference`` / ``audio_reference``) fixes the modality. ``role`` is + required only when it is ambiguous — a model with more than one required role + for that modality; a single role, or a single required role (e.g. i2v + first_frame), is inferred. + """ + + content: str = Field( + description="The reference payload, in the form declared by ``format``." + ) + format: Literal["path", "url", "base64"] = Field(description=( + "Wire form of ``content``: ``path`` (a file readable by the server; a " + "``file://`` URI is also accepted), ``url`` (``http(s)``, fetched " + "through the SSRF-guarded loader), or ``base64`` (a ``data:`` URI is " + "also accepted). Raw bytes reach the server as a multipart upload, " + "which carries no ``format`` of its own. Distinct from the top-level " + "``format``, which selects the *output* encoding.")) + role: Optional[MediaRole] = Field( + default=None, + description="Which conditioning slot this reference fills. Required only " + "when the target model accepts this modality in more than one slot; omit " + "it when the model leaves no ambiguity.", + ) + + +class VideoGenerationRequest(OpenAIBaseModel): + """Video generation request (extended API). + + Universal per-request fields map 1:1 to :class:`VisualGenParams`. + Model-specific knobs travel through ``extra_params``. Unknown + top-level fields are rejected with HTTP 422 via the inherited + ``extra="forbid"`` policy. + """ + + # Prompt + transport + prompt: str + response_format: Literal["file", "path"] = "file" + format: Literal["mp4", "avi", "auto", "safetensors", "pt"] = Field( + default="auto", + description=( + "Generation content encoding format. Video encoders write " + "``mp4``/``avi``/``auto``; tensor encoders write " + "``safetensors``/``pt`` and carry video, audio, and scalar " + "metadata (frame rate, audio sample rate) in one payload."), + ) + seed: Optional[int] = Field(default=None, + ge=0, + description="Random seed for reproducibility.") + image_reference: Optional[Union[ + UploadFile, MediaReferenceItem, List[MediaReferenceItem]]] = Field( + default=None, + description= + ("Image reference(s) conditioning generation (e.g. image-to-video " + "first frame). Send a ``{content, format, role}`` object or a list " + "of them, where ``format`` is ``path`` / ``url`` / ``base64``; or " + "upload a single image file via multipart, whose form is implied. " + "PNG or JPEG only — HEIF/AVIF are not supported."), + ) + video_reference: Optional[Union[ + UploadFile, MediaReferenceItem, List[MediaReferenceItem]]] = Field( + default=None, + description= + ("Video reference(s) conditioning generation (video-to-video). Send " + "a ``{content, format}`` object or a list of them, where ``format`` " + "is ``path`` / ``url`` / ``base64``; or upload a single video file " + "via multipart, whose form is implied. MP4 or AVI, with H.264 the " + "tested codec and others best-effort."), + ) + audio_reference: Optional[Union[ + UploadFile, MediaReferenceItem, List[MediaReferenceItem]]] = Field( + default=None, + description= + ("Audio reference(s) conditioning generation. Send a " + "``{content, format}`` object or a list of them, where ``format`` " + "is ``path`` / ``url`` / ``base64``; or upload a single audio " + "file via multipart, whose form is implied. Accepted only by " + "models that declare an audio reference slot."), + ) + input_reference: Optional[Union[str, UploadFile]] = Field( + default=None, + description= + ("Deprecated. A single image or video reference, routed by content " + "signature to image-to-video or video-to-video. A JSON request carries " + "base64 bytes; a multipart request uploads the file. Kept for backward " + "compatibility; prefer the typed ``image_reference`` / " + "``video_reference`` fields, which take precedence — this field is " + "ignored whenever a typed ``image_reference`` or ``video_reference`` " + "is provided."), + ) + + # Resolution + size: Optional[str] = Field(default=None, pattern=r"^(\d+x\d+|auto)$") + width: Optional[int] = Field(default=None, gt=0) + height: Optional[int] = Field(default=None, gt=0) + + # Frame budget. ``num_frames`` is preferred; if absent the engine + # derives it from ``seconds * frame_rate``. ``frame_rate`` is the + # canonical name (matches the Python field); ``fps`` is an alias for + # OpenAI-shape clients via ``populate_by_name=True``. + # All three constrain to strictly positive values so a zero + # ``frame_rate`` (division-by-zero in the AVI fallback) or a + # negative ``num_frames`` are rejected with HTTP 422 before + # reaching the encoder. + # Upper bounds keep request-boundary protection against requests + # that can exhaust GPU memory or pin the server on unbounded work. + # The numbers are generous (a minute of video at 120 fps) so common + # workloads pass; clients that need larger budgets can lift the cap + # at deployment time. + num_frames: Optional[int] = Field(default=None, gt=0, le=7200) + seconds: Optional[float] = Field(default=None, gt=0, le=60.0) + frame_rate: Optional[float] = Field(default=None, + alias="fps", + gt=0, + le=120.0) + + # TRT-LLM-supported per-request params (1:1 with VisualGenParams) + num_inference_steps: Optional[int] = Field(default=None, gt=0) + guidance_scale: Optional[float] = Field(default=None, gt=0) + max_sequence_length: Optional[int] = Field(default=None, gt=0) + negative_prompt: Optional[str] = None + + # Model-specific overflow + extra_params: Optional[Dict[str, Any]] = Field( + default=None, + description=( + "Model-specific parameters forwarded to the underlying pipeline. " + "See per-model docs for accepted keys."), + ) + + # Accepted-but-ignored OpenAI-shaped field + model: Optional[str] = None + + @model_validator(mode="after") + def _check_paired_dimensions(self): + """Reject sending exactly one of ``width`` / ``height``.""" + if (self.width is None) != (self.height is None): + raise ValueError( + "width and height must be sent together; got width=" + f"{self.width!r}, height={self.height!r}") + return self + + @field_validator("response_format", mode="before") + @classmethod + def _reject_removed_response_format(cls, value): + """Give migrating callers an actionable error for removed values. + + ``url``/``b64_json`` were valid before the transport rewrite; run + before the ``Literal`` check so the error names the replacement + instead of the generic "Input should be 'file' or 'path'". + """ + removed = { + "url": + ("'url' was removed for video; use 'file' (raw bytes -- the " + "old 'url' behavior, renamed) or 'path' (server-side path)."), + "b64_json": ("'b64_json' was removed for video; use 'file' (raw " + "bytes) or 'path' (server-side path)."), + } + if isinstance(value, str) and value in removed: + raise ValueError(removed[value]) + return value + + +class VideoJob(OpenAIBaseModel): + """Metadata for an asynchronous video generation job. + + Follows the OpenAI Videos API specification: + https://platform.openai.com/docs/api-reference/videos + """ + completed_at: Optional[int] = Field( + default=None, description="Unix timestamp of completion") + created_at: int = Field(description="Unix timestamp of creation") + error: Optional[str] = Field(default=None, + description="Error message if failed") + expires_at: Optional[int] = Field( + default=None, description="Unix timestamp of expiration") + id: str = Field(description="Unique identifier for the video") + model: str = Field(description="The model used for generation") + object: str = Field(default="video", description="Object type") + progress: Optional[int] = Field( + default=None, + description="Progress of the video generation job (0-100)") + prompt: str = Field(description="The prompt used to generate the video") + status: Literal["queued", "generating", "postprocessing", "completed", + "failed"] = Field(description=( + "Current status of the video generation job. " + "``generating`` (model inference) becomes " + "``postprocessing`` (encode and/or write the output " + "file) when inference finishes, then ``completed`` " + "once downloadable via ``/content``.")) + + # Video properties + duration: Optional[float] = Field(default=None, + description="Video duration in seconds") + fps: Optional[float] = Field( + default=None, + description=( + "Frames per second. Float to preserve cinematic rates such " + "as 23.976 / 29.97 that some encoders / pipelines use."), + ) + size: Optional[str] = Field(default=None, + description="Video dimensions in 'WxH' format") + # exclude=True: internal file-location for /content resolution + delete; + # never on the wire (the path payload is the hand-built {id, output_path} + # envelope in /content), so status/list model_dump() stays status-only. + output_path: Optional[str] = Field( + default=None, + exclude=True, + description="Server-side saved path (internal; excluded from the wire)." + ) + output_paths: Optional[List[str]] = Field( + default=None, + exclude=True, + description= + "Server-side paths for n>1 (internal; excluded from the wire).") + # exclude=True internal timings, never on the wire (status/list + # model_dump() stays status-only). ``request_started`` carries the + # steady-clock ``server_arrival_time``; the background task computes + # ``total`` from it and stores the header timings + # (``generation``/``denoise``/``total``) in ``timing_metrics`` so + # ``/content`` emits the same Server-Timing header as the sync route. + request_started: Optional[float] = Field(default=None, exclude=True) + timing_metrics: Optional[Dict[str, float]] = Field(default=None, + exclude=True) + response_format: Optional[Literal["file", "path"]] = Field( + default=None, + description=( + "Transport the client requested. ``GET /v1/videos/{id}/content`` " + "honors this: ``path`` returns the server-side output path(s) in a " + "JSON envelope; ``file`` (or unset) returns the file as a " + "``FileResponse`` download."), + ) + + +class VideoJobList(OpenAIBaseModel): + """Response from listing video jobs endpoint.""" + data: List[VideoJob] = Field(description="List of video jobs") + object: str = Field(default="list", description="Object type") diff --git a/tensorrt_llm/serve/api/visual_gen/serving_base.py b/tensorrt_llm/serve/api/visual_gen/serving_base.py new file mode 100644 index 000000000000..8a8e4d629e72 --- /dev/null +++ b/tensorrt_llm/serve/api/visual_gen/serving_base.py @@ -0,0 +1,62 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Shared state and helpers of the VisualGen serving classes.""" + +import asyncio +from http import HTTPStatus +from pathlib import Path +from typing import TYPE_CHECKING, Optional + +from fastapi.responses import Response + +from tensorrt_llm.serve._base.serving import BaseServing +from tensorrt_llm.serve.api.visual_gen.utils import \ + local_media_path_is_disallowed + +if TYPE_CHECKING: + from tensorrt_llm._utils import AdjustedSteadyClock + from tensorrt_llm.visual_gen.params import VisualGenParams + from tensorrt_llm.visual_gen.visual_gen import VisualGen, VisualGenResult + + +class VisualGenBaseServing(BaseServing): + """Shared state and helpers of the VisualGen serving classes.""" + + def __init__(self, *, generator: "VisualGen", model: str, + media_storage_path: Path, + adjusted_clock: "AdjustedSteadyClock") -> None: + self.generator = generator + self.model = model + self.media_storage_path = media_storage_path + self._adjusted_steady_clock = adjusted_clock + + async def _generate(self, prompt: str, + params: "VisualGenParams") -> "VisualGenResult": + """Submit one generation off the event loop; return its handle. + + ``generate_async`` resolves and enqueues synchronously, so it runs in a + worker thread. Callers await the handle (``await handle.aresult()``) or + hand it to a background task. + """ + return await asyncio.to_thread(self.generator.generate_async, prompt, + params) + + def _reject_disabled_path( + self, response_format: Optional[str]) -> Optional[Response]: + """Return a 400 when ``response_format='path'`` but it is disabled. + + Shares the switch with ``format='path'`` on the request side; see + :func:`local_media_path_is_disallowed`. Returns ``None`` when allowed. + """ + if response_format != "path": + return None + if local_media_path_is_disallowed(): + return self.create_error_response( + "response_format='path' is disabled on this server " + "(TRTLLM_DISALLOW_LOCAL_MEDIA_PATH=1); it returns " + "server-side filesystem paths and is only meaningful for " + "co-located clients.", + err_type="BadRequestError", + status_code=HTTPStatus.BAD_REQUEST, + ) + return None diff --git a/tensorrt_llm/serve/api/visual_gen/serving_images.py b/tensorrt_llm/serve/api/visual_gen/serving_images.py new file mode 100644 index 000000000000..a255076366f7 --- /dev/null +++ b/tensorrt_llm/serve/api/visual_gen/serving_images.py @@ -0,0 +1,432 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""VisualGen image endpoints: ``ImageServing`` and its module helpers.""" + +import base64 +import json +import time +import traceback +import uuid +from http import HTTPStatus +from pathlib import Path +from typing import Optional, Union + +from fastapi import Request +from fastapi.responses import FileResponse, JSONResponse, Response +from pydantic import ValidationError + +from tensorrt_llm.logger import logger +from tensorrt_llm.media.encoding import image_to_bytes +from tensorrt_llm.media.tensor_payload import is_tensor_format +from tensorrt_llm.serve.api.visual_gen.errors import \ + render_visual_gen_validation_error +from tensorrt_llm.serve.api.visual_gen.metrics import ( + build_visual_gen_server_timings, build_visual_gen_timing_headers) +from tensorrt_llm.serve.api.visual_gen.protocol import (ImageEditRequest, + ImageGenerationRequest, + ImageGenerationResponse, + ImageObject) +from tensorrt_llm.serve.api.visual_gen.serving_base import VisualGenBaseServing +from tensorrt_llm.serve.api.visual_gen.utils import parse_visual_gen_params + + +def _normalize_image_output(image) -> list: + """Normalize image output to a list of individual images. + + Handles single tensors, batched 4D tensors, and lists. + """ + if isinstance(image, list): + return image + if hasattr(image, "dim") and image.dim() == 4: + return [image[i] for i in range(image.shape[0])] + return [image] + + +def _image_output_size(image) -> Optional[str]: + pil_size = getattr(image, "size", None) + if isinstance(pil_size, tuple) and len(pil_size) >= 2: + width, height = pil_size[:2] + return f"{int(width)}x{int(height)}" + + shape = getattr(image, "shape", None) + if shape is None: + return None + + dims = tuple(int(dim) for dim in shape) + if len(dims) == 2: + height, width = dims + elif len(dims) == 3: + if dims[0] in (1, 3, 4) and dims[1] > 4 and dims[2] > 4: + height, width = dims[1], dims[2] + else: + height, width = dims[0], dims[1] + else: + return None + + return f"{width}x{height}" + + +class ImageServing(VisualGenBaseServing): + """Image generation and editing endpoints (generation, edit, content).""" + + def _supports_image_edit(self) -> bool: + executor = getattr(self.generator, "executor", None) + if executor is None: + return False + + pipeline = getattr(executor, "pipeline", None) + if pipeline is not None: + return bool(getattr(pipeline, "supports_image_edit", False)) + + supports_image_edit = getattr(executor, "supports_image_edit", None) + if supports_image_edit is not None: + return bool(supports_image_edit) + + return False + + def _create_not_supported_error(self, message: str) -> Response: + return self.create_error_response( + err_type="NotImplementedError", + message=message, + status_code=HTTPStatus.NOT_IMPLEMENTED, + ) + + async def openai_image_generation(self, request: ImageGenerationRequest, + raw_request: Request) -> Response: + """OpenAI-compatible image generation endpoint. + + Follows the OpenAI Images API specification for image generation, + with ``request.format`` extended to accept tensor payloads + (``"safetensors"``/``"pt"``) alongside the PNG/WebP/JPEG encoders. + """ + request_received = raw_request.state.server_arrival_time + try: + image_id = f"image_{uuid.uuid4().hex}" + + path_error = self._reject_disabled_path(request.response_format) + if path_error is not None: + return path_error + + # Client-side ValueErrors from request translation and + # parameter validation are 400. Serialization failures below + # (server-side: missing media, inconsistent batch) fall + # through to the outer ``except Exception`` → 500 so the + # client doesn't get blamed for a server-internal failure. + try: + params = parse_visual_gen_params(request, self.generator) + logger.info( + f"Generating image: {image_id} with params: {params} and prompt: {request.prompt}" + ) + image_gen_start = time.perf_counter() + # Offload the blocking resolve/enqueue off the event loop but + # await it (bad params → 400 here); then await generation. + handle = await self._generate(request.prompt, params) + output = await handle.aresult() + except ValueError as exc: + logger.error(f"Image request error: {exc}") + return self.create_error_response( + message=str(exc), + status_code=HTTPStatus.BAD_REQUEST, + ) + + if output.image is None: + return self.create_error_response( + message="Image generation failed", + err_type="InternalServerError", + status_code=HTTPStatus.INTERNAL_SERVER_ERROR, + ) + + if is_tensor_format(request.format): + # Tensor payloads carry every populated modality in a + # single file. Match the image-encoder fan-out by + # emitting one ``ImageObject`` per batch item. + from tensorrt_llm.media.tensor_payload import infer_batch_size + + ext = f".{request.format}" + batch_size = infer_batch_size(output) + if request.response_format == "b64_json": + data = [ + ImageObject( + b64_json=base64.b64encode( + output._save_bytes( + request.format, + batch_index=i)).decode("utf-8"), + revised_prompt=request.prompt, + ) for i in range(batch_size) + ] + else: + paths_in = [ + self.media_storage_path / f"{image_id}_{i}{ext}" + for i in range(batch_size) + ] + # Report the paths save() actually wrote, not paths_in -- + # save() may normalize (e.g. fill a missing extension), so + # its return is the on-disk location the client will open(). + saved = output.save(paths_in, format=request.format) + data = [ + self._image_object(request, raw_request, image_id, i, + saved[i]) for i in range(batch_size) + ] + response = ImageGenerationResponse( + created=int(time.time()), + data=data, + output_format=request.format, + size=f"{params.width}x{params.height}", + ) + else: + output_images = _normalize_image_output(output.image) + # Pillow's format name is the upper-case form of our + # request token. The on-disk extension matches the + # request token directly; ``.jpeg`` is interchangeable + # with ``.jpg`` for Pillow, the OS, and the OpenAI API. + pil_format = request.format.upper() + ext = f".{request.format}" + if request.response_format == "b64_json": + data = [ + ImageObject( + b64_json=base64.b64encode( + image_to_bytes( + image, format=pil_format)).decode("utf-8"), + revised_prompt=request.prompt, + ) for image in output_images + ] + else: + data = [] + for i, image in enumerate(output_images): + path = self.media_storage_path / f"{image_id}_{i}{ext}" + path.write_bytes( + image_to_bytes(image, format=pil_format)) + data.append( + self._image_object(request, raw_request, image_id, + i, path)) + response = ImageGenerationResponse( + created=int(time.time()), + data=data, + output_format=request.format, + size=f"{params.width}x{params.height}", + ) + + latency = time.perf_counter() - image_gen_start # seconds + metrics = output.metrics + generation = metrics.generation if metrics is not None else 0.0 + denoise = metrics.denoise if metrics is not None else 0.0 + logger.info(f"Image {image_id} generated and encoded: " + f"latency={latency:.3f}s generation={generation:.3f}s " + f"denoise={denoise:.3f}s") + total = self._adjusted_steady_clock.now() - request_received + headers = build_visual_gen_timing_headers( + build_visual_gen_server_timings(metrics, total=total)) + + return JSONResponse(content=response.model_dump(), headers=headers) + + except Exception as e: + logger.error(traceback.format_exc()) + return self.create_error_response( + message=str(e), + err_type="InternalServerError", + status_code=HTTPStatus.INTERNAL_SERVER_ERROR, + ) + + async def get_image_content( + self, + image_id: str, + raw_request: Request, + i: int = 0, + ) -> Response: + """Serve a generated image by ID and batch index. + + ``GET /v1/images/{image_id}/content?i=`` returns + the image file the corresponding ``POST /v1/images/generations`` + wrote into ``media_storage_path``. ``i`` defaults to ``0`` for + single-image requests; URL responses for ``n > 1`` requests + carry ``?i=N`` per item. + """ + for ext in (".png", ".webp", ".jpg", ".jpeg", ".safetensors", ".pt"): + candidate = self.media_storage_path / f"{image_id}_{i}{ext}" + if candidate.exists(): + media_type = ("application/octet-stream" + if ext in (".safetensors", ".pt") else + f"image/{ext.lstrip('.').replace('jpg', 'jpeg')}") + return FileResponse( + str(candidate), + media_type=media_type, + filename=candidate.name, + ) + return self.create_error_response( + message=f"Image {image_id!r} (batch index {i}) not found", + err_type="NotFoundError", + status_code=HTTPStatus.NOT_FOUND, + ) + + @staticmethod + def _build_image_content_url(raw_request: Request, image_id: str, + i: int) -> str: + """Return a fetchable HTTP URL for a generated image item.""" + base = str(raw_request.base_url).rstrip("/") + return f"{base}/v1/images/{image_id}/content?i={i}" + + def _image_object(self, request: Union[ImageGenerationRequest, + ImageEditRequest], + raw_request: Request, image_id: str, i: int, + path: Path) -> ImageObject: + """Build the per-item ``ImageObject`` for the ``path``/``url`` transports. + + ``b64_json`` is handled separately. Shared by the generation + (tensor + encoder) and edit routes so they cannot drift when a + transport changes. + """ + if request.response_format == "path": + return ImageObject(path=str(path), revised_prompt=request.prompt) + return ImageObject(url=self._build_image_content_url( + raw_request, image_id, i), + revised_prompt=request.prompt) + + async def _parse_image_edit_request( + self, + raw_request: Request, + ) -> ImageEditRequest: + """Parse an image edit request from JSON or multipart form data.""" + content_type = raw_request.headers.get("content-type", "") + normalized_content_type = content_type.lower() + + if "application/json" in normalized_content_type: + body = await raw_request.json() + if not isinstance(body, dict): + raise ValueError( + "JSON image edit request body must be an object") + return ImageEditRequest(**body) + + if "multipart/form-data" in normalized_content_type: + form = await raw_request.form() + data = {} + for key in form: + values = form.getlist(key) + if key == "image": + values = [ + value for value in values + if not (isinstance(value, str) and value == "") + ] + if not values: + continue + data[key] = values if len(values) > 1 else values[-1] + continue + + value = values[-1] + if key == "extra_params": + if value == "": + continue + if not isinstance(value, str): + raise ValueError( + "'extra_params' must be a JSON object string") + try: + data[key] = json.loads(value) + except (json.JSONDecodeError, TypeError) as exc: + raise ValueError( + f"'extra_params' must be a JSON object string; {exc}" + ) from exc + continue + if value == "": + continue + data[key] = value + return ImageEditRequest(**data) + + raise ValueError( + f"Unsupported content-type: {content_type}. Use 'application/json' or 'multipart/form-data'" + ) + + async def openai_image_edit(self, raw_request: Request) -> Response: + """OpenAI-compatible image editing endpoint.""" + request_received = raw_request.state.server_arrival_time + if not self._supports_image_edit(): + return self._create_not_supported_error( + "Image editing is not supported by the loaded visual generation model." + ) + + try: + image_id = f"image_{uuid.uuid4().hex}" + + try: + request = await self._parse_image_edit_request(raw_request) + path_error = self._reject_disabled_path(request.response_format) + if path_error is not None: + return path_error + params = parse_visual_gen_params(request, self.generator) + logger.info( + f"Editing image: {image_id} with params: {params} and prompt: {request.prompt}" + ) + image_edit_start = time.perf_counter() + output = self.generator.generate(inputs=request.prompt, + params=params) + except ValidationError as exc: + return render_visual_gen_validation_error( + exc, self.create_error_response) + except ValueError as exc: + logger.error(f"Image edit request error: {exc}") + return self.create_error_response( + message=str(exc), + status_code=HTTPStatus.BAD_REQUEST, + ) + + if output.image is None: + return self.create_error_response( + message="Image editing failed", + err_type="InternalServerError", + status_code=HTTPStatus.INTERNAL_SERVER_ERROR, + ) + + # Model-specific ``extra_params`` stay pipeline-owned. Layered + # image-edit models such as Qwen-Image-Layered use + # ``save_layers_to_grid`` to pack all layers into one image here. + output_images = _normalize_image_output(output.image) + output_size = _image_output_size( + output_images[0]) if output_images else None + pil_format = request.output_format.upper() + ext = f".{request.output_format}" + if request.response_format == "b64_json": + data = [ + ImageObject( + b64_json=base64.b64encode( + image_to_bytes(image, + format=pil_format)).decode("utf-8"), + revised_prompt=request.prompt, + ) for image in output_images + ] + else: + data = [] + for i, image in enumerate(output_images): + path = self.media_storage_path / f"{image_id}_{i}{ext}" + path.write_bytes(image_to_bytes(image, format=pil_format)) + data.append( + self._image_object(request, raw_request, image_id, i, + path)) + + response = ImageGenerationResponse( + created=int(time.time()), + data=data, + output_format=request.output_format, + size=output_size, + ) + + latency = time.perf_counter() - image_edit_start + metrics = output.metrics + generation = metrics.generation if metrics is not None else 0.0 + denoise = metrics.denoise if metrics is not None else 0.0 + logger.info(f"Image {image_id} edited and encoded: " + f"latency={latency:.3f}s generation={generation:.3f}s " + f"denoise={denoise:.3f}s") + total = self._adjusted_steady_clock.now() - request_received + headers = build_visual_gen_timing_headers( + build_visual_gen_server_timings(metrics, total=total)) + + return JSONResponse(content=response.model_dump(), headers=headers) + + except ValidationError as exc: + return render_visual_gen_validation_error( + exc, self.create_error_response) + except Exception as e: + logger.error(traceback.format_exc()) + return self.create_error_response( + message=str(e), + err_type="InternalServerError", + status_code=HTTPStatus.INTERNAL_SERVER_ERROR, + ) diff --git a/tensorrt_llm/serve/openai_video_routes.py b/tensorrt_llm/serve/api/visual_gen/serving_videos.py similarity index 92% rename from tensorrt_llm/serve/openai_video_routes.py rename to tensorrt_llm/serve/api/visual_gen/serving_videos.py index aa91f34fac4d..ec54dc11ae8b 100644 --- a/tensorrt_llm/serve/openai_video_routes.py +++ b/tensorrt_llm/serve/api/visual_gen/serving_videos.py @@ -1,14 +1,6 @@ # SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -"""Video-generation route handlers for the OpenAI-compatible server. - -Extracted from ``openai_server.py`` as a small mixin to keep that file -under the project's per-file line budget. ``OpenAIServer`` consumes this -mixin via subclassing; the handlers reach back into the server via -``self`` (e.g. ``self.generator``, ``self.media_storage_path``, -``self.create_error_response``, ``self.video_gen_tasks``), so behavior -is strictly unchanged from the inlined version. -""" +"""VisualGen video endpoints: ``VideoServing`` and its module helpers.""" from __future__ import annotations @@ -30,18 +22,25 @@ from tensorrt_llm.logger import logger from tensorrt_llm.media.encoding import resolve_video_format from tensorrt_llm.media.tensor_payload import is_tensor_format -from tensorrt_llm.serve.openai_protocol import VideoGenerationRequest, VideoJob, VideoJobList -from tensorrt_llm.serve.visual_gen_metrics import ( +from tensorrt_llm.serve.api.visual_gen.errors import render_visual_gen_validation_error +from tensorrt_llm.serve.api.visual_gen.metrics import ( build_visual_gen_server_timings, build_visual_gen_timing_headers, ) -from tensorrt_llm.serve.visual_gen_utils import VIDEO_STORE, parse_visual_gen_params +from tensorrt_llm.serve.api.visual_gen.protocol import ( + VideoGenerationRequest, + VideoJob, + VideoJobList, +) +from tensorrt_llm.serve.api.visual_gen.serving_base import VisualGenBaseServing +from tensorrt_llm.serve.api.visual_gen.utils import VIDEO_STORE, parse_visual_gen_params if TYPE_CHECKING: # Type-only: importing tensorrt_llm.visual_gen at runtime would pull the # whole visual_gen tree into every LLM serving process. + from tensorrt_llm._utils import AdjustedSteadyClock from tensorrt_llm.visual_gen.params import VisualGenParams - from tensorrt_llm.visual_gen.visual_gen import VisualGenResult + from tensorrt_llm.visual_gen.visual_gen import VisualGen, VisualGenResult def _video_content_type(suffix: str) -> str: @@ -129,14 +128,25 @@ def _path_json_video_response( return JSONResponse(content={"id": video_id, "output_path": str(path)}, headers=headers) -class _VideoRoutesMixin: - """Mixin providing the eight video-generation endpoints. +class VideoServing(VisualGenBaseServing): + """Video generation endpoints (sync, async jobs, listing, metadata, content, delete).""" - Concrete subclasses (``OpenAIServer``) supply ``self.generator``, - ``self.media_storage_path``, ``self.video_gen_tasks``, ``self.model``, - ``self._adjusted_steady_clock``, and ``self.create_error_response`` from - their own initializer. - """ + def __init__( + self, + *, + generator: VisualGen, + model: str, + media_storage_path: Path, + adjusted_clock: AdjustedSteadyClock, + ) -> None: + super().__init__( + generator=generator, + model=model, + media_storage_path=media_storage_path, + adjusted_clock=adjusted_clock, + ) + # Background generation tasks by video id (instance state). + self.video_gen_tasks: dict[str, asyncio.Task] = {} async def openai_video_generation_sync(self, raw_request: Request) -> Response: """Synchronous video generation endpoint. @@ -171,12 +181,10 @@ async def openai_video_generation_sync(self, raw_request: Request) -> Response: sync_video_start = time.perf_counter() # Awaited, not fire-and-forget: bad media / bad params must # surface as a 400 rather than a failed job. - handle = await asyncio.to_thread( - self.generator.generate_async, request.prompt, params - ) + handle = await self._generate(request.prompt, params) output = await handle.aresult() except ValidationError as exc: - return self._render_pydantic_validation_error(exc) + return render_visual_gen_validation_error(exc, self.create_error_response) except ValueError as exc: logger.error(f"Video request error: {exc}") return self.create_error_response(str(exc), status_code=HTTPStatus.BAD_REQUEST) @@ -270,7 +278,7 @@ async def openai_video_generation_sync(self, raw_request: Request) -> Response: ) except ValidationError as exc: - return self._render_pydantic_validation_error(exc) + return render_visual_gen_validation_error(exc, self.create_error_response) except Exception as e: logger.error(traceback.format_exc()) return self.create_error_response( @@ -345,35 +353,6 @@ async def _parse_video_generation_request( f"Unsupported content-type: {content_type}. Use 'application/json' or 'multipart/form-data'" ) - def _render_pydantic_validation_error(self, exc: ValidationError) -> Response: - """Render a multipart Pydantic ``ValidationError`` as the LLM envelope. - - The visual-gen-scoped 422 envelope is the same shape JSON requests - get from the FastAPI ``RequestValidationError`` handler, so JSON - and multipart clients see indistinguishable bodies on bad - payloads. - """ - parts: list[str] = [] - for err in exc.errors(): - loc = ".".join(str(seg) for seg in err.get("loc", ()) if seg != "body") - etype = err.get("type", "") - msg = err.get("msg", "") - if etype == "extra_forbidden": - parts.append( - f"Unknown request field {loc!r}. Pass model-specific " - "parameters via 'extra_params' instead." - ) - elif loc: - parts.append(f"{loc}: {msg}") - else: - parts.append(msg) - message = "; ".join(parts) if parts else str(exc) - return self.create_error_response( - message=message, - err_type="BadRequestError", - status_code=HTTPStatus.UNPROCESSABLE_ENTITY, - ) - async def openai_video_generation_async( self, raw_request: Request, @@ -422,7 +401,7 @@ async def openai_video_generation_async( # Awaited before the 202, so bad media / unknown extra_params are a # 400 rather than a queued job that later fails. - handle = await asyncio.to_thread(self.generator.generate_async, request.prompt, params) + handle = await self._generate(request.prompt, params) # Persist the queued job before scheduling the background task so # that a fast-completing task can always look it up in VIDEO_STORE. @@ -456,7 +435,7 @@ async def openai_video_generation_async( return JSONResponse(content=video_job.model_dump(), status_code=202) except ValidationError as exc: - return self._render_pydantic_validation_error(exc) + return render_visual_gen_validation_error(exc, self.create_error_response) except ValueError as e: logger.error(f"Async video request error: {e}") return self.create_error_response(str(e), status_code=HTTPStatus.BAD_REQUEST) diff --git a/tensorrt_llm/serve/visual_gen_utils.py b/tensorrt_llm/serve/api/visual_gen/utils.py similarity index 99% rename from tensorrt_llm/serve/visual_gen_utils.py rename to tensorrt_llm/serve/api/visual_gen/utils.py index 0702470f6d4f..50ce6da3fc51 100644 --- a/tensorrt_llm/serve/visual_gen_utils.py +++ b/tensorrt_llm/serve/api/visual_gen/utils.py @@ -1,3 +1,5 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 from __future__ import annotations import asyncio @@ -13,7 +15,7 @@ from tensorrt_llm.inputs.media_io import sniff_media_kind from tensorrt_llm.logger import logger -from tensorrt_llm.serve.openai_protocol import ( +from tensorrt_llm.serve.api.visual_gen.protocol import ( ImageEditRequest, ImageGenerationRequest, VideoGenerationRequest, diff --git a/tensorrt_llm/serve/openai_protocol.py b/tensorrt_llm/serve/openai_protocol.py index e2643c43d63c..d0b4bcf5f4b2 100644 --- a/tensorrt_llm/serve/openai_protocol.py +++ b/tensorrt_llm/serve/openai_protocol.py @@ -16,6 +16,7 @@ # Adapted from # https://github.com/vllm-project/vllm/blob/4db5176d9758b720b05460c50ace3c01026eb158/vllm/entrypoints/openai/protocol.py import base64 +import importlib import math import time import uuid @@ -23,7 +24,6 @@ import torch import xgrammar -from fastapi import UploadFile from openai.types.chat import ChatCompletionAssistantMessageParam from openai.types.chat import \ ChatCompletionContentPartParam as OpenAIChatCompletionContentPartParam @@ -47,9 +47,8 @@ from openai.types.responses.tool import Tool from openai.types.shared import Metadata, Reasoning from openai_harmony import ReasoningEffort -from pydantic import (AliasChoices, BaseModel, ConfigDict, Field, - NonNegativeInt, PositiveInt, field_validator, - model_serializer, model_validator) +from pydantic import (BaseModel, ConfigDict, Field, NonNegativeInt, PositiveInt, + field_validator, model_serializer, model_validator) from typing_extensions import Annotated, Required, TypeAlias, TypedDict from tensorrt_llm.executor.request import LoRARequest @@ -65,7 +64,6 @@ validate_thinking_token_budget) from tensorrt_llm.scheduling_params import AgentHierarchy from tensorrt_llm.serve.serving_extensions import structured_output_format_for -from tensorrt_llm.visual_gen.params import MediaRole _LOGIT_BIAS_MIN = -100.0 _LOGIT_BIAS_MAX = 100.0 @@ -2210,421 +2208,6 @@ def to_llm_conversation_params( conversation_id=conversation_params.conversation_id) -# ============================================================================ -# Diffusion API Protocol Classes -# ============================================================================ - - -class ImageGenerationRequest(OpenAIBaseModel): - """OpenAI-compatible image generation request. - - Universal per-request fields map 1:1 to :class:`VisualGenParams`. - Model-specific knobs (``stg_scale``, ``guidance_rescale``, …) - travel through ``extra_params``; the executor validates each - key against the loaded pipeline's - ``extra_param_specs``. Unknown top-level fields are rejected - with HTTP 422 via the inherited ``extra="forbid"`` policy. - """ - - # Prompt + transport (OpenAI-standard, always honored) - prompt: str - response_format: Literal["url", "b64_json", "path"] = "url" - format: Literal["png", "webp", "jpeg", "safetensors", "pt"] = Field( - default="png", - description=( - "Generation content encoding format. Image encoders write " - "``png``/``webp``/``jpeg``; tensor encoders write " - "``safetensors``/``pt`` for programmatic post-processing."), - ) - seed: Optional[int] = Field(default=None, - ge=0, - description="Random seed for reproducibility.") - - # Resolution. ``size`` is OpenAI-shaped; ``width`` + ``height`` are an - # equivalent structured alternative. Exactly one of width/height is - # rejected by the paired validator below. Numeric fields use - # ``gt=0`` as a safety net so zero / negative inputs are rejected - # with HTTP 422 before reaching the pipeline. - size: Optional[str] = Field(default=None, pattern=r"^(\d+x\d+|auto)$") - width: Optional[int] = Field(default=None, gt=0) - height: Optional[int] = Field(default=None, gt=0) - - # TRT-LLM-supported per-request params (1:1 with VisualGenParams fields) - num_inference_steps: Optional[int] = Field(default=None, gt=0) - guidance_scale: Optional[float] = Field(default=None, gt=0) - max_sequence_length: Optional[int] = Field(default=None, gt=0) - negative_prompt: Optional[str] = None - n: Optional[int] = Field( - default=None, - gt=0, - le=10, - description=("Number of images to generate. Capped at 10 to match the " - "OpenAI images API and to bound GPU memory / disk usage."), - ) - - # Model-specific overflow - extra_params: Optional[Dict[str, Any]] = Field( - default=None, - description=( - "Model-specific parameters forwarded to the underlying pipeline. " - "See per-model docs for accepted keys."), - ) - - # Accepted-but-ignored OpenAI-shaped fields. The conversion no-ops; the - # server logs WARNING when a client sets ``quality`` or ``style``, and - # WARNING-on-mismatch for ``model``. Kept in the schema so OpenAI-SDK - # clients don't trip ``extra="forbid"``. - model: Optional[str] = None - quality: Optional[Literal["standard", "hd"]] = None - style: Optional[Literal["vivid", "natural"]] = None - user: Optional[str] = None - - @model_validator(mode="after") - def _check_paired_dimensions(self): - """Reject sending exactly one of ``width`` / ``height``. - - Either both are sent (structured resolution wins over ``size``) - or neither is sent (``size`` or pipeline default applies). - """ - if (self.width is None) != (self.height is None): - raise ValueError( - "width and height must be sent together; got width=" - f"{self.width!r}, height={self.height!r}") - return self - - -class ImageEditRequest(OpenAIBaseModel): - """OpenAI-compatible image editing request. - - The server accepts the OpenAI multipart shape and a JSON/base64 - shape for tests and non-SDK clients. Model-specific knobs travel - through ``extra_params`` and are validated by the loaded visual - generation pipeline. - """ - - prompt: str - image: Union[str, UploadFile, List[Union[str, UploadFile]]] = Field( - description="Input image or images to edit.") - mask: Optional[Union[str, UploadFile]] = Field( - default=None, - description= - "Optional edit mask. Currently accepted for compatibility but unsupported.", - ) - response_format: Literal["url", "b64_json", "path"] = "url" - output_format: Literal["png", "webp", "jpeg"] = Field( - default="png", - validation_alias=AliasChoices("output_format", "format"), - description="Edited image content encoding format.", - ) - seed: Optional[int] = Field(default=None, - ge=0, - description="Random seed for reproducibility.") - - size: Optional[str] = Field(default=None, pattern=r"^(\d+x\d+|auto)$") - width: Optional[int] = Field(default=None, gt=0) - height: Optional[int] = Field(default=None, gt=0) - - num_inference_steps: Optional[int] = Field(default=None, gt=0) - guidance_scale: Optional[float] = Field(default=None, gt=0) - max_sequence_length: Optional[int] = Field(default=None, gt=0) - negative_prompt: Optional[str] = None - n: Optional[int] = Field( - default=None, - gt=0, - le=10, - description=("Number of edited images to generate. Capped at 10 to " - "match the OpenAI images API."), - ) - - extra_params: Optional[Dict[str, Any]] = Field( - default=None, - description=( - "Model-specific parameters forwarded to the underlying pipeline. " - "See per-model docs for accepted keys."), - ) - - model: Optional[str] = None - quality: Optional[Literal["standard", "hd"]] = None - user: Optional[str] = None - - @model_validator(mode="after") - def _check_paired_dimensions(self): - if isinstance(self.image, list) and not self.image: - raise ValueError("image must contain at least one input image") - if (self.width is None) != (self.height is None): - raise ValueError( - "width and height must be sent together; got width=" - f"{self.width!r}, height={self.height!r}") - return self - - -class ImageObject(OpenAIBaseModel): - """Generated image object in the response.""" - b64_json: Optional[str] = None - url: Optional[str] = None - path: Optional[str] = None - revised_prompt: Optional[str] = None - - -class ImageGenerationResponse(OpenAIBaseModel): - """Response from image generation endpoint. - - ``output_format`` reports the encoding actually applied to the - returned bytes / files so clients can decode or label the payload - correctly. Image encoders are ``"png"``/``"webp"``/``"jpeg"``; - tensor formats are ``"safetensors"``/``"pt"``. - """ - - created: int = Field(default_factory=lambda: int(time.time())) - data: List[ImageObject] - output_format: Literal["png", "webp", "jpeg", "safetensors", "pt"] = "png" - quality: Literal["low", "medium", "high"] = "medium" - size: Optional[str] = None - - -class MediaReferenceItem(OpenAIBaseModel): - """One media reference (image / video / audio) for conditioning (mirrors ``MediaRef``). - - ``format`` declares how to read ``content``; it is required, so no wire form - is ever guessed. The request field it sits in (``image_reference`` / - ``video_reference`` / ``audio_reference``) fixes the modality. ``role`` is - required only when it is ambiguous — a model with more than one required role - for that modality; a single role, or a single required role (e.g. i2v - first_frame), is inferred. - """ - - content: str = Field( - description="The reference payload, in the form declared by ``format``." - ) - format: Literal["path", "url", "base64"] = Field(description=( - "Wire form of ``content``: ``path`` (a file readable by the server; a " - "``file://`` URI is also accepted), ``url`` (``http(s)``, fetched " - "through the SSRF-guarded loader), or ``base64`` (a ``data:`` URI is " - "also accepted). Raw bytes reach the server as a multipart upload, " - "which carries no ``format`` of its own. Distinct from the top-level " - "``format``, which selects the *output* encoding.")) - role: Optional[MediaRole] = Field( - default=None, - description="Which conditioning slot this reference fills. Required only " - "when the target model accepts this modality in more than one slot; omit " - "it when the model leaves no ambiguity.", - ) - - -class VideoGenerationRequest(OpenAIBaseModel): - """Video generation request (extended API). - - Universal per-request fields map 1:1 to :class:`VisualGenParams`. - Model-specific knobs travel through ``extra_params``. Unknown - top-level fields are rejected with HTTP 422 via the inherited - ``extra="forbid"`` policy. - """ - - # Prompt + transport - prompt: str - response_format: Literal["file", "path"] = "file" - format: Literal["mp4", "avi", "auto", "safetensors", "pt"] = Field( - default="auto", - description=( - "Generation content encoding format. Video encoders write " - "``mp4``/``avi``/``auto``; tensor encoders write " - "``safetensors``/``pt`` and carry video, audio, and scalar " - "metadata (frame rate, audio sample rate) in one payload."), - ) - seed: Optional[int] = Field(default=None, - ge=0, - description="Random seed for reproducibility.") - image_reference: Optional[Union[ - UploadFile, MediaReferenceItem, List[MediaReferenceItem]]] = Field( - default=None, - description= - ("Image reference(s) conditioning generation (e.g. image-to-video " - "first frame). Send a ``{content, format, role}`` object or a list " - "of them, where ``format`` is ``path`` / ``url`` / ``base64``; or " - "upload a single image file via multipart, whose form is implied. " - "PNG or JPEG only — HEIF/AVIF are not supported."), - ) - video_reference: Optional[Union[ - UploadFile, MediaReferenceItem, List[MediaReferenceItem]]] = Field( - default=None, - description= - ("Video reference(s) conditioning generation (video-to-video). Send " - "a ``{content, format}`` object or a list of them, where ``format`` " - "is ``path`` / ``url`` / ``base64``; or upload a single video file " - "via multipart, whose form is implied. MP4 or AVI, with H.264 the " - "tested codec and others best-effort."), - ) - audio_reference: Optional[Union[ - UploadFile, MediaReferenceItem, List[MediaReferenceItem]]] = Field( - default=None, - description= - ("Audio reference(s) conditioning generation. Send a " - "``{content, format}`` object or a list of them, where ``format`` " - "is ``path`` / ``url`` / ``base64``; or upload a single audio " - "file via multipart, whose form is implied. Accepted only by " - "models that declare an audio reference slot."), - ) - input_reference: Optional[Union[str, UploadFile]] = Field( - default=None, - description= - ("Deprecated. A single image or video reference, routed by content " - "signature to image-to-video or video-to-video. A JSON request carries " - "base64 bytes; a multipart request uploads the file. Kept for backward " - "compatibility; prefer the typed ``image_reference`` / " - "``video_reference`` fields, which take precedence — this field is " - "ignored whenever a typed ``image_reference`` or ``video_reference`` " - "is provided."), - ) - - # Resolution - size: Optional[str] = Field(default=None, pattern=r"^(\d+x\d+|auto)$") - width: Optional[int] = Field(default=None, gt=0) - height: Optional[int] = Field(default=None, gt=0) - - # Frame budget. ``num_frames`` is preferred; if absent the engine - # derives it from ``seconds * frame_rate``. ``frame_rate`` is the - # canonical name (matches the Python field); ``fps`` is an alias for - # OpenAI-shape clients via ``populate_by_name=True``. - # All three constrain to strictly positive values so a zero - # ``frame_rate`` (division-by-zero in the AVI fallback) or a - # negative ``num_frames`` are rejected with HTTP 422 before - # reaching the encoder. - # Upper bounds keep request-boundary protection against requests - # that can exhaust GPU memory or pin the server on unbounded work. - # The numbers are generous (a minute of video at 120 fps) so common - # workloads pass; clients that need larger budgets can lift the cap - # at deployment time. - num_frames: Optional[int] = Field(default=None, gt=0, le=7200) - seconds: Optional[float] = Field(default=None, gt=0, le=60.0) - frame_rate: Optional[float] = Field(default=None, - alias="fps", - gt=0, - le=120.0) - - # TRT-LLM-supported per-request params (1:1 with VisualGenParams) - num_inference_steps: Optional[int] = Field(default=None, gt=0) - guidance_scale: Optional[float] = Field(default=None, gt=0) - max_sequence_length: Optional[int] = Field(default=None, gt=0) - negative_prompt: Optional[str] = None - - # Model-specific overflow - extra_params: Optional[Dict[str, Any]] = Field( - default=None, - description=( - "Model-specific parameters forwarded to the underlying pipeline. " - "See per-model docs for accepted keys."), - ) - - # Accepted-but-ignored OpenAI-shaped field - model: Optional[str] = None - - @model_validator(mode="after") - def _check_paired_dimensions(self): - """Reject sending exactly one of ``width`` / ``height``.""" - if (self.width is None) != (self.height is None): - raise ValueError( - "width and height must be sent together; got width=" - f"{self.width!r}, height={self.height!r}") - return self - - @field_validator("response_format", mode="before") - @classmethod - def _reject_removed_response_format(cls, value): - """Give migrating callers an actionable error for removed values. - - ``url``/``b64_json`` were valid before the transport rewrite; run - before the ``Literal`` check so the error names the replacement - instead of the generic "Input should be 'file' or 'path'". - """ - removed = { - "url": - ("'url' was removed for video; use 'file' (raw bytes -- the " - "old 'url' behavior, renamed) or 'path' (server-side path)."), - "b64_json": ("'b64_json' was removed for video; use 'file' (raw " - "bytes) or 'path' (server-side path)."), - } - if isinstance(value, str) and value in removed: - raise ValueError(removed[value]) - return value - - -class VideoJob(OpenAIBaseModel): - """Metadata for an asynchronous video generation job. - - Follows the OpenAI Videos API specification: - https://platform.openai.com/docs/api-reference/videos - """ - completed_at: Optional[int] = Field( - default=None, description="Unix timestamp of completion") - created_at: int = Field(description="Unix timestamp of creation") - error: Optional[str] = Field(default=None, - description="Error message if failed") - expires_at: Optional[int] = Field( - default=None, description="Unix timestamp of expiration") - id: str = Field(description="Unique identifier for the video") - model: str = Field(description="The model used for generation") - object: str = Field(default="video", description="Object type") - progress: Optional[int] = Field( - default=None, - description="Progress of the video generation job (0-100)") - prompt: str = Field(description="The prompt used to generate the video") - status: Literal["queued", "generating", "postprocessing", "completed", - "failed"] = Field(description=( - "Current status of the video generation job. " - "``generating`` (model inference) becomes " - "``postprocessing`` (encode and/or write the output " - "file) when inference finishes, then ``completed`` " - "once downloadable via ``/content``.")) - - # Video properties - duration: Optional[float] = Field(default=None, - description="Video duration in seconds") - fps: Optional[float] = Field( - default=None, - description=( - "Frames per second. Float to preserve cinematic rates such " - "as 23.976 / 29.97 that some encoders / pipelines use."), - ) - size: Optional[str] = Field(default=None, - description="Video dimensions in 'WxH' format") - # exclude=True: internal file-location for /content resolution + delete; - # never on the wire (the path payload is the hand-built {id, output_path} - # envelope in /content), so status/list model_dump() stays status-only. - output_path: Optional[str] = Field( - default=None, - exclude=True, - description="Server-side saved path (internal; excluded from the wire)." - ) - output_paths: Optional[List[str]] = Field( - default=None, - exclude=True, - description= - "Server-side paths for n>1 (internal; excluded from the wire).") - # exclude=True internal timings, never on the wire (status/list - # model_dump() stays status-only). ``request_started`` carries the - # steady-clock ``server_arrival_time``; the background task computes - # ``total`` from it and stores the header timings - # (``generation``/``denoise``/``total``) in ``timing_metrics`` so - # ``/content`` emits the same Server-Timing header as the sync route. - request_started: Optional[float] = Field(default=None, exclude=True) - timing_metrics: Optional[Dict[str, float]] = Field(default=None, - exclude=True) - response_format: Optional[Literal["file", "path"]] = Field( - default=None, - description=( - "Transport the client requested. ``GET /v1/videos/{id}/content`` " - "honors this: ``path`` returns the server-side output path(s) in a " - "JSON envelope; ``file`` (or unset) returns the file as a " - "``FileResponse`` download."), - ) - - -class VideoJobList(OpenAIBaseModel): - """Response from listing video jobs endpoint.""" - data: List[VideoJob] = Field(description="List of video jobs") - object: str = Field(default="list", description="Object type") - - UCompletionRequest = Union[CompletionRequest, ChatCompletionRequest] UCompletionResponse = Union[CompletionResponse, ChatCompletionResponse] @@ -2655,3 +2238,32 @@ class StartProfileRequest(OpenAIBaseModel): description="Which activities to trace. Supported values: " "'CPU', 'GPU', 'CUDA_PROFILER'. Unknown values are rejected at " "schema validation time.") + + +# Old import path of names that moved to +# tensorrt_llm.serve.api.visual_gen.protocol. +# They are re-exported lazily (PEP 562): importing this module does not import +# their new module. +_LAZY_NAMES = { + "ImageEditRequest": "tensorrt_llm.serve.api.visual_gen.protocol", + "ImageGenerationRequest": "tensorrt_llm.serve.api.visual_gen.protocol", + "ImageGenerationResponse": "tensorrt_llm.serve.api.visual_gen.protocol", + "ImageObject": "tensorrt_llm.serve.api.visual_gen.protocol", + "MediaReferenceItem": "tensorrt_llm.serve.api.visual_gen.protocol", + "VideoGenerationRequest": "tensorrt_llm.serve.api.visual_gen.protocol", + "VideoJob": "tensorrt_llm.serve.api.visual_gen.protocol", + "VideoJobList": "tensorrt_llm.serve.api.visual_gen.protocol", +} + + +def __getattr__(name): + module_name = _LAZY_NAMES.get(name) + if module_name is None: + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") + value = getattr(importlib.import_module(module_name), name) + globals()[name] = value # cache: later access skips __getattr__ + return value + + +def __dir__(): + return sorted(set(globals()) | set(_LAZY_NAMES)) diff --git a/tensorrt_llm/serve/openai_server.py b/tensorrt_llm/serve/openai_server.py index eb79cdb18397..4caee252e249 100644 --- a/tensorrt_llm/serve/openai_server.py +++ b/tensorrt_llm/serve/openai_server.py @@ -6,13 +6,13 @@ import asyncio import base64 import functools +import importlib import json import os import re import signal import socket import sys -import tempfile import time import traceback import uuid @@ -25,12 +25,10 @@ from typing import (TYPE_CHECKING, Annotated, Any, AsyncGenerator, AsyncIterator, Dict, List, Optional, Tuple, Union) -import msgspec import uvicorn from fastapi import Body, Depends, FastAPI, HTTPException, Query, Request from fastapi.exceptions import RequestValidationError -from fastapi.responses import (FileResponse, JSONResponse, Response, - StreamingResponse) +from fastapi.responses import JSONResponse, Response, StreamingResponse from pydantic import ValidationError from starlette.routing import Mount from transformers import AutoProcessor @@ -43,8 +41,6 @@ from tensorrt_llm.executor.postproc_worker import PostprocArgs, PostprocParams from tensorrt_llm.executor.request import DEFAULT_REQUEST_PRIORITY from tensorrt_llm.executor.rpc import RPCError -from tensorrt_llm.executor.utils import (CONTEXT_LENGTH_EXCEEDED_CODE, - is_context_length_exceeded_message) from tensorrt_llm.inputs import prompt_inputs from tensorrt_llm.inputs.data import TokensPrompt from tensorrt_llm.inputs.media_io import (BaseMediaIO, @@ -61,12 +57,13 @@ from tensorrt_llm.llmapi.thinking_budget import \ add_thinking_budget_logits_processor from tensorrt_llm.logger import logger -from tensorrt_llm.media.encoding import image_to_bytes -from tensorrt_llm.media.tensor_payload import is_tensor_format from tensorrt_llm.metrics.collector import MetricsCollector from tensorrt_llm.runtime.kv_cache_hash import \ get_effective_kv_cache_event_hash_algo from tensorrt_llm.sampling_params import GuidedDecodingParams, SamplingParams +from tensorrt_llm.serve._base.msgspec_route import _MsgspecRoute +from tensorrt_llm.serve._base.routing import ServerCapabilities, attach_routers +from tensorrt_llm.serve._base.serving import BaseServing from tensorrt_llm.serve._perf_metrics_config import resolve_perf_metrics_config from tensorrt_llm.serve.anthropic_adapter import ( AnthropicRequestError, AnthropicResponseError, anthropic_error_response, @@ -81,6 +78,7 @@ AnthropicCountTokensResponse, AnthropicCreateBatchRequest, AnthropicMessagesRequest) +from tensorrt_llm.serve.api.ops.system.serving import SystemServing from tensorrt_llm.serve.chat_tokenization import tokenize_harmony_chat_request from tensorrt_llm.serve.chat_utils import (load_chat_template, parse_chat_messages_coroutines) @@ -104,15 +102,12 @@ ChatCompletionResponse, ChatCompletionResponseChoice, ChatCompletionToolsParam, ChatMessage, CompletionRequest, CompletionResponse, CompletionResponseChoice, EmbeddingRequest, - EmbeddingResponse, EmbeddingResponseData, EmbeddingUsageInfo, ErrorResponse, - ImageEditRequest, ImageGenerationRequest, ImageGenerationResponse, - ImageObject, MemoryUpdateRequest, ModelCard, ModelList, PromptTokensDetails, - ResponseFormat, ResponsesRequest, ResponsesResponse, - RuntimeMemoryUpdateRequest, StartProfileRequest, TokenizeRequest, - TokenizeResponse, UpdateWeightsRequest, UsageInfo, + EmbeddingResponse, EmbeddingResponseData, EmbeddingUsageInfo, + MemoryUpdateRequest, PromptTokensDetails, ResponseFormat, ResponsesRequest, + ResponsesResponse, RuntimeMemoryUpdateRequest, StartProfileRequest, + TokenizeRequest, TokenizeResponse, UpdateWeightsRequest, UsageInfo, ensure_request_chat_template_allowed, to_llm_conversation_params, to_llm_disaggregated_params) -from tensorrt_llm.serve.openai_video_routes import _VideoRoutesMixin from tensorrt_llm.serve.perf_metrics import (PerfMetricsJsonlWriter, PerfMetricsMiddleware, build_request_metrics_record) @@ -145,10 +140,6 @@ RuntimeControlReplayCache, validate_runtime_control_request) from tensorrt_llm.serve.serving_extensions import load_builtin_extensions from tensorrt_llm.serve.tool_parser.tool_parser_factory import ToolParserFactory -from tensorrt_llm.serve.visual_gen_metrics import ( - build_visual_gen_server_timings, build_visual_gen_timing_headers) -from tensorrt_llm.serve.visual_gen_utils import (local_media_path_is_disallowed, - parse_visual_gen_params) from tensorrt_llm.usage import TerminalOutcome, record_termination_observation from tensorrt_llm.version import __version__ as VERSION @@ -157,7 +148,6 @@ set_prometheus_multiproc_dir) from ._telemetry import create_uvicorn_server from .harmony_adapter import HarmonyAdapter, get_harmony_adapter -from .kv_hints import KvHintsRequest, KvHintsRoute if TYPE_CHECKING: from tensorrt_llm.visual_gen import VisualGen @@ -179,33 +169,6 @@ def _is_visual_gen_instance(obj) -> bool: # yapf: enable -_msgpack_decoder = msgspec.msgpack.Decoder() - - -class _MsgspecRequest(KvHintsRequest): - """Request that decodes X-TRTLLM-Msgpack bodies with msgspec.""" - - async def json(self): - if not hasattr(self, "_json_body"): - body = await self.body() - if not body: - self._json_body = {} - elif self.headers.get("x-trtllm-msgpack") == "1": - try: - self._json_body = _msgpack_decoder.decode(body) - except msgspec.DecodeError as e: - raise json.JSONDecodeError(f"msgpack: {e}", "", 0) from e - else: - self._json_body = json.loads(body) - return self.filter_kv_hints(self._json_body) - - -class _MsgspecRoute(KvHintsRoute): - """Parse msgpack/JSON and apply hint trust policy before model validation.""" - - request_type = _MsgspecRequest - - TIMEOUT_KEEP_ALIVE = 5 # seconds. _warned_unresolvable_thinking = False @@ -478,84 +441,6 @@ def _build_forced_tool_call_decoding(tools, tool_parser_name, forced_tool_name): return begin_prefix, guided -def _new_media_dir(root: Path) -> Path: - """Create a directory under ``root`` stamped with the current time. - - ``mkdir`` without ``exist_ok`` is what makes this safe: the kernel either - creates the directory or raises, so two servers starting in the same - second take separate names instead of sharing one. - """ - stamp = datetime.now().strftime("%y%m%d-%H%M%S") - root.mkdir(parents=True, exist_ok=True) - n = 1 - while True: - candidate = root / (stamp if n == 1 else f"{stamp}-{n}") - try: - candidate.mkdir() - return candidate - except FileExistsError: - n += 1 - - -def _resolve_media_dir() -> Path: - """Create and return the directory to store generated media in. - - ``TRTLLM_MEDIA_STORAGE_PATH`` names the directory outright, empty meaning - unset. Otherwise it goes beside the working directory, and where that - cannot be written it goes to a private temporary one: a shared ``/tmp`` - holds directories owned by other users, so the fallback takes a name - nobody else can hold rather than a fixed one. - """ - explicit = os.getenv("TRTLLM_MEDIA_STORAGE_PATH") - if explicit: - path = Path(explicit) - path.mkdir(parents=True, exist_ok=True) - return path - try: - return _new_media_dir(Path.cwd() / "trtllm_generated") - except OSError: - # OSError rather than PermissionError: a read-only mount raises - # EROFS, which is not one. - stamp = datetime.now().strftime("%y%m%d-%H%M%S") - return Path(tempfile.mkdtemp(prefix=f"trtllm_generated-{stamp}-")) - - -def _normalize_image_output(image) -> list: - """Normalize image output to a list of individual images. - - Handles single tensors, batched 4D tensors, and lists. - """ - if isinstance(image, list): - return image - if hasattr(image, "dim") and image.dim() == 4: - return [image[i] for i in range(image.shape[0])] - return [image] - - -def _image_output_size(image) -> Optional[str]: - pil_size = getattr(image, "size", None) - if isinstance(pil_size, tuple) and len(pil_size) >= 2: - width, height = pil_size[:2] - return f"{int(width)}x{int(height)}" - - shape = getattr(image, "shape", None) - if shape is None: - return None - - dims = tuple(int(dim) for dim in shape) - if len(dims) == 2: - height, width = dims - elif len(dims) == 3: - if dims[0] in (1, 3, 4) and dims[1] > 4 and dims[2] > 4: - height, width = dims[1], dims[2] - else: - height, width = dims[0], dims[1] - else: - return None - - return f"{width}x{height}" - - def resolve_spec_decode_num_spec_tokens(args: Any) -> Optional[int]: """Fixed per-step draft bound to report, or None when there is not one. @@ -571,7 +456,7 @@ def resolve_spec_decode_num_spec_tokens(args: Any) -> Optional[int]: return getattr(spec_config, "max_draft_len", None) -class OpenAIServer(_VideoRoutesMixin): +class OpenAIServer: @staticmethod def _iteration_stats_buffer_maxlen( @@ -892,7 +777,8 @@ async def validation_exception_handler(request, exc): return anthropic_error_response(str(exc), "invalid_request_error", 400) if self.server_role is ServerRole.VISUAL_GEN: - return self._create_visual_gen_validation_error_response(exc) + return self._visual_gen_api.render_visual_gen_validation_error( + exc, self.create_error_response) # Non-visual-gen roles keep the shared 400 + ``{"error": ...}`` # response shape that integration tests (e.g. # ``test_malformed_json_request``) and existing clients @@ -907,6 +793,12 @@ async def validation_exception_handler(request, exc): len(detail) - 4096) return JSONResponse(status_code=400, content={"error": detail}) + # /health, /version and /v1/models for every role. The health + # probe stays here, with its private accesses, until the public + # health API exists. + self.app.state.ops_serving_system = SystemServing( + model=self.model, health_probe=self._health_probe) + if self.server_role is ServerRole.VISUAL_GEN: assert self._is_visual_gen, \ "generator must be a VisualGen for VISUAL_GEN server" @@ -926,6 +818,10 @@ async def validation_exception_handler(request, exc): self._register_launcher_forwarding_routes() self.register_routes() + # Attach routers after the role switch: every attach_router checks + # that its serving objects are on app.state. + attach_routers(self.app, ServerCapabilities.for_role(self.server_role)) + if self._collect_perf_metrics: self.app.add_middleware(PerfMetricsMiddleware, expose_headers=self._expose_perf_metrics, @@ -937,27 +833,6 @@ async def validation_exception_handler(request, exc): def _init_visual_gen(self): self.processor = None self.model_config = None - self.media_storage_path = _resolve_media_dir() - logger.info(f"VisualGen media storage path: {self.media_storage_path}") - self.video_gen_tasks = {} - - def _supports_image_edit(self) -> bool: - if not self._is_visual_gen: - return False - - executor = getattr(self.generator, "executor", None) - if executor is None: - return False - - pipeline = getattr(executor, "pipeline", None) - if pipeline is not None: - return bool(getattr(pipeline, "supports_image_edit", False)) - - supports_image_edit = getattr(executor, "supports_image_edit", None) - if supports_image_edit is not None: - return bool(supports_image_edit) - - return False def _init_llm(self, chat_template: Optional[str] = None): self.tokenizer = self.generator.tokenizer @@ -1143,22 +1018,7 @@ def postproc_worker_enabled(self) -> bool: return True if self.generator.args.num_postprocess_workers > 0 else False - @staticmethod - def create_error_response( - message: str, - err_type: str = "BadRequestError", - status_code: HTTPStatus = HTTPStatus.BAD_REQUEST) -> Response: - # Over-length prompts are detected from the message text because they - # cross the executor IPC boundary as plain strings (RequestError), so - # no exception type survives to here. - code: Union[int, str] = status_code.value - if is_context_length_exceeded_message(message): - code = CONTEXT_LENGTH_EXCEEDED_CODE - error_response = ErrorResponse(message=message, - type=err_type, - code=code) - return JSONResponse(content=error_response.model_dump(), - status_code=status_code.value) + create_error_response = staticmethod(BaseServing.create_error_response) def _create_invalid_response_id_error(self, response_id: str) -> Response: return self.create_error_response( @@ -1174,43 +1034,6 @@ def _create_response_id_not_found_error(self, response_id: str) -> Response: status_code=HTTPStatus.NOT_FOUND, ) - def _create_not_supported_error(self, message: str) -> Response: - return self.create_error_response( - err_type="NotImplementedError", - message=message, - status_code=HTTPStatus.NOT_IMPLEMENTED, - ) - - def _create_visual_gen_validation_error_response( - self, exc: RequestValidationError) -> Response: - """Render a ``RequestValidationError`` as the visual-gen 422 envelope. - - The body has the LLM-style ``{message, type, code}`` shape with - HTTP 422. The ``message`` field names the offending field(s) for - each error in ``exc.errors()`` so clients can fix the request - without parsing the full Pydantic payload. - """ - parts: List[str] = [] - for err in exc.errors(): - loc = ".".join( - str(seg) for seg in err.get("loc", ()) if seg != "body") - etype = err.get("type", "") - msg = err.get("msg", "") - if etype == "extra_forbidden": - parts.append( - f"Unknown request field {loc!r}. Pass model-specific " - "parameters via 'extra_params' instead.") - elif loc: - parts.append(f"{loc}: {msg}") - else: - parts.append(msg) - message = "; ".join(parts) if parts else str(exc) - return self.create_error_response( - message=message, - err_type="BadRequestError", - status_code=HTTPStatus.UNPROCESSABLE_ENTITY, - ) - def _check_health(self) -> bool: # An embedding server's requests flow through the batcher worker; if it # has exited the engine is up but every /v1/embeddings request hangs, so @@ -1223,12 +1046,9 @@ def _check_health(self) -> bool: return True def register_routes(self): - self.app.add_api_route("/health", self.health, methods=["GET"]) self.app.add_api_route("/health_generate", self.health_generate, methods=["GET"]) - self.app.add_api_route("/version", self.version, methods=["GET"]) - self.app.add_api_route("/v1/models", self.get_model, methods=["GET"]) self.app.add_api_route("/v1/data_transceiver_state", self.data_transceiver_state, methods=["GET"]) @@ -1373,9 +1193,6 @@ def mount_metrics(self): self.app.routes.append(metrics_route) def register_mm_encoder_routes(self): - self.app.add_api_route("/health", self.health, methods=["GET"]) - self.app.add_api_route("/version", self.version, methods=["GET"]) - self.app.add_api_route("/v1/models", self.get_model, methods=["GET"]) # TODO: the metrics endpoint only reports iteration stats, not the runtime stats for now self.app.add_api_route("/metrics", self.get_iteration_stats, @@ -1480,9 +1297,6 @@ def encode_fn(token_ids_batch): ) def register_embedding_routes(self): - self.app.add_api_route("/health", self.health, methods=["GET"]) - self.app.add_api_route("/version", self.version, methods=["GET"]) - self.app.add_api_route("/v1/models", self.get_model, methods=["GET"]) self.app.add_api_route("/v1/embeddings", self.openai_embedding, methods=["POST"]) @@ -1586,53 +1400,25 @@ async def openai_embedding(self, request: EmbeddingRequest, status_code=HTTPStatus.INTERNAL_SERVER_ERROR) def register_visual_gen_routes(self): - """Register routes for diffusion model serving.""" - # Health and info endpoints - self.app.add_api_route("/health", self.health, methods=["GET"]) - self.app.add_api_route("/version", self.version, methods=["GET"]) - self.app.add_api_route("/v1/models", self.get_model, methods=["GET"]) + """Wire VisualGen serving for the VISUAL_GEN role. + + The VisualGen routes come from their RouterSpec; /metrics is + registered here, not by a router. + """ + # The only place outside serve/api/visual_gen/ that loads it, besides + # attach_routers through the VisualGen RouterSpec. + self._visual_gen_api = importlib.import_module( + "tensorrt_llm.serve.api.visual_gen.api_router") + self.media_storage_path = self._visual_gen_api.init_serving_state( + self.app.state, + generator=self.generator, + model=self.model, + adjusted_clock=self._adjusted_steady_clock) + logger.info(f"VisualGen media storage path: {self.media_storage_path}") self.app.add_api_route("/metrics", self.get_iteration_stats, methods=["GET"]) - # Image generation endpoints (OpenAI compatible) - self.app.add_api_route("/v1/images/generations", - self.openai_image_generation, - methods=["POST"]) - self.app.add_api_route("/v1/images/edits", - self.openai_image_edit, - methods=["POST"]) - self.app.add_api_route("/v1/images/{image_id}/content", - self.get_image_content, - methods=["GET"]) - - # Video generation endpoints (Extended OpenAI API) - # Asynchronous video generation (returns immediately with job metadata, OpenAI API) - self.app.add_api_route("/v1/videos", - self.openai_video_generation_async, - methods=["POST"]) - # Synchronous video generation (waits for completion, extended API) - self.app.add_api_route("/v1/videos/sync", - self.openai_video_generation_sync, - methods=["POST"]) - # Deprecated alias of /v1/videos/sync, retained for upstream - # back-compat after the rename; both hit the same sync handler. - self.app.add_api_route("/v1/videos/generations", - self.openai_video_generation_sync, - methods=["POST"], - deprecated=True) - # Video management endpoints - self.app.add_api_route("/v1/videos", self.list_videos, methods=["GET"]) - self.app.add_api_route("/v1/videos/{video_id}", - self.get_video_metadata, - methods=["GET"]) - self.app.add_api_route("/v1/videos/{video_id}/content", - self.get_video_content, - methods=["GET"]) - self.app.add_api_route("/v1/videos/{video_id}", - self.delete_video, - methods=["DELETE"]) - async def data_transceiver_state(self) -> JSONResponse: """Return the serialized DataTransceiverState as base64-encoded JSON.""" state = self.generator.get_data_transceiver_state() @@ -1707,9 +1493,9 @@ def _on_launcher_lost(self, error: BaseException) -> None: _record_generator_termination(self.generator) signal.raise_signal(signal.SIGINT) - async def health(self) -> Response: + def _health_probe(self) -> bool: if self._check_health(): - return Response(status_code=200) + return True else: # If the engine has a fatal error, trigger server shutdown so the # pod doesn't linger as a zombie that accepts connections but never @@ -1727,11 +1513,7 @@ async def health(self) -> Response: f"server shutdown: {executor._fatal_error}") _record_generator_termination(self.generator) signal.raise_signal(signal.SIGINT) - return Response( - status_code=503, - content= - "LLM is unavailable. Please check the server logs for more details." - ) + return False async def health_generate(self, raw_request: Request) -> Response: """Health check that performs a minimal generation.""" @@ -1782,14 +1564,6 @@ async def health_generate(self, raw_request: Request) -> Response: return Response(status_code=500, content=f"Generation health check failed: {str(e)}") - async def version(self) -> JSONResponse: - ver = {"version": VERSION} - return JSONResponse(content=ver) - - async def get_model(self) -> JSONResponse: - model_list = ModelList(data=[ModelCard(id=self.model)]) - return JSONResponse(content=model_list.model_dump()) - async def get_iteration_stats(self) -> JSONResponse: # Visual-gen deployments use a separate iteration-stats producer # (see ``DiffusionRemoteClient._iter_stats``). The LLM PyExecutor @@ -3886,365 +3660,6 @@ async def get_server_info(self) -> JSONResponse: {}) return JSONResponse(content=content) - async def openai_image_generation(self, request: ImageGenerationRequest, - raw_request: Request) -> Response: - """OpenAI-compatible image generation endpoint. - - Follows the OpenAI Images API specification for image generation, - with ``request.format`` extended to accept tensor payloads - (``"safetensors"``/``"pt"``) alongside the PNG/WebP/JPEG encoders. - """ - request_received = raw_request.state.server_arrival_time - try: - image_id = f"image_{uuid.uuid4().hex}" - - path_error = self._reject_disabled_path(request.response_format) - if path_error is not None: - return path_error - - # Client-side ValueErrors from request translation and - # parameter validation are 400. Serialization failures below - # (server-side: missing media, inconsistent batch) fall - # through to the outer ``except Exception`` → 500 so the - # client doesn't get blamed for a server-internal failure. - try: - params = parse_visual_gen_params(request, self.generator) - logger.info( - f"Generating image: {image_id} with params: {params} and prompt: {request.prompt}" - ) - image_gen_start = time.perf_counter() - # Offload the blocking resolve/enqueue off the event loop but - # await it (bad params → 400 here); then await generation. - handle = await asyncio.to_thread(self.generator.generate_async, - request.prompt, params) - output = await handle.aresult() - except ValueError as exc: - logger.error(f"Image request error: {exc}") - return self.create_error_response( - message=str(exc), - status_code=HTTPStatus.BAD_REQUEST, - ) - - if output.image is None: - return self.create_error_response( - message="Image generation failed", - err_type="InternalServerError", - status_code=HTTPStatus.INTERNAL_SERVER_ERROR, - ) - - if is_tensor_format(request.format): - # Tensor payloads carry every populated modality in a - # single file. Match the image-encoder fan-out by - # emitting one ``ImageObject`` per batch item. - from tensorrt_llm.media.tensor_payload import infer_batch_size - - ext = f".{request.format}" - batch_size = infer_batch_size(output) - if request.response_format == "b64_json": - data = [ - ImageObject( - b64_json=base64.b64encode( - output._save_bytes( - request.format, - batch_index=i)).decode("utf-8"), - revised_prompt=request.prompt, - ) for i in range(batch_size) - ] - else: - paths_in = [ - self.media_storage_path / f"{image_id}_{i}{ext}" - for i in range(batch_size) - ] - # Report the paths save() actually wrote, not paths_in -- - # save() may normalize (e.g. fill a missing extension), so - # its return is the on-disk location the client will open(). - saved = output.save(paths_in, format=request.format) - data = [ - self._image_object(request, raw_request, image_id, i, - saved[i]) for i in range(batch_size) - ] - response = ImageGenerationResponse( - created=int(time.time()), - data=data, - output_format=request.format, - size=f"{params.width}x{params.height}", - ) - else: - output_images = _normalize_image_output(output.image) - # Pillow's format name is the upper-case form of our - # request token. The on-disk extension matches the - # request token directly; ``.jpeg`` is interchangeable - # with ``.jpg`` for Pillow, the OS, and the OpenAI API. - pil_format = request.format.upper() - ext = f".{request.format}" - if request.response_format == "b64_json": - data = [ - ImageObject( - b64_json=base64.b64encode( - image_to_bytes( - image, format=pil_format)).decode("utf-8"), - revised_prompt=request.prompt, - ) for image in output_images - ] - else: - data = [] - for i, image in enumerate(output_images): - path = self.media_storage_path / f"{image_id}_{i}{ext}" - path.write_bytes( - image_to_bytes(image, format=pil_format)) - data.append( - self._image_object(request, raw_request, image_id, - i, path)) - response = ImageGenerationResponse( - created=int(time.time()), - data=data, - output_format=request.format, - size=f"{params.width}x{params.height}", - ) - - latency = time.perf_counter() - image_gen_start # seconds - metrics = output.metrics - generation = metrics.generation if metrics is not None else 0.0 - denoise = metrics.denoise if metrics is not None else 0.0 - logger.info(f"Image {image_id} generated and encoded: " - f"latency={latency:.3f}s generation={generation:.3f}s " - f"denoise={denoise:.3f}s") - total = self._adjusted_steady_clock.now() - request_received - headers = build_visual_gen_timing_headers( - build_visual_gen_server_timings(metrics, total=total)) - - return JSONResponse(content=response.model_dump(), headers=headers) - - except Exception as e: - logger.error(traceback.format_exc()) - return self.create_error_response( - message=str(e), - err_type="InternalServerError", - status_code=HTTPStatus.INTERNAL_SERVER_ERROR, - ) - - async def get_image_content( - self, - image_id: str, - raw_request: Request, - i: int = 0, - ) -> Response: - """Serve a generated image by ID and batch index. - - ``GET /v1/images/{image_id}/content?i=`` returns - the image file the corresponding ``POST /v1/images/generations`` - wrote into ``media_storage_path``. ``i`` defaults to ``0`` for - single-image requests; URL responses for ``n > 1`` requests - carry ``?i=N`` per item. - """ - for ext in (".png", ".webp", ".jpg", ".jpeg", ".safetensors", ".pt"): - candidate = self.media_storage_path / f"{image_id}_{i}{ext}" - if candidate.exists(): - media_type = ("application/octet-stream" - if ext in (".safetensors", ".pt") else - f"image/{ext.lstrip('.').replace('jpg', 'jpeg')}") - return FileResponse( - str(candidate), - media_type=media_type, - filename=candidate.name, - ) - return self.create_error_response( - message=f"Image {image_id!r} (batch index {i}) not found", - err_type="NotFoundError", - status_code=HTTPStatus.NOT_FOUND, - ) - - @staticmethod - def _build_image_content_url(raw_request: Request, image_id: str, - i: int) -> str: - """Return a fetchable HTTP URL for a generated image item.""" - base = str(raw_request.base_url).rstrip("/") - return f"{base}/v1/images/{image_id}/content?i={i}" - - def _reject_disabled_path( - self, response_format: Optional[str]) -> Optional[Response]: - """Return a 400 when ``response_format='path'`` but it is disabled. - - Shares the switch with ``format='path'`` on the request side; see - :func:`local_media_path_is_disallowed`. Returns ``None`` when allowed. - """ - if response_format != "path": - return None - if local_media_path_is_disallowed(): - return self.create_error_response( - "response_format='path' is disabled on this server " - "(TRTLLM_DISALLOW_LOCAL_MEDIA_PATH=1); it returns " - "server-side filesystem paths and is only meaningful for " - "co-located clients.", - err_type="BadRequestError", - status_code=HTTPStatus.BAD_REQUEST, - ) - return None - - def _image_object(self, request: Union[ImageGenerationRequest, - ImageEditRequest], - raw_request: Request, image_id: str, i: int, - path: Path) -> ImageObject: - """Build the per-item ``ImageObject`` for the ``path``/``url`` transports. - - ``b64_json`` is handled separately. Shared by the generation - (tensor + encoder) and edit routes so they cannot drift when a - transport changes. - """ - if request.response_format == "path": - return ImageObject(path=str(path), revised_prompt=request.prompt) - return ImageObject(url=self._build_image_content_url( - raw_request, image_id, i), - revised_prompt=request.prompt) - - async def _parse_image_edit_request( - self, - raw_request: Request, - ) -> ImageEditRequest: - """Parse an image edit request from JSON or multipart form data.""" - content_type = raw_request.headers.get("content-type", "") - normalized_content_type = content_type.lower() - - if "application/json" in normalized_content_type: - body = await raw_request.json() - if not isinstance(body, dict): - raise ValueError( - "JSON image edit request body must be an object") - return ImageEditRequest(**body) - - if "multipart/form-data" in normalized_content_type: - form = await raw_request.form() - data = {} - for key in form: - values = form.getlist(key) - if key == "image": - values = [ - value for value in values - if not (isinstance(value, str) and value == "") - ] - if not values: - continue - data[key] = values if len(values) > 1 else values[-1] - continue - - value = values[-1] - if key == "extra_params": - if value == "": - continue - if not isinstance(value, str): - raise ValueError( - "'extra_params' must be a JSON object string") - try: - data[key] = json.loads(value) - except (json.JSONDecodeError, TypeError) as exc: - raise ValueError( - f"'extra_params' must be a JSON object string; {exc}" - ) from exc - continue - if value == "": - continue - data[key] = value - return ImageEditRequest(**data) - - raise ValueError( - f"Unsupported content-type: {content_type}. Use 'application/json' or 'multipart/form-data'" - ) - - async def openai_image_edit(self, raw_request: Request) -> Response: - """OpenAI-compatible image editing endpoint.""" - request_received = raw_request.state.server_arrival_time - if not self._supports_image_edit(): - return self._create_not_supported_error( - "Image editing is not supported by the loaded visual generation model." - ) - - try: - image_id = f"image_{uuid.uuid4().hex}" - - try: - request = await self._parse_image_edit_request(raw_request) - path_error = self._reject_disabled_path(request.response_format) - if path_error is not None: - return path_error - params = parse_visual_gen_params(request, self.generator) - logger.info( - f"Editing image: {image_id} with params: {params} and prompt: {request.prompt}" - ) - image_edit_start = time.perf_counter() - output = self.generator.generate(inputs=request.prompt, - params=params) - except ValidationError as exc: - return self._render_pydantic_validation_error(exc) - except ValueError as exc: - logger.error(f"Image edit request error: {exc}") - return self.create_error_response( - message=str(exc), - status_code=HTTPStatus.BAD_REQUEST, - ) - - if output.image is None: - return self.create_error_response( - message="Image editing failed", - err_type="InternalServerError", - status_code=HTTPStatus.INTERNAL_SERVER_ERROR, - ) - - # Model-specific ``extra_params`` stay pipeline-owned. Layered - # image-edit models such as Qwen-Image-Layered use - # ``save_layers_to_grid`` to pack all layers into one image here. - output_images = _normalize_image_output(output.image) - output_size = _image_output_size( - output_images[0]) if output_images else None - pil_format = request.output_format.upper() - ext = f".{request.output_format}" - if request.response_format == "b64_json": - data = [ - ImageObject( - b64_json=base64.b64encode( - image_to_bytes(image, - format=pil_format)).decode("utf-8"), - revised_prompt=request.prompt, - ) for image in output_images - ] - else: - data = [] - for i, image in enumerate(output_images): - path = self.media_storage_path / f"{image_id}_{i}{ext}" - path.write_bytes(image_to_bytes(image, format=pil_format)) - data.append( - self._image_object(request, raw_request, image_id, i, - path)) - - response = ImageGenerationResponse( - created=int(time.time()), - data=data, - output_format=request.output_format, - size=output_size, - ) - - latency = time.perf_counter() - image_edit_start - metrics = output.metrics - generation = metrics.generation if metrics is not None else 0.0 - denoise = metrics.denoise if metrics is not None else 0.0 - logger.info(f"Image {image_id} edited and encoded: " - f"latency={latency:.3f}s generation={generation:.3f}s " - f"denoise={denoise:.3f}s") - total = self._adjusted_steady_clock.now() - request_received - headers = build_visual_gen_timing_headers( - build_visual_gen_server_timings(metrics, total=total)) - - return JSONResponse(content=response.model_dump(), headers=headers) - - except ValidationError as exc: - return self._render_pydantic_validation_error(exc) - except Exception as e: - logger.error(traceback.format_exc()) - return self.create_error_response( - message=str(e), - err_type="InternalServerError", - status_code=HTTPStatus.INTERNAL_SERVER_ERROR, - ) - async def __call__(self, host, port, diff --git a/tensorrt_llm/serve/scripts/BENCHMARKING_VISUAL_GEN.md b/tensorrt_llm/serve/scripts/BENCHMARKING_VISUAL_GEN.md index 378deb04529d..951916103d2b 100644 --- a/tensorrt_llm/serve/scripts/BENCHMARKING_VISUAL_GEN.md +++ b/tensorrt_llm/serve/scripts/BENCHMARKING_VISUAL_GEN.md @@ -15,7 +15,7 @@ This page repeats no field description. Each lives with its definition: |---|---| | every flag, with its default | `--help` | | what a generation parameter means | `VisualGenParams` in [`visual_gen/params.py`](../../visual_gen/params.py) | -| which backend accepts which field | `ImageGenerationRequest` · `ImageEditRequest` · `VideoGenerationRequest` in [`openai_protocol.py`](../openai_protocol.py) | +| which backend accepts which field | `ImageGenerationRequest` · `ImageEditRequest` · `VideoGenerationRequest` in [`api/visual_gen/protocol.py`](../api/visual_gen/protocol.py) | | what a result-JSON key holds | `VisualGenBenchResult` and `VisualGenRequestRecord` in [`benchmark_visual_gen.py`](benchmark_visual_gen.py) | ## Benchmarking args diff --git a/tensorrt_llm/serve/scripts/benchmark_visual_gen.py b/tensorrt_llm/serve/scripts/benchmark_visual_gen.py index 5761ba4c093f..1c91138f316a 100644 --- a/tensorrt_llm/serve/scripts/benchmark_visual_gen.py +++ b/tensorrt_llm/serve/scripts/benchmark_visual_gen.py @@ -52,13 +52,7 @@ from tqdm.asyncio import tqdm from tensorrt_llm.llmapi.utils import StrictBaseModel -from tensorrt_llm.serve.openai_protocol import ( - ImageEditRequest, - ImageGenerationRequest, - MediaReferenceItem, - VideoGenerationRequest, -) -from tensorrt_llm.serve.visual_gen_metrics import ( +from tensorrt_llm.serve.api.visual_gen.metrics import ( SERVER_TIMING_HEADER, VISUAL_GEN_DENOISE_TIMING, VISUAL_GEN_GENERATION_TIMING, @@ -66,6 +60,12 @@ VISUAL_GEN_PRE_DENOISE_TIMING, VISUAL_GEN_TOTAL_TIMING, ) +from tensorrt_llm.serve.api.visual_gen.protocol import ( + ImageEditRequest, + ImageGenerationRequest, + MediaReferenceItem, + VideoGenerationRequest, +) from tensorrt_llm.visual_gen.params import VisualGenParams # 2 is the workload-document shape. The shape before it carried no version, so a diff --git a/tests/integration/defs/.test_durations b/tests/integration/defs/.test_durations index 8f5f9718a185..6df31a142a35 100644 --- a/tests/integration/defs/.test_durations +++ b/tests/integration/defs/.test_durations @@ -2704,6 +2704,8 @@ "test_unittests.py::test_unittests_v2[unittest/_torch/visual_gen/test_visual_gen_args.py]": 25.900797033041133, "unittest/_torch/visual_gen/test_visual_gen_params.py": 27.207403508771932, "test_unittests.py::test_unittests_v2[unittest/_torch/visual_gen/test_visual_gen_params.py]": 27.207403508771932, + "unittest/_torch/visual_gen/test_visual_gen_startup_shutdown.py": 28.712274495138367, + "test_unittests.py::test_unittests_v2[unittest/_torch/visual_gen/test_visual_gen_startup_shutdown.py]": 28.712274495138367, "unittest/_torch/visual_gen/test_visual_gen_utils.py": 28.702138720538724, "test_unittests.py::test_unittests_v2[unittest/_torch/visual_gen/test_visual_gen_utils.py]": 28.702138720538724, "unittest/_torch/visual_gen/test_wan21_i2v_pipeline.py": 176.01823778501628, @@ -3178,8 +3180,6 @@ "test_unittests.py::test_unittests_v2[unittest/llmapi/test_trtllm_serve_config_schemas.py]": 28.42781492764661, "unittest/llmapi/test_utils.py": 37.34388739746458, "test_unittests.py::test_unittests_v2[unittest/llmapi/test_utils.py]": 37.34388739746458, - "unittest/llmapi/test_visual_gen_startup_shutdown.py": 28.712274495138367, - "test_unittests.py::test_unittests_v2[unittest/llmapi/test_visual_gen_startup_shutdown.py]": 28.712274495138367, "unittest/llmapi/test_whisper_suppress_tokens_processor.py": 24.27737232453957, "test_unittests.py::test_unittests_v2[unittest/llmapi/test_whisper_suppress_tokens_processor.py]": 24.27737232453957, "unittest/metrics/test_collector.py": 24.164407904548842, diff --git a/tests/integration/test_lists/test-db/l0_cpu.yml b/tests/integration/test_lists/test-db/l0_cpu.yml index 41e0cabd17ea..71d202ea1efa 100644 --- a/tests/integration/test_lists/test-db/l0_cpu.yml +++ b/tests/integration/test_lists/test-db/l0_cpu.yml @@ -200,11 +200,13 @@ l0_cpu: - unittest/_torch/visual_gen/test_vanilla_key_padding_mask.py - unittest/_torch/visual_gen/test_visual_gen_args.py - unittest/_torch/visual_gen/test_visual_gen_params.py + - unittest/_torch/visual_gen/test_visual_gen_startup_shutdown.py - unittest/_torch/visual_gen/test_visual_gen_utils.py - unittest/_torch/visual_gen/test_wan_i2v_reference_conditioning.py - unittest/_torch/visual_gen/test_wan_timestep_routing.py - unittest/_torch/weight_sharing - unittest/api_stability + - unittest/api_stability/visual_gen/test_visual_gen_serve_api.py - unittest/bindings - unittest/disaggregated - unittest/docs/test_llmapi_reference_docs.py @@ -290,6 +292,7 @@ l0_cpu: - unittest/llmapi/apps/test_serving_extensions.py - unittest/llmapi/apps/test_tool_parsers.py - unittest/llmapi/apps/test_web_search_shared.py + - unittest/llmapi/apps/visual_gen/test_serve_visual_gen_isolation.py - unittest/llmapi/test_iteration_logging.py - unittest/llmapi/test_bench_async.py - unittest/llmapi/test_config_overrides.py @@ -334,13 +337,17 @@ l0_cpu: - unittest/llmapi/test_tokenizer_decode.py - unittest/llmapi/test_trtllm_serve_config_schemas.py - unittest/llmapi/test_utils.py - - unittest/llmapi/test_visual_gen_startup_shutdown.py - unittest/metrics/test_collector.py - unittest/models/test_quant_config_utils.py - unittest/others - unittest/quantization/test_mode.py - unittest/scaffolding - unittest/scripts + - unittest/serve + # VisualGen serve tests are also collected by the entry above. This entry keeps + # them for VisualGen-only PRs, where CBTS keeps only entries containing visual_gen/ + # (with the trailing slash). + - unittest/serve/api/visual_gen/ - unittest/tools - unittest/usage - unittest/utils/test_logger.py diff --git a/tests/test_common/serve/__init__.py b/tests/test_common/serve/__init__.py new file mode 100644 index 000000000000..467079831e16 --- /dev/null +++ b/tests/test_common/serve/__init__.py @@ -0,0 +1,14 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/tests/test_common/serve/app_factory.py b/tests/test_common/serve/app_factory.py new file mode 100644 index 000000000000..1e958e6b44f7 --- /dev/null +++ b/tests/test_common/serve/app_factory.py @@ -0,0 +1,366 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Factory that builds every trtllm-serve app on CPU through the real constructors. + +``isolated_serve_env`` is the only entry point: building a server touches +process-global state (the default Prometheus registry, ``BaseMediaIO``'s +executor, environment variables, the prometheus multiprocess directory, the +telemetry session), and the context manager both prepares and restores all of +it. Use it instead of ``object.__new__(OpenAIServer)``: + + with isolated_serve_env(tmp_path) as env: + server = env.build_openai_server(AggConfig()) + client = env.client(server.app) + ... + +or the ``serve_env`` fixture from ``tests/unittest/serve/conftest.py``. + +Inside an environment, change the state it saves through the environment +(``AggConfig.env``, ``record_terminations()``), not through ``monkeypatch``: +pytest may undo a monkeypatch change after the environment's exit, which then +overwrites the value the environment restored. +""" + +import contextlib +import json +import os +from contextlib import contextmanager +from dataclasses import dataclass +from pathlib import Path +from types import SimpleNamespace +from typing import Iterator, List, Optional +from unittest import mock + +from fastapi import FastAPI +from fastapi.testclient import TestClient +from prometheus_client import REGISTRY + +import tensorrt_llm._utils +from tensorrt_llm.inputs.media_io import BaseMediaIO +from tensorrt_llm.llmapi.disagg_utils import ( + CtxGenServerConfig, + DisaggClusterConfig, + DisaggServerConfig, + RouterConfig, + ServerRole, +) +from tensorrt_llm.serve.coordinator_server import CoordinatorServer +from tensorrt_llm.serve.disagg_coordinator import DisaggCoordinatorService +from tensorrt_llm.serve.openai_disagg_server import OpenAIDisaggServer +from tensorrt_llm.serve.openai_server import OpenAIServer +from tensorrt_llm.usage import usage_lib +from test_common.serve.fakes import ( + FakeAsyncLLM, + FakeEncodeOnlyLLM, + FakeLLM, + FakeLlmArgs, + FakeMultimodalEncoder, +) + +__all__ = [ + "AggConfig", + "CoordinatorConfig", + "DisaggConfig", + "ServeTestEnv", + "isolated_serve_env", +] + +_MISSING = object() + +# Environment variables that change route registration or request handling; +# removed on entry so every configuration starts from the same baseline and +# sets what it needs through AggConfig.env. +_CLEARED_ENV_VARS = ( + "ENABLE_METRICS", + "TRTLLM_ENABLE_RENDER_ENDPOINTS", + "DISABLE_HARMONY_ADAPTER", + "TRTLLM_RESPONSES_API_DISABLE_STORE", + "TRTLLM_KVCACHE_TIME_OUTPUT_PATH", +) + + +@dataclass(frozen=True) +class AggConfig: + """One ``OpenAIServer`` configuration, built through the real constructor.""" + + role: Optional[ServerRole] = None + model_type: str = "llama" # "gpt_oss" makes use_harmony true + governor_queue: bool = False # FakeExecutor(resource_governor_queue=object()) + rl_control: bool = False # FakeAsyncLLM + enable_rl_control_endpoints + runtime_control: bool = False # sleep_config + enable_runtime_control_endpoints + return_perf_metrics: bool = False + perf_metrics_output_dir: bool = False # sets args.perf_metrics_output_dir=/perf + env: tuple = () # (name, value) pairs applied before construction + model_name: str = "fake-model" # OpenAIServer(model=...): the /v1/models id + tool_parser: Optional[str] = None + reasoning_parser: Optional[str] = None + num_postprocess_workers: int = 0 # > 0 takes the postprocess-worker path + # Attached frontend of a multi-frontend server: registers the launcher + # forwarding routes ahead of the local handlers, which they shadow. + multi_frontend_attached: bool = False + + +@dataclass(frozen=True) +class DisaggConfig: + """One ``OpenAIDisaggServer`` configuration.""" + + fleet: bool = False # delegate to a remote coordinator (CoordinatorClient) + http_cluster_storage: bool = False + return_perf_metrics: bool = False + + +@dataclass(frozen=True) +class CoordinatorConfig: + """One ``CoordinatorServer`` configuration (the fleet-mode coordinator app).""" + + http_cluster_storage: bool = False + + +def _make_disagg_server_config( + *, return_perf_metrics: bool = False, http_cluster_storage: bool = False +) -> DisaggServerConfig: + # Loopback addresses on closed ports: construction is network-free, and + # nothing in these tests runs the disaggregated lifespan. + return DisaggServerConfig( + server_configs=[ + CtxGenServerConfig(type="ctx", hostname="127.0.0.1", port=9), + CtxGenServerConfig(type="gen", hostname="127.0.0.1", port=10), + ], + hostname="127.0.0.1", + port=0, + ctx_router_config=RouterConfig(server_role=ServerRole.CONTEXT), + gen_router_config=RouterConfig(server_role=ServerRole.GENERATION), + node_id=0, + return_perf_metrics=return_perf_metrics, + disagg_cluster_config=( + DisaggClusterConfig(cluster_uri="http://127.0.0.1:9", cluster_name="test") + if http_cluster_storage + else None + ), + ) + + +class _StubTelemetrySession: + """Collects termination observations for ``ServeTestEnv.record_terminations``.""" + + def __init__(self, sink: list) -> None: + self.owner_pid = os.getpid() + self._sink = sink + + def record_termination_observation(self, outcome, lifecycle_phase=None) -> None: + self._sink.append(outcome) + + +class ServeTestEnv: + """Handle returned by ``isolated_serve_env``; builds servers and clients.""" + + def __init__(self, tmp_dir: Path) -> None: + self.tmp_dir = Path(tmp_dir) + self._servers: List[OpenAIServer] = [] + self._entered_clients: List[TestClient] = [] + self._plain_clients: List[TestClient] = [] + + # -- builders --------------------------------------------------------- + + def _write_fake_checkpoint(self, model_type: str) -> Path: + """A directory with only a config.json, so load_pretrained_config works. + + No tokenizer files are written: they would make AutoProcessor succeed + and change ``server.processor`` from its fake-generator value (None). + """ + model_dir = self.tmp_dir / f"model-{model_type}" + model_dir.mkdir(parents=True, exist_ok=True) + architectures = { + "llama": ["LlamaForCausalLM"], + "gpt_oss": ["GptOssForCausalLM"], + }[model_type] + (model_dir / "config.json").write_text( + json.dumps({"model_type": model_type, "architectures": architectures}) + ) + return model_dir + + def build_openai_server(self, config: AggConfig) -> OpenAIServer: + from test_common.serve.fakes import FakeExecutor # local: keeps the import graph flat + + for name, value in config.env: + os.environ[name] = value + + args = FakeLlmArgs( + model=str(self._write_fake_checkpoint(config.model_type)), + return_perf_metrics=config.return_perf_metrics, + perf_metrics_output_dir=( + str(self.tmp_dir / "perf") if config.perf_metrics_output_dir else None + ), + sleep_config=SimpleNamespace() if config.runtime_control else None, + encode_only=config.role is ServerRole.EMBEDDING, + reasoning_parser=config.reasoning_parser, + num_postprocess_workers=config.num_postprocess_workers, + ) + executor = FakeExecutor(resource_governor_queue=object() if config.governor_queue else None) + if config.role is ServerRole.VISUAL_GEN: + # Lazy import: only VisualGen tests pay the visual_gen import cost, + # and importing it is what lets _is_visual_gen_instance say yes. + from test_common.serve.fakes_visual_gen import FakeVisualGen + + generator = FakeVisualGen(model=config.model_name) + elif config.role is ServerRole.MM_ENCODER: + generator = FakeMultimodalEncoder(args=args, executor=executor) + elif config.role is ServerRole.EMBEDDING: + generator = FakeEncodeOnlyLLM(args=args) + elif config.rl_control: + generator = FakeAsyncLLM(args=args, executor=executor) + else: + generator = FakeLLM(args=args, executor=executor) + + multi_frontend_serving = None + if config.multi_frontend_attached: + from tensorrt_llm.serve.multi_frontend import MultiFrontendServing + + ipc_dir = self.tmp_dir / "multi_frontend_ipc" + ipc_dir.mkdir(parents=True, exist_ok=True) + multi_frontend_serving = MultiFrontendServing( + launcher_uds=str(ipc_dir / "launcher.sock"), is_launcher=False + ) + + server = OpenAIServer( + generator=generator, + model=config.model_name, + tool_parser=config.tool_parser, + server_role=config.role, + metadata_server_cfg=None, + enable_rl_control_endpoints=config.rl_control, + rl_control_api_key="test-key" if config.rl_control else None, + enable_runtime_control_endpoints=config.runtime_control, + runtime_control_api_key="test-key" if config.runtime_control else None, + multi_frontend_serving=multi_frontend_serving, + ) + self._servers.append(server) + return server + + def build_disagg_server(self, config: DisaggConfig) -> OpenAIDisaggServer: + # At most one per environment: each registers the disaggregated server + # counters in the default Prometheus registry, and a second one fails + # with "Duplicated timeseries". + server_config = _make_disagg_server_config( + return_perf_metrics=config.return_perf_metrics, + http_cluster_storage=config.http_cluster_storage, + ) + return OpenAIDisaggServer( + server_config, + coordinator_url="http://127.0.0.1:9" if config.fleet else None, + ) + + def build_coordinator_server(self, config: CoordinatorConfig) -> CoordinatorServer: + server_config = _make_disagg_server_config(http_cluster_storage=config.http_cluster_storage) + coordinator = DisaggCoordinatorService(server_config, lambda *args, **kwargs: None) + return CoordinatorServer(coordinator) + + # -- request plumbing ------------------------------------------------- + + def client(self, app: FastAPI, *, lifespan: bool = True) -> TestClient: + """A TestClient closed at environment exit; runs the lifespan by default.""" + client = TestClient(app) + if lifespan: + client.__enter__() + self._entered_clients.append(client) + else: + self._plain_clients.append(client) + return client + + def record_terminations(self) -> list: + """Route termination observations of this process into the returned list. + + Installs a stub telemetry session; the environment's exit restores the + session that existed before entry. + """ + sink: list = [] + usage_lib._SESSION = _StubTelemetrySession(sink) + return sink + + # -- teardown helpers (called by isolated_serve_env) ------------------- + + def _close(self) -> None: + for client in self._entered_clients: + client.__exit__(None, None, None) + for client in self._plain_clients: + client.close() + self._entered_clients.clear() + self._plain_clients.clear() + for server in self._servers: + for pool_name in ( + "_input_proc_executor", + "_media_load_executor", + "_metrics_stats_executor", + ): + pool = getattr(server, pool_name, None) + if pool is not None: + pool.shutdown(wait=False, cancel_futures=True) + self._servers.clear() + + +@contextmanager +def isolated_serve_env(tmp_dir: Path) -> Iterator[ServeTestEnv]: + """Process-global state that building trtllm-serve apps touches, restored on exit. + + The only supported forms are ``with isolated_serve_env(tmp_path) as env:`` + and the ``serve_env`` fixture. The context-manager object has no builder + methods, so ``isolated_serve_env(tmp_path).build_openai_server(...)`` fails + with ``AttributeError`` instead of leaving global state behind. + + Build one configuration per environment when configurations differ in + environment variables or perf metrics. + """ + tmp_dir = Path(tmp_dir) + env_patcher = mock.patch.dict(os.environ) + env_patcher.start() + try: + os.environ["HF_HUB_OFFLINE"] = "1" + os.environ["TRANSFORMERS_OFFLINE"] = "1" + prometheus_dir = tmp_dir / "prometheus" + prometheus_dir.mkdir(parents=True, exist_ok=True) + os.environ["PROMETHEUS_MULTIPROC_DIR"] = str(prometheus_dir) + os.environ["TRTLLM_MEDIA_STORAGE_PATH"] = str(tmp_dir / "media") + for name in _CLEARED_ENV_VARS: + os.environ.pop(name, None) + + saved_media_executor = BaseMediaIO._executor + # The module global exists only after the first + # set_prometheus_multiproc_dir() call; save it with a sentinel. + saved_prometheus_dir = getattr(tensorrt_llm._utils, "prometheus_multiproc_dir", _MISSING) + # An unhealthy /health records a termination observation on the + # process-wide telemetry session, which keeps only its first + # observation; detach any session so tests cannot poison it. + saved_session = usage_lib._SESSION + usage_lib._SESSION = None + collectors_before = set(REGISTRY._collector_to_names.keys()) + + env = ServeTestEnv(tmp_dir) + try: + yield env + finally: + env._close() + for collector in list(REGISTRY._collector_to_names.keys()): + if collector not in collectors_before: + with contextlib.suppress(KeyError): + REGISTRY.unregister(collector) + BaseMediaIO._executor = saved_media_executor + if saved_prometheus_dir is _MISSING: + if hasattr(tensorrt_llm._utils, "prometheus_multiproc_dir"): + delattr(tensorrt_llm._utils, "prometheus_multiproc_dir") + else: + tensorrt_llm._utils.prometheus_multiproc_dir = saved_prometheus_dir + usage_lib._SESSION = saved_session + finally: + env_patcher.stop() diff --git a/tests/test_common/serve/cpu_tests.py b/tests/test_common/serve/cpu_tests.py new file mode 100644 index 000000000000..44575b7c24f1 --- /dev/null +++ b/tests/test_common/serve/cpu_tests.py @@ -0,0 +1,183 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The one command that runs every serve CPU test, as the CPU CI stage runs them. + + LLM_MODELS_ROOT=... PYTHONPATH=tests python3 -m test_common.serve.cpu_tests [--list] [pytest args...] + +Reads the CPU test-db list, keeps the entries whose files are serve CPU tests, +and runs one pytest process per kept entry from ``tests/`` with +``tests/unittest`` on ``PYTHONPATH`` — one process per entry, as the CPU stage +does — so process-global state does not leak between entries. Extra arguments go +to every process. Exits with the first non-zero pytest exit code, or 0. +""" + +import argparse +import os +import subprocess +import sys +from dataclasses import dataclass +from pathlib import Path +from typing import List, Optional, Sequence, Tuple + +import yaml + +__all__ = ["Entry", "select_entries"] + +REPO_ROOT = Path(__file__).resolve().parents[3] +CPU_LIST = REPO_ROOT / "tests" / "integration" / "test_lists" / "test-db" / "l0_cpu.yml" + +_MODULE_MARKERS = ( + "tensorrt_llm.serve", + "tensorrt_llm.commands.serve", + "from tensorrt_llm.commands import serve", + "test_common.serve", +) + + +@dataclass(frozen=True) +class Entry: + """One kept test-db entry with the targets it runs.""" + + entry: str # the test-db line, e.g. "unittest/serve" + targets: Tuple[str, ...] # pytest targets relative to tests/ + + +def _iter_test_entries(data) -> List[str]: + """Every string test entry of a test-db document, in file order.""" + entries: List[str] = [] + + def _walk(node) -> None: + if isinstance(node, str): + entries.append(node) + elif isinstance(node, list): + for item in node: + _walk(item) + elif isinstance(node, dict): + for value in node.values(): + _walk(value) + + _walk(data) + return entries + + +def _is_serve_cpu_test(path: Path) -> bool: + """Whether one test file is a serve CPU test. + + The file must contain the literal ``pytest.mark.cpu_only`` (the CPU stage + collects nothing from it otherwise) and either live under + ``tests/unittest/serve/`` or mention a serve module or ``test_common.serve`` + in its text. The path condition catches files that name no module, such as + checks over the test tree itself. + """ + try: + text = path.read_text(errors="replace") + except OSError: + return False + if "pytest.mark.cpu_only" not in text: + return False + serve_dir = REPO_ROOT / "tests" / "unittest" / "serve" + if serve_dir in path.parents: + return True + return any(marker in text for marker in _MODULE_MARKERS) + + +def select_entries(cpu_list: Path = CPU_LIST) -> Tuple[List[Entry], List[str]]: + """(kept entries with targets, notes about skipped entries).""" + data = yaml.safe_load(cpu_list.read_text()) + tests_root = REPO_ROOT / "tests" + kept: List[Entry] = [] + notes: List[str] = [] + for raw_entry in _iter_test_entries(data): + entry = raw_entry.strip() + if not entry.startswith("unittest/"): + continue + target_part = entry.split("::")[0].split(" ")[0] + if entry != target_part and "::" not in entry: + # Entries with -k, -m, TIMEOUT or ISOLATION run with options this + # runner does not reproduce; run them through the CI stage instead. + notes.append(f"skipped (has options): {entry}") + continue + if "::" in entry and " " in entry: + notes.append(f"skipped (has options): {entry}") + continue + target = entry.split("::")[0].rstrip("/") + path = tests_root / target + if "::" in entry: + # A node-id entry runs only that node, never the whole file. + if path.is_file() and _is_serve_cpu_test(path): + kept.append(Entry(entry=raw_entry, targets=(entry,))) + continue + if path.is_file(): + if _is_serve_cpu_test(path): + kept.append(Entry(entry=raw_entry, targets=(target,))) + continue + if path.is_dir(): + selected = tuple( + str(candidate.relative_to(tests_root)) + for candidate in sorted(path.rglob("test_*.py")) + if _is_serve_cpu_test(candidate) + ) + if selected: + kept.append(Entry(entry=raw_entry, targets=selected)) + return kept, notes + + +def main(argv: Optional[Sequence[str]] = None) -> int: + parser = argparse.ArgumentParser( + prog="python3 -m test_common.serve.cpu_tests", + description="Run every serve CPU test, one pytest process per test-db entry.", + ) + parser.add_argument( + "--list", action="store_true", help="print the kept entries and their targets" + ) + args, pytest_args = parser.parse_known_args(argv) + + kept, notes = select_entries() + if args.list: + for note in notes: + print(note) + for entry in kept: + print(entry.entry) + for target in entry.targets: + print(f" {target}") + return 0 + + if not os.environ.get("LLM_MODELS_ROOT"): + print( + "LLM_MODELS_ROOT is not set. Some selected tests read model files through " + "autouse fixtures and would error in setup; set LLM_MODELS_ROOT and rerun.", + file=sys.stderr, + ) + return 2 + + env = dict(os.environ) + unittest_dir = str(REPO_ROOT / "tests" / "unittest") + env["PYTHONPATH"] = os.pathsep.join( + part for part in (unittest_dir, env.get("PYTHONPATH", "")) if part + ) + first_failure = 0 + for note in notes: + print(note) + for entry in kept: + command = [sys.executable, "-m", "pytest", "-m", "cpu_only", *entry.targets, *pytest_args] + print(f"[{entry.entry}] {' '.join(command)}") + result = subprocess.run(command, cwd=REPO_ROOT / "tests", env=env) + if result.returncode != 0 and first_failure == 0: + first_failure = result.returncode + return first_failure + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/test_common/serve/fakes.py b/tests/test_common/serve/fakes.py new file mode 100644 index 000000000000..2318776cd4c8 --- /dev/null +++ b/tests/test_common/serve/fakes.py @@ -0,0 +1,493 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Fake generators with scripted generation for CPU tests of trtllm-serve. + +The fakes subclass the real generator classes, so every ``isinstance`` check in +``tensorrt_llm/serve`` passes without patching module attributes, but they never +run the real constructors. ``generate_async`` records every call and replays a +queued :class:`ScriptedOutput` through the same ``RequestOutput`` surface the +request handlers consume, so handler tests run through production code on CPU. + +The fakes fail loudly on purpose: a handler that reads a generator attribute the +fakes lack raises ``AttributeError``, which is the signal to extend the fakes +here (with a self-test in ``tests/unittest/serve/test_serve_test_helpers.py``), +not to catch it in the test. + +Not scripted: sampling, logits processors, guided decoding, logprobs, perf +metrics, multimodal data. A test that needs one of those adds it to these fakes +with a self-test, not as a private fake in its own test file. +""" + +import asyncio +import collections +import itertools +from dataclasses import dataclass, field +from types import SimpleNamespace +from typing import Any, AsyncIterator, Optional, Sequence, Union + +from tokenizers import Tokenizer +from tokenizers.models import WordLevel +from tokenizers.pre_tokenizers import Whitespace +from transformers import PreTrainedTokenizerFast + +from tensorrt_llm._torch.async_llm import AsyncLLM +from tensorrt_llm.executor.result import GenerationResultBase +from tensorrt_llm.inputs.registry import DefaultInputProcessor +from tensorrt_llm.llmapi import MultimodalEncoder +from tensorrt_llm.llmapi.llm import LLM, PreprocessedInputs +from tensorrt_llm.llmapi.tokenizer import TransformersTokenizer +from tensorrt_llm.sampling_params import SamplingParams + +__all__ = [ + "FAKE_CHAT_TEMPLATE", + "FakeAsyncLLM", + "FakeEncodeOnlyLLM", + "FakeEncoderExecutor", + "FakeExecutor", + "FakeLLM", + "FakeLlmArgs", + "FakeMultimodalEncoder", + "GenerateCall", + "PreprocessCall", + "ScriptedOutput", + "ScriptedRequestOutput", + "ScriptedStep", + "UserProbeMiddleware", + "make_fake_tokenizer", +] + +# Renders each message as <|role|>content and appends <|assistant|> when +# add_generation_prompt is true, so chat requests render offline through the +# production template machinery. +FAKE_CHAT_TEMPLATE = ( + "{% for message in messages %}" + "<|{{ message['role'] }}|>{{ message['content'] }}" + "{% endfor %}" + "{% if add_generation_prompt %}<|assistant|>{% endif %}" +) + + +def make_fake_tokenizer() -> TransformersTokenizer: + """An in-memory tokenizer with a working chat template, built offline. + + Gives the handlers ``.tokenizer``, ``encode``, ``decode`` and a chat + template without reading any file. The vocabulary only needs to exist; + unknown words map to ````. + """ + vocab = { + "": 0, + "": 1, + "<|system|>": 2, + "<|user|>": 3, + "<|assistant|>": 4, + "hi": 5, + "hello": 6, + "ok": 7, + } + backend = Tokenizer(WordLevel(vocab, unk_token="")) + backend.pre_tokenizer = Whitespace() + hf_tokenizer = PreTrainedTokenizerFast( + tokenizer_object=backend, + unk_token="", + eos_token="", + chat_template=FAKE_CHAT_TEMPLATE, + ) + return TransformersTokenizer(hf_tokenizer) + + +@dataclass +class FakeLlmArgs: + """The LLM args fields ``OpenAIServer`` reads at construction, in its lifespan and in its handlers. + + Defaults are the ``TorchLlmArgs`` defaults. A new direct read of a field + missing here fails loudly with ``AttributeError``; add the field. + """ + + model: str # path of the fake checkpoint directory + backend: str = "pytorch" + dtype: str = "auto" + trust_remote_code: bool = False + checkpoint_format: Optional[str] = None + num_postprocess_workers: int = 0 + post_processor_hook: Optional[str] = None + return_perf_metrics: bool = False + perf_metrics_output_dir: Optional[str] = None + per_request_spec_decode_stats: bool = False + speculative_config: Any = None + decoding_config: Any = None + prometheus_metrics_config: Any = None + quant_config: Any = None + max_seq_len: Optional[int] = None + max_batch_size: Optional[int] = 2048 # get_server_info reads it + parallel_config: Any = field( + default_factory=lambda: SimpleNamespace( + tp_size=1, pp_size=1, cp_size=1, world_size=1, moe_ep_size=None + ) + ) + kv_cache_config: Any = None + cache_transceiver_config: Any = None + enable_energy_metrics: bool = False + enable_iter_perf_stats: bool = False + iter_stats_max_iterations: Optional[int] = None + encode_only: bool = False + sleep_config: Any = None + num_serve_frontends: int = 1 + max_beam_width: int = 1 + reasoning_parser: Optional[str] = None # chat, completions, Responses + gather_generation_logits: bool = False # to_sampling_params in chat and completions + guided_decoding_backend: Optional[str] = None # the required-tool grammar check + + +class FakeExecutor: + """Stands in for the executor where ``OpenAIServer`` reads it.""" + + def __init__(self, *, resource_governor_queue: object = None) -> None: + # register_routes reads it to decide on the resource-governor routes. + self.resource_governor_queue = resource_governor_queue + self.healthy = True + self._fatal_error: Optional[BaseException] = None # read by the /health handler + self.doing_shutdown = False # read by the /health handler + + @property + def fatal_error(self) -> Optional[BaseException]: + """Public name of ``_fatal_error``; nothing reads it yet.""" + return self._fatal_error + + def check_health(self) -> bool: + # Like the real executor: healthy unless a fatal error was recorded. + return self.healthy and self._fatal_error is None + + def shutdown(self) -> None: + self.doing_shutdown = True + + +class FakeEncoderExecutor: + """Stands in for the encoder executor of an encode-only LLM.""" + + def __init__(self) -> None: + self.model_engine = SimpleNamespace(batch_size=8, max_num_tokens=8192, max_seq_len=2048) + + def shutdown(self) -> None: + pass + + +@dataclass(frozen=True) +class ScriptedStep: + """One engine response: what it appends to the outputs.""" + + text: str = "" + token_ids: tuple = () + finish_reason: Optional[str] = None # set on the last step: "stop", "length", ... + stop_reason: Optional[Union[int, str]] = None + index: Optional[int] = None # output index; None applies the step to every output + + +@dataclass(frozen=True) +class ScriptedOutput: + """What one ``generate_async`` call produces.""" + + steps: tuple = (ScriptedStep(text="ok", token_ids=(7,), finish_reason="stop"),) + raise_on_call: Optional[BaseException] = None # raised after the call is recorded + raise_after_steps: Optional[BaseException] = None # raised once the steps are replayed + hold_after_steps: bool = False # wait until release(), abort() or cancellation + prompt_token_ids: Optional[tuple] = None # default: derived from the inputs + + +@dataclass +class GenerateCall: + """One recorded ``generate_async`` call.""" + + inputs: Any # exactly what the handler passed + kwargs: dict # every other argument by name, including sampling_params + result: Optional["ScriptedRequestOutput"] # None when raise_on_call fired + + @property + def sampling_params(self) -> Optional[SamplingParams]: + return self.kwargs.get("sampling_params") + + +@dataclass +class PreprocessCall: + """One recorded ``preprocess`` call.""" + + inputs: Any + sampling_params: Any + disaggregated_params: Any + + +def _derive_prompt_fields(inputs: Any, tokenizer: TransformersTokenizer) -> tuple: + """(prompt token ids, prompt text or None) the way the engine would see them.""" + if isinstance(inputs, PreprocessedInputs): + return list(inputs.prompt_token_ids), None + if isinstance(inputs, dict): + if inputs.get("prompt_token_ids") is not None: # TokensPrompt + return list(inputs["prompt_token_ids"]), None + if inputs.get("prompt") is not None: # TextPrompt + return list(tokenizer.encode(inputs["prompt"])), inputs["prompt"] + if isinstance(inputs, str): + return list(tokenizer.encode(inputs)), inputs + if isinstance(inputs, Sequence) and all(isinstance(t, int) for t in inputs): + return list(inputs), None + raise TypeError(f"cannot derive prompt token ids from inputs of type {type(inputs)!r}") + + +class ScriptedRequestOutput(GenerationResultBase): + """Replays a :class:`ScriptedOutput` with the ``RequestOutput`` surface handlers use.""" + + def __init__( + self, + *, + request_id: int, + script: ScriptedOutput, + inputs: Any, + sampling_params: Optional[SamplingParams], + tokenizer: TransformersTokenizer, + postproc_params: Any = None, + ) -> None: + GenerationResultBase.__init__( + self, + request_id, + sampling_params if sampling_params is not None else SamplingParams(), + postproc_params=postproc_params, + ) + self._script = script + self._fake_tokenizer = tokenizer + if script.prompt_token_ids is not None: + self.prompt_token_ids = list(script.prompt_token_ids) + try: + _, self.prompt = _derive_prompt_fields(inputs, tokenizer) + except TypeError: + self.prompt = None + else: + self.prompt_token_ids, self.prompt = _derive_prompt_fields(inputs, tokenizer) + self._pending = collections.deque(script.steps) + self._release_event = asyncio.Event() + self._after_steps_raised = False + + @property + def request_id(self) -> int: + return self.id + + @property + def finished(self) -> bool: + return self._done + + def release(self) -> None: + """End a ``hold_after_steps`` wait normally.""" + self._release_event.set() + + def abort(self) -> None: + # An aborted engine request ends with finish_reason "cancelled". + for output in self._outputs: + output.finish_reason = "cancelled" + super().abort() + self._done = True + self._release_event.set() + + def _replay_step(self, step: ScriptedStep) -> None: + targets = self._outputs if step.index is None else [self._outputs[step.index]] + for output in targets: + # Update the diff markers the way the result handler does, so + # text_diff / token_ids_diff work for streaming post-processors. + output._last_text_len = len(output.text) + output._last_token_ids_len = len(output.token_ids) + output._last_logprobs_len = len(output.logprobs) + output.text += step.text + output.token_ids = list(output.token_ids) + list(step.token_ids) + if step.finish_reason is not None: + output.finish_reason = step.finish_reason + output.stop_reason = step.stop_reason + if not self._pending and not self._script.hold_after_steps: + self._done = True + if self.postproc_params is not None: + # As the postprocess worker does: fill _postprocess_result after + # each response, with the tokenizer bound on the args. + args = self.postproc_params.postproc_args + args.tokenizer = self._fake_tokenizer + self._outputs[0]._postprocess_result = self.postproc_params.post_processor(self, args) + + def _finish_after_steps(self) -> None: + if self._script.raise_after_steps is not None and not self._after_steps_raised: + self._after_steps_raised = True + self._done = True + raise self._script.raise_after_steps + + async def aresult(self) -> "ScriptedRequestOutput": + while self._pending: + self._replay_step(self._pending.popleft()) + self._finish_after_steps() + if self._script.hold_after_steps and not self._done: + await self._release_event.wait() + self._done = True + return self + + def __await__(self): + return self.aresult().__await__() + + def __aiter__(self) -> "ScriptedRequestOutput": + return self + + async def __anext__(self) -> "ScriptedRequestOutput": + if self._pending: + self._replay_step(self._pending.popleft()) + return self + self._finish_after_steps() + if self._script.hold_after_steps and not self._done: + await self._release_event.wait() + self._done = True + raise StopAsyncIteration + + +class _FakeGeneratorMixin: + """Shared state and scripted generation of every fake generator.""" + + def _setup_fake( + self, + *, + args: FakeLlmArgs, + executor: Optional[FakeExecutor], + encode_only: bool = False, + ) -> None: + self.args = args + self._hf_model_dir = args.model # read by OpenAIServer._init_llm + self._tokenizer = make_fake_tokenizer() + # BaseLLM.tokenizer returns input_processor.tokenizer; completions call + # the input processor for text prompts. The real DefaultInputProcessor + # needs only a tokenizer. + self.input_processor = DefaultInputProcessor( + model_path=args.model, config=None, tokenizer=self._tokenizer + ) + self._executor = executor # BaseLLM._check_health and /health read it + self._encode_only = encode_only # BaseLLM._check_health reads it + self._llm_id = "fake-llm" + self.generate_calls: list = [] + self.preprocess_calls: list = [] + self._scripts: collections.deque = collections.deque() + self._request_ids = itertools.count(1) + + @property + def llm_id(self) -> str: + return self._llm_id + + def script(self, *outputs: ScriptedOutput) -> None: + """Queue outputs for the next ``generate_async`` calls.""" + self._scripts.extend(outputs) + + def preprocess( + self, + inputs: Any, + sampling_params: Any = None, + disaggregated_params: Any = None, + ) -> PreprocessedInputs: + # Replaces the inherited BaseLLM.preprocess, which needs + # args.generation_config and a model. + self.preprocess_calls.append(PreprocessCall(inputs, sampling_params, disaggregated_params)) + token_ids, _ = _derive_prompt_fields(inputs, self._tokenizer) + return PreprocessedInputs(prompt_token_ids=token_ids) + + def generate_async( + self, + inputs: Any, + sampling_params: Optional[SamplingParams] = None, + **kwargs: Any, + ) -> ScriptedRequestOutput: + # Record first, so a scripted failure still leaves the call inspectable. + call = GenerateCall( + inputs=inputs, + kwargs={"sampling_params": sampling_params, **kwargs}, + result=None, + ) + self.generate_calls.append(call) + script = self._scripts.popleft() if self._scripts else ScriptedOutput() + if script.raise_on_call is not None: + raise script.raise_on_call + postproc_params = kwargs.get("_postproc_params") + promise = ScriptedRequestOutput( + request_id=next(self._request_ids), + script=script, + inputs=inputs, + sampling_params=sampling_params, + tokenizer=self._tokenizer, + postproc_params=postproc_params, + ) + if postproc_params is not None: + # As GenerationExecutor.generate_async does before handing the + # request to the postprocess worker. + postproc_params.postproc_args.num_prompt_tokens = len(promise.prompt_token_ids) + call.result = promise + return promise + + async def get_stats_async(self, timeout: Optional[float] = None) -> AsyncIterator[dict]: + return + yield # pragma: no cover - makes this an async generator + + def get_data_transceiver_state(self) -> None: + return None + + def shutdown(self) -> None: + # Overrides BaseLLM.shutdown, which BaseLLM.__del__ calls. + for name in ("_executor", "_encoder_executor"): + executor = getattr(self, name, None) + if executor is not None: + executor.shutdown() + + +class FakeLLM(_FakeGeneratorMixin, LLM): + """LLM generator fake: the default, CONTEXT, GENERATION and runtime-control roles.""" + + def __init__(self, *, args: FakeLlmArgs, executor: Optional[FakeExecutor] = None) -> None: + self._setup_fake(args=args, executor=executor or FakeExecutor()) + + +class FakeAsyncLLM(_FakeGeneratorMixin, AsyncLLM): + """AsyncLLM generator fake: the RL-control role gate requires AsyncLLM.""" + + def __init__(self, *, args: FakeLlmArgs, executor: Optional[FakeExecutor] = None) -> None: + self._setup_fake(args=args, executor=executor or FakeExecutor()) + + +class FakeMultimodalEncoder(_FakeGeneratorMixin, MultimodalEncoder): + """MultimodalEncoder generator fake: the MM_ENCODER role gate.""" + + def __init__(self, *, args: FakeLlmArgs, executor: Optional[FakeExecutor] = None) -> None: + self._setup_fake(args=args, executor=executor or FakeExecutor()) + + +class FakeEncodeOnlyLLM(FakeLLM): + """Encode-only LLM fake for the EMBEDDING role. + + A production encode-only LLM has no generation executor: ``_build_model`` + returns before creating one and ``_check_health`` reads only + ``_encoder_executor`` in encode-only mode. + """ + + def __init__(self, *, args: FakeLlmArgs) -> None: + self._setup_fake(args=args, executor=None, encode_only=True) + self._encoder_executor = FakeEncoderExecutor() + + def encode(self, token_ids_batch: Any) -> Any: + raise NotImplementedError( + "FakeEncodeOnlyLLM does not encode; script it when a test needs it." + ) + + +class UserProbeMiddleware: + """Pure ASGI no-op, used to check where ``--middleware`` lands in the stack.""" + + def __init__(self, app: Any) -> None: + self.app = app + + async def __call__(self, scope: Any, receive: Any, send: Any) -> None: + await self.app(scope, receive, send) diff --git a/tests/test_common/serve/fakes_visual_gen.py b/tests/test_common/serve/fakes_visual_gen.py new file mode 100644 index 000000000000..c1241fb6df77 --- /dev/null +++ b/tests/test_common/serve/fakes_visual_gen.py @@ -0,0 +1,44 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Fake VisualGen generator for CPU tests of the VISUAL_GEN serving role. + +Kept in its own module so that only tests that build a VisualGen app import the +``tensorrt_llm.visual_gen`` tree: ``OpenAIServer`` detects VisualGen generators +by probing ``sys.modules`` for ``tensorrt_llm.visual_gen.visual_gen``, so +importing this module is what makes ``_is_visual_gen_instance`` able to say yes. +""" + +import itertools +from typing import Any + +from tensorrt_llm.visual_gen.args import VisualGenArgs +from tensorrt_llm.visual_gen.visual_gen import VisualGen + +__all__ = ["FakeVisualGen"] + + +class FakeVisualGen(VisualGen): + """VisualGen generator fake; subclassing keeps ``isinstance`` checks true.""" + + def __init__(self, model: str = "fake-visual-gen") -> None: + # Never run VisualGen.__init__ (it loads a pipeline). VisualGen.shutdown, + # which __del__ calls, returns early when executor is None. + self.model = model + self.args = VisualGenArgs() + self.executor = None + self._req_counter = itertools.count() + + def generate_async(self, *args: Any, **kwargs: Any) -> Any: + raise NotImplementedError("FakeVisualGen does not generate.") diff --git a/tests/test_common/serve/layering.py b/tests/test_common/serve/layering.py new file mode 100644 index 000000000000..aba66f10df46 --- /dev/null +++ b/tests/test_common/serve/layering.py @@ -0,0 +1,222 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Import-direction contracts between serving layers, read from the source tree. + +The import graph is built with ``ast`` from the repository files, not the +installed package, and needs no new dependency. Each package a PR creates adds +its :class:`Contract` to ``tests/unittest/serve/test_layering.py``. +""" + +import ast +from dataclasses import dataclass, field +from pathlib import Path +from typing import FrozenSet, List, Optional, Sequence, Tuple + +__all__ = [ + "Contract", + "ImportEdge", + "build_import_graph", + "check_contracts", + "stale_allowances", +] + + +@dataclass(frozen=True) +class ImportEdge: + importer: str # dotted module of the importing file + imported: str # absolute dotted module (relative imports resolved) + names: Tuple[str, ...] # names of a from-import; () for "import x" + lineno: int + in_function: bool # inside a def or class body (runs at call time) + type_checking: bool # under "if TYPE_CHECKING:" + + +@dataclass(frozen=True) +class Contract: + name: str + importers: Tuple[str, ...] # module prefixes the rule applies to + forbidden: Tuple[str, ...] # imported-module prefixes that are not allowed + allowed: FrozenSet[Tuple[str, str, str]] = field(default_factory=frozenset) + include_type_checking: bool = False + fix: str = "" # printed on failure: which contract, where the code goes + + +def _matches_prefix(module: str, prefix: str) -> bool: + return module == prefix or module.startswith(prefix + ".") + + +class _ImportCollector(ast.NodeVisitor): + def __init__(self, module: str, package: str) -> None: + self._module = module + self._package = package + self._function_depth = 0 + self._type_checking_depth = 0 + self.edges: List[ImportEdge] = [] + + def _add(self, imported: Optional[str], names: Tuple[str, ...], lineno: int) -> None: + if imported is None: + return + self.edges.append( + ImportEdge( + importer=self._module, + imported=imported, + names=names, + lineno=lineno, + in_function=self._function_depth > 0, + type_checking=self._type_checking_depth > 0, + ) + ) + + def visit_Import(self, node: ast.Import) -> None: + for alias in node.names: + self._add(alias.name, (), node.lineno) + + def visit_ImportFrom(self, node: ast.ImportFrom) -> None: + imported = _resolve_relative(self._package, node.level, node.module) + self._add(imported, tuple(alias.name for alias in node.names), node.lineno) + + def visit_Call(self, node: ast.Call) -> None: + # importlib.import_module("") calls are edges with names=(). + target = node.func + is_import_module = ( + isinstance(target, ast.Attribute) + and target.attr == "import_module" + and isinstance(target.value, ast.Name) + and target.value.id == "importlib" + ) or (isinstance(target, ast.Name) and target.id == "import_module") + if is_import_module and node.args and isinstance(node.args[0], ast.Constant): + value = node.args[0].value + if isinstance(value, str): + self._add(value, (), node.lineno) + self.generic_visit(node) + + def visit_If(self, node: ast.If) -> None: + if _is_type_checking_test(node.test): + self._type_checking_depth += 1 + for child in node.body: + self.visit(child) + self._type_checking_depth -= 1 + for child in node.orelse: + self.visit(child) + return + self.generic_visit(node) + + def _visit_scope(self, node) -> None: + self._function_depth += 1 + self.generic_visit(node) + self._function_depth -= 1 + + def visit_FunctionDef(self, node: ast.FunctionDef) -> None: + self._visit_scope(node) + + def visit_AsyncFunctionDef(self, node: ast.AsyncFunctionDef) -> None: + self._visit_scope(node) + + def visit_ClassDef(self, node: ast.ClassDef) -> None: + self._visit_scope(node) + + +def _is_type_checking_test(test: ast.expr) -> bool: + if isinstance(test, ast.Name): + return test.id == "TYPE_CHECKING" + if isinstance(test, ast.Attribute): + return test.attr == "TYPE_CHECKING" + return False + + +def _resolve_relative(package: str, level: int, module: Optional[str]) -> Optional[str]: + if level == 0: + return module + parts = package.split(".") if package else [] + if level - 1 > len(parts): + return None + base = parts[: len(parts) - (level - 1)] + if module: + base.extend(module.split(".")) + return ".".join(base) if base else None + + +def build_import_graph(package_dir: Path, package: str) -> List[ImportEdge]: + """Every import edge of every ``*.py`` under ``package_dir``. + + Module-level and function-level imports, relative imports resolved, and + ``importlib.import_module("")`` calls recorded as edges with + ``names=()``. + """ + edges: List[ImportEdge] = [] + for path in sorted(package_dir.rglob("*.py")): + relative = path.relative_to(package_dir) + parts = [package, *relative.parts] + if parts[-1] == "__init__.py": + parts = parts[:-1] + else: + parts[-1] = parts[-1][: -len(".py")] + module = ".".join(parts) + file_package = module if path.name == "__init__.py" else module.rpartition(".")[0] + try: + tree = ast.parse(path.read_text(errors="replace")) + except SyntaxError: + continue + collector = _ImportCollector(module, file_package) + collector.visit(tree) + edges.extend(collector.edges) + return edges + + +def _edge_triples(edge: ImportEdge) -> List[Tuple[str, str, str]]: + names = edge.names or ("",) + return [(edge.importer, edge.imported, name) for name in names] + + +def check_contracts(edges: Sequence[ImportEdge], contracts: Sequence[Contract]) -> List[str]: + """Violations of each contract, as messages that name the contract and the fix. + + A from-import is matched as ``.``, so ``from pkg import sub`` + and ``from .. import sub`` count as imports of the submodule ``pkg.sub``. + """ + problems = [] + for contract in contracts: + for edge in edges: + if edge.type_checking and not contract.include_type_checking: + continue + if not any(_matches_prefix(edge.importer, prefix) for prefix in contract.importers): + continue + for triple in _edge_triples(edge): + importer, imported, name = triple + target = f"{imported}.{name}" if name else imported + if not any(_matches_prefix(target, prefix) for prefix in contract.forbidden): + continue + if triple in contract.allowed: + continue + problems.append( + f"contract '{contract.name}': {importer} (line {edge.lineno}) imports " + f"`{target}`. {contract.fix}" + ) + return problems + + +def stale_allowances(edges: Sequence[ImportEdge], contracts: Sequence[Contract]) -> List[str]: + """Baseline allowances that match no current import; the baseline only shrinks.""" + live = {triple for edge in edges for triple in _edge_triples(edge)} + problems = [] + for contract in contracts: + for triple in sorted(contract.allowed): + if triple not in live: + importer, imported, name = triple + problems.append( + f"contract '{contract.name}': the allowance ({importer}, {imported}, " + f"{name!r}) matches no import anymore; delete it, the baseline only shrinks." + ) + return problems diff --git a/tests/test_common/serve/middleware.py b/tests/test_common/serve/middleware.py new file mode 100644 index 000000000000..2cedec9a1741 --- /dev/null +++ b/tests/test_common/serve/middleware.py @@ -0,0 +1,42 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Middleware-order snapshot of a trtllm-serve app.""" + +from typing import Dict, List + +__all__ = ["middleware_snapshot"] + + +def middleware_snapshot(app) -> List[Dict]: + """One dict per middleware in ``app.user_middleware``, outermost first. + + Starlette's ``add_middleware`` inserts at position 0, so the last one added + is outermost and ``app.user_middleware`` already lists outermost first. For + a class whose module starts with ``tensorrt_llm.`` the keyword names are + recorded (plus ``expose_headers`` for ``PerfMetricsMiddleware``); for any + other class only the class name is, because third-party keyword names may + change between versions. + """ + snapshot = [] + for middleware in app.user_middleware: + cls = middleware.cls + if cls.__module__.startswith("tensorrt_llm."): + entry = {"class": cls.__name__, "kwargs": sorted(middleware.kwargs)} + if cls.__name__ == "PerfMetricsMiddleware": + entry["expose_headers"] = middleware.kwargs["expose_headers"] + else: + entry = {"class": cls.__name__} + snapshot.append(entry) + return snapshot diff --git a/tests/test_common/serve/routes.py b/tests/test_common/serve/routes.py new file mode 100644 index 000000000000..b4dc02823074 --- /dev/null +++ b/tests/test_common/serve/routes.py @@ -0,0 +1,494 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Route snapshot of every trtllm-serve app configuration. + +A route record is one string: ``" "``: + +- ````: the route's methods, sorted and comma-joined (``GET,HEAD`` for + FastAPI's documentation routes); ``MOUNT`` for a ``Mount``. +- ````: the effective path from :func:`effective_routes`. +- ````: the route's bare class name, on purpose: moving the route class + to another module must not change the snapshot. +- When two routes in one configuration share `` ``, both records + get `` #`` appended so their order can be compared. Names are not + recorded otherwise, so moving a handler into a router does not change the + snapshot. + +Regenerate the reference with:: + + PYTHONPATH=tests python3 -m test_common.serve.routes --write + +run from the repository root with the checkout's build importable. +""" + +import argparse +import sys +import tempfile +from collections import Counter +from dataclasses import dataclass +from pathlib import Path +from typing import Dict, List, Literal, Optional, Sequence, Tuple, Union + +import yaml +from fastapi import FastAPI + +from tensorrt_llm.llmapi.disagg_utils import ServerRole +from test_common.serve.app_factory import ( + AggConfig, + CoordinatorConfig, + DisaggConfig, + isolated_serve_env, +) + +__all__ = [ + "CONFIGS", + "VISUAL_GEN_CONFIGS", + "SnapshotConfig", + "compare", + "effective_routes", + "read_reference", + "reference_path", + "route_record", + "snapshot_config", + "snapshot_routes", + "write_reference", +] + +REPO_ROOT = Path(__file__).resolve().parents[3] + +REFERENCE_HEADER = """\ +# Routes of every trtllm-serve app configuration. Generated, do not edit by hand: +# PYTHONPATH=tests python3 -m test_common.serve.routes --write +# Each route is " ", in registration order. "#" is +# added only when two routes share methods and path. The checker compares the order +# only for routes that can match the same request. Changing this file changes the +# HTTP surface of trtllm-serve; the API review committee approves it. +""" + + +def reference_path(repo_root: Path = REPO_ROOT) -> Path: + return ( + repo_root + / "tests" + / "unittest" + / "api_stability" + / "references" + / "trtllm_serve_routes.yaml" + ) + + +# --------------------------------------------------------------------------- +# Walking routes +# --------------------------------------------------------------------------- + + +def effective_routes(app_or_routes, prefix: str = "") -> list: + """(effective path, leaf route) in match order, on FastAPI 0.136.x and 0.139.x. + + FastAPI 0.139 keeps one ``_IncludedRouter`` object per ``include_router`` + call in ``app.routes``; it has no ``path`` attribute, so reading ``.path`` + off ``app.routes`` raises once any router is included. This walks into such + objects and applies their include prefix. On 0.136.x included routes are + already flat, so the recursion never runs and the result equals + ``app.routes``. The duck-typed check below uses two attribute names of a + private FastAPI class; if a later FastAPI renames them, + ``test_effective_routes_flattens_included_routers`` fails first, naming this + function. + """ + routes = app_or_routes.routes if isinstance(app_or_routes, FastAPI) else app_or_routes + out = [] + for route in routes: + included = getattr(route, "original_router", None) + context = getattr(route, "include_context", None) + if included is not None and context is not None: # FastAPI 0.139 _IncludedRouter + out.extend(effective_routes(included.routes, prefix + context.prefix)) + continue + # Mounts keep their path and are not descended into. + out.append((prefix + getattr(route, "path", ""), route)) + return out + + +def route_record(path: str, route) -> str: + """``" "`` for one route, without the ``#`` suffix.""" + methods = getattr(route, "methods", None) + methods_text = ",".join(sorted(methods)) if methods else "MOUNT" + return f"{methods_text} {path} {type(route).__name__}" + + +def snapshot_routes(app: FastAPI) -> List[str]: + """Route records of ``app`` in registration order, disambiguated by name.""" + pairs = effective_routes(app) + records = [route_record(path, route) for path, route in pairs] + key_counts = Counter(record.rsplit(" ", 1)[0] for record in records) + out = [] + for record, (path, route) in zip(records, pairs): + methods_and_path = record.rsplit(" ", 1)[0] + if key_counts[methods_and_path] > 1: + record = f"{record} #{getattr(route, 'name', '')}" + out.append(record) + return out + + +# --------------------------------------------------------------------------- +# Configuration matrix +# --------------------------------------------------------------------------- + + +@dataclass(frozen=True) +class SnapshotConfig: + name: str + kind: Literal["openai_server", "disagg_server", "coordinator_server"] + build: Union[AggConfig, DisaggConfig, CoordinatorConfig] + + +CONFIGS: Tuple[SnapshotConfig, ...] = ( + SnapshotConfig("llm", "openai_server", AggConfig()), + SnapshotConfig("llm_context", "openai_server", AggConfig(role=ServerRole.CONTEXT)), + SnapshotConfig("llm_generation", "openai_server", AggConfig(role=ServerRole.GENERATION)), + SnapshotConfig("llm_gpt_oss", "openai_server", AggConfig(model_type="gpt_oss")), + SnapshotConfig( + "llm_gpt_oss_harmony_disabled", + "openai_server", + AggConfig(model_type="gpt_oss", env=(("DISABLE_HARMONY_ADAPTER", "1"),)), + ), + SnapshotConfig("llm_governor", "openai_server", AggConfig(governor_queue=True)), + SnapshotConfig("llm_rl_control", "openai_server", AggConfig(rl_control=True)), + SnapshotConfig("llm_runtime_control", "openai_server", AggConfig(runtime_control=True)), + SnapshotConfig( + "llm_rl_and_runtime_control", + "openai_server", + AggConfig(rl_control=True, runtime_control=True), + ), + SnapshotConfig("llm_perf_metrics", "openai_server", AggConfig(return_perf_metrics=True)), + SnapshotConfig( + "llm_perf_metrics_enable_metrics_env", + "openai_server", + AggConfig(return_perf_metrics=True, env=(("ENABLE_METRICS", "true"),)), + ), + SnapshotConfig( + "llm_perf_metrics_output_dir_only", + "openai_server", + AggConfig(perf_metrics_output_dir=True), + ), + SnapshotConfig( + "llm_render_endpoints", + "openai_server", + AggConfig(env=(("TRTLLM_ENABLE_RENDER_ENDPOINTS", "1"),)), + ), + # An attached frontend of a multi-frontend server registers the launcher + # forwarding routes before the local table; same method and path, so + # registration order decides which handler serves them. + SnapshotConfig( + "llm_multi_frontend_attached", + "openai_server", + AggConfig(multi_frontend_attached=True), + ), + SnapshotConfig("mm_encoder", "openai_server", AggConfig(role=ServerRole.MM_ENCODER)), + SnapshotConfig( + "mm_encoder_rl_control", + "openai_server", + AggConfig(role=ServerRole.MM_ENCODER, rl_control=True), + ), + SnapshotConfig("embedding", "openai_server", AggConfig(role=ServerRole.EMBEDDING)), + SnapshotConfig( + "embedding_runtime_control", + "openai_server", + AggConfig(role=ServerRole.EMBEDDING, runtime_control=True), + ), + SnapshotConfig("disagg_local", "disagg_server", DisaggConfig()), + SnapshotConfig( + "disagg_local_perf_metrics", "disagg_server", DisaggConfig(return_perf_metrics=True) + ), + SnapshotConfig( + "disagg_local_http_cluster_storage", + "disagg_server", + DisaggConfig(http_cluster_storage=True), + ), + SnapshotConfig("disagg_fleet", "disagg_server", DisaggConfig(fleet=True)), + SnapshotConfig( + "disagg_fleet_perf_metrics", + "disagg_server", + DisaggConfig(fleet=True, return_perf_metrics=True), + ), + SnapshotConfig( + "disagg_fleet_http_cluster_storage", + "disagg_server", + DisaggConfig(fleet=True, http_cluster_storage=True), + ), + SnapshotConfig("coordinator", "coordinator_server", CoordinatorConfig()), + SnapshotConfig( + "coordinator_http_cluster_storage", + "coordinator_server", + CoordinatorConfig(http_cluster_storage=True), + ), +) + +VISUAL_GEN_CONFIGS: Tuple[SnapshotConfig, ...] = ( + SnapshotConfig( + "visual_gen", + "openai_server", + AggConfig(role=ServerRole.VISUAL_GEN, model_name="fake-visual-gen"), + ), +) + + +def snapshot_config(config: SnapshotConfig, tmp_dir: Path) -> Dict: + """``{"kind": ..., "routes": [...]}`` or ``{"kind": ..., "error": ": "}``.""" + with isolated_serve_env(tmp_dir) as env: + try: + if config.kind == "openai_server": + app = env.build_openai_server(config.build).app + elif config.kind == "disagg_server": + app = env.build_disagg_server(config.build).app + else: + app = env.build_coordinator_server(config.build).app + except ValueError as error: + return {"kind": config.kind, "error": f"{type(error).__name__}: {error}"} + return {"kind": config.kind, "routes": snapshot_routes(app)} + + +# --------------------------------------------------------------------------- +# Comparison +# --------------------------------------------------------------------------- + + +def _parse_record(record: str) -> Tuple[str, str, str, str]: + """(methods, path, class, name) of one record; name is "" when absent.""" + parts = record.split(" ") + methods, path, cls = parts[0], parts[1], parts[2] + name = parts[3][1:] if len(parts) > 3 and parts[3].startswith("#") else "" + return methods, path, cls, name + + +def _literal_prefix(path: str) -> str: + """The path up to its first ``{``.""" + brace = path.find("{") + return path if brace < 0 else path[:brace] + + +def _paths_can_match_same_request(path_a: str, path_b: str) -> bool: + segments_a = path_a.split("/") + segments_b = path_b.split("/") + for i in range(max(len(segments_a), len(segments_b))): + a = segments_a[i] if i < len(segments_a) else None + b = segments_b[i] if i < len(segments_b) else None + # A {name:path} parameter matches the rest of the path. + if a is not None and "{" in a and a.rstrip("}").endswith(":path"): + return True + if b is not None and "{" in b and b.rstrip("}").endswith(":path"): + return True + if a is None or b is None: + # Different segment counts with no path parameter: no overlap. + return False + if "{" in a or "{" in b: + continue # a parameter matches any literal + if a != b: + return False + return True + + +def _records_conflict(record_a: str, record_b: str) -> bool: + """Whether two records can match the same request (over-approximated). + + Two records conflict when (a) their methods intersect or either is a + mount, and (b) their path templates can match one request path. + Over-approximating conflicts only locks more pairs, which is safe. + """ + methods_a, path_a, _, _ = _parse_record(record_a) + methods_b, path_b, _, _ = _parse_record(record_b) + a_is_mount = methods_a == "MOUNT" + b_is_mount = methods_b == "MOUNT" + if not a_is_mount and not b_is_mount: + if not set(methods_a.split(",")) & set(methods_b.split(",")): + return False + return _paths_can_match_same_request(path_a, path_b) + # A mount at P conflicts with every route whose literal prefix starts + # with P, or that P starts with. + if a_is_mount and b_is_mount: + return path_a.startswith(path_b) or path_b.startswith(path_a) + mount_path = path_a if a_is_mount else path_b + other_prefix = _literal_prefix(path_b if a_is_mount else path_a) + return other_prefix.startswith(mount_path) or mount_path.startswith(other_prefix) + + +def compare(expected: Sequence[str], actual: Sequence[str]) -> List[str]: + """Human-readable differences between the reference and the live records.""" + differences: List[str] = [] + expected_counts = Counter(expected) + actual_counts = Counter(actual) + removed = list((expected_counts - actual_counts).elements()) + added = list((actual_counts - expected_counts).elements()) + + # A removed and an added record with the same methods and path but another + # class are one "route class changed" line. + def _methods_path(record: str) -> str: + methods, path, _, _ = _parse_record(record) + return f"{methods} {path}" + + remaining_added = list(added) + class_changes = [] + for removed_record in list(removed): + for added_record in remaining_added: + if _methods_path(added_record) == _methods_path(removed_record): + old_cls = _parse_record(removed_record)[2] + new_cls = _parse_record(added_record)[2] + why = ( + " (a plain APIRouter breaks msgpack bodies from the disaggregated frontend)" + if old_cls == "_MsgspecRoute" + else "" + ) + class_changes.append( + f"route class changed: {_methods_path(removed_record)}: " + f"{old_cls} -> {new_cls}{why}" + ) + removed.remove(removed_record) + remaining_added.remove(added_record) + break + for record in remaining_added: + differences.append(f"added: {record}") + for record in removed: + differences.append(f"removed: {record}") + differences.extend(class_changes) + + # Conflict-relevant order: for every conflicting pair a-before-b in + # expected, a must come before b in actual, when both are present. For + # repeated identical records, the k-th occurrence pairs with the k-th. + actual_positions: Dict[str, List[int]] = {} + for position, record in enumerate(actual): + actual_positions.setdefault(record, []).append(position) + expected_occurrence: List[Optional[int]] = [] + seen: Counter = Counter() + for record in expected: + positions = actual_positions.get(record, []) + occurrence = seen[record] + seen[record] += 1 + expected_occurrence.append(positions[occurrence] if occurrence < len(positions) else None) + for i, record_a in enumerate(expected): + position_a = expected_occurrence[i] + if position_a is None: + continue + for j in range(i + 1, len(expected)): + record_b = expected[j] + position_b = expected_occurrence[j] + if position_b is None or record_a == record_b: + continue + if _records_conflict(record_a, record_b) and position_a > position_b: + differences.append( + f"order changed: {record_a} must come before {record_b} " + "(FastAPI matches in registration order)" + ) + return differences + + +def format_failure(name: str, differences: Sequence[str]) -> str: + lines = "\n".join(f" {difference}" for difference in differences) + return ( + f"Route snapshot of configuration '{name}' differs from " + "tests/unittest/api_stability/references/trtllm_serve_routes.yaml:\n" + f"{lines}\n" + "If the change is intended, regenerate with " + "`PYTHONPATH=tests python3 -m test_common.serve.routes --write`, commit the YAML, " + "and request review from @NVIDIA/trt-llm-noncommitted-api-review-committee " + "(owner of tests/unittest/api_stability/). New endpoints are a router and a " + "serving class under tensorrt_llm/serve/api///: create the " + "router with make_router() and add a RouterSpec to ROUTERS " + "(tensorrt_llm/serve/_base/routing.py). Do not add routes or methods to " + "OpenAIServer; see tensorrt_llm/serve/AGENTS.md." + ) + + +# --------------------------------------------------------------------------- +# Reference file +# --------------------------------------------------------------------------- + + +def build_reference_data(tmp_root: Path) -> Dict: + configs: Dict[str, Dict] = {} + for index, config in enumerate(CONFIGS + VISUAL_GEN_CONFIGS): + configs[config.name] = snapshot_config(config, tmp_root / f"cfg{index}") + return {"version": 1, "configs": configs} + + +def write_reference(data: Dict, path: Optional[Path] = None) -> Path: + path = path or reference_path() + body = yaml.safe_dump(data, sort_keys=False, width=4096) + path.write_text(REFERENCE_HEADER + body) + return path + + +def read_reference(path: Optional[Path] = None) -> Dict: + path = path or reference_path() + return yaml.safe_load(path.read_text()) + + +def main(argv: Optional[Sequence[str]] = None) -> int: + parser = argparse.ArgumentParser( + prog="python3 -m test_common.serve.routes", + description="Check, rewrite or print the trtllm-serve route reference.", + ) + parser.add_argument( + "--write", action="store_true", help="rebuild every configuration and rewrite the reference" + ) + parser.add_argument( + "--print", + dest="print_name", + metavar="CONFIG", + help="print one configuration's live records", + ) + args = parser.parse_args(argv) + + by_name = {config.name: config for config in CONFIGS + VISUAL_GEN_CONFIGS} + with tempfile.TemporaryDirectory() as tmp: + tmp_root = Path(tmp) + if args.print_name: + if args.print_name not in by_name: + print(f"unknown configuration '{args.print_name}'; one of: {sorted(by_name)}") + return 2 + snapshot = snapshot_config(by_name[args.print_name], tmp_root / "print") + for line in snapshot.get("routes", [snapshot.get("error", "")]): + print(line) + return 0 + data = build_reference_data(tmp_root) + if args.write: + path = write_reference(data) + print(f"wrote {path}") + return 0 + reference = read_reference() + exit_code = 0 + for name, live in data["configs"].items(): + recorded = reference["configs"].get(name) + if recorded is None: + print(f"configuration '{name}' missing from the reference") + exit_code = 1 + continue + if recorded.get("error") != live.get("error"): + print( + f"configuration '{name}': error changed: " + f"{recorded.get('error')!r} -> {live.get('error')!r}" + ) + exit_code = 1 + differences = compare(recorded.get("routes", []), live.get("routes", [])) + if differences: + print(format_failure(name, differences)) + exit_code = 1 + stale = set(reference["configs"]) - set(data["configs"]) + if stale: + print(f"configurations only in the reference: {sorted(stale)}") + exit_code = 1 + return exit_code + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/test_common/serve/shims.py b/tests/test_common/serve/shims.py new file mode 100644 index 000000000000..98ae1a1cfa04 --- /dev/null +++ b/tests/test_common/serve/shims.py @@ -0,0 +1,376 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Shim identity, FutureWarning and old-path-import checks for moved serve modules. + +A module move keeps the old path only when code outside this repository imports +it. Such a kept shim re-exports the public names (each the same object as at the +new path), warns once with ``FutureWarning``, and code inside the repository +must import the new path. These checks hold all three properties; the PR that +creates a shim adds its :class:`ShimRow` rows to the tables in +``tests/unittest/serve/test_shim_identity.py``. +""" + +import ast +import importlib +import re +import sys +import warnings +from dataclasses import dataclass +from pathlib import Path +from typing import Dict, List, Optional, Sequence, Tuple + +__all__ = [ + "SCAN_ROOTS", + "ShimRow", + "check_identity", + "check_warnings", + "find_old_path_imports", +] + +SCAN_ROOTS = ("tensorrt_llm", "examples", "scripts", "triton_backend", "docs", "setup.py") + + +@dataclass(frozen=True) +class ShimRow: + """One re-exported name of one kept old path.""" + + old_module: str # "tensorrt_llm.serve.openai_disagg_server" + name: str # "OpenAIDisaggServer"; public names only, except in interface rows + new_module: str # "tensorrt_llm.serve.disagg.openai_disagg_server" + retire_in: str # release that removes the shim; "not retired" for an interface row + ban_old_path: bool = True # False: repo code may keep importing name from old_module + warns: bool = True # False: the re-export is the module's own interface, not a shim + + +# --------------------------------------------------------------------------- +# Identity +# --------------------------------------------------------------------------- + + +def check_identity(rows: Sequence[ShimRow]) -> List[str]: + """Each old-path name must be the same object as the new-path name. + + Identity only, never ``__module__``: some re-exported names are dicts or + constants. + """ + problems = [] + for row in rows: + old_module = importlib.import_module(row.old_module) + new_module = importlib.import_module(row.new_module) + try: + old_object = getattr(old_module, row.name) + except AttributeError: + problems.append( + f"`{row.old_module}.{row.name}` no longer exists: the re-export was removed, " + "probably by autoflake or ruff during pre-commit, which drop an import that " + f"`__all__` does not list. Restore `from {row.new_module} import {row.name}` in " + f"{row.old_module.replace('.', '/')}.py and list the name in `__all__` (a pure " + "shim), or restore its row in `_LAZY_NAMES` (`commands/serve.py`)." + ) + continue + new_object = getattr(new_module, row.name) + if old_object is not new_object: + problems.append( + f"`{row.old_module}.{row.name}` is not the same object as " + f"`{row.new_module}.{row.name}`. The old module must re-export the object, " + "not define a copy." + ) + return problems + + +# --------------------------------------------------------------------------- +# FutureWarning +# --------------------------------------------------------------------------- + +_IMPORT_WARNING = re.compile( + r"^(?P[A-Za-z0-9_.]+) has moved to (?P[A-Za-z0-9_.]+) " + r"and will be removed in (?P\S+?)\.$" +) +_READ_WARNING = re.compile( + r"^(?P[A-Za-z0-9_.]+)\.(?P[A-Za-z0-9_]+) has moved to " + r"(?P[A-Za-z0-9_.]+) and will be removed in (?P\S+?)\.$" +) + + +def _matching_warnings(caught, prefix: str) -> List[str]: + """Messages of the FutureWarnings that start with ``prefix``. + + Filtering by message, as ``tests/unittest/_torch/peft/test_shim_peft.py`` + does, also drops the warning of a parent shim package that a fresh import of + one of its submodules emits. + """ + return [ + str(record.message) + for record in caught + if issubclass(record.category, FutureWarning) and str(record.message).startswith(prefix) + ] + + +def _no_warning_message(old_module: str, where: str, name: str = "") -> str: + what = f"reading `{old_module}.{name}`" if where == "read" else f"importing `{old_module}`" + return ( + f"{what} emitted no FutureWarning. A kept shim warns once with " + "warnings.warn(..., FutureWarning, stacklevel=2): the TRT-LLM logger defaults to level " + "error, so a logged warning would not reach callers outside the repository. Restore " + "that call." + ) + + +def check_warnings(rows: Sequence[ShimRow]) -> List[str]: + """Each kept shim warns once with the expected FutureWarning text. + + A pure shim (no ``_LAZY_NAMES``) warns exactly once at import with + `` has moved to and will be removed in .``, + where ```` is the row's new module or a package that contains it, + and never on reads. A ``_LAZY_NAMES`` module warns never at import and + exactly once on the first read of each lazy name; a name it imports eagerly + never warns. Rows with ``warns=False`` (interface rows) are skipped. + + Imports each old module fresh (a module body runs once per process) and + puts any previously imported module object back in ``sys.modules`` and on + its parent package, so later tests keep the objects they imported. + """ + problems: List[str] = [] + by_module: Dict[str, List[ShimRow]] = {} + for row in rows: + if row.warns: + by_module.setdefault(row.old_module, []).append(row) + + for module_name, module_rows in by_module.items(): + saved = sys.modules.get(module_name) + if saved is not None: + del sys.modules[module_name] + try: + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + module = importlib.import_module(module_name) + import_messages = _matching_warnings(caught, f"{module_name} has moved to ") + lazy_names = getattr(module, "_LAZY_NAMES", None) + + if lazy_names is None: + problems.extend( + _check_pure_shim_import(module_name, module_rows, import_messages) + ) + elif import_messages: + problems.append( + f"importing `{module_name}` emitted a FutureWarning; trtllm-serve " + "imports commands/serve.py on every start, so it may warn only when a " + "moved name is read." + ) + + for row in module_rows: + is_lazy_name = lazy_names is not None and row.name in lazy_names + for read_index in (1, 2): + before = len(caught) + getattr(module, row.name) + read_messages = _matching_warnings( + caught[before:], f"{module_name}.{row.name} has moved to " + ) + if is_lazy_name and read_index == 1: + problems.extend(_check_lazy_first_read(row, read_messages)) + elif read_messages: + problems.append( + f"the FutureWarning of `{module_name}` says " + f"`{read_messages[0]}`; expected no warning on this read of " + f"`{row.name}`." + ) + finally: + if saved is not None: + sys.modules[module_name] = saved + parent_name, _, tail = module_name.rpartition(".") + if parent_name and parent_name in sys.modules: + setattr(sys.modules[parent_name], tail, saved) + return problems + + +def _check_pure_shim_import( + module_name: str, module_rows: Sequence[ShimRow], import_messages: List[str] +) -> List[str]: + if not import_messages: + return [_no_warning_message(module_name, "import")] + problems = [] + if len(import_messages) > 1: + problems.append( + f"importing `{module_name}` emitted {len(import_messages)} FutureWarnings; a pure " + "shim warns exactly once, at import." + ) + message = import_messages[0] + match = _IMPORT_WARNING.match(message) + retire_in = module_rows[0].retire_in + expected = f"{module_name} has moved to and will be removed in {retire_in}." + if match is None or match.group("release") != retire_in: + problems.append( + f"the FutureWarning of `{module_name}` says `{message}`; expected `{expected}`: it " + "names the new location and the removal release." + ) + return problems + location = match.group("location") + for row in module_rows: + if not (row.new_module == location or row.new_module.startswith(location + ".")): + problems.append( + f"the FutureWarning of `{module_name}` says `{message}`; expected a location " + f"that contains `{row.new_module}`: it names the new location and the removal " + "release." + ) + return problems + + +def _check_lazy_first_read(row: ShimRow, read_messages: List[str]) -> List[str]: + if not read_messages: + return [_no_warning_message(row.old_module, "read", row.name)] + expected = ( + f"{row.old_module}.{row.name} has moved to {row.new_module} " + f"and will be removed in {row.retire_in}." + ) + if read_messages != [expected]: + return [ + f"the FutureWarning of `{row.old_module}` says `{read_messages[0]}`; expected " + f"`{expected}`: it names the new location and the removal release." + ] + return [] + + +# --------------------------------------------------------------------------- +# Old-path import ban +# --------------------------------------------------------------------------- + + +def _module_name_of(path: Path, repo_root: Path) -> str: + relative = path.relative_to(repo_root) + parts = list(relative.parts) + if parts[-1] == "__init__.py": + parts = parts[:-1] + else: + parts[-1] = parts[-1][: -len(".py")] + return ".".join(parts) + + +def _package_of(path: Path, repo_root: Path) -> str: + module = _module_name_of(path, repo_root) + if path.name == "__init__.py": + return module + return module.rpartition(".")[0] + + +def _resolve_relative(package: str, level: int, module: Optional[str]) -> Optional[str]: + if level == 0: + return module + parts = package.split(".") if package else [] + if level - 1 > len(parts): + return None + base = parts[: len(parts) - (level - 1)] + if module: + base.append(module) + return ".".join(base) if base else None + + +def find_old_path_imports( + rows: Sequence[ShimRow], repo_root: Path, roots: Sequence[str] = SCAN_ROOTS +) -> List[str]: + """Imports of banned names from kept old paths, anywhere under ``roots``. + + Flags ``from import `` (absolute, or relative resolved + against the file's package) and ``.`` attribute access where + ```` is bound to the old module in that file. Importing an old module + that still has code is allowed; only the banned names are flagged. The old + module's own file is exempt, and ``tests/`` is not scanned. + """ + banned: Dict[str, set] = {} + for row in rows: + if row.ban_old_path: + banned.setdefault(row.old_module, set()).add(row.name) + if not banned: + return [] + + retire_by_module = {row.old_module: row.retire_in for row in rows} + new_by_module_name: Dict[Tuple[str, str], str] = { + (row.old_module, row.name): row.new_module for row in rows + } + problems: List[str] = [] + files: List[Path] = [] + for root in roots: + root_path = repo_root / root + if root_path.is_file(): + files.append(root_path) + elif root_path.is_dir(): + files.extend(sorted(root_path.rglob("*.py"))) + + for path in files: + text = path.read_text(errors="replace") + # Cheap prefilter: parse only files that mention an old module. + if not any(module.rsplit(".", 1)[-1] in text for module in banned): + continue + try: + tree = ast.parse(text) + except SyntaxError: + continue + file_module = _module_name_of(path, repo_root) + exempt_modules = {module for module in banned if file_module == module} + package = _package_of(path, repo_root) + + aliases: Dict[str, str] = {} # local name -> old module it is bound to + hits: List[Tuple[int, str, str]] = [] # (line, old module, name) + + for node in ast.walk(tree): + if isinstance(node, ast.Import): + for alias in node.names: + if alias.name in banned and alias.name not in exempt_modules and alias.asname: + aliases[alias.asname] = alias.name + elif isinstance(node, ast.ImportFrom): + resolved = _resolve_relative(package, node.level, node.module) + if resolved is None: + continue + for alias in node.names: + if resolved in banned and resolved not in exempt_modules: + if alias.name in banned[resolved]: + hits.append((node.lineno, resolved, alias.name)) + # `from import ` binds the module. + candidate = f"{resolved}.{alias.name}" + if candidate in banned and candidate not in exempt_modules: + aliases[alias.asname or alias.name] = candidate + + for node in ast.walk(tree): + if not isinstance(node, ast.Attribute): + continue + dotted = _dotted_name(node) + if dotted is None: + continue + prefix, _, attribute = dotted.rpartition(".") + bound = aliases.get(prefix) + if bound is None and prefix in banned and prefix not in exempt_modules: + bound = prefix # the dotted `import ` used as `.` + if bound is not None and attribute in banned.get(bound, ()): + hits.append((node.lineno, bound, attribute)) + + for lineno, module, name in sorted(set(hits)): + problems.append( + f"{path.relative_to(repo_root)}:{lineno} imports `{name}` from the old path " + f"`{module}`; import it from `{new_by_module_name[(module, name)]}`. The old " + "path is kept only for callers outside the repository until " + f"{retire_by_module[module]}." + ) + return problems + + +def _dotted_name(node: ast.Attribute) -> Optional[str]: + parts = [node.attr] + value = node.value + while isinstance(value, ast.Attribute): + parts.append(value.attr) + value = value.value + if isinstance(value, ast.Name): + parts.append(value.id) + return ".".join(reversed(parts)) + return None diff --git a/tests/unittest/_torch/visual_gen/test_benchmark_visual_gen.py b/tests/unittest/_torch/visual_gen/test_benchmark_visual_gen.py index 07788843aeae..5c53692d6f09 100644 --- a/tests/unittest/_torch/visual_gen/test_benchmark_visual_gen.py +++ b/tests/unittest/_torch/visual_gen/test_benchmark_visual_gen.py @@ -21,6 +21,10 @@ import pytest +from tensorrt_llm.serve.api.visual_gen.metrics import ( + build_visual_gen_server_timings, + build_visual_gen_timing_headers, +) from tensorrt_llm.serve.scripts.benchmark_visual_gen import ( REFERENCE_KEYS, SCALAR_PARAM_FIELDS, @@ -37,10 +41,6 @@ build_visual_gen_result, load_workload, ) -from tensorrt_llm.serve.visual_gen_metrics import ( - build_visual_gen_server_timings, - build_visual_gen_timing_headers, -) PNG = base64.b64decode( "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO7Z4h8AAAAASUVORK5CYII=" diff --git a/tests/unittest/_torch/visual_gen/test_trtllm_serve_endpoints.py b/tests/unittest/_torch/visual_gen/test_trtllm_serve_endpoints.py index f0ce2de17187..c30697fc6e71 100644 --- a/tests/unittest/_torch/visual_gen/test_trtllm_serve_endpoints.py +++ b/tests/unittest/_torch/visual_gen/test_trtllm_serve_endpoints.py @@ -3,8 +3,8 @@ """trtllm-serve visual_gen endpoints tests. -Tests all endpoints registered for the VISUAL_GEN server role -in OpenAIServer.register_visual_gen_routes(): +Tests all endpoints of the VISUAL_GEN server role, served by ``ImageServing`` +and ``VideoServing`` in ``tensorrt_llm/serve/api/visual_gen/``: POST /v1/images/generations POST /v1/images/edits @@ -37,10 +37,10 @@ from PIL import Image from tensorrt_llm._utils import AdjustedSteadyClock -from tensorrt_llm.serve.openai_protocol import VideoJob -from tensorrt_llm.serve.openai_server import _normalize_image_output -from tensorrt_llm.serve.visual_gen_metrics import SERVER_TIMING_HEADER -from tensorrt_llm.serve.visual_gen_utils import VIDEO_STORE +from tensorrt_llm.serve.api.visual_gen.metrics import SERVER_TIMING_HEADER +from tensorrt_llm.serve.api.visual_gen.protocol import VideoJob +from tensorrt_llm.serve.api.visual_gen.serving_images import _normalize_image_output +from tensorrt_llm.serve.api.visual_gen.utils import VIDEO_STORE from tensorrt_llm.visual_gen.output import VisualGenMetrics, VisualGenOutput from tensorrt_llm.visual_gen.params import prepare_reference_slots, validate_visual_gen_params @@ -749,9 +749,9 @@ def test_a_server_starts_from_a_working_directory_it_cannot_write_to(tmp_path, m def test_servers_starting_in_the_same_second_get_separate_directories(tmp_path): """The stamp has one-second resolution, so two servers that start together would otherwise share a directory and interleave their media.""" - from tensorrt_llm.serve.openai_server import _new_media_dir + from tensorrt_llm.serve.api.visual_gen.media import _new_media_dir - with patch("tensorrt_llm.serve.openai_server.datetime") as clock: + with patch("tensorrt_llm.serve.api.visual_gen.media.datetime") as clock: clock.now.return_value = datetime(2026, 9, 15, 7, 12, 38) first = _new_media_dir(tmp_path) second = _new_media_dir(tmp_path) @@ -1080,7 +1080,7 @@ def test_image_generation_b64_with_4d_batch_pipeline_output(self, tmp_path): client = _create_server(gen) with ( patch( - "tensorrt_llm.serve.openai_server.image_to_bytes", + "tensorrt_llm.serve.api.visual_gen.serving_images.image_to_bytes", wraps=image_to_bytes, ) as mock_cvt, patch("tensorrt_llm.media.encoding.save_image") as mock_save, @@ -1503,7 +1503,7 @@ def test_image_edit_rejects_excessive_output_fanout(self, tmp_path, monkeypatch) def test_image_edit_rejects_oversized_base64_image_before_decode(self, tmp_path, monkeypatch): """Base64 image size is capped before allocating decoded bytes.""" - from tensorrt_llm.serve import visual_gen_utils + from tensorrt_llm.serve.api.visual_gen import utils as visual_gen_utils client, gen = self._client(tmp_path, monkeypatch) monkeypatch.setattr(visual_gen_utils, "IMAGE_EDIT_MAX_IMAGE_BYTES", 8) @@ -2635,6 +2635,176 @@ def test_async_video_route_rejects_validation_error_synchronously(self, tmp_path os.environ.pop("TRTLLM_MEDIA_STORAGE_PATH", None) +# ========================================================================= +# The visual-gen validation-error envelope (both entry points) +# ========================================================================= + + +class TestVisualGenValidationErrorRendering: + """Characterize the visual-gen 422 envelope at both entry points. + + Routes with a declared request model fail with FastAPI's + ``RequestValidationError``; handlers that build their own request + model (video sync/async, image edit, multipart) fail with pydantic's + ``ValidationError``. Every path must render byte-identical bodies. + These tests pin the full body, so they must pass unchanged before + and after any refactor of the rendering code. + """ + + # The exact envelope every unknown-field request below must produce. + _UNKNOWN_FIELD_BODY = { + "object": "error", + "message": "Unknown request field 'not_a_field'. Pass model-specific " + "parameters via 'extra_params' instead.", + "type": "BadRequestError", + "param": None, + "code": 422, + } + + def test_route_level_unknown_field_body_is_exact(self, image_client): + """``POST /v1/images/generations`` declares its request model, so an + unknown field arrives as a ``RequestValidationError``; the body is + pinned in full.""" + resp = image_client.post( + "/v1/images/generations", + json={"prompt": "a cat", "not_a_field": 1}, + ) + assert resp.status_code == 422 + assert resp.json() == self._UNKNOWN_FIELD_BODY + + def test_route_level_type_error_names_the_field(self, image_client): + """A type error reads ``: ``. The expected + message is computed from the model in the test, so the assertion + does not hard-code pydantic's wording.""" + from pydantic import ValidationError + + from tensorrt_llm.serve.openai_protocol import ImageGenerationRequest + + payload = {"prompt": "a cat", "seed": "abc"} + with pytest.raises(ValidationError) as exc_info: + ImageGenerationRequest.model_validate(payload) + expected_msg = exc_info.value.errors()[0]["msg"] + + resp = image_client.post("/v1/images/generations", json=payload) + assert resp.status_code == 422 + body = resp.json() + _assert_llm_envelope(body, code=422) + assert body["message"] == f"seed: {expected_msg}" + + def test_handler_level_bodies_match_route_level(self, tmp_path, monkeypatch): + """Handlers that build their own request model (video sync JSON, + video async JSON, image edit JSON) return the same 422 body as the + route-level path.""" + monkeypatch.setenv("TRTLLM_MEDIA_STORAGE_PATH", str(tmp_path)) + + video_client = _create_server(MockVisualGen(video_output=_make_dummy_video_tensor())) + for url in ("/v1/videos/sync", "/v1/videos"): + resp = video_client.post(url, json={"prompt": "a cat", "not_a_field": 1}) + assert resp.status_code == 422, (url, resp.text) + assert resp.json() == self._UNKNOWN_FIELD_BODY, url + + edit_client = _create_server( + MockVisualGen( + image_output=_make_dummy_image_tensor(), + supports_image_edit=True, + ) + ) + resp = edit_client.post( + "/v1/images/edits", + json={"prompt": "a cat", "image": _b64_white_png_1x1(), "not_a_field": 1}, + ) + assert resp.status_code == 422, resp.text + assert resp.json() == self._UNKNOWN_FIELD_BODY + + def test_multipart_handler_level_body_is_exact(self, video_client): + """The multipart path funnels through the same pydantic model and + renders the same envelope. The unknown field is sent as a plain + multipart text part (no filename) so it is the only validation + error and the body matches the route-level one byte for byte.""" + resp = video_client.post( + "/v1/videos/sync", + data={"prompt": "a cat"}, + files={"not_a_field": (None, "1")}, + ) + assert resp.status_code == 422, resp.text + assert resp.json() == self._UNKNOWN_FIELD_BODY + + @staticmethod + def _pydantic_unknown_field_error(): + """Return the pydantic ValidationError for an unknown field.""" + from pydantic import ValidationError + + from tensorrt_llm.serve.openai_protocol import ImageGenerationRequest + + with pytest.raises(ValidationError) as exc_info: + ImageGenerationRequest.model_validate({"prompt": "x", "not_a_field": 1}) + return exc_info.value + + def test_renderer_accepts_both_exception_types(self): + """The shared renderer produces the same status and bytes for a + pydantic ``ValidationError`` and for a ``RequestValidationError`` + whose ``loc`` entries carry FastAPI's leading ``body`` segment.""" + from fastapi.exceptions import RequestValidationError + + from tensorrt_llm.serve.api.visual_gen.errors import render_visual_gen_validation_error + from tensorrt_llm.serve.openai_server import OpenAIServer + + pydantic_exc = self._pydantic_unknown_field_error() + fastapi_exc = RequestValidationError( + errors=[{**err, "loc": ("body", *err["loc"])} for err in pydantic_exc.errors()] + ) + + responses = [ + render_visual_gen_validation_error(exc, OpenAIServer.create_error_response) + for exc in (pydantic_exc, fastapi_exc) + ] + assert [r.status_code for r in responses] == [422, 422] + assert responses[0].body == responses[1].body + assert json.loads(responses[0].body) == self._UNKNOWN_FIELD_BODY + + def test_renderer_falls_back_to_str_without_errors(self): + """With no error entries the message falls back to ``str(exc)``.""" + from fastapi.exceptions import RequestValidationError + + from tensorrt_llm.serve.api.visual_gen.errors import render_visual_gen_validation_error + from tensorrt_llm.serve.openai_server import OpenAIServer + + exc = RequestValidationError([]) + resp = render_visual_gen_validation_error(exc, OpenAIServer.create_error_response) + assert resp.status_code == 422 + assert json.loads(resp.body)["message"] == str(exc) + + def test_renderer_delegates_to_the_factory(self): + """The renderer builds no response itself: it calls the factory it + is given exactly once, with the rendered message and the fixed + error type and status, and returns the factory's result. The + factory owns the envelope and the context-length code rule.""" + from http import HTTPStatus + + from fastapi.responses import Response + + from tensorrt_llm.serve.api.visual_gen.errors import render_visual_gen_validation_error + + calls = [] + sentinel = Response(status_code=422) + + def spy_factory(*, message, err_type, status_code): + calls.append((message, err_type, status_code)) + return sentinel + + result = render_visual_gen_validation_error( + self._pydantic_unknown_field_error(), spy_factory + ) + assert result is sentinel + assert calls == [ + ( + self._UNKNOWN_FIELD_BODY["message"], + "BadRequestError", + HTTPStatus.UNPROCESSABLE_ENTITY, + ) + ] + + # ========================================================================= # Non-visual-gen routes keep FastAPI's default validation response # ========================================================================= @@ -2676,7 +2846,7 @@ async def _handler(_, exc): return _llm_envelope_branch(exc) return JSONResponse(status_code=400, content={"error": str(exc)}) - # Mirror :meth:`OpenAIServer._create_visual_gen_validation_error_response` + # Mirror :func:`tensorrt_llm.serve.api.visual_gen.errors.render_visual_gen_validation_error` # inline so the test does not depend on instance state. def _llm_envelope_branch(exc): from http import HTTPStatus @@ -3149,7 +3319,7 @@ class TestVideoEncoderFailsFast: ids=["unsupported_format", "missing_ffmpeg"], ) def test_sync_route_fails_before_generate(self, video_client, monkeypatch, raiser): - from tensorrt_llm.serve import openai_video_routes as routes + from tensorrt_llm.serve.api.visual_gen import serving_videos as routes monkeypatch.setattr(routes, "resolve_video_format", raiser) # Record whether the generator was called so the assertion @@ -3177,7 +3347,7 @@ def test_sync_route_fails_before_generate(self, video_client, monkeypatch, raise ids=["unsupported_format", "missing_ffmpeg"], ) def test_async_route_fails_before_queue(self, video_client, monkeypatch, raiser): - from tensorrt_llm.serve import openai_video_routes as routes + from tensorrt_llm.serve.api.visual_gen import serving_videos as routes monkeypatch.setattr(routes, "resolve_video_format", raiser) video_client.mock_gen.last_inputs = None @@ -3198,7 +3368,7 @@ def test_async_route_fails_before_queue(self, video_client, monkeypatch, raiser) def test_sync_route_tensor_format_unaffected(self, video_client, monkeypatch): """Tensor formats have no encoder dependency; a broken ``resolve_video_format`` must not affect them.""" - from tensorrt_llm.serve import openai_video_routes as routes + from tensorrt_llm.serve.api.visual_gen import serving_videos as routes monkeypatch.setattr(routes, "resolve_video_format", _raise_value_error) resp = video_client.post( @@ -3424,13 +3594,13 @@ def _specs(**flags): } def test_no_specs_is_a_noop(self): - from tensorrt_llm.serve.openai_video_routes import _resolve_tensor_only_format + from tensorrt_llm.serve.api.visual_gen.serving_videos import _resolve_tensor_only_format assert _resolve_tensor_only_format("auto", {"action_mode": "policy"}, None) == "auto" assert _resolve_tensor_only_format("auto", None, self._specs(a=True)) == "auto" def test_only_a_declared_param_triggers(self): - from tensorrt_llm.serve.openai_video_routes import _resolve_tensor_only_format + from tensorrt_llm.serve.api.visual_gen.serving_videos import _resolve_tensor_only_format specs = self._specs(action_mode=True, stg_scale=False) # a non-declaring param must not force a tensor payload @@ -3440,14 +3610,354 @@ def test_only_a_declared_param_triggers(self): ) def test_null_value_does_not_trigger(self): - from tensorrt_llm.serve.openai_video_routes import _resolve_tensor_only_format + from tensorrt_llm.serve.api.visual_gen.serving_videos import _resolve_tensor_only_format specs = self._specs(action_mode=True) assert _resolve_tensor_only_format("auto", {"action_mode": None}, specs) == "auto" def test_encoder_format_raises_naming_the_parameter(self): - from tensorrt_llm.serve.openai_video_routes import _resolve_tensor_only_format + from tensorrt_llm.serve.api.visual_gen.serving_videos import _resolve_tensor_only_format specs = self._specs(action_mode=True) with pytest.raises(ValueError, match="action_mode"): _resolve_tensor_only_format("mp4", {"action_mode": "policy"}, specs) + + +# ========================================================================= +# Serving classes, router and composition root +# ========================================================================= + + +def _build_visual_gen_server(generator: MockVisualGen, model_name: str = "test-model"): + """The VISUAL_GEN ``OpenAIServer`` itself (``_create_server`` returns a client).""" + from tensorrt_llm.llmapi.disagg_utils import ServerRole + from tensorrt_llm.serve.openai_server import OpenAIServer + + with patch( + "tensorrt_llm.serve.openai_server._is_visual_gen_instance", + return_value=True, + ): + return OpenAIServer( + generator=generator, + model=model_name, + tool_parser=None, + server_role=ServerRole.VISUAL_GEN, + metadata_server_cfg=None, + ) + + +def _sync_video_json(prompt: str) -> dict: + return { + "prompt": prompt, + "size": "32x32", + "seconds": 1.0, + "fps": 8, + "format": "safetensors", + } + + +# Handlers that used to be methods of OpenAIServer (or inherited from its +# video-routes mixin) and now live on ImageServing / VideoServing. +_REMOVED_FROM_OPENAI_SERVER = ( + "_supports_image_edit", + "_create_not_supported_error", + "openai_image_generation", + "get_image_content", + "_build_image_content_url", + "_reject_disabled_path", + "_image_object", + "_parse_image_edit_request", + "openai_image_edit", + "openai_video_generation_sync", + "_parse_video_generation_request", + "openai_video_generation_async", + "_generate_video_background", + "list_videos", + "get_video_metadata", + "get_video_content", + "delete_video", + "_on_video_task_done", +) + + +@pytest.mark.threadleak(enabled=False) # FileResponse spawns AnyIO worker threads +class TestVisualGenMediaDirectory: + def test_images_and_videos_share_one_media_directory(self, tmp_path, monkeypatch): + """The composition root resolves the media directory once per server and + hands the same ``Path`` to the image and the video serving object, so + images and videos keep landing in one directory.""" + monkeypatch.delenv("TRTLLM_MEDIA_STORAGE_PATH", raising=False) + monkeypatch.chdir(tmp_path) + server = _build_visual_gen_server( + MockVisualGen( + image_output=_make_dummy_image_tensor(), + video_output=_make_dummy_video_tensor(), + ) + ) + root = tmp_path / "trtllm_generated" + assert [p.name for p in root.iterdir()] == [server.media_storage_path.name] + images = server.app.state.visual_gen_serving_images + videos = server.app.state.visual_gen_serving_videos + assert images.media_storage_path is videos.media_storage_path + assert videos.media_storage_path is server.media_storage_path + + client = _ThreadSettlingTestClient(server.app) + image = client.post( + "/v1/images/generations", + json={"prompt": "cat", "response_format": "url", "size": "64x64"}, + ) + assert image.status_code == 200, image.text + video = client.post( + "/v1/videos/sync", + json=_sync_video_json("cat"), + headers={"content-type": "application/json"}, + ) + assert video.status_code == 200, video.text + + written = sorted(p.name for p in server.media_storage_path.iterdir()) + assert len(written) == 2, written + assert written[0].startswith("image_") and written[0].endswith(".png") + assert written[1].startswith("video_") and written[1].endswith(".safetensors") + # Still the one directory under the working directory. + assert [p.name for p in root.iterdir()] == [server.media_storage_path.name] + + +@pytest.mark.threadleak(enabled=False) # FileResponse spawns AnyIO worker threads +class TestVisualGenServingClasses: + def test_construction_needs_no_server_and_no_filesystem(self, tmp_path): + """The serving classes take their dependencies as constructor arguments + and never touch the filesystem: the media directory is injected.""" + from tensorrt_llm.serve.api.visual_gen.serving_images import ImageServing + from tensorrt_llm.serve.api.visual_gen.serving_videos import VideoServing + + generator = MockVisualGen(image_output=_make_dummy_image_tensor()) + clock = AdjustedSteadyClock() + missing = tmp_path / "never-created" + images = ImageServing( + generator=generator, + model="test-model", + media_storage_path=missing, + adjusted_clock=clock, + ) + videos = VideoServing( + generator=generator, + model="test-model", + media_storage_path=missing, + adjusted_clock=clock, + ) + for serving in (images, videos): + assert serving.generator is generator + assert serving.model == "test-model" + assert serving.media_storage_path is missing + assert serving._adjusted_steady_clock is clock + assert not missing.exists() + + other = VideoServing( + generator=generator, + model="test-model", + media_storage_path=missing, + adjusted_clock=clock, + ) + assert videos.video_gen_tasks == {} and other.video_gen_tasks == {} + assert videos.video_gen_tasks is not other.video_gen_tasks + + def test_router_serves_requests_without_openai_server(self, tmp_path, monkeypatch): + """A bare app with the arrival-time middleware, ``init_serving_state`` and + ``attach_router`` serves image and video requests, every route on the + msgpack route class.""" + from fastapi import FastAPI + from test_common.serve.routes import effective_routes + + from tensorrt_llm.serve._base.msgspec_route import _MsgspecRoute + from tensorrt_llm.serve.api.visual_gen import api_router + from tensorrt_llm.serve.responses_utils import ServerArrivalTimeMiddleware + + monkeypatch.setenv("TRTLLM_MEDIA_STORAGE_PATH", str(tmp_path / "media")) + app = FastAPI() + clock = AdjustedSteadyClock() + app.add_middleware(ServerArrivalTimeMiddleware, adjusted_clock=clock) + media = api_router.init_serving_state( + app.state, + generator=MockVisualGen( + image_output=_make_dummy_image_tensor(), + video_output=_make_dummy_video_tensor(), + ), + model="test-model", + adjusted_clock=clock, + ) + assert media == tmp_path / "media" + api_router.attach_router(app) + + client = _ThreadSettlingTestClient(app) + image = client.post( + "/v1/images/generations", + json={"prompt": "cat", "response_format": "b64_json", "size": "64x64"}, + ) + assert image.status_code == 200, image.text + assert image.json()["data"][0]["b64_json"] + video = client.post( + "/v1/videos/sync", + json=_sync_video_json("cat"), + headers={"content-type": "application/json"}, + ) + assert video.status_code == 200, video.text + + api_routes = [ + (path, route) for path, route in effective_routes(app) if path.startswith("/v1/") + ] + assert len(api_routes) == 10, [path for path, _ in api_routes] + assert all(isinstance(route, _MsgspecRoute) for _, route in api_routes), [ + (path, type(route).__name__) for path, route in api_routes + ] + + def test_attach_router_requires_serving_state(self, tmp_path, monkeypatch): + """``attach_router`` refuses an app whose serving objects are missing and + names what to call; this is why the composition root attaches routers + after its role switch.""" + from fastapi import FastAPI + + from tensorrt_llm.serve.api.visual_gen import api_router + + with pytest.raises(RuntimeError) as excinfo: + api_router.attach_router(FastAPI()) + assert "visual_gen_serving_images" in str(excinfo.value) + assert "init_serving_state" in str(excinfo.value) + + app = FastAPI() + app.state.visual_gen_serving_images = object() + with pytest.raises(RuntimeError) as excinfo: + api_router.attach_router(app) + assert "visual_gen_serving_videos" in str(excinfo.value) + + monkeypatch.setenv("TRTLLM_MEDIA_STORAGE_PATH", str(tmp_path / "media")) + app = FastAPI() + api_router.init_serving_state( + app.state, + generator=MockVisualGen(image_output=_make_dummy_image_tensor()), + model="test-model", + adjusted_clock=AdjustedSteadyClock(), + ) + api_router.attach_router(app) + # The route is attached now: an invalid body is a 422, not a 404. + assert TestClient(app).post("/v1/images/generations", json={}).status_code == 422 + + def test_openai_server_no_longer_hosts_visual_gen_handlers(self, tmp_path, monkeypatch): + from tensorrt_llm.serve.openai_server import OpenAIServer + + hosted = [name for name in _REMOVED_FROM_OPENAI_SERVER if hasattr(OpenAIServer, name)] + assert hosted == [], ( + "VisualGen handlers belong in tensorrt_llm/serve/api/visual_gen/ (ImageServing, " + f"VideoServing); do not add them back to OpenAIServer: {hosted}" + ) + assert "_VideoRoutesMixin" not in [cls.__name__ for cls in OpenAIServer.__mro__] + + monkeypatch.setenv("TRTLLM_MEDIA_STORAGE_PATH", str(tmp_path)) + server = _build_visual_gen_server(MockVisualGen(image_output=_make_dummy_image_tensor())) + assert not hasattr(server, "video_gen_tasks") + assert server.app.state.visual_gen_serving_videos.video_gen_tasks == {} + + +@pytest.mark.threadleak(enabled=False) # FileResponse spawns AnyIO worker threads +class TestVisualGenGenerateEntryPoint: + def test_generation_points_go_through_generate(self, tmp_path, monkeypatch): + """Image generation, synchronous video and asynchronous video submit + through ``VisualGenBaseServing._generate``. The image edit still calls + the generator's synchronous ``generate()``: taking it off the event loop + is a behavior change that is not part of the move.""" + from tensorrt_llm._torch.visual_gen.pipeline import RefSlotSpec, RoleSpec + from tensorrt_llm.serve.api.visual_gen.serving_base import VisualGenBaseServing + + submitted = [] + original = VisualGenBaseServing._generate + + async def spy(self, prompt, params): + submitted.append(prompt) + return await original(self, prompt, params) + + monkeypatch.setattr(VisualGenBaseServing, "_generate", spy) + monkeypatch.setenv("TRTLLM_MEDIA_STORAGE_PATH", str(tmp_path)) + + client = _create_server( + MockVisualGen( + image_output=_make_dummy_image_tensor(), + video_output=_make_dummy_video_tensor(), + ) + ) + resp = client.post( + "/v1/images/generations", + json={"prompt": "image", "response_format": "b64_json", "size": "64x64"}, + ) + assert resp.status_code == 200, resp.text + assert submitted == ["image"] + resp = client.post( + "/v1/videos/sync", + json=_sync_video_json("sync video"), + headers={"content-type": "application/json"}, + ) + assert resp.status_code == 200, resp.text + assert submitted == ["image", "sync video"] + resp = client.post( + "/v1/videos", + json=_sync_video_json("async video"), + headers={"content-type": "application/json"}, + ) + assert resp.status_code == 202, resp.text + assert submitted == ["image", "sync video", "async video"] + + # The image edit: an edit-capable mock (the edit slot takes joint + # conditioning images), its synchronous generate() recorded. + edit_gen = MockVisualGen( + image_output=_make_dummy_image_tensor(4, 4), + model="Qwen/Qwen-Image-Layered", + supports_image_edit=True, + ref_slot_specs={ + "image_reference": RefSlotSpec( + modality="image", roles=[RoleSpec(role="reference", min=1, max=None)] + ), + }, + ) + edited = [] + original_generate = edit_gen.generate + + def recording_generate(*args, **kwargs): + edited.append(kwargs.get("inputs")) + return original_generate(*args, **kwargs) + + edit_gen.generate = recording_generate + edit_client = _create_server(edit_gen, model_name="Qwen/Qwen-Image-Layered") + resp = edit_client.post( + "/v1/images/edits", + json={"prompt": "edit", "image": _b64_white_png_1x1(), "response_format": "b64_json"}, + ) + assert resp.status_code == 200, resp.text + assert edited == ["edit"] + assert submitted == ["image", "sync video", "async video"] + + def test_generate_submits_off_the_event_loop(self, tmp_path): + """``_generate`` runs ``generate_async`` in a worker thread, because it + resolves and enqueues synchronously.""" + from tensorrt_llm.serve.api.visual_gen.serving_images import ImageServing + + gen = MockVisualGen(image_output=_make_dummy_image_tensor()) + seen = {} + original = gen.generate_async + + def recording_generate_async(*args, **kwargs): + seen["thread"] = threading.current_thread() + return original(*args, **kwargs) + + gen.generate_async = recording_generate_async + serving = ImageServing( + generator=gen, + model="test-model", + media_storage_path=tmp_path, + adjusted_clock=AdjustedSteadyClock(), + ) + + async def submit(): + handle = await serving._generate("prompt", gen.default_params) + return threading.current_thread(), await handle.aresult() + + loop_thread, output = _run_async(submit()) + assert output.image is not None + assert seen["thread"] is not loop_thread diff --git a/tests/unittest/_torch/visual_gen/test_visual_gen_params.py b/tests/unittest/_torch/visual_gen/test_visual_gen_params.py index 555cd5679a6b..c27920b36d8a 100644 --- a/tests/unittest/_torch/visual_gen/test_visual_gen_params.py +++ b/tests/unittest/_torch/visual_gen/test_visual_gen_params.py @@ -1568,14 +1568,14 @@ class TestDeprecatedInputReferenceStaysCompatible: """ def test_a_bare_string_is_still_accepted(self): - from tensorrt_llm.serve.openai_protocol import VideoGenerationRequest + from tensorrt_llm.serve.api.visual_gen.protocol import VideoGenerationRequest assert VideoGenerationRequest(prompt="x", input_reference="aGk=").input_reference == "aGk=" def test_the_typed_field_still_requires_a_format(self): from pydantic import ValidationError - from tensorrt_llm.serve.openai_protocol import VideoGenerationRequest + from tensorrt_llm.serve.api.visual_gen.protocol import VideoGenerationRequest with pytest.raises(ValidationError): VideoGenerationRequest(prompt="x", image_reference="aGk=") diff --git a/tests/unittest/llmapi/test_visual_gen_startup_shutdown.py b/tests/unittest/_torch/visual_gen/test_visual_gen_startup_shutdown.py similarity index 100% rename from tests/unittest/llmapi/test_visual_gen_startup_shutdown.py rename to tests/unittest/_torch/visual_gen/test_visual_gen_startup_shutdown.py diff --git a/tests/unittest/_torch/visual_gen/test_visual_gen_utils.py b/tests/unittest/_torch/visual_gen/test_visual_gen_utils.py index b8d9aa865d60..8d261d053963 100644 --- a/tests/unittest/_torch/visual_gen/test_visual_gen_utils.py +++ b/tests/unittest/_torch/visual_gen/test_visual_gen_utils.py @@ -1,6 +1,6 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -"""Direct tests for :mod:`tensorrt_llm.serve.visual_gen_utils`. +"""Direct tests for :mod:`tensorrt_llm.serve.api.visual_gen.utils`. These tests bypass the HTTP transport and call ``parse_visual_gen_params`` and the ``_warn_if_set_with_no_semantic`` / ``_merge_extra_params`` @@ -23,9 +23,12 @@ from fastapi import UploadFile from PIL import Image -from tensorrt_llm.serve import visual_gen_utils -from tensorrt_llm.serve.openai_protocol import ImageGenerationRequest, VideoGenerationRequest -from tensorrt_llm.serve.visual_gen_utils import ( +from tensorrt_llm.serve.api.visual_gen import utils as visual_gen_utils +from tensorrt_llm.serve.api.visual_gen.protocol import ( + ImageGenerationRequest, + VideoGenerationRequest, +) +from tensorrt_llm.serve.api.visual_gen.utils import ( _merge_extra_params, _warn_if_set_with_no_semantic, parse_visual_gen_params, @@ -160,7 +163,7 @@ class TestSeedLowerBoundOnServeBoundary: """ def test_image_seed_accepts_zero_and_large_values(self): - from tensorrt_llm.serve.openai_protocol import ImageGenerationRequest + from tensorrt_llm.serve.api.visual_gen.protocol import ImageGenerationRequest assert ImageGenerationRequest(prompt="x", seed=0).seed == 0 large = 2**40 @@ -169,7 +172,7 @@ def test_image_seed_accepts_zero_and_large_values(self): def test_image_seed_rejects_negative(self): from pydantic import ValidationError - from tensorrt_llm.serve.openai_protocol import ImageGenerationRequest + from tensorrt_llm.serve.api.visual_gen.protocol import ImageGenerationRequest with pytest.raises(ValidationError): ImageGenerationRequest(prompt="x", seed=-1) @@ -177,7 +180,7 @@ def test_image_seed_rejects_negative(self): def test_video_seed_rejects_negative(self): from pydantic import ValidationError - from tensorrt_llm.serve.openai_protocol import VideoGenerationRequest + from tensorrt_llm.serve.api.visual_gen.protocol import VideoGenerationRequest with pytest.raises(ValidationError): VideoGenerationRequest(prompt="x", seed=-1) @@ -203,7 +206,7 @@ def _fake_warning(msg: str, *args: object, **kwargs: object) -> None: rendered = str(msg) captured.append(rendered) - from tensorrt_llm.serve import visual_gen_utils as vgu + from tensorrt_llm.serve.api.visual_gen import utils as vgu monkeypatch.setattr(vgu.logger, "warning", _fake_warning) return captured diff --git a/tests/unittest/api_stability/references/trtllm_serve_routes.yaml b/tests/unittest/api_stability/references/trtllm_serve_routes.yaml new file mode 100644 index 000000000000..523342d4afae --- /dev/null +++ b/tests/unittest/api_stability/references/trtllm_serve_routes.yaml @@ -0,0 +1,663 @@ +# Routes of every trtllm-serve app configuration. Generated, do not edit by hand: +# PYTHONPATH=tests python3 -m test_common.serve.routes --write +# Each route is " ", in registration order. "#" is +# added only when two routes share methods and path. The checker compares the order +# only for routes that can match the same request. Changing this file changes the +# HTTP surface of trtllm-serve; the API review committee approves it. +version: 1 +configs: + llm: + kind: openai_server + routes: + - GET,HEAD /openapi.json Route + - GET,HEAD /docs Route + - GET,HEAD /docs/oauth2-redirect Route + - GET,HEAD /redoc Route + - GET /health _MsgspecRoute + - GET /health_generate _MsgspecRoute + - GET /version _MsgspecRoute + - GET /v1/models _MsgspecRoute + - GET /v1/data_transceiver_state _MsgspecRoute + - GET /metrics _MsgspecRoute + - GET /energy_metrics _MsgspecRoute + - GET /steady_clock_offset _MsgspecRoute + - POST /steady_clock_offset _MsgspecRoute + - POST /kv_cache_events _MsgspecRoute + - POST /v1/completions _MsgspecRoute + - POST /v1/chat/completions _MsgspecRoute + - POST /v1/messages _MsgspecRoute + - POST /v1/messages/count_tokens _MsgspecRoute + - POST /v1/messages/batches _MsgspecRoute + - GET /v1/messages/batches _MsgspecRoute + - GET /v1/messages/batches/{batch_id} _MsgspecRoute + - DELETE /v1/messages/batches/{batch_id} _MsgspecRoute + - POST /v1/messages/batches/{batch_id}/cancel _MsgspecRoute + - GET /v1/messages/batches/{batch_id}/results _MsgspecRoute + - POST /v1/responses _MsgspecRoute + - GET /v1/responses/{response_id} _MsgspecRoute + - DELETE /v1/responses/{response_id} _MsgspecRoute + - POST /_internal/tokenize _MsgspecRoute + - POST /start_profile _MsgspecRoute + - POST /stop_profile _MsgspecRoute + - GET /server_info _MsgspecRoute + llm_context: + kind: openai_server + routes: + - GET,HEAD /openapi.json Route + - GET,HEAD /docs Route + - GET,HEAD /docs/oauth2-redirect Route + - GET,HEAD /redoc Route + - GET /health _MsgspecRoute + - GET /health_generate _MsgspecRoute + - GET /version _MsgspecRoute + - GET /v1/models _MsgspecRoute + - GET /v1/data_transceiver_state _MsgspecRoute + - GET /metrics _MsgspecRoute + - GET /energy_metrics _MsgspecRoute + - GET /steady_clock_offset _MsgspecRoute + - POST /steady_clock_offset _MsgspecRoute + - POST /kv_cache_events _MsgspecRoute + - POST /v1/completions _MsgspecRoute + - POST /v1/chat/completions _MsgspecRoute + - POST /v1/messages _MsgspecRoute + - POST /v1/messages/count_tokens _MsgspecRoute + - POST /v1/messages/batches _MsgspecRoute + - GET /v1/messages/batches _MsgspecRoute + - GET /v1/messages/batches/{batch_id} _MsgspecRoute + - DELETE /v1/messages/batches/{batch_id} _MsgspecRoute + - POST /v1/messages/batches/{batch_id}/cancel _MsgspecRoute + - GET /v1/messages/batches/{batch_id}/results _MsgspecRoute + - POST /v1/responses _MsgspecRoute + - GET /v1/responses/{response_id} _MsgspecRoute + - DELETE /v1/responses/{response_id} _MsgspecRoute + - POST /_internal/tokenize _MsgspecRoute + - POST /start_profile _MsgspecRoute + - POST /stop_profile _MsgspecRoute + - GET /server_info _MsgspecRoute + llm_generation: + kind: openai_server + routes: + - GET,HEAD /openapi.json Route + - GET,HEAD /docs Route + - GET,HEAD /docs/oauth2-redirect Route + - GET,HEAD /redoc Route + - GET /health _MsgspecRoute + - GET /health_generate _MsgspecRoute + - GET /version _MsgspecRoute + - GET /v1/models _MsgspecRoute + - GET /v1/data_transceiver_state _MsgspecRoute + - GET /metrics _MsgspecRoute + - GET /energy_metrics _MsgspecRoute + - GET /steady_clock_offset _MsgspecRoute + - POST /steady_clock_offset _MsgspecRoute + - POST /kv_cache_events _MsgspecRoute + - POST /v1/completions _MsgspecRoute + - POST /v1/chat/completions _MsgspecRoute + - POST /v1/messages _MsgspecRoute + - POST /v1/messages/count_tokens _MsgspecRoute + - POST /v1/messages/batches _MsgspecRoute + - GET /v1/messages/batches _MsgspecRoute + - GET /v1/messages/batches/{batch_id} _MsgspecRoute + - DELETE /v1/messages/batches/{batch_id} _MsgspecRoute + - POST /v1/messages/batches/{batch_id}/cancel _MsgspecRoute + - GET /v1/messages/batches/{batch_id}/results _MsgspecRoute + - POST /v1/responses _MsgspecRoute + - GET /v1/responses/{response_id} _MsgspecRoute + - DELETE /v1/responses/{response_id} _MsgspecRoute + - POST /_internal/tokenize _MsgspecRoute + - POST /start_profile _MsgspecRoute + - POST /stop_profile _MsgspecRoute + - GET /server_info _MsgspecRoute + llm_gpt_oss: + kind: openai_server + routes: + - GET,HEAD /openapi.json Route + - GET,HEAD /docs Route + - GET,HEAD /docs/oauth2-redirect Route + - GET,HEAD /redoc Route + - GET /health _MsgspecRoute + - GET /health_generate _MsgspecRoute + - GET /version _MsgspecRoute + - GET /v1/models _MsgspecRoute + - GET /v1/data_transceiver_state _MsgspecRoute + - GET /metrics _MsgspecRoute + - GET /energy_metrics _MsgspecRoute + - GET /steady_clock_offset _MsgspecRoute + - POST /steady_clock_offset _MsgspecRoute + - POST /kv_cache_events _MsgspecRoute + - POST /v1/completions _MsgspecRoute + - POST /v1/chat/completions _MsgspecRoute + - POST /v1/responses _MsgspecRoute + - GET /v1/responses/{response_id} _MsgspecRoute + - DELETE /v1/responses/{response_id} _MsgspecRoute + - POST /_internal/tokenize _MsgspecRoute + - POST /start_profile _MsgspecRoute + - POST /stop_profile _MsgspecRoute + - GET /server_info _MsgspecRoute + llm_gpt_oss_harmony_disabled: + kind: openai_server + routes: + - GET,HEAD /openapi.json Route + - GET,HEAD /docs Route + - GET,HEAD /docs/oauth2-redirect Route + - GET,HEAD /redoc Route + - GET /health _MsgspecRoute + - GET /health_generate _MsgspecRoute + - GET /version _MsgspecRoute + - GET /v1/models _MsgspecRoute + - GET /v1/data_transceiver_state _MsgspecRoute + - GET /metrics _MsgspecRoute + - GET /energy_metrics _MsgspecRoute + - GET /steady_clock_offset _MsgspecRoute + - POST /steady_clock_offset _MsgspecRoute + - POST /kv_cache_events _MsgspecRoute + - POST /v1/completions _MsgspecRoute + - POST /v1/chat/completions _MsgspecRoute + - POST /v1/messages _MsgspecRoute + - POST /v1/messages/count_tokens _MsgspecRoute + - POST /v1/messages/batches _MsgspecRoute + - GET /v1/messages/batches _MsgspecRoute + - GET /v1/messages/batches/{batch_id} _MsgspecRoute + - DELETE /v1/messages/batches/{batch_id} _MsgspecRoute + - POST /v1/messages/batches/{batch_id}/cancel _MsgspecRoute + - GET /v1/messages/batches/{batch_id}/results _MsgspecRoute + - POST /v1/responses _MsgspecRoute + - GET /v1/responses/{response_id} _MsgspecRoute + - DELETE /v1/responses/{response_id} _MsgspecRoute + - POST /_internal/tokenize _MsgspecRoute + - POST /start_profile _MsgspecRoute + - POST /stop_profile _MsgspecRoute + - GET /server_info _MsgspecRoute + llm_governor: + kind: openai_server + routes: + - GET,HEAD /openapi.json Route + - GET,HEAD /docs Route + - GET,HEAD /docs/oauth2-redirect Route + - GET,HEAD /redoc Route + - GET /health _MsgspecRoute + - GET /health_generate _MsgspecRoute + - GET /version _MsgspecRoute + - GET /v1/models _MsgspecRoute + - GET /v1/data_transceiver_state _MsgspecRoute + - GET /metrics _MsgspecRoute + - GET /energy_metrics _MsgspecRoute + - GET /steady_clock_offset _MsgspecRoute + - POST /steady_clock_offset _MsgspecRoute + - POST /kv_cache_events _MsgspecRoute + - POST /_resource_governor/truncate _MsgspecRoute + - POST /_control/kv_cache/truncate _MsgspecRoute + - POST /_control/kv_cache/truncate_tokens _MsgspecRoute + - POST /v1/completions _MsgspecRoute + - POST /v1/chat/completions _MsgspecRoute + - POST /v1/messages _MsgspecRoute + - POST /v1/messages/count_tokens _MsgspecRoute + - POST /v1/messages/batches _MsgspecRoute + - GET /v1/messages/batches _MsgspecRoute + - GET /v1/messages/batches/{batch_id} _MsgspecRoute + - DELETE /v1/messages/batches/{batch_id} _MsgspecRoute + - POST /v1/messages/batches/{batch_id}/cancel _MsgspecRoute + - GET /v1/messages/batches/{batch_id}/results _MsgspecRoute + - POST /v1/responses _MsgspecRoute + - GET /v1/responses/{response_id} _MsgspecRoute + - DELETE /v1/responses/{response_id} _MsgspecRoute + - POST /_internal/tokenize _MsgspecRoute + - POST /start_profile _MsgspecRoute + - POST /stop_profile _MsgspecRoute + - GET /server_info _MsgspecRoute + llm_rl_control: + kind: openai_server + routes: + - GET,HEAD /openapi.json Route + - GET,HEAD /docs Route + - GET,HEAD /docs/oauth2-redirect Route + - GET,HEAD /redoc Route + - GET /health _MsgspecRoute + - GET /health_generate _MsgspecRoute + - GET /version _MsgspecRoute + - GET /v1/models _MsgspecRoute + - GET /v1/data_transceiver_state _MsgspecRoute + - GET /metrics _MsgspecRoute + - GET /energy_metrics _MsgspecRoute + - GET /steady_clock_offset _MsgspecRoute + - POST /steady_clock_offset _MsgspecRoute + - POST /kv_cache_events _MsgspecRoute + - POST /v1/completions _MsgspecRoute + - POST /v1/chat/completions _MsgspecRoute + - POST /v1/messages _MsgspecRoute + - POST /v1/messages/count_tokens _MsgspecRoute + - POST /v1/messages/batches _MsgspecRoute + - GET /v1/messages/batches _MsgspecRoute + - GET /v1/messages/batches/{batch_id} _MsgspecRoute + - DELETE /v1/messages/batches/{batch_id} _MsgspecRoute + - POST /v1/messages/batches/{batch_id}/cancel _MsgspecRoute + - GET /v1/messages/batches/{batch_id}/results _MsgspecRoute + - POST /v1/responses _MsgspecRoute + - GET /v1/responses/{response_id} _MsgspecRoute + - DELETE /v1/responses/{response_id} _MsgspecRoute + - POST /_internal/tokenize _MsgspecRoute + - POST /start_profile _MsgspecRoute + - POST /stop_profile _MsgspecRoute + - POST /release_memory _MsgspecRoute + - POST /resume_memory _MsgspecRoute + - POST /update_weights _MsgspecRoute + - GET /server_info _MsgspecRoute + llm_runtime_control: + kind: openai_server + routes: + - GET,HEAD /openapi.json Route + - GET,HEAD /docs Route + - GET,HEAD /docs/oauth2-redirect Route + - GET,HEAD /redoc Route + - GET /health _MsgspecRoute + - GET /health_generate _MsgspecRoute + - GET /version _MsgspecRoute + - GET /v1/models _MsgspecRoute + - GET /v1/data_transceiver_state _MsgspecRoute + - GET /metrics _MsgspecRoute + - GET /energy_metrics _MsgspecRoute + - GET /steady_clock_offset _MsgspecRoute + - POST /steady_clock_offset _MsgspecRoute + - POST /kv_cache_events _MsgspecRoute + - POST /v1/completions _MsgspecRoute + - POST /v1/chat/completions _MsgspecRoute + - POST /v1/messages _MsgspecRoute + - POST /v1/messages/count_tokens _MsgspecRoute + - POST /v1/messages/batches _MsgspecRoute + - GET /v1/messages/batches _MsgspecRoute + - GET /v1/messages/batches/{batch_id} _MsgspecRoute + - DELETE /v1/messages/batches/{batch_id} _MsgspecRoute + - POST /v1/messages/batches/{batch_id}/cancel _MsgspecRoute + - GET /v1/messages/batches/{batch_id}/results _MsgspecRoute + - POST /v1/responses _MsgspecRoute + - GET /v1/responses/{response_id} _MsgspecRoute + - DELETE /v1/responses/{response_id} _MsgspecRoute + - POST /_internal/tokenize _MsgspecRoute + - POST /start_profile _MsgspecRoute + - POST /stop_profile _MsgspecRoute + - POST /release_memory _MsgspecRoute + - POST /resume_memory _MsgspecRoute + - GET /memory_status _MsgspecRoute + - GET /server_info _MsgspecRoute + llm_rl_and_runtime_control: + kind: openai_server + error: 'ValueError: Legacy RL control and runtime control endpoints cannot both be enabled.' + llm_perf_metrics: + kind: openai_server + routes: + - GET,HEAD /openapi.json Route + - GET,HEAD /docs Route + - GET,HEAD /docs/oauth2-redirect Route + - GET,HEAD /redoc Route + - GET /health _MsgspecRoute + - GET /health_generate _MsgspecRoute + - GET /version _MsgspecRoute + - GET /v1/models _MsgspecRoute + - GET /v1/data_transceiver_state _MsgspecRoute + - GET /metrics _MsgspecRoute + - GET /energy_metrics _MsgspecRoute + - GET /steady_clock_offset _MsgspecRoute + - POST /steady_clock_offset _MsgspecRoute + - POST /kv_cache_events _MsgspecRoute + - POST /v1/completions _MsgspecRoute + - POST /v1/chat/completions _MsgspecRoute + - POST /v1/messages _MsgspecRoute + - POST /v1/messages/count_tokens _MsgspecRoute + - POST /v1/messages/batches _MsgspecRoute + - GET /v1/messages/batches _MsgspecRoute + - GET /v1/messages/batches/{batch_id} _MsgspecRoute + - DELETE /v1/messages/batches/{batch_id} _MsgspecRoute + - POST /v1/messages/batches/{batch_id}/cancel _MsgspecRoute + - GET /v1/messages/batches/{batch_id}/results _MsgspecRoute + - POST /v1/responses _MsgspecRoute + - GET /v1/responses/{response_id} _MsgspecRoute + - DELETE /v1/responses/{response_id} _MsgspecRoute + - POST /_internal/tokenize _MsgspecRoute + - POST /start_profile _MsgspecRoute + - POST /stop_profile _MsgspecRoute + - GET /server_info _MsgspecRoute + - MOUNT /prometheus/metrics Mount + llm_perf_metrics_enable_metrics_env: + kind: openai_server + routes: + - GET,HEAD /openapi.json Route + - GET,HEAD /docs Route + - GET,HEAD /docs/oauth2-redirect Route + - GET,HEAD /redoc Route + - GET /health _MsgspecRoute + - GET /health_generate _MsgspecRoute + - GET /version _MsgspecRoute + - GET /v1/models _MsgspecRoute + - GET /v1/data_transceiver_state _MsgspecRoute + - 'GET /metrics _MsgspecRoute #get_iteration_stats' + - GET /energy_metrics _MsgspecRoute + - GET /steady_clock_offset _MsgspecRoute + - POST /steady_clock_offset _MsgspecRoute + - POST /kv_cache_events _MsgspecRoute + - POST /v1/completions _MsgspecRoute + - POST /v1/chat/completions _MsgspecRoute + - POST /v1/messages _MsgspecRoute + - POST /v1/messages/count_tokens _MsgspecRoute + - POST /v1/messages/batches _MsgspecRoute + - GET /v1/messages/batches _MsgspecRoute + - GET /v1/messages/batches/{batch_id} _MsgspecRoute + - DELETE /v1/messages/batches/{batch_id} _MsgspecRoute + - POST /v1/messages/batches/{batch_id}/cancel _MsgspecRoute + - GET /v1/messages/batches/{batch_id}/results _MsgspecRoute + - POST /v1/responses _MsgspecRoute + - GET /v1/responses/{response_id} _MsgspecRoute + - DELETE /v1/responses/{response_id} _MsgspecRoute + - POST /_internal/tokenize _MsgspecRoute + - POST /start_profile _MsgspecRoute + - POST /stop_profile _MsgspecRoute + - GET /server_info _MsgspecRoute + - 'GET /metrics _MsgspecRoute #metrics' + - MOUNT /prometheus/metrics Mount + llm_perf_metrics_output_dir_only: + kind: openai_server + routes: + - GET,HEAD /openapi.json Route + - GET,HEAD /docs Route + - GET,HEAD /docs/oauth2-redirect Route + - GET,HEAD /redoc Route + - GET /health _MsgspecRoute + - GET /health_generate _MsgspecRoute + - GET /version _MsgspecRoute + - GET /v1/models _MsgspecRoute + - GET /v1/data_transceiver_state _MsgspecRoute + - GET /metrics _MsgspecRoute + - GET /energy_metrics _MsgspecRoute + - GET /steady_clock_offset _MsgspecRoute + - POST /steady_clock_offset _MsgspecRoute + - POST /kv_cache_events _MsgspecRoute + - POST /v1/completions _MsgspecRoute + - POST /v1/chat/completions _MsgspecRoute + - POST /v1/messages _MsgspecRoute + - POST /v1/messages/count_tokens _MsgspecRoute + - POST /v1/messages/batches _MsgspecRoute + - GET /v1/messages/batches _MsgspecRoute + - GET /v1/messages/batches/{batch_id} _MsgspecRoute + - DELETE /v1/messages/batches/{batch_id} _MsgspecRoute + - POST /v1/messages/batches/{batch_id}/cancel _MsgspecRoute + - GET /v1/messages/batches/{batch_id}/results _MsgspecRoute + - POST /v1/responses _MsgspecRoute + - GET /v1/responses/{response_id} _MsgspecRoute + - DELETE /v1/responses/{response_id} _MsgspecRoute + - POST /_internal/tokenize _MsgspecRoute + - POST /start_profile _MsgspecRoute + - POST /stop_profile _MsgspecRoute + - GET /server_info _MsgspecRoute + - MOUNT /prometheus/metrics Mount + llm_render_endpoints: + kind: openai_server + routes: + - GET,HEAD /openapi.json Route + - GET,HEAD /docs Route + - GET,HEAD /docs/oauth2-redirect Route + - GET,HEAD /redoc Route + - GET /health _MsgspecRoute + - GET /health_generate _MsgspecRoute + - GET /version _MsgspecRoute + - GET /v1/models _MsgspecRoute + - GET /v1/data_transceiver_state _MsgspecRoute + - GET /metrics _MsgspecRoute + - GET /energy_metrics _MsgspecRoute + - GET /steady_clock_offset _MsgspecRoute + - POST /steady_clock_offset _MsgspecRoute + - POST /kv_cache_events _MsgspecRoute + - POST /v1/completions _MsgspecRoute + - POST /v1/chat/completions _MsgspecRoute + - POST /v1/messages _MsgspecRoute + - POST /v1/messages/count_tokens _MsgspecRoute + - POST /v1/messages/batches _MsgspecRoute + - GET /v1/messages/batches _MsgspecRoute + - GET /v1/messages/batches/{batch_id} _MsgspecRoute + - DELETE /v1/messages/batches/{batch_id} _MsgspecRoute + - POST /v1/messages/batches/{batch_id}/cancel _MsgspecRoute + - GET /v1/messages/batches/{batch_id}/results _MsgspecRoute + - POST /v1/responses _MsgspecRoute + - GET /v1/responses/{response_id} _MsgspecRoute + - DELETE /v1/responses/{response_id} _MsgspecRoute + - POST /_internal/tokenize _MsgspecRoute + - POST /start_profile _MsgspecRoute + - POST /stop_profile _MsgspecRoute + - GET /server_info _MsgspecRoute + - POST /v1/chat/completions/render _MsgspecRoute + - POST /v1/completions/render _MsgspecRoute + llm_multi_frontend_attached: + kind: openai_server + routes: + - GET,HEAD /openapi.json Route + - GET,HEAD /docs Route + - GET,HEAD /docs/oauth2-redirect Route + - GET,HEAD /redoc Route + - 'GET /metrics _MsgspecRoute #forward' + - 'POST /kv_cache_events _MsgspecRoute #forward' + - 'POST /start_profile _MsgspecRoute #forward' + - 'POST /stop_profile _MsgspecRoute #forward' + - 'POST /steady_clock_offset _MsgspecRoute #forward' + - 'GET /v1/messages/batches _MsgspecRoute #forward' + - 'POST /v1/messages/batches _MsgspecRoute #forward' + - GET /v1/messages/batches/{rest:path} _MsgspecRoute + - POST /v1/messages/batches/{rest:path} _MsgspecRoute + - DELETE /v1/messages/batches/{rest:path} _MsgspecRoute + - GET /health _MsgspecRoute + - GET /health_generate _MsgspecRoute + - GET /version _MsgspecRoute + - GET /v1/models _MsgspecRoute + - GET /v1/data_transceiver_state _MsgspecRoute + - 'GET /metrics _MsgspecRoute #get_iteration_stats' + - GET /energy_metrics _MsgspecRoute + - GET /steady_clock_offset _MsgspecRoute + - 'POST /steady_clock_offset _MsgspecRoute #set_steady_clock_offset' + - 'POST /kv_cache_events _MsgspecRoute #get_kv_cache_events' + - POST /v1/completions _MsgspecRoute + - POST /v1/chat/completions _MsgspecRoute + - POST /v1/messages _MsgspecRoute + - POST /v1/messages/count_tokens _MsgspecRoute + - 'POST /v1/messages/batches _MsgspecRoute #anthropic_create_batch' + - 'GET /v1/messages/batches _MsgspecRoute #anthropic_list_batches' + - GET /v1/messages/batches/{batch_id} _MsgspecRoute + - DELETE /v1/messages/batches/{batch_id} _MsgspecRoute + - POST /v1/messages/batches/{batch_id}/cancel _MsgspecRoute + - GET /v1/messages/batches/{batch_id}/results _MsgspecRoute + - POST /v1/responses _MsgspecRoute + - GET /v1/responses/{response_id} _MsgspecRoute + - DELETE /v1/responses/{response_id} _MsgspecRoute + - POST /_internal/tokenize _MsgspecRoute + - 'POST /start_profile _MsgspecRoute #start_profile' + - 'POST /stop_profile _MsgspecRoute #stop_profile' + - GET /server_info _MsgspecRoute + mm_encoder: + kind: openai_server + routes: + - GET,HEAD /openapi.json Route + - GET,HEAD /docs Route + - GET,HEAD /docs/oauth2-redirect Route + - GET,HEAD /redoc Route + - GET /health _MsgspecRoute + - GET /version _MsgspecRoute + - GET /v1/models _MsgspecRoute + - GET /metrics _MsgspecRoute + - POST /v1/chat/completions _MsgspecRoute + mm_encoder_rl_control: + kind: openai_server + error: 'ValueError: RL control endpoints require AsyncLLM' + embedding: + kind: openai_server + routes: + - GET,HEAD /openapi.json Route + - GET,HEAD /docs Route + - GET,HEAD /docs/oauth2-redirect Route + - GET,HEAD /redoc Route + - GET /health _MsgspecRoute + - GET /version _MsgspecRoute + - GET /v1/models _MsgspecRoute + - POST /v1/embeddings _MsgspecRoute + embedding_runtime_control: + kind: openai_server + error: 'ValueError: Runtime control endpoints are not supported for embedding servers' + disagg_local: + kind: disagg_server + routes: + - GET,HEAD /openapi.json Route + - GET,HEAD /docs Route + - GET,HEAD /docs/oauth2-redirect Route + - GET,HEAD /redoc Route + - POST /v1/completions KvHintsRoute + - POST /v1/chat/completions KvHintsRoute + - POST /v1/messages KvHintsRoute + - POST /v1/messages/count_tokens KvHintsRoute + - POST /v1/responses KvHintsRoute + - GET /v1/models KvHintsRoute + - GET /health KvHintsRoute + - GET /cluster_info KvHintsRoute + - GET /version KvHintsRoute + - MOUNT /prometheus/metrics Mount + disagg_local_perf_metrics: + kind: disagg_server + routes: + - GET,HEAD /openapi.json Route + - GET,HEAD /docs Route + - GET,HEAD /docs/oauth2-redirect Route + - GET,HEAD /redoc Route + - POST /v1/completions KvHintsRoute + - POST /v1/chat/completions KvHintsRoute + - POST /v1/messages KvHintsRoute + - POST /v1/messages/count_tokens KvHintsRoute + - POST /v1/responses KvHintsRoute + - GET /v1/models KvHintsRoute + - GET /health KvHintsRoute + - GET /cluster_info KvHintsRoute + - GET /version KvHintsRoute + - MOUNT /prometheus/metrics Mount + disagg_local_http_cluster_storage: + kind: disagg_server + routes: + - GET,HEAD /openapi.json Route + - GET,HEAD /docs Route + - GET,HEAD /docs/oauth2-redirect Route + - GET,HEAD /redoc Route + - POST /v1/completions KvHintsRoute + - POST /v1/chat/completions KvHintsRoute + - POST /v1/messages KvHintsRoute + - POST /v1/messages/count_tokens KvHintsRoute + - POST /v1/responses KvHintsRoute + - GET /v1/models KvHintsRoute + - GET /health KvHintsRoute + - GET /cluster_info KvHintsRoute + - GET /version KvHintsRoute + - MOUNT /prometheus/metrics Mount + - POST /set KvHintsRoute + - GET /get KvHintsRoute + - DELETE /delete KvHintsRoute + - GET /expire KvHintsRoute + - GET /get_prefix KvHintsRoute + disagg_fleet: + kind: disagg_server + routes: + - GET,HEAD /openapi.json Route + - GET,HEAD /docs Route + - GET,HEAD /docs/oauth2-redirect Route + - GET,HEAD /redoc Route + - POST /v1/completions KvHintsRoute + - POST /v1/chat/completions KvHintsRoute + - POST /v1/messages KvHintsRoute + - POST /v1/messages/count_tokens KvHintsRoute + - POST /v1/responses KvHintsRoute + - GET /v1/models KvHintsRoute + - GET /health KvHintsRoute + - GET /cluster_info KvHintsRoute + - GET /version KvHintsRoute + - MOUNT /prometheus/metrics Mount + disagg_fleet_perf_metrics: + kind: disagg_server + routes: + - GET,HEAD /openapi.json Route + - GET,HEAD /docs Route + - GET,HEAD /docs/oauth2-redirect Route + - GET,HEAD /redoc Route + - POST /v1/completions KvHintsRoute + - POST /v1/chat/completions KvHintsRoute + - POST /v1/messages KvHintsRoute + - POST /v1/messages/count_tokens KvHintsRoute + - POST /v1/responses KvHintsRoute + - GET /v1/models KvHintsRoute + - GET /health KvHintsRoute + - GET /cluster_info KvHintsRoute + - GET /version KvHintsRoute + - MOUNT /prometheus/metrics Mount + disagg_fleet_http_cluster_storage: + kind: disagg_server + routes: + - GET,HEAD /openapi.json Route + - GET,HEAD /docs Route + - GET,HEAD /docs/oauth2-redirect Route + - GET,HEAD /redoc Route + - POST /v1/completions KvHintsRoute + - POST /v1/chat/completions KvHintsRoute + - POST /v1/messages KvHintsRoute + - POST /v1/messages/count_tokens KvHintsRoute + - POST /v1/responses KvHintsRoute + - GET /v1/models KvHintsRoute + - GET /health KvHintsRoute + - GET /cluster_info KvHintsRoute + - GET /version KvHintsRoute + - MOUNT /prometheus/metrics Mount + - POST /set KvHintsRoute + - GET /get KvHintsRoute + - DELETE /delete KvHintsRoute + - GET /expire KvHintsRoute + - GET /get_prefix KvHintsRoute + coordinator: + kind: coordinator_server + routes: + - GET,HEAD /openapi.json Route + - GET,HEAD /docs Route + - GET,HEAD /docs/oauth2-redirect Route + - GET,HEAD /redoc Route + - POST /select APIRoute + - POST /finish APIRoute + - POST /renew APIRoute + - GET /cluster_info APIRoute + - GET /health APIRoute + - GET /version APIRoute + coordinator_http_cluster_storage: + kind: coordinator_server + routes: + - GET,HEAD /openapi.json Route + - GET,HEAD /docs Route + - GET,HEAD /docs/oauth2-redirect Route + - GET,HEAD /redoc Route + - POST /select APIRoute + - POST /finish APIRoute + - POST /renew APIRoute + - GET /cluster_info APIRoute + - GET /health APIRoute + - GET /version APIRoute + - POST /set APIRoute + - GET /get APIRoute + - DELETE /delete APIRoute + - GET /expire APIRoute + - GET /get_prefix APIRoute + visual_gen: + kind: openai_server + routes: + - GET,HEAD /openapi.json Route + - GET,HEAD /docs Route + - GET,HEAD /docs/oauth2-redirect Route + - GET,HEAD /redoc Route + - GET /health _MsgspecRoute + - GET /version _MsgspecRoute + - GET /v1/models _MsgspecRoute + - GET /metrics _MsgspecRoute + - POST /v1/images/generations _MsgspecRoute + - POST /v1/images/edits _MsgspecRoute + - GET /v1/images/{image_id}/content _MsgspecRoute + - POST /v1/videos _MsgspecRoute + - POST /v1/videos/sync _MsgspecRoute + - POST /v1/videos/generations _MsgspecRoute + - GET /v1/videos _MsgspecRoute + - GET /v1/videos/{video_id} _MsgspecRoute + - GET /v1/videos/{video_id}/content _MsgspecRoute + - DELETE /v1/videos/{video_id} _MsgspecRoute diff --git a/tests/unittest/api_stability/test_serve_routes.py b/tests/unittest/api_stability/test_serve_routes.py new file mode 100644 index 000000000000..1392c1428ec3 --- /dev/null +++ b/tests/unittest/api_stability/test_serve_routes.py @@ -0,0 +1,251 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Route snapshot of every trtllm-serve configuration: a new api-stability gate. + +Each configuration's live routes must equal the generated reference +``references/trtllm_serve_routes.yaml``. Regenerating the reference cannot hide +the invariants at the bottom of this file: they are checked on the live apps. +The VisualGen configuration is checked by +``tests/unittest/serve/api/visual_gen/test_routes_visual_gen.py`` so that it +runs on VisualGen-only pull requests. +""" + +import pytest +from test_common.serve.routes import ( + CONFIGS, + VISUAL_GEN_CONFIGS, + compare, + format_failure, + read_reference, + snapshot_config, +) + +pytestmark = pytest.mark.cpu_only + + +@pytest.fixture(scope="module") +def reference(): + return read_reference() + + +@pytest.fixture(scope="module") +def live_snapshots(tmp_path_factory): + root = tmp_path_factory.mktemp("serve_routes") + return {config.name: snapshot_config(config, root / config.name) for config in CONFIGS} + + +def test_reference_configuration_names(reference): + expected = [config.name for config in CONFIGS + VISUAL_GEN_CONFIGS] + assert list(reference["configs"].keys()) == expected, ( + "The configuration names in references/trtllm_serve_routes.yaml must equal the " + "names in CONFIGS plus VISUAL_GEN_CONFIGS of tests/test_common/serve/routes.py, in " + "that order. Regenerate with `PYTHONPATH=tests python3 -m test_common.serve.routes " + "--write`." + ) + + +@pytest.mark.parametrize("name", [config.name for config in CONFIGS]) +def test_routes_match_reference(name, reference, live_snapshots): + recorded = reference["configs"][name] + live = live_snapshots[name] + assert recorded.get("error") == live.get("error"), ( + f"Configuration '{name}' now fails with {live.get('error')!r} instead of " + f"{recorded.get('error')!r}. If the change is intended, regenerate with " + "`PYTHONPATH=tests python3 -m test_common.serve.routes --write` and request review " + "from @NVIDIA/trt-llm-noncommitted-api-review-committee." + ) + differences = compare(recorded.get("routes", []), live.get("routes", [])) + assert not differences, format_failure(name, differences) + + +# --------------------------------------------------------------------------- +# Invariants checked on the live apps, independent of the reference. +# Regenerating the reference cannot hide these. +# --------------------------------------------------------------------------- + +_DOC_ROUTES = {"/openapi.json", "/docs", "/docs/oauth2-redirect", "/redoc"} + + +def _routes_of(live_snapshots, name): + return live_snapshots[name]["routes"] + + +def _parse(record): + parts = record.split(" ") + return parts[0], parts[1], parts[2] + + +def test_openai_server_routes_are_msgspec(live_snapshots): + for name, snapshot in live_snapshots.items(): + if snapshot.get("error") or snapshot["kind"] != "openai_server": + continue + for record in snapshot["routes"]: + methods, path, cls = _parse(record) + if path in _DOC_ROUTES: + assert cls == "Route", record + elif methods == "MOUNT": + assert cls == "Mount", record + else: + assert cls == "_MsgspecRoute", ( + f"configuration '{name}': {record}: every API route of the aggregated " + "server must keep the msgpack route class, or workers reject the " + "disaggregated frontend's msgpack bodies with 400/422 while plain JSON " + "still works." + ) + + +_API_ROUTE_CLASSES = { + "disagg_server": ( + "KvHintsRoute", + "every API route of the disaggregated frontend must keep KvHintsRoute: it strips " + "kv_hints from request bodies unless the server trusts its ingress " + "(TRTLLM_TRUST_KV_HINTS=1), and a plain APIRoute skips that policy.", + ), + "coordinator_server": ( + "APIRoute", + "the coordinator app registers FastAPI's plain routes; it takes neither the " + "disaggregated frontend's KvHintsRoute nor the aggregated server's msgpack route " + "class.", + ), +} + + +def test_disagg_and_coordinator_route_classes(live_snapshots): + for name, snapshot in live_snapshots.items(): + if snapshot.get("error") or snapshot["kind"] == "openai_server": + continue + expected, reason = _API_ROUTE_CLASSES[snapshot["kind"]] + for record in snapshot["routes"]: + methods, path, cls = _parse(record) + if path in _DOC_ROUTES: + assert cls == "Route", record + elif methods == "MOUNT": + assert cls == "Mount", record + else: + assert cls == expected, f"configuration '{name}': {record}: {reason}" + + +def test_control_route_groups(live_snapshots): + def paths(name): + return {_parse(record)[1] for record in _routes_of(live_snapshots, name)} + + rl = paths("llm_rl_control") + assert {"/release_memory", "/resume_memory", "/update_weights"} <= rl + assert "/memory_status" not in rl, ( + "the RL control group has no /memory_status; the runtime control group owns it" + ) + runtime = paths("llm_runtime_control") + assert {"/release_memory", "/resume_memory", "/memory_status"} <= runtime + assert "/update_weights" not in runtime, ( + "the runtime control group has no /update_weights; the RL control group owns it" + ) + control_paths = {"/release_memory", "/resume_memory", "/update_weights", "/memory_status"} + for name in ("llm", "llm_context", "llm_generation", "mm_encoder", "embedding"): + assert not control_paths & paths(name), ( + f"configuration '{name}' must register no memory-control route: those routes " + "exist only behind their construction-time switches." + ) + + +def test_metrics_presence_per_role(live_snapshots): + embedding_paths = {_parse(r)[1] for r in _routes_of(live_snapshots, "embedding")} + assert "/metrics" not in embedding_paths, ( + "the embedding server registers no /metrics today; keep the asymmetry until a " + "change deliberately adds it." + ) + mm_paths = {_parse(r)[1] for r in _routes_of(live_snapshots, "mm_encoder")} + assert "/metrics" in mm_paths + + +def test_launcher_forwarding_shadows_local_routes(live_snapshots): + """An attached frontend's forwarding routes precede the local handlers. + + Launcher-owned routes are registered before the local table with the same + method and path (or a path parameter that matches the same requests), and + FastAPI matches in registration order: flipping the order silently serves + launcher-owned state from the local process instead. + """ + records = _routes_of(live_snapshots, "llm_multi_frontend_attached") + base = _routes_of(live_snapshots, "llm") + assert len(records) == len(base) + 10, ( + "the attached-frontend configuration registers the ten launcher " + "forwarding routes on top of the default table" + ) + forward_positions = [i for i, r in enumerate(records) if r.endswith("#forward")] + assert len(forward_positions) == 7, records + for position in forward_positions: + methods_path = " ".join(records[position].split(" ")[:2]) + shadowed = [ + j + for j, record in enumerate(records) + if j != position and " ".join(record.split(" ")[:2]) == methods_path + ] + assert shadowed and all(position < j for j in shadowed), ( + f"{records[position]} must stay registered before the local handler of {methods_path}" + ) + rest_positions = [i for i, r in enumerate(records) if "{rest:path}" in _parse(r)[1]] + batch_id_positions = [i for i, r in enumerate(records) if "{batch_id}" in _parse(r)[1]] + assert rest_positions and batch_id_positions + assert max(rest_positions) < min(batch_id_positions), ( + "the batches forwarding routes (a path parameter that matches every " + "batch id) must stay registered before the local batch-id handlers" + ) + + +def test_metrics_shadowing_order(live_snapshots): + records = _routes_of(live_snapshots, "llm_perf_metrics_enable_metrics_env") + metrics = [r for r in records if _parse(r)[1] == "/metrics" and _parse(r)[0] == "GET"] + assert len(metrics) == 2, metrics + assert metrics[0].endswith("#get_iteration_stats") and metrics[1].endswith("#metrics"), ( + "the JSON /metrics route must stay registered before the Prometheus-text /metrics " + "route: FastAPI matches in registration order, so swapping them silently changes " + "the /metrics payload when ENABLE_METRICS is set." + ) + + +# The only configurations that fail at construction, with their exact errors. +_ERROR_CONFIGURATIONS = { + "llm_rl_and_runtime_control": ( + "ValueError: Legacy RL control and runtime control endpoints cannot both be enabled." + ), + "mm_encoder_rl_control": "ValueError: RL control endpoints require AsyncLLM", + "embedding_runtime_control": ( + "ValueError: Runtime control endpoints are not supported for embedding servers" + ), +} + + +def test_valid_configurations_build(live_snapshots): + failing = { + name: snapshot.get("error") + for name, snapshot in live_snapshots.items() + if name not in _ERROR_CONFIGURATIONS and "routes" not in snapshot + } + assert not failing, ( + f"these configurations must build but fail at construction: {failing}. Only the " + "configurations in _ERROR_CONFIGURATIONS may fail, and a regenerated reference that " + "records the error does not change that." + ) + + +def test_error_configurations(tmp_path): + by_name = {config.name: config for config in CONFIGS} + for name, message in _ERROR_CONFIGURATIONS.items(): + snapshot = snapshot_config(by_name[name], tmp_path / name) + assert snapshot.get("error") == message, ( + f"configuration '{name}' must fail at construction with exactly " + f"{message!r}, got {snapshot.get('error')!r}: the conflicting route groups are " + "rejected before any route is registered." + ) diff --git a/tests/unittest/api_stability/visual_gen/test_visual_gen_serve_api.py b/tests/unittest/api_stability/visual_gen/test_visual_gen_serve_api.py new file mode 100644 index 000000000000..f691dd23c5a8 --- /dev/null +++ b/tests/unittest/api_stability/visual_gen/test_visual_gen_serve_api.py @@ -0,0 +1,219 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""CI gate for the VisualGen request and response models of ``trtllm-serve``. + +Runs the checks of ``tests/unittest/api_stability/test_serve_api.py`` on the +models pinned in ``references/trtllm_serve_api.yaml`` that are defined in +``tensorrt_llm.serve.api.visual_gen.protocol``, and checks that +``tensorrt_llm.serve.openai_protocol`` keeps re-exporting them lazily under +their old names, without a warning. + +The file lives under a ``visual_gen/`` path so that CI selection for +VisualGen-only pull requests still runs it: the directory entry +``unittest/api_stability`` is not kept for those. The reference YAML is +unchanged and stays with the API review committee, which also owns this file. +""" + +from __future__ import annotations + +import importlib +import importlib.util +import json +import subprocess +import sys +import textwrap +from pathlib import Path +from typing import Any + +import pytest + +# The L0 CPU stage invokes registered files with `-m cpu_only`; without this +# marker every test is deselected and the stage collects nothing from the file. +pytestmark = pytest.mark.cpu_only + +_VISUAL_GEN_PROTOCOL_MODULE = "tensorrt_llm.serve.api.visual_gen.protocol" + +# The VisualGen models that `tensorrt_llm.serve.openai_protocol` re-exports. +_VISUAL_GEN_MODEL_NAMES = ( + "ImageGenerationRequest", + "ImageEditRequest", + "ImageObject", + "ImageGenerationResponse", + "MediaReferenceItem", + "VideoGenerationRequest", + "VideoJob", + "VideoJobList", +) + +# The VisualGen models the reference YAML pins today. The fixture below resolves +# every pinned model with the full gate's own loader, which fails for a renamed or +# removed model whatever its name, and selects the VisualGen ones by their defining +# module, so a model pinned later is gated automatically. This set is a secondary +# check that the four known models did not quietly stop being VisualGen models. +_PINNED_VISUAL_GEN_MODELS = frozenset( + { + "ImageGenerationRequest", + "ImageGenerationResponse", + "MediaReferenceItem", + "VideoGenerationRequest", + } +) + + +def _load_serve_api_checks(): + """Load ``test_serve_api.py`` by path, without pytest collecting it twice. + + The module is kept in a private name: a public ``TestServeAPIStability`` + in this module's namespace would be collected a second time, with the + whole reference instead of the VisualGen part of it. + """ + path = Path(__file__).resolve().parents[1] / "test_serve_api.py" + spec = importlib.util.spec_from_file_location("trtllm_serve_api_checks", path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +_serve_api = _load_serve_api_checks() + + +class TestVisualGenServeAPIStability(_serve_api.TestServeAPIStability): + """The serve API gate, restricted to the pinned VisualGen models.""" + + @pytest.fixture(scope="class") + def reference(self) -> dict[str, Any]: + """The reference YAML with only the models defined in the VisualGen package. + + Every pinned model is resolved through ``tensorrt_llm.serve.openai_protocol`` + with the full gate's own loader, so a pinned model that no longer resolves + there fails this gate too, whether or not it is a VisualGen model. A model + counts as VisualGen when the class it resolves to is defined in + ``tensorrt_llm.serve.api.visual_gen.protocol``. + """ + full = _serve_api._load_reference() + models: dict[str, Any] = {} + for model_name, model_spec in (full.get("models", {}) or {}).items(): + cls = _serve_api._load_model(model_name) + if cls.__module__ == _VISUAL_GEN_PROTOCOL_MODULE: + models[model_name] = model_spec + missing = sorted(_PINNED_VISUAL_GEN_MODELS - set(models)) + assert not missing, ( + f"trtllm_serve_api.yaml pins VisualGen models {missing} but they no longer " + f"resolve to {_VISUAL_GEN_PROTOCOL_MODULE} through {_serve_api._PROTOCOL_MODULE}. " + "Keep them in serve/api/visual_gen/protocol.py and in the lazy re-export of " + "openai_protocol; changes to the YAML need the API review committee." + ) + return {**full, "models": models} + + +def _run_in_fresh_interpreter(code: str) -> dict: + """Run ``code`` in a new interpreter and return the JSON it prints last.""" + result = subprocess.run( + [sys.executable, "-c", textwrap.dedent(code)], + capture_output=True, + text=True, + timeout=600, + ) + assert result.returncode == 0, ( + f"the probe interpreter exited with {result.returncode}; stdout tail: " + f"{result.stdout[-1000:]!r}; stderr tail: {result.stderr[-2000:]!r}" + ) + return json.loads(result.stdout.strip().splitlines()[-1]) + + +class TestVisualGenProtocolLazyReexport: + """``openai_protocol`` keeps the VisualGen names without importing their module.""" + + def test_importing_openai_protocol_does_not_load_visual_gen(self) -> None: + out = _run_in_fresh_interpreter( + f""" + import json, sys, warnings + import tensorrt_llm.serve.openai_protocol as protocol + + target = {_VISUAL_GEN_PROTOCOL_MODULE!r} + names = {list(_VISUAL_GEN_MODEL_NAMES)!r} + result = {{ + "before": target in sys.modules, + "importers": [], + "diagnostic_error": None, + "warned": [], + "errors": [], + }} + if result["before"]: + # Best effort and identity only: attribute access on arbitrary objects + # in sys.modules can raise (module-level __getattr__ hooks do), and the + # verdict below is printed whatever happens here. + try: + loaded = sys.modules[target] + held = [loaded] + [getattr(loaded, n) for n in names if hasattr(loaded, n)] + for module_name, module in list(sys.modules.items()): + if module is None or module is loaded: + continue + try: + values = list(vars(module).values()) + except TypeError: + continue + if any(value is obj for value in values for obj in held): + result["importers"].append(module_name) + result["importers"].sort() + except Exception as exc: + result["diagnostic_error"] = repr(exc) + with warnings.catch_warnings(): + warnings.simplefilter("error", FutureWarning) + warnings.simplefilter("error", DeprecationWarning) + for name in names: + try: + getattr(protocol, name) + except (FutureWarning, DeprecationWarning) as exc: + result["warned"].append(f"{{name}}: {{exc}}") + except Exception as exc: + result["errors"].append(f"{{name}}: {{exc!r}}") + result["after"] = target in sys.modules + print(json.dumps(result)) + """ + ) + diagnostic = ( + f" (diagnostic error: {out['diagnostic_error']})" if out["diagnostic_error"] else "" + ) + assert out["before"] is False, ( + f"importing tensorrt_llm.serve.openai_protocol loaded {_VISUAL_GEN_PROTOCOL_MODULE} " + f"eagerly; the modules holding its names are {out['importers']}{diagnostic}. The " + "VisualGen models are re-exported lazily through the module __getattr__ of " + "openai_protocol; do not import them at module level there." + ) + assert out["errors"] == [], ( + "reading the lazily re-exported names from tensorrt_llm.serve.openai_protocol " + f"failed: {out['errors']}" + ) + assert out["warned"] == [], ( + f"reading {out['warned']} from tensorrt_llm.serve.openai_protocol emitted a " + "FutureWarning or DeprecationWarning; the lazy re-export is openai_protocol's own " + "permanent interface and must not warn." + ) + assert out["after"] is True, ( + "reading the VisualGen names from openai_protocol did not import " + f"{_VISUAL_GEN_PROTOCOL_MODULE}; the lazy re-export no longer resolves them there." + ) + + def test_reexported_names_are_listed_and_unknown_names_raise(self) -> None: + protocol = importlib.import_module(_serve_api._PROTOCOL_MODULE) + listed = set(dir(protocol)) + not_listed = [name for name in _VISUAL_GEN_MODEL_NAMES if name not in listed] + assert not not_listed, ( + f"dir(tensorrt_llm.serve.openai_protocol) lacks {not_listed}; add the names to the " + "lazy re-export table of openai_protocol." + ) + with pytest.raises(AttributeError): + getattr(protocol, "NotAVisualGenModel") diff --git a/tests/unittest/disaggregated/test_coordinator_e2e.py b/tests/unittest/disaggregated/test_coordinator_e2e.py index 9b058001c2c8..530015a7f2c1 100644 --- a/tests/unittest/disaggregated/test_coordinator_e2e.py +++ b/tests/unittest/disaggregated/test_coordinator_e2e.py @@ -54,11 +54,11 @@ ServerRole, ) from tensorrt_llm.logger import logger +from tensorrt_llm.serve._base.msgspec_route import _MsgspecRequest from tensorrt_llm.serve.coordinator_server import CoordinatorServer from tensorrt_llm.serve.disagg_coordinator import DisaggCoordinatorService from tensorrt_llm.serve.openai_client import OpenAIHttpClient from tensorrt_llm.serve.openai_disagg_server import OpenAIDisaggServer -from tensorrt_llm.serve.openai_server import _MsgspecRequest GEN_TEXT = "HELLO_FROM_GEN" diff --git a/tests/unittest/disaggregated/test_msgspec_route.py b/tests/unittest/disaggregated/test_msgspec_route.py index e9c5e0269c08..f8a988d59e9f 100644 --- a/tests/unittest/disaggregated/test_msgspec_route.py +++ b/tests/unittest/disaggregated/test_msgspec_route.py @@ -19,8 +19,8 @@ from fastapi.testclient import TestClient from pydantic import BaseModel +from tensorrt_llm.serve._base.msgspec_route import _MsgspecRequest, _MsgspecRoute from tensorrt_llm.serve.openai_client import MSGPACK_HEADERS, _msgpack_encoder -from tensorrt_llm.serve.openai_server import _MsgspecRequest, _MsgspecRoute PAYLOAD = { "model": "m", diff --git a/tests/unittest/grpc/openengine/test_metrics.py b/tests/unittest/grpc/openengine/test_metrics.py index 3e97cc47d4b5..df3662fbeb30 100644 --- a/tests/unittest/grpc/openengine/test_metrics.py +++ b/tests/unittest/grpc/openengine/test_metrics.py @@ -15,6 +15,7 @@ from urllib.request import urlopen import pytest +from starlette.routing import Match pytestmark = [pytest.mark.cpu_only, pytest.mark.threadleak(enabled=False)] @@ -620,10 +621,16 @@ def _http_enablement() -> None: server = OpenAIServer(generator, "test-model", None, None, None) try: enabled = requested or output_dir is not None - assert ( - any(route.path == "/prometheus/metrics" for route in server.app.routes) - == enabled - ) + # Match a request instead of reading .path off app.routes: FastAPI + # 0.139 keeps included routers there as objects without a path. + scope = { + "type": "http", + "method": "GET", + "path": "/prometheus/metrics", + "path_params": {}, + } + exposed = any(route.matches(scope)[0] == Match.FULL for route in server.app.routes) + assert exposed == enabled assert server._expose_perf_metrics is requested assert server._collect_perf_metrics is enabled assert args.return_perf_metrics is enabled diff --git a/tests/unittest/llmapi/apps/test_context_length_error.py b/tests/unittest/llmapi/apps/test_context_length_error.py index c1004c1f8fdc..5a2cdfa4452c 100644 --- a/tests/unittest/llmapi/apps/test_context_length_error.py +++ b/tests/unittest/llmapi/apps/test_context_length_error.py @@ -169,3 +169,19 @@ def test_disagg_route_other_upstream_errors_unchanged(): _disagg_server()._handle_exception(_upstream_error(worker_body)) assert excinfo.value.status_code == 400 assert excinfo.value.detail == "`max_tokens` (0) must be greater than 0" + + +def test_serving_classes_share_the_server_error_factory(): + """OpenAIServer and the serving classes render errors through one function. + + The one function on BaseServing keeps the envelope and the context-length + code rule from drifting between serve/api/ and the composition root. + """ + from tensorrt_llm.serve._base.serving import BaseServing + + assert OpenAIServer.create_error_response is BaseServing.create_error_response + msg = context_length_exceeded_message(2048, 4096) + response = BaseServing().create_error_response(msg) + assert response.status_code == HTTPStatus.BAD_REQUEST + assert _body(response) == _body(OpenAIServer.create_error_response(msg)) + assert _body(response)["code"] == CONTEXT_LENGTH_EXCEEDED_CODE diff --git a/tests/unittest/llmapi/apps/visual_gen/__init__.py b/tests/unittest/llmapi/apps/visual_gen/__init__.py new file mode 100644 index 000000000000..52a7a9daf028 --- /dev/null +++ b/tests/unittest/llmapi/apps/visual_gen/__init__.py @@ -0,0 +1,2 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 diff --git a/tests/unittest/llmapi/apps/visual_gen/test_serve_visual_gen_isolation.py b/tests/unittest/llmapi/apps/visual_gen/test_serve_visual_gen_isolation.py new file mode 100644 index 000000000000..71e117de9709 --- /dev/null +++ b/tests/unittest/llmapi/apps/visual_gen/test_serve_visual_gen_isolation.py @@ -0,0 +1,745 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Import isolation of the VisualGen serving package, and where its tests live. + +CBTS, the CI test selector in ``jenkins/scripts/cbts/``, runs only VisualGen test +entries for a pull request whose changed files are all under +``tensorrt_llm/serve/api/visual_gen/``. That is safe only while no other serving +role, CLI entry point or test outside a ``visual_gen/`` path depends on the +package. The checks here fail as soon as that stops being true: + +- the static import graph of ``tensorrt_llm/``: the only references to the + package from outside it are the edges in ``ALLOWED_EDGES`` (importing one of + the VisualGen models from ``tensorrt_llm.serve.openai_protocol`` counts, since + that re-export loads the package); +- at run time, no non-VisualGen serving role and no CLI entry point loads the + package or the media helpers it uses; the VISUAL_GEN role does (the control + that proves the probe sees them); +- every test module that exercises VisualGen serving lives under a path that + contains ``visual_gen/``, or is listed in ``ALLOWED_NON_VG_TESTS`` with a + reason; +- test-db entries that name a ``visual_gen`` directory keep the trailing slash + the selector matches on. + +This file lives under a ``visual_gen/`` path so that VisualGen-only pull +requests run it. Changes to its allowlists are reviewed by the runtime team and +the owners of ``jenkins/scripts/cbts``. +""" + +from __future__ import annotations + +import ast +import json +import subprocess +import sys +import textwrap +from dataclasses import dataclass +from pathlib import Path +from typing import Dict, Iterator, List, Optional, Set, Tuple + +import pytest +import yaml + +__extra_import_path__ = ["~/jenkins/scripts/cbts"] +from cbts.rules.visual_gen import _entry_is_vg + +# The L0 CPU stage invokes registered files with `-m cpu_only`; the probes run in +# subprocesses and leave no threads behind to account for. +pytestmark = [pytest.mark.cpu_only, pytest.mark.threadleak(enabled=False)] + +REPO_ROOT = Path(__file__).resolve().parents[5] +TESTS_ROOT = REPO_ROOT / "tests" +TEST_DB_DIR = TESTS_ROOT / "integration" / "test_lists" / "test-db" +THIS_FILE = Path(__file__).resolve().relative_to(REPO_ROOT).as_posix() + +PACKAGE = "tensorrt_llm.serve.api.visual_gen" +PACKAGE_DIR = "tensorrt_llm/serve/api/visual_gen" + +# Modules only the VISUAL_GEN role may load: the serving package and the media +# helpers its handlers import at module level. +WATCHED_MODULES = (PACKAGE, "tensorrt_llm.media.encoding", "tensorrt_llm.media.tensor_payload") + +# The VisualGen request and response models that tensorrt_llm.serve.openai_protocol +# re-exports lazily under their old names. +VISUAL_GEN_PROTOCOL_MODELS = frozenset( + { + "ImageGenerationRequest", + "ImageEditRequest", + "ImageObject", + "ImageGenerationResponse", + "MediaReferenceItem", + "VideoGenerationRequest", + "VideoJob", + "VideoJobList", + } +) +# The module that re-exports them lazily under their old names; importing one of them from +# here loads the VisualGen package, so such an import counts as a reference to it. +OPENAI_PROTOCOL_MODULE = "tensorrt_llm.serve.openai_protocol" + +# Every reference the scans below look for contains one of these substrings: the +# package's dotted and slashed names, the role, or a VisualGen model's name. A file +# without any of them is skipped before parsing. +_SCAN_NEEDLES = ("visual_gen", "VISUAL_GEN", *sorted(VISUAL_GEN_PROTOCOL_MODELS)) + +EdgeKey = Tuple[str, str, str, str] # (file, scope, kind, target) + + +def _openai_protocol_file() -> str: + """The module that re-exports the VisualGen models: a module today, a package later.""" + as_package = "tensorrt_llm/serve/openai_protocol/__init__.py" + if (REPO_ROOT / as_package).exists(): + return as_package + return "tensorrt_llm/serve/openai_protocol.py" + + +# Every reference to the package from outside it, with the reason it is allowed. +# Kinds: "import" (an import statement, `if TYPE_CHECKING:` included, and an import +# of a VisualGen model from tensorrt_llm.serve.openai_protocol), "importlib" +# (importlib.import_module or __import__ with a literal name) and "string" (any +# other string literal naming a module of the package, such as a routing table). +ALLOWED_EDGES: Dict[EdgeKey, str] = { + ( + "tensorrt_llm/serve/openai_server.py", + "OpenAIServer.register_visual_gen_routes", + "importlib", + f"{PACKAGE}.api_router", + ): "the composition root: the one place that loads the VisualGen router, for the VISUAL_GEN " + "role only", + ( + "tensorrt_llm/serve/_base/routing.py", + "", + "string", + f"{PACKAGE}.api_router", + ): "the VisualGen entry of the routing table, which names router modules by dotted path", + ( + _openai_protocol_file(), + "", + "string", + f"{PACKAGE}.protocol", + ): "the lazy re-export of the VisualGen models under their old names: a name table, never " + "an import", + ( + "tensorrt_llm/serve/scripts/benchmark_visual_gen.py", + "", + "import", + f"{PACKAGE}.metrics", + ): "the VisualGen benchmark client", + ( + "tensorrt_llm/serve/scripts/benchmark_visual_gen.py", + "", + "import", + f"{PACKAGE}.protocol", + ): "the VisualGen benchmark client", +} + +# Test modules outside a visual_gen/ path that match a criterion below without +# exercising VisualGen serving, with the reason. +ALLOWED_NON_VG_TESTS: Dict[str, str] = { + "tests/unittest/disaggregated/test_disagg_internal_auth.py": ( + "passes ServerRole.VISUAL_GEN as a role value to validate_subagent_affinity; starts no " + "VisualGen serving" + ), + "tests/unittest/serve/_base/test_routing.py": ( + "checks that role_group_of maps ServerRole.VISUAL_GEN to its role group; starts no " + "VisualGen serving" + ), +} + + +# --------------------------------------------------------------------------- +# Shared AST helpers +# --------------------------------------------------------------------------- + + +def _is_in_package(module: str) -> bool: + return module == PACKAGE or module.startswith(PACKAGE + ".") + + +def _docstring_nodes(tree: ast.AST) -> Set[int]: + """Ids of the string constants that are docstrings; documentation is not a reference.""" + ids: Set[int] = set() + for node in ast.walk(tree): + if isinstance(node, (ast.Module, ast.ClassDef, ast.FunctionDef, ast.AsyncFunctionDef)): + body = node.body + if ( + body + and isinstance(body[0], ast.Expr) + and isinstance(body[0].value, ast.Constant) + and isinstance(body[0].value.value, str) + ): + ids.add(id(body[0].value)) + return ids + + +def _is_import_call(func: ast.expr) -> bool: + if isinstance(func, ast.Attribute): + return func.attr == "import_module" + return isinstance(func, ast.Name) and func.id in ("import_module", "__import__") + + +def _literal_import_argument(node: ast.Call) -> Optional[ast.Constant]: + """The literal module name of an importlib.import_module / __import__ call, if any.""" + if not _is_import_call(node.func) or not node.args: + return None + first = node.args[0] + if isinstance(first, ast.Constant) and isinstance(first.value, str): + return first + return None + + +def _resolve_relative(package: str, level: int, module: Optional[str]) -> Optional[str]: + if level == 0: + return module + parts = package.split(".") if package else [] + if level - 1 > len(parts): + return None + base = parts[: len(parts) - (level - 1)] + if module: + base.extend(module.split(".")) + return ".".join(base) if base else None + + +def _module_name(file: str) -> str: + """Dotted module name of a repo-relative ``.py`` path.""" + parts = file[: -len(".py")].split("/") + if parts[-1] == "__init__": + parts = parts[:-1] + return ".".join(parts) + + +# --------------------------------------------------------------------------- +# Static import graph (the first check) +# --------------------------------------------------------------------------- + + +@dataclass(frozen=True) +class Edge: + """One reference from a module outside the package to a module inside it.""" + + file: str # repo-relative path of the referencing file + scope: str # enclosing definitions, dotted; "" at module level + kind: str # "import", "importlib" or "string" + target: str # the referenced module + lineno: int + + @property + def key(self) -> EdgeKey: + return (self.file, self.scope, self.kind, self.target) + + +class _EdgeCollector(ast.NodeVisitor): + def __init__(self, file: str, package: str, skip: Set[int]) -> None: + self._file = file + self._package = package + self._skip = skip # ids of string constants that are not references + self._scope: List[str] = [] + self.edges: List[Edge] = [] + + def _add(self, kind: str, target: str, lineno: int) -> None: + scope = ".".join(self._scope) or "" + self.edges.append(Edge(self._file, scope, kind, target, lineno)) + + def _visit_definition(self, node) -> None: + self._scope.append(node.name) + self.generic_visit(node) + self._scope.pop() + + visit_FunctionDef = _visit_definition + visit_AsyncFunctionDef = _visit_definition + visit_ClassDef = _visit_definition + + def visit_Import(self, node: ast.Import) -> None: + for alias in node.names: + if _is_in_package(alias.name): + self._add("import", alias.name, node.lineno) + + def visit_ImportFrom(self, node: ast.ImportFrom) -> None: + module = _resolve_relative(self._package, node.level, node.module) + if module is None: + return + if _is_in_package(module): + self._add("import", module, node.lineno) + return + for alias in node.names: + # `from tensorrt_llm.serve.api import visual_gen` imports the package. + if _is_in_package(f"{module}.{alias.name}"): + self._add("import", f"{module}.{alias.name}", node.lineno) + # The VisualGen models re-exported by openai_protocol load the package on access. + elif alias.name in VISUAL_GEN_PROTOCOL_MODELS and module == OPENAI_PROTOCOL_MODULE: + self._add("import", f"{module}.{alias.name}", node.lineno) + + def visit_Call(self, node: ast.Call) -> None: + literal = _literal_import_argument(node) + if literal is not None: + if _is_in_package(literal.value): + self._add("importlib", literal.value, node.lineno) + self._skip.add(id(literal)) # recorded as this call's edge, not again as a string + self.generic_visit(node) + + def visit_Constant(self, node: ast.Constant) -> None: + if id(node) in self._skip: + return + if isinstance(node.value, str) and _is_in_package(node.value): + self._add("string", node.value, node.lineno) + + +def edges_in_source(source: str, file: str) -> List[Edge]: + """Every reference to the package in the source of the module at ``file``.""" + tree = ast.parse(source) + module = _module_name(file) + package = module if file.endswith("__init__.py") else module.rpartition(".")[0] + collector = _EdgeCollector(file, package, _docstring_nodes(tree)) + collector.visit(tree) + return collector.edges + + +def edges_into_package(repo_root: Path) -> List[Edge]: + """Every reference to the package from a module under ``tensorrt_llm/`` outside it.""" + edges: List[Edge] = [] + for path in sorted((repo_root / "tensorrt_llm").rglob("*.py")): + file = path.relative_to(repo_root).as_posix() + if file.startswith(PACKAGE_DIR + "/"): + continue + source = path.read_text(errors="replace") + if not any(needle in source for needle in _SCAN_NEEDLES): # a reference always contains one + continue + edges.extend(edges_in_source(source, file)) + return edges + + +def _unexpected_edge(edge: Edge) -> str: + verb = "names" if edge.kind == "string" else "imports" + return ( + f"{edge.file}:{edge.lineno} ({edge.scope}) {verb} `{edge.target}`. Code outside " + f"{PACKAGE_DIR}/ must not import VisualGen serving: CBTS runs only VisualGen tests for " + "changes under that package, so an LLM, embedding or disaggregated path that imports it " + "would lose its tests. Reach VisualGen through the composition root's role-gated load. " + f"If this edge is needed, add it to ALLOWED_EDGES in {THIS_FILE} with a reason; the " + "runtime team and the owners of jenkins/scripts/cbts review that change." + ) + + +def _stale_edge(key: EdgeKey) -> str: + file, scope, kind, target = key + return ( + f"allowed edge {file} ({scope}, {kind}) `{target}` no longer exists; remove it from " + f"ALLOWED_EDGES in {THIS_FILE}." + ) + + +def test_no_module_outside_the_package_imports_visual_gen_serving() -> None: + found: Dict[EdgeKey, Edge] = {} + for edge in edges_into_package(REPO_ROOT): + found.setdefault(edge.key, edge) # equal (file, scope, kind, target) count once + + problems = [ + _unexpected_edge(edge) for key, edge in sorted(found.items()) if key not in ALLOWED_EDGES + ] + problems += [_stale_edge(key) for key in ALLOWED_EDGES if key not in found] + assert not problems, "\n".join(problems) + + +# --------------------------------------------------------------------------- +# Runtime checks per role and per CLI entry point (the second check) +# --------------------------------------------------------------------------- + +# Each probe runs in a fresh interpreter: the pytest process has already imported +# VisualGen modules through other tests, so sys.modules there proves nothing. +_PROBE_PRELUDE = """ +import json +import sys + +WATCHED = tuple(json.loads(sys.argv[1])) + + +def loaded(): + return sorted( + name for name in sys.modules if any(name == w or name.startswith(w + ".") for w in WATCHED) + ) +""" + +# Builds every non-VisualGen app through the fixture factory, one after another, +# and records the watched modules present after each build and its first request. +_ROLE_PROBE = ( + _PROBE_PRELUDE + + """ +import tempfile +from pathlib import Path + +sys.path.insert(0, sys.argv[2]) # tests/: the fixture factory and its fakes, nothing else +tmp_root = sys.argv[3] +steps = json.loads(sys.argv[4]) + +from tensorrt_llm.llmapi.disagg_utils import ServerRole +from test_common.serve.app_factory import ( + AggConfig, + CoordinatorConfig, + DisaggConfig, + isolated_serve_env, +) + +configs = { + "the default LLM role": ("openai_server", AggConfig()), + "the CONTEXT role": ("openai_server", AggConfig(role=ServerRole.CONTEXT)), + "the GENERATION role": ("openai_server", AggConfig(role=ServerRole.GENERATION)), + "the MM_ENCODER role": ("openai_server", AggConfig(role=ServerRole.MM_ENCODER)), + "the EMBEDDING role": ("openai_server", AggConfig(role=ServerRole.EMBEDDING)), + "the disaggregated frontend with a local coordinator": ("disagg_server", DisaggConfig()), + "the disaggregated frontend in fleet mode": ("disagg_server", DisaggConfig(fleet=True)), + "the fleet coordinator": ("coordinator_server", CoordinatorConfig()), +} +report = {"importing the fixture factory": {"loaded": loaded(), "health": None}} +for step in steps: + kind, config = configs[step] + with tempfile.TemporaryDirectory(dir=tmp_root) as tmp_dir, isolated_serve_env(Path(tmp_dir)) as env: + if kind == "openai_server": + app = env.build_openai_server(config).app + client = env.client(app) + elif kind == "disagg_server": + # The disaggregated lifespan connects to its workers; /health answers without it. + app = env.build_disagg_server(config).app + client = env.client(app, lifespan=False) + else: + app = env.build_coordinator_server(config).app + client = env.client(app, lifespan=False) + # Every app serves /health; the request is sent unconditionally rather than after + # finding the route in app.routes, where FastAPI 0.139 nests included routers. A + # handler that imports VisualGen at request time only shows up after this call. + status = client.get("/health").status_code + report["starting " + step] = {"loaded": loaded(), "health": status} +print(json.dumps(report)) +""" +) + +# Runs every trtllm-serve subcommand's --help and trtllm-render --help. +_CLI_PROBE = ( + _PROBE_PRELUDE + + """ +import contextlib +import io + +report = {} +from tensorrt_llm.commands.serve import main + +report["importing tensorrt_llm.commands.serve"] = loaded() +with contextlib.redirect_stdout(io.StringIO()): + main(["--help"], standalone_mode=False) +report["running trtllm-serve --help"] = loaded() +for name in sorted(main.commands): + with contextlib.redirect_stdout(io.StringIO()): + main([name, "--help"], standalone_mode=False) + report["running trtllm-serve " + name + " --help"] = loaded() + +from tensorrt_llm.serve.render.__main__ import main as render_main + +with contextlib.suppress(SystemExit), contextlib.redirect_stdout(io.StringIO()): + render_main(["--help"]) +report["running trtllm-render --help"] = loaded() +print(json.dumps(report)) +""" +) + +# The control: the VISUAL_GEN app must load the watched modules. +_VISUAL_GEN_PROBE = ( + _PROBE_PRELUDE + + """ +import tempfile +from pathlib import Path + +sys.path.insert(0, sys.argv[2]) +tmp_root = sys.argv[3] + +from tensorrt_llm.llmapi.disagg_utils import ServerRole +from test_common.serve.app_factory import AggConfig, isolated_serve_env + +with tempfile.TemporaryDirectory(dir=tmp_root) as tmp_dir, isolated_serve_env(Path(tmp_dir)) as env: + config = AggConfig(role=ServerRole.VISUAL_GEN, model_name="fake-visual-gen") + app = env.build_openai_server(config).app + status = env.client(app).get("/health").status_code +print(json.dumps({"health": status, "loaded": loaded()})) +""" +) + +NON_VISUAL_GEN_STEPS = ( + "the default LLM role", + "the CONTEXT role", + "the GENERATION role", + "the MM_ENCODER role", + "the EMBEDDING role", + "the disaggregated frontend with a local coordinator", + "the disaggregated frontend in fleet mode", + "the fleet coordinator", +) + + +def _run_in_fresh_interpreter(code: str, *args: str) -> dict: + """Run ``code`` in a new interpreter and return the JSON it prints last.""" + result = subprocess.run( + [sys.executable, "-c", textwrap.dedent(code), *args], + capture_output=True, + text=True, + timeout=900, + ) + assert result.returncode == 0, result.stderr[-4000:] + return json.loads(result.stdout.strip().splitlines()[-1]) + + +def _runtime_problem(step: str, module: str) -> str: + return ( + f"{step[:1].upper()}{step[1:]} imported `{module}`, which only the VISUAL_GEN role may " + f"load. CBTS runs only VisualGen tests for changes under {PACKAGE_DIR}/, so this path " + "would no longer be tested by them. Find the import with " + "test_no_module_outside_the_package_imports_visual_gen_serving (this file) or " + "`python -X importtime`, and load VisualGen code only from the composition root's " + "VISUAL_GEN branch." + ) + + +def test_non_visual_gen_roles_do_not_load_visual_gen_serving(tmp_path: Path) -> None: + report = _run_in_fresh_interpreter( + _ROLE_PROBE, + json.dumps(WATCHED_MODULES), + str(TESTS_ROOT), + str(tmp_path), + json.dumps(NON_VISUAL_GEN_STEPS), + ) + # Every step ran: a probe that skipped a role would pass vacuously. + expected_steps = ( + "importing the fixture factory", + *("starting " + s for s in NON_VISUAL_GEN_STEPS), + ) + assert tuple(report) == expected_steps + # Every app answered its first request: the request path ran, not only construction. + unanswered = [ + step for step in expected_steps[1:] if not isinstance(report[step]["health"], int) + ] + assert not unanswered, ( + f"no /health response after {unanswered}; the probe skipped the request path" + ) + problems = [ + _runtime_problem(step, module) + for step, result in report.items() + for module in result["loaded"] + ] + assert not problems, "\n".join(problems) + + +def test_cli_entry_points_do_not_load_visual_gen_serving() -> None: + report = _run_in_fresh_interpreter(_CLI_PROBE, json.dumps(WATCHED_MODULES)) + assert "running trtllm-serve serve --help" in report + assert "running trtllm-render --help" in report + problems = [ + _runtime_problem(step, module) for step, modules in report.items() for module in modules + ] + assert not problems, "\n".join(problems) + + +def test_visual_gen_role_loads_visual_gen_serving(tmp_path: Path) -> None: + report = _run_in_fresh_interpreter( + _VISUAL_GEN_PROBE, json.dumps(WATCHED_MODULES), str(TESTS_ROOT), str(tmp_path) + ) + assert report["health"] == 200 + for module in (f"{PACKAGE}.api_router", "tensorrt_llm.media.encoding"): + assert module in report["loaded"], ( + f"Building the VISUAL_GEN app did not load `{module}`: the probe the other tests in " + "this file rely on no longer sees VisualGen serving. Fix the probe or the fixture " + "factory before trusting them." + ) + + +# --------------------------------------------------------------------------- +# VisualGen serving tests live under visual_gen/ paths (the third check) +# --------------------------------------------------------------------------- + + +@dataclass(frozen=True) +class Match: + lineno: int + criterion: str + + +def _last_name(node: ast.expr) -> Optional[str]: + if isinstance(node, ast.Name): + return node.id + if isinstance(node, ast.Attribute): + return node.attr + return None + + +def visual_gen_serving_criteria(source: str) -> List[Match]: + """Why a test module counts as a VisualGen serving test; empty when it does not. + + A test module exercises VisualGen serving when, at any scope, it imports the + package or a submodule, names one of them in a string (a patch target), uses + ``ServerRole.VISUAL_GEN`` or ``launch_visual_gen_server`` as a name or + attribute (not inside a string), or imports one of the VisualGen models from + ``tensorrt_llm.serve.openai_protocol``. Docstrings are not references. + """ + tree = ast.parse(source) + skip = _docstring_nodes(tree) + matches: List[Match] = [] + for node in ast.walk(tree): + if isinstance(node, ast.Import): + for alias in node.names: + if _is_in_package(alias.name): + matches.append(Match(node.lineno, f"imports {alias.name}")) + elif isinstance(node, ast.ImportFrom) and node.level == 0 and node.module: + if _is_in_package(node.module): + matches.append(Match(node.lineno, f"imports {node.module}")) + continue + for alias in node.names: + name = f"{node.module}.{alias.name}" + if _is_in_package(name): + matches.append(Match(node.lineno, f"imports {name}")) + elif ( + node.module == OPENAI_PROTOCOL_MODULE + and alias.name in VISUAL_GEN_PROTOCOL_MODELS + ): + matches.append( + Match( + node.lineno, + f"imports {alias.name} from tensorrt_llm.serve.openai_protocol", + ) + ) + elif isinstance(node, ast.Constant): + if id(node) in skip or not isinstance(node.value, str): + continue + if _is_in_package(node.value): + matches.append(Match(node.lineno, f"names {node.value} in a string")) + elif isinstance(node, ast.Attribute): + if node.attr == "VISUAL_GEN" and _last_name(node.value) == "ServerRole": + matches.append(Match(node.lineno, "uses ServerRole.VISUAL_GEN")) + elif node.attr == "launch_visual_gen_server": + matches.append(Match(node.lineno, "uses launch_visual_gen_server")) + elif isinstance(node, ast.Name) and node.id == "launch_visual_gen_server": + matches.append(Match(node.lineno, "uses launch_visual_gen_server")) + return sorted(set(matches), key=lambda match: (match.lineno, match.criterion)) + + +def is_test_module(path: Path) -> bool: + """Pytest's default ``python_files``; the repository's pytest.ini files keep it.""" + return path.suffix == ".py" and ( + path.name.startswith("test_") or path.name.endswith("_test.py") + ) + + +def visual_gen_serving_tests(tests_root: Path, repo_root: Path) -> Dict[str, List[Match]]: + """Repo-relative path -> matches, for every test module that exercises VisualGen serving. + + Helper modules (``conftest.py``, ``tests/test_common/**``, anything not named + like a test) are not scanned: they run only through a test module, whose own + path decides the selection. + """ + found: Dict[str, List[Match]] = {} + for path in sorted(tests_root.rglob("*.py")): + if not is_test_module(path): + continue + source = path.read_text(errors="replace") + if not any(needle in source for needle in _SCAN_NEEDLES): + continue + matches = visual_gen_serving_criteria(source) + if matches: + found[path.relative_to(repo_root).as_posix()] = matches + return found + + +def _misplaced_test(path: str, match: Match) -> str: + return ( + f"{path} exercises VisualGen serving ({match.criterion} at line {match.lineno}) but its " + "path does not contain visual_gen/, so CBTS does not run it for VisualGen-only pull " + "requests. Move it under a directory whose path contains visual_gen/ " + "(tests/unittest/serve/api/visual_gen/ for serve tests, tests/unittest/_torch/visual_gen/ " + "for runtime tests) and update its entry in tests/integration/test_lists/test-db/l0_cpu.yml, " + "or, if it does not exercise VisualGen serving, add it to ALLOWED_NON_VG_TESTS in " + f"{THIS_FILE} with a reason." + ) + + +def test_visual_gen_serving_tests_live_under_visual_gen_paths() -> None: + found = visual_gen_serving_tests(TESTS_ROOT, REPO_ROOT) + # The scan sees the VisualGen serving tests that do exist; otherwise it is broken. + assert any(_entry_is_vg(path) for path in found), "no VisualGen serving test found at all" + + problems = [] + for path, matches in sorted(found.items()): + if _entry_is_vg(path) or path in ALLOWED_NON_VG_TESTS: + continue + problems.append(_misplaced_test(path, matches[0])) + for path in ALLOWED_NON_VG_TESTS: + if path not in found: + problems.append( + f"{path} is listed in ALLOWED_NON_VG_TESTS but matches no criterion of a " + f"VisualGen serving test (or no longer exists); remove it from " + f"ALLOWED_NON_VG_TESTS in {THIS_FILE}." + ) + assert not problems, "\n".join(problems) + + +# --------------------------------------------------------------------------- +# Test-db entries keep the trailing slash (the fourth check) +# --------------------------------------------------------------------------- + + +def iter_test_db_entries(yml: Path) -> Iterator[str]: + """The ``tests:`` entries of every block of one test-db YAML file.""" + data = yaml.safe_load(yml.read_text()) or {} + for blocks in data.values(): + if not isinstance(blocks, list): + continue + for block in blocks: + if not isinstance(block, dict): + continue + for entry in block.get("tests") or []: + if isinstance(entry, str): + yield entry + + +def _entry_path(entry: str) -> str: + """The test path of an entry: the text before the first space and before ``::``.""" + words = entry.split() + return words[0].split("::")[0] if words else "" + + +def names_visual_gen_directory(entry: str) -> bool: + """The entry's test path has a component named exactly ``visual_gen``.""" + return "visual_gen" in _entry_path(entry).split("/") + + +def with_trailing_slash(entry: str) -> str: + """The entry with ``/`` appended to its test path, options and node ids kept.""" + path = _entry_path(entry) + return entry.replace(path, path + "/", 1) + + +def test_visual_gen_test_db_entries_keep_the_trailing_slash() -> None: + problems = [] + checked = 0 + for yml in sorted(TEST_DB_DIR.glob("*.yml")): + for entry in iter_test_db_entries(yml): + if not names_visual_gen_directory(entry): + continue + checked += 1 + if _entry_is_vg(entry): + continue + problems.append( + f"{yml.relative_to(REPO_ROOT).as_posix()}: test-db entry `{entry}` names a " + "visual_gen directory without the trailing slash. CBTS keeps an entry for " + "VisualGen-only pull requests only if its text contains visual_gen/ " + "(_VG_ENTRY_PATTERNS in jenkins/scripts/cbts/cbts/rules/visual_gen.py). Write " + f"`{with_trailing_slash(entry)}`." + ) + assert checked, "no test-db entry names a visual_gen directory; the scan is broken" + assert not problems, "\n".join(problems) diff --git a/tests/unittest/llmapi/test_kv_hints.py b/tests/unittest/llmapi/test_kv_hints.py index 218e7482d8a6..e73a6097d2d8 100644 --- a/tests/unittest/llmapi/test_kv_hints.py +++ b/tests/unittest/llmapi/test_kv_hints.py @@ -739,9 +739,9 @@ def test_http_ingress_policy_before_nested_validation( from fastapi import FastAPI from fastapi.testclient import TestClient + from tensorrt_llm.serve._base.msgspec_route import _MsgspecRoute from tensorrt_llm.serve.kv_hints import KvHintsRoute from tensorrt_llm.serve.openai_protocol import CompletionRequest, ResponsesRequest - from tensorrt_llm.serve.openai_server import _MsgspecRoute hints = _wire() if hint_kind == "unknown": @@ -832,9 +832,9 @@ def test_ignored_hints_do_not_relax_http_request_validation( from fastapi import FastAPI from fastapi.testclient import TestClient + from tensorrt_llm.serve._base.msgspec_route import _MsgspecRoute from tensorrt_llm.serve.kv_hints import KvHintsRoute from tensorrt_llm.serve.openai_protocol import CompletionRequest - from tensorrt_llm.serve.openai_server import _MsgspecRoute app = FastAPI() app.state.trust_kv_hints = True diff --git a/tests/unittest/llmapi/test_serve_multi_frontend_helpers.py b/tests/unittest/llmapi/test_serve_multi_frontend_helpers.py index 0a6f3b9055bb..add864bb829d 100644 --- a/tests/unittest/llmapi/test_serve_multi_frontend_helpers.py +++ b/tests/unittest/llmapi/test_serve_multi_frontend_helpers.py @@ -35,7 +35,9 @@ from tensorrt_llm._utils import AdjustedSteadyClock from tensorrt_llm.llmapi.disagg_utils import ServerRole from tensorrt_llm.serve import _frontend_processes, openai_server +from tensorrt_llm.serve._base.routing import ServerCapabilities, attach_routers from tensorrt_llm.serve._frontend_processes import _watch_attached_frontends +from tensorrt_llm.serve.api.ops.system.serving import SystemServing from tensorrt_llm.serve.multi_frontend import ( FORWARDED_ROUTES, AttachedFrontendWatchdog, @@ -111,7 +113,11 @@ async def lifespan(_: FastAPI): server._enable_runtime_control_endpoints = False server.resource_governor = None server._launcher_forwarder = forwarder - # The order OpenAIServer.__init__ registers them in. + # The order OpenAIServer.__init__ registers them in: the system router + # (/health, /version, /v1/models) first, then the launcher forwarding + # routes, then the local table. + server.app.state.ops_serving_system = SystemServing(model="m", health_probe=lambda: True) + attach_routers(server.app, ServerCapabilities.for_role(None)) server._register_launcher_forwarding_routes() server.register_routes() return server diff --git a/tests/unittest/llmapi/test_serve_multi_frontend_route_gate.py b/tests/unittest/llmapi/test_serve_multi_frontend_route_gate.py index e477c020d314..f419d5458da0 100644 --- a/tests/unittest/llmapi/test_serve_multi_frontend_route_gate.py +++ b/tests/unittest/llmapi/test_serve_multi_frontend_route_gate.py @@ -25,7 +25,10 @@ import pytest from fastapi import FastAPI from starlette.routing import Match +from test_common.serve.routes import effective_routes +from tensorrt_llm.serve._base.routing import ServerCapabilities, attach_routers +from tensorrt_llm.serve.api.ops.system.serving import SystemServing from tensorrt_llm.serve.multi_frontend import FORWARDED_ROUTES from tensorrt_llm.serve.openai_server import OpenAIServer @@ -73,10 +76,16 @@ def _llm_server_routes() -> list[tuple[str, str]]: server._enable_rl_control_endpoints = True server._enable_runtime_control_endpoints = True server.resource_governor = None + # As OpenAIServer.__init__ does: the system router (/health, /version, + # /v1/models) is attached for every role before the role's own table. + server.app.state.ops_serving_system = SystemServing(model="m", health_probe=lambda: True) + attach_routers(server.app, ServerCapabilities.for_role(None)) server.register_routes() + # effective_routes walks included routers, which FastAPI 0.139 keeps as + # objects without .path or .methods in app.routes. return sorted( - (method, route.path) - for route in server.app.routes + (method, path) + for path, route in effective_routes(server.app) if getattr(route, "methods", None) for method in route.methods if method != "HEAD" diff --git a/tests/unittest/scripts/cbts/test_docs.py b/tests/unittest/scripts/cbts/test_docs.py index a2a8700ad7a3..f8a8332220c2 100644 --- a/tests/unittest/scripts/cbts/test_docs.py +++ b/tests/unittest/scripts/cbts/test_docs.py @@ -176,6 +176,7 @@ def test_documentation_does_not_trigger_backend_rules() -> None: assert not _is_openengine_claim("tensorrt_llm/grpc/openengine/guide.rst") assert not _is_spec_claim("examples/eagle/guide.rst") assert not _is_vg_claim("examples/visual_gen/guide.rst") + assert not _is_vg_claim("tensorrt_llm/serve/api/visual_gen/guide.rst") def test_modeling_v2_entries_cover_unit_and_accuracy_tests() -> None: diff --git a/tests/unittest/scripts/cbts/test_visual_gen_rule.py b/tests/unittest/scripts/cbts/test_visual_gen_rule.py new file mode 100644 index 000000000000..fa00f83a47e6 --- /dev/null +++ b/tests/unittest/scripts/cbts/test_visual_gen_rule.py @@ -0,0 +1,111 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""VisualGenRule claims the VisualGen serving package and narrows to VisualGen entries.""" + +from __future__ import annotations + +import pytest + +__extra_import_path__ = ["~/jenkins/scripts/cbts"] +from cbts.blocks import Block, Stage, YAMLIndex +from cbts.command.main import Selector +from cbts.rules.base import PRInputs +from cbts.rules.visual_gen import _VG_OUTWARD_PREFIXES, VisualGenRule, _is_vg_claim + +pytestmark = pytest.mark.cpu_only + +SERVE_PACKAGE = "tensorrt_llm/serve/api/visual_gen/" +CPU_STAGE = "CPU-Generic-x86-1" +VISUAL_GEN_ENTRIES = ( + "unittest/_torch/visual_gen/test_trtllm_serve_endpoints.py", + "unittest/llmapi/apps/visual_gen/test_serve_visual_gen_isolation.py", + "unittest/api_stability/visual_gen/test_visual_gen_serve_api.py", +) +OTHER_ENTRIES = ( + "unittest/api_stability", + "unittest/llmapi/apps/test_serve_lazy_import.py", +) + + +def _rule() -> tuple[VisualGenRule, dict[str, Stage]]: + index = YAMLIndex() + index.blocks = [Block("l0_cpu", 0, {}, [*VISUAL_GEN_ENTRIES, *OTHER_ENTRIES])] + stages = {CPU_STAGE: Stage(CPU_STAGE, "l0_cpu", "x86_64", 1, 1)} + return VisualGenRule(index, stages), stages + + +@pytest.mark.parametrize( + "path", + [ + SERVE_PACKAGE + "serving_videos.py", + SERVE_PACKAGE + "protocol.py", + SERVE_PACKAGE + "api_router.py", + SERVE_PACKAGE + "__init__.py", + ], +) +def test_serve_visual_gen_package_is_claimed(path: str) -> None: + assert _is_vg_claim(path) + + +@pytest.mark.parametrize( + "path", + [ + SERVE_PACKAGE + "README.md", + "tensorrt_llm/serve/api/visual_gen_extra/x.py", + "tensorrt_llm/serve/api/openai/chat/serving.py", + "tensorrt_llm/serve/openai_server.py", + "tensorrt_llm/serve/openai_protocol.py", + "tensorrt_llm/serve/visual_gen_utils.py", + ], +) +def test_paths_next_to_the_package_are_not_claimed(path: str) -> None: + assert not _is_vg_claim(path) + + +def test_serve_visual_gen_package_is_not_outward() -> None: + assert not any(SERVE_PACKAGE.startswith(prefix) for prefix in _VG_OUTWARD_PREFIXES) + + +def test_serve_visual_gen_change_narrows_to_visual_gen_entries() -> None: + rule, _ = _rule() + changed = [SERVE_PACKAGE + "serving_videos.py", SERVE_PACKAGE + "protocol.py"] + + result = rule.apply(PRInputs(changed_files=changed, diffs={})) + + assert result is not None + assert result.scope == "visualgenonly" + assert result.handled_files == set(changed) + assert result.affected_stages == {CPU_STAGE} + assert result.sanity_relevant is False + assert set(result.block_filters[("l0_cpu", 0)]) == set(VISUAL_GEN_ENTRIES) + + +def test_mixed_change_falls_back() -> None: + rule, stages = _rule() + pr = PRInputs( + changed_files=[SERVE_PACKAGE + "serving_videos.py", "tensorrt_llm/serve/openai_server.py"], + diffs={}, + ) + + result = Selector(stages).run(pr, [rule]) + + assert result.scope is None + fallbacks = [ + reason + for reason in result.reasons + if isinstance(reason, dict) and reason.get("reason") == "unhandled_files" + ] + assert len(fallbacks) == 1 + assert fallbacks[0]["files"] == ["tensorrt_llm/serve/openai_server.py"] diff --git a/tests/unittest/serve/__init__.py b/tests/unittest/serve/__init__.py new file mode 100644 index 000000000000..467079831e16 --- /dev/null +++ b/tests/unittest/serve/__init__.py @@ -0,0 +1,14 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/tests/unittest/serve/_base/__init__.py b/tests/unittest/serve/_base/__init__.py new file mode 100644 index 000000000000..467079831e16 --- /dev/null +++ b/tests/unittest/serve/_base/__init__.py @@ -0,0 +1,14 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/tests/unittest/serve/_base/test_routing.py b/tests/unittest/serve/_base/test_routing.py new file mode 100644 index 000000000000..37fbd7fec2c8 --- /dev/null +++ b/tests/unittest/serve/_base/test_routing.py @@ -0,0 +1,264 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""``make_router()``, ``attach_routers()`` and the role mapping of ``serve/_base/routing.py``.""" + +import ast +import importlib +import sys +import textwrap +from pathlib import Path + +import pytest +from fastapi import Depends, FastAPI, Request +from fastapi.routing import APIRoute +from fastapi.testclient import TestClient +from test_common.serve.app_factory import AggConfig +from test_common.serve.routes import effective_routes + +from tensorrt_llm.llmapi.disagg_utils import ServerRole +from tensorrt_llm.serve._base.msgspec_route import _MsgspecRoute +from tensorrt_llm.serve._base.routing import ( + ROUTERS, + RoleGroup, + RouterSpec, + ServerCapabilities, + attach_routers, + make_router, + role_group_of, +) +from tensorrt_llm.serve.openai_client import MSGPACK_HEADERS, _msgpack_encoder + +pytestmark = pytest.mark.cpu_only + + +def test_make_router_uses_msgspec_route(): + router = make_router() + assert router.route_class is _MsgspecRoute + + @router.get("/x") + async def x(): + return {} + + assert len(router.routes) == 1 + assert isinstance(router.routes[0], _MsgspecRoute) + + +def test_make_router_rejects_route_class(): + with pytest.raises(TypeError, match="_MsgspecRoute"): + make_router(route_class=APIRoute) + + +def test_role_group_of_every_role(): + expected = { + None: RoleGroup.LLM, + ServerRole.CONTEXT: RoleGroup.LLM, + ServerRole.GENERATION: RoleGroup.LLM, + ServerRole.MM_ENCODER: RoleGroup.MM_ENCODER, + ServerRole.EMBEDDING: RoleGroup.EMBEDDING, + ServerRole.VISUAL_GEN: RoleGroup.VISUAL_GEN, + } + # Every ServerRole member must have a row here: a new role must decide its + # role group (and its routes) explicitly. + assert set(expected) - {None} == set(ServerRole) + for role, group in expected.items(): + assert role_group_of(role) is group + caps = ServerCapabilities.for_role(role) + assert caps.role is role + assert caps.role_group is group + + +_ROUTER_MODULE_TEMPLATE = """ +from fastapi import FastAPI + +from tensorrt_llm.serve._base.routing import make_router + +router = make_router() + + +@router.get("{path}") +async def handler(): + return {{}} + + +def attach_router(app: FastAPI) -> None: + app.include_router(router) +""" + + +def _write_router_package(tmp_path, package: str, modules: dict) -> None: + pkg = tmp_path / package + pkg.mkdir() + (pkg / "__init__.py").write_text("") + for name, path in modules.items(): + (pkg / f"{name}.py").write_text(_ROUTER_MODULE_TEMPLATE.format(path=path)) + + +def test_attach_routers_imports_only_matching_specs(tmp_path, monkeypatch): + _write_router_package( + tmp_path, + "attachpkg", + {"llm_router": "/llm-only", "mm_router": "/mm-only", "gated_router": "/gated"}, + ) + monkeypatch.syspath_prepend(str(tmp_path)) + module_names = ("attachpkg.llm_router", "attachpkg.mm_router", "attachpkg.gated_router") + specs = ( + RouterSpec("attachpkg.llm_router", roles=frozenset({RoleGroup.LLM})), + RouterSpec("attachpkg.mm_router", roles=frozenset({RoleGroup.MM_ENCODER})), + RouterSpec( + "attachpkg.gated_router", + roles=frozenset({RoleGroup.LLM}), + when=lambda caps: False, + ), + ) + try: + app = FastAPI() + attach_routers(app, ServerCapabilities.for_role(None), routers=specs) + assert "attachpkg.llm_router" in sys.modules + assert "attachpkg.mm_router" not in sys.modules, "role mismatch must not be imported" + assert "attachpkg.gated_router" not in sys.modules, "a false `when` must not be imported" + paths = [path for path, _ in effective_routes(app)] + assert "/llm-only" in paths + assert "/mm-only" not in paths + assert "/gated" not in paths + finally: + for name in ("attachpkg", *module_names): + sys.modules.pop(name, None) + + +def test_router_routes_decode_msgpack(): + router = make_router() + + @router.post("/echo") + async def echo(raw_request: Request): + return {"body": await raw_request.json()} + + app = FastAPI() + app.include_router(router) + body = _msgpack_encoder.encode({"prompt": [1, 2, 3]}) + with TestClient(app) as client: + response = client.post("/echo", content=body, headers=MSGPACK_HEADERS) + assert response.status_code == 200 + assert response.json() == {"body": {"prompt": [1, 2, 3]}} + + +def _route_path(raw_request: Request) -> str: + return raw_request.scope["route"].path + + +def test_include_keeps_route_path(): + # A path prefix goes to make_router(prefix=...), never include_router(prefix=...): + # FastAPI 0.139 drops include prefixes from scope["route"].path. + router = make_router(prefix="/p") + + @router.get("/x") + async def x(route_path: str = Depends(_route_path)): + return {"route_path": route_path} + + app = FastAPI() + app.include_router(router) + with TestClient(app) as client: + response = client.get("/p/x") + assert response.status_code == 200 + assert response.json() == {"route_path": "/p/x"} + + +def test_every_router_spec_module_exposes_attach_router(): + # ROUTERS holds module paths as strings, so a renamed router module would + # break attachment only at server startup; import each one here instead. + assert ROUTERS, "ROUTERS must list at least the system router" + for spec in ROUTERS: + module = importlib.import_module(spec.module) + assert callable(getattr(module, "attach_router", None)), ( + f"{spec.module} must define attach_router(app)" + ) + tree = ast.parse(Path(module.__file__).read_text()) + for node in ast.walk(tree): + is_include_call = ( + isinstance(node, ast.Call) + and isinstance(node.func, ast.Attribute) + and node.func.attr == "include_router" + ) + if is_include_call: + assert all(keyword.arg != "prefix" for keyword in node.keywords), ( + f"{spec.module} passes prefix= to include_router; give the prefix to " + "make_router(prefix=...) instead: FastAPI 0.139 drops include prefixes " + "from scope['route'].path." + ) + + +_ECHO_ROUTER_MODULE = textwrap.dedent( + ''' + """A new endpoint is a router plus a serving class: the router reads its + serving object from app.state; the composition root sets it and attaches.""" + + from fastapi import FastAPI, Request + + from tensorrt_llm.serve._base.routing import make_router + + router = make_router() + + + @router.post("/v1/test-echo") + async def echo(raw_request: Request): + serving = raw_request.app.state.test_serving_echo + return serving.render(await raw_request.json()) + + + def attach_router(app: FastAPI) -> None: + if not hasattr(app.state, "test_serving_echo"): + raise RuntimeError("app.state.test_serving_echo must be set before attaching") + app.include_router(router) + ''' +) + + +class _EchoServing: + def render(self, body): + return {"echo": body} + + +# The TestClient portal thread and the fake server's lazy worker-pool threads +# are alive when the leak check runs; the serve_env fixture closes them in its +# teardown (precedent: tests/unittest/serve/api/ops/system/test_system_endpoints.py). +@pytest.mark.threadleak(enabled=False) +def test_new_endpoint_lands_as_router_and_serving_class(tmp_path, monkeypatch, serve_env): + pkg = tmp_path / "newendpointpkg" + pkg.mkdir() + (pkg / "__init__.py").write_text("") + (pkg / "api_router.py").write_text(_ECHO_ROUTER_MODULE) + monkeypatch.syspath_prepend(str(tmp_path)) + spec = RouterSpec("newendpointpkg.api_router", roles=frozenset({RoleGroup.LLM})) + body = _msgpack_encoder.encode({"prompt": "hi"}) + try: + server = serve_env.build_openai_server(AggConfig()) + server.app.state.test_serving_echo = _EchoServing() + attach_routers(server.app, ServerCapabilities.for_role(None), routers=(spec,)) + client = serve_env.client(server.app) + response = client.post("/v1/test-echo", content=body, headers=MSGPACK_HEADERS) + assert response.status_code == 200 + assert response.json() == {"echo": {"prompt": "hi"}} + + # The same spec on a role outside its role set: not imported again, not + # attached, and the route is absent. + mm_server = serve_env.build_openai_server(AggConfig(role=ServerRole.MM_ENCODER)) + attach_routers( + mm_server.app, ServerCapabilities.for_role(ServerRole.MM_ENCODER), routers=(spec,) + ) + mm_client = serve_env.client(mm_server.app) + mm_response = mm_client.post("/v1/test-echo", content=body, headers=MSGPACK_HEADERS) + assert mm_response.status_code == 404 + finally: + for name in ("newendpointpkg", "newendpointpkg.api_router"): + sys.modules.pop(name, None) diff --git a/tests/unittest/serve/api/__init__.py b/tests/unittest/serve/api/__init__.py new file mode 100644 index 000000000000..467079831e16 --- /dev/null +++ b/tests/unittest/serve/api/__init__.py @@ -0,0 +1,14 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/tests/unittest/serve/api/ops/__init__.py b/tests/unittest/serve/api/ops/__init__.py new file mode 100644 index 000000000000..467079831e16 --- /dev/null +++ b/tests/unittest/serve/api/ops/__init__.py @@ -0,0 +1,14 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/tests/unittest/serve/api/ops/system/__init__.py b/tests/unittest/serve/api/ops/system/__init__.py new file mode 100644 index 000000000000..467079831e16 --- /dev/null +++ b/tests/unittest/serve/api/ops/system/__init__.py @@ -0,0 +1,14 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/tests/unittest/serve/api/ops/system/test_system_endpoints.py b/tests/unittest/serve/api/ops/system/test_system_endpoints.py new file mode 100644 index 000000000000..12a88b166e90 --- /dev/null +++ b/tests/unittest/serve/api/ops/system/test_system_endpoints.py @@ -0,0 +1,132 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""/health, /version and /v1/models behavior, through the production handlers. + +These pin what the system endpoints do today, per serving role, so a later +change can show it changed nothing. An unhealthy engine makes ``/health`` raise +``SIGINT`` (after recording a termination observation) so the process does not +linger as a zombie; the signal is patched out here before any unhealthy request. +""" + +import signal + +import pytest +from test_common.serve.app_factory import AggConfig + +import tensorrt_llm.version +from tensorrt_llm.llmapi.disagg_utils import ServerRole + +# threadleak is off: these tests create TestClients and run requests inside the +# test body, so the client's portal thread and the fake server's worker-pool +# threads are still alive when the leak check runs; the serve_env fixture closes +# them in its teardown, which runs after that check (precedent: +# tests/unittest/llmapi/apps/test_serve_lazy_import.py). +pytestmark = [pytest.mark.cpu_only, pytest.mark.threadleak(enabled=False)] + +UNAVAILABLE_BODY = "LLM is unavailable. Please check the server logs for more details." + + +@pytest.fixture +def sigint_recorder(monkeypatch): + calls = [] + monkeypatch.setattr(signal, "raise_signal", calls.append) + return calls + + +@pytest.mark.parametrize( + "role", [None, ServerRole.MM_ENCODER, ServerRole.EMBEDDING], ids=["llm", "mm", "embedding"] +) +def test_health_returns_200_with_empty_body(role, serve_env): + server = serve_env.build_openai_server(AggConfig(role=role)) + response = serve_env.client(server.app).get("/health") + assert response.status_code == 200 + assert response.content == b"" + + +@pytest.mark.parametrize("role", [None, ServerRole.MM_ENCODER], ids=["llm", "mm"]) +def test_unhealthy_executor_returns_503_without_shutdown(role, serve_env, sigint_recorder): + server = serve_env.build_openai_server(AggConfig(role=role)) + server.generator._executor.healthy = False + response = serve_env.client(server.app).get("/health") + assert response.status_code == 503 + assert response.text == UNAVAILABLE_BODY + assert sigint_recorder == [], "an unhealthy executor without a fatal error must not SIGINT" + + +@pytest.mark.parametrize("role", [None, ServerRole.MM_ENCODER], ids=["llm", "mm"]) +def test_fatal_error_triggers_sigint_and_termination_record(role, serve_env, sigint_recorder): + server = serve_env.build_openai_server(AggConfig(role=role)) + client = serve_env.client(server.app) + seen = serve_env.record_terminations() + server.generator._executor._fatal_error = RuntimeError("boom") + server.generator._executor.doing_shutdown = False + response = client.get("/health") + assert response.status_code == 503 + assert sigint_recorder == [signal.SIGINT] + assert len(seen) == 1 + assert seen[0].termination_kind == "exception" + assert seen[0].component == "llm" + assert seen[0].reporting_source == "self" + + +@pytest.mark.parametrize("role", [None, ServerRole.MM_ENCODER], ids=["llm", "mm"]) +def test_fatal_error_during_shutdown_signals_once(role, serve_env, sigint_recorder): + server = serve_env.build_openai_server(AggConfig(role=role)) + client = serve_env.client(server.app) + seen = serve_env.record_terminations() + server.generator._executor._fatal_error = RuntimeError("boom") + server.generator._executor.doing_shutdown = True + response = client.get("/health") + assert response.status_code == 503 + assert sigint_recorder == [], "a teardown already in progress must not stack signals" + assert seen == [] + + +def test_embedding_health_depends_on_batcher_and_encoder(serve_env, sigint_recorder): + server = serve_env.build_openai_server(AggConfig(role=ServerRole.EMBEDDING)) + # Without the lifespan the encode batcher never started, so every + # /v1/embeddings request would hang; /health reports unhealthy. + without_lifespan = serve_env.client(server.app, lifespan=False) + assert without_lifespan.get("/health").status_code == 503 + with_lifespan = serve_env.client(server.app) + assert with_lifespan.get("/health").status_code == 200 + # Encode-only generators have no generation executor; health reads the + # encoder executor instead. + server.generator._encoder_executor = None + assert with_lifespan.get("/health").status_code == 503 + assert sigint_recorder == [], ( + "the embedding health path finds no generation executor, so it must not SIGINT" + ) + + +def test_version_reports_package_version(serve_env): + server = serve_env.build_openai_server(AggConfig()) + response = serve_env.client(server.app).get("/version") + assert response.status_code == 200 + assert response.json() == {"version": tensorrt_llm.version.__version__} + + +def test_models_lists_the_served_model(serve_env): + server = serve_env.build_openai_server(AggConfig()) + response = serve_env.client(server.app).get("/v1/models") + assert response.status_code == 200 + body = response.json() + assert body["object"] == "list" + assert len(body["data"]) == 1 + entry = body["data"][0] + assert entry["id"] == "fake-model" + assert entry["object"] == "model" + assert entry["owned_by"] == "tensorrt_llm" + assert isinstance(entry["created"], int) # the request time; never compare the value diff --git a/tests/unittest/serve/api/ops/system/test_system_router.py b/tests/unittest/serve/api/ops/system/test_system_router.py new file mode 100644 index 000000000000..36b680d1e7c2 --- /dev/null +++ b/tests/unittest/serve/api/ops/system/test_system_router.py @@ -0,0 +1,65 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The ops.system router: attachment contract and route provenance per role.""" + +import pytest +from fastapi import FastAPI +from test_common.serve.app_factory import AggConfig +from test_common.serve.routes import effective_routes + +from tensorrt_llm.llmapi.disagg_utils import ServerRole +from tensorrt_llm.serve._base.msgspec_route import _MsgspecRoute +from tensorrt_llm.serve.api.ops.system.api_router import attach_router +from tensorrt_llm.serve.api.ops.system.serving import SystemServing + +pytestmark = pytest.mark.cpu_only + +SYSTEM_PATHS = ("/health", "/version", "/v1/models") +SYSTEM_ROUTER_MODULE = "tensorrt_llm.serve.api.ops.system.api_router" + + +def test_attach_requires_serving_state(): + # The composition root must set the serving object before attaching, so a + # wiring bug fails at startup, not with an AttributeError per request. + with pytest.raises(RuntimeError, match="ops_serving_system"): + attach_router(FastAPI()) + + +def test_system_serving_requires_arguments(): + # No defaults: a serving class built without its collaborators must fail at + # construction, not fall back silently. + with pytest.raises(TypeError): + SystemServing() + + +@pytest.mark.parametrize( + "role", + [None, ServerRole.MM_ENCODER, ServerRole.EMBEDDING], + ids=["llm", "mm_encoder", "embedding"], +) +def test_routes_come_from_ops_system(role, serve_env): + server = serve_env.build_openai_server(AggConfig(role=role)) + by_path = {path: [] for path in SYSTEM_PATHS} + for path, route in effective_routes(server.app): + if path in by_path: + by_path[path].append(route) + for path, routes in by_path.items(): + assert len(routes) == 1, f"{path} must be registered exactly once, found {len(routes)}" + route = routes[0] + assert isinstance(route, _MsgspecRoute), ( + f"{path} must be a _MsgspecRoute; a plain APIRoute breaks msgpack request " + "bodies from the disaggregated frontend" + ) + assert route.endpoint.__module__ == SYSTEM_ROUTER_MODULE diff --git a/tests/unittest/serve/api/visual_gen/__init__.py b/tests/unittest/serve/api/visual_gen/__init__.py new file mode 100644 index 000000000000..467079831e16 --- /dev/null +++ b/tests/unittest/serve/api/visual_gen/__init__.py @@ -0,0 +1,14 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/tests/unittest/serve/api/visual_gen/test_ops_system_router_visual_gen.py b/tests/unittest/serve/api/visual_gen/test_ops_system_router_visual_gen.py new file mode 100644 index 000000000000..488a5e621d05 --- /dev/null +++ b/tests/unittest/serve/api/visual_gen/test_ops_system_router_visual_gen.py @@ -0,0 +1,48 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Route provenance of the system endpoints for the VisualGen serving role. + +Lives under a ``visual_gen/`` path so that VisualGen-only pull requests, whose +CI keeps only test entries containing ``visual_gen/``, still run it. +""" + +import pytest +from test_common.serve.app_factory import isolated_serve_env +from test_common.serve.routes import VISUAL_GEN_CONFIGS, effective_routes + +from tensorrt_llm.serve._base.msgspec_route import _MsgspecRoute + +pytestmark = pytest.mark.cpu_only + +SYSTEM_PATHS = ("/health", "/version", "/v1/models") +SYSTEM_ROUTER_MODULE = "tensorrt_llm.serve.api.ops.system.api_router" + + +@pytest.mark.parametrize("config", VISUAL_GEN_CONFIGS, ids=lambda config: config.name) +def test_routes_come_from_ops_system_visual_gen(config, tmp_path): + with isolated_serve_env(tmp_path) as env: + server = env.build_openai_server(config.build) + by_path = {path: [] for path in SYSTEM_PATHS} + for path, route in effective_routes(server.app): + if path in by_path: + by_path[path].append(route) + for path, routes in by_path.items(): + assert len(routes) == 1, f"{path} must be registered exactly once, found {len(routes)}" + route = routes[0] + assert isinstance(route, _MsgspecRoute), ( + f"{path} must be a _MsgspecRoute; a plain APIRoute breaks msgpack request " + "bodies from the disaggregated frontend" + ) + assert route.endpoint.__module__ == SYSTEM_ROUTER_MODULE diff --git a/tests/unittest/serve/api/visual_gen/test_ops_system_visual_gen.py b/tests/unittest/serve/api/visual_gen/test_ops_system_visual_gen.py new file mode 100644 index 000000000000..205391381c13 --- /dev/null +++ b/tests/unittest/serve/api/visual_gen/test_ops_system_visual_gen.py @@ -0,0 +1,52 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""/health, /version and /v1/models of the VisualGen serving role.""" + +import pytest +from test_common.serve.app_factory import AggConfig, isolated_serve_env + +import tensorrt_llm.version +from tensorrt_llm.llmapi.disagg_utils import ServerRole + +pytestmark = pytest.mark.cpu_only + + +@pytest.fixture +def visual_gen_client(tmp_path): + with isolated_serve_env(tmp_path) as env: + server = env.build_openai_server( + AggConfig(role=ServerRole.VISUAL_GEN, model_name="fake-visual-gen") + ) + yield env.client(server.app) + + +def test_health_always_succeeds_today(visual_gen_client): + # The VisualGen generator exposes no health probe, so /health answers 200 + # unconditionally today; a change to that is a behavior change. + assert visual_gen_client.get("/health").status_code == 200 + + +def test_version(visual_gen_client): + response = visual_gen_client.get("/version") + assert response.status_code == 200 + assert response.json() == {"version": tensorrt_llm.version.__version__} + + +def test_models_lists_the_served_model(visual_gen_client): + response = visual_gen_client.get("/v1/models") + assert response.status_code == 200 + body = response.json() + assert body["object"] == "list" + assert [entry["id"] for entry in body["data"]] == ["fake-visual-gen"] diff --git a/tests/unittest/serve/api/visual_gen/test_routes_visual_gen.py b/tests/unittest/serve/api/visual_gen/test_routes_visual_gen.py new file mode 100644 index 000000000000..c20344b6eea7 --- /dev/null +++ b/tests/unittest/serve/api/visual_gen/test_routes_visual_gen.py @@ -0,0 +1,56 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Route snapshot of the VisualGen serving configuration. + +Lives under a ``visual_gen/`` path so that VisualGen-only pull requests, whose +CI keeps only test entries containing ``visual_gen/``, still run it. +""" + +import pytest +from test_common.serve.routes import ( + VISUAL_GEN_CONFIGS, + compare, + format_failure, + read_reference, + snapshot_config, +) + +pytestmark = pytest.mark.cpu_only + +_DOC_ROUTES = {"/openapi.json", "/docs", "/docs/oauth2-redirect", "/redoc"} + + +@pytest.mark.parametrize("config", VISUAL_GEN_CONFIGS, ids=lambda config: config.name) +def test_visual_gen_routes_match_reference(config, tmp_path): + reference = read_reference() + recorded = reference["configs"][config.name] + live = snapshot_config(config, tmp_path) + assert recorded.get("error") == live.get("error") + differences = compare(recorded.get("routes", []), live.get("routes", [])) + assert not differences, format_failure(config.name, differences) + + +@pytest.mark.parametrize("config", VISUAL_GEN_CONFIGS, ids=lambda config: config.name) +def test_visual_gen_routes_keep_msgpack_route_class(config, tmp_path): + live = snapshot_config(config, tmp_path) + for record in live["routes"]: + methods, path, cls = record.split(" ")[:3] + if path in _DOC_ROUTES: + assert cls == "Route", record + else: + assert cls == "_MsgspecRoute", ( + f"{record}: every VisualGen API route must keep the msgpack route class, " + "like every other aggregated-server route." + ) diff --git a/tests/unittest/serve/api/visual_gen/test_shim_identity_visual_gen.py b/tests/unittest/serve/api/visual_gen/test_shim_identity_visual_gen.py new file mode 100644 index 000000000000..a58f93feb6d4 --- /dev/null +++ b/tests/unittest/serve/api/visual_gen/test_shim_identity_visual_gen.py @@ -0,0 +1,117 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Identity rows of VisualGen names re-exported from moved serve modules. + +No kept shim has a VisualGen path, so this table holds interface rows only +(``warns=False``, ``ban_old_path=False``, ``retire_in="not retired"``): names a +package facade keeps re-exporting as its own interface, checked for identity +only. Lives under a ``visual_gen/`` path so that VisualGen-only pull requests +still run it; the machinery's self-tests are in +``tests/unittest/serve/test_shim_identity.py``. +""" + +import pytest +from test_common.serve.shims import ShimRow, check_identity + +pytestmark = pytest.mark.cpu_only + +# The VisualGen request and response models live in +# ``tensorrt_llm.serve.api.visual_gen.protocol``; ``tensorrt_llm.serve.openai_protocol`` +# keeps re-exporting them lazily as part of its own interface, for good: no warning, no +# ban on the old path. These rows check identity only. +VISUAL_GEN_SHIM_ROWS: tuple = ( + ShimRow( + "tensorrt_llm.serve.openai_protocol", + "ImageGenerationRequest", + "tensorrt_llm.serve.api.visual_gen.protocol", + retire_in="not retired", + ban_old_path=False, + warns=False, + ), + ShimRow( + "tensorrt_llm.serve.openai_protocol", + "ImageEditRequest", + "tensorrt_llm.serve.api.visual_gen.protocol", + retire_in="not retired", + ban_old_path=False, + warns=False, + ), + ShimRow( + "tensorrt_llm.serve.openai_protocol", + "ImageObject", + "tensorrt_llm.serve.api.visual_gen.protocol", + retire_in="not retired", + ban_old_path=False, + warns=False, + ), + ShimRow( + "tensorrt_llm.serve.openai_protocol", + "ImageGenerationResponse", + "tensorrt_llm.serve.api.visual_gen.protocol", + retire_in="not retired", + ban_old_path=False, + warns=False, + ), + ShimRow( + "tensorrt_llm.serve.openai_protocol", + "MediaReferenceItem", + "tensorrt_llm.serve.api.visual_gen.protocol", + retire_in="not retired", + ban_old_path=False, + warns=False, + ), + ShimRow( + "tensorrt_llm.serve.openai_protocol", + "VideoGenerationRequest", + "tensorrt_llm.serve.api.visual_gen.protocol", + retire_in="not retired", + ban_old_path=False, + warns=False, + ), + ShimRow( + "tensorrt_llm.serve.openai_protocol", + "VideoJob", + "tensorrt_llm.serve.api.visual_gen.protocol", + retire_in="not retired", + ban_old_path=False, + warns=False, + ), + ShimRow( + "tensorrt_llm.serve.openai_protocol", + "VideoJobList", + "tensorrt_llm.serve.api.visual_gen.protocol", + retire_in="not retired", + ban_old_path=False, + warns=False, + ), +) + + +def test_visual_gen_shim_identity(): + assert check_identity(VISUAL_GEN_SHIM_ROWS) == [] + + +def test_visual_gen_rows_are_interface_rows(): + kept_shims = [ + f"{row.old_module}.{row.name}" + for row in VISUAL_GEN_SHIM_ROWS + if row.warns or row.ban_old_path or row.retire_in != "not retired" + ] + assert kept_shims == [], ( + f"{kept_shims} are kept-shim rows, but this table checks identity only. A kept shim " + "also needs its FutureWarning and old-path ban checked: call check_warnings and " + "find_old_path_imports from test_common.serve.shims on this table here, and delete " + "this test." + ) diff --git a/tests/unittest/serve/conftest.py b/tests/unittest/serve/conftest.py new file mode 100644 index 000000000000..cda9b5cc0c2e --- /dev/null +++ b/tests/unittest/serve/conftest.py @@ -0,0 +1,26 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import pytest + + +@pytest.fixture +def serve_env(tmp_path): + """A :class:`test_common.serve.app_factory.ServeTestEnv` per test.""" + # Imported here, not at module level: this conftest also governs checks + # that need no tensorrt_llm build (the ratchet, the agent-docs test). + from test_common.serve.app_factory import isolated_serve_env + + with isolated_serve_env(tmp_path) as env: + yield env diff --git a/tests/unittest/serve/test_agents_md.py b/tests/unittest/serve/test_agents_md.py new file mode 100644 index 000000000000..b95dac68ff16 --- /dev/null +++ b/tests/unittest/serve/test_agents_md.py @@ -0,0 +1,132 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The serve agent docs name only paths and commands that exist. + +Rules written for agents rot silently when the file or command they name moves; +this test keeps every inline-code path and command in the serve ``AGENTS.md`` +files real, and bans line-number anchors, which drift without failing anything. +""" + +import re +from pathlib import Path + +import pytest + +pytestmark = pytest.mark.cpu_only + +REPO_ROOT = Path(__file__).resolve().parents[3] + +DOCS = ("tensorrt_llm/serve/AGENTS.md", "tensorrt_llm/commands/AGENTS.md") + +PATH_ROOTS = ( + "tensorrt_llm/", + "serve/", + "commands/", + "tests/", + "scripts/", + "jenkins/", + ".github/", + "docs/", + "examples/", +) +ROOT_FILES = ("AGENTS.md", "CLAUDE.md", "legacy-files.txt", "CODING_GUIDELINES.md") +COMMAND_STARTS = ("pytest", "python", "python3", "PYTHONPATH=", "LLM_MODELS_ROOT=") + +_INLINE_CODE = re.compile(r"`([^`]+)`") +_LINE_ANCHOR = re.compile(r"\.(py|md|ya?ml|groovy|txt)\s*:\s*\d") +_BARE_ANCHOR_SPAN = re.compile(r"`:\d") + + +def _spans(doc: Path): + return _INLINE_CODE.findall(doc.read_text()) + + +def _resolve(path_text: str) -> Path: + if path_text.startswith(("serve/", "commands/")): + return REPO_ROOT / "tensorrt_llm" / path_text + return REPO_ROOT / path_text + + +def _is_template(token: str) -> bool: + return any(symbol in token for symbol in "<>*") + + +def _missing(doc: str, token: str) -> str: + return ( + f"{doc} names `{token}`, which does not exist. Update the rule in the PR that " + "moved or deleted it." + ) + + +def _check_command(doc: str, span: str, problems: list) -> None: + tokens = span.split(" ") + pythonpath_roots = [] + for token in tokens: + if token.startswith("PYTHONPATH="): + pythonpath_roots = token.split("=", 1)[1].split(":") + for index, token in enumerate(tokens): + if _is_template(token): + continue + if index > 0 and tokens[index - 1] == "-m" and "/" not in token and tokens[0] != "pytest": + # `python3 -m `: resolve to a file under the PYTHONPATH= + # roots or the repository root. + candidates = [] + for root in [*pythonpath_roots, "."]: + base = REPO_ROOT / root / Path(*token.split(".")) + candidates.extend((base.with_suffix(".py"), base / "__init__.py")) + if not any(candidate.exists() for candidate in candidates): + problems.append(_missing(doc, token)) + continue + if token.startswith(PATH_ROOTS): + target = token.split("::")[0] + if not _resolve(target).exists(): + problems.append(_missing(doc, token)) + + +@pytest.mark.parametrize("doc", DOCS) +def test_paths_and_commands_are_real(doc): + doc_path = REPO_ROOT / doc + problems = [] + for span in _spans(doc_path): + if " " not in span and (span.startswith(PATH_ROOTS) or span in ROOT_FILES): + if _is_template(span): + continue + target = _resolve(span.split("::")[0]) + if not target.exists(): + problems.append(_missing(doc, span)) + elif span.startswith(COMMAND_STARTS): + _check_command(doc, span, problems) + assert not problems, "\n".join(problems) + + +@pytest.mark.parametrize("doc", DOCS) +def test_no_line_number_anchors(doc): + text = (REPO_ROOT / doc).read_text() + assert not _LINE_ANCHOR.search(text) and not _BARE_ANCHOR_SPAN.search(text), ( + f"{doc} contains a line-number anchor. Name files and symbols, never line numbers: " + "anchors drift silently when the file changes." + ) + + +@pytest.mark.parametrize("doc", DOCS) +def test_sibling_claude_md(doc): + doc_path = REPO_ROOT / doc + sibling = doc_path.with_name("CLAUDE.md") + assert sibling.exists(), f"{doc} needs a sibling CLAUDE.md pointer file" + lines = [line.strip() for line in sibling.read_text().splitlines() if line.strip()] + assert lines == ["# In ./CLAUDE.md", "@AGENTS.md"], ( + f"{sibling.relative_to(REPO_ROOT)} must hold exactly the repo's two-line pointer " + "form: `# In ./CLAUDE.md` and `@AGENTS.md`." + ) diff --git a/tests/unittest/serve/test_layering.py b/tests/unittest/serve/test_layering.py new file mode 100644 index 000000000000..357dcd4b02fc --- /dev/null +++ b/tests/unittest/serve/test_layering.py @@ -0,0 +1,349 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Import directions between serving layers, written as tests. + +Each pull request that creates a package under ``tensorrt_llm/serve`` adds its +contract here. A contract forbids imports by module prefix; a baseline allowance +records the imports that existed when the contract was written and only shrinks. +""" + +import ast +import textwrap +from pathlib import Path + +import pytest +from test_common.serve.layering import ( + Contract, + ImportEdge, + build_import_graph, + check_contracts, + stale_allowances, +) + +pytestmark = pytest.mark.cpu_only + +REPO_ROOT = Path(__file__).resolve().parents[3] + +CONTRACTS = ( + Contract( + name="render core has no HTTP or executor dependency", + importers=( + "tensorrt_llm.serve.render.chat", + "tensorrt_llm.serve.render.resources", + "tensorrt_llm.serve.render.fingerprint", + "tensorrt_llm.serve.render.prompt_types", + ), + forbidden=("fastapi", "starlette", "tensorrt_llm.executor"), + fix=( + "Keep HTTP code in serve/render/api_router.py or _http.py and pass engine data " + "in through RenderResources." + ), + ), + Contract( + name="gRPC frontends do not reach into serve", + importers=("tensorrt_llm.grpc",), + forbidden=("tensorrt_llm.serve",), + allowed=frozenset( + { + ( + "tensorrt_llm.grpc.openengine.server", + "tensorrt_llm.serve._frontend_processes", + name, + ) + for name in ( + "FrontendStartupCancelled", + "_init_multi_frontend_mode", + "_signal_frontend_ready", + "_spawn_attached_frontends", + "_terminate_attached_frontends", + ) + } + | { + ( + "tensorrt_llm.grpc.openengine.server", + "tensorrt_llm.serve._perf_metrics_config", + "resolve_perf_metrics_config", + ) + } + ), + fix=( + "gRPC frontends use serving code only through public entry points; add a public " + "API in tensorrt_llm/llmapi instead. The baseline only shrinks: delete an " + "allowance when its import goes away." + ), + ), + Contract( + name="serve/_base/ does not import serve/api/", + importers=("tensorrt_llm.serve._base",), + forbidden=("tensorrt_llm.serve.api",), + fix=( + "serve/_base/ is shared infrastructure and must not depend on endpoint " + "packages; pass what it needs in from the composition root." + ), + ), + Contract( + name="serve/api/ and serve/_base/ do not import the composition root", + importers=("tensorrt_llm.serve.api", "tensorrt_llm.serve._base"), + forbidden=("tensorrt_llm.serve.openai_server", "tensorrt_llm.serve.app"), + fix=( + "Endpoint packages and serve/_base/ must not import the composition root " + "(serve/openai_server.py or serve/app.py); the root imports them and injects " + "what they need. Move the shared helper to serve/_base/ instead." + ), + ), +) + + +@pytest.fixture(scope="module") +def edges(): + return build_import_graph(REPO_ROOT / "tensorrt_llm", "tensorrt_llm") + + +def test_contracts_hold(edges): + assert check_contracts(edges, CONTRACTS) == [] + + +def test_no_stale_allowances(edges): + assert stale_allowances(edges, CONTRACTS) == [] + + +_API_PREFIX = "tensorrt_llm.serve.api" + + +def _api_package_of(module: str): + """The endpoint package of a module under ``tensorrt_llm.serve.api``. + + The package is the first two components below ``api`` for ``openai`` and + ``ops`` (``openai.chat``, ``ops.system``) and the first one otherwise + (``anthropic``, ``visual_gen``). + """ + below = module.split(".")[3:] + if below and below[0] in ("openai", "ops"): + return tuple(below[:2]) + return tuple(below[:1]) + + +def _under_api(module: str) -> bool: + return module == _API_PREFIX or module.startswith(_API_PREFIX + ".") + + +def _cross_package_imports(edges) -> list: + """Imports between endpoint packages, matched per imported name as check_contracts does. + + ``from tensorrt_llm.serve import api`` names the api root package and + ``from tensorrt_llm.serve.api.ops import system`` names ``ops.system``: the + package is read off ``.``, not off the ``from`` module alone. + """ + problems = [] + for edge in edges: + if edge.type_checking or not _under_api(edge.importer): + continue + for name in edge.names or ("",): + target = f"{edge.imported}.{name}" if name else edge.imported + if not _under_api(target): + continue + if _api_package_of(target) != _api_package_of(edge.importer): + problems.append( + f"serve/api/ packages do not import each other: {edge.importer} " + f"(line {edge.lineno}) imports `{target}`. Share code through serve/_base/ " + "or inject it from the composition root." + ) + return problems + + +def test_api_packages_do_not_import_each_other(edges): + assert _cross_package_imports(edges) == [] + + +def test_cross_package_classification_reads_the_imported_name(): + def edge(importer, imported, names): + return ImportEdge( + importer=importer, + imported=imported, + names=names, + lineno=1, + in_function=False, + type_checking=False, + ) + + system = "tensorrt_llm.serve.api.ops.system.api_router" + # Parent-package forms resolve to the submodule they name: the same package. + assert _cross_package_imports([edge(system, "tensorrt_llm.serve.api.ops", ("system",))]) == [] + assert ( + _cross_package_imports([edge(system, "tensorrt_llm.serve.api.ops.system", ("serving",))]) + == [] + ) + # The api root, a sibling package and another dialect are cross-package, whatever the form. + assert len(_cross_package_imports([edge(system, "tensorrt_llm.serve", ("api",))])) == 1 + assert ( + len(_cross_package_imports([edge(system, "tensorrt_llm.serve.api.ops", ("metrics",))])) == 1 + ) + anthropic = "tensorrt_llm.serve.api.anthropic.serving" + assert len(_cross_package_imports([edge(system, anthropic, ("AnthropicServing",))])) == 1 + # Importers outside serve/api/ are not classified here. + root = "tensorrt_llm.serve.openai_server" + assert ( + _cross_package_imports( + [edge(root, "tensorrt_llm.serve.api.ops.system.serving", ("SystemServing",))] + ) + == [] + ) + + +def test_api_init_imports_nothing(): + tree = ast.parse((REPO_ROOT / "tensorrt_llm" / "serve" / "api" / "__init__.py").read_text()) + imports = [node for node in ast.walk(tree) if isinstance(node, (ast.Import, ast.ImportFrom))] + assert imports == [], ( + "serve/api/__init__.py imports nothing: attach_routers imports routers by role; an " + "import here would load them for every role and break the VisualGen CI selection." + ) + + +# --------------------------------------------------------------------------- +# Self-test on a synthetic package: the graph must see every import form. +# --------------------------------------------------------------------------- + + +@pytest.fixture +def synthetic_package(tmp_path): + pkg = tmp_path / "layerpkg" + pkg.mkdir() + (pkg / "__init__.py").write_text("") + (pkg / "inner.py").write_text("VALUE = 1\n") + (pkg / "top.py").write_text( + textwrap.dedent( + """ + from typing import TYPE_CHECKING + + import os + from json import dumps, loads + + from .inner import VALUE + + if TYPE_CHECKING: + import socket + + def late(): + import importlib + + importlib.import_module("collections.abc") + from ..sibling import thing # noqa: F401 + return VALUE + """ + ) + ) + return pkg + + +def test_import_graph_records_every_form(synthetic_package): + edges = build_import_graph(synthetic_package, "layerpkg") + by_imported = {edge.imported: edge for edge in edges} + + assert by_imported["os"].names == () + assert not by_imported["os"].in_function and not by_imported["os"].type_checking + assert by_imported["json"].names == ("dumps", "loads") + assert by_imported["layerpkg.inner"].names == ("VALUE",) # relative import resolved + assert by_imported["socket"].type_checking + assert by_imported["importlib"].in_function + assert by_imported["collections.abc"].names == () # importlib.import_module literal + assert by_imported["collections.abc"].in_function + assert by_imported["sibling"].names == ("thing",) # level-2 relative from layerpkg.top + + +def test_contract_violation_and_allowance(synthetic_package): + edges = build_import_graph(synthetic_package, "layerpkg") + contract = Contract( + name="top does not import json", + importers=("layerpkg.top",), + forbidden=("json",), + fix="Use the serializer helper instead.", + ) + problems = check_contracts(edges, [contract]) + assert len(problems) == 2 # one per from-import name + assert "contract 'top does not import json'" in problems[0] + assert "Use the serializer helper instead." in problems[0] + + allowed = Contract( + name="top does not import json", + importers=("layerpkg.top",), + forbidden=("json",), + allowed=frozenset({("layerpkg.top", "json", "dumps"), ("layerpkg.top", "json", "loads")}), + fix="Use the serializer helper instead.", + ) + assert check_contracts(edges, [allowed]) == [] + assert stale_allowances(edges, [allowed]) == [] + + stale = Contract( + name="top does not import json", + importers=("layerpkg.top",), + forbidden=("json",), + allowed=frozenset({("layerpkg.top", "json", "gone")}), + fix="Use the serializer helper instead.", + ) + messages = stale_allowances(edges, [stale]) + assert len(messages) == 1 and "the baseline only shrinks" in messages[0] + + +def test_parent_package_import_of_a_forbidden_module(synthetic_package): + # Both forms record the edge against the parent package, with the forbidden + # submodule only as an imported name. + (synthetic_package / "via_parent.py").write_text( + textwrap.dedent( + """ + from layerpkg import inner, top + from . import inner as relative_inner + """ + ) + ) + edges = build_import_graph(synthetic_package, "layerpkg") + contract = Contract( + name="no inner", + importers=("layerpkg.via_parent",), + forbidden=("layerpkg.inner",), + fix="Import VALUE through layerpkg.top.", + ) + problems = check_contracts(edges, [contract]) + assert len(problems) == 2 # `top` from the same statement is not flagged + assert "(line 2) imports `layerpkg.inner`." in problems[0] # from layerpkg import inner + assert "(line 3) imports `layerpkg.inner`." in problems[1] # from . import inner + + allowed = Contract( + name="no inner", + importers=("layerpkg.via_parent",), + forbidden=("layerpkg.inner",), + allowed=frozenset({("layerpkg.via_parent", "layerpkg", "inner")}), + fix="Import VALUE through layerpkg.top.", + ) + assert check_contracts(edges, [allowed]) == [] + assert stale_allowances(edges, [allowed]) == [] + + +def test_type_checking_imports_are_skipped_by_default(synthetic_package): + edges = build_import_graph(synthetic_package, "layerpkg") + contract = Contract( + name="no socket", + importers=("layerpkg",), + forbidden=("socket",), + fix="unused", + ) + assert check_contracts(edges, [contract]) == [] + including = Contract( + name="no socket", + importers=("layerpkg",), + forbidden=("socket",), + include_type_checking=True, + fix="unused", + ) + assert len(check_contracts(edges, [including])) == 1 diff --git a/tests/unittest/serve/test_middleware_order.py b/tests/unittest/serve/test_middleware_order.py new file mode 100644 index 000000000000..aec17dd4f79d --- /dev/null +++ b/tests/unittest/serve/test_middleware_order.py @@ -0,0 +1,133 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Middleware-order snapshot of the aggregated and disaggregated apps. + +Starlette's ``add_middleware`` inserts at position 0, so the last one added is +outermost. ``ServerArrivalTimeMiddleware`` assigns ``scope['state'] = {}`` and +``PerfMetricsMiddleware`` only ``setdefault``s into it, so their relative order +is load-bearing: swapping them wipes every perf-metrics record. VisualGen is not +listed: it takes the default code path without perf metrics, and no VisualGen +path can change middleware registration. +""" + +import pytest +from test_common.serve.app_factory import AggConfig, CoordinatorConfig, DisaggConfig +from test_common.serve.middleware import middleware_snapshot + +from tensorrt_llm.llmapi.disagg_utils import ServerRole + +pytestmark = pytest.mark.cpu_only + +_ARRIVAL_WITH_CLOCK = {"class": "ServerArrivalTimeMiddleware", "kwargs": ["adjusted_clock"]} +_ARRIVAL_PLAIN = {"class": "ServerArrivalTimeMiddleware", "kwargs": []} + + +def _perf(kwargs, expose_headers): + return { + "class": "PerfMetricsMiddleware", + "kwargs": sorted(kwargs), + "expose_headers": expose_headers, + } + + +# Outermost first, matching middleware_snapshot. +EXPECTED = { + "llm": (AggConfig(), [_ARRIVAL_WITH_CLOCK]), + "mm_encoder": (AggConfig(role=ServerRole.MM_ENCODER), [_ARRIVAL_WITH_CLOCK]), + "embedding": (AggConfig(role=ServerRole.EMBEDDING), [_ARRIVAL_WITH_CLOCK]), + "llm_perf_metrics": ( + AggConfig(return_perf_metrics=True), + [ + _ARRIVAL_WITH_CLOCK, + _perf(["adjusted_clock", "expose_headers", "writer"], True), + ], + ), + "llm_perf_metrics_output_dir_only": ( + AggConfig(perf_metrics_output_dir=True), + [ + _ARRIVAL_WITH_CLOCK, + _perf(["adjusted_clock", "expose_headers", "writer"], False), + ], + ), + "llm_perf_metrics_enable_metrics_env": ( + AggConfig(return_perf_metrics=True, env=(("ENABLE_METRICS", "true"),)), + [ + _ARRIVAL_WITH_CLOCK, + _perf(["adjusted_clock", "expose_headers", "writer"], True), + {"class": "PrometheusInstrumentatorMiddleware"}, + ], + ), + "disagg_local": (DisaggConfig(), [_ARRIVAL_PLAIN]), + "disagg_fleet": (DisaggConfig(fleet=True), [_ARRIVAL_PLAIN]), + "disagg_local_perf_metrics": ( + DisaggConfig(return_perf_metrics=True), + [_ARRIVAL_PLAIN, _perf(["expose_headers", "writer"], True)], + ), + "disagg_fleet_perf_metrics": ( + DisaggConfig(fleet=True, return_perf_metrics=True), + [_ARRIVAL_PLAIN, _perf(["expose_headers", "writer"], True)], + ), + "coordinator": (CoordinatorConfig(), []), +} + + +def _build(serve_env, config): + if isinstance(config, AggConfig): + return serve_env.build_openai_server(config).app + if isinstance(config, DisaggConfig): + return serve_env.build_disagg_server(config).app + return serve_env.build_coordinator_server(config).app + + +def _failure(name, expected, got): + return ( + f"Middleware stack of '{name}' changed: expected {expected}, got {got}. " + "Starlette's add_middleware inserts at position 0, so the last one added is " + "outermost. ServerArrivalTimeMiddleware assigns scope['state'] = {} and must stay " + "outside PerfMetricsMiddleware, or every perf-metrics record is wiped. Agg passes " + "adjusted_clock to both, disagg to neither. If the change is intended, update " + "EXPECTED in tests/unittest/serve/test_middleware_order.py and say why in the PR " + "body." + ) + + +@pytest.mark.parametrize("name", sorted(EXPECTED)) +def test_middleware_order(name, serve_env): + config, expected = EXPECTED[name] + snapshot = middleware_snapshot(_build(serve_env, config)) + assert snapshot == expected, _failure(name, expected, snapshot) + + +@pytest.mark.parametrize("name", sorted(EXPECTED)) +def test_arrival_time_stays_outside_perf_metrics(name, serve_env): + """When both are present, ServerArrivalTimeMiddleware is outermost.""" + config, _ = EXPECTED[name] + classes = [entry["class"] for entry in middleware_snapshot(_build(serve_env, config))] + if "PerfMetricsMiddleware" not in classes or "ServerArrivalTimeMiddleware" not in classes: + return + assert classes.index("ServerArrivalTimeMiddleware") < classes.index("PerfMetricsMiddleware"), ( + _failure(name, "ServerArrivalTimeMiddleware before PerfMetricsMiddleware", classes) + ) + + +def test_user_middleware_is_outermost(serve_env): + """``--middleware`` classes are applied after construction, so they end up outermost.""" + from tensorrt_llm.commands.serve import _apply_fastapi_middlewares + + server = serve_env.build_openai_server(AggConfig()) + _apply_fastapi_middlewares(server.app, ["test_common.serve.fakes.UserProbeMiddleware"]) + snapshot = middleware_snapshot(server.app) + expected = [{"class": "UserProbeMiddleware"}, _ARRIVAL_WITH_CLOCK] + assert snapshot == expected, _failure("llm_user_middleware", expected, snapshot) diff --git a/tests/unittest/serve/test_no_object_new.py b/tests/unittest/serve/test_no_object_new.py new file mode 100644 index 000000000000..0aa59460caf8 --- /dev/null +++ b/tests/unittest/serve/test_no_object_new.py @@ -0,0 +1,302 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Ratchet against new ``object.__new__()`` test sites. + +Tests that build a server with ``object.__new__`` bypass the constructor and pin +whatever attribute set the handler happens to read; they break or silently +mistest when handlers move. New tests build servers with ``isolated_serve_env`` +from ``tests/test_common/serve/app_factory.py`` instead. The existing sites stay +until the change that moves each handler rewrites them, so this test holds a +per-file baseline of sites that may only shrink. A site is named by its +enclosing function or class and the server class it builds, so a site added in +another function fails even when one is removed from the same file. + +The scan counts AST call nodes, not text, so a docstring or comment that +mentions ``object.__new__(OpenAIServer)`` does not count. A name bound by +``from ... import OpenAIServer as Server`` counts as ``OpenAIServer``. +""" + +import ast +from collections import Counter +from pathlib import Path + +import pytest + +pytestmark = pytest.mark.cpu_only + +REPO_ROOT = Path(__file__).resolve().parents[3] +TESTS_ROOT = REPO_ROOT / "tests" + +SERVER_CLASSES = ("OpenAIServer", "OpenAIDisaggServer", "CoordinatorServer") + +# Per-file sites that existed when this ratchet landed, as +# " " (see find_new_sites), repeated +# when one scope builds the class twice. The baseline only shrinks: rewrite a +# site on the factory, delete its entry. +BASELINE = { + "tests/unittest/disaggregated/test_coordinator_worker.py": [ + "test_coordinator_keep_alive_timeout_is_passed_to_uvicorn CoordinatorServer", + "test_coordinator_tcp_listener_uses_the_prebound_socket CoordinatorServer", + ], + "tests/unittest/disaggregated/test_disagg_internal_auth.py": [ + "test_aggregated_worker_ignores_affinity_header OpenAIServer", + "test_worker_affinity_survives_wire_roundtrip OpenAIServer", + "test_worker_rejects_protected_fields_without_cache_transceiver_config OpenAIServer", + ], + "tests/unittest/disaggregated/test_disagg_openai_client.py": [ + "test_worker_clock_calibration_uses_global_clock OpenAIServer", + ], + "tests/unittest/disaggregated/test_disagg_responses_api.py": [ + "test_a_context_worker_with_postprocessing_workers_returns_the_prompt OpenAIServer", + "test_a_models_failure_is_an_error_response OpenAIDisaggServer", + ], + "tests/unittest/disaggregated/test_openai_disagg_server.py": [ + "test_create_client_does_not_register_with_server_metrics_collector OpenAIDisaggServer", + "test_http_cluster_storage_request_is_proxied_to_coordinator OpenAIDisaggServer", + "test_server_keep_alive_timeout_is_passed_to_uvicorn OpenAIDisaggServer", + ], + "tests/unittest/disaggregated/test_openai_disagg_service.py": [ + "test_create_chat_response_sets_prompt_token_ids_for_context_only OpenAIServer", + "test_subagent_affinity_http_worker_adp_placement.make_worker OpenAIServer", + ], + "tests/unittest/disaggregated/test_openai_server_info.py": [ + "_make_server OpenAIServer", + ], + "tests/unittest/disaggregated/test_openai_server_stream_errors.py": [ + "_bare_server OpenAIServer", + ], + "tests/unittest/disaggregated/test_paired_request_cancellation.py": [ + "test_http_failure_reaches_paired_worker_abort OpenAIDisaggServer", + "test_http_failure_reaches_paired_worker_abort OpenAIServer", + ], + "tests/unittest/disaggregated/test_router.py": [ + "test_chat_harmony_preserves_original_tool_conversion_error OpenAIServer", + "test_gpt_oss_router_tokens_match_chat_harmony_server_input OpenAIServer", + ], + "tests/unittest/executor/test_spec_decode_stats_payload.py": [ + "TestServerOptIn._server OpenAIServer", + ], + "tests/unittest/llmapi/apps/_test_trtllm_serve_profile.py": [ + "server_with_mock_generator OpenAIServer", + ], + "tests/unittest/llmapi/apps/test_anthropic_routes.py": [ + "_batch_client OpenAIServer", + "_chat_stream OpenAIServer", + "_count_tokens_client OpenAIServer", + "_handle OpenAIDisaggServer", + "_make_route_client OpenAIDisaggServer", + "_make_route_client OpenAIServer", + "test_await_disconnected_returns_immediately_for_a_synthetic_request OpenAIServer", + "test_batch_routes_are_registered_on_the_standard_server OpenAIServer", + "test_count_tokens_honours_the_server_chat_template OpenAIServer", + "test_create_batch_at_capacity_is_429_not_400 OpenAIServer", + "test_results_of_an_unfinished_batch_are_400_not_404.scenario OpenAIServer", + "test_standard_and_disagg_register_messages_route OpenAIDisaggServer", + "test_standard_and_disagg_register_messages_route OpenAIServer", + ], + "tests/unittest/llmapi/apps/test_context_length_error.py": [ + "_disagg_server OpenAIDisaggServer", + ], + "tests/unittest/llmapi/apps/test_openai_server_iteration_stats.py": [ + "_make_server OpenAIServer", + ], + "tests/unittest/llmapi/apps/test_render_callers.py": [ + "TestCountTokens._client OpenAIServer", + "TestServerInfoFingerprint.test_the_first_call_hashes_off_the_event_loop OpenAIServer", + ], + "tests/unittest/llmapi/apps/test_responses_store_replay.py": [ + "_server_up_to_preprocess OpenAIServer", + ], + "tests/unittest/llmapi/apps/test_responses_streaming_events.py": [ + "_server_streaming OpenAIServer", + ], + "tests/unittest/llmapi/apps/test_serving_extensions.py": [ + "TestOpenAIChatIntegration.chat_client OpenAIServer", + ], + "tests/unittest/llmapi/apps/test_tool_parsers.py": [ + "TestConfigureParserSpecialTokenDecoding.test_the_responses_route_applies_it OpenAIServer", + ], + "tests/unittest/llmapi/test_kv_hints.py": [ + "test_http_handlers_forward_hints OpenAIServer", + ], + "tests/unittest/llmapi/test_llm.py": [ + "test_openai_completion_list_prompt_stream_reuses_stream_metadata.run_request OpenAIServer", + "test_startup_metrics_by_server_info OpenAIServer", + ], + "tests/unittest/llmapi/test_rl_control_auth.py": [ + "_make_server OpenAIServer", + ], + "tests/unittest/llmapi/test_runtime_control.py": [ + "_make_server OpenAIServer", + ], + "tests/unittest/llmapi/test_serve_multi_frontend_helpers.py": [ + "_attached_server OpenAIServer", + "test_on_launcher_lost_fails_fast_then_shuts_down OpenAIServer", + "test_only_the_launcher_registers_the_server OpenAIServer", + "test_set_steady_clock_offset OpenAIServer", + ], + "tests/unittest/llmapi/test_serve_multi_frontend_route_gate.py": [ + "_llm_server_routes OpenAIServer", + ], +} + + +def _class_name(node) -> str: + if isinstance(node, ast.Name): + return node.id + if isinstance(node, ast.Attribute): + return node.attr + return "" + + +def _server_class_names(tree: ast.AST) -> dict[str, str]: + """Local name -> server class, with the names bound by ``import ... as``.""" + names = {server_class: server_class for server_class in SERVER_CLASSES} + for node in ast.walk(tree): + if isinstance(node, ast.ImportFrom): + for alias in node.names: + if alias.name in SERVER_CLASSES and alias.asname: + names[alias.asname] = alias.name + return names + + +def _built_server_class(node: ast.AST, names: dict[str, str]) -> str: + """The server class that a ``__new__`` call node builds, or "" for any other node.""" + if not isinstance(node, ast.Call) or not isinstance(node.func, ast.Attribute): + return "" + if node.func.attr != "__new__": + return "" + owner = node.func.value + if _class_name(owner) == "object": + if not node.args: + return "" + owner = node.args[0] + if isinstance(owner, ast.Name): + return names.get(owner.id, "") + if isinstance(owner, ast.Attribute) and owner.attr in SERVER_CLASSES: + return owner.attr + return "" + + +def find_new_sites(tree: ast.AST) -> list[str]: + """``" "`` per ``__new__`` call that builds one. + + The scope is the dotted chain of enclosing ``def``/``class`` names, or + ```` at module level; the list is sorted. + """ + names = _server_class_names(tree) + sites = [] + stack = [(tree, "")] + while stack: + node, scope = stack.pop() + server_class = _built_server_class(node, names) + if server_class: + sites.append(f"{scope or ''} {server_class}") + if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)): + scope = f"{scope}.{node.name}" if scope else node.name + stack.extend((child, scope) for child in ast.iter_child_nodes(node)) + return sorted(sites) + + +def scan_tests(tests_root: Path = TESTS_ROOT) -> dict[str, list[str]]: + sites_by_file = {} + for path in sorted(tests_root.rglob("*.py")): + try: + tree = ast.parse(path.read_text(errors="replace")) + except SyntaxError: + continue + sites = find_new_sites(tree) + if sites: + sites_by_file[str(path.relative_to(REPO_ROOT))] = sites + return sites_by_file + + +def ratchet_problems( + sites_by_file: dict[str, list[str]], baseline: dict[str, list[str]] +) -> list[str]: + """Sites missing from ``baseline``, then baseline entries with no site left, per file.""" + problems = [] + for file in sorted(set(sites_by_file) | set(baseline)): + live = Counter(sites_by_file.get(file, [])) + recorded = Counter(baseline.get(file, [])) + for site in sorted((live - recorded).elements()): + problems.append( + f"{file}: '{site}' builds a server with object.__new__ and is not in the " + "baseline; use `isolated_serve_env` from " + "tests/test_common/serve/app_factory.py instead; see " + "tensorrt_llm/serve/AGENTS.md." + ) + for site in sorted((recorded - live).elements()): + problems.append( + f"{file}: '{site}' no longer builds a server with object.__new__; delete it " + f"from BASELINE[{file!r}] in tests/unittest/serve/test_no_object_new.py; the " + "baseline only shrinks." + ) + return problems + + +def test_no_new_object_new_sites(): + problems = ratchet_problems(scan_tests(), BASELINE) + assert not problems, "\n".join(problems) + + +# --------------------------------------------------------------------------- +# Self-test on synthetic sources: the scan counts calls, not text. +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + "source,expected", + [ + ('"""object.__new__(OpenAIServer) in a docstring"""', 0), + ("# object.__new__(OpenAIServer) in a comment\nx = 1", 0), + ("server = object.__new__(OpenAIServer)", 1), + ("server = object.__new__(mod.OpenAIDisaggServer)", 1), + ("server = CoordinatorServer.__new__(CoordinatorServer)", 1), + ("thing = object.__new__(SomethingElse)", 0), + ("from m import OpenAIServer as Server\nserver = object.__new__(Server)", 1), + ("from m import OpenAIDisaggServer as S\nserver = S.__new__(S)", 1), + ("from m import SomethingElse as Server\nthing = object.__new__(Server)", 0), + ], +) +def test_scan_counts_call_nodes(source, expected): + assert len(find_new_sites(ast.parse(source))) == expected + + +def test_scan_names_sites_by_scope_and_class(): + source = ( + "from tensorrt_llm.serve.openai_server import OpenAIServer as Server\n" + "SERVER = object.__new__(OpenAIServer)\n" + "class TestServer:\n" + " def test_build(self):\n" + " return object.__new__(Server)\n" + ) + assert find_new_sites(ast.parse(source)) == [ + " OpenAIServer", + "TestServer.test_build OpenAIServer", + ] + + +def test_ratchet_flags_a_replaced_site(): + # Removing one site and adding one in another function keeps the file's + # total; the ratchet still reports both. + file = "tests/unittest/test_example.py" + before = find_new_sites(ast.parse("def test_old():\n object.__new__(OpenAIServer)\n")) + after = find_new_sites(ast.parse("def test_new():\n object.__new__(OpenAIServer)\n")) + assert ratchet_problems({file: after}, {file: after}) == [] + problems = ratchet_problems({file: after}, {file: before}) + assert len(problems) == 2, problems + assert "'test_new OpenAIServer' builds a server" in problems[0] + assert "'test_old OpenAIServer' no longer builds a server" in problems[1] diff --git a/tests/unittest/serve/test_serve_test_helpers.py b/tests/unittest/serve/test_serve_test_helpers.py new file mode 100644 index 000000000000..aa70512d9986 --- /dev/null +++ b/tests/unittest/serve/test_serve_test_helpers.py @@ -0,0 +1,404 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Self-tests of the serve test seam: the helpers other serve tests build on.""" + +import asyncio +import json +import os +from pathlib import Path + +import pytest +from fastapi import APIRouter, FastAPI +from prometheus_client import REGISTRY +from test_common.serve.app_factory import AggConfig, isolated_serve_env +from test_common.serve.cpu_tests import select_entries +from test_common.serve.fakes import ( + FakeLLM, + FakeLlmArgs, + ScriptedOutput, + ScriptedStep, + UserProbeMiddleware, +) +from test_common.serve.middleware import middleware_snapshot +from test_common.serve.routes import _records_conflict, compare, effective_routes + +import tensorrt_llm._utils +from tensorrt_llm.inputs.media_io import BaseMediaIO +from tensorrt_llm.sampling_params import SamplingParams +from tensorrt_llm.usage import usage_lib + +# threadleak is off: the scripted-generation tests create TestClients and run +# requests inside the test body, so the client's portal thread and the fake +# server's worker-pool threads are still alive when the leak check runs; the +# serve_env fixture closes them in its teardown, which runs after that check +# (precedent: tests/unittest/llmapi/apps/test_serve_lazy_import.py). +pytestmark = [pytest.mark.cpu_only, pytest.mark.threadleak(enabled=False)] + +REPO_ROOT = Path(__file__).resolve().parents[3] +_MISSING = object() + + +# --------------------------------------------------------------------------- +# effective_routes +# --------------------------------------------------------------------------- + + +def test_effective_routes_flattens_included_routers(): + app = FastAPI() + app.add_api_route("/direct", lambda: None, methods=["GET"]) + router = APIRouter() + router.add_api_route("/from_router", lambda: None, methods=["POST"]) + app.include_router(router) + prefixed = APIRouter() + prefixed.add_api_route("/suffix", lambda: None, methods=["GET"]) + app.include_router(prefixed, prefix="/pre") + paths = [path for path, _ in effective_routes(app)] + assert "/direct" in paths + assert "/from_router" in paths, ( + "effective_routes must walk into included routers; FastAPI 0.139 keeps them as " + "objects without a path attribute (duck-typed on original_router and " + "include_context in test_common/serve/routes.py)." + ) + assert "/pre/suffix" in paths, "an include_router prefix must be applied to the leaf paths" + + +def test_effective_routes_matches_app_routes_without_includes(): + app = FastAPI() + app.add_api_route("/only", lambda: None, methods=["GET"]) + assert [route for _, route in effective_routes(app)] == list(app.routes) + + +# --------------------------------------------------------------------------- +# compare and the conflict rule +# --------------------------------------------------------------------------- + + +def test_compare_reports_each_difference_kind(): + expected = [ + "GET /a _MsgspecRoute", + "GET /metrics _MsgspecRoute #get_iteration_stats", + "GET /metrics _MsgspecRoute #metrics", + "POST /v1/chat/completions _MsgspecRoute", + ] + actual = [ + "GET /metrics _MsgspecRoute #metrics", + "GET /metrics _MsgspecRoute #get_iteration_stats", + "POST /v1/chat/completions APIRoute", + "POST /new _MsgspecRoute", + ] + differences = compare(expected, actual) + assert any(d.startswith("added:") and "/new" in d for d in differences) + assert any(d.startswith("removed:") and "GET /a" in d for d in differences) + assert any( + "route class changed" in d + and "_MsgspecRoute -> APIRoute" in d + and "(a plain APIRouter breaks msgpack bodies from the disaggregated frontend)" in d + for d in differences + ) + assert any("order changed" in d and "#get_iteration_stats" in d for d in differences) + + +def test_compare_ignores_order_of_non_conflicting_routes(): + expected = ["GET /a APIRoute", "GET /b APIRoute"] + assert compare(expected, ["GET /b APIRoute", "GET /a APIRoute"]) == [] + assert compare(expected, list(expected)) == [] + + +# The first six rows use records of the real apps, the rest are synthetic. +@pytest.mark.parametrize( + "record_a,record_b,conflict", + [ + ( + "GET /metrics _MsgspecRoute #get_iteration_stats", + "GET /metrics _MsgspecRoute #metrics", + True, + ), + ( + "GET /v1/responses/{response_id} _MsgspecRoute", + "DELETE /v1/responses/{response_id} _MsgspecRoute", + False, + ), + ( + "GET /v1/messages/batches _MsgspecRoute", + "GET /v1/messages/batches/{batch_id} _MsgspecRoute", + False, + ), + ( + "GET /v1/images/{image_id}/content _MsgspecRoute", + "GET /v1/videos/{video_id}/content _MsgspecRoute", + False, + ), + ("MOUNT /prometheus/metrics Mount", "GET /metrics _MsgspecRoute", False), + ("GET,HEAD /docs Route", "GET,HEAD /docs/oauth2-redirect Route", False), + ("GET /v1/models _MsgspecRoute", "GET /v1/{name} APIRoute", True), + ("GET,HEAD /openapi.json Route", "GET /openapi.json APIRoute", True), + ("GET /files/{rest:path} APIRoute", "GET /files/a/b APIRoute", True), + ("MOUNT /prometheus/metrics Mount", "POST /prometheus/metrics/x APIRoute", True), + ], +) +def test_conflict_rule(record_a, record_b, conflict): + assert _records_conflict(record_a, record_b) is conflict + + +# --------------------------------------------------------------------------- +# middleware_snapshot format +# --------------------------------------------------------------------------- + + +def test_middleware_snapshot_format(): + from tensorrt_llm.serve.responses_utils import ServerArrivalTimeMiddleware + + app = FastAPI() + app.add_middleware(ServerArrivalTimeMiddleware, adjusted_clock=None) + app.add_middleware(UserProbeMiddleware) # added last, so outermost + snapshot = middleware_snapshot(app) + assert snapshot == [ + {"class": "UserProbeMiddleware"}, # not a tensorrt_llm class: name only + {"class": "ServerArrivalTimeMiddleware", "kwargs": ["adjusted_clock"]}, + ] + + +# --------------------------------------------------------------------------- +# isolated_serve_env +# --------------------------------------------------------------------------- + + +def test_isolated_serve_env_restores_global_state(tmp_path): + environ_before = dict(os.environ) + media_executor_before = BaseMediaIO._executor + prometheus_dir_before = getattr(tensorrt_llm._utils, "prometheus_multiproc_dir", _MISSING) + session_before = usage_lib._SESSION + collectors_before = set(REGISTRY._collector_to_names.keys()) + + with isolated_serve_env(tmp_path) as env: + env.build_openai_server(AggConfig(return_perf_metrics=True)) + os.environ["A2_RESTORE_SENTINEL"] = "1" + sink = env.record_terminations() + assert usage_lib._SESSION is not None and sink == [] + + assert dict(os.environ) == environ_before + assert BaseMediaIO._executor is media_executor_before + prometheus_dir_after = getattr(tensorrt_llm._utils, "prometheus_multiproc_dir", _MISSING) + if prometheus_dir_before is _MISSING: + assert prometheus_dir_after is _MISSING, ( + "isolated_serve_env must delete tensorrt_llm._utils.prometheus_multiproc_dir " + "when it did not exist before entry" + ) + else: + assert prometheus_dir_after is prometheus_dir_before + assert usage_lib._SESSION is session_before + assert set(REGISTRY._collector_to_names.keys()) == collectors_before, ( + "isolated_serve_env must unregister every Prometheus collector the build added" + ) + + +def test_isolated_serve_env_rejects_use_without_with(tmp_path): + with pytest.raises(AttributeError): + isolated_serve_env(tmp_path).build_openai_server(AggConfig()) + + +# --------------------------------------------------------------------------- +# cpu_tests selection +# --------------------------------------------------------------------------- + + +def test_cpu_tests_selection(): + kept, _ = select_entries() + targets = [target for entry in kept for target in entry.targets] + expected_new_files = [ + "unittest/api_stability/test_serve_routes.py", + "unittest/serve/test_agents_md.py", + "unittest/serve/test_layering.py", + "unittest/serve/test_middleware_order.py", + "unittest/serve/test_no_object_new.py", + "unittest/serve/test_serve_test_helpers.py", + "unittest/serve/test_shim_identity.py", + "unittest/serve/api/ops/system/test_system_endpoints.py", + "unittest/serve/api/visual_gen/test_ops_system_visual_gen.py", + "unittest/serve/api/visual_gen/test_routes_visual_gen.py", + "unittest/serve/api/visual_gen/test_shim_identity_visual_gen.py", + ] + for target in expected_new_files: + assert target in targets, f"the serve CPU runner must select {target}" + assert "unittest/llmapi/apps/test_anthropic_routes.py" in targets + for target in targets: + file_part = target.split("::")[0] + text = (REPO_ROOT / "tests" / file_part).read_text(errors="replace") + assert "pytest.mark.cpu_only" in text, ( + f"{file_part} is selected but carries no cpu_only marker; the CPU stage would " + "collect nothing from it" + ) + + +def test_cpu_tests_selection_keeps_node_ids(tmp_path): + # A node-id entry stays a node id: only that node runs, never the whole file. + node = "unittest/serve/test_serve_test_helpers.py::test_cpu_tests_selection" + cpu_list = tmp_path / "l0_cpu.yml" + cpu_list.write_text(f"l0_cpu:\n- tests:\n - {node}\n") + kept, notes = select_entries(cpu_list) + assert [entry.targets for entry in kept] == [(node,)], kept + assert not notes, notes + + +# --------------------------------------------------------------------------- +# Scripted generation through the production handlers +# --------------------------------------------------------------------------- + +_CHAT_BODY = { + "model": "fake-model", + "messages": [{"role": "user", "content": "hi"}], + "cache_salt": "salted", +} + + +def test_scripted_chat_non_streaming(serve_env): + server = serve_env.build_openai_server(AggConfig()) + client = serve_env.client(server.app) + response = client.post("/v1/chat/completions", json=_CHAT_BODY) + assert response.status_code == 200, response.text + body = response.json() + assert body["choices"][0]["message"]["content"] == "ok" # the default scripted text + generator = server.generator + assert len(generator.preprocess_calls) == 1 + call = generator.generate_calls[0] + assert isinstance(call.sampling_params, SamplingParams) + assert call.kwargs["streaming"] is False + assert call.kwargs["cache_salt"] == "salted" + + +def test_scripted_chat_streaming(serve_env): + server = serve_env.build_openai_server(AggConfig()) + server.generator.script( + ScriptedOutput( + steps=( + ScriptedStep(text="he", token_ids=(6,)), + ScriptedStep(text="llo", token_ids=(6,), finish_reason="stop"), + ) + ) + ) + client = serve_env.client(server.app) + with client.stream( + "POST", "/v1/chat/completions", json={**_CHAT_BODY, "stream": True} + ) as response: + assert response.status_code == 200 + lines = [line for line in response.iter_lines() if line.startswith("data: ")] + assert lines[-1] == "data: [DONE]" + deltas = [json.loads(line[len("data: ") :]) for line in lines[:-1]] + text = "".join( + choice["delta"].get("content") or "" for delta in deltas for choice in delta["choices"] + ) + assert text == "hello" + assert server.generator.generate_calls[0].kwargs["streaming"] is True + + +def test_scripted_completion_through_real_input_processor(serve_env): + server = serve_env.build_openai_server(AggConfig()) + server.generator.script( + ScriptedOutput(steps=(ScriptedStep(text="done", token_ids=(7,), finish_reason="stop"),)) + ) + client = serve_env.client(server.app) + response = client.post("/v1/completions", json={"model": "fake-model", "prompt": "hello hi"}) + assert response.status_code == 200, response.text + assert response.json()["choices"][0]["text"] == "done" + call = server.generator.generate_calls[0] + # A text prompt goes through the real DefaultInputProcessor, which + # tokenizes with the fake tokenizer: "hello hi" -> ids 6 and 5. + assert call.inputs == {"prompt_token_ids": [6, 5]} + + +def test_postprocess_worker_path_answers_through_postprocess_result(serve_env): + server = serve_env.build_openai_server(AggConfig(num_postprocess_workers=1)) + client = serve_env.client(server.app) + response = client.post("/v1/chat/completions", json=_CHAT_BODY) + assert response.status_code == 200, response.text + assert response.json()["choices"][0]["message"]["content"] == "ok" + promise = server.generator.generate_calls[0].result + assert promise.outputs[0]._postprocess_result is not None + with client.stream( + "POST", "/v1/chat/completions", json={**_CHAT_BODY, "stream": True} + ) as streaming_response: + lines = [line for line in streaming_response.iter_lines() if line.startswith("data: ")] + assert lines[-1] == "data: [DONE]" + assert any('"content"' in line for line in lines[:-1]) + + +def test_raise_on_call_returns_400_and_records_the_call(serve_env): + server = serve_env.build_openai_server(AggConfig()) + server.generator.script(ScriptedOutput(raise_on_call=RuntimeError("scripted failure"))) + client = serve_env.client(server.app) + response = client.post("/v1/chat/completions", json=_CHAT_BODY) + assert response.status_code == 400 + assert response.json()["message"] == "scripted failure" + call = server.generator.generate_calls[0] + assert call.result is None # recorded before the scripted exception fired + assert isinstance(call.sampling_params, SamplingParams) + + +def test_raise_after_steps_ends_a_stream_with_the_scripted_error(serve_env): + server = serve_env.build_openai_server(AggConfig()) + server.generator.script( + ScriptedOutput( + steps=(ScriptedStep(text="partial", token_ids=(5,)),), + raise_after_steps=RuntimeError("stream exploded"), + ) + ) + client = serve_env.client(server.app) + received = [] + with pytest.raises(RuntimeError, match="stream exploded"): + with client.stream( + "POST", "/v1/chat/completions", json={**_CHAT_BODY, "stream": True} + ) as response: + for line in response.iter_lines(): + received.append(line) + assert any("partial" in line for line in received), ( + "the first scripted chunk must reach the client before the scripted error" + ) + + +def test_hold_after_steps_release_and_cancellation(): + async def scenario(): + llm = FakeLLM(args=FakeLlmArgs(model="unused")) + llm.script( + ScriptedOutput( + steps=(ScriptedStep(text="first", token_ids=(5,)),), hold_after_steps=True + ) + ) + promise = llm.generate_async({"prompt_token_ids": [1, 2]}, SamplingParams()) + first = await promise.__anext__() + assert first.outputs[0].text == "first" + assert not promise.finished + + async def consume_rest(): + async for _ in promise: + pass + + consumer = asyncio.create_task(consume_rest()) + await asyncio.sleep(0) # the consumer reaches the hold + promise.release() + await consumer # release ends the wait with a normal end of stream + assert promise.finished + + llm.script( + ScriptedOutput(steps=(ScriptedStep(text="x", token_ids=(5,)),), hold_after_steps=True) + ) + held = llm.generate_async({"prompt_token_ids": [1]}, SamplingParams()) + await held.__anext__() + hanging = asyncio.create_task(held.__anext__()) + await asyncio.sleep(0) + hanging.cancel() # a client disconnect cancels the consuming task + with pytest.raises(asyncio.CancelledError): + await hanging + + asyncio.run(scenario()) diff --git a/tests/unittest/serve/test_shim_identity.py b/tests/unittest/serve/test_shim_identity.py new file mode 100644 index 000000000000..2843e2bb1353 --- /dev/null +++ b/tests/unittest/serve/test_shim_identity.py @@ -0,0 +1,245 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Identity, FutureWarning and old-path-import checks of the kept serve shims. + +``SHIM_ROWS`` starts empty: only the pull requests that keep an old import path +as a shim (old paths that code outside the repository imports) add rows here. +Each row then checks that the old name is the same object as the new one, that +the shim warns with the expected ``FutureWarning``, and that nothing inside the +repository imports the old path. The self-tests below prove the three checks +can fail, so the empty table is not vacuous. +""" + +import sys +import textwrap +from pathlib import Path + +import pytest +from test_common.serve.shims import ShimRow, check_identity, check_warnings, find_old_path_imports + +pytestmark = pytest.mark.cpu_only + +REPO_ROOT = Path(__file__).resolve().parents[3] + +# Rows are added only by the pull requests that create the kept shims. +SHIM_ROWS: tuple = () + + +def test_shim_identity(): + assert check_identity(SHIM_ROWS) == [] + + +def test_shim_warnings(): + assert check_warnings(SHIM_ROWS) == [] + + +def test_no_old_path_imports(): + assert find_old_path_imports(SHIM_ROWS, REPO_ROOT) == [] + + +# --------------------------------------------------------------------------- +# Self-test on a synthetic package: each check must be able to fail. +# --------------------------------------------------------------------------- + + +@pytest.fixture +def shim_package(tmp_path, monkeypatch): + """A synthetic package with good, silent, copying, lazy and interface shims.""" + pkg = "shim_selftest_pkg" + root = tmp_path / pkg + root.mkdir() + (root / "__init__.py").write_text("") + (root / "new.py").write_text( + textwrap.dedent( + """ + class X: + pass + + TABLE = {"a": 1} + + def main(): + pass + """ + ) + ) + (root / "good.py").write_text( + textwrap.dedent( + f""" + import warnings + + from {pkg}.new import TABLE, X + + warnings.warn( + "{pkg}.good has moved to {pkg}.new and will be removed in 1.6.0.", + FutureWarning, + stacklevel=2, + ) + __all__ = ["TABLE", "X"] + """ + ) + ) + (root / "silent.py").write_text(f"from {pkg}.new import X\n__all__ = ['X']\n") + (root / "bad.py").write_text("class X:\n pass\n__all__ = ['X']\n") + (root / "lazy.py").write_text( + textwrap.dedent( + f""" + import warnings + + from {pkg}.new import main + + _LAZY_NAMES = {{"X": "{pkg}.new"}} + + def __getattr__(name): + if name in _LAZY_NAMES: + warnings.warn( + f"{pkg}.lazy.{{name}} has moved to {pkg}.new " + "and will be removed in 1.6.0.", + FutureWarning, + stacklevel=2, + ) + import importlib + + value = getattr(importlib.import_module(_LAZY_NAMES[name]), name) + globals()[name] = value # warn once: later reads skip __getattr__ + return value + raise AttributeError(name) + """ + ) + ) + (root / "iface.py").write_text( + textwrap.dedent( + f""" + def __getattr__(name): + if name == "X": + from {pkg}.new import X + + return X + raise AttributeError(name) + """ + ) + ) + sub = root / "sub" + sub.mkdir() + (sub / "__init__.py").write_text( + textwrap.dedent( + f""" + import warnings + + from {pkg}.new import X + + warnings.warn( + "{pkg}.sub has moved to {pkg}.new and will be removed in 1.6.0.", + FutureWarning, + stacklevel=2, + ) + __all__ = ["X"] + """ + ) + ) + (sub / "mod.py").write_text( + textwrap.dedent( + f""" + import warnings + + from {pkg}.new import X + + warnings.warn( + "{pkg}.sub.mod has moved to {pkg}.new and will be removed in 1.6.0.", + FutureWarning, + stacklevel=2, + ) + __all__ = ["X"] + """ + ) + ) + (root / "importer.py").write_text(f"from {pkg}.good import X\n") + (root / "module_user.py").write_text( + f"from {pkg} import good\n\n\ndef use():\n return good.X\n" + ) + (root / "other_name_user.py").write_text( + f"from {pkg} import good\n\n\ndef use():\n return good.TABLE\n" + ) + monkeypatch.syspath_prepend(str(tmp_path)) + yield pkg, tmp_path + for name in list(sys.modules): + if name == pkg or name.startswith(pkg + "."): + del sys.modules[name] + + +def _row(pkg, module, name, **kwargs): + retire_in = kwargs.pop("retire_in", "1.6.0") + return ShimRow(f"{pkg}.{module}", name, f"{pkg}.new", retire_in=retire_in, **kwargs) + + +def test_identity_check_passes_and_fails(shim_package): + pkg, _ = shim_package + good_rows = [_row(pkg, "good", "X"), _row(pkg, "good", "TABLE")] + assert check_identity(good_rows) == [] + problems = check_identity([_row(pkg, "bad", "X")]) + assert len(problems) == 1 and "not the same object" in problems[0] + problems = check_identity([_row(pkg, "good", "GONE")]) + assert len(problems) == 1 and "no longer exists" in problems[0] + + +def test_warning_check_passes_for_shim_styles(shim_package): + pkg, _ = shim_package + rows = [ + _row(pkg, "good", "X"), + _row(pkg, "good", "TABLE"), + _row(pkg, "lazy", "X"), # warns on the first read only + _row(pkg, "lazy", "main"), # eager name: never warns + _row(pkg, "iface", "X", warns=False, ban_old_path=False, retire_in="not retired"), + # A fresh import of a shim submodule also imports (and warns for) its + # parent shim package; the message filter must not count that warning. + _row(pkg, "sub.mod", "X"), + ] + assert f"{pkg}.sub" not in sys.modules + assert check_warnings(rows) == [] + + +def test_warning_check_reports_silent_and_wrong_release(shim_package): + pkg, _ = shim_package + problems = check_warnings([_row(pkg, "silent", "X")]) + assert len(problems) == 1 and "emitted no FutureWarning" in problems[0] + wrong_release = ShimRow(f"{pkg}.good", "X", f"{pkg}.new", retire_in="9.9.9") + problems = check_warnings([wrong_release]) + assert len(problems) == 1 and "names the new location and the removal release" in problems[0] + + +def test_warning_check_restores_sys_modules(shim_package): + pkg, _ = shim_package + import importlib + + before = importlib.import_module(f"{pkg}.good") + assert check_warnings([_row(pkg, "good", "X")]) == [] + assert sys.modules[f"{pkg}.good"] is before + assert getattr(sys.modules[pkg], "good") is before + + +def test_old_path_import_scan(shim_package): + pkg, tmp_path = shim_package + rows = [_row(pkg, "good", "X")] + problems = find_old_path_imports(rows, tmp_path, roots=(pkg,)) + importing_lines = [p for p in problems if "importer.py" in p] + module_attribute_lines = [p for p in problems if "module_user.py" in p] + other_name_lines = [p for p in problems if "other_name_user.py" in p] + assert len(importing_lines) == 1, problems + assert f"import it from `{pkg}.new`" in importing_lines[0] + # `from import good` + `good.X` loads the shim as surely as a from-import. + assert len(module_attribute_lines) == 1, problems + # Reading another name of the module is not banned by this row. + assert other_name_lines == [], problems + # The shim's own file is exempt. + assert not any("good.py" in p for p in problems), problems