Skip to content

[Bugfix][Router] loadaware: KV lookup for chat completions, fall back when the lookup fails - #1107

Merged
ruizhang0101 merged 5 commits into
vllm-project:mainfrom
ibrahimnd2000:loadaware-chat-lookup
Oct 6, 2026
Merged

ruizhang0101 merged 5 commits into
vllm-project:mainfrom
ibrahimnd2000:loadaware-chat-lookup

Conversation

@ibrahimnd2000

@ibrahimnd2000 ibrahimnd2000 commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

Problem

  1. Chat requests are never matched. LoadAwareRouter.tokenize_prompt only reads request_json["prompt"]. A /v1/chat/completions request has messages and no prompt, so it is tokenized as an empty string, the LMCache controller lookup matches nothing, and every chat request takes the session/QPS fallback route. KV-cache-aware placement never applies to chat traffic.
  2. A failed lookup fails the request. If the engine's /tokenize returns an error (for example while an engine restarts), response.json()["tokens"] raises KeyError: 'tokens' and the client gets an HTTP 500. A controller lookup error does the same. A lookup is an optimisation, so neither should fail a request that could still be routed.

Fix

  • Chat tokenization via the engine. When the body has messages, tokenize through the engine's /tokenize with messages, add_generation_prompt (default True) and, when present, tools and chat_template_kwargs. The engine applies the model's own chat template, so the token ids match what it prefills and caches. The blocking HTTP call runs in an executor, as the existing remote fallback does.
  • Text-only list content is flattened. [{"type": "text", "text": ...}, ...] is joined into one string with "\n", the same way vLLM's chat_utils renders it before applying the template. vLLM's /tokenize rejects list content on text-only models ("... is not a multimodal model"), and some OpenAI-compatible benchmark clients always send list-style content. Messages containing any non-text part are sent unchanged. The client's request body is not mutated.
  • Clear error. If /tokenize returns a body without tokens, raise an error that includes the status code and body, instead of a bare KeyError.
  • Safe fallback. In route_request, tokenization and the controller lookup are wrapped in try/except. On failure, log a warning and take the existing fallback_url route (session hash, else lowest QPS).

The prompt (completions) path is unchanged.

Tests

New tests in src/tests/test_loadaware_router.py (/tokenize mocked):

  • a chat request is sent to /tokenize with messages, add_generation_prompt, tools and chat_template_kwargs;
  • text-only list content is flattened with "\n", and the request body is not mutated;
  • list content with non-text parts is left unchanged;
  • the completions path still uses the local tokenizer and makes no HTTP call;
  • an error body without tokens raises a clear error;
  • route_request falls back (no exception) when /tokenize fails, and when the controller lookup fails;
  • end to end, a chat request is looked up by its chat-template tokens and routed to the endpoint holding them.
pytest src/tests/test_loadaware_router.py src/tests/test_kvaware_router.py src/tests/test_request_stats.py
51 passed

Seven of the new tests fail on main. pre-commit (black, isort, ruff, codespell) passes.

Validation

In a multi-replica deployment (GLM-5.x, 3–5 vLLM replicas with LMCache) serving chat completions:

  • Before: every chat request fell back to QPS routing.
  • After: requests are placed on the replica holding their prefix, with warm-pass cache hit rates of 94–99% across replicas.
  • The fallback removed HTTP 500s seen while engines restarted.

Note

This PR and "loadaware: score bursts against live load" both add a test section at the same place in test_loadaware_router.py. Whichever lands second needs a trivial rebase; routing_logic.py merges cleanly.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces chat completions tokenization using the engine's /tokenize endpoint and adds fallback routing logic to handle tokenization or lookup failures gracefully. It also includes comprehensive unit tests for these changes. Feedback on the changes suggests adding defensive checks to handle non-list messages in _flatten_text_content and wrapping response.json() in a try-except block to handle non-JSON responses from the remote endpoint.

