Skip to content

[TRTLLM-17262][refactor] Shared middleware package for the aggregated and disaggregated servers - #21447

Open
JunyiXu-nv wants to merge 2 commits into
NVIDIA:mainfrom
JunyiXu-nv:dev-junyix-feat-serve-middleware-package
Open

JunyiXu-nv wants to merge 2 commits into
NVIDIA:mainfrom
JunyiXu-nv:dev-junyix-feat-serve-middleware-package

Conversation

@JunyiXu-nv

@JunyiXu-nv JunyiXu-nv commented Nov 2, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Move the built-in arrival-time middleware, performance-metrics middleware and CLI middleware loader to tensorrt_llm/serve/middleware/. Both server constructors use the same registration function, while retaining their distinct arguments. This is a single behavior-preserving refactor; it does not add request tracing or change how request state is initialized.

Request-state behavior is unchanged. On HTTP requests ServerArrivalTimeMiddleware still assigns a fresh scope["state"] and then sets server_arrival_time. It does not keep keys from an outer middleware or lifespan, and it does not mutate the previous dictionary. Non-HTTP scopes still pass through untouched. The three relocated definitions match their pre-move source text exactly.

  • Both servers register metrics first (when enabled) and arrival time second, so arrival runs before metrics. User middleware registered after construction remains outermost.
  • The aggregate server forwards the same clock to the installed middleware and its existing observer to metrics. With metrics off, the constructors do not read the metrics writer, header-exposure flag, or observer just to pass unused arguments. The disaggregated server still omits both clock and observer keywords.

For contributors

  • serve.responses_utils.ServerArrivalTimeMiddleware → serve.middleware.arrival_time.ServerArrivalTimeMiddleware
  • serve.perf_metrics.PerfMetricsMiddleware → serve.middleware.perf_metrics.PerfMetricsMiddleware
  • commands.serve._apply_fastapi_middlewares → serve.middleware.user_middleware._apply_fastapi_middlewares

Paths above are relative to tensorrt_llm. Import or patch the moved definitions in their new modules; no compatibility re-exports are added. The existing serving instructions point contributors to serve/middleware/register.py; no agent instruction files are added. The unittest/serve CPU entry already collects the new tests, and the middleware package is included in the existing multi-GPU trigger table.

Validation

At d1ed8cefcdec, the same 160 CPU cases passed on both FastAPI 0.136.3 and 0.139.2 (158 core and two VisualGen route cases per version, no failures, setup errors or skips). Each run used the worktree's Python source and test factory with the official native build for its exact base, b963a7ab7565. An interrupted earlier run was not counted.

Four characterization cases cover absent, empty and populated state and a real FastAPI outer-middleware/lifespan request. Substituting the discarded setdefault implementation makes the three existing-state cases fail by assertion; the absent-state case still passes. Registration was also compared over 32 bounded input combinations; both deliberately introduced registration defects were detected.

The relocation check and independent source comparison found three verbatim definitions and no undeclared differences. Normal hooks and strict checks on the new product modules passed. The advisory type check is not clean across all changed files: four unchanged-line diagnostics were retained in the explicit scoped hook runs. No GPU/model run or restricted socket-fixture coverage is claimed. The earlier graceful-shutdown cleanup discrepancy remains a separate, unwaived observation.

Before merging, reconcile intervening edits, including #20280 if it lands first, and complete normal owner review and required CI.

Complete relocation comparison
## Move spec

```yaml
moves:
- from: tensorrt_llm/serve/responses_utils.py
  to: tensorrt_llm/serve/middleware/arrival_time.py
  group: B
  symbols:
  - ServerArrivalTimeMiddleware
- from: tensorrt_llm/serve/perf_metrics.py
  to: tensorrt_llm/serve/middleware/perf_metrics.py
  group: A
  symbols:
  - PerfMetricsMiddleware
- from: tensorrt_llm/commands/serve.py
  to: tensorrt_llm/serve/middleware/user_middleware.py
  group: B
  symbols:
  - _apply_fastapi_middlewares
modified:
- symbol: tensorrt_llm/serve/openai_server.py::OpenAIServer.__init__
  reason: register_middlewares replaces the two add_middleware calls
- symbol: tensorrt_llm/serve/openai_disagg_server.py::OpenAIDisaggServer.__init__
  reason: register_middlewares replaces the two add_middleware calls
rewrite_internal_imports: true
```

Pure-move check: base b963a7ab7565, head d1ed8cefcdec, tools 488af2dd4cb7

| Symbol | From | To | Result |
|---|---|---|---|
| `_apply_fastapi_middlewares` | tensorrt_llm/commands/serve.py | tensorrt_llm/serve/middleware/user_middleware.py | verbatim |
| `OpenAIDisaggServer.__init__` | tensorrt_llm/serve/openai_disagg_server.py | tensorrt_llm/serve/openai_disagg_server.py | modified (declared) |
| `OpenAIServer.__init__` | tensorrt_llm/serve/openai_server.py | tensorrt_llm/serve/openai_server.py | modified (declared) |
| `PerfMetricsMiddleware` | tensorrt_llm/serve/perf_metrics.py | tensorrt_llm/serve/middleware/perf_metrics.py | verbatim |
| `ServerArrivalTimeMiddleware` | tensorrt_llm/serve/responses_utils.py | tensorrt_llm/serve/middleware/arrival_time.py | verbatim |

## Modified (declared)

- `OpenAIServer.__init__`: register_middlewares replaces the two add_middleware calls
  --- base
  +++ head
  @@ -192,5 +192,6 @@
           self._register_launcher_forwarding_routes()
           self.register_routes()
       if self._collect_perf_metrics:
  -        self.app.add_middleware(PerfMetricsMiddleware, expose_headers=self._expose_perf_metrics, writer=self._perf_metrics_writer, adjusted_clock=self._adjusted_steady_clock, input_processing_observer=self.metrics_collector.log_input_processing if self.metrics_collector else None)
  -    self.app.add_middleware(ServerArrivalTimeMiddleware, adjusted_clock=self._adjusted_steady_clock)
  +        register_middlewares(self.app, collect_perf_metrics=True, expose_perf_metrics=self._expose_perf_metrics, perf_metrics_writer=self._perf_metrics_writer, adjusted_clock=self._adjusted_steady_clock, input_processing_observer=self.metrics_collector.log_input_processing if self.metrics_collector else None)
  +    else:
  +        register_middlewares(self.app, collect_perf_metrics=False, adjusted_clock=self._adjusted_steady_clock)
- `OpenAIDisaggServer.__init__`: register_middlewares replaces the two add_middleware calls
  --- base
  +++ head
  @@ -41,8 +41,9 @@
       self.app.state.trust_kv_hints = os.getenv('TRTLLM_TRUST_KV_HINTS', '0') == '1'
       self.app.router.route_class = KvHintsRoute
       if self._collect_perf_metrics:
  -        self.app.add_middleware(PerfMetricsMiddleware, expose_headers=self._expose_perf_metrics, writer=self._perf_metrics_writer)
  -    self.app.add_middleware(ServerArrivalTimeMiddleware)
  +        register_middlewares(self.app, collect_perf_metrics=True, expose_perf_metrics=self._expose_perf_metrics, perf_metrics_writer=self._perf_metrics_writer)
  +    else:
  +        register_middlewares(self.app, collect_perf_metrics=False)
       self._val_err_n = 0
   
       @self.app.exception_handler(RequestValidationError)

3 definitions moved verbatim; 0 differences; 2 modified (declared); shim exports 0 names

🤖 Generated with Claude Code

