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]

fix(logging): deliver completed batch success callbacks consistently (#47192)

joshua-berri9c958aff3496
diff --git a/litellm/integrations/custom_logger.py b/litellm/integrations/custom_logger.py
index 5addc994df2..a4de1be1842 100644
--- a/litellm/integrations/custom_logger.py
+++ b/litellm/integrations/custom_logger.py
@@ -912,9 +912,11 @@ class CustomLogger: # https://docs.litellm.ai/docs/observability/custom_callbac
This is useful for logging payloads that contain sensitive information.
"""
import litellm
- from litellm import Choices, Message, ModelResponse
from litellm.litellm_core_utils.classifier_logging import CLASSIFIER_AUDIT_FIELDS
- from litellm.litellm_core_utils.redact_messages import redacted_litellm_params
+ from litellm.litellm_core_utils.redact_messages import (
+ redacted_litellm_params,
+ redacted_standard_logging_payload,
+ )
turn_off_message_logging: Final[bool] = getattr(self, "turn_off_message_logging", False)
excluded_fields: Final[list[str] | None] = getattr(litellm, "standard_logging_payload_excluded_fields", None)
@@ -940,41 +942,14 @@ class CustomLogger: # https://docs.litellm.ai/docs/observability/custom_callbac
if key not in (excluded_fields or ()) and not (turn_off_message_logging and key in CLASSIFIER_AUDIT_FIELDS)
}
- # Handle turn_off_message_logging - redact messages and responses (if not already excluded)
- if turn_off_message_logging and not self.redacts_messages_itself():
- redacted_str: Final = "redacted-by-litellm"
-
- if "messages" not in (excluded_fields or ()) and standard_logging_object_copy.get("messages") is not None:
- standard_logging_object_copy["messages"] = [Message(content=redacted_str).model_dump()]
-
- if "response" not in (excluded_fields or ()) and standard_logging_object_copy.get("response") is not None:
- response: Final = standard_logging_object_copy["response"]
- # Check if this is a ResponsesAPIResponse (has "output" field)
- if isinstance(response, dict) and "output" in response:
- # Make a copy to avoid modifying the original
- from copy import deepcopy
-
- response_copy: Final = deepcopy(response)
- # Redact content in output array
- if isinstance(response_copy.get("output"), list):
- for output_item in response_copy["output"]:
- if isinstance(output_item, dict) and "content" in output_item:
- if isinstance(output_item["content"], list):
- # Redact text in content items
- for content_item in output_item["content"]:
- if isinstance(content_item, dict) and "text" in content_item:
- content_item["text"] = redacted_str
- standard_logging_object_copy["response"] = response_copy
- else:
- # Standard ModelResponse format
- model_response: Final = ModelResponse(choices=[Choices(message=Message(content=redacted_str))])
- model_response_dict: Final = model_response.model_dump()
- standard_logging_object_copy["response"] = model_response_dict
-
return {
**model_call_details,
**redacted_params,
- "standard_logging_object": standard_logging_object_copy,
+ "standard_logging_object": (
+ redacted_standard_logging_payload(standard_logging_object_copy)
+ if turn_off_message_logging and not self.redacts_messages_itself()
+ else standard_logging_object_copy
+ ),
}
async def get_proxy_server_request_from_cold_storage_with_object_key(
diff --git a/litellm/litellm_core_utils/litellm_logging.py b/litellm/litellm_core_utils/litellm_logging.py
index b6bdc21bc05..5d9652cc8a2 100644
--- a/litellm/litellm_core_utils/litellm_logging.py
+++ b/litellm/litellm_core_utils/litellm_logging.py
@@ -634,15 +634,15 @@ class Logging(LiteLLMLoggingBaseClass):
self,
model: str,
messages,
- stream,
+ stream: bool | None,
call_type,
start_time: datetime.datetime,
litellm_call_id: str,
function_id: str,
litellm_trace_id: str | None = None,
dynamic_input_callbacks: list[str | Callable | CustomLogger] | None = None,
- dynamic_success_callbacks: list[str | Callable | CustomLogger] | None = None,
- dynamic_async_success_callbacks: list[str | Callable | CustomLogger] | None = None,
+ dynamic_success_callbacks: list[str | Callable[..., object] | CustomLogger] | None = None,
+ dynamic_async_success_callbacks: list[str | Callable[..., object] | CustomLogger] | None = None,
dynamic_failure_callbacks: list[str | Callable | CustomLogger] | None = None,
dynamic_async_failure_callbacks: list[str | Callable | CustomLogger] | None = None,
applied_guardrails: list[str] | None = None,
@@ -718,8 +718,10 @@ class Logging(LiteLLMLoggingBaseClass):
# Initialize dynamic callbacks
self.dynamic_input_callbacks: list[str | Callable | CustomLogger] | None = dynamic_input_callbacks
- self.dynamic_success_callbacks: list[str | Callable | CustomLogger] | None = dynamic_success_callbacks
- self.dynamic_async_success_callbacks: list[str | Callable | CustomLogger] | None = (
+ self.dynamic_success_callbacks: list[str | Callable[..., object] | CustomLogger] | None = (
+ dynamic_success_callbacks
+ )
+ self.dynamic_async_success_callbacks: list[str | Callable[..., object] | CustomLogger] | None = (
dynamic_async_success_callbacks
)
self.dynamic_failure_callbacks: list[str | Callable | CustomLogger] | None = dynamic_failure_callbacks
@@ -786,6 +788,7 @@ class Logging(LiteLLMLoggingBaseClass):
self.defer_async_logging: bool = False
self.enqueue_deferred_logging: Callable[[], None] | None = None
self._async_success_scheduled: bool = False
+ self._sync_success_scheduled: bool = False
self.on_detached_stream_failure: Callable[[Exception], Awaitable[None]] | None = None
self.shadow_eval_request_snapshot: GuardrailRequestSnapshot | None = None
@@ -2318,7 +2321,7 @@ class Logging(LiteLLMLoggingBaseClass):
**kwargs,
)
- if not self._should_run_sync_callbacks_for_async_calls():
+ if not self.stream or not self._should_run_sync_callbacks_for_async_calls():
return
executor.submit(
@@ -2446,7 +2449,7 @@ class Logging(LiteLLMLoggingBaseClass):
self,
event_type: Literal["async_success", "sync_success", "async_failure", "sync_failure"],
) -> None:
- if self.stream is not None and self.stream is True and event_type in ["async_success", "sync_success"]:
+ if self.stream is True and event_type in ["async_success", "sync_success"]:
"""
Ignore check on stream, as there can be multiple chunks
"""
@@ -2943,6 +2946,8 @@ class Logging(LiteLLMLoggingBaseClass):
discarded as a duplicate of the in-progress create.
"""
self.model_call_details.pop("has_logged_async_success", None)
+ self.model_call_details.pop("has_logged_sync_success", None)
+ self._sync_success_scheduled = False
litellm_params = self.model_call_details.get("litellm_params")
if not isinstance(litellm_params, dict):
return
@@ -3131,6 +3136,11 @@ class Logging(LiteLLMLoggingBaseClass):
dynamic_success_callbacks=self.dynamic_success_callbacks,
global_callbacks=litellm.success_callback,
)
+ delivery_callbacks: Final = (
+ self._get_completed_success_callbacks(asynchronous=False)
+ if for_async_request and not self.stream
+ else callbacks
+ )
## REDACT MESSAGES ##
result = redact_message_input_output_from_logging(
@@ -3138,7 +3148,8 @@ class Logging(LiteLLMLoggingBaseClass):
result=result,
)
## LOGGING HOOK ##
- for callback in callbacks:
+ hook_callbacks: Final = tuple(dict.fromkeys((*callbacks, *delivery_callbacks)))
+ for callback in hook_callbacks:
if isinstance(callback, CustomGuardrail):
from litellm.types.guardrails import GuardrailEventHooks
@@ -3168,7 +3179,7 @@ class Logging(LiteLLMLoggingBaseClass):
call_details_view: Final = MappingProxyType[str, object](call_details)
self.mark_logging_complete(event_type="sync_success")
- for callback in callbacks:
+ for callback in delivery_callbacks:
try:
should_run = self.should_run_callback(
callback=callback,
@@ -3440,7 +3451,12 @@ class Logging(LiteLLMLoggingBaseClass):
)
if (
isinstance(callback, CustomLogger)
- and is_sync_request
+ and (is_sync_request or (for_async_request and not self.stream))
+ and not (
+ for_async_request
+ and self.stream
+ and callback in (self.dynamic_async_success_callbacks or ())
+ )
and self.call_type
!= CallTypes.pass_through.value # pass-through endpoints call async_log_success_event
): # custom logger class
@@ -3457,7 +3473,7 @@ class Logging(LiteLLMLoggingBaseClass):
result = call_details_view["complete_response"]
callback.log_success_event(
- kwargs=call_details,
+ kwargs=callback.redact_standard_logging_payload_from_model_call_details(call_details),
response_obj=result,
start_time=start_time,
end_time=end_time,
@@ -3699,6 +3715,9 @@ class Logging(LiteLLMLoggingBaseClass):
dynamic_success_callbacks=self.dynamic_async_success_callbacks,
global_callbacks=litellm._async_success_callback,
)
+ delivery_callbacks: Final = (
+ self._get_completed_success_callbacks(asynchronous=True) if not self.stream else callbacks
+ )
result = redact_message_input_output_from_logging(
model_call_details=(self.model_call_details if hasattr(self, "model_call_details") else {}),
@@ -3707,7 +3726,8 @@ class Logging(LiteLLMLoggingBaseClass):
## LOGGING HOOK ##
- for callback in callbacks:
+ hook_callbacks: Final = tuple(dict.fromkeys((*callbacks, *delivery_callbacks)))
+ for callback in hook_callbacks:
try:
if isinstance(callback, CustomGuardrail):
from litellm.types.guardrails import GuardrailEventHooks
@@ -3745,7 +3765,7 @@ class Logging(LiteLLMLoggingBaseClass):
self.mark_logging_complete(event_type="async_success")
- for callback in callbacks:
+ for callback in delivery_callbacks:
# check if callback can run for this request
litellm_params = self.model_call_details.get("litellm_params", {})
should_run = self.should_run_callback(
@@ -3880,6 +3900,13 @@ class Logging(LiteLLMLoggingBaseClass):
traceback.format_exc(),
)
self._handle_callback_failure(callback=callback)
+ if not self.stream:
+ try:
+ self.handle_sync_success_callbacks_for_async_calls(
+ result=result, start_time=start_time, end_time=end_time, cache_hit=cache_hit
+ )
+ except RuntimeError:
+ verbose_logger.exception("Could not schedule synchronous success callbacks")
await flush_post_call_redis_batches()
def _handle_callback_failure(self, callback: object):
@@ -4303,6 +4330,10 @@ class Logging(LiteLLMLoggingBaseClass):
if self._should_run_sync_callbacks_for_async_calls() is False:
return
+ if not self.stream and self._sync_success_scheduled:
+ return
+ if not self.stream:
+ self._sync_success_scheduled = True
executor.submit(
self.success_handler,
result,
@@ -4321,11 +4352,57 @@ class Logging(LiteLLMLoggingBaseClass):
) -> None:
executor.submit(self.success_handler, result, start_time, end_time, cache_hit)
+ def _get_completed_success_callbacks(
+ self, *, asynchronous: bool
+ ) -> tuple[str | Callable[..., object] | CustomLogger, ...]:
+ sync_callbacks: Final = self.get_combined_callback_list(
+ self.dynamic_success_callbacks, litellm.success_callback
+ )
+ async_callbacks: Final = self.get_combined_callback_list(
+ self.dynamic_async_success_callbacks,
+ litellm._async_success_callback, # pyright: ignore[reportPrivateUsage] # shared logging registry
+ )
+ legacy_sync_callbacks: Final = self._remove_internal_litellm_callbacks(
+ self._remove_internal_custom_logger_callbacks(sync_callbacks)
+ )
+ selected: Final = async_callbacks if asynchronous else sync_callbacks
+ other: Final = sync_callbacks if asynchronous else async_callbacks
+ return tuple(
+ callback
+ for callback in self.get_combined_callback_list(selected, other)
+ if (
+ (
+ (
+ getattr(callback.async_log_success_event, "__func__", callback.async_log_success_event)
+ is not CustomLogger.async_log_success_event
+ )
+ == asynchronous
+ and (
+ asynchronous
+ or getattr(callback.log_success_event, "__func__", callback.log_success_event)
+ is not CustomLogger.log_success_event
+ )
+ )
+ if isinstance(callback, CustomLogger)
+ else callback in selected
+ and (
+ asynchronous
+ or (
+ callback not in async_callbacks
+ and callback in legacy_sync_callbacks
+ and not (isinstance(callback, str) and callback in INTERNAL_CALLBACK_NAMES)
+ )
+ )
+ )
+ )
+
def _should_run_sync_callbacks_for_async_calls(self) -> bool:
"""
Returns:
- bool: True if sync callbacks should be run for async calls. eg. `langfuse`, `s3`
"""
+ if not self.stream:
+ return bool(self._get_completed_success_callbacks(asynchronous=False))
_combined_sync_callbacks: Final = self.get_combined_callback_list(
dynamic_success_callbacks=self.dynamic_success_callbacks,
global_callbacks=litellm.success_callback,
@@ -4355,7 +4432,11 @@ class Logging(LiteLLMLoggingBaseClass):
_filtered_failure_callbacks = self._remove_internal_litellm_callbacks(_filtered_failure_callbacks)
return len(_filtered_failure_callbacks) > 0
- def get_combined_callback_list(self, dynamic_success_callbacks: list | None, global_callbacks: list) -> list:
+ def get_combined_callback_list(
+ self,
+ dynamic_success_callbacks: list[str | Callable[..., object] | CustomLogger] | None,
+ global_callbacks: list[str | Callable[..., object] | CustomLogger],
+ ) -> list[str | Callable[..., object] | CustomLogger]:
if dynamic_success_callbacks is None:
return list(global_callbacks)
return list(dict.fromkeys(dynamic_success_callbacks + global_callbacks))
diff --git a/litellm/proxy/guardrails/guardrail_endpoints.py b/litellm/proxy/guardrails/guardrail_endpoints.py
index 1d5c530a616..70e7aac12b5 100644
--- a/litellm/proxy/guardrails/guardrail_endpoints.py
+++ b/litellm/proxy/guardrails/guardrail_endpoints.py
@@ -2367,9 +2367,6 @@ class _GuardrailLoggingObj(Protocol):
@property
def async_success_handler(self) -> "Callable[..., Awaitable[object]]": ...
- @property
- def success_handler(self) -> "Callable[..., object]": ...
-
class _GuardrailProxyLogging(Protocol):
@property
@@ -2399,10 +2396,6 @@ async def _emit_guardrail_success_logs(
caller from receiving the guardrail response. Returns the (possibly
hook-modified) response.
"""
- from litellm.litellm_core_utils.thread_pool_executor import (
- executor as thread_pool_executor,
- )
-
try:
modified: Final = await proxy_logging_obj.post_call_success_hook(
data=data,
@@ -2430,16 +2423,6 @@ async def _emit_guardrail_success_logs(
)
except Exception:
verbose_proxy_logger.exception("apply_guardrail: async_success_handler failed")
- try:
- thread_pool_executor.submit(
- litellm_logging_obj.success_handler,
- response_for_logging,
- start_time,
- end_time,
- False,
- )
- except Exception:
- verbose_proxy_logger.exception("apply_guardrail: success_handler submit failed")
return response
diff --git a/tests/integration/_support/redaction_probe.py b/tests/integration/_support/redaction_probe.py
index 2a344daa73c..91b5faa2758 100644
--- a/tests/integration/_support/redaction_probe.py
+++ b/tests/integration/_support/redaction_probe.py
@@ -10,12 +10,15 @@ from pydantic import BaseModel
from litellm.integrations.custom_logger import CustomLogger
-def _payload(kwargs: Mapping[str, object], response_obj: object) -> str:
+def _payload(kwargs: Mapping[str, object], response_obj: object, logger: str, hook: str) -> str:
params: Final = kwargs.get("litellm_params")
request: Final = params.get("proxy_server_request") if isinstance(params, Mapping) else None
standard: Final = kwargs.get("standard_logging_object")
return json.dumps(
{
+ "logger": logger,
+ "hook": hook,
+ "standard": standard,
"request": request,
"response": response_obj.model_dump() if isinstance(response_obj, BaseModel) else response_obj,
"standard_response": standard.get("response") if isinstance(standard, Mapping) else None,
@@ -29,7 +32,9 @@ class SyncRedactionProbe(CustomLogger):
self, kwargs: Mapping[str, object], response_obj: object, start_time: datetime, end_time: datetime
) -> None:
with httpx.Client(trust_env=False) as client:
- response: Final = client.post(os.environ["REDACTION_PROBE_URL"], content=_payload(kwargs, response_obj))
+ response: Final = client.post(
+ os.environ["REDACTION_PROBE_URL"], content=_payload(kwargs, response_obj, type(self).__name__, "sync")
+ )
response.raise_for_status()
@@ -39,9 +44,16 @@ class RedactionProbe(CustomLogger):
) -> None:
async with httpx.AsyncClient(trust_env=False) as client:
response: Final = await client.post(
- os.environ["REDACTION_PROBE_URL"], content=_payload(kwargs, response_obj)
+ os.environ["REDACTION_PROBE_URL"], content=_payload(kwargs, response_obj, type(self).__name__, "async")
)
response.raise_for_status()
+class DualRedactionProbe(CustomLogger):
+ log_success_event = SyncRedactionProbe.log_success_event
+ async_log_success_event = RedactionProbe.async_log_success_event
+
+
probe: Final = RedactionProbe()
+sync_probe: Final = SyncRedactionProbe()
+dual_probe: Final = DualRedactionProbe()
diff --git a/tests/integration/spend/test_batch_completion_accounting.py b/tests/integration/spend/test_batch_completion_accounting.py
index bbc0300b3f0..6973864117c 100644
--- a/tests/integration/spend/test_batch_completion_accounting.py
+++ b/tests/integration/spend/test_batch_completion_accounting.py
@@ -4,11 +4,16 @@ import json
import uuid
from datetime import datetime, timedelta, timezone
from hashlib import sha256
+from pathlib import Path
+from queue import SimpleQueue
from typing import Final
import pytest
+import yaml
from integration._support.client import JSON_OBJECT, Gateway, eventually, object_value, string_value
-from integration._support.database import read_rows
+from integration._support.database import read_rows, scratch_database
+from integration._support.process import owned_proxy
+from integration._support.wire import Reply, Request, wire_server
from integration._support.upstream import delete_scenario, register_scenario
from integration.cost_calculation.cost_tracking_case import JsonResponse, RoutedResponse, TextResponse
from pydantic import JsonValue
@@ -299,3 +304,129 @@ def test_completed_batch_spend_lands_under_batches_in_team_endpoint_activity(gat
endpoint_metrics: Final = object_value(object_value(endpoints["/batches"])["metrics"])
assert float(endpoint_metrics["spend"]) == pytest.approx(BATCH_SPEND), endpoints
assert endpoint_metrics["total_tokens"] == BATCH_PROMPT_TOKENS + BATCH_COMPLETION_TOKENS, endpoints
+
+
+def test_batch_reconciliation_delivers_each_configured_logger_once(gateway: Gateway, tmp_path: Path) -> None:
+ events: Final[SimpleQueue[dict[str, JsonValue]]] = SimpleQueue()
+
+ def receive(request: Request) -> Reply:
+ payload: Final = JSON_OBJECT.validate_json(request.body)
+ standard: Final = object_value(payload.get("standard"))
+ if standard.get("call_type") == "aretrieve_batch" and standard.get("response_cost"):
+ events.put(payload)
+ return Reply()
+
+ config: Final = tmp_path / "batch-callbacks.yaml"
+ config.write_text(
+ yaml.safe_dump(
+ {
+ "model_list": [
+ {
+ "model_name": "batch-bootstrap",
+ "litellm_params": {
+ "model": "openai/gpt-6.1-sol",
+ "api_base": gateway.upstream_url + "/v1",
+ "api_key": "integration-provider-key",
+ },
+ }
+ ],
+ "litellm_settings": {
+ "callbacks": [
+ "integration._support.redaction_probe.sync_probe",
+ "integration._support.redaction_probe.probe",
+ "integration._support.redaction_probe.dual_probe",
+ ],
+ },
+ "general_settings": {
+ "master_key": "os.environ/LITELLM_MASTER_KEY",
+ "database_url": "os.environ/DATABASE_URL",
+ "disable_model_info_refresh": True,
+ "proxy_batch_polling_interval": 1,
+ },
+ }
+ )
+ )
+ with scratch_database() as database, wire_server(receive) as sink:
+ with (
+ owned_proxy(
+ gateway,
+ tmp_path,
+ {"DATABASE_URL": database, "REDACTION_PROBE_URL": sink.url, "PROXY_BATCH_POLLING_ENABLED": "true"},
+ config=config,
+ ) as proxy,
+ proxy.scenario() as scenario,
+ ):
+ scenario_id: Final = f"batch-callbacks-{uuid.uuid4().hex}"
+ routes: Final = batch_routes("gpt-6.1-sol")
+ handle: Final = register_scenario(scenario_id, routes)
+ scenario.cleanups.callback(delete_scenario, handle)
+ model: Final = scenario.model(
+ model="openai/gpt-6.1-sol",
+ api_base=handle.api_base(),
+ input_cost_per_token=INPUT_COST_PER_TOKEN,
+ output_cost_per_token=OUTPUT_COST_PER_TOKEN,
+ )
+ register_scenario(
+ scenario_id,
+ routes.model_copy(
+ update={
+ "routes": {
+ **routes.routes,
+ "GET /files/file-in-$REQUEST_ID/content": TextResponse(
+ content_type="application/jsonl", body=batch_input_file(model).decode()
+ ),
+ }
+ }
+ ),
+ )
+ key: Final = scenario.key(models=[model])
+ uploaded: Final = proxy.request_multipart(
+ "/v1/files",
+ {"purpose": "batch", "target_model_names": model},
+ {"file": ("in.jsonl", batch_input_file(model), "application/jsonl")},
+ key=key,
+ )
+ assert uploaded.status_code == 200, uploaded.text
+ created: Final = proxy.request(
+ "POST",
+ "/v1/batches",
+ {
+ "input_file_id": string_value(JSON_OBJECT.validate_json(uploaded.content)["id"]),
+ "endpoint": "/v1/chat/completions",
+ "completion_window": "24h",
+ "model": model,
+ },
+ key=key,
+ )
+ assert created.status_code == 200, created.text
+ assert eventually(events.qsize, lambda count: count >= 3, seconds=90) == 3
+ rows: Final = eventually(
+ lambda: read_rows(
+ 'SELECT spend, prompt_tokens, completion_tokens FROM "LiteLLM_SpendLogs" '
+ "WHERE api_key=%s AND call_type='aretrieve_batch'",
+ (sha256(key.encode()).hexdigest(),),
+ database_url=database,
+ ),
+ lambda values: len(values) == 1,
+ seconds=70,
+ )
+ assert float(rows[0]["spend"]) == pytest.approx(BATCH_SPEND)
+ assert (rows[0]["prompt_tokens"], rows[0]["completion_tokens"]) == (
+ BATCH_PROMPT_TOKENS,
+ BATCH_COMPLETION_TOKENS,
+ )
+ assert events.qsize() == 3
+ received: Final = tuple(events.get_nowait() for _ in range(3))
+ assert {(event["logger"], event["hook"]) for event in received} == {
+ ("SyncRedactionProbe", "sync"),
+ ("RedactionProbe", "async"),
+ ("DualRedactionProbe", "async"),
+ }
+ for event in received:
+ standard: Final = object_value(event["standard"])
+ assert standard["response_cost"] == pytest.approx(BATCH_SPEND)
+ usage: Final = object_value(object_value(event["response"])["usage"])
+ assert (usage["prompt_tokens"], usage["completion_tokens"]) == (
+ BATCH_PROMPT_TOKENS,
+ BATCH_COMPLETION_TOKENS,
+ )
diff --git a/tests/unit/litellm_core_utils/test_litellm_logging.py b/tests/unit/litellm_core_utils/test_litellm_logging.py
index c7450c852c0..e392ee746b3 100644
--- a/tests/unit/litellm_core_utils/test_litellm_logging.py
+++ b/tests/unit/litellm_core_utils/test_litellm_logging.py
@@ -2238,31 +2238,42 @@ async def test_async_success_handler_truncates_large_base64_off_the_event_loop(m
@pytest.mark.parametrize(
- "async_flag",
+ ("async_flag", "for_async_request"),
[
- "acompletion",
- "aresponses",
- "allm_passthrough_route",
- "aanthropic_messages",
- "agenerate_content",
- "agenerate_content_stream",
+ ("acompletion", False),
+ ("aresponses", False),
+ ("allm_passthrough_route", False),
+ ("aanthropic_messages", False),
+ ("agenerate_content", False),
+ ("agenerate_content_stream", False),
+ (None, True),
],
)
-def test_success_handler_skips_sync_callbacks_for_async_requests(logging_obj, async_flag):
- """Ensure sync success callbacks are skipped when async call type flags are set."""
+def test_success_handler_skips_sync_callbacks_for_async_requests(
+ logging_obj: LitellmLogging, async_flag: str | None, for_async_request: bool
+) -> None:
from litellm.integrations.custom_logger import CustomLogger
class DummyLogger(CustomLogger):
- pass
+ async def async_log_success_event(
+ self,
+ kwargs: dict[str, object],
+ response_obj: object,
+ start_time: datetime.datetime,
+ end_time: datetime.datetime,
+ ) -> None:
+ return None
logging_obj.stream = False # simulate non-streaming request where sync callbacks would normally run
- logging_obj.model_call_details["litellm_params"] = {async_flag: True}
+ logging_obj.model_call_details["litellm_params"] = {async_flag: True} if async_flag else {}
logging_obj.litellm_params = logging_obj.model_call_details["litellm_params"]
dummy_logger = DummyLogger()
dummy_logger.log_success_event = MagicMock()
dummy_logger.log_stream_event = MagicMock()
+ logging_obj.dynamic_async_success_callbacks = [dummy_logger]
+
model_response = ModelResponse(
id="resp-123",
model="gpt-4o-mini",
@@ -2281,14 +2292,17 @@ def test_success_handler_skips_sync_callbacks_for_async_requests(logging_obj, as
"get_combined_callback_list",
return_value=[dummy_logger],
):
- logging_obj.success_handler(result=model_response)
+ logging_obj.success_handler(result=model_response, for_async_request=for_async_request)
dummy_logger.log_success_event.assert_not_called()
dummy_logger.log_stream_event.assert_not_called()
@pytest.mark.parametrize("call_type", ["completion", "responses"])
-def test_success_handler_runs_sync_callbacks_for_sync_requests(logging_obj, call_type):
[email protected]("for_async_request", [False, True])
+def test_success_handler_runs_sync_callbacks_for_sync_requests(
+ logging_obj: LitellmLogging, call_type: str, for_async_request: bool, monkeypatch: pytest.MonkeyPatch
+) -> None:
"""Ensure sync success callbacks execute when call type is sync (completion/responses)."""
from litellm.integrations.custom_logger import CustomLogger
@@ -2317,17 +2331,160 @@ def test_success_handler_runs_sync_callbacks_for_sync_requests(logging_obj, call
usage={"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2},
)
- with patch.object(
- logging_obj,
- "get_combined_callback_list",
- return_value=[dummy_logger],
- ):
- logging_obj.success_handler(result=model_response)
+ logging_obj.dynamic_success_callbacks = [dummy_logger]
+ logging_obj.dynamic_async_success_callbacks = []
+ monkeypatch.setattr(litellm, "success_callback", [])
+ monkeypatch.setattr(litellm, "_async_success_callback", [])
+ logging_obj.success_handler(result=model_response, for_async_request=for_async_request)
dummy_logger.log_success_event.assert_called_once()
dummy_logger.log_stream_event.assert_not_called()
[email protected]("registration", ["sync", "async", "overlapping"])
[email protected]("kind", ["sync", "async", "dual"])
[email protected]("compatibility_first", [False, True])
+async def test_completed_success_selects_one_implemented_hook(
+ monkeypatch: pytest.MonkeyPatch, registration: str, kind: str, compatibility_first: bool
+) -> None:
+ from concurrent.futures import ThreadPoolExecutor
+ from queue import SimpleQueue
+
+ events: Final[SimpleQueue[tuple[str, str, object, int]]] = SimpleQueue()
+ loop_thread: Final = threading.get_ident()
+
+ def record(hook: str, kwargs: dict[str, object], response_obj: object) -> None:
+ assert isinstance(response_obj, ModelResponse)
+ events.put((hook, response_obj.id, kwargs["response_cost"], threading.get_ident()))
+
+ class SyncRecorder(CustomLogger):
+ def log_success_event(
+ self,
+ kwargs: dict[str, object],
+ response_obj: object,
+ start_time: datetime.datetime,
+ end_time: datetime.datetime,
+ ) -> None:
+ record("sync", kwargs, response_obj)
+
+ class AsyncRecorder(CustomLogger):
+ async def async_log_success_event(
+ self,
+ kwargs: dict[str, object],
+ response_obj: object,
+ start_time: datetime.datetime,
+ end_time: datetime.datetime,
+ ) -> None:
+ record("async", kwargs, response_obj)
+
+ class DualRecorder(CustomLogger):
+ def log_success_event(
+ self,
+ kwargs: dict[str, object],
+ response_obj: object,
+ start_time: datetime.datetime,
+ end_time: datetime.datetime,
+ ) -> None:
+ record("sync", kwargs, response_obj)
+
+ async def async_log_success_event(
+ self,
+ kwargs: dict[str, object],
+ response_obj: object,
+ start_time: datetime.datetime,
+ end_time: datetime.datetime,
+ ) -> None:
+ record("async", kwargs, response_obj)
+
+ callback: Final = {"sync": SyncRecorder, "async": AsyncRecorder, "dual": DualRecorder}[kind]()
+ monkeypatch.setattr(litellm, "success_callback", [callback] if registration != "async" else [])
+ monkeypatch.setattr(litellm, "_async_success_callback", [callback] if registration != "sync" else [])
+ logging_obj: Final = _async_request_logging_obj("completed-hook", [])
+ response: Final = ModelResponse(id="chatcmpl-completed-hook")
+ now: Final = datetime.datetime.now()
+
+ with ThreadPoolExecutor(max_workers=1) as pool:
+ monkeypatch.setattr(litellm_logging, "executor", pool)
+ if compatibility_first:
+ logging_obj.handle_sync_success_callbacks_for_async_calls(response, now, now)
+ await logging_obj.async_success_handler(response, now, now)
+ logging_obj.handle_sync_success_callbacks_for_async_calls(response, now, now)
+
+ assert events.qsize() == 1
+ hook, response_id, cost, thread_id = events.get_nowait()
+ assert hook == ("sync" if kind == "sync" else "async")
+ assert response_id == response.id
+ assert cost == logging_obj.model_call_details["response_cost"]
+ assert (thread_id == loop_thread) is (kind != "sync")
+
+
+
[email protected]("for_async_request", [False, True])
[email protected]("private_first", [False, True])
[email protected]("response_kind", ["responses", "completion"])
+def test_sync_success_redacts_only_opted_out_loggers(
+ monkeypatch: pytest.MonkeyPatch, for_async_request: bool, private_first: bool, response_kind: str
+) -> None:
+ from queue import SimpleQueue
+
+ events: Final[SimpleQueue[tuple[bool, str]]] = SimpleQueue()
+
+ class PayloadRecorder(CustomLogger):
+ def log_success_event(
+ self,
+ kwargs: dict[str, object],
+ response_obj: object,
+ start_time: datetime.datetime,
+ end_time: datetime.datetime,
+ ) -> None:
+ events.put((self.turn_off_message_logging, json.dumps(kwargs["standard_logging_object"])))
+
+ private_logger: Final = PayloadRecorder(turn_off_message_logging=True)
+ public_logger: Final = PayloadRecorder()
+ callbacks: Final = [private_logger, public_logger] if private_first else [public_logger, private_logger]
+ monkeypatch.setattr(litellm, "success_callback", callbacks)
+ monkeypatch.setattr(litellm, "_async_success_callback", [])
+ monkeypatch.setattr(litellm, "turn_off_message_logging", False)
+ logging_obj: Final = LitellmLogging(
+ model="openai/gpt-6.1-sol",
+ messages=[{"role": "user", "content": "private-request-marker"}],
+ stream=False,
+ call_type="aget_responses",
+ start_time=datetime.datetime.now(),
+ litellm_call_id="callback-redaction",
+ function_id="callback-redaction",
+ )
+ logging_obj.update_environment_variables(litellm_params={}, optional_params={}, custom_llm_provider="openai")
+ response: Final = (
+ _responses_api_response_with_text("private-response-marker")
+ if response_kind == "responses"
+ else ModelResponse(
+ id="chatcmpl-private",
+ model="openai/gpt-6.1-sol",
+ choices=[{"message": {"role": "assistant", "content": "private-response-marker"}}],
+ usage=Usage(prompt_tokens=11, completion_tokens=7, total_tokens=18),
+ )
+ )
+ logging_obj.success_handler(result=response, for_async_request=for_async_request)
+
+ assert events.qsize() == 2
+ payloads: Final = dict(events.get_nowait() for _ in range(2))
+ assert "private-request-marker" not in payloads[True]
+ assert "private-response-marker" not in payloads[True]
+ assert REDACTED_BY_LITELLM in payloads[True]
+ assert "private-request-marker" in payloads[False]
+ assert "private-response-marker" in payloads[False]
+ private_payload, public_payload = json.loads(payloads[True]), json.loads(payloads[False])
+ assert private_payload["total_tokens"] == public_payload["total_tokens"]
+ assert private_payload["response"]["usage"] == public_payload["response"]["usage"]
+ assert private_payload["response"]["usage"]["total_tokens"] == response.usage.total_tokens
+ assert private_payload["response"]["id"] == public_payload["response"]["id"]
+ assert private_payload["response"]["model"] == public_payload["response"]["model"]
+ assert private_payload["response_cost"] == public_payload["response_cost"]
+ assert "private-response-marker" in response.model_dump_json()
+
+
class _PhaseRecordingLogger(CustomLogger):
"""Records whether each success callback ran inside the post-response phase."""
@@ -6526,35 +6683,57 @@ def test_in_progress_background_create_is_not_billed(call_type):
@pytest.mark.asyncio
-async def test_background_interaction_completion_rebills_after_in_progress_success():
+async def test_background_interaction_completion_rebills_after_in_progress_success(monkeypatch: pytest.MonkeyPatch):
import datetime as dt
+ from concurrent.futures import ThreadPoolExecutor
+ from queue import SimpleQueue
from litellm.types.interactions import InteractionsAPIResponse
- logging_obj = _interactions_logging_obj(stream=False)
- in_progress = InteractionsAPIResponse(id="interactions/abc", model="gemini-2.5-flash", status="in_progress")
- await logging_obj.async_success_handler(
- result=in_progress,
- start_time=dt.datetime.now(),
- end_time=dt.datetime.now(),
- )
+ events: Final[SimpleQueue[tuple[object, object]]] = SimpleQueue()
+ logged: Final = threading.Event()
- assert logging_obj.model_call_details.get("response_cost") is None
- assert logging_obj.should_run_logging(event_type="async_success") is False
+ class SyncRecorder(CustomLogger):
+ def log_success_event(
+ self, kwargs: dict[str, object], response_obj: object,
+ start_time: dt.datetime, end_time: dt.datetime,
+ ) -> None:
+ events.put((response_obj, kwargs.get("response_cost")))
+ logged.set()
- completed = InteractionsAPIResponse(
- id="interactions/abc",
- model="gemini-2.5-flash",
- status="completed",
- steps=[],
- usage=dict(INTERACTIONS_USAGE_BLOCK),
- )
- await logging_obj.async_log_background_interaction_completion(result=completed)
+ monkeypatch.setattr(litellm, "success_callback", [SyncRecorder()])
+ monkeypatch.setattr(litellm, "_async_success_callback", [])
+ with ThreadPoolExecutor(max_workers=1) as pool:
+ monkeypatch.setattr(litellm_logging, "executor", pool)
+ logging_obj = _interactions_logging_obj(stream=False)
+ in_progress = InteractionsAPIResponse(id="interactions/abc", model="gemini-2.5-flash", status="in_progress")
+ await logging_obj.async_success_handler(
+ result=in_progress,
+ start_time=dt.datetime.now(),
+ end_time=dt.datetime.now(),
+ )
- assert logging_obj.model_call_details["response_cost"] > 0
- assert logging_obj.model_call_details["standard_logging_object"]["total_tokens"] == 175
+ assert await asyncio.to_thread(logged.wait, 10)
+ assert logging_obj.model_call_details.get("response_cost") is None
+ assert logging_obj.should_run_logging(event_type="async_success") is False
+
+ completed = InteractionsAPIResponse(
+ id="interactions/abc",
+ model="gemini-2.5-flash",
+ status="completed",
+ steps=[],
+ usage=dict(INTERACTIONS_USAGE_BLOCK),
+ )
+ await logging_obj.async_log_background_interaction_completion(result=completed)
+
+ assert logging_obj.model_call_details["response_cost"] > 0
+ assert logging_obj.model_call_details["standard_logging_object"]["total_tokens"] == 175
+ assert events.qsize() == 2
+ assert events.get_nowait() == (in_progress, None)
+ assert events.get_nowait() == (completed, logging_obj.model_call_details["response_cost"])
+
@pytest.mark.asyncio
async def test_background_interaction_completion_prices_the_settled_body_itself():
"""
@@ -7797,6 +7976,7 @@ async def test_sync_only_logger_keeps_the_async_payload_when_its_result_builds_n
monkeypatch: pytest.MonkeyPatch,
) -> None:
sync_payloads: Final[list[object]] = []
+ sync_logged: Final = threading.Event()
class AthinaRecorder:
def log_event(
@@ -7808,9 +7988,10 @@ async def test_sync_only_logger_keeps_the_async_payload_when_its_result_builds_n
print_verbose: object,
) -> None:
sync_payloads.append(kwargs.get("standard_logging_object"))
+ sync_logged.set()
monkeypatch.setattr(litellm, "_async_success_callback", [])
- monkeypatch.setattr(litellm, "success_callback", ["athina"])
+ monkeypatch.setattr(litellm, "success_callback", [_ResponseEditingHook(), "athina"])
monkeypatch.setattr(litellm_logging, "athinaLogger", AthinaRecorder())
logging_obj: Final = LitellmLogging(
model="pass-through-model",
@@ -7827,9 +8008,7 @@ async def test_sync_only_logger_keeps_the_async_payload_when_its_result_builds_n
async_payload: Final = logging_obj.model_call_details.get("standard_logging_object")
assert isinstance(async_payload, dict)
async_payload_before_sync: Final = dict(async_payload)
- monkeypatch.setattr(litellm, "success_callback", [_ResponseEditingHook(), "athina"])
-
- logging_obj.success_handler(result=raw_body, for_async_request=True)
+ assert sync_logged.wait(timeout=10)
assert sync_payloads == [{**async_payload_before_sync, "response": "edited by sync hook"}]
assert logging_obj.model_call_details["standard_logging_object"] is async_payload
diff --git a/tests/unit/proxy/common_utils/test_check_batch_cost.py b/tests/unit/proxy/common_utils/test_check_batch_cost.py
index eb2a5b7f66c..1253e15676b 100644
--- a/tests/unit/proxy/common_utils/test_check_batch_cost.py
+++ b/tests/unit/proxy/common_utils/test_check_batch_cost.py
@@ -9,12 +9,17 @@ ARN unified_object_id) batches with no managed unified id.
import asyncio
import json
import logging
+from concurrent.futures import ThreadPoolExecutor
from contextlib import contextmanager
+from datetime import datetime
from hashlib import sha256
-from typing import TYPE_CHECKING, Final
+from queue import SimpleQueue
+from types import SimpleNamespace
+from typing import TYPE_CHECKING, Final, Literal
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
+import respx
from fastapi import HTTPException
from litellm.types.utils import LiteLLMBatch
@@ -1659,10 +1664,9 @@ class TestCheckBatchCost:
model_name="gpt-5-batch",
)
assert mock_hook.store_batch_output_file.await_count == 2
- assert {
- call.kwargs["model_name"]
- for call in mock_hook.store_batch_output_file.await_args_list
- } == {"gpt-5-batch"}
+ assert {call.kwargs["model_name"] for call in mock_hook.store_batch_output_file.await_args_list} == {
+ "gpt-5-batch"
+ }
stored = {
c.kwargs["provider_file_id"]: c.kwargs["unified_file_id"]
for c in mock_hook.store_batch_output_file.call_args_list
@@ -2521,9 +2525,7 @@ class TestBatchCostAttribution:
async def test_raw_cli_session_token_on_a_legacy_batch_row_is_not_treated_as_the_alias(self):
instance = self._instance(key_row=None)
- metadata = await instance.batch_metadata(
- self._job(api_key="cli-session-Qm7xJ2kP9sLw4vT1nR8yAa"), "batch-1"
- )
+ metadata = await instance.batch_metadata(self._job(api_key="cli-session-Qm7xJ2kP9sLw4vT1nR8yAa"), "batch-1")
assert metadata.get("user_api_key_alias") is None
@@ -3732,9 +3734,7 @@ class TestBatchLineItemsFromThePoller:
assert len(logger.payloads) == stored
@pytest.mark.asyncio
- async def test_a_batch_whose_output_file_is_gone_still_sends_its_error_lines_after_it_is_retired(
- self, monkeypatch
- ):
+ async def test_a_batch_whose_output_file_is_gone_still_sends_its_error_lines_after_it_is_retired(self, monkeypatch):
import litellm
journal: list = []
@@ -3834,7 +3834,6 @@ class TestBatchLineItemsFromThePoller:
assert row.batch_processed is True
assert f"so the line items of batch batch-456 (job {row.id}) were not stored" in caplog.text
-
@pytest.mark.asyncio
async def test_batches_store_their_lines_one_at_a_time_in_the_order_they_were_retired(self, monkeypatch):
import litellm
@@ -4109,3 +4108,166 @@ class TestCreatorTurnedOffMessageLogging:
assert await instance._creator_turned_off_message_logging(self._job(api_key=api_key)) is False
instance.prisma_client.db.litellm_verificationtoken.find_unique.assert_not_called()
+
+
+ "kind", ["sync", "async", "custom", "overlapping", "general", "mixed", "sync_only", "executor_shutdown"]
+)
[email protected]("initialized", [False, True])
[email protected]("claimed", [False, True])
+async def test_batch_cost_reaches_configured_success_callbacks(
+ kind: Literal["sync", "async", "custom", "overlapping", "general", "mixed", "sync_only", "executor_shutdown"],
+ initialized: bool,
+ claimed: bool,
+) -> None:
+ import litellm
+ from litellm.integrations.custom_logger import CustomLogger
+ from litellm.litellm_core_utils.logging_worker import GLOBAL_LOGGING_WORKER
+ from litellm.types.utils import LiteLLMBatch
+ from litellm_enterprise.proxy.common_utils.check_batch_cost import CheckBatchCost
+
+ events: Final[SimpleQueue[tuple[str, object, int, int]]] = SimpleQueue()
+
+ def record(
+ kwargs: dict[str, object],
+ response_obj: object,
+ start_time: datetime,
+ end_time: datetime,
+ recipient: str = "function",
+ ) -> None:
+ if kwargs.get("call_type") != "aretrieve_batch":
+ return
+ assert isinstance(response_obj, LiteLLMBatch)
+ assert response_obj.usage is not None
+ events.put(
+ (recipient, kwargs["response_cost"], response_obj.usage.prompt_tokens, response_obj.usage.completion_tokens)
+ )
+
+ async def async_record(
+ kwargs: dict[str, object], response_obj: object, start_time: datetime, end_time: datetime
+ ) -> None:
+ record(kwargs, response_obj, start_time, end_time)
+ if kind == "executor_shutdown" and kwargs.get("call_type") == "aretrieve_batch":
+ executor.shutdown(wait=True)
+
+ class BatchRecorder(CustomLogger):
+ def log_success_event(
+ self, kwargs: dict[str, object], response_obj: object, start_time: datetime, end_time: datetime
+ ) -> None:
+ record(kwargs, response_obj, start_time, end_time, "custom")
+
+ async def async_log_success_event(
+ self, kwargs: dict[str, object], response_obj: object, start_time: datetime, end_time: datetime
+ ) -> None:
+ record(kwargs, response_obj, start_time, end_time, "custom")
+
+ class SyncRecorder(CustomLogger):
+ def log_success_event(
+ self, kwargs: dict[str, object], response_obj: object, start_time: datetime, end_time: datetime
+ ) -> None:
+ record(kwargs, response_obj, start_time, end_time, "custom")
+
+ callback: Final = SyncRecorder() if kind == "sync_only" else BatchRecorder()
+ match kind:
+ case "sync":
+ litellm.logging_callback_manager.add_litellm_success_callback(record)
+ case "async":
+ litellm.logging_callback_manager.add_litellm_success_callback(async_record)
+ case "executor_shutdown":
+ litellm.logging_callback_manager.add_litellm_success_callback(async_record)
+ litellm.logging_callback_manager.add_litellm_success_callback(record)
+ case "custom" | "overlapping" | "sync_only":
+ litellm.logging_callback_manager.add_litellm_success_callback(callback)
+ if kind == "overlapping":
+ litellm.logging_callback_manager.add_litellm_async_success_callback(callback)
+ case "general":
+ litellm.logging_callback_manager.add_litellm_callback(callback)
+ case "mixed":
+ litellm.logging_callback_manager.add_litellm_success_callback(callback)
+ litellm.logging_callback_manager.add_litellm_success_callback(record)
+
+ model: Final = "gpt-6.1-sol"
+ credentials: Final = {
+ "api_key": "synthetic-key",
+ "api_base": "https://batch.invalid/v1",
+ "custom_llm_provider": "openai",
+ }
+ deployment: Final = SimpleNamespace(
+ litellm_params=SimpleNamespace(model=f"openai/{model}", custom_llm_provider="openai", api_base=None),
+ model_name="batch-group",
+ )
+ prisma: Final = MagicMock()
+ prisma.db.litellm_managedobjecttable.update_many = AsyncMock(return_value=int(claimed))
+ checker: Final = CheckBatchCost(
+ proxy_logging_obj=SimpleNamespace(get_proxy_hook=lambda _: None),
+ prisma_client=prisma,
+ llm_router=SimpleNamespace(
+ get_deployment_credentials_with_provider=lambda _: credentials,
+ get_deployment=lambda **_: deployment,
+ ),
+ )
+ job: Final = SimpleNamespace(
+ id="job",
+ unified_object_id="batch-record",
+ status="in_progress",
+ file_object={},
+ created_by=None,
+ team_id=None,
+ api_key=None,
+ org_id=None,
+ request_tags=None,
+ )
+ response: Final = LiteLLMBatch(
+ id="batch-record",
+ completion_window="24h",
+ created_at=1,
+ endpoint="/v1/chat/completions",
+ input_file_id="input",
+ object="batch",
+ status="completed",
+ output_file_id="output",
+ )
+ output: Final = json.dumps(
+ {
+ "id": "line",
+ "response": {
+ "status_code": 200,
+ "body": {
+ "model": model,
+ "usage": {"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15},
+ "choices": [
+ {"index": 0, "message": {"role": "assistant", "content": "ok"}, "finish_reason": "stop"}
+ ],
+ },
+ },
+ }
+ ).encode()
+ with (
+ ThreadPoolExecutor(max_workers=1) as executor,
+ patch("litellm.litellm_core_utils.litellm_logging.executor", executor),
+ respx.mock(assert_all_called=True) as transport,
+ ):
+ transport.get("https://batch.invalid/v1/files/output/content").respond(200, content=output)
+ if initialized:
+ await litellm.afile_content(file_id="output", **credentials)
+ await GLOBAL_LOGGING_WORKER.flush()
+ result: Final = await checker._track_completed_batch_cost(job, response, "deployment", "batch-record", None)
+ assert result == ((model, "openai") if claimed else None)
+ if kind == "executor_shutdown" and claimed:
+ prisma.db.litellm_managedobjecttable.update_many.assert_awaited_once()
+ await GLOBAL_LOGGING_WORKER.flush()
+ recipients: Final = (
+ ("custom", "function")
+ if kind == "mixed"
+ else ("custom",)
+ if kind in ("custom", "overlapping", "general", "sync_only")
+ else ("function",)
+ )
+ expected: Final = recipients if claimed else ()
+ assert events.qsize() == len(expected)
+ received: Final = tuple(events.get_nowait() for _ in expected)
+ assert tuple(sorted(event[0] for event in received)) == expected
+ for _, cost, prompt_tokens, completion_tokens in received:
+ assert isinstance(cost, float) and cost > 0
+ assert (prompt_tokens, completion_tokens) == (10, 5)
diff --git a/tests/unit/proxy/guardrails/test_guardrail_endpoints.py b/tests/unit/proxy/guardrails/test_guardrail_endpoints.py
index 2e968ec04f5..6807a4fb569 100644
--- a/tests/unit/proxy/guardrails/test_guardrail_endpoints.py
+++ b/tests/unit/proxy/guardrails/test_guardrail_endpoints.py
@@ -125,6 +125,7 @@ def test_get_guardrails_list_response() -> None:
assert minimal_response.guardrails[0].guardrail_name == "minimal-guard"
assert minimal_response.guardrails[0].guardrail_info is None
+
_INVALID_SCOPE_LITELLM_PARAMS: Final = MappingProxyType(
{
"guardrail": "litellm_content_filter",
@@ -655,6 +656,8 @@ async def test_get_guardrail_info_tolerates_invalid_stored_stream_scope(mocker,
response = await get_guardrail_info("test-db-guardrail")
assert response.litellm_params.stream_scope is None
+
+
async def test_get_guardrail_info_normalizes_invalid_scope_from_db(
mocker, mock_guardrail_registry, mock_in_memory_handler
):
@@ -2159,7 +2162,6 @@ async def test_apply_guardrail_invokes_logging_pipeline(mocker):
mock_proxy_logging.post_call_success_hook.assert_awaited_once()
mock_logging_obj.async_success_handler.assert_awaited_once()
assert mock_logging_obj.call_type == "pass_through_endpoint"
- mock_executor.submit.assert_called_once()
assert mock_logging_obj.async_success_handler.await_args.kwargs["result"] == {
"response": {"response_text": "masked"}
}
@@ -3624,3 +3626,68 @@ async def test_patch_guardrail_rejects_encrypted_marker_values(mocker, mock_guar
assert exc_info.value.status_code == 400
mock_guardrail_registry.update_guardrail_in_db.assert_not_called()
+
+
+async def test_guardrail_success_delivers_sync_callback_once_with_overlapping_workers(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ from concurrent.futures import ThreadPoolExecutor
+ from threading import Barrier
+ from unittest.mock import Mock
+
+ import litellm
+ from litellm.integrations.custom_logger import CustomLogger
+ from litellm.litellm_core_utils import litellm_logging, thread_pool_executor
+ from litellm.proxy.guardrails.guardrail_endpoints import _emit_guardrail_success_logs
+ from litellm.types.guardrails import ApplyGuardrailResponse
+
+ class OverlappingHook(CustomLogger):
+ barrier: Barrier
+
+ def logging_hook(
+ self, kwargs: dict[str, object], result: object, call_type: str
+ ) -> tuple[dict[str, object], object]:
+ self.barrier.wait(timeout=5)
+ return kwargs, result
+
+ hook: Final = OverlappingHook()
+ callback: Final = Mock()
+ queued_executor: Final = Mock()
+ proxy_logging: Final = Mock(post_call_success_hook=AsyncMock(return_value=None))
+
+ def sync_callback(kwargs: dict[str, object], response_obj: object, start_time: object, end_time: object) -> None:
+ callback(response_obj)
+
+ monkeypatch.setattr(litellm, "success_callback", [hook, sync_callback])
+ monkeypatch.setattr(litellm, "_async_success_callback", [])
+ monkeypatch.setattr(litellm_logging, "customLogger", CustomLogger())
+ monkeypatch.setattr(litellm_logging, "executor", queued_executor)
+ monkeypatch.setattr(thread_pool_executor, "executor", queued_executor)
+ start: Final = datetime(2026, 1, 1)
+ logging_obj: Final = litellm_logging.Logging(
+ model="guardrail",
+ messages=[],
+ stream=False,
+ call_type="pass_through_endpoint",
+ start_time=start,
+ litellm_call_id="guardrail-success",
+ function_id="guardrail-success",
+ )
+ logging_obj.update_environment_variables(litellm_params={"metadata": {}}, optional_params={})
+ response: Final = ApplyGuardrailResponse(response_text="masked")
+
+ returned: Final = await _emit_guardrail_success_logs(
+ proxy_logging, logging_obj, {}, UserAPIKeyAuth(), response, start
+ )
+ submissions: Final = tuple(queued_executor.submit.call_args_list)
+ assert submissions
+ hook.barrier = Barrier(len(submissions))
+ with ThreadPoolExecutor(max_workers=len(submissions)) as pool:
+ futures: Final = tuple(pool.submit(call.args[0], *call.args[1:], **call.kwargs) for call in submissions)
+ for future in futures:
+ future.result(timeout=10)
+
+ assert returned is response
+ callback.assert_called_once()
+ assert callback.call_args.args[0] == {"response": {"response_text": "masked"}}