litellm/tests/test_litellm/proxy
milan-berri 4250713700
fix(spend_counter): seed Redis counter via SET NX to prevent cross-pod double-seed (#27854)
* fix(spend_counter): seed Redis counter via SET NX to prevent cross-pod double-seed

Symptom
-------
Customers on multi-pod deployments see team `spend` jump to ~2x (or N x
the pod count) shortly after a Redis cache miss / TTL expiry, triggering
spurious "Budget Crossed" alerts and blocked requests until the value is
manually reset.

Root cause
----------
`SpendCounterReseed.coalesced` warmed the primary spend counter by
calling `redis.async_increment(key, value=db_spend, refresh_ttl=True)`,
which lowers to Redis `INCRBYFLOAT`. That is additive, not idempotent.

The per-counter `asyncio.Lock` only coalesces seeders inside one
process. With N pods sharing one Redis, on a cold key (cold start, TTL
expiry, manual delete) every pod independently passes its lock + Redis
re-check, reads the same `db_spend`, and issues `INCRBYFLOAT db_spend`.
Final value: N x db_spend.

Fix
---
Use `redis.async_set_cache(key, value=db_spend, nx=True)` for the seed.
SET NX is atomic across pods: exactly one writer initializes the key;
losers read the winner's value via `async_get_cache`. This is the same
idiom already used by `coalesced_window` in the same file, so the two
seed paths are now consistent.

Per-request deltas continue to use `INCRBYFLOAT` (correct - additive
behaviour is what we want for increments, not for initial seed).

Verification
------------
Live two-process repro against the same Postgres + Redis (DB
spend = 506):

  Unpatched: 4/4 runs -> Redis counter = ~1012  (~2 x db_spend)
  Patched:  12/12 runs -> Redis counter = ~506

Unit tests (`test_proxy_server.py`):

- New `test_primary_spend_counter_redis_concurrent_seed_does_not_double_seed`
  patches `_get_lock` to return a fresh lock per caller (otherwise the
  per-process lock masks the race), races two `coalesced` calls, and
  asserts final = 506 with exactly one of two SET NX attempts winning.
- 4 existing tests updated for the new seed contract (SET NX for the
  seed, INCRBYFLOAT only for the per-request delta).
- Full `spend_counter or reseed or budget` slice: 22 passed.

Co-authored-by: Cursor <cursoragent@cursor.com>

* test(spend_counter): make SET NX mock atomic so loser branch is exercised

Greptile flagged that `redis_set_cache` in
test_primary_spend_counter_redis_concurrent_seed_does_not_double_seed
placed `await asyncio.sleep(0)` AFTER the NX membership check. Both
concurrent tasks observed an empty `redis_store`, passed the guard, and
both returned True - so the loser branch (else: read back winner's value)
was never exercised.

Fix the mock to model real atomic Redis SET NX:

- Yield BEFORE the membership check so two concurrent callers interleave
  the way real SET NX does (first to resume runs check + write atomically
  and wins; second resumes after the key exists and loses).
- Track set_cache return values; assert sorted([loser, winner]) so we
  know exactly one task wins and one loses.
- Track async_get_cache calls that happen AFTER at least one SET NX has
  completed; assert at least one such read - that is the loser-path
  fallback (`current_value = float(cached)` when seeded is False).

Verified by temporarily reverting the mock to the old order: the test
now fails with `expected exactly one SET NX winner and one loser, got
[True, True]`, exactly the failure mode Greptile described.

No production code change.

Co-authored-by: Cursor <cursoragent@cursor.com>

* test(spend_counter): mock async_set_cache to populate redis_store in concurrent read+write test

`test_concurrent_read_and_write_paths_share_one_db_query` mocks
`async_increment` to populate the in-memory `redis_store`, but did not
mock `async_set_cache`. After the SET-NX seed change in `coalesced()`,
the seed step writes via `async_set_cache(nx=True)` (default AsyncMock,
no `redis_store` write), so the simulated Redis stays empty after the
first reseed. The second `get_current_spend` then sees a clean Redis
miss, re-enters the DB read path, and the test fails with
`expected 1 DB query, got 2`.

Fix: add a `redis_set_cache` side_effect that updates `redis_store` on
`nx=True` (and rejects when the key already exists), matching the
pattern used by the four sibling tests fixed in this branch's first
commit. Pre-existing assertions are unchanged.

Full `tests/test_litellm/proxy/test_proxy_server.py`: 158 passed.

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
(cherry picked from commit 0fb710400f)
2026-05-20 18:42:35 -07:00
..
_experimental/mcp_server fix(mcp): static headers win over forwarded headers in OpenAPI MCP 2026-05-12 23:33:37 +03:00
agent_endpoints style: run black formatter on files from main merge 2026-04-17 13:02:59 -07:00
anthropic_endpoints test: isolate proxy master_key/prisma_client module globals between tests 2026-04-23 15:31:16 -07:00
auth Merge remote-tracking branch 'origin/litellm_1.84.0rc2' into backport/27878-litellm_1.84.0rc2 2026-05-13 21:39:17 -07:00
client [Infra] Promote internal staging to main (#27245) 2026-05-05 16:15:03 -07:00
common_utils [Infra] Promote internal staging to main (#27245) 2026-05-05 16:15:03 -07:00
db [Infra] Promote internal staging to main (#27245) 2026-05-05 16:15:03 -07:00
discovery_endpoints style: run black formatter on files from main merge 2026-04-17 13:02:59 -07:00
experimental/mcp_server
google_endpoints run pre_call_hook on Google generateContent endpoints 2026-04-30 16:43:42 -07:00
guardrails [Infra] Promote internal staging to main (#27245) 2026-05-05 16:15:03 -07:00
health_endpoints fix(proxy): expose db status on public /health/readiness 2026-05-13 13:18:54 -07:00
hooks [Infra] Promote internal staging to main (#27245) 2026-05-05 16:15:03 -07:00
image_endpoints style: run black formatter on files from main merge 2026-04-17 13:02:59 -07:00
management_endpoints fix: harden /key/update authorization checks (#27878) 2026-05-13 21:33:14 -07:00
management_helpers feat(proxy): move search tool access to object permissions 2026-04-29 12:29:20 +05:30
memory Litellm memory improvements v2 (#26541) 2026-04-25 19:03:43 -07:00
middleware fix(proxy): point /metrics 401 at the opt-out flag 2026-05-08 18:42:14 -07:00
openai_files_endpoint Merge remote-tracking branch 'origin/litellm_internal_staging' into litellm_yj_apr17 2026-04-17 17:36:40 -07:00
pass_through_endpoints Merge pull request #26827 from stuxf/fix/passthrough-auth-default 2026-04-30 17:06:37 -07:00
policy_engine style: run black formatter on files from main merge 2026-04-17 13:02:59 -07:00
prompts style: run black formatter on files from main merge 2026-04-17 13:02:59 -07:00
public_endpoints [Infra] Promote internal staging to main (#27245) 2026-05-05 16:15:03 -07:00
rag_endpoints Merge remote-tracking branch 'origin/litellm_1.84.0rc2' into backport/27878-litellm_1.84.0rc2 2026-05-13 21:39:17 -07:00
realtime_endpoints test: isolate proxy master_key/prisma_client module globals between tests 2026-04-23 15:31:16 -07:00
response_api_endpoints style: run black formatter on files from main merge 2026-04-17 13:02:59 -07:00
spend_tracking [Infra] Promote internal staging to main (#27245) 2026-05-05 16:15:03 -07:00
test_configs
types_utils Merge pull request #27801 from stuxf/chore/get-instance-fn-runtime-s3-gate 2026-05-13 20:57:24 -07:00
ui_crud_endpoints [Infra] Promote internal staging to main (#27245) 2026-05-05 16:15:03 -07:00
vector_store_endpoints [Infra] Promote internal staging to main (#27245) 2026-05-05 16:15:03 -07:00
__init__.py style: run black formatter on files from main merge 2026-04-17 13:02:59 -07:00
conftest.py test: isolate proxy master_key/prisma_client module globals between tests 2026-04-23 15:31:16 -07:00
test_aiohttp_cleanup_closed.py style: run black formatter on files from main merge 2026-04-17 13:02:59 -07:00
test_aiohttp_session_recovery.py fix: use AsyncMock for concurrent test consistency 2026-03-18 00:54:23 +00:00
test_api_key_masking_in_errors.py style: run black formatter on files from main merge 2026-04-17 13:02:59 -07:00
test_audio_speech_prometheus_hooks.py fix req changes 2026-02-28 21:32:57 +05:30
test_batch_expiry.py fix(proxy): improve team expiry enforcement validation 2026-03-03 17:29:39 -08:00
test_batch_metadata_none_fix.py style: run black formatter on files from main merge 2026-04-17 13:02:59 -07:00
test_batch_retrieve_bedrock.py fix(proxy/batches): forward model to retrieve_batch for bedrock 2026-04-29 22:48:03 +02:00
test_budget_reservation.py fix(proxy): gate image-gen reservation strictly on model mode 2026-05-09 10:29:55 -07:00
test_caching_routes.py
test_chat_completion_metadata.py fix: propagate JWT auth metadata to OTEL spans (#19627) 2026-01-23 21:21:23 -08:00
test_common_request_processing.py feat(proxy): LiteLLM headers on Google native generateContent routes (#25500) 2026-04-29 12:34:14 -07:00
test_cors_config.py refactor: extract _get_cors_config() for testability, fix no-op CORS tests 2026-04-11 22:24:04 +05:30
test_custom_proxy.py
test_empty_model_list.py style: run black formatter on files from main merge 2026-04-17 13:02:59 -07:00
test_enforce_user_param.py style: run black formatter on files from main merge 2026-04-17 13:02:59 -07:00
test_fallback_management_endpoints.py style: run black formatter on files from main merge 2026-04-17 13:02:59 -07:00
test_fastapi_offline_routes.py style: run black formatter on files from main merge 2026-04-17 13:02:59 -07:00
test_filter_models_by_team_access_group.py [Infra] Promote internal staging to main (#27245) 2026-05-05 16:15:03 -07:00
test_health_check_functions.py style: run black formatter on files from main merge 2026-04-17 13:02:59 -07:00
test_health_check_max_tokens.py [Infra] Promote internal staging to main (#27245) 2026-05-05 16:15:03 -07:00
test_langfuse_passthrough_security.py [Infra] Promote internal staging to main (#27245) 2026-05-05 16:15:03 -07:00
test_lazy_openapi_snapshot.py [Infra] Promote internal staging to main (#27245) 2026-05-05 16:15:03 -07:00
test_litellm_pre_call_utils.py fix(proxy): always merge caller-supplied tags into request metadata 2026-05-12 16:34:42 -07:00
test_max_budget_env_var.py style: run black formatter on files from main merge 2026-04-17 13:02:59 -07:00
test_model_dump_with_preserved_fields.py Fix_mapped tests part 2 2026-02-26 12:43:39 +05:30
test_model_id_header_propagation.py style: run black formatter on files from main merge 2026-04-17 13:02:59 -07:00
test_model_info_default_limits.py style: run black formatter on files from main merge 2026-04-17 13:02:59 -07:00
test_model_level_guardrails.py style: run black formatter on files from main merge 2026-04-17 13:02:59 -07:00
test_openapi_schema_validation.py style: run black formatter on files from main merge 2026-04-17 13:02:59 -07:00
test_pricing_field_strip.py [Infra] Promote internal staging to main (#27245) 2026-05-05 16:15:03 -07:00
test_prometheus_cleanup.py style: run black formatter on files from main merge 2026-04-17 13:02:59 -07:00
test_provider_url_destination_guard.py [Infra] Promote internal staging to main (#27245) 2026-05-05 16:15:03 -07:00
test_proxy_cli.py feat(proxy): add --timeout_worker_healthcheck flag for uvicorn worker triage 2026-04-27 11:06:56 -07:00
test_proxy_server.py fix(spend_counter): seed Redis counter via SET NX to prevent cross-pod double-seed (#27854) 2026-05-20 18:42:35 -07:00
test_proxy_types.py style: run black formatter on files from main merge 2026-04-17 13:02:59 -07:00
test_proxy_utils.py style: run black formatter on files from main merge 2026-04-17 13:02:59 -07:00
test_pyroscope.py [Infra] Promote internal staging to main (#27245) 2026-05-05 16:15:03 -07:00
test_redis_auth_cache_flag.py [Infra] Promote internal staging to main (#27245) 2026-05-05 16:15:03 -07:00
test_response_model_sanitization.py style: run black formatter on files from main merge 2026-04-17 13:02:59 -07:00
test_route_a2a_models.py style: run black formatter on files from main merge 2026-04-17 13:02:59 -07:00
test_route_llm_request.py [Infra] Promote internal staging to main (#27245) 2026-05-05 16:15:03 -07:00
test_sensitive_route_auth.py [Infra] Promote internal staging to main (#27245) 2026-05-05 16:15:03 -07:00
test_shared_health_check.py style: run black formatter on files from main merge 2026-04-17 13:02:59 -07:00
test_spend_log_cleanup.py fix: harden CORS, create_views exception handling, and spend log cleanup loop 2026-04-11 18:58:04 +05:30
test_swagger_chat_completions.py [Infra] Promote internal staging to main (#27245) 2026-05-05 16:15:03 -07:00
test_team_member_update.py
test_team_org_move.py fix(team_endpoints): auto-add SSO team members to org on move (proxy admin only) (#26377) 2026-04-24 08:36:25 -07:00
test_tools_allowlist_enforcement.py style: run black formatter on files from main merge 2026-04-17 13:02:59 -07:00
test_update_llm_router_resilience.py style: run black formatter on files from main merge 2026-04-17 13:02:59 -07:00
test_utils.py add NO_OPENAPI env var to disable /openapi.json endpoint (#25547) 2026-04-14 23:37:49 +05:30