fix(api,inference): upstream-payload robustness (F1, F2, F6, F16)#5
Merged
Conversation
Two adjacent hardenings on the API <-> vLLM seam, both surfaced by a
security review:
* `_record_token_usage` previously did `int(usage.get("prompt_tokens",
0) or 0)`. A buggy or hostile vLLM returning `{"usage":
{"prompt_tokens": "abc"}}` raised an unhandled ValueError out of
the success path, becoming a 500 to the client *after* the response
body had already been consumed. New `_safe_token_count` helper
coerces non-numeric / negative / None values to 0 so telemetry can
never crash a successful chat completion.
* `_extract_upstream_message` documented two accepted error-body
shapes ({"error": {"message": ...}} and the bare-string
{"error": "..."}) but only handled the first: the bare-string form
raised AttributeError on `"text".get("message")`, defeating the
documented fallback. Now isinstance-dispatches on `body["error"]`
and returns the same 1024-char-capped, generic-fallback envelope
for every non-conforming shape.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
`VLLMHTTPBackend.stream()` reads the upstream error body via `await response.aread()` and only then calls `await response.aclose()`. If `aread()` raises (network drop, decode error on compressed body, idle timeout) the `aclose()` is skipped and the response keeps its httpx connection attached to the pool until GC. Compounded by the fact that a hostile upstream 5xx-and-drop pattern under streaming load leaks one connection per request — the pool saturates and the gateway starts returning 502s for unrelated traffic that has nothing to do with the upstream's misbehaviour. Wrap each `aread()` in try/finally so `aclose()` always runs. Also pre-initialise `body_bytes = b""` so the JSON-decode fallback below sees an empty bytes object (not UnboundLocalError) when `aread()` itself raised. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Previously `VLLMHTTPBackend.ping()` swallowed every `httpx.HTTPError` silently and returned False. An operator watching `/ready` flap had no signal as to the cause (timeout vs DNS vs TLS vs refused connection) without enabling debug logging on the whole package. Log the exception class + message at WARNING; behaviour (the boolean return) is unchanged so callers stay simple. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Three defensive fixes on the API ↔ vLLM seam, surfaced by a security-review pass and split into atomic commits for review:
fix(api): defensive parsing of upstream chat-completion payload—_record_token_usagenow coerces non-numeric / negative /Noneprompt_tokens&completion_tokensto 0 instead of raisingValueErrorand 500-ing a successful chat completion._extract_upstream_messagenow isinstance-dispatches onbody["error"]so the documented bare-string fallback ({"error": "some text"}) actually works — it previously raisedAttributeErroronstr.get("message").fix(inference): close upstream response on stream() error path— wrapsawait response.aread()intry/finallysoaclose()always runs. Without this, a hostile or buggy upstream that 5xxs and drops the connection mid-read leaks one httpx connection per request; the pool eventually saturates and the gateway starts 502-ing unrelated traffic.fix(inference): log upstream ping failures at WARNING—VLLMHTTPBackend.ping()previously swallowed everyhttpx.HTTPErrorsilently. Operators staring at a flapping/readyhad no signal as to whether it was DNS, TLS, refused, or timeout. Logs the exception class + message; boolean return contract unchanged.Why these are bundled
All three sit on the same code path (chat-completion request → stream proxy → telemetry → response) and share the same underlying property: the upstream is untrusted. Splitting them across PRs would make the review reader chase three branches for one mental model.
Test plan
_safe_token_countdefaults to 0 onNone/ non-numeric / negative — preserves the original "absent ⇒ no metric increment" semantics_extract_upstream_messagereturns the same fallback string for the same shapes; only the buggystr.getpath is fixedvllm_http.stream()try/finallydoes not change happy-path behaviour;aclose()runs in both paths now (was: only whenaread()succeeded)Related
Findings F1, F2, F6, F16 from internal security review punch list.
🤖 Generated with Claude Code