Open-source inference server and production cluster for all the models your agent needs.
Python bgecolbertdata-pipelinedeep-learningembeddingsinferenceinference-serverinformation-retrievalllmmlmlopsnatural-language-processingnlppythonrerankingretrievalretrieval-augmented-generationsemantic-searchspladevector-search
fix(gateway): keep X-SIE-RateLimit headers in the Messages error envelope (#1019)
Krisztian Gajdar04f8ff1dcc72
diff --git a/packages/sie_gateway/docs/architecture-guide.md b/packages/sie_gateway/docs/architecture-guide.mdindex d01c2d3b2..0f6e9b0a5 100644--- a/packages/sie_gateway/docs/architecture-guide.md+++ b/packages/sie_gateway/docs/architecture-guide.md@@ -46,7 +46,7 @@ Key terms used throughout this document:- `POST /v1/score/{*model}`- `POST /v1/extract/{*model}`- `POST /v1/embeddings` — OpenAI-compatible JSON surface; the gateway accepts **string** or **list of strings** for `input`, supports `encoding_format=float` (default) or `base64`, translates to an internal **`POST /v1/encode/{model}`** with `items[].text` and `params.output_types=["dense"]`, then maps encode `items[].dense` vectors into OpenAI `data[].embedding` plus a rough `usage` estimate. Token-id / nested-array inputs are rejected with **`400`**. `dimensions` is accepted only when it equals the model's native dense width and otherwise rejected with **`400 unsupported_field`**, the same rule as the single-node server. The wrapper must buffer the whole encode reply before reshaping it, and that reply is an *amplification* of the request (N short texts in, N × `dim` floats out), so the buffer is bounded by its own **response**-specific cap, `MAX_COMPAT_RESPONSE_BODY` (16 MiB) — deliberately a separate constant from the request cap it used to be derived from, since the two quantities are unrelated and a change to ingress must not silently move this bound. The value holds today's effective bound rather than raising it: at the queue's item ceiling a float reply reaches ~90 MB at 1024 dims and ~224 MB at 2560 dims (`Qwen/Qwen3-Embedding-4B`, served here), the handler holds ~4 copies at once, and the deployed gateway is a 1 GiB container running 4 requests concurrently — so no bound both admits the largest real reply and fits. **Consequence, stated plainly: a batch above roughly 760 inputs at 1024 dims cannot be served on this surface.** The cure is an ingress item cap (terminal `400` before any GPU work), streaming assembly, or a larger container — each its own change. Over the cap the surface answers a **terminal `413`** naming the one remedy that works (fewer inputs — `encoding_format=base64` is inert here, because the field is never forwarded to `/v1/encode` and base64 is applied afterwards to the outer response), never a retryable `503`. Both that `413` and the unreadable-body `500` carry `GatewayOwnedFault`: the worker has already run and reported its units, so a metered composition must release the hold rather than bill for a response carrying zero embeddings.- - `POST /v1/messages` — Anthropic Messages compatibility surface (`handlers::messages`). The handler validates the body in Anthropic terms, translates it into a `/v1/chat/completions` body, awaits `proxy_chat` in process on the same task, and translates the answer back: a chat completion into a Message, chat SSE chunks into Messages events, and every error into the Anthropic envelope `{"type":"error","error":{"type","message"},"request_id"}` with the status the chat route chose. Every chat gate, profile limit, timeout, serving disclosure and metering point therefore applies unchanged. Unknown fields fail with `400 <field>: Extra inputs are not permitted`; `metadata`, every `cache_control`, `thinking.display: "summarized"`, tool `eager_input_streaming` and the `anthropic-beta` header are accepted and have no effect, and `metadata` is never logged or forwarded. `thinking` `enabled` or `adaptive` sets the chat request's `include_reasoning`, and reasoning comes back as `thinking` blocks with an opaque signature. `output_config.effort` sets the chat request's `reasoning_effort`, and a model that does not accept the value answers `400 output_config.effort: Extra inputs are not permitted`, the wording clients that drop the field recover from. Usage reports `prompt_tokens - cached_tokens` as `input_tokens` and the cached part as `cache_read_input_tokens`, so the two add up to the chat route's prompt tokens. A stream sends `message_start` with zero usage when the chat stream opens, the authoritative usage on `message_delta`, a `ping` whenever nothing was sent for 10 seconds, and a mid-stream failure as an `error` event without `message_stop`. Dropping the response body drops the chat body, so a client disconnect cancels the generation as on chat. The Anthropic error envelope is also an outer middleware, `anthropic_error_envelope`, applied to `/v1/messages` and every path below it, so auth refusals, unknown sub-paths such as `/v1/messages/count_tokens` (not served) and the method check take the same shape; a composition that adds admission layers applies it outermost. `messages_dispatch_inputs` composes the translation with `chat_completions_dispatch_inputs` for estimates and admission checks. Shared vectors under `conformance/anthropic_messages/` pin the request translation, the buffered answer, the event sequence, the error mapping, and the tool-calling and image-input refusals both chat routes give before any engine runs.+ - `POST /v1/messages` — Anthropic Messages compatibility surface (`handlers::messages`). The handler validates the body in Anthropic terms, translates it into a `/v1/chat/completions` body, awaits `proxy_chat` in process on the same task, and translates the answer back: a chat completion into a Message, chat SSE chunks into Messages events, and every error into the Anthropic envelope `{"type":"error","error":{"type","message"},"request_id"}` with the status the chat route chose. Every chat gate, profile limit, timeout, serving disclosure and metering point therefore applies unchanged. Unknown fields fail with `400 <field>: Extra inputs are not permitted`; `metadata`, every `cache_control`, `thinking.display: "summarized"`, tool `eager_input_streaming` and the `anthropic-beta` header are accepted and have no effect, and `metadata` is never logged or forwarded. `thinking` `enabled` or `adaptive` sets the chat request's `include_reasoning`, and reasoning comes back as `thinking` blocks with an opaque signature. `output_config.effort` sets the chat request's `reasoning_effort`, and a model that does not accept the value answers `400 output_config.effort: Extra inputs are not permitted`, the wording clients that drop the field recover from. Usage reports `prompt_tokens - cached_tokens` as `input_tokens` and the cached part as `cache_read_input_tokens`, so the two add up to the chat route's prompt tokens. A stream sends `message_start` with zero usage when the chat stream opens, the authoritative usage on `message_delta`, a `ping` whenever nothing was sent for 10 seconds, and a mid-stream failure as an `error` event without `message_stop`. Dropping the response body drops the chat body, so a client disconnect cancels the generation as on chat. The Anthropic error envelope is also an outer middleware, `anthropic_error_envelope`, applied to `/v1/messages` and every path below it, so auth refusals, unknown sub-paths such as `/v1/messages/count_tokens` (not served) and the method check take the same shape; a composition that adds admission layers applies it outermost, and the envelope keeps the `X-SIE-RateLimit-RPS`, `X-SIE-RateLimit-Concurrency`, `X-SIE-RateLimit-Scope` and `X-SIE-RateLimit-Dimension` headers such a layer sets on a `429`. `messages_dispatch_inputs` composes the translation with `chat_completions_dispatch_inputs` for estimates and admission checks. Shared vectors under `conformance/anthropic_messages/` pin the request translation, the buffered answer, the event sequence, the error mapping, and the tool-calling and image-input refusals both chat routes give before any engine runs.- `POST /v1/responses` — OpenAI Responses compatibility surface (`handlers::responses`), built the same way as `/v1/messages`: the handler validates the body in Responses terms, translates it into a `/v1/chat/completions` body, awaits `proxy_chat` in process on the same task, and translates the answer back: a chat completion into a Response, chat SSE chunks into Responses events, and a chat error into the same OpenAI error envelope, keeping its status, `Retry-After` and `X-SIE-Error-Code` and renaming `error.param` to the Responses field (`tools[i].function.name` to `tools[i].name`, `max_completion_tokens` to `max_output_tokens`, `reasoning_effort` to `reasoning.effort`, `response_format` to `text.format`). Every chat gate, profile limit, timeout, serving disclosure and metering point therefore applies unchanged. `instructions` and the leading `system` and `developer` messages form one system message; `function_call` and `custom_tool_call` items join the adjacent assistant text in one chat assistant message, their outputs become `tool` messages, and `reasoning` items are dropped. Function tools pass through; a custom tool becomes a function with one string `input`, and calls to it come back as `custom_tool_call` items. `text.format` becomes `response_format` and `reasoning.effort` becomes `reasoning_effort`; reasoning is not returned. Responses are not stored: `store: true`, `previous_response_id`, `conversation` and `background: true` are refused with `400 unsupported_field`, as are hosted tools and item types, and the `/v1/responses/{id}` routes are not served. Unknown fields fail with `400 <field>: Extra inputs are not permitted`. A stream sends `response.created` and `response.in_progress` when the chat stream opens, then item, content-part, text and argument events, each with a `sequence_number`, then `response.completed` or `response.incomplete` with the full Response; a mid-stream failure is `response.failed` and ends the stream. The chat route's SSE comment heartbeats pass through until the terminal event, and dropping the response body drops the chat body. `handlers::proxy::responses_dispatch_inputs` composes the translation with `chat_completions_dispatch_inputs` for estimates and admission checks. Shared vectors under `conformance/openai_responses/` pin the request translation, the buffered answer, the event sequence and the error mapping.2. Gateway resolves the request to a model, a bundle, a machine profile, a logical API pool, and the backing queue pool using its in-memory registry.3. Gateway ordinarily publishes work to JetStream on the backing queue subject `sie.work.{pool}.{machine_profile}.{bundle}.{model}` and carries the logical pool as `admission_pool` in the work item. A capped logical batch pool instead targets one assigned worker on `sie.work.{pool}.{machine_profile}.{bundle}.{model}.{worker_id}`.diff --git a/packages/sie_gateway/src/handlers/messages/error.rs b/packages/sie_gateway/src/handlers/messages/error.rsindex 86b076ec1..b4e9c8294 100644--- a/packages/sie_gateway/src/handlers/messages/error.rs+++ b/packages/sie_gateway/src/handlers/messages/error.rs@@ -326,6 +326,10 @@ pub(crate) async fn anthropic_error_response(|| name_str.eq_ignore_ascii_case("x-sie-error-version")|| name_str.eq_ignore_ascii_case("retry-after")|| name_str.eq_ignore_ascii_case("www-authenticate")+ || name_str.eq_ignore_ascii_case("x-sie-ratelimit-rps")+ || name_str.eq_ignore_ascii_case("x-sie-ratelimit-concurrency")+ || name_str.eq_ignore_ascii_case("x-sie-ratelimit-scope")+ || name_str.eq_ignore_ascii_case("x-sie-ratelimit-dimension"){headers.append(name.clone(), value.clone());}diff --git a/packages/sie_gateway/src/handlers/messages/tests.rs b/packages/sie_gateway/src/handlers/messages/tests.rsindex 026497fa9..6fb47938f 100644--- a/packages/sie_gateway/src/handlers/messages/tests.rs+++ b/packages/sie_gateway/src/handlers/messages/tests.rs@@ -5,7 +5,10 @@ use std::time::Duration;use axum::body::{to_bytes, Body};use axum::extract::{Request, State};use axum::http::{HeaderName, HeaderValue, Method, StatusCode};-use axum::response::Response;+use axum::middleware::{from_fn, Next};+use axum::response::{IntoResponse, Response};+use axum::routing::post;+use axum::Router;use bytes::Bytes;use futures_util::StreamExt;use serde_json::{json, Value};@@ -412,6 +415,60 @@ async fn an_inner_error_keeps_its_response_extensions() {);}+#[tokio::test]+async fn an_outer_rate_limit_refusal_keeps_its_rate_limit_headers() {+ async fn rate_limited(_request: Request, _next: Next) -> Response {+ let mut response = (+ StatusCode::TOO_MANY_REQUESTS,+ axum::Json(json!({+ "error": {"message": "rate limit exceeded", "type": "rate_limit_error"}+ })),+ )+ .into_response();+ for (name, value) in [+ ("retry-after", "1"),+ ("x-sie-ratelimit-rps", "10"),+ ("x-sie-ratelimit-concurrency", "4"),+ ("x-sie-ratelimit-scope", "key"),+ ("x-sie-ratelimit-dimension", "rps"),+ ("x-unlisted", "dropped"),+ ] {+ response+ .headers_mut()+ .insert(name, HeaderValue::from_static(value));+ }+ response+ }+ let router = Router::new()+ .route("/v1/messages", post(|| async { StatusCode::OK }))+ .layer(from_fn(rate_limited))+ .layer(from_fn(super::anthropic_error_envelope));++ let response = router+ .oneshot(messages_request(+ json!({"model": "acme/chat", "max_tokens": 16, "messages": []}),+ ))+ .await+ .unwrap();++ assert_eq!(response.status(), StatusCode::TOO_MANY_REQUESTS);+ for (name, value) in [+ ("retry-after", "1"),+ ("x-should-retry", "true"),+ ("x-sie-ratelimit-rps", "10"),+ ("x-sie-ratelimit-concurrency", "4"),+ ("x-sie-ratelimit-scope", "key"),+ ("x-sie-ratelimit-dimension", "rps"),+ ] {+ assert_eq!(response.headers()[name], value, "{name}");+ }+ assert!(response.headers().get("x-unlisted").is_none());+ let body = json_body(response).await;+ assert_eq!(body["type"], "error");+ assert_eq!(body["error"]["type"], "rate_limit_error");+ assert_eq!(body["error"]["message"], "rate limit exceeded");+}+#[derive(Clone, Copy)]enum Step {Role,