@ibrahimnd2000 ibrahimnd2000 changed the title [Bugfix][Router] loadaware: KV lookup for chat completions, fall back… [Bugfix][Router] loadaware: KV lookup for chat completions, fall back when the lookup fails Sep 28, 2026

@ruizhang0101 ruizhang0101 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@ruizhang0101
ruizhang0101 enabled auto-merge (squash) September 29, 2026 22:17
… when the lookup fails

LoadAwareRouter.tokenize_prompt only read request_json["prompt"], so every
/v1/chat/completions request was looked up with an empty token list and
loadaware never found a cache match for chat traffic.

- Tokenize chat requests through the engine's /tokenize with "messages"
  (plus add_generation_prompt, tools and chat_template_kwargs), so the token
  ids match what the engine prefills and caches.
- Flatten text-only list content into one string joined with "\n", as
  vLLM's chat_utils does; vLLM's /tokenize rejects list content on text-only
  models ("... is not a multimodal model").
- Raise a clear error when /tokenize returns no "tokens".
- route_request: when tokenization or the controller lookup fails, log a
  warning and take the session/QPS fallback route instead of failing the
  request with an HTTP 500.

Signed-off-by: Muhammad Ibrahim <ibrahimnd2000@gmail.com>
…rate malformed messages

Address review feedback:
- Wrap response.json() so a non-JSON /tokenize reply (e.g. an HTML error
  page from a proxy) raises an error naming the status code and body.
- Return a non-list `messages` unchanged from _flatten_text_content so the
  engine's /tokenize validates it instead of the router raising TypeError.

Both cases already ended in the fallback route; this makes the logged
reason clear and avoids the TypeError. Adds tests for both.

Signed-off-by: Muhammad Ibrahim <ibrahimnd2000@gmail.com>
auto-merge was automatically disabled September 30, 2026 06:25

Head branch was pushed to by a user without write access

@ibrahimnd2000

ibrahimnd2000 commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor Author

Rebased onto main (behind by 1 → 0; the new commit, #1099, only touches helm/). Could a maintainer approve the workflow run?

cc: @ruizhang0101

Note k8s-discovery-e2e-test is currently failing on other PRs too (#1098, #1094, #1104): the test vLLM (opt-125m) pods crash-loop before any router test runs, so every routing test then reports "No models found".

ibrahimnd2000 pushed a commit to ibrahimnd2000/production-stack that referenced this pull request Oct 1, 2026
Move the live request_stats read from the no-cache branch of
route_request into fallback_url, so every fallback scores against the
live load: no cache info, no endpoint selected, and the lookup-failure
fallback added in vllm-project#1107, in either merge order.

Add a cold-burst test (nothing cached anywhere) that fails when the
fallback uses the arrival snapshot: 128/0/0 instead of 43/43/42.

Signed-off-by: Muhammad Ibrahim <muhammad.ibrahim@multiversecomputing.com>
@ibrahimnd2000

Copy link
Copy Markdown
Contributor Author

@ruizhang0101 thanks for the approval! The one red check is k8s-discovery-e2e-test, and it looks unrelated to this change: the opt-125m engine pods never passed their startup probe (connection refused on :8000/health, then back-off), so the router port-forward failed and the job timed out after 20 minutes. Could you re-run it? I can't re-run jobs from a fork. Once it's green this should be ready to merge.

@ruizhang0101
ruizhang0101 enabled auto-merge (squash) October 6, 2026 04:57
@ruizhang0101
ruizhang0101 merged commit 936247c into vllm-project:main Oct 6, 2026
16 checks passed
David-Wu1119 added a commit to David-Wu1119/production-stack that referenced this pull request Oct 6, 2026
Resolve the conflict with vllm-project#1107, which added chat-completion tokenization to
LoadAwareRouter.tokenize_prompt: KvawareRouter keeps the non-blocking prompt
tokenizer from this branch, and LoadAwareRouter handles messages and defers
plain prompts to it with super().

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: David-Wu1119 <133224895+David-Wu1119@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants