mirror of
https://github.com/BerriAI/litellm.git
synced 2026-09-26 01:12:21 +00:00
* ci: run the unit_selection.sh shard files on every event instead of only fork pull requests Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * ci: rename fork-flag to unit-flag now that it applies on every event * test: move tests/test_litellm root and small trees into tests/unit Pure renames, no content changes. Follow-up commits in this PR fix references, merge the three files that already existed in tests/unit, keep live-provider tests in tests/test_litellm and wire CI. * test: carry tests/test_litellm conftest isolation into tests/unit Callback lists, routing fallbacks, cached HTTP clients, logger state, AWS, proxy-URL and keychain env, and session-end client cleanup now reset for unit tests too. The environment isolation owns its MonkeyPatch so a test's own monkeypatch is undone before the model-cost teardown runs. * test: merge, split and prune the moved root and small-tree tests Merge batches/test_batch_utils.py and the chat_completions and messages dispatch tests into the files that already existed in tests/unit. Keep the live Gemini interactions tests, the async image-fetch format test and the OpenAI embedding scorer test in tests/test_litellm since they need real network or keys. Put test_router.py under tests/unit/test_router so the existing package no longer shadows it. Delete eight tests the audit found superseded by stronger ones kept in this move. * ci: run the moved root and small-tree tests under their legacy flags Add the misc and responses-caching-types flags to unit_selection.sh and CircleCI, extend enterprise-routing and mcp-integration, and point the legacy GHA shards, Makefile, redis-compat workflow, merge smoke manifest and change classifier at the new paths. * test: make the new tests/unit directories packages tests/unit/test_package_layout.py requires every directory to carry an __init__.py, and without one the moved and retained test_litellm_responses_bridge.py modules collide on import. * test: scope the unit socket block to tests/unit in shared sessions The GHA shards collect the legacy test-path and the unit selection in one pytest session. The unit conftest's loopback-only block leaked into legacy modules that reach the network at import. The legacy conftest now lifts the restriction at collect and setup time, and the unit conftest re-applies it when collecting its own modules. * test: move tests/test_litellm/llms into tests/unit/llms Rename-only. Moves the provider tests and the fine-tuning fixtures they load, mirroring the old paths. Follow-up commits merge, split and wire them. * test: merge, split and prune the moved llms tests Merges the Databricks chat transformation tests into the existing unit file, keeps the tests that need real keys or the network in tests/test_litellm, deletes the audited tests a stronger unit test already covers, and points imports at tests.unit.llms. * ci: run the moved llms tests under their legacy flags The Vertex AI and All Other Providers shards keep their legacy test-path for the retained files and add the llm-vertex-ai and llm-other-providers unit selections. CircleCI gets matching unit jobs. * test: make the tests/unit/llms directories packages Adds __init__.py to the moved dirs and drops the legacy ones whose directories no longer hold tests. * test: drop script runners and path hacks the llms split left dangling The __main__ runners in the split openai_like files and the Databricks e2e runner called tests that now live in the other half of the split or were deleted. The retained legacy halves also no longer need sys.path edits. * test: give the shard-script tests their own GITHUB_OUTPUT They only passed where the runner set it. The CircleCI unit job's env allowlist drops it, so the script's redirect failed there. * test: point the router and module-deletion checks at tests/unit router_code_coverage and code_qa_check_tests only searched tests/test_litellm, so the moved router tests no longer counted. The two silent-experiment tests the audit deleted were the only direct callers of those methods; they are replaced with tests that assert the forwarded shadow request and the recursion guard. * test: move tests/test_litellm integrations and secret_managers into tests/unit Rename-only. Mirrors the old paths, including the directory conftests and the prompt and JSON fixtures. Follow-up commits prune and wire them. * test: prune and repoint the moved integrations tests Deletes the 7 audited tests a stronger test in the same tree already covers, imports the TLS sink helpers from their new conftest path, and restores os.environ after each integrations test. Some presets write OTEL_EXPORTER_OTLP_HEADERS straight into os.environ, and without the legacy tree's test ordering that header leaked into the AgentOps tests. * ci: run the moved integrations tests under their legacy flag The integrations GHA shard and a new CircleCI job run the integrations unit selection. secret_managers joins the misc selection. * docs: point integrations and secret_managers references at tests/unit * test: make the moved integrations directories packages * test: keep the Databricks manual e2e runner and fix the SageMaker Nova run path The Databricks e2e file is a manual script whose main() calls the tests that were pruned, so pruning them broke the documented run. It is back to its main version. The SageMaker Nova docstring now points at the file's real location in tests/local_testing. * test: keep the job's UNIT_FLAG out of the shard-script tests --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
337 lines
14 KiB
Python
337 lines
14 KiB
Python
import json
|
|
import time
|
|
from typing import Optional
|
|
from unittest.mock import AsyncMock, MagicMock, patch
|
|
|
|
import pytest
|
|
|
|
# Adds the grandparent directory to sys.path to allow importing project modules
|
|
|
|
from litellm.integrations.SlackAlerting.hanging_request_check import (
|
|
AlertingHangingRequestCheck,
|
|
)
|
|
from litellm.types.integrations.slack_alerting import HangingRequestData
|
|
|
|
|
|
class TestAlertingHangingRequestCheck:
|
|
"""Test suite for AlertingHangingRequestCheck class"""
|
|
|
|
@pytest.fixture
|
|
def mock_slack_alerting(self):
|
|
"""Create a mock SlackAlerting object for testing"""
|
|
mock_slack = MagicMock()
|
|
mock_slack.alerting_threshold = 300 # 5 minutes
|
|
mock_slack.send_alert = AsyncMock()
|
|
return mock_slack
|
|
|
|
@pytest.fixture
|
|
def hanging_request_checker(self, mock_slack_alerting):
|
|
"""Create an AlertingHangingRequestCheck instance for testing"""
|
|
return AlertingHangingRequestCheck(slack_alerting_object=mock_slack_alerting)
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_init_creates_cache_with_correct_ttl(self, mock_slack_alerting):
|
|
"""
|
|
Test that initialization creates a hanging request cache with correct TTL.
|
|
The TTL should be 1.5x alerting_threshold + buffer time, so entries
|
|
survive long enough to be checked after crossing the threshold.
|
|
"""
|
|
checker = AlertingHangingRequestCheck(slack_alerting_object=mock_slack_alerting)
|
|
|
|
expected_ttl = int(
|
|
mock_slack_alerting.alerting_threshold * 1.5 + 60
|
|
) # HANGING_ALERT_BUFFER_TIME_SECONDS
|
|
assert checker.hanging_request_cache.default_ttl == expected_ttl
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_add_request_to_hanging_request_check_success(
|
|
self, hanging_request_checker
|
|
):
|
|
"""
|
|
Test successfully adding a request to the hanging request cache.
|
|
Should extract metadata and store HangingRequestData in cache.
|
|
"""
|
|
request_data = {
|
|
"litellm_call_id": "test_request_123",
|
|
"model": "gpt-4",
|
|
"deployment": {"litellm_params": {"api_base": "https://api.openai.com/v1"}},
|
|
"metadata": {
|
|
"user_api_key_alias": "test_key",
|
|
"user_api_key_team_alias": "test_team",
|
|
},
|
|
}
|
|
|
|
with patch("litellm.get_api_base", return_value="https://api.openai.com/v1"):
|
|
await hanging_request_checker.add_request_to_hanging_request_check(
|
|
request_data
|
|
)
|
|
|
|
# Verify the request was added to cache
|
|
cached_data = (
|
|
await hanging_request_checker.hanging_request_cache.async_get_cache(
|
|
key="test_request_123"
|
|
)
|
|
)
|
|
|
|
assert cached_data is not None
|
|
assert isinstance(cached_data, HangingRequestData)
|
|
assert cached_data.request_id == "test_request_123"
|
|
assert cached_data.model == "gpt-4"
|
|
assert cached_data.api_base == "https://api.openai.com/v1"
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_add_request_to_hanging_request_check_none_request_data(
|
|
self, hanging_request_checker
|
|
):
|
|
"""
|
|
Test that passing None request_data returns early without error.
|
|
Should handle gracefully when no request data is provided.
|
|
"""
|
|
result = await hanging_request_checker.add_request_to_hanging_request_check(
|
|
None
|
|
)
|
|
assert result is None
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_add_request_to_hanging_request_check_minimal_data(
|
|
self, hanging_request_checker
|
|
):
|
|
"""
|
|
Test adding request with minimal required data.
|
|
Should handle cases where optional fields are missing.
|
|
"""
|
|
request_data = {
|
|
"litellm_call_id": "minimal_request_456",
|
|
"model": "gpt-3.5-turbo",
|
|
}
|
|
|
|
await hanging_request_checker.add_request_to_hanging_request_check(request_data)
|
|
|
|
cached_data = (
|
|
await hanging_request_checker.hanging_request_cache.async_get_cache(
|
|
key="minimal_request_456"
|
|
)
|
|
)
|
|
|
|
assert cached_data is not None
|
|
assert cached_data.request_id == "minimal_request_456"
|
|
assert cached_data.model == "gpt-3.5-turbo"
|
|
assert cached_data.api_base is None
|
|
assert cached_data.key_alias == ""
|
|
assert cached_data.team_alias == ""
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_send_hanging_request_alert(self, hanging_request_checker):
|
|
"""
|
|
Test sending a hanging request alert.
|
|
Should format the alert message correctly and call slack alerting.
|
|
"""
|
|
hanging_request_data = HangingRequestData(
|
|
request_id="test_hanging_request",
|
|
model="gpt-4",
|
|
api_base="https://api.openai.com/v1",
|
|
key_alias="test_key",
|
|
team_alias="test_team",
|
|
)
|
|
|
|
await hanging_request_checker.send_hanging_request_alert(hanging_request_data)
|
|
|
|
# Verify slack alert was called
|
|
hanging_request_checker.slack_alerting_object.send_alert.assert_called_once()
|
|
|
|
# Check the alert message format
|
|
call_args = hanging_request_checker.slack_alerting_object.send_alert.call_args
|
|
message = call_args[1]["message"]
|
|
|
|
assert "Requests are hanging - 300s+ request time" in message
|
|
assert "Request Model: `gpt-4`" in message
|
|
assert "API Base: `https://api.openai.com/v1`" in message
|
|
assert "Key Alias: `test_key`" in message
|
|
assert "Team Alias: `test_team`" in message
|
|
assert call_args[1]["level"] == "Medium"
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_send_alerts_for_hanging_requests_no_proxy_logging(
|
|
self, hanging_request_checker
|
|
):
|
|
"""
|
|
Test send_alerts_for_hanging_requests when proxy_logging_obj.internal_usage_cache is None.
|
|
Should return early without processing when internal usage cache is unavailable.
|
|
"""
|
|
with patch("litellm.proxy.proxy_server.proxy_logging_obj") as mock_proxy:
|
|
mock_proxy.internal_usage_cache = None
|
|
|
|
result = await hanging_request_checker.send_alerts_for_hanging_requests()
|
|
assert result is None
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_send_alerts_for_hanging_requests_with_completed_request(
|
|
self, hanging_request_checker
|
|
):
|
|
"""
|
|
Test send_alerts_for_hanging_requests when request has completed (not hanging).
|
|
Should remove completed requests from cache and not send alerts.
|
|
"""
|
|
# Add a request to the hanging cache
|
|
hanging_data = HangingRequestData(
|
|
request_id="completed_request_789",
|
|
model="gpt-4",
|
|
api_base="https://api.openai.com/v1",
|
|
)
|
|
await hanging_request_checker.hanging_request_cache.async_set_cache(
|
|
key="completed_request_789", value=hanging_data, ttl=300
|
|
)
|
|
|
|
with patch("litellm.proxy.proxy_server.proxy_logging_obj") as mock_proxy:
|
|
# Mock internal usage cache to return a request status (meaning request completed)
|
|
mock_internal_cache = AsyncMock()
|
|
mock_internal_cache.async_get_cache.return_value = {"status": "success"}
|
|
mock_proxy.internal_usage_cache = mock_internal_cache
|
|
|
|
# Mock the cache method to return our test request
|
|
hanging_request_checker.hanging_request_cache.async_get_oldest_n_keys = (
|
|
AsyncMock(return_value=["completed_request_789"])
|
|
)
|
|
|
|
await hanging_request_checker.send_alerts_for_hanging_requests()
|
|
|
|
# Verify no alert was sent since request completed
|
|
hanging_request_checker.slack_alerting_object.send_alert.assert_not_called()
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_send_alerts_for_hanging_requests_with_actual_hanging_request(
|
|
self, hanging_request_checker
|
|
):
|
|
"""
|
|
Test send_alerts_for_hanging_requests when request is actually hanging.
|
|
Should send alert for requests that haven't completed within threshold.
|
|
"""
|
|
# Add a hanging request that is older than the alerting threshold
|
|
hanging_data = HangingRequestData(
|
|
request_id="hanging_request_999",
|
|
model="gpt-4",
|
|
api_base="https://api.openai.com/v1",
|
|
key_alias="test_key",
|
|
team_alias="test_team",
|
|
created_at=time.time() - 301,
|
|
)
|
|
await hanging_request_checker.hanging_request_cache.async_set_cache(
|
|
key="hanging_request_999", value=hanging_data, ttl=300
|
|
)
|
|
|
|
with patch("litellm.proxy.proxy_server.proxy_logging_obj") as mock_proxy:
|
|
# Mock internal usage cache to return None (meaning request is still hanging)
|
|
mock_internal_cache = AsyncMock()
|
|
mock_internal_cache.async_get_cache.return_value = None
|
|
mock_proxy.internal_usage_cache = mock_internal_cache
|
|
|
|
# Mock the cache method to return our test request
|
|
hanging_request_checker.hanging_request_cache.async_get_oldest_n_keys = (
|
|
AsyncMock(return_value=["hanging_request_999"])
|
|
)
|
|
|
|
await hanging_request_checker.send_alerts_for_hanging_requests()
|
|
|
|
# Verify alert was sent for hanging request
|
|
hanging_request_checker.slack_alerting_object.send_alert.assert_called_once()
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_send_alerts_for_hanging_requests_alerts_once_per_hang(
|
|
self, hanging_request_checker
|
|
):
|
|
"""
|
|
A single hanging request must alert exactly once even though the
|
|
checker tick revisits it on every run within the cache TTL.
|
|
"""
|
|
hanging_data = HangingRequestData(
|
|
request_id="hanging_once_555",
|
|
model="gpt-4",
|
|
api_base="https://api.openai.com/v1",
|
|
created_at=time.time() - 301,
|
|
)
|
|
await hanging_request_checker.hanging_request_cache.async_set_cache(
|
|
key="hanging_once_555", value=hanging_data, ttl=300
|
|
)
|
|
|
|
with patch("litellm.proxy.proxy_server.proxy_logging_obj") as mock_proxy:
|
|
mock_internal_cache = AsyncMock()
|
|
mock_internal_cache.async_get_cache.return_value = None
|
|
mock_proxy.internal_usage_cache = mock_internal_cache
|
|
|
|
hanging_request_checker.hanging_request_cache.async_get_oldest_n_keys = (
|
|
AsyncMock(return_value=["hanging_once_555"])
|
|
)
|
|
|
|
for _ in range(3):
|
|
await hanging_request_checker.send_alerts_for_hanging_requests()
|
|
|
|
assert hanging_request_checker.slack_alerting_object.send_alert.call_count == 1
|
|
cached = await hanging_request_checker.hanging_request_cache.async_get_cache(
|
|
key="hanging_once_555"
|
|
)
|
|
assert cached is not None
|
|
assert cached.alerted is True
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_send_alerts_for_hanging_requests_skips_request_younger_than_threshold(
|
|
self, hanging_request_checker
|
|
):
|
|
"""
|
|
Test that an in-flight request younger than the alerting threshold
|
|
does not trigger an alert and stays in the cache for later checks.
|
|
"""
|
|
hanging_data = HangingRequestData(
|
|
request_id="young_request_123",
|
|
model="gpt-4",
|
|
api_base="https://api.openai.com/v1",
|
|
)
|
|
await hanging_request_checker.hanging_request_cache.async_set_cache(
|
|
key="young_request_123", value=hanging_data, ttl=300
|
|
)
|
|
|
|
with patch("litellm.proxy.proxy_server.proxy_logging_obj") as mock_proxy:
|
|
# Mock internal usage cache to return None (request still in flight)
|
|
mock_internal_cache = AsyncMock()
|
|
mock_internal_cache.async_get_cache.return_value = None
|
|
mock_proxy.internal_usage_cache = mock_internal_cache
|
|
|
|
hanging_request_checker.hanging_request_cache.async_get_oldest_n_keys = (
|
|
AsyncMock(return_value=["young_request_123"])
|
|
)
|
|
|
|
await hanging_request_checker.send_alerts_for_hanging_requests()
|
|
|
|
# No alert for a request below the threshold, and it must remain
|
|
# cached so a later check can alert if it never completes
|
|
hanging_request_checker.slack_alerting_object.send_alert.assert_not_called()
|
|
assert (
|
|
await hanging_request_checker.hanging_request_cache.async_get_cache(
|
|
key="young_request_123"
|
|
)
|
|
is not None
|
|
)
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_send_alerts_for_hanging_requests_with_missing_hanging_data(
|
|
self, hanging_request_checker
|
|
):
|
|
"""
|
|
Test send_alerts_for_hanging_requests when hanging request data is missing from cache.
|
|
Should continue processing other requests when individual request data is missing.
|
|
"""
|
|
with patch("litellm.proxy.proxy_server.proxy_logging_obj") as mock_proxy:
|
|
mock_internal_cache = AsyncMock()
|
|
mock_proxy.internal_usage_cache = mock_internal_cache
|
|
|
|
# Mock cache to return request ID but no data (simulating expired or missing data)
|
|
hanging_request_checker.hanging_request_cache.async_get_oldest_n_keys = (
|
|
AsyncMock(return_value=["missing_request_111"])
|
|
)
|
|
hanging_request_checker.hanging_request_cache.async_get_cache = AsyncMock(
|
|
return_value=None
|
|
)
|
|
|
|
await hanging_request_checker.send_alerts_for_hanging_requests()
|
|
|
|
# Should not crash and should not send any alerts
|
|
hanging_request_checker.slack_alerting_object.send_alert.assert_not_called()
|