Dev Engineer Review

  • Removed import paths: No compatibility re-exports remain. PerfMetricsMiddleware leaves tensorrt_llm/serve/perf_metrics.py, ServerArrivalTimeMiddleware leaves tensorrt_llm/serve/responses_utils.py, and _apply_fastapi_middlewares leaves tensorrt_llm/commands/serve.py. External importers of these names fail.
  • Shared registration: register_middlewares in middleware/register.py installs ServerArrivalTimeMiddleware first and PerfMetricsMiddleware second, only when collect_perf_metrics is true. The last added middleware is outermost, so metrics wraps arrival time. The PR objectives describe the order as "metrics register before arrival-time middleware." Confirm the intended order against the code.
  • Client split: The aggregate server passes the clock and observer. The disaggregated server omits them. Confirm this split is intended.
  • Request state: ServerArrivalTimeMiddleware replaces scope["state"] with a new dictionary. Check this against existing consumers of scope state.
  • Lint baseline: ruff-legacy-baseline.json adds one D212 violation for arrival_time.py.
  • CI: The latest reported L0_MergeRequest_PR run (#72362) failed, though its PR_Github job succeeded. Failure analysis is linked in the PR. jenkins/L0_MergeRequest.groovy now routes tensorrt_llm/serve/middleware/ changes to multi-GPU testing.
  • Open items: A graceful-shutdown cleanup discrepancy is unresolved. Reconciliation with #20280 and owner review are pending.

QA Engineer Review

Test files changed:

  • Added: tests/unittest/serve/middleware/test_register.py (350 lines). It covers registration order and arguments for both app types, arrival-time state replacement, outermost user middleware, metrics records and headers, and observer behavior on success, failure, and liveness requests. Failing requests must not submit metrics or emit a server-timing header.
  • Added: tests/unittest/serve/middleware/__init__.py (license header only).
  • Modified (import updates only): test_disagg_openai_client.py, test_anthropic_routes.py, test_openai_input_metrics.py, test_request_metrics.py, test_config_database.py, test_middleware_order.py, test_serve_test_helpers.py.
  • Modified (new rule): tests/unittest/serve/test_layering.py forbids middleware from importing serve.api, the OpenAI server modules, or serve.responses_utils.

Coverage:

  • The author reports 160 CPU cases passing on FastAPI 0.136.3 and 0.139.2.
  • No GPU or model run is claimed.
  • Test-db or QA list membership for the new test file is not established.

Verdict: needs follow-up. Confirm the test-db listing. Resolve the graceful-shutdown discrepancy. Run the GPU-backed serving path before merge.

Per-File QA Perspective

  • tensorrt_llm/serve/middleware/register.py: Verify metrics-off and metrics-on paths, and clock and observer forwarding.
  • tensorrt_llm/serve/middleware/arrival_time.py: Verify server_arrival_time is set on HTTP requests and non-HTTP scopes pass through.
  • tensorrt_llm/serve/middleware/perf_metrics.py: Verify metrics headers, SSE append, JSONL submission, and that /health_generate is excluded from the observer.
  • tensorrt_llm/serve/middleware/user_middleware.py: Verify --middleware accepts only <module>.<object> and raises ValueError for invalid objects.
  • tensorrt_llm/serve/middleware/__init__.py: Header and docstring only.
  • tensorrt_llm/serve/openai_server.py: Verify metrics-enabled and metrics-disabled registration paths.
  • tensorrt_llm/serve/openai_disagg_server.py: Verify metrics stay disabled when not configured, and that clock and observer are not passed.
  • tensorrt_llm/serve/perf_metrics.py: Class removed. Verify no remaining importers.
  • tensorrt_llm/serve/responses_utils.py: Middleware removed. Verify get_steady_clock_now_in_seconds remains importable.
  • tensorrt_llm/commands/serve.py: Verify trtllm-serve --middleware still loads user middleware.
  • jenkins/L0_MergeRequest.groovy: Middleware changes now trigger multi-GPU testing. Expect longer CI for these changes.
  • .pre-commit-config.yaml, legacy-files.txt, pyproject.toml, ruff-legacy.toml, ruff-legacy-baseline.json: Lint and legacy-list updates for the moved files. Lint results are not established.
  • tensorrt_llm/serve/AGENTS.md: Guidance names register.py and states that middleware order must not change.

@JunyiXu-nv
JunyiXu-nv force-pushed the dev-junyix-feat-serve-middleware-package branch from 8971d38 to a0aa0df Compare November 4, 2026 12:49
JunyiXu-nv added a commit to JunyiXu-nv/TensorRT-LLM that referenced this pull request Nov 4, 2026
…eware package branch as the base for the shared app assembly

Base for the shared app assembly: both open PRs it builds on, NVIDIA#21447 (shared
middleware package for the aggregated and disaggregated servers) and NVIDIA#21448
(router skeleton and the ops.system endpoints), merged into one branch.

Conflicts resolved by keeping both sides: the mypy file list in
pyproject.toml and the import-direction contracts in
tests/unittest/serve/test_layering.py.

