The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
test(e2e): make dynamic model provisioning robust on split deployments (#32670)
mubashir1osmani97d09512969f
diff --git a/tests/e2e/e2e_gateway.py b/tests/e2e/e2e_gateway.pyindex 055d06d1c79..d62c9c4b17b 100644--- a/tests/e2e/e2e_gateway.py+++ b/tests/e2e/e2e_gateway.py@@ -42,6 +42,7 @@ from models import (ModelMode,ModelNewBody,ModelNewResponse,+ ModelsListResponse,OcrBody,OcrResponse,SpendLogRow,@@ -125,21 +126,59 @@ class Gateway:litellm_params: LiteLLMParamsBody,mode: ModelMode | None = None,) -> str:- """Register a deployment under `model_name` (id == model_name) and return the- model_id. add_deployment runs synchronously in /model/new, so the model is- callable as soon as this returns."""- return unwrap(+ """Register a deployment under `model_name` and return its proxy-assigned+ model_id, once the model is actually servable on the data plane.++ /model/new is a control-plane route; in a split control/data-plane+ deployment the gateway (data plane, which serves /chat, /ocr, ...) only+ picks the new model up on its next DB reload, so a call issued the instant+ this returns can race the reload and 400 with "Invalid model name passed".+ We therefore poll the data-plane /v1/models until the model appears before+ handing back, so callers can invoke it immediately. In the monolithic case+ it is already present on the first poll, so this adds one request."""+ model_id = unwrap(self.transport.post("/model/new",headers=self.transport.master,json=ModelNewBody(model_name=model_name,litellm_params=litellm_params,- model_info=ModelInfoBody(id=model_name, mode=mode),+ model_info=ModelInfoBody(mode=mode),),response_type=ModelNewResponse,)).model_id+ self._await_model_servable(model_name)+ return model_id++ def _await_model_servable(self, model_name: str) -> None:+ """Block until the data plane lists `model_name`, or fail loudly if it does+ not within poll_timeout (a real propagation/config problem, surfaced here+ instead of as a downstream "Invalid model name passed")."""+ deadline = time.monotonic() + self.poll_timeout+ last_result: Result[ModelsListResponse] | None = None+ while time.monotonic() < deadline:+ last_result = self.transport.get(+ "/v1/models",+ headers=self.transport.master,+ params=NoBody(),+ response_type=ModelsListResponse,+ )+ if isinstance(last_result, Success) and any(+ entry.id == model_name for entry in last_result.data.data+ ):+ return+ time.sleep(self.poll_interval)+ last_error = (+ f"; last /v1/models poll did not succeed: {last_result}"+ if last_result is not None and not isinstance(last_result, Success)+ else ""+ )+ raise AssertionError(+ f"model {model_name!r} was created but never became servable on the data "+ f"plane within {self.poll_timeout}s of /model/new (control/data-plane "+ f"propagation or STORE_MODEL_IN_DB reload issue){last_error}"+ )def delete_model(self, model_id: str) -> None:result = self.transport.post(diff --git a/tests/e2e/models.py b/tests/e2e/models.pyindex 0490db286ea..f287058b313 100644--- a/tests/e2e/models.py+++ b/tests/e2e/models.py@@ -394,7 +394,11 @@ ModelMode = Literal["batch", "realtime", "image_generation"]class ModelInfoBody(BaseModel):- id: str+ # id is left unset so the proxy assigns a unique model_id per deployment.+ # Pinning it to the model_name made re-registrations of a fixed-name model+ # (e.g. the batch suite's openai-batch) collide on the model_id unique+ # constraint when a prior run's teardown had not removed the row.+ id: str | None = Nonemode: ModelMode | None = None@@ -410,6 +414,18 @@ class ModelNewResponse(BaseModel):model_id: str+class ModelListEntry(BaseModel):+ id: str+++class ModelsListResponse(BaseModel):+ """GET /v1/models on the data plane: the deployments the gateway can actually+ serve right now. Used to confirm a freshly created model has propagated from+ the control plane before a test calls it."""++ data: tuple[ModelListEntry, ...] = ()++class ModelDeleteBody(BaseModel):id: strdiff --git a/tests/e2e/test_e2e_gateway.py b/tests/e2e/test_e2e_gateway.pyindex a6dcc6112d6..9a9aa2fd2cc 100644--- a/tests/e2e/test_e2e_gateway.py+++ b/tests/e2e/test_e2e_gateway.py@@ -10,6 +10,7 @@ signature drift fails here instead of in a live stage run.from dataclasses import dataclass, field+import pytestfrom pydantic import BaseModelfrom batches.batch_client import BatchClient@@ -21,26 +22,38 @@ from e2e_http import (Result,StreamingResponse,Success,+ UnknownApiError,)from models import (LiteLLMParamsBody,ModelDeleteBody,ModelNewBody,ModelNewResponse,+ ModelsListResponse,)@dataclassclass _RecordingTransport:"""Typed fake fulfilling the Transport protocol; records every post and- answers with a canned success so the test asserts on what was sent."""+ answers with a canned success so the test asserts on what was sent.++ `get("/v1/models")` reports a created model as servable only after+ `servable_after_gets` polls, so a test can drive the data-plane wait in+ create_model."""posts: list[tuple[str, BaseModel]] = field(default_factory=list)+ servable_after_gets: int = 0+ models_error: UnknownApiError | None = None+ model_gets: int = 0+ _created: list[str] = field(default_factory=list)def post[R: BaseModel](self, path: str, *, headers: BaseModel, json: BaseModel, response_type: type[R]) -> Result[R]:self.posts.append((path, json))+ if path == "/model/new" and isinstance(json, ModelNewBody):+ self._created.append(json.model_name)payload = ({"model_id": "registered-id"} if response_type is ModelNewResponse else {})@@ -70,7 +83,15 @@ class _RecordingTransport:params: BaseModel,response_type: type[R],) -> Result[R]:- raise AssertionError("get is not part of model management")+ if path == "/v1/models" and response_type is ModelsListResponse:+ self.model_gets += 1+ if self.models_error is not None:+ return self.models_error+ visible = self._created if self.model_gets > self.servable_after_gets else []+ return Success(+ data=response_type.model_validate({"data": [{"id": name} for name in visible]})+ )+ raise AssertionError(f"unexpected get: {path}")def delete[R: BaseModel](self, path: str, *, headers: BaseModel, json: BaseModel, response_type: type[R]@@ -106,7 +127,7 @@ class _RecordingTransport:def test_gateway_create_model_registers_deployment_and_returns_model_id() -> None:transport = _RecordingTransport()- gateway = Gateway(transport=transport)+ gateway = Gateway(transport=transport, poll_interval=0.0)model_id = gateway.create_model("e2e-test-model", LiteLLMParamsBody(model="openai/gpt-4o-mini")@@ -117,13 +138,48 @@ def test_gateway_create_model_registers_deployment_and_returns_model_id() -> Nonassert path == "/model/new"assert isinstance(body, ModelNewBody)assert body.model_name == "e2e-test-model"- assert body.model_info.id == "e2e-test-model"+ # No pinned model_id: the proxy assigns a unique one, so a fixed-name model+ # re-registered after a failed teardown can't collide on the id constraint.+ assert body.model_info.id is Noneassert body.model_info.mode is None+ # It confirmed data-plane visibility before returning.+ assert transport.model_gets >= 1+++def test_gateway_create_model_waits_until_servable_on_the_data_plane() -> None:+ # The model shows up on /v1/models only on the third poll (simulating the+ # gateway's delayed DB reload in a split deployment); create_model must keep+ # polling instead of returning after /model/new.+ transport = _RecordingTransport(servable_after_gets=2)+ gateway = Gateway(transport=transport, poll_interval=0.0)++ gateway.create_model("e2e-late-model", LiteLLMParamsBody(model="openai/gpt-4o-mini"))++ assert transport.model_gets == 3+++def test_gateway_create_model_fails_loudly_when_never_servable() -> None:+ transport = _RecordingTransport(servable_after_gets=10**9)+ gateway = Gateway(transport=transport, poll_timeout=0.05, poll_interval=0.0)++ with pytest.raises(AssertionError, match="never became servable"):+ gateway.create_model("e2e-ghost-model", LiteLLMParamsBody(model="openai/gpt-4o-mini"))+++def test_gateway_create_model_surfaces_the_last_data_plane_error() -> None:+ transport = _RecordingTransport(+ models_error=UnknownApiError(status_code=503, body="data plane down")+ )+ gateway = Gateway(transport=transport, poll_timeout=0.05, poll_interval=0.0)++ with pytest.raises(AssertionError, match="data plane down") as excinfo:+ gateway.create_model("e2e-flaky-model", LiteLLMParamsBody(model="openai/gpt-4o-mini"))+ assert "503" in str(excinfo.value)def test_batch_client_create_model_registers_a_batch_mode_deployment() -> None:transport = _RecordingTransport()- client = BatchClient(gateway=Gateway(transport=transport))+ client = BatchClient(gateway=Gateway(transport=transport, poll_interval=0.0))model_id = client.create_model("e2e-batch-model", LiteLLMParamsBody(model="openai/gpt-4o-mini")