Repository navigation
merge main - #26437
merge main#26437Sameerlite merged 93 commits into
Conversation
…th team-scoped deployments When vector store endpoints (POST/GET /v1/vector_stores) are called, model=None is passed to the router. map_team_model(None, team_id) was returning None unchanged after the team model routing fix in #25148, so the router never found the team's BYOK deployment and forwarded requests without the API key. Fix: when team_model_name is None, return the matched deployment's team_public_model_name (or model_name fallback) so the router can route to it and inject the BYOK credentials. Does not affect the sibling-deployment load-balancing fix since that only applies when a non-None model is passed. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
… litellm_vector-store-team-byok-model-none
…transformation logic and tests
…ertex AI credentials When aimage_edit or image_edit was called with Vertex AI Gemini/Imagen models via YAML-style config (vertex_project / vertex_credentials in proxy YAML), the credentials were dropped during handler-to-config plumbing, causing fallback to Application Default Credentials and DefaultCredentialsError. Root cause: image_edit_handler and async_image_edit_handler did not pass litellm_params to validate_environment, unlike image_generation_handler. Fixes: 1. Widen BaseImageEditConfig.validate_environment signature to accept litellm_params and api_base (optional kwargs). 2. Forward dict(litellm_params) and litellm_params.api_base from both sync and async image_edit handlers to validate_environment. 3. Update VertexAIImagenImageEditConfig.validate_environment to read vertex_ai_project/vertex_ai_credentials from litellm_params first, matching Gemini config pattern (secondary latent bug fix). 4. Widen all image-edit config override signatures to match base. Made-with: Cursor
Adds three test cases to prevent regression of the Vertex AI image_edit credentials bug: 1. test_validate_environment_signature_includes_litellm_params: ensures all image-edit configs accept litellm_params (contract for the handler) 2. test_vertex_gemini_image_edit_reads_credentials_from_litellm_params: verifies Gemini config reads from litellm_params first 3. test_vertex_imagen_image_edit_reads_credentials_from_litellm_params: verifies Imagen config reads from litellm_params first These tests catch if the fix is accidentally reverted or if new image-edit configs are added without the litellm_params parameter. Made-with: Cursor
…Imagen get_complete_url VertexAIImagenImageEditConfig.get_complete_url was resolving vertex_project and vertex_location only from env vars and global settings, ignoring litellm_params. Users supplying project/location exclusively via YAML config would get a ValueError or wrong URL even after auth headers were fixed. Mirrors the pattern already used by VertexAIGeminiImageEditConfig and image_generation counterpart (safe_get_vertex_ai_project/location). Also fixes api_key type hint in MockImageEditConfig (str -> Optional[str]) and adds a test covering get_complete_url credential resolution. Made-with: Cursor
[Fix] Align image URL fetch with validated HTTP client in Bedrock and token counter paths
…strictions [Fix] Extend request body parameter restrictions to cloud provider auth fields
Adds a "Total Spend (USD)" column backed by the new membership.total_spend field. Cumulative across budget cycles; tracking began 2026-04-21.
Consolidate 6 distinct cache-key prefixes (v2-dependencies-,
v1-router-testing-deps-, v1-router-unit-deps-, v1-llm-translation-deps-,
v1-llm-responses-deps-, v3-litellm-uv-deps-, ui-e2e-py-deps-v2-) onto a
single v1-uv-cache-<uv.lock checksum> key shared across all Python jobs.
Cache only ~/.cache/uv (the content-addressed uv download cache,
hash-verified against uv.lock at install time). Drop ./.venv,
~/.local/{bin,lib}, and /home/circleci/.{pyenv,local} from cache paths.
~/.cache/uv is the only path uv sync needs to avoid re-downloading from
PyPI; everything else is rebuilt each run from that verified cache.
Remove partial-prefix restore-keys fallbacks — cache either hits exactly
on the uv.lock hash or rebuilds cleanly.
First run after merge will cold-miss on the new key; subsequent runs
hit the unified cache.
Brings the Snowflake, S3 Vectors, Vertex AI, and Bedrock URL construction paths in line with the existing pattern of validating interpolated values before use.
Adds a formatBudgetReset helper (dayjs-based, with validity guard) that renders the next reset as "today" / "in N days" / "on MMM D, YYYY". The team budget card now shows the team's reset timestamp and the member- default reset (when a shared team_member_budget is configured), and the Members tab gains a Budget Reset column per member.
…ation [Fix] Enforce format constraints on provider URL parameters
Adds back the per-cycle spend column that was replaced by Total Spend in 331e3f2. Current Cycle Spend reads membership.spend (zeroed on budget_reset_at) — this is the value enforced against the member's budget, so admins need it to see whether a member is approaching their cap for the active window. Total Spend remains for lifetime analytics.
Bring string input handling for image/mask parameters in line with the multipart-only contract expected by the image edit endpoint.
…itellm_team_member_total_spend_frontend
…dgets Two independent bugs both masked budget_reset_at from consumers that needed it: 1. /team/info.team_member_budget_table was typed as LiteLLM_BudgetTable (the user-settable allowlist), which dropped server-managed fields. Switched to LiteLLM_BudgetTableFull so budget_reset_at and created_at are serialized. 2. _clone_team_default_budget_for_member copied the pool's numeric fields but never set budget_reset_at on the cloned row. With budget_duration present but no reset timestamp, the reset job never fires on the member's budget (its query is reset_at <= now, which never matches NULL). Now computes budget_reset_at from the cloned budget_duration via get_budget_reset_time so each member's cycle starts at clone time rather than inheriting the pool's stale reset.
…itellm_team_member_total_spend_frontend
… prefix (#26078) (#26117) * fix(mcp_semantic_tool_filter): match canonical tools that arrive with a client-side namespace prefix. `SemanticMCPToolFilter._get_tools_by_names` matched by exact equality between the canonical name stored in the router (`<server><MCP_TOOL_PREFIX_SEPARATOR><tool>`) and the name in the incoming `tools[]` list. MCP clients such as opencode wrap every tool name with their own additive alias prefix (`<client_alias>_<canonical>`), so the two never matched, the filter dropped every tool to zero, and the proxy forwarded `tools: []` with `tool_choice: auto` — which strict upstream providers reject with a 400. The fix adds anchored suffix matching with a separator check: the canonical must form the complete tail of the incoming name and be preceded by `_` or `-`. Exact matches still win over suffix matches, incoming tools are returned at most once, and the original tool object is passed through unchanged so the client-facing name survives for tool-call round-trips. Seven unit tests in a new TestGetToolsByNames class cover exact match, underscore- and dash-prefixed variants, non-separator-anchored suffixes (which must not match), exact-wins-over-prefixed precedence, deduplication when two canonicals suffix-match the same incoming tool, and ordering-follows-router-output. Fixes #26078 * review: strengthen the suffix-fallback tie-breaker and the deduplication regression test (Greptile comments on #26117) - test_same_tool_not_returned_twice now passes two distinct canonicals ("read_file" and "file") that both suffix-match the same incoming tool, rather than the same canonical twice, so the assertion actually exercises the used_ids dedup path instead of the duplicate-input-list path. - The suffix fallback in _get_tools_by_names now prefers the shortest incoming name that still qualifies under the separator-anchored match. In the one-prefix-per-client opencode scenario this is a no-op, but in multi-namespace configurations the shortest qualifying name is the least-wrapped one and is the most defensible deterministic choice, replacing the dict-insertion-order fallback. - Adds test_suffix_fallback_prefers_shortest_candidate covering the new tie-breaker directly. Still 15 tests passing locally (was 14). * review(#26117): gate suffix-matching on canonical containing MCP_TOOL_PREFIX_SEPARATOR @krrish-berri-2 flagged a possible collision in the suffix fallback: a local user function whose name happens to end in a bare canonical substring (e.g. my_firecrawl_scrape vs canonical firecrawl_scrape) would be spuriously selected. Server-registered MCP tools are always emitted as <server_name><MCP_TOOL_PREFIX_SEPARATOR><tool_name> via add_server_prefix_to_name, so a canonical without the separator is not a namespaced MCP tool and does not warrant suffix matching. Added that guard to _name_matches_canonical with a regression test (test_does_not_collide_with_local_function_on_unprefixed_canonical) that reproduces the collision before the fix and is pinned after. Pre-existing TestGetToolsByNames fixtures that relied on bare canonicals (get_weather, search, read_file, write/delete/read) were switched to realistic server-prefixed ones so they continue to exercise the suffix-fallback path under the new guard. The opencode scenario (client prefix on already-server-prefixed canonical) is unchanged. --------- Co-authored-by: sakenuGOD <sakenuGOD@users.noreply.github.com> Co-authored-by: Krrish Dholakia <krrish+github@berri.ai>
[Infra] Promote interal staging to main
…26111) * fix(model-info): include reasoning effort support fields in get_model_info _get_model_info_helper constructs ModelInfoBase explicitly but never reads supports_xhigh/minimal/none_reasoning_effort from the cost map JSON. Add the three fields so get_model_info() returns them correctly. Also add supports_minimal_reasoning_effort to the ModelInfo TypedDict (xhigh and none were already declared, minimal was missing). * fix(model-registry): add missing reasoning effort fields for claude 4.6/4.7 Claude Opus 4.7 supports max reasoning effort (above xhigh). The field was present for Opus 4.6 but missing for all Opus 4.7 entries (base, dated, Bedrock, Vertex AI, Azure AI). All Claude 4.6/4.7 models (Opus 4.6, Sonnet 4.6, Opus 4.7) support minimal reasoning effort via adaptive thinking. Add the field to all provider variants. * fix(adapter): map output_config.effort to reasoning_effort (#25079) Anthropic's adaptive thinking (thinking.type="adaptive") and output_config.effort were silently dropped when translating to OpenAI format, resulting in no reasoning_effort on the outgoing request. Adapter changes (format translation): - adapters/transformation.py: add "adaptive" branch to translate_anthropic_thinking_to_reasoning_effort(); pass through output_config.effort as-is in _translate_thinking_to_openai(); add "output_config" to translatable_anthropic_params - adapters/handler.py: extract output_config from extra_kwargs into request_data so it reaches the translation layer - responses_adapters/transformation.py: add "adaptive" branch and output_config param to translate_thinking_to_reasoning() Handler changes (model-aware normalization): - utils.py: add normalize_reasoning_effort_value() that uses get_model_info() to map "max" → "xhigh"/"high" and "minimal" → "minimal"/"low" based on model capabilities - adapters/handler.py: call normalization before responses routing - responses_adapters/handler.py: call normalization after translation Relates to #25079 * test(reasoning-effort): add tests for effort capability fields and normalize logic Test coverage for: - get_model_info returning supports_minimal/max_reasoning_effort fields - JSON registry entries for claude 4.6/4.7 across all providers - normalize_reasoning_effort_value degradation chains and exception fallback - Adapter translation of adaptive thinking + output_config.effort * fix: forward custom_llm_provider to normalize_reasoning_effort_value in responses adapter
…scovery (#26228) `get_file_ids_from_messages` and `update_messages_with_model_file_ids` assume every content block with `type: "file"` has a nested `file` dict in the OpenAI Chat Completions shape. That assumption is too strong: `type: "file"` is a public content-block discriminator and several real producers emit blocks that use it without the OpenAI `file` sub-dict. For example, LangChain v1's `_normalize_messages` rewrites OpenAI file blocks into `{"type":"file","id":"...","base64":"...","mime_type":"...","extras":{}}` before they reach LiteLLM. `AnthropicConfig.validate_environment` calls both helpers unconditionally on every Anthropic (and Anthropic-via-Vertex) request, so any such block raises `KeyError: 'file'` which the Vertex partner layer then wraps as a `500 InternalServerError` before the LLM is even contacted. This patch switches both helpers from `c["file"]` to a defensive `c.get("file")` + dict check. When the block does not match the OpenAI shape there is no file_id to extract or remap, so we skip it and leave the block untouched for the downstream provider transformer to handle. Adds 5 regression tests covering the LangChain v1 shape, the OpenAI happy path, mixed shapes in one message, `file` set to a non-dict value, and the remap path for non-OpenAI blocks. Related to #24503, which proposed raising `BadRequestError` in the same spots. For these two discovery functions specifically, the skip semantics is strictly more permissive: well-formed OpenAI blocks still yield their file_id, and legitimate non-OpenAI blocks stop crashing the request.
…tive /v1/messages (#25883) When reasoning_auto_summary is enabled (via litellm_settings or env var), automatically set thinking.display="summarized" on native /v1/messages requests. This ensures thinking content is returned in the response instead of being omitted (the default on Claude 4.7+). Only applies when thinking is enabled (type != "disabled"). The existing reasoning_auto_summary flag already handles the /v1/responses path (summary="detailed") and the chat/completions adapter path — this extends coverage to the native messages handler.
* fix(ovhcloud): fix tool calling * fix import order
[Fix] Deflake spend tracking tests
…is (#26162) (#26318) Temporary MCP OAuth sessions were kept in process-local memory, so on multi-instance/LB proxy deployments a session created on instance A could not be found when the follow-up /server/oauth/{server_id}/... request landed on instance B. Persist temporary session records to Redis (encrypted with the existing proxy encryption helpers) as a best-effort L2 cache alongside the current in-memory L1. Convert get_cached_temporary_mcp_server to async and await it from the authorize/token/register OAuth endpoints. Made-with: Cursor
test_db_schema_migration.py has exactly one test, and that test is mostly waiting on prisma subprocesses (~170s: prisma migrate deploy + prisma migrate diff). No CPU-bound Python work inside the test body, and only one test in the file means xdist's parallelism is unused regardless. Previous run on commit 5df9f39: 10.0m wall-clock for the shard, of which 4:56 was silence between step start and pytest banner — the cost of 4 xdist workers each cold-starting (pytest plugin load + litellm import + pytest-cov instrumentation) so that exactly one of them could pick up the single test. Switching to workers: 0 takes the serial pytest branch in the base workflow, which already handles this case correctly (no -n, no --dist). Single-process startup instead of 4. Expected wall-clock: ~6m.
The `_test-unit-services-base.yml` reusable workflow attached every job to the `integration-postgres` GHA environment to read three "secrets": DATABASE_URL, POSTGRES_USER, POSTGRES_PASSWORD. These are not secrets — the postgres service container is spawned per-job on localhost and destroyed with the job, so the user/password are bootstrap values for a throwaway container and the URL is always `postgresql://…@localhost:…`. Each environment attachment produces a "temporarily deployed to integration-postgres" deployment record, which the PR timeline renders as a message per matrix shard per push. With 14 proxy-db shards that's ~14 notifications per push, drowning the PR conversation. Changes: * Hardcode POSTGRES_USER/POSTGRES_PASSWORD/POSTGRES_DB and the derived DATABASE_URL in `_test-unit-services-base.yml`. * Delete the `environment: integration-postgres` attachment. * Delete the `secrets:` declarations on the reusable workflow and on the two callers (test-unit-proxy-db.yml, test-unit-security.yml). * The `services:` container still starts a fresh postgres per job; the connection string now matches what the container boots up with. Security review: no regression. The environment wasn't gating anything real — no protection rules configured, no approval gates, and the branch restriction is already enforced by `on: push: branches: [...]` on both caller workflows. Zizmor pedantic-mode findings are identical before and after (same 6 pre-existing findings, zero new ones). The `integration-postgres` environment and its three "secrets" in repo settings are now unreferenced and can be deleted from repo admin.
[Fix] Reset budget windows failing due to Prisma Json? null filter
…itellm_team_member_total_spend_frontend
MCP server CRUD endpoints (/v1/mcp/server*) were bundled with MCP
tool-call / passthrough endpoints under llm_api_routes, so setting
DISABLE_LLM_API_ENDPOINTS=true on admin-only nodes also blocked the
Admin UI from listing, adding, or attaching MCP servers.
Separate mcp_inference_routes (data-plane, gated by
DISABLE_LLM_API_ENDPOINTS) from mcp_management_routes (control-plane,
gated by DISABLE_ADMIN_ENDPOINTS). Keep mcp_routes as a union for
backward compat with allowed_routes=["mcp_routes"] virtual key configs.
Upgrade is_management_route to pattern-aware matching so
/v1/mcp/server/{path:path} resolves for concrete IDs.
Out of scope for the members-tab feature and regressed legacy teams whose budget_reset_at is null (duration was previously shown as a fallback).
Members tab column reads this field; dropping it from the type in the previous revert broke the type check without affecting the reverted render logic.
…d_frontend Surface per-member budget cycle in Teams > Members tab
[Infra] Bump version 1.83.12 → 1.83.13
…m-byok-model-none
…-model-none fix(router): restore BYOK key injection for vector store endpoints with team-scoped deployments
[Infra] Remove CCI/GHA test duplication and semantically shard proxy DB tests
…gement-vs-inference Split MCP routes into inference vs management (unblock Admin UI on DISABLE_LLM_API_ENDPOINTS nodes)
be41d4b
into
litellm_vertex_request_metadata_labels
|
Michael Riad Zaky seems not to be a GitHub user. You need a GitHub account to be able to sign the CLA. If you have already a GitHub account, please add the email address used for this commit to your account. You have signed the CLA already but the status is still pending? Let us recheck it. |
Low: No new security issues foundThis large PR includes several positive security hardening changes: expanding the Status: 0 open Posted by Veria AI · 2026-04-24T15:25:31.874Z |
Greptile SummaryThis is a large "merge main" sync PR (97 files) that brings in multiple features and fixes from the main branch into the Confidence Score: 4/5Mostly safe to merge; findings are P2 quality concerns rather than blocking defects. The PR carries no P0/P1 findings. The direct DB queries in litellm/proxy/proxy_server.py (_reseed_spend_from_db direct DB access) and litellm/proxy/auth/auth_checks.py (team-default budget bypass edge case).
|
| Filename | Overview |
|---|---|
| litellm/proxy/proxy_server.py | Adds _reseed_spend_from_db which makes direct Prisma queries on spend-counter cold-start — violates the no-direct-DB-in-request-path rule; also improves team/org spend counter seeding logic. |
| litellm/proxy/auth/auth_checks.py | Adds get_team_member_default_budget helper and wires team-level default member budget fallback into _check_team_member_budget; edge case with non-null budget table but null max_budget bypasses team default. |
| litellm/proxy/auth/auth_utils.py | Security improvement: adds aws_sts_endpoint, aws_web_identity_token, aws_role_name, vertex_credentials to banned request body params to prevent credential theft via api_base SSRF pattern. |
| litellm/proxy/auth/route_checks.py | Fixes is_management_route to use check_route_access (wildcard matching) instead of a plain in check; changes LLM API route check to mcp_inference_routes (excluding CRUD management routes). |
| litellm/proxy/_types.py | Splits mcp_routes into mcp_inference_routes and mcp_management_routes; adds mcp_management_routes to management_routes; converts management_routes to list-concatenation. |
| litellm/litellm_core_utils/logging_worker.py | Fixes flush() race condition — replaces while not empty(): join() (misses in-flight tasks) with await join() (waits on internal task counter). |
| litellm/llms/vertex_ai/common_utils.py | Adds multi-region URL format (aiplatform.{geo}.rep.googleapis.com) for locations without a dash, plus input validation and a None guard. |
| litellm/proxy/management_endpoints/mcp_management_endpoints.py | Adds Redis-backed encrypted caching for temporary MCP OAuth sessions to share state across proxy instances; changes get_cached_temporary_mcp_server to async. |
| litellm/llms/dashscope/image_generation/transformation.py | New DashScope image generation provider supporting OpenAI-compatible size params and qwen-image-2.0 model family; handles 200-status API-level errors correctly. |
| litellm/proxy/common_utils/reset_budget_job.py | Replaces ORM find_many with query_raw for budget_limits IS NOT NULL filtering (workaround for prisma-client-py#714 with Json? columns); writes still use ORM. |
Flowchart
%%{init: {'theme': 'neutral'}}%%
flowchart TD
A[Request arrives] --> B{spend_counter_cache hit?}
B -- Yes --> E[Atomically increment counter]
B -- No --> C[_reseed_spend_from_db]
C --> C1{prisma_client available?}
C1 -- No --> D[Fallback: read from user_api_key_cache]
C1 -- Yes --> C2[Direct DB find_unique by key prefix]
C2 --> C3[Return base_spend]
D --> C3
C3 --> F{base_spend > 0?}
F -- Yes --> G[async_increment_cache seed]
F -- No --> E
G --> E
E --> H[Budget enforcement check]
H --> H1{team_membership.litellm_budget_table != None?}
H1 -- Yes --> H2[team_member_budget = max_budget - may be None]
H1 -- No --> H3[Try team_member_budget_id fallback]
H2 --> H4{team_member_budget != None?}
H3 --> H4
H4 -- Yes --> H5[Check spend vs budget]
H4 -- No --> H6[No enforcement]
Reviews (1): Last reviewed commit: "Merge pull request #26367 from BerriAI/l..." | Re-trigger Greptile
|
| GitGuardian id | GitGuardian status | Secret | Commit | Filename | |
|---|---|---|---|---|---|
| 29203065 | Triggered | JSON Web Token | e982fe8 | tests/test_litellm/proxy/test_litellm_pre_call_utils.py | View secret |
| 31539530 | Triggered | Generic Password | 66bf890 | .github/workflows/_test-unit-services-base.yml | View secret |
| 31539530 | Triggered | Generic Password | 8e652d1 | .github/workflows/_test-unit-services-base.yml | View secret |
🛠 Guidelines to remediate hardcoded secrets
- Understand the implications of revoking this secret by investigating where it is used in your code.
- Replace and store your secrets safely. Learn here the best practices.
- Revoke and rotate these secrets.
- If possible, rewrite git history. Rewriting git history is not a trivial act. You might completely break other contributing developers' workflow and you risk accidentally deleting legitimate data.
To avoid such incidents in the future consider
- following these best practices for managing and storing secrets including API keys and other credentials
- install secret detection on pre-commit to catch secret before it leaves your machine and ease remediation.
🦉 GitGuardian detects secrets in your source code to help developers and security teams secure the modern development process. You are seeing this because you or someone else with access to this repository has authorized GitGuardian to scan your pull request.
| ) | ||
|
|
||
|
|
||
| async def _reseed_spend_from_db(counter_key: str) -> float: | ||
| """ | ||
| Read the authoritative spend for a missing counter from the DB. The | ||
| counter_key prefix encodes the table to query: | ||
|
|
||
| spend:key:{token} -> LiteLLM_VerificationToken.spend | ||
| spend:team:{team_id} -> LiteLLM_TeamTable.spend | ||
| spend:team_member:{uid}:{tid} -> LiteLLM_TeamMembership.spend | ||
| spend:user:{user_id} -> LiteLLM_UserTable.spend | ||
| spend:org:{org_id} -> LiteLLM_OrganizationTable.spend | ||
|
|
||
| Returns 0.0 if prisma is unavailable, the row is missing, or the | ||
| key format is unrecognized. On failure, logs and returns 0.0 rather | ||
| than raising so the caller can still record the current increment. | ||
| """ | ||
| if prisma_client is None: | ||
| return 0.0 | ||
| # Per-window counters (spend:*:window:{duration}) share prefixes with | ||
| # primary counters but don't correspond to a DB row; their ambiguity | ||
| # would otherwise be silently parsed as a regular counter and miss. | ||
| if ":window:" in counter_key: | ||
| return 0.0 | ||
| try: | ||
| if counter_key.startswith("spend:key:"): | ||
| token = counter_key[len("spend:key:") :] | ||
| row = await prisma_client.db.litellm_verificationtoken.find_unique( | ||
| where={"token": token} | ||
| ) | ||
| elif counter_key.startswith("spend:team_member:"): | ||
| suffix = counter_key[len("spend:team_member:") :] | ||
| if ":" not in suffix: | ||
| return 0.0 | ||
| user_id, team_id = suffix.rsplit(":", 1) | ||
| row = await prisma_client.db.litellm_teammembership.find_unique( | ||
| where={"user_id_team_id": {"user_id": user_id, "team_id": team_id}} | ||
| ) | ||
| elif counter_key.startswith("spend:team:"): | ||
| team_id = counter_key[len("spend:team:") :] | ||
| row = await prisma_client.db.litellm_teamtable.find_unique( | ||
| where={"team_id": team_id} | ||
| ) | ||
| elif counter_key.startswith("spend:user:"): | ||
| user_id = counter_key[len("spend:user:") :] | ||
| row = await prisma_client.db.litellm_usertable.find_unique( | ||
| where={"user_id": user_id} | ||
| ) | ||
| elif counter_key.startswith("spend:org:"): | ||
| org_id = counter_key[len("spend:org:") :] | ||
| row = await prisma_client.db.litellm_organizationtable.find_unique( | ||
| where={"organization_id": org_id} | ||
| ) | ||
| else: | ||
| return 0.0 | ||
| except Exception: | ||
| verbose_proxy_logger.exception( | ||
| "Failed to reseed spend counter %s from DB", counter_key | ||
| ) | ||
| return 0.0 | ||
| if row is None: | ||
| return 0.0 | ||
| return float(getattr(row, "spend", 0.0) or 0.0) | ||
|
|
There was a problem hiding this comment.
Direct DB queries in request path
_reseed_spend_from_db issues raw Prisma find_unique calls directly against litellm_verificationtoken, litellm_teammembership, litellm_teamtable, litellm_usertable, and litellm_organizationtable tables. This is called from _init_and_increment_spend_counter which runs inside every request when the in-memory spend counter is cold (first request after pod start or cache eviction). The team rule requires all DB access in the critical request path to go through the get_team/get_user/get_key helper functions rather than hitting the ORM directly, to prevent DB regression patterns.
Rule Used: What: In critical path of request, there should be... (source)
|
|
||
| - ``global`` uses the global control plane host. | ||
| - Multi-region geographies (e.g. ``us``, ``eu``) use ``aiplatform.{geo}.rep.googleapis.com``. | ||
| - Regional locations (e.g. ``us-central1``) use ``{region}-aiplatform.googleapis.com``. | ||
| """ | ||
| if vertex_location == "global": | ||
| return "https://aiplatform.googleapis.com" | ||
| else: | ||
| return f"https://{vertex_location}-aiplatform.googleapis.com" | ||
| if vertex_location is None: | ||
| raise ValueError("vertex_location is required") | ||
| if not re.match(r"^[a-z][a-z0-9-]*$", vertex_location): | ||
| raise ValueError("Invalid vertex_location format") | ||
| if "-" not in vertex_location: | ||
| return f"https://aiplatform.{vertex_location}.rep.googleapis.com" | ||
| return f"https://{vertex_location}-aiplatform.googleapis.com" |
There was a problem hiding this comment.
None guard placed after the "global" branch is correct, but regex may reject valid locations
The validation regex ^[a-z][a-z0-9-]*$ rejects any location string containing uppercase letters or underscores. Vertex AI location strings are always lowercase-plus-dash, so this is defensively fine — however, the regex also implicitly validates "global" (which would pass), even though it is already handled by the early return above. More importantly, the None guard comes after the "global" string comparison, not before: None == "global" is False in Python, so there is no NPE here. The logic is correct, but documenting the None-before-global ordering would reduce confusion for future readers.
| self._running_tasks.clear() | ||
|
|
||
| async def flush(self) -> None: | ||
| """Flush the logging queue.""" | ||
| """Flush the logging queue. | ||
|
|
||
| Waits until every enqueued task has completed. ``queue.join()`` blocks | ||
| on the queue's unfinished-task counter (decremented by ``task_done()``), | ||
| so it correctly handles items that have been dequeued but whose | ||
| callback hasn't finished yet — ``queue.empty()`` would return True in | ||
| that window and cause us to skip the wait. | ||
| """ | ||
| if self._queue is None: | ||
| return | ||
| while not self._queue.empty(): | ||
| await self._queue.join() | ||
| await self._queue.join() | ||
|
|
||
| async def clear_queue(self): | ||
| """ |
There was a problem hiding this comment.
flush() bug fix is correct but note the semantic change
The old implementation while not self._queue.empty(): await self._queue.join() has a genuine race window: a worker thread can dequeue an item (making empty() return True) before it calls task_done(), causing flush() to return prematurely and lose in-flight log events. The replacement await self._queue.join() blocks on the internal unfinished-task counter which is incremented on put and decremented on task_done(), so it correctly waits for all in-flight callbacks — this is the correct fix per the asyncio.Queue contract.
| proxy_logging_obj=proxy_logging_obj, | ||
| ) | ||
|
|
||
| # Per-member override wins; otherwise fall back to the team-level | ||
| # default configured via team.metadata["team_member_budget_id"]. | ||
| team_member_budget: Optional[float] = None | ||
| if ( | ||
| team_membership is not None | ||
| and team_membership.litellm_budget_table is not None | ||
| and team_membership.litellm_budget_table.max_budget is not None | ||
| ): | ||
| team_member_budget = team_membership.litellm_budget_table.max_budget | ||
| team_member_spend = team_membership.spend or 0.0 | ||
| else: | ||
| default_budget_id = (team_object.metadata or {}).get( | ||
| "team_member_budget_id" | ||
| ) | ||
| if isinstance(default_budget_id, str): | ||
| default_budget = await get_team_member_default_budget( | ||
| budget_id=default_budget_id, | ||
| prisma_client=prisma_client, | ||
| user_api_key_cache=user_api_key_cache, | ||
| ) | ||
| if default_budget is not None: | ||
| team_member_budget = default_budget.max_budget | ||
|
|
||
| if team_member_budget is not None: | ||
| team_member_spend = ( | ||
| team_membership.spend if team_membership is not None else 0.0 | ||
| ) or 0.0 | ||
|
|
||
| # Read from cross-pod counter (Redis-first) if available | ||
| from litellm.proxy.proxy_server import get_current_spend |
There was a problem hiding this comment.
Team-default budget skipped when membership has a budget table with
max_budget=None
When team_membership.litellm_budget_table is not None but litellm_budget_table.max_budget is None, the code sets team_member_budget = None (from the table) and the else fallback to the team-level team_member_budget_id is not taken. This means a member whose TeamMembership row carries an explicit budget table that happens to have no max_budget will bypass both the per-member check and the team-default fallback — effectively no budget enforcement for that member. If this is the intended "per-member override wins even with no cap", a comment explaining that intent would prevent accidental re-introduction of the max_budget is not None guard.
…ession storage The PR #121 conflict resolution took upstream's streaming_iterator.py __init__ (which has no litellm_completion_request param) while git auto-merged handler.py cleanly, keeping CARTO's call sites that pass litellm_completion_request= (PR #16, Redis session storage). Result: every streaming Responses API request raised TypeError: LiteLLMCompletionStreamingIterator.__init__() got an unexpected keyword argument 'litellm_completion_request' (3,079 occurrences in the cloud-native integration run for PR BerriAI#26437; 36 AI integration tests failed). The method body _store_session_in_redis also reads self.litellm_completion_request, which was never assigned. Restore the param and the attribute assignment exactly as on carto/main before the sync (7244577), with CARTO markers so future syncs see it.
…andler Second dropped wiring from the PR #121 conflict resolution, subtler than the first: async_responses_api_session_handler lost the CARTO PATCH that reads sessions from Redis before the DB-backed store (PR #16). Both Redis helpers survived the merge, so manifest pattern greps passed, but _patch_get_session_from_redis was left orphaned - defined with zero call sites. Session writes (restored in 1c1f2a0) landed in Redis while reads went to the batch-delayed SpendLogs store, so immediate follow-up turns lost their conversation history. Observed blast radius in cloud-native PR BerriAI#26437 integration rerun: conversations answered with other conversations' content, ai-api agent loops spun (4,333 /responses calls in 13 minutes, ~25/min is normal), and the CI org burned through its 10M AI quota mid-run. Restore the Redis-first read exactly as on carto/main pre-sync, and add regression tests pinning the read-before-DB wiring so an orphaned helper can't silently pass future syncs.
…e Redis store keys Two changes closing the remaining session-context regression from the v1.92.0 sync (integration rerun on cloud-native PR BerriAI#26437 still showed multi-turn context loss: "assistant failed to recall the previous instruction", agent loops, 3,259 /responses calls): 1. Replace the earlier condensed restoration of the Redis-first session lookup with carto/main's exact block, byte-identical including its verbose_logger.debug lines (verified with diff against 7244577). Verbatim over rewrite - the debug lines also make CI diagnosable. 2. Key Redis session stores by the DECODED response id. This bug cannot be fixed by copying carto/main code because it does not exist at v1.83.14: upstream v1.92.0 introduced b64-encoded response ids (response.completed carries the encoded id) while previous_response_id is decoded in responses/utils.py before reaching the session handler. carto/main's code keyed stores by response.id, which at v1.83.14 was the raw provider id (store == lookup); on v1.92.0 the same code keys by the encoded id and the decoded lookup misses 100% of the time. Verified empirically by driving the streaming iterator on both versions. Decode at the two store call sites; the CARTO Redis helpers themselves remain byte-identical to carto/main. Adds a regression test driving the real streaming iterator and asserting the stored key equals the decoded form of the client-visible response id.
Relevant issues
Pre-Submission checklist
Please complete all items before asking a LiteLLM maintainer to review your PR
tests/test_litellm/directory, Adding at least 1 test is a hard requirement - see detailsmake test-unit@greptileaiand received a Confidence Score of at least 4/5 before requesting a maintainer reviewDelays in PR merge?
If you're seeing a delay in your PR being merged, ping the LiteLLM Team on Slack (#pr-review).
CI (LiteLLM team)
Branch creation CI run
Link:
CI run for the last commit
Link:
Merge / cherry-pick CI run
Links:
Screenshots / Proof of Fix
Type
🆕 New Feature
🐛 Bug Fix
🧹 Refactoring
📖 Documentation
🚄 Infrastructure
✅ Test
Changes