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(unit): wait on the work itself instead of fixed sleeps (#46261)

yuneng-jiang1587faeeb990
diff --git a/tests/unit/a2a_protocol/test_cost_calculator.py b/tests/unit/a2a_protocol/test_cost_calculator.py
index 8d8ec815f3a..212af4a6760 100644
--- a/tests/unit/a2a_protocol/test_cost_calculator.py
+++ b/tests/unit/a2a_protocol/test_cost_calculator.py
@@ -117,6 +117,7 @@ class CostLogger(CustomLogger):
def __init__(self):
self.response_cost: Optional[float] = None
+ self.logged = asyncio.Event()
super().__init__()
async def async_log_success_event(self, kwargs, response_obj, start_time, end_time):
@@ -125,6 +126,7 @@ class CostLogger(CustomLogger):
self.response_cost = (
slp.get("response_cost") if isinstance(slp, dict) else getattr(slp, "response_cost", None)
)
+ self.logged.set()
@pytest.mark.asyncio
@@ -157,7 +159,7 @@ async def test_asend_message_uses_cost_per_query(monkeypatch):
cost_per_query=0.05,
)
- await asyncio.sleep(0.1)
+ assert await asyncio.wait_for(cost_logger.logged.wait(), timeout=5)
assert cost_logger.response_cost == 0.05
@@ -194,7 +196,7 @@ async def test_asend_message_uses_cost_per_query_from_litellm_params_dict(monkey
},
)
- await asyncio.sleep(0.1)
+ assert await asyncio.wait_for(cost_logger.logged.wait(), timeout=5)
assert cost_logger.response_cost == 0.5
@@ -206,6 +208,7 @@ class TokenAndCostLogger(CustomLogger):
self.response_cost: Optional[float] = None
self.prompt_tokens: Optional[int] = None
self.completion_tokens: Optional[int] = None
+ self.logged = asyncio.Event()
super().__init__()
async def async_log_success_event(self, kwargs, response_obj, start_time, end_time):
@@ -220,6 +223,7 @@ class TokenAndCostLogger(CustomLogger):
self.completion_tokens = (
slp.get("completion_tokens") if isinstance(slp, dict) else getattr(slp, "completion_tokens", None)
)
+ self.logged.set()
@pytest.mark.asyncio
@@ -257,7 +261,7 @@ async def test_asend_message_uses_input_output_cost_per_token(monkeypatch):
output_cost_per_token=output_cost_per_token,
)
- await asyncio.sleep(0.1)
+ assert await asyncio.wait_for(token_cost_logger.logged.wait(), timeout=5)
# Get actual token counts from logger
prompt_tokens = token_cost_logger.prompt_tokens
@@ -290,11 +294,13 @@ class AgentIdLogger(CustomLogger):
def __init__(self):
self.agent_id: Optional[str] = None
self.kwargs: Optional[dict] = None
+ self.logged = asyncio.Event()
super().__init__()
async def async_log_success_event(self, kwargs, response_obj, start_time, end_time):
self.kwargs = kwargs
self.agent_id = kwargs.get("agent_id")
+ self.logged.set()
@pytest.mark.asyncio
@@ -329,7 +335,7 @@ async def test_asend_message_passes_agent_id_to_callback(monkeypatch):
agent_id=test_agent_id,
)
- await asyncio.sleep(0.1)
+ assert await asyncio.wait_for(agent_id_logger.logged.wait(), timeout=5)
# Verify agent_id was passed to callback
assert agent_id_logger.agent_id == test_agent_id, (
@@ -346,6 +352,7 @@ class MetadataLogger(CustomLogger):
self.user_api_key: Optional[str] = None
self.user_id: Optional[str] = None
self.team_id: Optional[str] = None
+ self.logged = asyncio.Event()
super().__init__()
async def async_log_success_event(self, kwargs, response_obj, start_time, end_time):
@@ -354,6 +361,7 @@ class MetadataLogger(CustomLogger):
self.user_api_key = self.metadata.get("user_api_key")
self.user_id = self.metadata.get("user_api_key_user_id")
self.team_id = self.metadata.get("user_api_key_team_id")
+ self.logged.set()
@pytest.mark.asyncio
@@ -396,7 +404,7 @@ async def test_asend_message_streaming_propagates_metadata():
):
chunks.append(chunk)
- await asyncio.sleep(0.2)
+ assert await asyncio.wait_for(metadata_logger.logged.wait(), timeout=5)
# Verify metadata was propagated to callback
assert metadata_logger.user_api_key == "sk-test-key-hash-12345"
@@ -439,7 +447,7 @@ async def test_asend_message_streaming_triggers_callbacks():
):
chunks.append(chunk)
- await asyncio.sleep(0.2)
+ assert await asyncio.wait_for(callback_logger.logged.wait(), timeout=5)
# Verify chunks were received
assert len(chunks) == 2
diff --git a/tests/unit/caching/test_redis_cache.py b/tests/unit/caching/test_redis_cache.py
index 57c32ace509..0a041694d52 100644
--- a/tests/unit/caching/test_redis_cache.py
+++ b/tests/unit/caching/test_redis_cache.py
@@ -573,9 +573,10 @@ async def test_sync_batch_get_cache_reports_a_failed_read_from_a_running_loop(
outage while the success path keeps reporting, so the dashboards read healthy.
"""
cache, service_logger = sync_batch_cache_with_service_logger
+ tasks_before_read = asyncio.all_tasks()
assert cache.batch_get_cache(key_list=["lit6729"]) == {}
- await asyncio.sleep(0.05)
+ await asyncio.wait_for(asyncio.gather(*(asyncio.all_tasks() - tasks_before_read)), timeout=5)
assert service_logger.mock_testing_sync_failure_hook == 1
assert service_logger.mock_testing_async_failure_hook == 1
@@ -779,21 +780,29 @@ async def test_concurrent_success_is_not_cancelled_by_another_calls_failure():
# The failure has to land after both calls are already in flight, which is the only
# ordering where a shared counter confuses the two. Failing before the healthy call
# starts would leave its snapshot correct and prove nothing.
- async def swallows_a_failure():
- await asyncio.sleep(0.02)
- _record_swallowed_redis_failure(breaker, RedisConnectionError("redis unreachable"))
+ async def run_one_round() -> None:
+ healthy_call_in_flight = asyncio.Event()
+ failure_recorded = asyncio.Event()
- async def succeeds_while_the_other_fails():
- await asyncio.sleep(0.05)
- return "ok"
+ async def swallows_a_failure() -> None:
+ await asyncio.wait_for(healthy_call_in_flight.wait(), timeout=5)
+ _record_swallowed_redis_failure(breaker, RedisConnectionError("redis unreachable"))
+ failure_recorded.set()
+
+ async def succeeds_while_the_other_fails() -> str:
+ healthy_call_in_flight.set()
+ await asyncio.wait_for(failure_recorded.wait(), timeout=5)
+ return "ok"
- rounds = breaker.failure_threshold + 1
- for _ in range(rounds):
await asyncio.gather(
_run_under_circuit_breaker(breaker, "failing", swallows_a_failure),
_run_under_circuit_breaker(breaker, "healthy", succeeds_while_the_other_fails),
)
+ rounds = breaker.failure_threshold + 1
+ for _ in range(rounds):
+ await run_one_round()
+
assert breaker._failure_count < breaker.failure_threshold, "the healthy call must clear the streak"
assert breaker.is_open() is False, "a Redis answering every round must stay in the pool"
diff --git a/tests/unit/integrations/datadog/test_datadog.py b/tests/unit/integrations/datadog/test_datadog.py
index eec0022c1db..14cd376cbc8 100644
--- a/tests/unit/integrations/datadog/test_datadog.py
+++ b/tests/unit/integrations/datadog/test_datadog.py
@@ -3,7 +3,7 @@ import json
import os
from datetime import datetime
from pathlib import Path
-from typing import Coroutine, Final, TypedDict
+from typing import Awaitable, Coroutine, Final, TypedDict, TypeVar
from unittest.mock import AsyncMock, patch
import pytest
@@ -41,6 +41,17 @@ STANDARD_START_TIME: Final[datetime] = datetime(2025, 1, 1)
STANDARD_END_TIME: Final[datetime] = datetime(2025, 1, 1, 0, 0, 1)
+_T = TypeVar("_T")
+
+
+async def _await_with_spawned_tasks(call: Awaitable[_T]) -> _T:
+ before: Final = asyncio.all_tasks()
+ result: Final = await call
+ spawned: Final = asyncio.all_tasks() - before - {asyncio.current_task()}
+ await asyncio.wait_for(asyncio.gather(*spawned), timeout=5)
+ return result
+
+
def _discard_periodic_flush(coroutine: Coroutine[object, object, None]) -> None:
coroutine.close()
@@ -267,17 +278,19 @@ async def test_datadog_logging_http_request():
# Make the completion call
for _ in range(5):
- response = await litellm.acompletion(
- model="gpt-4.1-mini",
- messages=[{"role": "user", "content": "what llm are u"}],
- max_tokens=10,
- temperature=0.2,
- mock_response="Accepted",
+ response = await _await_with_spawned_tasks(
+ litellm.acompletion(
+ model="gpt-4.1-mini",
+ messages=[{"role": "user", "content": "what llm are u"}],
+ max_tokens=10,
+ temperature=0.2,
+ mock_response="Accepted",
+ )
)
print(response)
- # Wait for 5 seconds
- await asyncio.sleep(6)
+ await asyncio.wait_for(GLOBAL_LOGGING_WORKER.flush(), timeout=5)
+ await dd_logger.flush_queue()
# Assert that the mock was called
assert mock_post.called, "HTTP request was not made"
diff --git a/tests/unit/integrations/generic_api/test_generic_api_callback.py b/tests/unit/integrations/generic_api/test_generic_api_callback.py
index e3bb47cad02..7a712786a84 100644
--- a/tests/unit/integrations/generic_api/test_generic_api_callback.py
+++ b/tests/unit/integrations/generic_api/test_generic_api_callback.py
@@ -4,7 +4,7 @@ import json
import logging
import os
from collections.abc import AsyncIterator, Iterator, Sequence
-from typing import Final, TypedDict
+from typing import Awaitable, Final, TypedDict, TypeVar
from unittest.mock import AsyncMock
import httpx
@@ -24,6 +24,17 @@ from litellm.types.utils import StandardLoggingPayload
from tests._vcr_conftest_common import install_live_call_probe, record_vcr_outcome
+_T = TypeVar("_T")
+
+
+async def _await_with_spawned_tasks(call: Awaitable[_T]) -> _T:
+ before: Final = asyncio.all_tasks()
+ result: Final = await call
+ spawned: Final = asyncio.all_tasks() - before - {asyncio.current_task()}
+ await asyncio.wait_for(asyncio.gather(*spawned), timeout=5)
+ return result
+
+
@pytest.fixture(autouse=True)
def set_verbose_logger_level() -> Iterator[None]:
original_level = verbose_logger.level
@@ -51,20 +62,22 @@ async def test_generic_api_callback():
os.environ["GENERIC_LOGGER_ENDPOINT"] = test_endpoint
# Initialize the GenericAPILogger and set the mock
- generic_logger = GenericAPILogger(endpoint=test_endpoint, headers=test_headers, flush_interval=1)
+ generic_logger = GenericAPILogger(endpoint=test_endpoint, headers=test_headers, flush_interval=3600)
generic_logger.async_httpx_client.post = mock_post
litellm.callbacks = [generic_logger]
# Make the completion call
- response = await litellm.acompletion(
- model="gpt-5.5",
- messages=[{"role": "user", "content": "Hello, world!"}],
- mock_response="hi",
- user="test_user",
+ response = await _await_with_spawned_tasks(
+ litellm.acompletion(
+ model="gpt-5.5",
+ messages=[{"role": "user", "content": "Hello, world!"}],
+ mock_response="hi",
+ user="test_user",
+ )
)
- # Wait for async flush
- await asyncio.sleep(3)
+ await asyncio.wait_for(GLOBAL_LOGGING_WORKER.flush(), timeout=LOGGING_WORKER_DRAIN_TIMEOUT_SECONDS)
+ await generic_logger.flush_queue()
# Assert httpx post was called
mock_post.assert_called_once()
@@ -130,21 +143,23 @@ async def test_generic_api_callback_multiple_logs():
os.environ["GENERIC_LOGGER_ENDPOINT"] = test_endpoint
# Initialize the GenericAPILogger and set the mock
- generic_logger = GenericAPILogger(endpoint=test_endpoint, headers=test_headers, flush_interval=5)
+ generic_logger = GenericAPILogger(endpoint=test_endpoint, headers=test_headers, flush_interval=3600)
generic_logger.async_httpx_client.post = mock_post
litellm.callbacks = [generic_logger]
# Make the completion call
for _ in range(10):
- response = await litellm.acompletion(
- model="gpt-5.5",
- messages=[{"role": "user", "content": "Hello, world!"}],
- mock_response="hi",
- user="test_user",
+ response = await _await_with_spawned_tasks(
+ litellm.acompletion(
+ model="gpt-5.5",
+ messages=[{"role": "user", "content": "Hello, world!"}],
+ mock_response="hi",
+ user="test_user",
+ )
)
- # Wait for async flush
- await asyncio.sleep(6)
+ await asyncio.wait_for(GLOBAL_LOGGING_WORKER.flush(), timeout=LOGGING_WORKER_DRAIN_TIMEOUT_SECONDS)
+ await generic_logger.flush_queue()
# Assert httpx post was called
mock_post.assert_called_once()
@@ -208,7 +223,7 @@ async def test_generic_api_callback_ndjson_format():
generic_logger = GenericAPILogger(
endpoint=test_endpoint,
headers=test_headers,
- flush_interval=1,
+ flush_interval=3600,
log_format="ndjson", # Set NDJSON format
)
generic_logger.async_httpx_client.post = mock_post
@@ -216,15 +231,17 @@ async def test_generic_api_callback_ndjson_format():
# Make multiple completion calls to generate multiple logs
for i in range(3):
- response = await litellm.acompletion(
- model="gpt-5.5",
- messages=[{"role": "user", "content": f"Hello, world! {i}"}],
- mock_response="hi",
- user="test_user",
+ response = await _await_with_spawned_tasks(
+ litellm.acompletion(
+ model="gpt-5.5",
+ messages=[{"role": "user", "content": f"Hello, world! {i}"}],
+ mock_response="hi",
+ user="test_user",
+ )
)
- # Wait for async flush
- await asyncio.sleep(3)
+ await asyncio.wait_for(GLOBAL_LOGGING_WORKER.flush(), timeout=LOGGING_WORKER_DRAIN_TIMEOUT_SECONDS)
+ await generic_logger.flush_queue()
# Assert httpx post was called
mock_post.assert_called_once()
@@ -277,7 +294,7 @@ async def test_generic_api_callback_single_format():
generic_logger = GenericAPILogger(
endpoint=test_endpoint,
headers=test_headers,
- flush_interval=1, # Quick flush to trigger batch send
+ flush_interval=3600,
log_format="single", # Set single format
)
generic_logger.async_httpx_client.post = mock_post
@@ -285,15 +302,17 @@ async def test_generic_api_callback_single_format():
# Make 3 completion calls
for i in range(3):
- response = await litellm.acompletion(
- model="gpt-5.5",
- messages=[{"role": "user", "content": f"Hello, world! {i}"}],
- mock_response="hi",
- user="test_user",
+ response = await _await_with_spawned_tasks(
+ litellm.acompletion(
+ model="gpt-5.5",
+ messages=[{"role": "user", "content": f"Hello, world! {i}"}],
+ mock_response="hi",
+ user="test_user",
+ )
)
- # Wait for async flush
- await asyncio.sleep(3)
+ await asyncio.wait_for(GLOBAL_LOGGING_WORKER.flush(), timeout=LOGGING_WORKER_DRAIN_TIMEOUT_SECONDS)
+ await generic_logger.flush_queue()
# Assert httpx post was called 3 times (once per log in batch)
assert mock_post.call_count == 3, f"Expected 3 calls, got {mock_post.call_count}"
@@ -336,7 +355,7 @@ async def test_generic_api_callback_json_array_format_explicit():
generic_logger = GenericAPILogger(
endpoint=test_endpoint,
headers=test_headers,
- flush_interval=1,
+ flush_interval=3600,
log_format="json_array", # Explicitly set json_array
)
generic_logger.async_httpx_client.post = mock_post
@@ -344,15 +363,17 @@ async def test_generic_api_callback_json_array_format_explicit():
# Make multiple completion calls
for i in range(5):
- response = await litellm.acompletion(
- model="gpt-5.5",
- messages=[{"role": "user", "content": f"Hello, world! {i}"}],
- mock_response="hi",
- user="test_user",
+ response = await _await_with_spawned_tasks(
+ litellm.acompletion(
+ model="gpt-5.5",
+ messages=[{"role": "user", "content": f"Hello, world! {i}"}],
+ mock_response="hi",
+ user="test_user",
+ )
)
- # Wait for async flush
- await asyncio.sleep(3)
+ await asyncio.wait_for(GLOBAL_LOGGING_WORKER.flush(), timeout=LOGGING_WORKER_DRAIN_TIMEOUT_SECONDS)
+ await generic_logger.flush_queue()
# Assert httpx post was called once (batched)
mock_post.assert_called_once()
@@ -386,7 +407,7 @@ async def test_generic_api_callback_sumologic_uses_ndjson():
os.environ["SUMOLOGIC_WEBHOOK_URL"] = "https://collectors.sumologic.com/receiver/v1/http/test123"
# Initialize using callback_name (loads from JSON config)
- generic_logger = GenericAPILogger(callback_name="sumologic", flush_interval=1)
+ generic_logger = GenericAPILogger(callback_name="sumologic", flush_interval=3600)
generic_logger.async_httpx_client.post = mock_post
litellm.callbacks = [generic_logger]
@@ -395,15 +416,17 @@ async def test_generic_api_callback_sumologic_uses_ndjson():
# Make completion calls
for i in range(2):
- await litellm.acompletion(
- model="gpt-5.5",
- messages=[{"role": "user", "content": f"Test {i}"}],
- mock_response="response",
- user="test_user",
+ await _await_with_spawned_tasks(
+ litellm.acompletion(
+ model="gpt-5.5",
+ messages=[{"role": "user", "content": f"Test {i}"}],
+ mock_response="response",
+ user="test_user",
+ )
)
- # Wait for async flush
- await asyncio.sleep(3)
+ await asyncio.wait_for(GLOBAL_LOGGING_WORKER.flush(), timeout=LOGGING_WORKER_DRAIN_TIMEOUT_SECONDS)
+ await generic_logger.flush_queue()
# Assert httpx post was called
mock_post.assert_called_once()
diff --git a/tests/unit/integrations/opik/test_opik.py b/tests/unit/integrations/opik/test_opik.py
index 1aad7079a4a..f7f5e252ed4 100644
--- a/tests/unit/integrations/opik/test_opik.py
+++ b/tests/unit/integrations/opik/test_opik.py
@@ -4,6 +4,7 @@ import logging
import os
import time
from collections.abc import Iterator
+from typing import Awaitable, Final, TypeVar
from unittest.mock import AsyncMock, Mock
import pytest
@@ -15,6 +16,17 @@ from litellm.utils import _invalidate_model_cost_lowercase_map
from tests._vcr_conftest_common import install_live_call_probe, record_vcr_outcome
+_T = TypeVar("_T")
+
+
+async def _await_with_spawned_tasks(call: Awaitable[_T]) -> _T:
+ before: Final = asyncio.all_tasks()
+ result: Final = await call
+ spawned: Final = asyncio.all_tasks() - before - {asyncio.current_task()}
+ await asyncio.wait_for(asyncio.gather(*spawned), timeout=5)
+ return result
+
+
@pytest.fixture(autouse=True)
def isolate_opik_logging_state(monkeypatch: pytest.MonkeyPatch) -> Iterator[None]:
original_level = verbose_logger.level
@@ -54,27 +66,31 @@ async def test_opik_logging_http_request():
]
for _ in range(5):
- await litellm.acompletion(
- model="gpt-3.5-turbo",
- messages=[{"role": "user", "content": "Test message"}],
- max_tokens=10,
- temperature=0.2,
- mock_response="This is a mock response",
+ await _await_with_spawned_tasks(
+ litellm.acompletion(
+ model="gpt-3.5-turbo",
+ messages=[{"role": "user", "content": "Test message"}],
+ max_tokens=10,
+ temperature=0.2,
+ mock_response="This is a mock response",
+ )
)
- await asyncio.sleep(1)
+ await asyncio.wait_for(GLOBAL_LOGGING_WORKER.flush(), timeout=10)
assert opik_batch_calls() == [], "events below batch_size must stay queued"
assert len(test_opik_logger.log_queue) == 10
for _ in range(3):
- await litellm.acompletion(
- model="gpt-3.5-turbo",
- messages=[{"role": "user", "content": "Test message"}],
- max_tokens=10,
- temperature=0.2,
- mock_response="This is a mock response",
+ await _await_with_spawned_tasks(
+ litellm.acompletion(
+ model="gpt-3.5-turbo",
+ messages=[{"role": "user", "content": "Test message"}],
+ max_tokens=10,
+ temperature=0.2,
+ mock_response="This is a mock response",
+ )
)
- await asyncio.sleep(1)
+ await asyncio.wait_for(GLOBAL_LOGGING_WORKER.flush(), timeout=10)
assert opik_batch_calls(), "crossing batch_size must flush the queue"
events_left_over_after_the_size_triggered_flush = len(test_opik_logger.log_queue)
diff --git a/tests/unit/integrations/otel/test_otel_v2_destinations.py b/tests/unit/integrations/otel/test_otel_v2_destinations.py
index 068b2aa2e2e..c7a057cca5c 100644
--- a/tests/unit/integrations/otel/test_otel_v2_destinations.py
+++ b/tests/unit/integrations/otel/test_otel_v2_destinations.py
@@ -2,6 +2,7 @@
import asyncio
import contextvars
+import threading
import time
from base64 import b64encode
from collections.abc import Mapping
@@ -3496,9 +3497,11 @@ class TestEvictionSafety:
def __init__(self):
super().__init__(InMemorySpanExporter())
self.shutdown_calls = 0
+ self.closed = threading.Event()
def shutdown(self):
self.shutdown_calls += 1
+ self.closed.set()
def _fan_out(self):
built = []
@@ -3540,7 +3543,7 @@ class TestEvictionSafety:
assert id(held) in fan_out._retired
fan_out._release(held)
- self._settle(fan_out, held)
+ assert held.closed.wait(timeout=5)
assert held.shutdown_calls == 1
@@ -3554,7 +3557,7 @@ class TestEvictionSafety:
fan_out._release(fan_out._acquire(self._dest(index)))
fan_out._release(fan_out._acquire(self._dest(0)))
fan_out._release(fan_out._acquire(self._dest(_MAX_CACHED_DESTINATION_PROCESSORS)))
- self._settle(fan_out, built[1])
+ assert built[1].closed.wait(timeout=5)
assert built[1].shutdown_calls == 1
assert built[0].shutdown_calls == 0, "the destination used most recently was the one shed"
@@ -3566,7 +3569,7 @@ class TestEvictionSafety:
for index in range(_MAX_CACHED_DESTINATION_PROCESSORS + 1):
fan_out._acquire(self._dest(index))
fan_out._release(built[-1])
- self._settle(fan_out, built[0])
+ assert built[0].closed.wait(timeout=5)
assert built[0].shutdown_calls == 1
assert len(fan_out._processors) == _MAX_CACHED_DESTINATION_PROCESSORS
@@ -3577,9 +3580,11 @@ class TestEvictionSafety:
every other tenant's spans."""
from litellm.integrations.otel.plumbing.providers import _MAX_CACHED_DESTINATION_PROCESSORS
+ release = threading.Event()
+
class Slow(self.Recording):
def shutdown(self):
- time.sleep(3)
+ release.wait(timeout=10)
super().shutdown()
built = []
@@ -3589,12 +3594,14 @@ class TestEvictionSafety:
return built[-1]
fan_out = TenantFanOutSpanProcessor(processor_factory=factory)
- started = time.monotonic()
- for index in range(_MAX_CACHED_DESTINATION_PROCESSORS + 1):
- fan_out._acquire(self._dest(index))
- fan_out._release(built[-1])
+ try:
+ for index in range(_MAX_CACHED_DESTINATION_PROCESSORS + 1):
+ fan_out._acquire(self._dest(index))
+ fan_out._release(built[-1])
- assert time.monotonic() - started < 2
+ assert not built[0].closed.is_set(), "the shed processor was closed inline on the export path"
+ finally:
+ release.set()
def test_shedding_many_processors_does_not_spawn_a_thread_each(self):
"""A tenant that cycles its destination config sheds a processor per request,
@@ -3970,11 +3977,7 @@ class TestEvictionSafety:
fan_out.shutdown()
fan_out._drain.submit(stray)
- for _ in range(500):
- if stray.shutdown_calls:
- break
- time.sleep(0.02)
-
+ assert stray.closed.wait(timeout=5)
assert stray.shutdown_calls == 1
def test_releasing_a_straggler_after_shutdown_does_not_block_the_span_thread(self):
@@ -4036,7 +4039,7 @@ class TestEvictionSafety:
assert held.shutdown_calls == 0
fan_out._release(held)
- self._settle(fan_out, held)
+ assert held.closed.wait(timeout=5)
assert held.shutdown_calls == 1
@@ -4153,10 +4156,7 @@ class TestEvictionSafety:
close_returned.set()
submitter.join(timeout=5)
closer.join(timeout=5)
- for _ in range(250):
- if submitted.shutdown_calls:
- break
- time.sleep(0.02)
+ assert submitted.closed.wait(timeout=5), "a processor was queued behind the sentinels and never closed"
assert submitted.shutdown_calls == 1, "a processor was queued behind the sentinels and never closed"
@@ -4175,7 +4175,7 @@ class TestEvictionSafety:
assert held.shutdown_calls == 0
fan_out._release(held)
- self._settle(fan_out, held)
+ assert held.closed.wait(timeout=5)
assert held.shutdown_calls == 1
diff --git a/tests/unit/integrations/test_mlflow.py b/tests/unit/integrations/test_mlflow.py
index f828c34a9ff..058d0ae885d 100644
--- a/tests/unit/integrations/test_mlflow.py
+++ b/tests/unit/integrations/test_mlflow.py
@@ -1,5 +1,6 @@
import asyncio
import json
+import threading
from datetime import datetime
from unittest.mock import MagicMock, patch
@@ -19,7 +20,13 @@ async def test_mlflow_logging_functionality():
mock_span = MagicMock()
mock_span.parent_id = None # Simulate root trace
mock_span.request_id = "test_trace_id"
- mock_client.start_trace.return_value = mock_span
+ trace_started = threading.Event()
+
+ def start_trace(*args: object, **kwargs: object) -> MagicMock:
+ trace_started.set()
+ return mock_span
+
+ mock_client.start_trace.side_effect = start_trace
# Mock all MLflow-related imports to avoid requiring MLflow as a dependency
mock_mlflow_tracking = MagicMock()
@@ -67,8 +74,7 @@ async def test_mlflow_logging_functionality():
},
)
- # Allow time for async processing
- await asyncio.sleep(1)
+ assert await asyncio.to_thread(trace_started.wait, 5)
# Verify start_trace was called with tags parameter
assert mock_client.start_trace.called, "start_trace should have been called"
diff --git a/tests/unit/integrations/test_prometheus_metrics_endpoint.py b/tests/unit/integrations/test_prometheus_metrics_endpoint.py
index f0e6495ba22..a41508661d6 100644
--- a/tests/unit/integrations/test_prometheus_metrics_endpoint.py
+++ b/tests/unit/integrations/test_prometheus_metrics_endpoint.py
@@ -59,22 +59,18 @@ async def _scrape(client: httpx.AsyncClient, headers: Mapping[str, str] | None =
@pytest.mark.asyncio
async def test_render_does_not_block_the_event_loop():
- ticks: Final[list[float]] = [] # mutable-ok: records loop wakeups while the scrape is in flight
-
- async def ticker() -> None:
- while True:
- await asyncio.sleep(0.01)
- ticks.append(time.monotonic())
-
- ticker_task: Final = asyncio.create_task(ticker())
- async with _client(_registry_with(_SlowCollector(block_seconds=0.5))) as client:
+ collector: Final = _GatedCollector()
+ async with _client(_registry_with(collector)) as client:
try:
- response: Final = await _scrape(client)
+ scrape: Final = asyncio.create_task(_scrape(client))
+ assert await asyncio.to_thread(collector.started.wait, _GATE_TIMEOUT_SECONDS), "render never started"
+ assert not collector.finished.is_set(), "event loop was blocked while the registry was rendered"
+ collector.release.set()
+ response: Final = await scrape
finally:
- ticker_task.cancel()
+ collector.release.set()
- assert b"slow_metric" in response.content
- assert len(ticks) > 5, "event loop was blocked while the registry was rendered"
+ assert b"gated_metric" in response.content
@pytest.mark.asyncio
@@ -170,6 +166,7 @@ class _GatedCollector(Collector):
def __init__(self) -> None:
self.started = threading.Event()
self.release = threading.Event()
+ self.finished = threading.Event()
self._lock = threading.Lock()
self.collect_calls = 0
@@ -178,6 +175,7 @@ class _GatedCollector(Collector):
self.collect_calls += 1
self.started.set()
self.release.wait(timeout=_GATE_TIMEOUT_SECONDS)
+ self.finished.set()
family: Final = GaugeMetricFamily("gated_metric", "gated")
family.add_metric((), 1.0)
yield family
diff --git a/tests/unit/integrations/test_s3_v2.py b/tests/unit/integrations/test_s3_v2.py
index 8e9a8982cd9..8449eae7bf4 100644
--- a/tests/unit/integrations/test_s3_v2.py
+++ b/tests/unit/integrations/test_s3_v2.py
@@ -4,6 +4,7 @@ import json
import re
import sys
import textwrap
+import threading
import time
import uuid
from collections.abc import AsyncIterator, Awaitable, Callable, Coroutine
@@ -5291,12 +5292,15 @@ class _FakeS3Paginator:
class _FakeS3Client:
def __init__(self):
self.objects = defaultdict(dict)
+ self.object_written = threading.Event()
def clear(self):
self.objects.clear()
+ self.object_written.clear()
def put_object(self, Bucket, Key, Body, **_kwargs):
self.objects[Bucket][Key] = Body
+ self.object_written.set()
return {"ResponseMetadata": {"HTTPStatusCode": 200}}
def delete_object(self, Bucket, Key):
@@ -5363,7 +5367,7 @@ async def test_basic_s3_logging(sync_mode, streaming):
response_id = chunk.id
else:
response_id = response.id
- time.sleep(2)
+ assert _FAKE_S3_CLIENT.object_written.wait(timeout=5)
else:
response = await litellm.acompletion(
model="gpt-5-mini",
@@ -5376,7 +5380,7 @@ async def test_basic_s3_logging(sync_mode, streaming):
response_id = chunk.id
else:
response_id = response.id
- await asyncio.sleep(2)
+ assert await asyncio.to_thread(_FAKE_S3_CLIENT.object_written.wait, 5)
total_objects, all_s3_keys = list_all_s3_objects("load-testing-oct")
@@ -5411,9 +5415,11 @@ async def test_basic_s3_v2_logging(streaming):
litellm.callbacks = [s3_v2_logger]
uploaded_keys: list = []
+ uploaded = asyncio.Event()
async def mock_upload(batch_logging_element):
uploaded_keys.append(batch_logging_element.s3_object_key)
+ uploaded.set()
s3_v2_logger.async_upload_data_to_s3 = mock_upload
@@ -5431,7 +5437,7 @@ async def test_basic_s3_v2_logging(streaming):
else:
response_id = response.id
- await asyncio.sleep(5)
+ assert await asyncio.wait_for(uploaded.wait(), timeout=5)
assert len(uploaded_keys) > 0, "S3 upload was never called"
assert any(response_id in key for key in uploaded_keys), (
@@ -5465,6 +5471,7 @@ async def test_basic_s3_v2_logging_failure():
s3_v2_logger.async_httpx_client.put.return_value = mock_response
upload_called = False
+ uploaded = asyncio.Event()
async def mock_upload(batch_logging_element):
nonlocal upload_called
@@ -5474,6 +5481,7 @@ async def test_basic_s3_v2_logging_failure():
data = '{"model": "gpt-5-mini"}'
await s3_v2_logger.async_httpx_client.put(url=url, headers=headers, data=data)
+ uploaded.set()
s3_v2_logger.async_upload_data_to_s3 = mock_upload
@@ -5496,7 +5504,7 @@ async def test_basic_s3_v2_logging_failure():
except Exception:
pass
- await asyncio.sleep(5)
+ assert await asyncio.wait_for(uploaded.wait(), timeout=5)
assert upload_called, "S3 upload method was not called"
diff --git a/tests/unit/interactions/test_interactions_streaming_iterator.py b/tests/unit/interactions/test_interactions_streaming_iterator.py
index 9f88b2c9611..c52ab36deaa 100644
--- a/tests/unit/interactions/test_interactions_streaming_iterator.py
+++ b/tests/unit/interactions/test_interactions_streaming_iterator.py
@@ -90,8 +90,10 @@ async def test_custom_logger_only_never_submits_sync_success_handler(monkeypatch
)
iterator.completed_response = InteractionsAPIStreamingResponse()
+ existing_tasks = asyncio.all_tasks()
iterator._handle_logging_completed_response()
- await asyncio.sleep(0.5)
+ spawned_tasks = asyncio.all_tasks() - existing_tasks
+ await asyncio.wait_for(asyncio.gather(*spawned_tasks, return_exceptions=True), timeout=5)
assert recorder.async_hook_fired is True
assert recording_executor.submitted_for(logging_obj) == []
diff --git a/tests/unit/litellm_core_utils/test_streaming_handler.py b/tests/unit/litellm_core_utils/test_streaming_handler.py
index 01fae0958e6..b60544e6606 100644
--- a/tests/unit/litellm_core_utils/test_streaming_handler.py
+++ b/tests/unit/litellm_core_utils/test_streaming_handler.py
@@ -1,5 +1,6 @@
import asyncio
import json
+import threading
import time
from typing import Final, NoReturn, Optional
from unittest.mock import AsyncMock, MagicMock, Mock, patch
@@ -548,9 +549,11 @@ async def test_streaming_with_usage_and_logging(sync_mode: bool):
mock_callback, "async_log_stream_event"
) as mock_async_log_stream_event,
):
+ existing_tasks = asyncio.all_tasks()
await test_streaming_handler_with_usage(
sync_mode=sync_mode, final_usage_block=final_usage_block
)
+ spawned_tasks = asyncio.all_tasks() - existing_tasks
if sync_mode:
time.sleep(1)
mock_log_success_event.assert_called_once()
@@ -560,7 +563,7 @@ async def test_streaming_with_usage_and_logging(sync_mode: bool):
== final_usage_block
)
else:
- await asyncio.sleep(1)
+ await asyncio.wait_for(asyncio.gather(*spawned_tasks, return_exceptions=True), timeout=5)
mock_async_log_success_event.assert_called_once()
# mock_async_log_stream_event.assert_called()
assert (
@@ -750,10 +753,12 @@ async def test_streaming_completion_start_time(logging_obj: Logging):
logging_obj=logging_obj,
)
+ existing_tasks = asyncio.all_tasks()
async for chunk in response:
print(chunk)
- await asyncio.sleep(2)
+ spawned_tasks = asyncio.all_tasks() - existing_tasks
+ await asyncio.wait_for(asyncio.gather(*spawned_tasks, return_exceptions=True), timeout=5)
assert logging_obj.model_call_details["completion_start_time"] is not None
assert (
@@ -2952,15 +2957,19 @@ async def test_custom_stream_wrapper_anext_does_not_block_event_loop_for_sync_it
"""
class BlockingIterator:
- def __init__(self, chunks, delay_s: float):
+ def __init__(self, chunks: list[ModelResponseStream]) -> None:
self._it = iter(chunks)
- self._delay_s = delay_s
+ self.entered = threading.Event()
+ self.release = threading.Event()
+ self.returned = threading.Event()
- def __iter__(self):
+ def __iter__(self) -> "BlockingIterator":
return self
- def __next__(self):
- time.sleep(self._delay_s) # simulate blocking I/O
+ def __next__(self) -> ModelResponseStream:
+ self.entered.set()
+ self.release.wait(timeout=5)
+ self.returned.set()
return next(self._it)
test_chunk = ModelResponseStream(
@@ -2988,34 +2997,23 @@ async def test_custom_stream_wrapper_anext_does_not_block_event_loop_for_sync_it
usage=None,
)
- # Delay is intentionally > the wait_for timeout used to detect event loop blocking.
+ blocking_iterator = BlockingIterator([test_chunk])
wrapper = CustomStreamWrapper(
- completion_stream=BlockingIterator([test_chunk], delay_s=0.3),
+ completion_stream=blocking_iterator,
model="test-model",
logging_obj=logging_obj,
custom_llm_provider="cached_response",
)
- tick_event = asyncio.Event()
-
- async def background_tick():
- await asyncio.sleep(0.05)
- tick_event.set()
-
- # Run the two coroutines concurrently and measure wall time.
- # If __anext__ blocks the event loop, background_tick can't run and the gather
- # takes the full 0.3 s delay; if non-blocking both finish within ~0.35 s total.
- start = asyncio.get_event_loop().time()
-
- out, _ = await asyncio.gather(
- wrapper.__anext__(),
- background_tick(),
- )
+ anext_task = asyncio.create_task(wrapper.__anext__())
+ try:
+ assert await asyncio.to_thread(blocking_iterator.entered.wait, 5)
+ assert not blocking_iterator.returned.is_set(), "Event loop was blocked by the sync iterator"
+ finally:
+ blocking_iterator.release.set()
- elapsed = asyncio.get_event_loop().time() - start
+ out = await anext_task
assert isinstance(out, ModelResponseStream)
- # background_tick sleeps 0.05 s; total must finish well under 2 × 0.3 s
- assert elapsed < 0.5, f"Event loop was likely blocked (elapsed={elapsed:.2f}s)"
@pytest.mark.asyncio
diff --git a/tests/unit/litellm_core_utils/test_url_utils.py b/tests/unit/litellm_core_utils/test_url_utils.py
index fccdc1a2a0a..46bb91959c0 100644
--- a/tests/unit/litellm_core_utils/test_url_utils.py
+++ b/tests/unit/litellm_core_utils/test_url_utils.py
@@ -1,7 +1,6 @@
import asyncio
import socket
import threading
-import time
import httpx
import pytest
@@ -542,31 +541,33 @@ def test_assert_same_origin_error_message_does_not_leak_hostnames():
async def test_async_safe_get_resolves_dns_off_the_event_loop(monkeypatch):
+ loop = asyncio.get_running_loop()
loop_thread = threading.current_thread()
resolver_threads = []
+ resolver_blocked = asyncio.Event()
+ loop_ran_while_resolver_blocked = threading.Event()
+ released_by_the_loop = []
- def slow_getaddrinfo(host, port, *args, **kwargs):
+ def blocking_getaddrinfo(host, port, *args, **kwargs):
resolver_threads.append(threading.current_thread())
- time.sleep(0.4)
+ loop.call_soon_threadsafe(resolver_blocked.set)
+ released_by_the_loop.append(loop_ran_while_resolver_blocked.wait(timeout=5))
return [(socket.AF_INET, socket.SOCK_STREAM, 6, "", ("93.184.216.34", port or 443))]
- monkeypatch.setattr(url_utils.socket, "getaddrinfo", slow_getaddrinfo)
+ monkeypatch.setattr(url_utils.socket, "getaddrinfo", blocking_getaddrinfo)
class FakeClient:
async def get(self, url, **kwargs):
return httpx.Response(200, request=httpx.Request("GET", url))
- ticks = [time.perf_counter()]
+ async def release_resolver_from_the_loop() -> None:
+ await resolver_blocked.wait()
+ loop_ran_while_resolver_blocked.set()
- async def heartbeat():
- while True:
- await asyncio.sleep(0.01)
- ticks.append(time.perf_counter())
-
- beating = asyncio.create_task(heartbeat())
+ releaser = asyncio.create_task(release_resolver_from_the_loop())
response = await url_utils.async_safe_get(FakeClient(), "https://img.example/a.png")
- beating.cancel()
+ await asyncio.wait_for(releaser, timeout=5)
assert response.status_code == 200
assert resolver_threads and all(thread is not loop_thread for thread in resolver_threads)
- assert max(b - a for a, b in zip(ticks, ticks[1:])) < 0.2
+ assert released_by_the_loop and all(released_by_the_loop)
diff --git a/tests/unit/llms/vertex_ai/test_vertex_gemini_gcs_uri_mime.py b/tests/unit/llms/vertex_ai/test_vertex_gemini_gcs_uri_mime.py
index 3906528ae2e..b60da3a7548 100644
--- a/tests/unit/llms/vertex_ai/test_vertex_gemini_gcs_uri_mime.py
+++ b/tests/unit/llms/vertex_ai/test_vertex_gemini_gcs_uri_mime.py
@@ -3,7 +3,7 @@
Split from test_vertex.py to satisfy CI per-file size limits.
"""
import asyncio
-import time
+import threading
from dotenv import load_dotenv
@@ -265,8 +265,10 @@ def test_async_transform_request_body_offloads_extensionless_gs_not_plain_text()
}
]
- def slow_http_get(*args, **kwargs):
- time.sleep(0.5)
+ http_get_released_by_the_loop = threading.Event()
+ released_while_blocked = []
+
+ def http_get_response() -> MagicMock:
response = MagicMock()
response.is_error = False
response.status_code = 200
@@ -280,14 +282,22 @@ def test_async_transform_request_body_offloads_extensionless_gs_not_plain_text()
mock_v = MagicMock()
mock_v.get_access_token.return_value = ("token", "project")
mock_http = MagicMock()
- mock_http.get.side_effect = slow_http_get
- async def run_scenario() -> float:
- async def concurrent_sleep() -> float:
- start = time.monotonic()
- await asyncio.sleep(0.05)
- return time.monotonic() - start
+ async def run_scenario() -> None:
+ loop = asyncio.get_running_loop()
+ http_get_blocked = asyncio.Event()
+
+ def blocking_http_get(*args: object, **kwargs: object) -> MagicMock:
+ loop.call_soon_threadsafe(http_get_blocked.set)
+ released_while_blocked.append(http_get_released_by_the_loop.wait(timeout=5))
+ return http_get_response()
+
+ async def release_http_get_from_the_loop() -> None:
+ await http_get_blocked.wait()
+ http_get_released_by_the_loop.set()
+ mock_http.get.side_effect = blocking_http_get
+ releaser = asyncio.create_task(release_http_get_from_the_loop())
task = asyncio.create_task(
gemini_transformation.async_transform_request_body(
gemini_api_key=None,
@@ -306,9 +316,8 @@ def test_async_transform_request_body_offloads_extensionless_gs_not_plain_text()
vertex_auth_header=None,
)
)
- elapsed = await concurrent_sleep()
await task
- return elapsed
+ await asyncio.wait_for(releaser, timeout=5)
with (
patch.object(gemini_transformation, "_GCS_METADATA_VERTEX_BASE", mock_v),
@@ -322,11 +331,10 @@ def test_async_transform_request_body_offloads_extensionless_gs_not_plain_text()
new=fake_check_and_create_cache,
),
):
- sleep_elapsed = asyncio.run(run_scenario())
+ asyncio.run(run_scenario())
- assert sleep_elapsed < 0.4, (
- f"Event loop blocked for {sleep_elapsed:.3f}s; "
- "async_transform_request_body did not offload sync GCS metadata"
+ assert released_while_blocked and all(released_while_blocked), (
+ "Event loop blocked; async_transform_request_body did not offload sync GCS metadata"
)
async def fake_cache2(self, **kwargs):
diff --git a/tests/unit/llms/vertex_ai/test_vertex_llm_base.py b/tests/unit/llms/vertex_ai/test_vertex_llm_base.py
index 514728137cf..b65e0e1d59c 100644
--- a/tests/unit/llms/vertex_ai/test_vertex_llm_base.py
+++ b/tests/unit/llms/vertex_ai/test_vertex_llm_base.py
@@ -1874,8 +1874,8 @@ class TestVertexBase:
# Should return the current (still usable) token immediately
assert token == "near-expiry-token"
- # Let the background refresh task run
- await asyncio.sleep(0.05)
+ background_refreshes = tuple(vertex_base._background_refresh_tasks.values())
+ await asyncio.wait_for(asyncio.gather(*background_refreshes), timeout=5)
assert mock_refresh.called, "Background refresh should have been triggered"
@@ -1982,8 +1982,8 @@ class TestVertexBase:
custom_llm_provider="vertex_ai",
)
- # Allow the background task to complete.
- await asyncio.sleep(0.1)
+ background_refreshes = tuple(vertex_base._background_refresh_tasks.values())
+ await asyncio.wait_for(asyncio.gather(*background_refreshes), timeout=5)
# After completion the entry should have been removed by the done-callback.
assert len(vertex_base._background_refresh_tasks) == 0, (
@@ -2002,6 +2002,7 @@ class TestVertexBase:
vertex_base = VertexBase()
num_keys = 20
+ background_refreshes: list[asyncio.Task] = []
for i in range(num_keys):
mock_creds = MagicMock()
@@ -2032,9 +2033,9 @@ class TestVertexBase:
project_id=f"project-{i}",
custom_llm_provider="vertex_ai",
)
+ background_refreshes.extend(vertex_base._background_refresh_tasks.values())
- # Let all background tasks finish.
- await asyncio.sleep(0.1)
+ await asyncio.wait_for(asyncio.gather(*set(background_refreshes)), timeout=5)
assert len(vertex_base._background_refresh_tasks) == 0, (
f"Expected 0 tasks after all refreshes completed, "
diff --git a/tests/unit/proxy/common_utils/test_auth_cache_invalidation_pubsub.py b/tests/unit/proxy/common_utils/test_auth_cache_invalidation_pubsub.py
index 34d9741bcc0..ce0e2f77e87 100644
--- a/tests/unit/proxy/common_utils/test_auth_cache_invalidation_pubsub.py
+++ b/tests/unit/proxy/common_utils/test_auth_cache_invalidation_pubsub.py
@@ -60,11 +60,14 @@ class _QueuePubSub:
self.queue.put_nowait(message)
self.subscribed_channels: list[str] = []
self.closed = False
+ self.drained = asyncio.Event()
async def subscribe(self, *channels: str) -> None:
self.subscribed_channels.extend(channels)
async def get_message(self, *, ignore_subscribe_messages: bool, timeout: float) -> object | None:
+ if self.queue.empty():
+ self.drained.set()
try:
return await asyncio.wait_for(self.queue.get(), timeout)
except asyncio.TimeoutError:
@@ -155,10 +158,7 @@ async def test_subscriber_deletes_local_cache_entry_on_message() -> None:
)
subscriber.start()
try:
- for _ in range(200):
- if cache.in_memory_cache.get_cache("project_id:p-1") is None:
- break
- await asyncio.sleep(0.01)
+ assert await asyncio.wait_for(pubsub.drained.wait(), timeout=5)
finally:
await subscriber.stop()
@@ -185,10 +185,7 @@ async def test_subscriber_deletes_key_object_partition_entry_on_message() -> Non
)
subscriber.start()
try:
- for _ in range(200):
- if cache.get_cache(hashed_token, model_type=UserAPIKeyAuth) is None:
- break
- await asyncio.sleep(0.01)
+ assert await asyncio.wait_for(pubsub.drained.wait(), timeout=5)
finally:
await subscriber.stop()
@@ -216,10 +213,7 @@ async def test_subscriber_deletes_additional_in_memory_cache_entry_on_message()
)
subscriber.start()
try:
- for _ in range(200):
- if spend_counter_in_memory_cache.get_cache("spend:team_member:u-1:t-1") is None:
- break
- await asyncio.sleep(0.01)
+ assert await asyncio.wait_for(pubsub.drained.wait(), timeout=5)
finally:
await subscriber.stop()
diff --git a/tests/unit/proxy/guardrails/guardrail_hooks/test_custom_code_bounded_execution.py b/tests/unit/proxy/guardrails/guardrail_hooks/test_custom_code_bounded_execution.py
index dc3d3c8cf91..9114d811c57 100644
--- a/tests/unit/proxy/guardrails/guardrail_hooks/test_custom_code_bounded_execution.py
+++ b/tests/unit/proxy/guardrails/guardrail_hooks/test_custom_code_bounded_execution.py
@@ -17,6 +17,12 @@ def _worker_threads() -> list[str]:
return [t.name for t in threading.enumerate() if t.name.startswith("guardrail-code:")]
+def _join_worker_threads() -> None:
+ for thread in threading.enumerate():
+ if thread.name.startswith("guardrail-code:"):
+ thread.join(timeout=5)
+
+
def _spin_forever() -> None:
n = 0
while True:
@@ -82,7 +88,7 @@ def test_call_with_timeout_interrupts_a_busy_loop_and_reclaims_the_thread(fn):
assert exc_info.value.timeout == 0.2
assert time.monotonic() - started < 1.5
- time.sleep(0.2)
+ _join_worker_threads()
assert _worker_threads() == []
@@ -105,7 +111,7 @@ async def test_call_off_loop_with_timeout_keeps_the_loop_running_and_stops_the_w
ticker.cancel()
assert ticks >= 5
- await asyncio.sleep(0.2)
+ await asyncio.to_thread(_join_worker_threads)
assert _worker_threads() == []
@@ -142,22 +148,30 @@ async def test_await_with_timeout_abandons_a_coroutine_that_never_stops_swallowi
@pytest.mark.asyncio
async def test_call_off_loop_with_timeout_stops_the_worker_when_the_caller_is_cancelled():
- waiting = asyncio.create_task(call_off_loop_with_timeout(_spin_forever, 30.0, label="spin"))
- await asyncio.sleep(0.1)
+ spinning = threading.Event()
+
+ def signal_then_spin() -> None:
+ spinning.set()
+ _spin_forever()
+
+ waiting = asyncio.create_task(call_off_loop_with_timeout(signal_then_spin, 30.0, label="spin"))
+ assert await asyncio.to_thread(spinning.wait, 5)
waiting.cancel()
with pytest.raises(asyncio.CancelledError):
await waiting
- await asyncio.sleep(0.3)
+ await asyncio.to_thread(_join_worker_threads)
assert _worker_threads() == []
@pytest.mark.asyncio
async def test_await_with_timeout_cancels_the_code_when_the_caller_is_cancelled():
+ started = asyncio.Event()
interrupted = asyncio.Event()
async def sleep_until_cancelled() -> None:
+ started.set()
try:
await asyncio.sleep(30)
except asyncio.CancelledError:
@@ -165,10 +179,10 @@ async def test_await_with_timeout_cancels_the_code_when_the_caller_is_cancelled(
raise
waiting = asyncio.create_task(await_with_timeout(sleep_until_cancelled(), 30.0, label="sleep"))
- await asyncio.sleep(0.1)
+ assert await asyncio.wait_for(started.wait(), timeout=5)
waiting.cancel()
with pytest.raises(asyncio.CancelledError):
await waiting
- await asyncio.wait_for(interrupted.wait(), timeout=1.0)
+ assert await asyncio.wait_for(interrupted.wait(), timeout=5)
diff --git a/tests/unit/proxy/test_proxy_server_endpoints_and_startup.py b/tests/unit/proxy/test_proxy_server_endpoints_and_startup.py
index 920f9d90bb8..b981e8282bf 100644
--- a/tests/unit/proxy/test_proxy_server_endpoints_and_startup.py
+++ b/tests/unit/proxy/test_proxy_server_endpoints_and_startup.py
@@ -3422,26 +3422,27 @@ async def test_add_proxy_budget_to_db_only_creates_user_no_keys(monkeypatch: pyt
litellm_proxy_budget_name = "litellm-proxy-budget"
- # Mock generate_key_helper_fn to capture its call arguments
- mock_generate_key_helper = AsyncMock(
- return_value={
+ generate_key_helper_called: Final = asyncio.Event()
+
+ async def _record_generate_key_helper(*args: object, **kwargs: object) -> dict[str, object]:
+ generate_key_helper_called.set()
+ return {
"user_id": litellm_proxy_budget_name,
"max_budget": 100.0,
"budget_duration": "30d",
"spend": 0,
"models": [],
}
- )
+
+ # Mock generate_key_helper_fn to capture its call arguments
+ mock_generate_key_helper = AsyncMock(side_effect=_record_generate_key_helper)
# Patch generate_key_helper_fn in proxy_server where it's being called from
with patch("litellm.proxy.proxy_server.generate_key_helper_fn", mock_generate_key_helper):
# Call the function under test
ProxyStartupEvent._add_proxy_budget_to_db()
- # Allow async task to complete
- import asyncio
-
- await asyncio.sleep(0.1)
+ assert await asyncio.wait_for(generate_key_helper_called.wait(), timeout=5)
# Verify that generate_key_helper_fn was called
mock_generate_key_helper.assert_called_once()
@@ -6305,8 +6306,15 @@ async def test_tag_cache_update_called():
"spend": 10.0,
}
+ set_cache_called: Final = asyncio.Event()
+
+ async def _record_set_cache(*args: object, **kwargs: object) -> None:
+ set_cache_called.set()
+
with patch.object(cache, "async_batch_get_cache", new=AsyncMock(return_value=[mock_tag_obj])) as mock_get_cache:
- with patch.object(cache, "async_set_cache_pipeline", new=AsyncMock()) as mock_set_cache:
+ with patch.object(
+ cache, "async_set_cache_pipeline", new=AsyncMock(side_effect=_record_set_cache)
+ ) as mock_set_cache:
await litellm.proxy.proxy_server.update_cache(
token=None,
user_id=None,
@@ -6317,7 +6325,7 @@ async def test_tag_cache_update_called():
tags=["test-tag"],
)
- await asyncio.sleep(0.1)
+ assert await asyncio.wait_for(set_cache_called.wait(), timeout=5)
mock_get_cache.assert_awaited_once_with(keys=["tag:test-tag"], parent_otel_span=None, throttle_redis=False)
mock_set_cache.assert_awaited_once()
@@ -6353,10 +6361,17 @@ async def test_tag_cache_update_multiple_tags():
async def mock_get_cache_side_effect(keys, **kwargs):
return [{"tag:tag1": mock_tag1_obj, "tag:tag2": mock_tag2_obj}.get(key) for key in keys]
+ set_cache_called: Final = asyncio.Event()
+
+ async def _record_set_cache(*args: object, **kwargs: object) -> None:
+ set_cache_called.set()
+
with patch.object(
cache, "async_batch_get_cache", new=AsyncMock(side_effect=mock_get_cache_side_effect)
) as mock_get_cache:
- with patch.object(cache, "async_set_cache_pipeline", new=AsyncMock()) as mock_set_cache:
+ with patch.object(
+ cache, "async_set_cache_pipeline", new=AsyncMock(side_effect=_record_set_cache)
+ ) as mock_set_cache:
await litellm.proxy.proxy_server.update_cache(
token=None,
user_id=None,
@@ -6367,7 +6382,7 @@ async def test_tag_cache_update_multiple_tags():
tags=["tag1", "tag2"],
)
- await asyncio.sleep(0.1)
+ assert await asyncio.wait_for(set_cache_called.wait(), timeout=5)
mock_get_cache.assert_awaited_once_with(keys=["tag:tag1", "tag:tag2"], parent_otel_span=None, throttle_redis=False)
mock_set_cache.assert_awaited_once()
@@ -6397,13 +6412,20 @@ async def test_update_cache_pipeline_honors_user_api_key_cache_ttl():
original_cache = litellm.proxy.proxy_server.user_api_key_cache
cache = DualCache(default_in_memory_ttl=300)
setattr(litellm.proxy.proxy_server, "user_api_key_cache", cache)
+ set_cache_called: Final = asyncio.Event()
+
+ async def _record_set_cache(*args: object, **kwargs: object) -> None:
+ set_cache_called.set()
+
try:
with patch.object(
cache,
"async_batch_get_cache",
new=AsyncMock(return_value=[{"tag_name": "active-tag", "spend": 1.0}]),
):
- with patch.object(cache, "async_set_cache_pipeline", new=AsyncMock()) as mock_set_cache:
+ with patch.object(
+ cache, "async_set_cache_pipeline", new=AsyncMock(side_effect=_record_set_cache)
+ ) as mock_set_cache:
await litellm.proxy.proxy_server.update_cache(
token=None,
user_id=None,
@@ -6414,7 +6436,7 @@ async def test_update_cache_pipeline_honors_user_api_key_cache_ttl():
tags=["active-tag"],
)
- await asyncio.sleep(0.1)
+ assert await asyncio.wait_for(set_cache_called.wait(), timeout=5)
mock_set_cache.assert_awaited_once()
assert mock_set_cache.call_args.kwargs["ttl"] == 300
diff --git a/tests/unit/responses/test_responses_streaming_iterator.py b/tests/unit/responses/test_responses_streaming_iterator.py
index 9ba7dfcaa80..0419fce8ec2 100644
--- a/tests/unit/responses/test_responses_streaming_iterator.py
+++ b/tests/unit/responses/test_responses_streaming_iterator.py
@@ -119,6 +119,11 @@ def _make_iterator(logging_obj: LitellmLogging) -> ResponsesAPIStreamingIterator
return iterator
+async def _await_tasks_spawned_since(existing: set["asyncio.Task[object]"]) -> None:
+ spawned = asyncio.all_tasks() - existing
+ await asyncio.wait_for(asyncio.gather(*spawned, return_exceptions=True), timeout=5)
+
+
@pytest.mark.asyncio
async def test_custom_logger_only_never_submits_sync_success_handler(recording_executor):
recorder = RecordingCustomLogger()
@@ -128,8 +133,9 @@ async def test_custom_logger_only_never_submits_sync_success_handler(recording_e
logging_obj = _make_logging_obj()
iterator = _make_iterator(logging_obj)
+ existing_tasks = asyncio.all_tasks()
iterator._log_completed_response(is_async=True)
- await asyncio.sleep(0.6)
+ await _await_tasks_spawned_since(existing_tasks)
assert recorder.async_hook_started is not None
assert recording_executor.submit_times_for(logging_obj) == []
@@ -149,8 +155,9 @@ async def test_sync_callbacks_run_only_after_async_handler_completes(recording_e
logging_obj = _make_logging_obj()
iterator = _make_iterator(logging_obj)
+ existing_tasks = asyncio.all_tasks()
iterator._log_completed_response(is_async=True)
- await asyncio.sleep(0.8)
+ await _await_tasks_spawned_since(existing_tasks)
assert recorder.async_hook_finished is not None
submit_times = recording_executor.submit_times_for(logging_obj)
diff --git a/tests/unit/responses/test_streaming_iterator.py b/tests/unit/responses/test_streaming_iterator.py
index 4d44b8602df..9e3b4e86f6f 100644
--- a/tests/unit/responses/test_streaming_iterator.py
+++ b/tests/unit/responses/test_streaming_iterator.py
@@ -5,6 +5,7 @@ completion_start_time = end_time."""
import asyncio, importlib
import json
+import threading
from collections.abc import Callable
from datetime import datetime
from typing import Final, Optional
@@ -1350,6 +1351,8 @@ class _FakeLoggingObj:
self.start_time = datetime.now()
self.completion_start_time = None
self.model_call_details = {"litellm_params": {}}
+ self.success_logged = threading.Event()
+ self.failure_logged = threading.Event()
# Signature alignment with Logging handlers
async def dispatch_success_handlers(self, *args, **kwargs):
@@ -1360,6 +1363,7 @@ class _FakeLoggingObj:
def success_handler(self, *args, **kwargs):
self.success_calls += 1
self.last_success_kwargs = kwargs
+ self.success_logged.set()
async def async_success_handler(self, *args, **kwargs):
self.async_success_calls += 1
@@ -1367,6 +1371,7 @@ class _FakeLoggingObj:
def failure_handler(self, *args, **kwargs):
self.failure_calls += 1
+ self.failure_logged.set()
async def async_failure_handler(self, *args, **kwargs):
self.async_failure_calls += 1
@@ -1375,6 +1380,10 @@ class _FakeLoggingObj:
self.completion_start_time = completion_start_time
self.model_call_details["completion_start_time"] = completion_start_time
+async def _await_tasks_spawned_since(existing: set["asyncio.Task[object]"]) -> None:
+ spawned: Final = asyncio.all_tasks() - existing
+ await asyncio.wait_for(asyncio.gather(*spawned, return_exceptions=True), timeout=5)
+
def _make_completed_response(response_id: str = "resp_test") -> ResponseCompletedEvent:
return ResponseCompletedEvent(
type=ResponsesAPIStreamEvents.RESPONSE_COMPLETED,
@@ -1525,8 +1534,9 @@ async def test_responses_streaming_triggers_hooks(monkeypatch):
type=ResponsesAPIStreamEvents.RESPONSE_COMPLETED, response=SimpleNamespace()
)
+ existing_tasks = asyncio.all_tasks()
iterator._handle_logging_completed_response()
- await asyncio.sleep(0.2) # allow async tasks to run
+ await _await_tasks_spawned_since(existing_tasks)
assert logging_obj.success_calls == 1
assert logging_obj.async_success_calls == 1
@@ -1601,8 +1611,7 @@ async def test_responses_streaming_failure_triggers_failure_handlers():
with pytest.raises(ValueError, match="boom"):
iterator._process_chunk('{"delta": "chunk"}')
- # allow failure callbacks to run
- await asyncio.sleep(0.2)
+ assert await asyncio.to_thread(logging_obj.failure_logged.wait, 5)
assert logging_obj.failure_calls >= 1
assert logging_obj.async_failure_calls >= 1
@@ -1769,7 +1778,7 @@ async def test_handle_logging_failed_response_uses_response_error_message():
)
iterator._handle_logging_failed_response()
- await asyncio.sleep(0.2)
+ assert await asyncio.to_thread(logging_obj.failure_logged.wait, 5)
assert logging_obj.failure_calls == 1
assert logging_obj.async_failure_calls == 1
@@ -1891,8 +1900,9 @@ async def test_responses_streaming_completed_event_persists_async_cache():
)
iterator.completed_response = _make_completed_response()
+ existing_tasks = asyncio.all_tasks()
iterator._handle_logging_completed_response()
- await asyncio.sleep(0.2)
+ await _await_tasks_spawned_since(existing_tasks)
litellm.cache.async_add_cache.assert_called_once()
assert litellm.cache.async_add_cache.call_args.kwargs["stream"] is True
@@ -1981,7 +1991,7 @@ def test_log_completed_response_sync_direct_path(monkeypatch):
iterator.completed_response = _make_completed_response("resp_log_sync")
iterator._log_completed_response(is_async=False)
- asyncio.run(asyncio.sleep(0.2))
+ assert logging_obj.success_logged.wait(timeout=5)
assert logging_obj.success_calls == 1
assert logging_obj.async_success_calls == 1
@@ -2012,7 +2022,7 @@ def test_log_completed_response_falls_back_when_model_validate_fails(monkeypatch
monkeypatch.setattr(iterator, "_run_post_success_hooks", MagicMock())
iterator._log_completed_response(is_async=False)
- asyncio.run(asyncio.sleep(0.2))
+ assert logging_obj.success_logged.wait(timeout=5)
assert logging_obj.success_calls == 1
assert logging_obj.async_success_calls == 1
@@ -2178,8 +2188,9 @@ async def test_mock_responses_streaming_iterator_async_iteration_logs_completion
call_type=CallTypes.responses.value,
)
+ existing_tasks = asyncio.all_tasks()
streamed_events = [event async for event in iterator]
- await asyncio.sleep(0.2)
+ await _await_tasks_spawned_since(existing_tasks)
assert streamed_events[0].type == ResponsesAPIStreamEvents.RESPONSE_CREATED
assert streamed_events[-1].type == ResponsesAPIStreamEvents.RESPONSE_COMPLETED
@@ -2224,7 +2235,7 @@ def test_mock_responses_streaming_iterator_sync_iteration_logs_completion(monkey
)
streamed_events = list(iterator)
- asyncio.run(asyncio.sleep(0.2))
+ assert logging_obj.success_logged.wait(timeout=5)
assert streamed_events[0].type == ResponsesAPIStreamEvents.RESPONSE_CREATED
assert streamed_events[-1].type == ResponsesAPIStreamEvents.RESPONSE_COMPLETED
@@ -2277,8 +2288,9 @@ async def test_cached_responses_stream_async_hit_triggers_success_callbacks(
call_type=CallTypes.aresponses.value,
)
+ existing_tasks = asyncio.all_tasks()
streamed_events = [event async for event in iterator]
- await asyncio.sleep(0.2)
+ await _await_tasks_spawned_since(existing_tasks)
assert streamed_events[-1].type == ResponsesAPIStreamEvents.RESPONSE_COMPLETED
assert logging_obj.success_calls == 1
@@ -2333,7 +2345,7 @@ def test_cached_responses_stream_sync_hit_triggers_success_callbacks(monkeypatch
)
streamed_events = list(iterator)
- asyncio.run(asyncio.sleep(0.2))
+ assert logging_obj.success_logged.wait(timeout=5)
assert streamed_events[-1].type == ResponsesAPIStreamEvents.RESPONSE_COMPLETED
assert logging_obj.success_calls == 1
diff --git a/tests/unit/test_litellm_overhead.py b/tests/unit/test_litellm_overhead.py
index a944a6da487..c2241b55adb 100644
--- a/tests/unit/test_litellm_overhead.py
+++ b/tests/unit/test_litellm_overhead.py
@@ -145,6 +145,7 @@ async def test_litellm_overhead_stream(monkeypatch):
@pytest.mark.asyncio
async def test_litellm_overhead_cache_hit(monkeypatch):
from litellm.caching.caching import Cache
+ from litellm.caching.caching_handler import _PENDING_CACHE_WRITES
calls = _mock_openai_completion_transport(monkeypatch, response_id="chatcmpl-cache")
litellm.cache = Cache()
@@ -157,7 +158,7 @@ async def test_litellm_overhead_cache_hit(monkeypatch):
messages=messages,
caching=True,
)
- await asyncio.sleep(0.5)
+ await asyncio.wait_for(asyncio.gather(*_PENDING_CACHE_WRITES), timeout=5)
response2 = await litellm.acompletion(
model="gpt-4o",
api_key="test-key",
diff --git a/tests/unit/test_utils.py b/tests/unit/test_utils.py
index 6ad4f75f97f..124369a9528 100644
--- a/tests/unit/test_utils.py
+++ b/tests/unit/test_utils.py
@@ -6264,25 +6264,30 @@ async def test_wrapper_async_preserves_original_exception_when_hook_await_is_can
the caller - not get replaced by CancelledError/TimeoutError from the hook's own
await getting cancelled."""
+ hook_entered: Final = asyncio.Event()
+ hook_released: Final = asyncio.Event()
+
class SlowLogger(CustomLogger):
async def async_post_call_failure_deployment_hook(
self, request_data, exception, call_type, fallback_depth=None
):
- await asyncio.sleep(5)
+ hook_entered.set()
+ await hook_released.wait()
monkeypatch.setattr(litellm, "callbacks", [SlowLogger()])
- with pytest.raises(litellm.AuthenticationError):
- await asyncio.wait_for(
- litellm.acompletion(
- model="gpt-4o-mini",
- messages=[{"role": "user", "content": "hi"}],
- mock_response=litellm.AuthenticationError(
- message="bad key", llm_provider="openai", model="gpt-4o-mini"
- ),
- ),
- timeout=0.2,
+ call: Final = asyncio.create_task(
+ litellm.acompletion(
+ model="gpt-4o-mini",
+ messages=[{"role": "user", "content": "hi"}],
+ mock_response=litellm.AuthenticationError(message="bad key", llm_provider="openai", model="gpt-4o-mini"),
)
+ )
+ assert await asyncio.wait_for(hook_entered.wait(), timeout=5)
+ call.cancel()
+
+ with pytest.raises(litellm.AuthenticationError):
+ await call
@pytest.mark.asyncio