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
fix(files): never hand the sdk an empty page while matches remain
mateo-berri6b63623ca0bb
diff --git a/enterprise/litellm_enterprise/proxy/hooks/managed_files.py b/enterprise/litellm_enterprise/proxy/hooks/managed_files.pyindex 78d6674863c..be37f648397 100644--- a/enterprise/litellm_enterprise/proxy/hooks/managed_files.py+++ b/enterprise/litellm_enterprise/proxy/hooks/managed_files.py@@ -1384,11 +1384,13 @@ class _PROXY_LiteLLMManagedFiles(CustomLogger, BaseFileEndpoints):Pagination is keyset based on ``unified_file_id`` so a key that ownsevery file on the proxy still reads one bounded page at a time.- ``purpose`` is applied after parsing because the managed file table- keeps it inside the ``file_object`` blob instead of a column, so a- narrowed page can hold fewer files than ``limit``. ``last_id`` then- falls back to the last row the page read, which keeps the cursor- usable even when every file on the page was filtered out.+ ``purpose`` is applied after parsing, because the managed file table+ keeps it inside the ``file_object`` blob instead of a column, and rows+ whose blob will not parse drop out there too, so a chunk of rows can+ yield fewer matches than the page holds. Successive chunks are read+ until the page is full or the caller's rows run out, which keeps+ ``data`` non-empty while matches remain and its last id usable as the+ next cursor."""validate_file_list_limit(limit)@@ -1410,28 +1412,29 @@ class _PROXY_LiteLLMManagedFiles(CustomLogger, BaseFileEndpoints):)page_size: Final = min(limit or MAX_FILE_LIST_LIMIT, MAX_FILE_LIST_LIMIT)- cursor_args: _CursorPageArgs = {"cursor": {"unified_file_id": after}, "skip": 1} if after else {}-- rows: Final = await _managed_file_table(self.prisma_client).find_many(- where=owner_filter,- take=page_size + 1,- order=[{"created_at": "desc"}, {"unified_file_id": "desc"}],- **cursor_args,- )- has_more: Final = len(rows) > page_size- page_rows: Final = rows[:page_size]+ chunk_size: Final = page_size + 1+ matches: Final[List[OpenAIFileObject]] = []+ cursor_id = after++ while len(matches) <= page_size:+ cursor_args: _CursorPageArgs = {"cursor": {"unified_file_id": cursor_id}, "skip": 1} if cursor_id else {}+ chunk = await _managed_file_table(self.prisma_client).find_many(+ where=owner_filter,+ take=chunk_size,+ order=[{"created_at": "desc"}, {"unified_file_id": "desc"}],+ **cursor_args,+ )+ matches.extend(+ parsed_file_object.model_copy(update={"id": row.unified_file_id})+ for row in chunk+ if (parsed_file_object := _parse_managed_file_object(row.file_object, row.unified_file_id)) is not None+ and (purpose is None or parsed_file_object.purpose == purpose)+ )+ if len(chunk) < chunk_size:+ break+ cursor_id = chunk[-1].unified_file_id- files: Final = [- parsed_file_object.model_copy(update={"id": row.unified_file_id})- for row in page_rows- if (parsed_file_object := _parse_managed_file_object(row.file_object, row.unified_file_id)) is not None- and (purpose is None or parsed_file_object.purpose == purpose)- ]- return build_list_page(- files,- has_more=has_more,- next_cursor_id=page_rows[-1].unified_file_id if page_rows else None,- )+ return build_list_page(matches[:page_size], has_more=len(matches) > page_size)def _is_batch_polling_enabled(self) -> bool:"""diff --git a/litellm/llms/base_llm/managed_resources/isolation.py b/litellm/llms/base_llm/managed_resources/isolation.pyindex f1a54943de0..e1b204214d7 100644--- a/litellm/llms/base_llm/managed_resources/isolation.py+++ b/litellm/llms/base_llm/managed_resources/isolation.py@@ -19,23 +19,15 @@ from litellm.proxy._types import ()-def build_list_page(- items: list[Any],- has_more: bool = False,- next_cursor_id: str | None = None,-) -> dict[str, Any]:+def build_list_page(items: list[Any], has_more: bool = False) -> dict[str, Any]:"""Build the OpenAI-style paginated list response shape used by managedfile/batch/vector-store listings. ``first_id`` and ``last_id`` are- sourced from each item's ``.id`` attribute.-- A listing that filters rows out after reading them can pass- ``next_cursor_id`` so an empty page still carries the cursor the caller- needs to reach the rows behind it."""+ sourced from each item's ``.id`` attribute."""return {"object": "list","data": items,"first_id": items[0].id if items else None,- "last_id": items[-1].id if items else next_cursor_id,+ "last_id": items[-1].id if items else None,"has_more": has_more,}diff --git a/litellm/proxy/openai_files_endpoints/files_endpoints.py b/litellm/proxy/openai_files_endpoints/files_endpoints.pyindex 6b460d0239b..c9c794d94e3 100644--- a/litellm/proxy/openai_files_endpoints/files_endpoints.py+++ b/litellm/proxy/openai_files_endpoints/files_endpoints.py@@ -65,6 +65,7 @@ from litellm.proxy.openai_files_endpoints.common_utils import (get_credentials_for_model,handle_model_based_routing,prepare_data_with_credentials,+ validate_file_list_limit,validate_managed_files_requirement,validate_managed_id_requirement,)@@ -1436,6 +1437,8 @@ async def list_files(data: dict = {}try:+ validate_file_list_limit(limit)+# Include original request and headers in the database_llm_response_processor: Final = ProxyBaseLLMRequestProcessing(data=data)(diff --git a/tests/test_litellm/enterprise/proxy/test_managed_files_hook.py b/tests/test_litellm/enterprise/proxy/test_managed_files_hook.pyindex 091e287a96c..40abcac1008 100644--- a/tests/test_litellm/enterprise/proxy/test_managed_files_hook.py+++ b/tests/test_litellm/enterprise/proxy/test_managed_files_hook.py@@ -81,6 +81,14 @@ def _make_managed_file_row()+def _make_unparseable_managed_file_row(+ unified_file_id: str,+ created_by: str = "test-user",+) -> MagicMock:+ """A row whose stored blob cannot be parsed back into a file object."""+ return MagicMock(unified_file_id=unified_file_id, file_object=None, created_by=created_by)++class _FakeManagedFileTable:"""In-memory stand-in for the managed file table, newest row first."""@@ -334,13 +342,37 @@ async def test_afile_list_filters_by_purpose():assert [file.id for file in response["data"]] == ["unified-batch"]+async def _walk_afile_list(managed_files, user_api_key_dict, purpose, limit):+ """Page through the listing the way the official SDK does, off ``data[-1].id``."""+ seen = []+ after = None+ while True:+ page = await managed_files.afile_list(+ purpose=purpose,+ litellm_parent_otel_span=None,+ user_api_key_dict=user_api_key_dict,+ limit=limit,+ after=after,+ )+ page_ids = [file.id for file in page["data"]]+ assert not set(page_ids) & set(seen)+ seen.extend(page_ids)+ if not page["has_more"]:+ return seen+ assert page_ids, "an SDK stops paging on an empty page, so has_more must never ride one"+ after = page_ids[-1]++@pytest.mark.asyncio-async def test_afile_list_keeps_a_usable_cursor_when_a_page_filters_everything_out():+async def test_afile_list_fills_a_page_past_rows_the_purpose_filter_drops():+ """The newest rows do not match, so the page must reach past them rather than come back empty."""managed_files, _ = _make_managed_files_over_rows([_make_managed_file_row("unified-0"),_make_managed_file_row("unified-1"),_make_managed_file_row("unified-2", purpose="batch"),+ _make_managed_file_row("unified-3"),+ _make_managed_file_row("unified-4", purpose="batch"),])user_api_key_dict = _make_user_api_key_dict()@@ -349,25 +381,85 @@ async def test_afile_list_keeps_a_usable_cursor_when_a_page_filters_everything_opurpose="batch",litellm_parent_otel_span=None,user_api_key_dict=user_api_key_dict,- limit=2,+ limit=1,)- assert first_page["data"] == []+ assert [file.id for file in first_page["data"]] == ["unified-2"]assert first_page["has_more"] is True- assert first_page["last_id"] == "unified-1"+ assert first_page["last_id"] == "unified-2"second_page = await managed_files.afile_list(purpose="batch",litellm_parent_otel_span=None,user_api_key_dict=user_api_key_dict,- limit=2,+ limit=1,after=first_page["last_id"],)- assert [file.id for file in second_page["data"]] == ["unified-2"]+ assert [file.id for file in second_page["data"]] == ["unified-4"]assert second_page["has_more"] is False[email protected]("limit", [1, 2, 3])+async def test_afile_list_walks_every_purpose_match_at_any_limit(limit):+ managed_files, _ = _make_managed_files_over_rows(+ [+ _make_managed_file_row("unified-0"),+ _make_managed_file_row("unified-1"),+ _make_managed_file_row("unified-2", purpose="batch"),+ _make_managed_file_row("unified-3"),+ _make_managed_file_row("unified-4", purpose="batch"),+ _make_managed_file_row("unified-5", purpose="batch"),+ _make_managed_file_row("unified-6"),+ ]+ )++ seen = await _walk_afile_list(managed_files, _make_user_api_key_dict(), "batch", limit)++ assert seen == ["unified-2", "unified-4", "unified-5"]+++async def test_afile_list_fills_a_page_past_rows_that_do_not_parse():+ managed_files, _ = _make_managed_files_over_rows(+ [+ _make_unparseable_managed_file_row("unified-0"),+ _make_unparseable_managed_file_row("unified-1"),+ _make_managed_file_row("unified-2"),+ ]+ )++ page = await managed_files.afile_list(+ purpose=None,+ litellm_parent_otel_span=None,+ user_api_key_dict=_make_user_api_key_dict(),+ limit=1,+ )++ assert [file.id for file in page["data"]] == ["unified-2"]+ assert page["has_more"] is False+++async def test_afile_list_reports_no_more_pages_when_nothing_matches():+ managed_files, _ = _make_managed_files_over_rows(+ [_make_managed_file_row(f"unified-{index}") for index in range(5)]+ )++ page = await managed_files.afile_list(+ purpose="batch",+ litellm_parent_otel_span=None,+ user_api_key_dict=_make_user_api_key_dict(),+ limit=2,+ )++ assert page["data"] == []+ assert page["has_more"] is False+ assert page["first_id"] is None+ assert page["last_id"] is None++@pytest.mark.asyncioasync def test_afile_list_honors_limit_and_reports_more_pages():managed_files, table = _make_managed_files_over_rows(diff --git a/tests/test_litellm/proxy/openai_files_endpoint/test_files_endpoint.py b/tests/test_litellm/proxy/openai_files_endpoint/test_files_endpoint.pyindex 08df05cdc8b..5bc77f1bd7a 100644--- a/tests/test_litellm/proxy/openai_files_endpoint/test_files_endpoint.py+++ b/tests/test_litellm/proxy/openai_files_endpoint/test_files_endpoint.py@@ -1,7 +1,7 @@import jsonimport osimport sys-from typing import List+from typing import Final, Listfrom unittest.mock import ANY, AsyncMockimport pytest@@ -2617,27 +2617,39 @@ def _setup_unscoped_list_files_route(mocker, monkeypatch, llm_router: Router, afreturn managed_files-def _get_unscoped_list_files(query: str):+def _get_list_files(path: str):try:- return client.get(f"/v1/files{query}", headers={"Authorization": "Bearer test-key"})+ return client.get(path, headers={"Authorization": "Bearer test-key"})finally:import litellm.proxy.proxy_server as psapp.dependency_overrides.pop(ps.user_api_key_auth, None)+def _get_unscoped_list_files(query: str):+ return _get_list_files(f"/v1/files{query}")+++_EMPTY_FILE_LIST_PAGE: Final = {+ "object": "list",+ "data": [],+ "first_id": None,+ "last_id": None,+ "has_more": False,+}++async def _validating_afile_list(**kwargs):"""Stand in for the managed file store, applying the real limit validation."""from litellm.proxy.openai_files_endpoints.common_utils import validate_file_list_limitvalidate_file_list_limit(kwargs.get("limit"))- return {- "object": "list",- "data": [],- "first_id": None,- "last_id": None,- "has_more": False,- }+ return dict(_EMPTY_FILE_LIST_PAGE)+++async def _permissive_afile_list(**kwargs):+ """Stand in for a file store that validates nothing, so only the route can reject."""+ return dict(_EMPTY_FILE_LIST_PAGE)@pytest.mark.parametrize(@@ -2683,6 +2695,30 @@ def test_unscoped_list_files_accepts_the_ends_of_the_openai_limit_range(assert managed_files.afile_list.await_args.kwargs["limit"] == limit+ "path",+ [+ "/v1/files?limit=0",+ "/v1/files?limit=0&target_model_names=gpt-3.5-turbo",+ "/openai/v1/files?limit=0",+ ],+ ids=["managed-file-store", "target-model-names", "provider-route"],+)+def test_list_files_validates_the_limit_on_every_branch(+ mocker: MockerFixture, monkeypatch, llm_router: Router, path+):+ """The limit is a route-level contract, so the scoped and provider branches reject it too."""+ _setup_unscoped_list_files_route(mocker, monkeypatch, llm_router, _permissive_afile_list)++ response = _get_list_files(path)++ assert response.status_code == 400, response.text+ assert response.json()["error"]["param"] == "limit"+ assert response.json()["error"]["message"] == (+ "Invalid 'limit': integer below minimum value. Expected a value >= 1, but got 0 instead."+ )++def test_unscoped_list_files_returns_400_for_an_unknown_after_cursor(mocker: MockerFixture, monkeypatch, llm_router: Router):