Skip to content

fix(guardrails): instrument during-call and post-call guardrail latency - #31414

Merged
yassin-berriai merged 1 commit into
litellm_internal_stagingfrom
litellm_guardrail_latency_during_post_hooks
Jun 26, 2026
Merged

yassin-berriai merged 1 commit into
litellm_internal_stagingfrom
litellm_guardrail_latency_during_post_hooks

Conversation

@yassin-berriai

@yassin-berriai yassin-berriai commented Jun 26, 2026 •

Copy link
Copy Markdown
Contributor

Relevant issues

Resolves LIT-3999

Linear ticket

LIT-3999

Pre-Submission checklist

Please complete all items before asking a LiteLLM maintainer to review your PR

  • I have added meaningful tests
  • My PR passes all CI/CD checks (e.g., lint, format, unit tests)
  • My PR's scope is as isolated as possible; it only solves 1 specific problem
  • I have requested a Greptile review by commenting @greptileai and received a Confidence Score of at least 4/5 before requesting a maintainer review (Greptile scored 5/5)

Screenshots / Proof of Fix

Local proxy with three guardrails of the same pass-through class attached in pre_call, during_call, and post_call mode, prometheus enabled, hitting a real OpenAI model. The guardrail sleeps a few ms per phase so the latency is visible.

config.yaml

model_list:
  - model_name: gpt-4o-mini
    litellm_params:
      model: openai/gpt-4o-mini
      api_key: os.environ/OPENAI_API_KEY

litellm_settings:
  callbacks: ["prometheus"]

guardrails:
  - guardrail_name: "phase-pre"
    litellm_params: { guardrail: phase_timing_guardrail.PhaseTimingGuardrail, mode: "pre_call", default_on: true }
  - guardrail_name: "phase-during"
    litellm_params: { guardrail: phase_timing_guardrail.PhaseTimingGuardrail, mode: "during_call", default_on: true }
  - guardrail_name: "phase-post"
    litellm_params: { guardrail: phase_timing_guardrail.PhaseTimingGuardrail, mode: "post_call", default_on: true }

phase_timing_guardrail.py

import asyncio
from litellm.integrations.custom_guardrail import CustomGuardrail


class PhaseTimingGuardrail(CustomGuardrail):
    async def async_pre_call_hook(self, user_api_key_dict, cache, data, call_type):
        await asyncio.sleep(0.02)
        return data

    async def async_moderation_hook(self, data, user_api_key_dict, call_type):
        await asyncio.sleep(0.03)
        return data

    async def async_post_call_success_hook(self, data, user_api_key_dict, response):
        await asyncio.sleep(0.04)
        return response

Send a few real completions, then scrape the metric.

for i in 1 2 3; do
  curl -s http://127.0.0.1:4999/v1/chat/completions \
    -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H "Content-Type: application/json" \
    -d '{"model":"gpt-4o-mini","messages":[{"role":"user","content":"Say hi"}]}' >/dev/null
done
curl -sL http://127.0.0.1:4999/metrics -H "Authorization: Bearer $LITELLM_MASTER_KEY" \
  | grep litellm_guardrail_latency_seconds_count | grep -v '^#' | sort

Before (current litellm_internal_staging); only the pre-call guardrail is instrumented even though all three ran

litellm_guardrail_latency_seconds_count{error_type="none",guardrail_name="phase-pre",hook_type="pre_call",status="success"} 3.0

After (this PR); every phase contributes

litellm_guardrail_latency_seconds_count{error_type="none",guardrail_name="phase-during",hook_type="during_call",status="success"} 3.0
litellm_guardrail_latency_seconds_count{error_type="none",guardrail_name="phase-post",hook_type="post_call",status="success"} 3.0
litellm_guardrail_latency_seconds_count{error_type="none",guardrail_name="phase-pre",hook_type="pre_call",status="success"} 3.0

The _sum series confirms real time is captured per phase, not just a count

litellm_guardrail_latency_seconds_sum{...hook_type="during_call"...} 0.3446330400183797
litellm_guardrail_latency_seconds_sum{...hook_type="post_call"...} 0.1232265830039978
litellm_guardrail_latency_seconds_sum{...hook_type="pre_call"...} 0.06254129199078307

Type

🐛 Bug Fix

Changes

