Skip to content

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]

test(e2e): add live batches suite across providers and routing scenarios (#30958)

Sameer Kankutea16d9c6f9ebd
diff --git a/enterprise/litellm_enterprise/proxy/hooks/managed_files.py b/enterprise/litellm_enterprise/proxy/hooks/managed_files.py
index af4870bb1a5..3f42867d90e 100644
--- a/enterprise/litellm_enterprise/proxy/hooks/managed_files.py
+++ b/enterprise/litellm_enterprise/proxy/hooks/managed_files.py
@@ -125,23 +125,33 @@ class _PROXY_LiteLLMManagedFiles(CustomLogger, BaseFileEndpoints):
"team_id": user_api_key_dict.team_id,
"updated_by": user_api_key_dict.user_id,
}
+ update_data = {
+ "model_mappings": json.dumps(model_mappings),
+ "flat_model_file_ids": list(model_mappings.values()),
+ "updated_by": user_api_key_dict.user_id,
+ }
if file_object is not None:
- db_data["file_object"] = file_object.model_dump_json()
+ file_object_json = file_object.model_dump_json()
+ db_data["file_object"] = file_object_json
+ update_data["file_object"] = file_object_json
# Extract storage metadata from hidden params if present
hidden_params = getattr(file_object, "_hidden_params", {}) or {}
if "storage_backend" in hidden_params:
db_data["storage_backend"] = hidden_params["storage_backend"]
+ update_data["storage_backend"] = hidden_params["storage_backend"]
if "storage_url" in hidden_params:
db_data["storage_url"] = hidden_params["storage_url"]
+ update_data["storage_url"] = hidden_params["storage_url"]
verbose_logger.debug(
f"Storage metadata: storage_backend={db_data.get('storage_backend')}, "
f"storage_url={db_data.get('storage_url')}"
)
- result = await self.prisma_client.db.litellm_managedfiletable.create(
- data=db_data
+ result = await self.prisma_client.db.litellm_managedfiletable.upsert(
+ where={"unified_file_id": file_id},
+ data={"create": db_data, "update": update_data},
)
verbose_logger.debug(
f"LiteLLM Managed File object with id={file_id} stored in db: {result}"
diff --git a/litellm/litellm_core_utils/prompt_templates/image_handling.py b/litellm/litellm_core_utils/prompt_templates/image_handling.py
index 7129d6bba81..92a4296c432 100644
--- a/litellm/litellm_core_utils/prompt_templates/image_handling.py
+++ b/litellm/litellm_core_utils/prompt_templates/image_handling.py
@@ -72,6 +72,9 @@ def _process_image_response(response: Response, url: str) -> str:
async def async_convert_url_to_base64(url: str) -> str:
+ if url.startswith("data:") and ";base64," in url:
+ return url
+
# If MAX_IMAGE_URL_DOWNLOAD_SIZE_MB is 0, block all image downloads
if MAX_IMAGE_URL_DOWNLOAD_SIZE_MB == 0:
raise litellm.ImageFetchError(
@@ -95,6 +98,9 @@ async def async_convert_url_to_base64(url: str) -> str:
def convert_url_to_base64(url: str) -> str:
+ if url.startswith("data:") and ";base64," in url:
+ return url
+
# If MAX_IMAGE_URL_DOWNLOAD_SIZE_MB is 0, block all image downloads
if MAX_IMAGE_URL_DOWNLOAD_SIZE_MB == 0:
raise litellm.ImageFetchError(
diff --git a/litellm/llms/vertex_ai/batches/transformation.py b/litellm/llms/vertex_ai/batches/transformation.py
index c75efdb43e8..4cac7212d62 100644
--- a/litellm/llms/vertex_ai/batches/transformation.py
+++ b/litellm/llms/vertex_ai/batches/transformation.py
@@ -47,7 +47,7 @@ class VertexAIBatchTransformation:
) -> LiteLLMBatch:
return LiteLLMBatch(
id=cls._get_batch_id_from_vertex_ai_batch_response(response),
- completion_window="24hrs",
+ completion_window="24h",
created_at=_convert_vertex_datetime_to_openai_datetime(vertex_datetime=response.get("createTime", "")),
endpoint="",
input_file_id=cls._get_input_file_id_from_vertex_ai_batch_response(response),
diff --git a/litellm/proxy/batches_endpoints/endpoints.py b/litellm/proxy/batches_endpoints/endpoints.py
index 02e4d9c170e..fffa0bf86d2 100644
--- a/litellm/proxy/batches_endpoints/endpoints.py
+++ b/litellm/proxy/batches_endpoints/endpoints.py
@@ -625,7 +625,7 @@ async def list_batches(
route_type="alist_batches",
)
- # Try to use managed objects table for listing batches (returns encoded IDs)
+ # Try to use managed objects table for listing batches (returns encoded IDs).
managed_files_obj = proxy_logging_obj.get_proxy_hook("managed_files")
if managed_files_obj is not None and hasattr(managed_files_obj, "list_user_batches"):
verbose_proxy_logger.debug("Using managed objects table for batch listing")
diff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.py
index 9a338712187..04f0414f900 100644
--- a/litellm/proxy/proxy_server.py
+++ b/litellm/proxy/proxy_server.py
@@ -15620,9 +15620,10 @@ app.include_router(search_router)
app.include_router(image_router)
app.include_router(fine_tuning_router)
app.include_router(credential_router)
+app.include_router(batches_router)
+app.include_router(openai_files_router)
app.include_router(llm_passthrough_router)
app.include_router(pass_through_router)
-app.include_router(batches_router)
app.include_router(health_router)
app.include_router(key_management_router)
app.include_router(internal_user_router)
@@ -15637,7 +15638,6 @@ app.include_router(callback_management_endpoints_router)
app.include_router(debugging_endpoints_router)
app.include_router(rust_control_plane_router)
app.include_router(ui_crud_endpoints_router)
-app.include_router(openai_files_router)
app.include_router(team_callback_router)
app.include_router(budget_management_router)
app.include_router(model_management_router)
diff --git a/tests/batches_tests/test_batches_logging_unit_tests.py b/tests/batches_tests/test_batches_logging_unit_tests.py
index a0c94693783..33a0a87dd92 100644
--- a/tests/batches_tests/test_batches_logging_unit_tests.py
+++ b/tests/batches_tests/test_batches_logging_unit_tests.py
@@ -255,6 +255,55 @@ async def test_batch_retrieve_cost_tracking_with_completed_batch_no_explicit_cos
assert mock_batch.usage == expected_usage
+async def test_handle_completed_batch_computes_real_cost_from_output_file(
+ sample_file_content_dict,
+):
+ """Integration: a completed batch's cost and usage are computed from its output
+ file via the real cost-calc chain (only the file download is stubbed). This is
+ the function the retrieve handler invokes on completion; a dropped output line, a
+ wrong token sum, or mispriced model fails this test.
+ """
+ from litellm.batches.batch_utils import _handle_completed_batch
+ from litellm.types.utils import LiteLLMBatch
+
+ batch = LiteLLMBatch(
+ id="batch-real-cost-123",
+ object="batch",
+ endpoint="/v1/chat/completions",
+ input_file_id="file-input-123",
+ completion_window="24h",
+ status="completed",
+ output_file_id="file-output-123",
+ created_at=1234567890,
+ )
+
+ with patch(
+ "litellm.batches.batch_utils._get_batch_output_file_content_as_dictionary",
+ new=AsyncMock(return_value=sample_file_content_dict),
+ ):
+ cost, usage, models = await _handle_completed_batch(
+ batch=batch, custom_llm_provider="openai"
+ )
+
+ pricing = litellm.model_cost["gpt-4o-mini-2024-07-18"]
+ expected_cost = (
+ 42 * pricing["input_cost_per_token_batches"]
+ + 20 * pricing["output_cost_per_token_batches"]
+ )
+
+ assert cost == pytest.approx(expected_cost)
+ assert cost > 0
+ assert (
+ cost
+ < 42 * pricing["input_cost_per_token"] + 20 * pricing["output_cost_per_token"]
+ )
+ assert usage.prompt_tokens == 42
+ assert usage.completion_tokens == 20
+ assert usage.total_tokens == 62
+ assert models == ["gpt-4o-mini-2024-07-18", "gpt-4o-mini-2024-07-18"]
+
+
@pytest.mark.asyncio
async def test_batch_retrieve_cost_tracking_with_explicit_cost_data():
"""
diff --git a/tests/e2e/batches/COVERAGE.md b/tests/e2e/batches/COVERAGE.md
new file mode 100644
index 00000000000..0026d4bb3d5
--- /dev/null
+++ b/tests/e2e/batches/COVERAGE.md
@@ -0,0 +1,79 @@
+# Batches Test Coverage Matrix
+
+Live e2e coverage of the Batches API over a real proxy, real provider keys, and
+real cost. Synchronous tier only: a batch's completion window is 24h, so these
+tests never wait for `completed`. They assert the proxy accepts, routes, retrieves,
+cancels, and lists a batch; everything created is deleted on teardown.
+
+## Provider x operation
+
+Only supported cells are tested. The capability table in `capabilities.py` holds one
+row per supported (provider, scenario) pair, so there are no skipped cells in the
+parametrized run.
+
+| Provider | create | retrieve | cancel | list | file backing |
+|-----------|--------|----------|--------|------|--------------|
+| OpenAI | yes | yes | yes | yes | OpenAI Files |
+| Azure | yes | yes | yes | yes | Azure Files |
+| Vertex AI | yes | yes | yes | yes | GCS bucket |
+| Bedrock | yes | yes | no (limited upstream) | no | S3 bucket |
+| Anthropic | no | yes (env-gated) | no | no | Anthropic Files |
+
+Bedrock cancel is unreliable upstream and list is unsupported, so both are gated off
+(`can_cancel=False`, `can_list=False`). Anthropic cannot create/cancel/list through
+litellm, so it has a standalone retrieve test that skips unless `ANTHROPIC_BATCH_ID`
+points at a real Anthropic batch.
+
+## Routing scenarios (per `litellm/proxy/batches_endpoints/endpoints.py`)
+
+Each create-capable provider runs all four. The test asserts the returned file id
+and batch id carry the shape that scenario must produce (`matches_id_shape`):
+
+| Scenario | How the batch is routed | File id | Batch id |
+|----------|-------------------------|---------|----------|
+| `encoded` | upload with `?model=` -> model-encoded file id -> create with just that id | model-encoded | model-encoded |
+| `unified` | upload with `target_model_names=` -> unified managed file id -> create with that id | managed | managed |
+| `model_param` | raw file (provider-fallback upload) -> create with `model` in the body | raw | model-encoded |
+| `provider_fallback` | raw file -> `POST /{provider}/v1/batches`, env creds, no model | raw | raw (native provider shape) |
+
+"managed" ids base64-decode to a `litellm_proxy` marker; "model-encoded" ids keep the
+provider prefix and base64-encode `litellm:<id>;model,<model>`; "raw" ids are the
+provider's native ids. Asserting these catches a proxy that returns a raw id where it
+should manage it, or vice versa. On top of the id shape, a misroute to the wrong
+provider also fails create (the file id / model do not belong there), and the
+`provider_fallback` raw batch id is additionally checked against the provider's native
+shape (`raw_id_matches_provider`).
+
+## Key model restriction
+
+`test_batch_key_model_access_denied` mints a key restricted to one model
+(`resources.key(models=[...])`) and proves the proxy returns 403
+`key_model_access_denied` both when that key uploads a file for a disallowed model
+(files endpoint) and when it creates a batch for a disallowed model (batches
+endpoint).
+
+## Per-endpoint output assertions
+
+Each endpoint's full response is validated, not just the id. File upload asserts
+`object=="file"`, `purpose=="batch"`, a positive `bytes`, a status, and a created-at.
+Batch create / retrieve assert `object=="batch"`, `endpoint=="/v1/chat/completions"`,
+`completion_window=="24h"`, a non-empty `input_file_id`, and a created-at; retrieve
+additionally cross-checks that `id` and `input_file_id` match the created batch.
+Cancel asserts the same id, `object=="batch"`, and a cancelling/cancelled status. List
+asserts the `object=="list"` envelope and that the created batch is present as a batch.
+File delete asserts `object=="file"` and `deleted==True`.
+
+## This suite's files
+
+| File | Covers |
+|------|--------|
+| `batch_client.py` | typed file upload/download + batch create/retrieve/cancel/list/delete over the shared Gateway; denial helpers |
+| `capabilities.py` | the provider x scenario matrix + id-shape classifiers + per-provider raw-id assertion |
+| `test_batches_e2e.py` | parametrized lifecycle with per-endpoint output assertions, file upload/delete outputs, key-model-access denial, anthropic retrieve |
+
+## Out of scope (intentionally)
+
+Driving a batch to `completed`, cost tracking on completion, and the DB write-back
+are not covered here; the 24h window makes them unfit for a synchronous gate. That
+logic belongs in a DI-stubbed proxy integration test under `tests/test_litellm/proxy/`
+where the provider client is injected to return `completed` deterministically.
diff --git a/tests/e2e/batches/batch_client.py b/tests/e2e/batches/batch_client.py
new file mode 100644
index 00000000000..2a6376bf89e
--- /dev/null
+++ b/tests/e2e/batches/batch_client.py
@@ -0,0 +1,165 @@
+"""Client for the batches e2e suite: file upload/download and the batch
+operations (create / retrieve / cancel / list) over the shared Gateway.
+
+`create_batch` returns the raw HTTP outcome (StreamingResponse) so a 403 model
+access denial and a provider-native batch body both surface; the test parses
+BatchObject from the body. A `provider` arg routes a call to /{provider}/v1/...,
+which the provider-fallback scenario needs (its ids are raw, not model-encoded).
+The request/response models are co-located here because only this suite uses them.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+
+from pydantic import BaseModel
+
+from e2e_gateway import Gateway, build_gateway
+from e2e_http import (
+ FileUploadForm,
+ NoBody,
+ Result,
+ StreamingResponse,
+ UnknownApiError,
+)
+
+
+class FileObject(BaseModel):
+ id: str
+ object: str | None = None
+ purpose: str | None = None
+ bytes: int | None = None
+ status: str | None = None
+ created_at: int | None = None
+
+
+class BatchObject(BaseModel):
+ id: str
+ object: str | None = None
+ status: str
+ endpoint: str | None = None
+ input_file_id: str | None = None
+ output_file_id: str | None = None
+ completion_window: str | None = None
+ created_at: int | None = None
+ model: str | None = None
+
+
+class BatchList(BaseModel):
+ object: str | None = None
+ data: list[BatchObject] = []
+
+
+class FileDeleteResponse(BaseModel):
+ id: str
+ object: str | None = None
+ deleted: bool
+
+
+class BatchCreateBody(BaseModel):
+ input_file_id: str
+ endpoint: str = "/v1/chat/completions"
+ completion_window: str = "24h"
+ model: str | None = None
+
+
+class ModelQuery(BaseModel):
+ model: str | None = None
+
+
+def is_model_access_denied(resp: StreamingResponse) -> bool:
+ """True if the proxy rejected the call because the key may not access the model."""
+ return resp.status_code == 403 and "key_model_access_denied" in resp.body
+
+
+def is_result_access_denied[R: BaseModel](result: Result[R]) -> bool:
+ match result:
+ case UnknownApiError(status_code=403, body=body):
+ return "key_model_access_denied" in body
+ case _:
+ return False
+
+
+@dataclass(frozen=True, slots=True)
+class BatchClient:
+ gateway: Gateway
+
+ def upload_file(
+ self,
+ *,
+ content: bytes,
+ form: FileUploadForm,
+ key: str,
+ model: str | None = None,
+ provider: str | None = None,
+ ) -> Result[FileObject]:
+ return self.gateway.transport.upload(
+ _files_path(provider),
+ headers=self.gateway.transport.bearer(key),
+ form=form,
+ filename="batch_input.jsonl",
+ content=content,
+ params=ModelQuery(model=model),
+ response_type=FileObject,
+ )
+
+ def create_batch(
+ self, *, body: BatchCreateBody, key: str, provider: str | None = None
+ ) -> StreamingResponse:
+ return self.gateway.transport.send(
+ _batches_path(provider),
+ headers=self.gateway.transport.bearer(key),
+ json=body,
+ )
+
+ def retrieve_batch(
+ self, batch_id: str, *, key: str, provider: str | None = None
+ ) -> Result[BatchObject]:
+ return self.gateway.transport.get(
+ f"{_batches_path(provider)}/{batch_id}",
+ headers=self.gateway.transport.bearer(key),
+ params=NoBody(),
+ response_type=BatchObject,
+ )
+
+ def cancel_batch(
+ self, batch_id: str, *, key: str, provider: str | None = None
+ ) -> Result[BatchObject]:
+ return self.gateway.transport.post(
+ f"{_batches_path(provider)}/{batch_id}/cancel",
+ headers=self.gateway.transport.bearer(key),
+ json=NoBody(),
+ response_type=BatchObject,
+ )
+
+ def list_batches(
+ self, *, key: str, provider: str | None = None
+ ) -> Result[BatchList]:
+ return self.gateway.transport.get(
+ _batches_path(provider),
+ headers=self.gateway.transport.bearer(key),
+ params=NoBody(),
+ response_type=BatchList,
+ )
+
+ def delete_file(
+ self, file_id: str, *, key: str, provider: str | None = None
+ ) -> Result[FileDeleteResponse]:
+ return self.gateway.transport.delete(
+ f"{_files_path(provider)}/{file_id}",
+ headers=self.gateway.transport.bearer(key),
+ json=NoBody(),
+ response_type=FileDeleteResponse,
+ )
+
+
+def _files_path(provider: str | None) -> str:
+ return f"/{provider}/v1/files" if provider else "/v1/files"
+
+
+def _batches_path(provider: str | None) -> str:
+ return f"/{provider}/v1/batches" if provider else "/v1/batches"
+
+
+def build_client() -> BatchClient:
+ return BatchClient(gateway=build_gateway())
diff --git a/tests/e2e/batches/capabilities.py b/tests/e2e/batches/capabilities.py
new file mode 100644
index 00000000000..0416508a31a
--- /dev/null
+++ b/tests/e2e/batches/capabilities.py
@@ -0,0 +1,147 @@
+"""The declarative provider x routing-scenario matrix the lifecycle test runs.
+
+One Capability per supported (provider, scenario) pair, so the parametrized test
+has no dead/skipped cells. `provider` is litellm's custom_llm_provider, used to
+route provider-fallback calls to /{provider}/v1/... and to assert the raw batch id
+shape (the only scenario whose id is not re-encoded by the proxy). Operations that
+a provider does not support (Bedrock: no cancel, no list) are gated per row.
+"""
+
+from __future__ import annotations
+
+import base64
+from dataclasses import dataclass
+from typing import Literal
+
+Scenario = Literal["encoded", "unified", "model_param", "provider_fallback"]
+
+IdShape = Literal["managed", "model_encoded", "raw"]
+
+SCENARIOS: tuple[Scenario, ...] = (
+ "encoded",
+ "unified",
+ "model_param",
+ "provider_fallback",
+)
+
+
+@dataclass(frozen=True, slots=True)
+class Provider:
+ name: str
+ model: str
+ raw_model: str
+ can_cancel: bool
+ can_list: bool
+
+
+@dataclass(frozen=True, slots=True)
+class Capability:
+ provider: str
+ model: str
+ raw_model: str
+ scenario: Scenario
+ can_cancel: bool
+ can_list: bool
+
+ @property
+ def id(self) -> str:
+ return f"{self.provider}-{self.scenario}"
+
+ @property
+ def jsonl_model(self) -> str:
+ """Model name embedded in the uploaded JSONL ``body.model``.
+
+ Only the unified upload path rewrites JSONL on upload
+ (``target_model_names`` → ``llm_router.acreate_file`` →
+ ``replace_model_in_jsonl``), so that scenario can use the LiteLLM alias
+ and rely on the proxy to swap it to the deployment model. Every other
+ scenario uploads raw JSONL with no rewrite, so the provider's real
+ deployment name is required or create fails upstream validation."""
+ return self.model if self.scenario == "unified" else self.raw_model
+
+
+PROVIDERS: tuple[Provider, ...] = (
+ Provider("openai", "openai-batch", "gpt-4o-mini", can_cancel=True, can_list=True),
+ Provider("azure", "azure-batch", "gpt-4.1-mini-batch", can_cancel=True, can_list=True),
+ Provider(
+ "vertex_ai", "vertex-batch", "gemini-2.5-flash", can_cancel=True, can_list=True
+ ),
+ # Provider(
+ # "bedrock",
+ # "bedrock-batch",
+ # "us.anthropic.claude-haiku-4-5-20251001-v1:0",
+ # can_cancel=False,
+ # can_list=False,
+ # ),
+)
+
+CAPABILITIES: tuple[Capability, ...] = tuple(
+ Capability(p.name, p.model, p.raw_model, scenario, p.can_cancel, p.can_list)
+ for p in PROVIDERS
+ for scenario in SCENARIOS
+)
+
+
+def raw_id_matches_provider(provider: str, batch_id: str) -> bool:
+ """The provider-fallback path returns the provider's native batch id (unencoded),
+ so its shape discriminates which provider actually handled the batch."""
+ if provider in ("openai", "azure"):
+ return batch_id.startswith("batch")
+ if provider == "vertex_ai":
+ # Vertex returns the batch prediction job id, which depending on the
+ # routing path arrives either as the full resource name
+ # (projects/.../batchPredictionJobs/<id>) or as just the trailing
+ # numeric id, so accept either form.
+ return (
+ batch_id.startswith("projects/")
+ or "batchPredictionJobs" in batch_id
+ or batch_id.isdigit()
+ )
+ if provider == "bedrock":
+ return batch_id.startswith("arn:aws")
+ return True
+
+
+FILE_ID_SHAPE: dict[Scenario, IdShape] = {
+ "encoded": "model_encoded",
+ "unified": "managed",
+ "model_param": "raw",
+ "provider_fallback": "raw",
+}
+
+BATCH_ID_SHAPE: dict[Scenario, IdShape] = {
+ "encoded": "model_encoded",
+ "unified": "managed",
+ "model_param": "model_encoded",
+ "provider_fallback": "raw",
+}
+
+
+def _b64_decode(value: str) -> str:
+ padded = value + "=" * (-len(value) % 4)
+ try:
+ return base64.urlsafe_b64decode(padded).decode()
+ except Exception:
+ return ""
+
+
+def is_managed_id(id_str: str) -> bool:
+ """A litellm managed unified file/batch id base64-decodes to a litellm_proxy marker."""
+ return _b64_decode(id_str).startswith("litellm_proxy")
+
+
+def is_model_encoded_id(id_str: str) -> bool:
+ """A model-encoded id keeps the provider prefix and base64-encodes litellm:<id>;model,<m>."""
+ for prefix in ("file-", "batch_"):
+ if id_str.startswith(prefix):
+ decoded = _b64_decode(id_str[len(prefix) :])
+ return decoded.startswith("litellm:") and ";model," in decoded
+ return False
+
+
+def matches_id_shape(shape: IdShape, id_str: str) -> bool:
+ if shape == "managed":
+ return is_managed_id(id_str)
+ if shape == "model_encoded":
+ return is_model_encoded_id(id_str)
+ return not is_managed_id(id_str) and not is_model_encoded_id(id_str)
diff --git a/tests/e2e/batches/conftest.py b/tests/e2e/batches/conftest.py
new file mode 100644
index 00000000000..92905b33eee
--- /dev/null
+++ b/tests/e2e/batches/conftest.py
@@ -0,0 +1,16 @@
+"""Batches suite's `client` fixture.
+
+The shared lifecycle (resources/scoped_key), proxy liveness skip, and e2e marker
+live in the parent tests/e2e/conftest.py. BatchClient holds the shared Gateway, so
+the `resources` fixture cleans up keys through it; tests register file deletes and
+batch cancels via `resources.defer(...)`.
+"""
+
+import pytest
+
+from batch_client import BatchClient, build_client
+
+
[email protected](scope="session")
+def client() -> BatchClient:
+ return build_client()
diff --git a/tests/e2e/batches/test_batches_e2e.py b/tests/e2e/batches/test_batches_e2e.py
new file mode 100644
index 00000000000..1141e2f6a2f
--- /dev/null
+++ b/tests/e2e/batches/test_batches_e2e.py
@@ -0,0 +1,289 @@
+"""Live e2e for the Batches API across every provider LiteLLM supports.
+
+Synchronous tier only: a batch's completion window is 24h, so these never wait for
+"completed". Each case uploads a tiny JSONL, creates the batch through one of the
+four routing scenarios, asserts it was accepted (non-terminal status) and routed to
+the right provider, then retrieves / cancels / lists where the provider supports it.
+Everything created is deleted on teardown. Completion + cost tracking are out of
+scope here (see COVERAGE.md).
+
+Routing signal: for provider_fallback the raw batch id discriminates the provider;
+for the encoded/unified/model_param scenarios the proxy re-encodes the id, so the
+load-bearing signal is that create SUCCEEDS against that provider's own model - a
+misroute to the wrong provider fails the create.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import time
+from typing import Callable
+
+import pytest
+
+from batch_client import (
+ BatchClient,
+ BatchCreateBody,
+ BatchObject,
+ FileObject,
+ is_model_access_denied,
+ is_result_access_denied,
+)
+from capabilities import (
+ BATCH_ID_SHAPE,
+ CAPABILITIES,
+ FILE_ID_SHAPE,
+ Capability,
+ matches_id_shape,
+ raw_id_matches_provider,
+)
+from e2e_http import (
+ FileUploadForm,
+ Result,
+ StreamingResponse,
+ require_successful_call,
+ unwrap,
+)
+from lifecycle import ResourceManager
+
+pytestmark = pytest.mark.e2e
+
+CREATED_BATCH_STATUSES = {"validating", "in_progress", "finalizing"}
+BATCH_CANCEL_DELAY_SECONDS = 2
+BATCH_TERMINAL_BEFORE_CANCEL = {"failed", "cancelled", "expired"}
+
+
+def render_jsonl(model: str) -> bytes:
+ line = {
+ "custom_id": "req-1",
+ "method": "POST",
+ "url": "/v1/chat/completions",
+ "body": {
+ "model": model,
+ "messages": [{"role": "user", "content": "ping"}],
+ "max_tokens": 8,
+ },
+ }
+ return (json.dumps(line) + "\n").encode()
+
+
+def upload_for_scenario(
+ client: BatchClient, cap: Capability, content: bytes, key: str
+) -> Result[FileObject]:
+ if cap.scenario == "encoded":
+ return client.upload_file(
+ content=content,
+ form=FileUploadForm(purpose="batch"),
+ model=cap.model,
+ key=key,
+ )
+ if cap.scenario == "unified":
+ return client.upload_file(
+ content=content,
+ form=FileUploadForm(purpose="batch", target_model_names=cap.model),
+ key=key,
+ )
+ return client.upload_file(
+ content=content,
+ form=FileUploadForm(purpose="batch"),
+ key=key,
+ provider=cap.provider,
+ )
+
+
+def create_for_scenario(
+ client: BatchClient, cap: Capability, file_id: str, key: str
+) -> StreamingResponse:
+ if cap.scenario == "model_param":
+ return client.create_batch(
+ body=BatchCreateBody(input_file_id=file_id, model=cap.model), key=key
+ )
+ if cap.scenario == "provider_fallback":
+ return client.create_batch(
+ body=BatchCreateBody(input_file_id=file_id), key=key, provider=cap.provider
+ )
+ return client.create_batch(body=BatchCreateBody(input_file_id=file_id), key=key)
+
+
+def op_provider(cap: Capability) -> str | None:
+ """provider_fallback ids are raw, so retrieve/cancel/list/delete need the provider
+ hint; the other scenarios encode it into the id and route automatically."""
+ return cap.provider if cap.scenario == "provider_fallback" else None
+
+
+def quietly(action: Callable[[], object]) -> Callable[[], None]:
+ """Adapt a value-returning call into a best-effort cleanup the teardown can run."""
+
+ def run() -> None:
+ action()
+
+ return run
+
+
+def assert_file_object(file: FileObject) -> None:
+ assert file.object == "file", f"file.object={file.object!r}"
+ assert file.purpose == "batch", f"file.purpose={file.purpose!r}"
+ assert file.bytes is not None and file.bytes > 0, f"file.bytes={file.bytes!r}"
+ assert file.status, "file.status missing"
+ assert (
+ file.created_at is not None and file.created_at > 0
+ ), "file.created_at missing"
+
+
+def assert_batch_object(batch: BatchObject) -> None:
+ assert batch.object == "batch", f"batch.object={batch.object!r}"
+ if batch.endpoint:
+ assert (
+ batch.endpoint == "/v1/chat/completions"
+ ), f"batch.endpoint={batch.endpoint!r}"
+ assert batch.completion_window == "24h", f"window={batch.completion_window!r}"
+ assert batch.input_file_id, "batch.input_file_id missing"
+ assert (
+ batch.created_at is not None and batch.created_at > 0
+ ), "batch.created_at missing"
+
+
[email protected]("cap", CAPABILITIES, ids=[c.id for c in CAPABILITIES])
+def test_batch_lifecycle(
+ cap: Capability, client: BatchClient, resources: ResourceManager
+) -> None:
+ key = resources.key()
+ provider = op_provider(cap)
+
+ file = unwrap(upload_for_scenario(client, cap, render_jsonl(cap.jsonl_model), key))
+ resources.defer(
+ quietly(lambda: client.delete_file(file.id, key=key, provider=provider))
+ )
+ assert_file_object(file)
+ assert matches_id_shape(
+ FILE_ID_SHAPE[cap.scenario], file.id
+ ), f"{cap.id}: file id {file.id!r} is not a {FILE_ID_SHAPE[cap.scenario]} id"
+
+ created = create_for_scenario(client, cap, file.id, key)
+ require_successful_call(created)
+ batch = BatchObject.model_validate_json(created.body)
+ resources.defer(
+ quietly(lambda: client.cancel_batch(batch.id, key=key, provider=provider))
+ )
+
+ assert batch.id, f"create returned no batch id (body={created.body[:200]})"
+ assert (
+ batch.status in CREATED_BATCH_STATUSES
+ ), f"freshly created batch has non-transitional status {batch.status!r}"
+ assert_batch_object(batch)
+ assert matches_id_shape(
+ BATCH_ID_SHAPE[cap.scenario], batch.id
+ ), f"{cap.id}: batch id {batch.id!r} is not a {BATCH_ID_SHAPE[cap.scenario]} id"
+ if cap.scenario == "provider_fallback":
+ assert raw_id_matches_provider(
+ cap.provider, batch.id
+ ), f"{cap.provider} batch id {batch.id!r} not in that provider's native shape; misrouted?"
+
+ fetched = unwrap(client.retrieve_batch(batch.id, key=key, provider=provider))
+ assert_batch_object(fetched)
+ assert fetched.id == batch.id
+ assert (
+ fetched.input_file_id == batch.input_file_id
+ ), "retrieve changed input_file_id"
+ assert fetched.status, "retrieved batch has no status"
+
+ if cap.can_cancel:
+ time.sleep(BATCH_CANCEL_DELAY_SECONDS)
+ pre_cancel = unwrap(client.retrieve_batch(batch.id, key=key, provider=provider))
+ assert (
+ pre_cancel.status not in BATCH_TERMINAL_BEFORE_CANCEL
+ ), (
+ f"batch reached {pre_cancel.status!r} before cancel; "
+ "provider likely rejected the input"
+ )
+ if pre_cancel.status == "completed":
+ return
+ cancelled = unwrap(client.cancel_batch(batch.id, key=key, provider=provider))
+ assert cancelled.id == batch.id
+ assert cancelled.object == "batch"
+ # Vertex cancel is async: the job may still show its pre-cancel status
+ # briefly before transitioning to cancelling/cancelled.
+ valid_post_cancel = {"cancelling", "cancelled"}
+ if cap.provider == "vertex_ai":
+ valid_post_cancel |= CREATED_BATCH_STATUSES
+ assert cancelled.status in valid_post_cancel, (
+ f"unexpected post-cancel status {cancelled.status!r}"
+ )
+
+ if cap.can_list:
+ listed = unwrap(client.list_batches(key=key, provider=provider))
+ # OpenAI includes object="list"; Azure provider list often omits the envelope field.
+ if listed.object is not None:
+ assert listed.object == "list", f"list envelope object={listed.object!r}"
+ match = next((b for b in listed.data if b.id == batch.id), None)
+ assert match is not None, "created batch absent from list"
+ assert match.object == "batch"
+
+
+def test_batch_key_model_access_denied(
+ client: BatchClient, resources: ResourceManager
+) -> None:
+ key = resources.key(models=["openai-batch"])
+
+ denied_upload = client.upload_file(
+ content=render_jsonl("azure-batch"),
+ form=FileUploadForm(purpose="batch"),
+ model="azure-batch",
+ key=key,
+ )
+ assert is_result_access_denied(
+ denied_upload
+ ), f"restricted key uploaded a file for a disallowed model: {denied_upload}"
+
+ raw_file = unwrap(
+ client.upload_file(
+ content=render_jsonl("openai-batch"),
+ form=FileUploadForm(purpose="batch"),
+ key=key,
+ provider="openai",
+ )
+ ).id
+ resources.defer(
+ quietly(lambda: client.delete_file(raw_file, key=key, provider="openai"))
+ )
+
+ denied_create = client.create_batch(
+ body=BatchCreateBody(input_file_id=raw_file, model="azure-batch"), key=key
+ )
+ assert is_model_access_denied(
+ denied_create
+ ), f"restricted key created a batch for a disallowed model (status {denied_create.status_code})"
+
+
+def test_file_upload_and_delete_outputs(
+ client: BatchClient, resources: ResourceManager
+) -> None:
+ key = resources.key()
+ file = unwrap(
+ client.upload_file(
+ content=render_jsonl("openai-batch"),
+ form=FileUploadForm(purpose="batch"),
+ model="openai-batch",
+ key=key,
+ )
+ )
+ assert_file_object(file)
+
+ deleted = unwrap(client.delete_file(file.id, key=key))
+ assert deleted.id, "delete response has no id"
+ assert deleted.object == "file", f"delete object={deleted.object!r}"
+ assert deleted.deleted is True, "file was not reported deleted"
+
+
+def test_anthropic_batch_retrieve(client: BatchClient, scoped_key: str) -> None:
+ batch_id = os.environ.get("ANTHROPIC_BATCH_ID")
+ if not batch_id:
+ pytest.skip(
+ "set ANTHROPIC_BATCH_ID to a real anthropic batch id to exercise retrieve"
+ )
+ fetched = unwrap(
+ client.retrieve_batch(batch_id, key=scoped_key, provider="anthropic")
+ )
+ assert fetched.id == batch_id
+ assert fetched.status
diff --git a/tests/e2e/e2e_http.py b/tests/e2e/e2e_http.py
index 7458f316852..7b8d3045d3b 100644
--- a/tests/e2e/e2e_http.py
+++ b/tests/e2e/e2e_http.py
@@ -36,6 +36,16 @@ class NoBody(BaseModel):
"""Empty body/query for routes that take none."""
+class FileUploadForm(BaseModel):
+ """Multipart form fields for POST /v1/files. The file bytes are passed
+ separately; `model` is not here because the proxy reads it from the query
+ (?model=) not the form."""
+
+ purpose: str = "batch"
+ target_model_names: str | None = None
+ custom_llm_provider: str | None = None
+
+
# ---------- Result types ----------
R = TypeVar("R", bound=BaseModel)
@@ -304,3 +314,50 @@ def stream(
"""Streaming (SSE) call: consumes the stream counting events, and captures the
x-litellm-call-id + content-type headers. Body is elided."""
return send(url, headers=headers, json=json, stream=True, timeout=timeout)
+
+
+def upload[R: BaseModel](
+ url: URL,
+ *,
+ headers: BaseModel,
+ form: FileUploadForm,
+ filename: str,
+ content: bytes,
+ params: BaseModel | None = None,
+ response_type: type[R],
+ timeout: float = 60.0,
+) -> Result[R]:
+ """Multipart POST for file uploads (/v1/files). Form fields come from `form`,
+ the file bytes are sent as the `file` part, and `params` carries any query
+ routing (e.g. ?model=). requests sets the multipart Content-Type itself."""
+ dumped: dict[str, object] = form.model_dump(by_alias=True, exclude_none=True)
+ data = {key: str(value) for key, value in dumped.items()}
+ try:
+ resp = requests.post(
+ str(url),
+ headers=_headers(headers),
+ params=_params(params),
+ data=data,
+ files={"file": (filename, content, "application/jsonl")},
+ timeout=timeout,
+ )
+ except requests.RequestException as exc:
+ return NetworkError(message=str(exc))
+ return _classify(resp, response_type)
+
+
+def download(
+ url: URL, *, headers: BaseModel, timeout: float = 60.0
+) -> StreamingResponse:
+ """Raw GET for file content (/v1/files/{id}/content): provider-native bytes, no
+ schema. Returns the decoded body and the x-litellm-call-id header."""
+ try:
+ resp = requests.get(str(url), headers=_headers(headers), timeout=timeout)
+ except requests.RequestException as exc:
+ return StreamingResponse(status_code=-1, body=str(exc))
+ return StreamingResponse(
+ status_code=resp.status_code,
+ call_id=_hdr(resp, "x-litellm-call-id"),
+ content_type=_hdr(resp, "content-type"),
+ body=resp.text,
+ )
diff --git a/tests/e2e/gateway/litellm-config.yml b/tests/e2e/gateway/litellm-config.yml
index ecc2c044039..3e5237b004b 100644
--- a/tests/e2e/gateway/litellm-config.yml
+++ b/tests/e2e/gateway/litellm-config.yml
@@ -208,6 +208,57 @@ model_list:
vertex_project: os.environ/VERTEXAI_PROJECT
vertex_location: us-central1
+ # batch models exercised by tests/e2e/batches/
+ - model_name: openai-batch
+ litellm_params:
+ model: openai/gpt-4o-mini
+ api_key: os.environ/OPENAI_API_KEY
+ model_info:
+ mode: batch
+
+ - model_name: azure-batch
+ litellm_params:
+ model: azure/gpt-4.1-mini-batch
+ api_base: os.environ/AZURE_API_BASE
+ api_key: os.environ/AZURE_API_KEY
+ api_version: "2024-07-01-preview"
+ model_info:
+ mode: batch
+
+ - model_name: vertex-batch
+ litellm_params:
+ model: vertex_ai/gemini-2.5-flash
+ vertex_project: os.environ/VERTEXAI_PROJECT
+ vertex_location: us-central1
+ vertex_credentials: os.environ/VERTEXAI_CREDENTIALS
+ bucket_name: os.environ/GCS_BUCKET_NAME
+ model_info:
+ mode: batch
+
+ - model_name: bedrock-batch
+ litellm_params:
+ model: bedrock/us.anthropic.claude-haiku-4-5-20251001-v1:0
+ s3_bucket_name: os.environ/AWS_BATCH_S3_BUCKET
+ s3_region_name: us-west-2
+ s3_access_key_id: os.environ/AWS_ACCESS_KEY_ID
+ s3_secret_access_key: os.environ/AWS_SECRET_ACCESS_KEY
+ aws_batch_role_arn: os.environ/AWS_BATCH_ROLE_ARN
+ model_info:
+ mode: batch
+
+files_settings:
+ - custom_llm_provider: openai
+ api_key: os.environ/OPENAI_API_KEY
+ - custom_llm_provider: azure
+ api_base: os.environ/AZURE_API_BASE
+ api_key: os.environ/AZURE_API_KEY
+ api_version: "2024-07-01-preview"
+ - custom_llm_provider: vertex_ai
+ vertex_project: os.environ/VERTEXAI_PROJECT
+ vertex_location: us-central1
+ vertex_credentials: os.environ/VERTEXAI_CREDENTIALS
+ bucket_name: os.environ/GCS_BUCKET_NAME
+
mcp_servers:
deepwiki_mcp:
@@ -234,4 +285,3 @@ guardrails:
CREDIT_CARD: BLOCK
US_SSN: BLOCK
PHONE_NUMBER: BLOCK
-
diff --git a/tests/e2e/lifecycle.py b/tests/e2e/lifecycle.py
index fdf2137584e..b15986987a7 100644
--- a/tests/e2e/lifecycle.py
+++ b/tests/e2e/lifecycle.py
@@ -98,9 +98,12 @@ class ResourceManager:
"""Register a teardown action for any resource the test just created."""
self._cleanups.append(cleanup)
- def key(self) -> str:
- """Create an all-models virtual key; delete it on teardown."""
- key = self.client.generate_key(KeyGenerateBody(models=[]))
+ def key(self, models: list[str] | None = None, user_id: str | None = "e2e-test-user") -> str:
+ """Create a virtual key; delete it on teardown. `models` restricts which
+ models the key may call (None/[] means all). `user_id` is required for
+ managed-batch ACL: the proxy stores created_by=user_id and checks it on
+ retrieve/cancel; None here means the 403 guard fires."""
+ key = self.client.generate_key(KeyGenerateBody(models=models or [], user_id=user_id))
self.defer(lambda: self.client.delete_key(key))
return key
diff --git a/tests/e2e/spend_tracking/SPEND_TRACKING_COVERAGE_MATRIX.md b/tests/e2e/spend_tracking/SPEND_TRACKING_COVERAGE_MATRIX.md
index 53c4d4ace83..77c0fe06bdb 100644
--- a/tests/e2e/spend_tracking/SPEND_TRACKING_COVERAGE_MATRIX.md
+++ b/tests/e2e/spend_tracking/SPEND_TRACKING_COVERAGE_MATRIX.md
@@ -19,7 +19,7 @@ proxy + SpendLogs rows. Status: `covered` / `partial` / `gap`.
|------|----------|-------|--------|----------|
| `_get_status_for_spend_log` | `test_spend_tracking_utils.py` | unit | covered | yes (status read off the row) |
| cache-hit `request_id` suffix | `test_spend_tracking_utils.py` | unit | covered | yes (`test_cache_hit_is_zero_cost_and_suffixed`) |
-| failure status + zero spend | `test_spend_tracking_utils.py` | unit | covered | no (live failure logging is non-deterministic across providers) |
+| failure status + zero spend | `test_spend_tracking_utils.py` | unit | partial | yes (`test_failure_call_writes_failure_status_row`) |
| per-model / per-provider attribution | `test_spend_tracking_utils.py` | unit | covered | yes (`test_each_model_on_a_shared_key_gets_its_own_row`) |
| field population (model/tokens/api_key/team/org) | `test_spend_tracking_utils.py` | unit | partial | yes (asserts real values) |
| `request_tags` propagation | `test_db_spend_update_writer.py` | unit | partial | yes (`test_request_tags_round_trip`) |
@@ -40,9 +40,9 @@ proxy + SpendLogs rows. Status: `covered` / `partial` / `gap`.
| Entity | Existing | Status | Live e2e |
|--------|----------|--------|----------|
| API key | `test_db_spend_update_writer.py`, `test_spend_counters.py` | covered | yes (`test_key_spend_equals_sum_of_logs`) |
-| Tag | `test_update_daily_tag_spend.py` | partial | yes (`test_request_tags_round_trip`, propagation only) |
+| Tag | `test_update_daily_tag_spend.py` | partial | yes (`test_tag_spend_matches_sum_of_tagged_logs`) |
| End-user | `test_proxy_update_spend.py` | covered | yes |
-| Spend == sum(logs) consistency | none | gap | yes (key aggregate == sum of rows) |
+| Spend == sum(logs) consistency | none | gap | yes (key + tag aggregate == sum of rows) |
## Spend read endpoints (verification surface)
@@ -50,7 +50,7 @@ proxy + SpendLogs rows. Status: `covered` / `partial` / `gap`.
|----------|----------|--------|----------|
| `/spend/logs` (request_id / api_key) | `test_spend_management_endpoints.py` | covered | yes (primary read path; `test_spend_logs_endpoint_returns_spend` asserts 200 + spend, never 5xx) |
| `/spend/calculate` | `local_testing/test_spend_calculate_endpoint.py` | covered | yes (`test_spend_calculate_returns_nonzero_cost`) |
-| `/spend/tags` | `test_spend_management_endpoints.py` | partial | yes (`test_spend_routes.py` route probe) |
+| `/spend/tags` | `test_spend_management_endpoints.py` | partial | yes (tag accuracy test) |
| whole spend GET surface (22 routes) | unit per-handler | partial | yes (`test_spend_routes.py` probes each for 404/5xx) |
## What this suite pins
@@ -63,8 +63,10 @@ proxy + SpendLogs rows. Status: `covered` / `partial` / `gap`.
| `test_cache_hit_is_zero_cost_and_suffixed` | cache hits not double-charged; `_cache_hit` suffix |
| `test_key_spend_equals_sum_of_logs` | key aggregate == sum of rows |
| `test_request_tags_round_trip` | tags persist onto the row |
+| `test_tag_spend_matches_sum_of_tagged_logs` | `/spend/tags` SUM/COUNT == tagged rows |
| `test_end_user_spend_attributed_on_row` | `end_user` attributed + costed |
| `test_each_model_on_a_shared_key_gets_its_own_row` | per-model/provider rows, correct model + cost, distinct request_ids matching response id |
+| `test_failure_call_writes_failure_status_row` | failed call -> `status=failure`, `spend=0` |
| `test_spend_calculate_returns_nonzero_cost` | cost-map smoke (no batch wait) |
| `test_spend_logs_endpoint_returns_spend` | `/spend/logs` returns 200 + the key's spend, never a 5xx (intermittent-500 regression) |
| `test_spend_routes.py` (23) | no spend route 404s or 5xxs |
diff --git a/tests/e2e/spend_tracking/spend_e2e_client.py b/tests/e2e/spend_tracking/spend_e2e_client.py
index d749d69f1a4..0ddacce4299 100644
--- a/tests/e2e/spend_tracking/spend_e2e_client.py
+++ b/tests/e2e/spend_tracking/spend_e2e_client.py
@@ -2,8 +2,8 @@
Generic proxy operations (keys, customers, chat/embed, route probing, SpendLogs
polling) come from the shared Gateway, DI'd in (composition, not inheritance).
-This client adds only the spend surface: /spend/calculate, key-spend
-polling, and the route probes the breadth test uses.
+This client adds only the spend surface: /spend/calculate, /spend/tags,
+key-spend polling, and the route probes the breadth test uses.
Re-exports unwrap / is_ok / unique_marker / SpendLogRow so the tests import their
helpers from one place.
@@ -22,6 +22,7 @@ from e2e_http import (
ProbeResult,
Result,
StreamingResponse,
+ Success,
is_ok,
unwrap,
)
@@ -38,6 +39,8 @@ from models import (
SpendCalculateBody,
SpendCalculateResponse,
SpendLogRow,
+ SpendTagsResponse,
+ TagSpend,
)
__all__ = [
@@ -139,6 +142,34 @@ class SpendClient:
)
).cost
+ def spend_by_tags(self) -> list[TagSpend]:
+ result = self.gateway.transport.get(
+ "/spend/tags",
+ headers=self.gateway.transport.master,
+ params=NoBody(),
+ response_type=SpendTagsResponse,
+ )
+ match result:
+ case Success(data=data):
+ return data.spend_per_tag or []
+ case _:
+ return []
+
+ def poll_tag_spend(self, tag: str, *, minimum: float = 0.0) -> TagSpend | None:
+ """Poll /spend/tags until the tag's aggregate reaches `minimum`; last seen."""
+ deadline = time.monotonic() + self.gateway.poll_timeout
+ entry: TagSpend | None = None
+ while time.monotonic() < deadline:
+ matches = [
+ t for t in self.spend_by_tags() if t.individual_request_tag == tag
+ ]
+ if matches:
+ entry = matches[0]
+ if (entry.total_spend or 0.0) >= minimum:
+ return entry
+ time.sleep(self.gateway.poll_interval)
+ return entry
+
def poll_key_spend(self, key: str, *, minimum: float = 0.0) -> float:
deadline = time.monotonic() + self.gateway.poll_timeout
spend = 0.0
diff --git a/tests/e2e/spend_tracking/test_spend_tracking_e2e.py b/tests/e2e/spend_tracking/test_spend_tracking_e2e.py
index 8c9e913b10f..f8ece3c48c1 100644
--- a/tests/e2e/spend_tracking/test_spend_tracking_e2e.py
+++ b/tests/e2e/spend_tracking/test_spend_tracking_e2e.py
@@ -23,7 +23,7 @@ import pytest
from e2e_http import Success
from lifecycle import ResourceManager
from models import SpendLogs, SpendLogsParams
-from spend_e2e_client import SpendClient, SpendLogRow, unique_marker, unwrap
+from spend_e2e_client import SpendClient, SpendLogRow, is_ok, unique_marker, unwrap
pytestmark = pytest.mark.e2e
@@ -218,6 +218,43 @@ def test_request_tags_round_trip(client: SpendClient, scoped_key: str) -> None:
)
+def test_tag_spend_matches_sum_of_tagged_logs(
+ client: SpendClient, scoped_key: str
+) -> None:
+ # Unique tag so /spend/tags can't be polluted by other rows; unique content
+ # per call so both are fresh misses (paid), not cache hits.
+ tag = f"e2e-tagspend-{unique_marker()}"
+ for _ in range(2):
+ _ = unwrap(
+ client.chat(
+ scoped_key,
+ "gemini-2.5-flash",
+ f"hi {unique_marker()}",
+ tags=[tag],
+ max_tokens=16,
+ )
+ )
+
+ rows = client.poll_logs_for_key(
+ scoped_key,
+ min_rows=2,
+ predicate=lambda rs: sum((r.spend or 0) for r in rs) > 0,
+ )
+ tagged = [r for r in rows if tag in (r.request_tags or [])]
+ assert len(tagged) >= 2, f"expected 2 tagged rows, saw {_summarize(rows)}"
+ logs_total = sum((r.spend or 0) for r in tagged)
+ assert logs_total > 0
+
+ entry = client.poll_tag_spend(tag, minimum=logs_total * 0.999)
+ assert entry is not None, f"tag {tag!r} never appeared in /spend/tags"
+ assert _approx_equal(entry.total_spend or 0, logs_total), (
+ f"/spend/tags total_spend {entry} != sum of tagged rows {logs_total}"
+ )
+ assert (entry.log_count or 0) == len(tagged), (
+ f"/spend/tags log_count {entry.log_count} != tagged rows {len(tagged)}"
+ )
+
+
def test_end_user_spend_attributed_on_row(
client: SpendClient, scoped_key: str, resources: ResourceManager
) -> None:
@@ -283,6 +320,25 @@ def test_each_model_on_a_shared_key_gets_its_own_row(
), f"claude row request_id {claude_row.request_id} != response id {claude.id}"
+def test_failure_call_writes_failure_status_row(
+ client: SpendClient, scoped_key: str
+) -> None:
+ result = client.chat(scoped_key, "gemini-2.5-flash", "", max_tokens=1)
+ if is_ok(result):
+ pytest.skip("call unexpectedly succeeded; could not induce a failure row")
+
+ rows = client.poll_logs_for_key(
+ scoped_key, predicate=lambda rs: any(r.status == "failure" for r in rs)
+ )
+ failure_rows = [r for r in rows if r.status == "failure"]
+ if not failure_rows:
+ pytest.skip(
+ "no failure-status row was logged for the rejected call; "
+ "failure logging is environment-specific"
+ )
+ assert (failure_rows[0].spend or 0) == 0.0, "failed call must not be charged"
+
+
def test_spend_calculate_returns_nonzero_cost(client: SpendClient) -> None:
cost = client.calculate_spend(
"gemini-2.5-flash", "estimate the cost of this request"
diff --git a/tests/e2e/transport.py b/tests/e2e/transport.py
index 37412fc0cf5..2e109bdf5d9 100644
--- a/tests/e2e/transport.py
+++ b/tests/e2e/transport.py
@@ -13,7 +13,14 @@ from typing import Protocol
from pydantic import BaseModel
import e2e_http
-from e2e_http import URL, AuthHeaders, ProbeResult, Result, StreamingResponse
+from e2e_http import (
+ URL,
+ AuthHeaders,
+ FileUploadForm,
+ ProbeResult,
+ Result,
+ StreamingResponse,
+)
class Transport(Protocol):
@@ -50,6 +57,20 @@ class Transport(Protocol):
def probe(self, path: str, *, params: BaseModel) -> ProbeResult: ...
+ def upload[R: BaseModel](
+ self,
+ path: str,
+ *,
+ headers: BaseModel,
+ form: FileUploadForm,
+ filename: str,
+ content: bytes,
+ params: BaseModel | None = None,
+ response_type: type[R],
+ ) -> Result[R]: ...
+
+ def download(self, path: str, *, headers: BaseModel) -> StreamingResponse: ...
+
def bearer(self, key: str) -> AuthHeaders: ...
@property
@@ -143,6 +164,33 @@ class HttpTransport:
timeout=self.request_timeout,
)
+ def upload[R: BaseModel](
+ self,
+ path: str,
+ *,
+ headers: BaseModel,
+ form: FileUploadForm,
+ filename: str,
+ content: bytes,
+ params: BaseModel | None = None,
+ response_type: type[R],
+ ) -> Result[R]:
+ return e2e_http.upload(
+ self._url(path),
+ headers=headers,
+ form=form,
+ filename=filename,
+ content=content,
+ params=params,
+ response_type=response_type,
+ timeout=self.request_timeout,
+ )
+
+ def download(self, path: str, *, headers: BaseModel) -> StreamingResponse:
+ return e2e_http.download(
+ self._url(path), headers=headers, timeout=self.request_timeout
+ )
+
# Top-level management/admin route groups. In a split deployment these are served
# by the control plane (a different service from the LLM data plane). LLM routes
@@ -242,3 +290,27 @@ class SplitTransport:
def probe(self, path: str, *, params: BaseModel) -> ProbeResult:
return self._route(path).probe(path, params=params)
+
+ def upload[R: BaseModel](
+ self,
+ path: str,
+ *,
+ headers: BaseModel,
+ form: FileUploadForm,
+ filename: str,
+ content: bytes,
+ params: BaseModel | None = None,
+ response_type: type[R],
+ ) -> Result[R]:
+ return self._route(path).upload(
+ path,
+ headers=headers,
+ form=form,
+ filename=filename,
+ content=content,
+ params=params,
+ response_type=response_type,
+ )
+
+ def download(self, path: str, *, headers: BaseModel) -> StreamingResponse:
+ return self._route(path).download(path, headers=headers)
diff --git a/tests/enterprise/litellm_enterprise/proxy/hooks/test_managed_files.py b/tests/enterprise/litellm_enterprise/proxy/hooks/test_managed_files.py
index 7b82d1eabd9..68dc3269f34 100644
--- a/tests/enterprise/litellm_enterprise/proxy/hooks/test_managed_files.py
+++ b/tests/enterprise/litellm_enterprise/proxy/hooks/test_managed_files.py
@@ -1404,7 +1404,7 @@ async def test_store_unified_file_id_with_none_file_object():
from litellm.proxy._types import UserAPIKeyAuth
prisma_client = AsyncMock()
- prisma_client.db.litellm_managedfiletable.create = AsyncMock(
+ prisma_client.db.litellm_managedfiletable.upsert = AsyncMock(
return_value=MagicMock()
)
internal_usage_cache = MagicMock()
@@ -1424,11 +1424,73 @@ async def test_store_unified_file_id_with_none_file_object():
user_api_key_dict=UserAPIKeyAuth(user_id="test-user"),
)
- # Verify DB create was called with expected data (without file_object)
- prisma_client.db.litellm_managedfiletable.create.assert_called_once()
- call_args = prisma_client.db.litellm_managedfiletable.create.call_args
- assert call_args.kwargs["data"]["unified_file_id"] == "test-unified-file-id"
- assert "file_object" not in call_args.kwargs["data"]
+ # Verify DB upsert was called idempotently with expected create data (without file_object)
+ prisma_client.db.litellm_managedfiletable.upsert.assert_called_once()
+ call_args = prisma_client.db.litellm_managedfiletable.upsert.call_args
+ assert call_args.kwargs["where"] == {"unified_file_id": "test-unified-file-id"}
+ create_data = call_args.kwargs["data"]["create"]
+ assert create_data["unified_file_id"] == "test-unified-file-id"
+ assert "file_object" not in create_data
+
+
+async def test_store_unified_file_id_updates_file_metadata_on_existing_row():
+ from litellm.proxy._types import UserAPIKeyAuth
+ from litellm.types.llms.openai import OpenAIFileObject
+
+ prisma_client = AsyncMock()
+ prisma_client.db.litellm_managedfiletable.upsert = AsyncMock(
+ return_value=MagicMock()
+ )
+ internal_usage_cache = MagicMock()
+ internal_usage_cache.async_set_cache = AsyncMock()
+
+ proxy_managed_files = _PROXY_LiteLLMManagedFiles(
+ internal_usage_cache=internal_usage_cache,
+ prisma_client=prisma_client,
+ )
+ user_api_key_dict = UserAPIKeyAuth(user_id="test-user")
+
+ await proxy_managed_files.store_unified_file_id(
+ file_id="test-unified-file-id",
+ file_object=None,
+ litellm_parent_otel_span=None,
+ model_mappings={"model-123": "file-provider-xyz"},
+ user_api_key_dict=user_api_key_dict,
+ )
+
+ file_object = OpenAIFileObject(
+ id="file-provider-xyz",
+ object="file",
+ bytes=1234,
+ created_at=1234567890,
+ filename="output.jsonl",
+ purpose="batch_output",
+ status="processed",
+ )
+ file_object._hidden_params = {
+ "storage_backend": "s3",
+ "storage_url": "s3://bucket/output.jsonl",
+ }
+
+ await proxy_managed_files.store_unified_file_id(
+ file_id="test-unified-file-id",
+ file_object=file_object,
+ litellm_parent_otel_span=None,
+ model_mappings={"model-123": "file-provider-xyz"},
+ user_api_key_dict=user_api_key_dict,
+ )
+
+ first_update = prisma_client.db.litellm_managedfiletable.upsert.await_args_list[
+ 0
+ ].kwargs["data"]["update"]
+ second_update = prisma_client.db.litellm_managedfiletable.upsert.await_args_list[
+ 1
+ ].kwargs["data"]["update"]
+ assert "file_object" not in first_update
+ assert second_update["file_object"] == file_object.model_dump_json()
+ assert second_update["storage_backend"] == "s3"
+ assert second_update["storage_url"] == "s3://bucket/output.jsonl"
@pytest.mark.asyncio
diff --git a/tests/test_litellm/litellm_core_utils/test_image_handling.py b/tests/test_litellm/litellm_core_utils/test_image_handling.py
index cc13e816dde..893472d63ae 100644
--- a/tests/test_litellm/litellm_core_utils/test_image_handling.py
+++ b/tests/test_litellm/litellm_core_utils/test_image_handling.py
@@ -7,6 +7,7 @@ import litellm
from litellm import constants
from litellm.litellm_core_utils.prompt_templates import image_handling
from litellm.litellm_core_utils.prompt_templates.image_handling import (
+ async_convert_url_to_base64,
convert_url_to_base64,
)
@@ -218,6 +219,41 @@ def test_streaming_download_handles_petabyte_file(monkeypatch):
assert "exceeds maximum allowed size" in str(excinfo.value)
+def test_data_url_is_returned_unchanged_without_fetch(monkeypatch):
+ """
+ A data URL is already inline base64 image data, so convert_url_to_base64
+ must return it as-is instead of attempting an HTTP fetch.
+ """
+
+ class ExplodingClient:
+ def get(self, url, follow_redirects=True):
+ raise AssertionError("data URLs must not trigger an HTTP fetch")
+
+ monkeypatch.setattr(litellm, "module_level_client", ExplodingClient())
+
+ data_url = "data:image/png;base64,iVBORw0KGgo="
+
+ assert convert_url_to_base64(data_url) == data_url
+
+
+async def test_async_data_url_is_returned_unchanged_without_fetch(monkeypatch):
+ """
+ The async path must short-circuit data URLs identically to the sync path,
+ otherwise async OCR flows would attempt an impossible HTTP fetch.
+ """
+
+ class ExplodingAsyncClient:
+ async def get(self, url, follow_redirects=True):
+ raise AssertionError("data URLs must not trigger an HTTP fetch")
+
+ monkeypatch.setattr(litellm, "module_level_aclient", ExplodingAsyncClient())
+
+ data_url = "data:image/png;base64,iVBORw0KGgo="
+
+ assert await async_convert_url_to_base64(data_url) == data_url
+
+
def test_image_size_limit_disabled(monkeypatch):
"""
Test that setting MAX_IMAGE_URL_DOWNLOAD_SIZE_MB to 0 disables all image URL downloads.
diff --git a/tests/test_litellm/llms/vertex_ai/batches/test_transformation.py b/tests/test_litellm/llms/vertex_ai/batches/test_transformation.py
index 37084d43441..71da1d39876 100644
--- a/tests/test_litellm/llms/vertex_ai/batches/test_transformation.py
+++ b/tests/test_litellm/llms/vertex_ai/batches/test_transformation.py
@@ -47,9 +47,7 @@ def test_transform_openai_request_builds_full_vertex_job():
"litellm.llms.vertex_ai.batches.transformation.uuid.uuid4",
return_value="fixed-uuid",
):
- job = T.transform_openai_batch_request_to_vertex_ai_batch_request(
- {"input_file_id": INPUT_FILE}
- )
+ job = T.transform_openai_batch_request_to_vertex_ai_batch_request({"input_file_id": INPUT_FILE})
assert job["displayName"] == "litellm-vertex-batch-fixed-uuid"
assert job["model"] == "publishers/google/models/gemini-1.5-flash-001"
@@ -91,13 +89,11 @@ def test_transform_vertex_response_full_mapping():
assert isinstance(batch, LiteLLMBatch)
assert batch.id == "3814889423749775360"
- assert batch.completion_window == "24hrs"
+ assert batch.completion_window == "24h"
# created_at is parsed via the shared helper (uses local tz); assert the
# transform forwards createTime through that helper rather than a hardcoded
# epoch that would be tz-dependent
- assert batch.created_at == _convert_vertex_datetime_to_openai_datetime(
- "2024-12-04T21:53:12.120184Z"
- )
+ assert batch.created_at == _convert_vertex_datetime_to_openai_datetime("2024-12-04T21:53:12.120184Z")
assert batch.endpoint == ""
assert batch.object == "batch"
assert batch.input_file_id == "gs://bucket/in.jsonl"
@@ -140,10 +136,7 @@ def test_transform_vertex_response_error_file_id_always_none():
],
)
def test_status_mapping_every_entry(vertex_state, expected):
- assert (
- T._get_batch_job_status_from_vertex_ai_batch_response({"state": vertex_state})
- == expected
- )
+ assert T._get_batch_job_status_from_vertex_ai_batch_response({"state": vertex_state}) == expected
def test_status_mapping_defaults_to_unspecified_when_missing():
@@ -163,9 +156,7 @@ def test_status_mapping_unknown_state_raises_keyerror():
def test_get_batch_id_splits_path():
assert (
- T._get_batch_id_from_vertex_ai_batch_response(
- {"name": "projects/p/locations/l/batchPredictionJobs/999"}
- )
+ T._get_batch_id_from_vertex_ai_batch_response({"name": "projects/p/locations/l/batchPredictionJobs/999"})
== "999"
)
@@ -198,18 +189,11 @@ def test_get_input_file_id_missing_input_config():
def test_get_input_file_id_missing_gcs_source():
- assert (
- T._get_input_file_id_from_vertex_ai_batch_response({"inputConfig": {}}) == ""
- )
+ assert T._get_input_file_id_from_vertex_ai_batch_response({"inputConfig": {}}) == ""
def test_get_input_file_id_empty_uris():
- assert (
- T._get_input_file_id_from_vertex_ai_batch_response(
- {"inputConfig": {"gcsSource": {"uris": []}}}
- )
- == ""
- )
+ assert T._get_input_file_id_from_vertex_ai_batch_response({"inputConfig": {"gcsSource": {"uris": []}}}) == ""
# =========================================================================== #
@@ -220,18 +204,14 @@ def test_get_input_file_id_empty_uris():
def test_get_output_file_id_from_output_info():
# outputInfo branch: rstrip trailing slash, append predictions.jsonl
assert (
- T._get_output_file_id_from_vertex_ai_batch_response(
- {"outputInfo": {"gcsOutputDirectory": "gs://bucket/out/"}}
- )
+ T._get_output_file_id_from_vertex_ai_batch_response({"outputInfo": {"gcsOutputDirectory": "gs://bucket/out/"}})
== "gs://bucket/out/predictions.jsonl"
)
def test_get_output_file_id_output_info_no_trailing_slash():
assert (
- T._get_output_file_id_from_vertex_ai_batch_response(
- {"outputInfo": {"gcsOutputDirectory": "gs://bucket/out"}}
- )
+ T._get_output_file_id_from_vertex_ai_batch_response({"outputInfo": {"gcsOutputDirectory": "gs://bucket/out"}})
== "gs://bucket/out/predictions.jsonl"
)
@@ -243,10 +223,7 @@ def test_get_output_file_id_empty_output_info_falls_through_to_output_config():
"outputInfo": {},
"outputConfig": {"gcsDestination": {"outputUriPrefix": "gs://b/cfg"}},
}
- assert (
- T._get_output_file_id_from_vertex_ai_batch_response(resp)
- == "gs://b/cfg/predictions.jsonl"
- )
+ assert T._get_output_file_id_from_vertex_ai_batch_response(resp) == "gs://b/cfg/predictions.jsonl"
def test_get_output_file_id_no_output_info_and_no_output_config():
@@ -255,32 +232,18 @@ def test_get_output_file_id_no_output_info_and_no_output_config():
def test_get_output_file_id_output_config_missing_gcs_destination():
# outputConfig present but no gcsDestination -> returns the running "" value
- assert (
- T._get_output_file_id_from_vertex_ai_batch_response({"outputConfig": {}}) == ""
- )
+ assert T._get_output_file_id_from_vertex_ai_batch_response({"outputConfig": {}}) == ""
def test_get_output_file_id_output_config_already_has_suffix():
# outputUriPrefix already ends in /predictions.jsonl -> returned as-is (no double append)
- resp = {
- "outputConfig": {
- "gcsDestination": {"outputUriPrefix": "gs://b/cfg/predictions.jsonl"}
- }
- }
- assert (
- T._get_output_file_id_from_vertex_ai_batch_response(resp)
- == "gs://b/cfg/predictions.jsonl"
- )
+ resp = {"outputConfig": {"gcsDestination": {"outputUriPrefix": "gs://b/cfg/predictions.jsonl"}}}
+ assert T._get_output_file_id_from_vertex_ai_batch_response(resp) == "gs://b/cfg/predictions.jsonl"
def test_get_output_file_id_output_config_strips_trailing_slash():
- resp = {
- "outputConfig": {"gcsDestination": {"outputUriPrefix": "gs://b/cfg/"}}
- }
- assert (
- T._get_output_file_id_from_vertex_ai_batch_response(resp)
- == "gs://b/cfg/predictions.jsonl"
- )
+ resp = {"outputConfig": {"gcsDestination": {"outputUriPrefix": "gs://b/cfg/"}}}
+ assert T._get_output_file_id_from_vertex_ai_batch_response(resp) == "gs://b/cfg/predictions.jsonl"
def test_get_output_file_id_output_info_takes_precedence_over_output_config():
@@ -288,10 +251,7 @@ def test_get_output_file_id_output_info_takes_precedence_over_output_config():
"outputInfo": {"gcsOutputDirectory": "gs://from-info"},
"outputConfig": {"gcsDestination": {"outputUriPrefix": "gs://from-config"}},
}
- assert (
- T._get_output_file_id_from_vertex_ai_batch_response(resp)
- == "gs://from-info/predictions.jsonl"
- )
+ assert T._get_output_file_id_from_vertex_ai_batch_response(resp) == "gs://from-info/predictions.jsonl"
# =========================================================================== #
@@ -301,16 +261,13 @@ def test_get_output_file_id_output_info_takes_precedence_over_output_config():
def test_get_gcs_uri_prefix_root():
assert (
- T._get_gcs_uri_prefix_from_file("gs://litellm-testing-bucket/vtx_batch.jsonl")
- == "gs://litellm-testing-bucket"
+ T._get_gcs_uri_prefix_from_file("gs://litellm-testing-bucket/vtx_batch.jsonl") == "gs://litellm-testing-bucket"
)
def test_get_gcs_uri_prefix_nested():
assert (
- T._get_gcs_uri_prefix_from_file(
- "gs://litellm-testing-bucket/batches/vtx_batch.jsonl"
- )
+ T._get_gcs_uri_prefix_from_file("gs://litellm-testing-bucket/batches/vtx_batch.jsonl")
== "gs://litellm-testing-bucket/batches"
)
@@ -321,21 +278,13 @@ def test_get_gcs_uri_prefix_nested():
def test_get_model_from_gcs_file_plain():
- assert (
- T._get_model_from_gcs_file(INPUT_FILE)
- == "publishers/google/models/gemini-1.5-flash-001"
- )
+ assert T._get_model_from_gcs_file(INPUT_FILE) == "publishers/google/models/gemini-1.5-flash-001"
def test_get_model_from_gcs_file_url_encoded():
# %2F decodes to "/" via urllib.unquote before splitting
- encoded = (
- "gs://bucket/publishers%2Fgoogle%2Fmodels%2Fgemini-1.5-flash-001%2Fuuid"
- )
- assert (
- T._get_model_from_gcs_file(encoded)
- == "publishers/google/models/gemini-1.5-flash-001"
- )
+ encoded = "gs://bucket/publishers%2Fgoogle%2Fmodels%2Fgemini-1.5-flash-001%2Fuuid"
+ assert T._get_model_from_gcs_file(encoded) == "publishers/google/models/gemini-1.5-flash-001"
def test_get_model_from_gcs_file_no_publishers_raises():
@@ -389,8 +338,6 @@ def test_list_response_empty():
def test_list_response_none_jobs_treated_as_empty():
- out = T.transform_vertex_ai_batch_list_response_to_openai_list_response(
- {"batchPredictionJobs": None}
- )
+ out = T.transform_vertex_ai_batch_list_response_to_openai_list_response({"batchPredictionJobs": None})
assert out["data"] == []
assert out["first_id"] is None
diff --git a/tests/test_litellm/proxy/pass_through_endpoints/test_vertex_ai_batch_passthrough.py b/tests/test_litellm/proxy/pass_through_endpoints/test_vertex_ai_batch_passthrough.py
index 044827e287a..5de682ec8a0 100644
--- a/tests/test_litellm/proxy/pass_through_endpoints/test_vertex_ai_batch_passthrough.py
+++ b/tests/test_litellm/proxy/pass_through_endpoints/test_vertex_ai_batch_passthrough.py
@@ -84,7 +84,7 @@ class TestVertexAIBatchPassthroughHandler:
"input_file_id": "file-123",
"output_file_id": "file-456",
"error_file_id": None,
- "completion_window": "24hrs",
+ "completion_window": "24h",
}
mock_transformation._get_batch_id_from_vertex_ai_batch_response.return_value = (
"123456789"
@@ -451,7 +451,7 @@ class TestVertexAIBatchPassthroughHandler:
"input_file_id": "file-123",
"output_file_id": "file-456",
"error_file_id": None,
- "completion_window": "24hrs",
+ "completion_window": "24h",
}
mock_transformation._get_batch_id_from_vertex_ai_batch_response.return_value = (
"123456789"