Signed-off-by: JunyiXu-nv <[email protected]>
@JunyiXu-nv
JunyiXu-nv force-pushed the dev-junyix-feat-serve-middleware-package branch from a0aa0df to d1ed8ce Compare November 20, 2026 09:14
@JunyiXu-nv
JunyiXu-nv marked this pull request as ready for review November 20, 2026 09:15
@JunyiXu-nv
JunyiXu-nv requested review from a team as code owners November 20, 2026 09:15
@coderabbitai

coderabbitai Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

The change moves arrival-time and performance-metrics middleware into a dedicated package, centralizes built-in middleware registration for both serving apps, and relocates user middleware loading from the serve command.

Changes

Serving Middleware

Layer / File(s) Summary
Middleware behavior and module move
tensorrt_llm/serve/middleware/arrival_time.py, tensorrt_llm/serve/middleware/perf_metrics.py, tensorrt_llm/serve/perf_metrics.py, tensorrt_llm/serve/responses_utils.py, serving middleware tests, Ruff and CI configuration
The arrival-time and performance-metrics middleware are added under serve/middleware, and their former definitions are removed. Tests import the middleware from the new modules. Ruff and CI configuration includes the new middleware paths.
Built-in registration and server wiring
tensorrt_llm/serve/middleware/register.py, tensorrt_llm/serve/openai_server.py, tensorrt_llm/serve/openai_disagg_server.py, tensorrt_llm/serve/AGENTS.md, tests/unittest/serve/middleware/*, tests/unittest/serve/test_layering.py
register_middlewares installs arrival-time middleware and conditionally installs performance-metrics middleware. Both server apps use this function. Tests cover registration arguments, request state, metrics, and observer behavior.
User middleware loading
tensorrt_llm/serve/middleware/user_middleware.py, tensorrt_llm/commands/serve.py, tests/unittest/llmapi/test_config_database.py, tests/unittest/serve/test_middleware_order.py, tests/unittest/serve/middleware/test_register.py
The user middleware loading helper moves from commands/serve.py to serve/middleware/user_middleware.py. The command and tests import it from the new location. Tests cover the outermost position of user middleware.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Change: Refactor

Sequence Diagram(s)

sequenceDiagram
  participant openai_server
  participant register_middlewares
  participant FastAPI
  openai_server->>register_middlewares: Pass app and middleware options
  register_middlewares->>FastAPI: Add ServerArrivalTimeMiddleware
  opt Performance metrics collection enabled
    register_middlewares->>FastAPI: Add PerfMetricsMiddleware
  end
Loading
Merge Risk: Minimal · up to 39d0e

This is a refactor that moves serving middleware into its own package and centralizes built-in registration without changing runtime behavior. No concrete defect was found. Before merging, check the failed CI pipelines and confirm that no external code still imports the removed module paths.

Security architecture risk: Minimal · up to 39d0e

The refactor centralizes middleware setup without changing its execution order, request-state handling, or metrics exposure. The old Python import paths for two middleware classes are removed, but the reviewed change does not establish a new security or failure-containment risk.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • observed — The shared helper governs built-in middleware registration in both server variants. The inspected constructor changes alter registration calls, not the routes or controls that HTTP clients reach.

Trust Boundaries and Controls

  • observed — A client header can request response metrics, but cannot enable their exposure: the server-side exposure flag must also be set. JSONL submission remains separate and requires a configured writer and completed response records.
  • observed — Dotted-path imports remain a startup capability controlled by CLI configuration. Moving the loader does not add an HTTP path to import or register middleware.
Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title names the main change: a shared middleware package for the aggregated and disaggregated servers, with a ticket ID and refactor type in the required format. It matches the changeset, which mo…
Description check Passed The description is thorough and follows the template's intent. It gives a summary of the refactor, explains the request-state behavior, lists the moved symbols for contributors, and reports validation…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Title check

Explanation

The title names the main change: a shared middleware package for the aggregated and disaggregated servers, with a ticket ID and refactor type in the required format. It matches the changeset, which moves the arrival-time middleware, performance-metrics middleware, and CLI middleware loader into tensorrt_llm/serve/middleware/ and adds a shared registration function used by both servers.

Full details: Description check

Explanation

The description is thorough and follows the template's intent. It gives a summary of the refactor, explains the request-state behavior, lists the moved symbols for contributors, and reports validation (160 CPU cases on two FastAPI versions, characterization tests, relocation comparison). It has no separate Test Coverage section, so test coverage appears only inside the Validation section. The PR checklist is not ticked, and the description does not mention the template's title format or API label status. These gaps are minor.

Finishing Touches

Generate unit tests (beta)

  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
Recent review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between d1ed8ce and 39d0e1f.

Files selected for processing: 12

  • jenkins/L0_MergeRequest.groovy
  • tensorrt_llm/commands/serve.py
  • tensorrt_llm/serve/openai_disagg_server.py
  • tensorrt_llm/serve/openai_server.py
  • tensorrt_llm/serve/perf_metrics.py
  • tensorrt_llm/serve/responses_utils.py
  • tests/unittest/disaggregated/test_disagg_openai_client.py
  • tests/unittest/llmapi/apps/test_anthropic_routes.py
  • tests/unittest/llmapi/apps/test_openai_input_metrics.py
  • tests/unittest/llmapi/apps/test_request_metrics.py
  • tests/unittest/llmapi/test_config_database.py
  • tests/unittest/serve/test_layering.py
Files with no reviewable changes: 2

  • tensorrt_llm/serve/perf_metrics.py
  • tensorrt_llm/serve/responses_utils.py

Included review availability: This review used your included allowance. Your plan provides up to 12 included reviews per hour; 11 remain after this review.

@github-actions

Copy link
Copy Markdown

Automatically added "ci: full pre-merge approved" because this PR has satisfied the required GitHub review approvals. Unresolved review conversations and other required checks remain independent merge requirements.

@JunyiXu-nv

Copy link
Copy Markdown
Collaborator Author

/bot run

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #86938 [ run ] triggered by Bot. Commit: d1ed8ce Link to invocation

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #86938 [ run ] completed with state SUCCESS. Commit: d1ed8ce
/LLM/main/L0_MergeRequest_PR pipeline #72098 completed with status: 'FAILURE'

CI Report

⚠️ Action Required:

  • Please check the failed tests and fix your PR
  • If you cannot view the failures, ask the CI triggerer to share details
  • Once fixed, request an NVIDIA team member to trigger CI again

CI Agent Failure Analysis

Link to invocation

@JunyiXu-nv

Copy link
Copy Markdown
Collaborator Author

/bot run

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #87162 [ run ] triggered by Bot. Commit: d1ed8ce Link to invocation

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #87162 [ run ] completed with state SUCCESS. Commit: d1ed8ce
/LLM/main/L0_MergeRequest_PR pipeline #72310 completed with status: 'FAILURE'

CI Report

⚠️ Action Required:

  • Please check the failed tests and fix your PR
  • If you cannot view the failures, ask the CI triggerer to share details
  • Once fixed, request an NVIDIA team member to trigger CI again

CI Agent Failure Analysis

Link to invocation

@JunyiXu-nv

Copy link
Copy Markdown
Collaborator Author

/bot run

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #87222 [ run ] triggered by Bot. Commit: d1ed8ce Link to invocation

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #87222 [ run ] completed with state SUCCESS. Commit: d1ed8ce
/LLM/main/L0_MergeRequest_PR pipeline #72362 completed with status: 'FAILURE'

CI Report

⚠️ Action Required:

  • Please check the failed tests and fix your PR
  • If you cannot view the failures, ask the CI triggerer to share details
  • Once fixed, request an NVIDIA team member to trigger CI again

CI Agent Failure Analysis

Link to invocation

@JunyiXu-nv

Copy link
Copy Markdown
Collaborator Author

/bot run

1 similar comment
@JunyiXu-nv

Copy link
Copy Markdown
Collaborator Author

/bot run

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #87367 [ run ] triggered by Bot. Commit: 39d0e1f Link to invocation

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #87367 [ run ] completed with state SUCCESS. Commit: 39d0e1f
/LLM/main/L0_MergeRequest_PR pipeline #72491 completed with status: 'FAILURE'

CI Report

⚠️ Action Required:

  • Please check the failed tests and fix your PR
  • If you cannot view the failures, ask the CI triggerer to share details
  • Once fixed, request an NVIDIA team member to trigger CI again

CI Agent Failure Analysis

Link to invocation

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants