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(guardrails): keep remaining usage upserts when one write fails

mateo-berrib7593a99c74a
diff --git a/litellm/proxy/guardrails/usage_endpoints.py b/litellm/proxy/guardrails/usage_endpoints.py
index be324e3d81b..da29f27458d 100644
--- a/litellm/proxy/guardrails/usage_endpoints.py
+++ b/litellm/proxy/guardrails/usage_endpoints.py
@@ -177,7 +177,7 @@ class UsageOverviewRow(BaseModel):
avgLatency: float | None
status: str # healthy | warning | critical
trend: str # up | down | stable
- usageUnits: Mapping[str, int] # provider counter name -> billable units in range
+ usageUnits: Mapping[str, int]
class UsageOverviewResponse(BaseModel):
@@ -209,8 +209,8 @@ class UsageDetailResponse(BaseModel):
time_series: list[UsageChartPoint]
usage_units: Mapping[str, int]
usage_units_daily: Sequence[UsageUnitsDailyPoint]
- usage_units_by_team: Mapping[str, Mapping[str, int]] # team_id ("" = no team) -> counter -> units
- usage_units_by_key: Mapping[str, Mapping[str, int]] # hashed api key ("" = unknown) -> counter -> units
+ usage_units_by_team: Mapping[str, Mapping[str, int]]
+ usage_units_by_key: Mapping[str, Mapping[str, int]]
class UsageLogEntry(BaseModel):
diff --git a/litellm/proxy/guardrails/usage_tracking.py b/litellm/proxy/guardrails/usage_tracking.py
index cebf329b601..22c98868598 100644
--- a/litellm/proxy/guardrails/usage_tracking.py
+++ b/litellm/proxy/guardrails/usage_tracking.py
@@ -196,32 +196,47 @@ async def process_spend_logs_guardrail_usage(
n = int(agg["requests_evaluated"])
if n == 0:
continue
- await DailyGuardrailMetricsRepository(prisma_client).table.upsert(
- where={
- "guardrail_id_date": {
- "guardrail_id": guardrail_id,
- "date": date_key,
- }
- },
- data={
- "create": {
- "guardrail_id": guardrail_id,
- "date": date_key,
- "requests_evaluated": n,
- "passed_count": int(agg["passed_count"]),
- "blocked_count": int(agg["blocked_count"]),
- "flagged_count": int(agg["flagged_count"]),
+ try:
+ await DailyGuardrailMetricsRepository(prisma_client).table.upsert(
+ where={
+ "guardrail_id_date": {
+ "guardrail_id": guardrail_id,
+ "date": date_key,
+ }
},
- "update": {
- "requests_evaluated": {"increment": n},
- "passed_count": {"increment": int(agg["passed_count"])},
- "blocked_count": {"increment": int(agg["blocked_count"])},
- "flagged_count": {"increment": int(agg["flagged_count"])},
+ data={
+ "create": {
+ "guardrail_id": guardrail_id,
+ "date": date_key,
+ "requests_evaluated": n,
+ "passed_count": int(agg["passed_count"]),
+ "blocked_count": int(agg["blocked_count"]),
+ "flagged_count": int(agg["flagged_count"]),
+ },
+ "update": {
+ "requests_evaluated": {"increment": n},
+ "passed_count": {"increment": int(agg["passed_count"])},
+ "blocked_count": {"increment": int(agg["blocked_count"])},
+ "flagged_count": {"increment": int(agg["flagged_count"])},
+ },
},
- },
- )
+ )
+ except Exception as metrics_error:
+ verbose_proxy_logger.warning(
+ "Guardrail usage tracking: daily metrics upsert failed for %s on %s (non-fatal): %s",
+ guardrail_id,
+ date_key,
+ metrics_error,
+ )
for unit_key, units in usage_unit_totals.items():
- await _upsert_usage_unit_row(prisma_client, unit_key, units)
+ try:
+ await _upsert_usage_unit_row(prisma_client, unit_key, units)
+ except Exception as unit_error:
+ verbose_proxy_logger.warning(
+ "Guardrail usage tracking: usage unit upsert failed for %s (non-fatal): %s",
+ unit_key,
+ unit_error,
+ )
except Exception as e:
verbose_proxy_logger.warning("Guardrail usage tracking failed (non-fatal): %s", e)
diff --git a/litellm/proxy/hooks/proxy_track_cost_callback.py b/litellm/proxy/hooks/proxy_track_cost_callback.py
index da44c06040d..5dc92d82bda 100644
--- a/litellm/proxy/hooks/proxy_track_cost_callback.py
+++ b/litellm/proxy/hooks/proxy_track_cost_callback.py
@@ -125,10 +125,6 @@ class _ProxyDBLogger(CustomLogger):
existing_metadata: Final[dict] = request_data.get("metadata", None) or {}
existing_metadata.update(_metadata)
- # Guardrail hooks write standard_logging_guardrail_information into the
- # request's litellm_metadata bucket when one exists (get_or_create_metadata_bucket
- # prefers it). Failure rows are serialized from the metadata bucket lifted below,
- # so carry the guardrail info over or blocked invocations lose it in spend logs.
litellm_metadata_bucket: Final = request_data.get("litellm_metadata")
if (
isinstance(litellm_metadata_bucket, dict)
diff --git a/tests/test_litellm/proxy/guardrails/test_usage_tracking.py b/tests/test_litellm/proxy/guardrails/test_usage_tracking.py
index 7adc1dd314d..67953c66720 100644
--- a/tests/test_litellm/proxy/guardrails/test_usage_tracking.py
+++ b/tests/test_litellm/proxy/guardrails/test_usage_tracking.py
@@ -80,6 +80,26 @@ async def test_usage_units_rolled_up_by_guardrail_team_key_and_date():
}
+async def test_one_failing_upsert_does_not_drop_remaining_writes():
+ """
+ A DB error on one daily-metrics or usage-unit upsert must not cancel the
+ remaining upserts in the flushed batch, or the usage endpoints would
+ permanently under-report billable counters (batches are never retried).
+ """
+ prisma = _prisma()
+ prisma.db.litellm_dailyguardrailmetrics.upsert.side_effect = RuntimeError("db down")
+ prisma.db.litellm_dailyguardrailusageunits.upsert.side_effect = [RuntimeError("db down"), None]
+ logs = [
+ _payload("r1", usage={"topicPolicyUnits": 1}),
+ _payload("r2", team_id=None, api_key="hashed-key-2", usage={"topicPolicyUnits": 1}),
+ ]
+
+ await process_spend_logs_guardrail_usage(prisma, logs)
+
+ assert prisma.db.litellm_dailyguardrailusageunits.upsert.call_count == 2
+
+
@pytest.mark.asyncio
async def test_zero_and_non_int_usage_counters_are_skipped():
prisma = _prisma()