Skip to content

armgit / sie

Public Imported from GitHub
0

Open-source inference server and production cluster for all the models your agent needs.

fix(server): bound native encode, score and extract request bodies (#271)

Krisztian Gajdar8479f1c8beff
diff --git a/packages/sie_server/openapi.json b/packages/sie_server/openapi.json
index e9e8ddbad..6df18a1eb 100644
--- a/packages/sie_server/openapi.json
+++ b/packages/sie_server/openapi.json
@@ -135,6 +135,9 @@
"404": {
"description": "Model not found"
},
+ "413": {
+ "description": "Request body exceeds the configured size limit"
+ },
"502": {
"description": "Terminal model-load failure (MODEL_LOAD_FAILED). Carried in the ``detail`` envelope: ``{code, message, error_class, permanent, attempts}``. No ``Retry-After`` header \u2014 clients MUST NOT auto-retry."
},
@@ -238,6 +241,9 @@
"404": {
"description": "Model not found"
},
+ "413": {
+ "description": "Request body exceeds the configured size limit"
+ },
"502": {
"description": "Terminal model-load failure (MODEL_LOAD_FAILED). Carried in the ``detail`` envelope: ``{code, message, error_class, permanent, attempts}``. No ``Retry-After`` header \u2014 clients MUST NOT auto-retry."
},
@@ -448,6 +454,9 @@
"404": {
"description": "Model not found"
},
+ "413": {
+ "description": "Request body exceeds the configured size limit"
+ },
"502": {
"description": "Terminal model-load failure (MODEL_LOAD_FAILED). Carried in the ``detail`` envelope: ``{code, message, error_class, permanent, attempts}``. No ``Retry-After`` header \u2014 clients MUST NOT auto-retry."
},
diff --git a/packages/sie_server/src/sie_server/api/encode.py b/packages/sie_server/src/sie_server/api/encode.py
index b49cc15a1..186c8b495 100644
--- a/packages/sie_server/src/sie_server/api/encode.py
+++ b/packages/sie_server/src/sie_server/api/encode.py
@@ -198,6 +198,7 @@ def _build_response_items(
},
400: {"description": "Invalid request"},
404: {"description": "Model not found"},
+ 413: {"description": "Request body exceeds the configured size limit"},
502: {
"description": (
"Terminal model-load failure (MODEL_LOAD_FAILED). "
diff --git a/packages/sie_server/src/sie_server/api/extract.py b/packages/sie_server/src/sie_server/api/extract.py
index bfc6ee35d..46d6eeaa4 100644
--- a/packages/sie_server/src/sie_server/api/extract.py
+++ b/packages/sie_server/src/sie_server/api/extract.py
@@ -266,6 +266,7 @@ def _build_response(
},
400: {"description": "Invalid request"},
404: {"description": "Model not found"},
+ 413: {"description": "Request body exceeds the configured size limit"},
502: {
"description": (
"Terminal model-load failure (MODEL_LOAD_FAILED). "
diff --git a/packages/sie_server/src/sie_server/api/generate.py b/packages/sie_server/src/sie_server/api/generate.py
index 60bcc7a61..ac0ae3fda 100644
--- a/packages/sie_server/src/sie_server/api/generate.py
+++ b/packages/sie_server/src/sie_server/api/generate.py
@@ -78,7 +78,7 @@ from sie_server.adapters._generation_base import (
suppress_thinking_blocks,
thinking_blocks_must_be_hidden,
)
-from sie_server.api.helpers import ModelStateChecker, oom_retry_after_from_registry
+from sie_server.api.helpers import ModelStateChecker, oom_retry_after_from_registry, read_bounded_request_body
from sie_server.api.validation import validate_machine_profile_header, validate_signed_i64
from sie_server.core.runtime_options import apply_generation_runtime_options
from sie_server.core.tokenizer import image_first_chat_message, load_tokenizer
@@ -665,25 +665,6 @@ def _payload_too_large(message: str, *, param: str | None = None) -> HTTPExcepti
return HTTPException(status_code=status.HTTP_413_CONTENT_TOO_LARGE, detail=detail)
-async def _read_bounded_request_body(request: Request, limit: int) -> bytes:
- """Read an ASGI request without aggregating more than ``limit`` bytes."""
- content_length = request.headers.get("content-length")
- if content_length is not None:
- try:
- declared_length = int(content_length)
- except ValueError:
- declared_length = -1
- if declared_length > limit:
- raise _payload_too_large(f"request body exceeds the limit of {limit} bytes")
-
- body = bytearray()
- async for chunk in request.stream():
- if len(chunk) > limit - len(body):
- raise _payload_too_large(f"request body exceeds the limit of {limit} bytes")
- body.extend(chunk)
- return bytes(body)
-
-
def _generation_http_exception(error: GenerationError, registry: ModelRegistry | None = None) -> HTTPException:
"""Map an expected adapter refusal without rewriting it as a 500."""
if isinstance(
@@ -1058,7 +1039,7 @@ async def generate(
if x_machine_profile:
span.set_attribute("machine_profile", x_machine_profile)
- raw_body = await _read_bounded_request_body(http_request, _MAX_GENERATE_BODY_BYTES)
+ raw_body = await read_bounded_request_body(http_request, _MAX_GENERATE_BODY_BYTES)
try:
body = json.loads(raw_body)
except (json.JSONDecodeError, ValueError) as exc:
diff --git a/packages/sie_server/src/sie_server/api/helpers.py b/packages/sie_server/src/sie_server/api/helpers.py
index 2d83abc19..4c781fe7e 100644
--- a/packages/sie_server/src/sie_server/api/helpers.py
+++ b/packages/sie_server/src/sie_server/api/helpers.py
@@ -1,5 +1,6 @@
import logging
import math
+import os
import time
from importlib.metadata import PackageNotFoundError
from importlib.metadata import version as pkg_version
@@ -38,6 +39,27 @@ _OOM_DEFAULT_RETRY_AFTER_S = 5
# MODEL_LOADING/OOM values.
_QUEUE_FULL_RETRY_AFTER_S = 1
+# Ceiling on a native encode/score/extract request body. Defaults to the
+# largest native ingress ceiling the OSS gateway enforces (34 MiB, its extract
+# body bound), so a server behind that gateway never refuses a body the
+# gateway already admitted, while a server exposed directly cannot be made
+# to buffer an unbounded body before admission runs.
+_DEFAULT_MAX_REQUEST_BODY_BYTES = 34 * 1024 * 1024
+
+
+def _request_body_limit_from_env() -> int:
+ raw = os.environ.get("SIE_MAX_REQUEST_BODY_BYTES")
+ if raw is None:
+ return _DEFAULT_MAX_REQUEST_BODY_BYTES
+ limit = int(raw)
+ if limit < 0:
+ msg = "SIE_MAX_REQUEST_BODY_BYTES must be non-negative"
+ raise ValueError(msg)
+ return limit
+
+
+MAX_REQUEST_BODY_BYTES = _request_body_limit_from_env()
+
# Retry-After (seconds) for a request that was still queued when its model
# was evicted (``WorkerDrainedError``). Matches the ``MODEL_LOADING``
# Retry-After the state checks above already emit: the client's next attempt
@@ -152,6 +174,38 @@ class ContentNegotiator:
return MSGPACK_CONTENT_TYPE in content_type_lower or "application/x-msgpack" in content_type_lower
+def payload_too_large(message: str) -> HTTPException:
+ """413 with the server's standard error detail."""
+ return HTTPException(
+ status_code=status.HTTP_413_CONTENT_TOO_LARGE,
+ detail={"code": ErrorCode.INPUT_TOO_LONG.value, "message": message},
+ )
+
+
+async def read_bounded_request_body(request: Request, limit: int) -> bytes:
+ """Read an ASGI request without aggregating more than ``limit`` bytes.
+
+ A declared ``Content-Length`` above the limit is refused before the first
+ byte is read; a chunked or misdeclared body is refused the moment the
+ aggregate would cross it.
+ """
+ content_length = request.headers.get("content-length")
+ if content_length is not None:
+ try:
+ declared_length = int(content_length)
+ except ValueError:
+ declared_length = -1
+ if declared_length > limit:
+ raise payload_too_large(f"request body exceeds the limit of {limit} bytes")
+
+ body = bytearray()
+ async for chunk in request.stream():
+ if len(chunk) > limit - len(body):
+ raise payload_too_large(f"request body exceeds the limit of {limit} bytes")
+ body.extend(chunk)
+ return bytes(body)
+
+
class RequestParser:
"""Parses and validates HTTP request bodies via msgspec."""
@@ -174,7 +228,7 @@ class RequestParser:
"""
check_sdk_version(http_request)
content_type = http_request.headers.get("content-type")
- body = await http_request.body()
+ body = await read_bounded_request_body(http_request, MAX_REQUEST_BODY_BYTES)
try:
if ContentNegotiator.is_msgpack_request(content_type):
diff --git a/packages/sie_server/src/sie_server/api/score.py b/packages/sie_server/src/sie_server/api/score.py
index cb412e73a..d8812698c 100644
--- a/packages/sie_server/src/sie_server/api/score.py
+++ b/packages/sie_server/src/sie_server/api/score.py
@@ -143,6 +143,7 @@ async def _score_via_worker(
},
400: {"description": "Invalid request"},
404: {"description": "Model not found"},
+ 413: {"description": "Request body exceeds the configured size limit"},
502: {
"description": (
"Terminal model-load failure (MODEL_LOAD_FAILED). "
diff --git a/packages/sie_server/tests/api/test_request_body_limit.py b/packages/sie_server/tests/api/test_request_body_limit.py
new file mode 100644
index 000000000..aff681b3c
--- /dev/null
+++ b/packages/sie_server/tests/api/test_request_body_limit.py
@@ -0,0 +1,115 @@
+"""Native encode/score/extract bodies are bounded before they are buffered.
+
+Fixture mirrors ``test_error_code_hygiene.py``: a mocked registry on the
+direct adapter path, with an adapter that raises a distinctive error so a
+body that was read and parsed is observable as that error's status.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Iterator
+from unittest.mock import MagicMock
+
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+from sie_server.api import helpers
+from sie_server.api.encode import router as encode_router
+from sie_server.config.model import EmbeddingDim, EncodeTask, ModelConfig, ProfileConfig, Tasks
+from sie_server.core.registry import ModelRegistry
+from sie_server.core.worker import QueueFullError
+
+JSON_HEADERS = {"Accept": "application/json", "Content-Type": "application/json"}
+
+
+def _client() -> tuple[TestClient, MagicMock]:
+ adapter = MagicMock()
+ adapter.encode = MagicMock(side_effect=QueueFullError("queue occupied"))
+ config = ModelConfig(
+ sie_id="test-model",
+ hf_id="org/test",
+ tasks=Tasks(encode=EncodeTask(dense=EmbeddingDim(dim=3))),
+ profiles={"default": ProfileConfig(adapter_path="test:TestAdapter", max_batch_tokens=8192)},
+ )
+ registry = MagicMock(spec=ModelRegistry)
+ registry.has_model.return_value = True
+ registry.is_loaded.return_value = True
+ registry.is_loading.return_value = False
+ registry.is_unloading.return_value = False
+ registry.is_failed.return_value = False
+ registry.get_failure.return_value = None
+ registry.get.return_value = adapter
+ registry.get_config.return_value = config
+ registry.model_names = [config.sie_id]
+ registry.device = "cpu"
+ registry.engine_config = None
+ preprocessor_registry = MagicMock()
+ preprocessor_registry.has_tokenizer.return_value = False
+ preprocessor_registry.has_preprocessor.return_value = False
+ registry.preprocessor_registry = preprocessor_registry
+
+ app = FastAPI()
+ app.include_router(encode_router)
+ app.state.registry = registry
+ return TestClient(app), adapter
+
+
+def _body(n_items: int) -> bytes:
+ items = ",".join(f'{{"text": "item {i} padded out a little"}}' for i in range(n_items))
+ return f'{{"items": [{items}]}}'.encode()
+
+
+def small_limit(monkeypatch: pytest.MonkeyPatch) -> int:
+ limit = 256
+ monkeypatch.setattr(helpers, "MAX_REQUEST_BODY_BYTES", limit)
+ return limit
+
+
+def test_declared_oversized_body_is_refused_before_reading(small_limit: int) -> None:
+ client, adapter = _client()
+ body = _body(64)
+ assert len(body) > small_limit
+ resp = client.post("/v1/encode/test-model", content=body, headers=JSON_HEADERS)
+ assert resp.status_code == 413
+ assert resp.json()["detail"]["code"] == "INPUT_TOO_LONG"
+ adapter.encode.assert_not_called()
+
+
+def test_chunked_body_is_refused_at_the_limit(small_limit: int) -> None:
+ """No Content-Length: the bound has to hold on the stream itself."""
+ client, adapter = _client()
+ body = _body(64)
+
+ def chunks() -> Iterator[bytes]:
+ for start in range(0, len(body), 100):
+ yield body[start : start + 100]
+
+ resp = client.post("/v1/encode/test-model", content=chunks(), headers=JSON_HEADERS)
+ assert resp.status_code == 413
+ assert resp.json()["detail"]["code"] == "INPUT_TOO_LONG"
+ adapter.encode.assert_not_called()
+
+
+def test_body_within_the_limit_reaches_the_handler(small_limit: int) -> None:
+ client, adapter = _client()
+ body = _body(2)
+ assert len(body) <= small_limit
+ resp = client.post("/v1/encode/test-model", content=body, headers=JSON_HEADERS)
+ # The adapter's QueueFullError is the proof the body was read and parsed.
+ assert resp.status_code == 503
+ assert resp.json()["detail"]["code"] == "QUEUE_FULL"
+ adapter.encode.assert_called_once()
+
+
+def test_default_limit_matches_the_gateway_native_ceiling(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.delenv("SIE_MAX_REQUEST_BODY_BYTES", raising=False)
+ assert helpers.MAX_REQUEST_BODY_BYTES == 34 * 1024 * 1024
+
+
+def test_negative_limit_is_rejected_at_startup(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("SIE_MAX_REQUEST_BODY_BYTES", "-1")
+ with pytest.raises(ValueError, match="non-negative"):
+ helpers._request_body_limit_from_env()
+ monkeypatch.setenv("SIE_MAX_REQUEST_BODY_BYTES", "0")
+ assert helpers._request_body_limit_from_env() == 0