litellm_guardrail_latency_seconds only recorded latency for pre-call guardrails. during_call_hook (running async_moderation_hook) and post_call_success_hook (running async_post_call_success_hook) executed guardrails without emitting any latency, so during-call and post-call guardrail time was invisible in the metric and double-counted as litellm_overhead_latency_metric. That broke the documented workaround of subtracting guardrail latency from overhead to isolate LiteLLM's internal overhead, and it under-reported total guardrail latency.

The metric recorder (_record_guardrail_metrics) already accepted a hook_type label for pre_call, during_call, and post_call; nothing ever called it for the latter two. This pulls the "find the PrometheusLogger and record" step out into _emit_guardrail_metrics and adds _run_guardrail_with_metrics, one wrapper that times a guardrail coroutine, classifies the outcome (success / intervened / error), enriches a raised HTTPException with the guardrail context, and records the latency under the supplied hook_type. The pre-call emit, during_call_hook, and post_call_success_hook all route through it, so each phase is instrumented identically and the duplicated enrichment try/except blocks in the post-call loop collapse into the shared path.

Scope is limited to the non-streaming during-call and post-call dispatch the ticket calls out. The streaming post-call guardrail path (async_post_call_streaming_hook / async_post_call_streaming_iterator_hook) accumulates latency per chunk and is a separate mechanism; it is left for a follow-up rather than widened here.

Tests extend the mapped tests/test_litellm/proxy/utils/proxy_logging/test_guardrail_pipeline.py. _run_guardrail_with_metrics is covered for the success and error paths, and during_call_hook / post_call_success_hook are driven end to end with a stub PrometheusLogger asserting the recorded hook_type. A surgical mutation that reverts during_call_hook to bypass the wrapper makes test_during_call_hook_records_latency_metric fail, confirming the regression bites.

litellm_guardrail_latency_seconds was only emitted for pre-call guardrails.
during_call_hook and post_call_success_hook ran guardrails without recording
any latency, so during-call and post-call guardrail time was invisible in the
metric and leaked into litellm_overhead_latency_metric, making the documented
"subtract guardrail latency from overhead" workaround under-report total
guardrail time.

Extract the find-the-PrometheusLogger-and-record step into _emit_guardrail_metrics
and add _run_guardrail_with_metrics, a single wrapper that times a guardrail
coroutine, classifies its outcome (success / intervened / error), enriches any
raised HTTPException, and records the latency under the given hook_type. Route
the pre-call emit, during_call_hook, and post_call_success_hook through it so
every guardrail phase contributes to the metric the same way.

Resolves LIT-3999
@CLAassistant

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you sign our Contributor License Agreement before we can accept your contribution.
You have signed the CLA already but the status is still pending? Let us recheck it.

@yassin-berriai

Copy link
Copy Markdown
Contributor Author

@greptileai

@greptile-apps

greptile-apps Bot commented Jun 26, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR fixes a gap where litellm_guardrail_latency_seconds only recorded latency for pre-call guardrails — during-call and post-call phases ran their guardrails without emitting any metric, causing that time to surface as unattributed overhead latency.

  • Adds _emit_guardrail_metrics (extracted from the inline PrometheusLogger loop that already existed for pre-call) and _run_guardrail_with_metrics (a timing + enrichment wrapper that replaces the narrower _run_guardrail_task_with_enrichment); during_call_hook and post_call_success_hook are routed through the new wrapper so every hook phase now emits a properly labelled latency data point.
  • Test suite is extended with unit tests for _run_guardrail_with_metrics (success and error paths) and integration-level regression tests for during_call_hook / post_call_success_hook that assert the emitted hook_type label with a stub PrometheusLogger.

Confidence Score: 5/5

Safe to merge — the change is purely additive metric instrumentation; the actual guardrail execution path is unchanged and the exception-enrichment behaviour is preserved identically.

Both new static methods are small and well-bounded. _emit_guardrail_metrics is a direct extraction of the already-working inline loop in the pre-call path, so its behaviour is proven. _run_guardrail_with_metrics adds a time.perf_counter() bookend and a finally emit around the same try/except pattern that the old _run_guardrail_task_with_enrichment used — the only net-new logic is the metric emission. Exception handling covers SensitiveDataRouteException ("intervened") and the general Exception branch consistently with the pre-call path. The renamed method has no other callers in the codebase. Tests cover success, error, and end-to-end hook-level paths with a real isinstance check on a spec'd PrometheusLogger mock.

No files require special attention.

Important Files Changed

Filename Overview
litellm/proxy/utils.py Extracts _emit_guardrail_metrics helper and introduces _run_guardrail_with_metrics wrapper that times a guardrail coroutine and records latency; wires during_call_hook and post_call_success_hook through the new wrapper so all three hook phases now emit litellm_guardrail_latency_seconds. Logic is correct and consistent with the existing pre-call timing path.
tests/test_litellm/proxy/utils/proxy_logging/test_guardrail_pipeline.py Updates renamed method reference, extends existing success/error unit tests to assert metric recording, and adds two end-to-end regression tests for during_call_hook and post_call_success_hook with a stub PrometheusLogger verifying the emitted hook_type label. Tests are mock-only with no network calls.

Reviews (1): Last reviewed commit: "fix(guardrails): instrument during-call ..." | Re-trigger Greptile

@codecov

codecov Bot commented Jun 26, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 82.60870% with 4 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
litellm/proxy/utils.py 82.60% 4 Missing ⚠️

📢 Thoughts on this report? Let us know!

@greptile-apps

greptile-apps Bot commented Jun 26, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR fixes a gap where litellm_guardrail_latency_seconds only captured pre-call guardrail latency; during-call and post-call guardrail time was silently dropped. It refactors the dispatch layer by extracting _emit_guardrail_metrics and introducing _run_guardrail_with_metrics, a single wrapper that times a guardrail coroutine, classifies the outcome (success / intervened / error), enriches raised HTTPExceptions with guardrail context, and emits the metric — then routes all three phases through it.

  • _run_guardrail_task_with_enrichment is replaced by _run_guardrail_with_metrics, which adds time.perf_counter timing, SensitiveDataRouteException-aware status classification, and a finally-block metric emit; the PrometheusLogger import moves from the deferred (inside-method) location to the module top-level, which is safe since prometheus.py only imports litellm.proxy.utils in deferred function-level imports.
  • during_call_hook and post_call_success_hook both route through the new wrapper, so each per-callback invocation now records its own hook_type-labelled latency entry; the duplicated try/except enrichment blocks in the post-call loop are removed as the shared path handles them.
  • New tests drive during_call_hook and post_call_success_hook end-to-end with a MagicMock(spec=PrometheusLogger) stub and assert the recorded hook_type, guardrail_name, and status labels are correct.

Confidence Score: 5/5

Safe to merge — the change is additive (adds metric emission where none existed) and the existing pre-call guardrail flow is unchanged apart from the inline loop being extracted to a shared helper.

The refactor is tightly scoped: three call sites updated to use the new wrapper, no changes to the guardrail execution logic itself, and the wrapper's finally block guarantees metrics are emitted even on exception. The SensitiveDataRouteException branch is handled consistently with the pre-call path. The PrometheusLogger top-level import is safe because prometheus.py only imports litellm.proxy.utils inside functions. New regression tests confirm both phases emit under their correct hook_type label and verify a surgical revert of during_call_hook breaks the test.

No files require special attention.

Important Files Changed

Filename Overview
litellm/proxy/utils.py Extracts _emit_guardrail_metrics helper, renames _run_guardrail_task_with_enrichment to _run_guardrail_with_metrics adding timing + Prometheus emission, and wires during_call_hook and post_call_success_hook through the new wrapper so all three phases emit litellm_guardrail_latency_seconds.
tests/test_litellm/proxy/utils/proxy_logging/test_guardrail_pipeline.py Updates renamed test helpers, adds metric-emission assertions to existing tests, and adds two new end-to-end regression tests that verify during_call_hook and post_call_success_hook each record a hook_type-labelled latency metric via a stub PrometheusLogger.

Reviews (2): Last reviewed commit: "fix(guardrails): instrument during-call ..." | Re-trigger Greptile

@yassin-berriai
yassin-berriai enabled auto-merge (squash) June 26, 2026 11:43
@yassin-berriai
yassin-berriai merged commit f2fa23b into litellm_internal_staging Jun 26, 2026
76 checks passed
@yassin-berriai
yassin-berriai deleted the litellm_guardrail_latency_during_post_hooks branch June 26, 2026 20:07
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants