Skip to content

fix(guardrails): stop re-initializing DB guardrails on every poll - #30542

Merged
yassin-berriai merged 3 commits into
litellm_internal_stagingfrom
litellm_fix_guardrail_dup_init
Jun 16, 2026
Merged

yassin-berriai merged 3 commits into
litellm_internal_stagingfrom
litellm_fix_guardrail_dup_init

Conversation

@yassin-berriai

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

Copy link
Copy Markdown
Contributor

Relevant issues

Fixes the guardrail re-initialization memory leak reported during performance testing.

Linear ticket

LIT-3606

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 unit tests on make test-unit
  • 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

Delays in PR merge?

If you're seeing a delay in your PR being merged, ping the LiteLLM Team on Slack (#pr-review).

CI (LiteLLM team)

  • Branch creation CI run
    Link:

  • CI run for the last commit
    Link:

  • Merge / cherry-pick CI run
    Links:

Screenshots / Proof of Fix

Reproduced against a live proxy backed by a Dockerized Postgres, hitting the real OpenAI API (gpt-4o-mini). The DB row is seeded with a sparse litellm_params (only the keys a user actually set), which is what an older proxy version writes; this is the shape that triggers the comparison mismatch.

Setup:

docker run -d --name lit3606-pg -e POSTGRES_PASSWORD=postgres -e POSTGRES_DB=litellm -p 5434:5432 postgres:16

docker exec lit3606-pg psql -U postgres -d litellm -c \
  "INSERT INTO \"LiteLLM_GuardrailsTable\" (guardrail_id, guardrail_name, litellm_params, guardrail_info, status, created_at, updated_at) \
   VALUES (gen_random_uuid()::text, 'my-content-filter', \
   '{\"guardrail\":\"litellm_content_filter\",\"mode\":\"pre_call\",\"default_on\":true,\"blocked_words\":[{\"keyword\":\"secret\",\"action\":\"BLOCK\"}]}'::jsonb, \
   '{}'::jsonb, 'active', now(), now());"

python litellm/proxy/proxy_cli.py --config config.yaml --detailed_debug

for n in 1 2; do
  curl -s -X POST http://localhost:4000/v1/chat/completions \
    -H "Authorization: Bearer sk-1234" -H "Content-Type: application/json" \
    -d '{"model":"gpt-4o-mini","messages":[{"role":"user","content":"say hello in 3 words"}]}' \
    -o /dev/null -w "request $n -> HTTP %{http_code}\n"
done
# request 1 -> HTTP 200
# request 2 -> HTTP 200

Then the proxy is left running across DB poll cycles (30s interval) and the re-initialization log lines are counted.

Before the fix, the DB-stored guardrail re-initializes on every single poll:

DB poll cycles that saw the guardrail : 4
re-initialization log lines           : 4
16:24:06 - guardrail_registry.py:752 - Guardrail 'my-content-filter' params changed, re-initializing...
16:24:36 - guardrail_registry.py:752 - Guardrail 'my-content-filter' params changed, re-initializing...
16:25:06 - guardrail_registry.py:752 - Guardrail 'my-content-filter' params changed, re-initializing...
16:25:36 - guardrail_registry.py:752 - Guardrail 'my-content-filter' params changed, re-initializing...

After the fix, it is initialized once when first loaded and never re-initialized again, even as polling continues:

DB poll cycles that saw the guardrail : 5
re-initialization log lines           : 1
16:26:12 - guardrail_registry.py:781 - Guardrail 'my-content-filter' params changed, re-initializing...

The single line after the fix is the initial load (the guardrail is not yet in memory); every subsequent poll sees the config as unchanged and leaves the existing instance in place.

Type

🐛 Bug Fix

Changes

DB-stored guardrails were re-initializing on every DB poll cycle. InMemoryGuardrailHandler._has_guardrail_params_changed compared the in-memory LitellmParams against the raw dict loaded from the database. The in-memory side is a LitellmParams whose model_dump() carries every field default and coerces enums, while the DB side is the raw stored dict that only holds the keys originally written (so a row written by an earlier proxy version is missing fields the current model fills in, and a value like version reads as 2 on one side and absent on the other). The two shapes never compared equal, so the handler treated the guardrail as changed on every poll and rebuilt it indefinitely.

Each rebuild created a fresh guardrail instance, but delete_in_memory_guardrail only removed the old callback from litellm.callbacks. Request handling promotes guardrail callbacks into the success, failure, and async callback lists, so the previous instance stayed referenced in those lists after every rebuild and instances accumulated until the pod was OOM-killed.

The comparison now normalizes both sides through LitellmParams(...).model_dump() before diffing, so an unchanged config compares equal and the guardrail is rebuilt only on a genuine change. If a stored row fails LitellmParams validation the normalizer catches that specific ValidationError, logs a warning so the offending row is diagnosable, and treats the guardrail as changed rather than swallowing every error or crashing the poll cycle. delete_in_memory_guardrail now purges the callback from every callback list, so a rebuild leaves nothing stranded.

Tests in tests/test_litellm/proxy/guardrails/test_guardrail_registry.py cover the comparison (unchanged DB params no longer register as changed, a genuine change still does), the delete path (the callback is removed from every list), and an end-to-end check that repeated DB syncs keep exactly one live guardrail instance across all callback lists.

InMemoryGuardrailHandler._has_guardrail_params_changed compared the
in-memory LitellmParams against the raw dict loaded from the DB. The
in-memory side carries every field default and coerces enums via
model_dump(), while the DB side only holds the keys originally stored,
so the two shapes never compared equal and the guardrail was rebuilt on
every poll cycle.

Each rebuild created a fresh instance, but delete_in_memory_guardrail
only removed the old callback from litellm.callbacks. Request handling
promotes guardrail callbacks into the success/failure/async lists, so
the previous instance stayed referenced there and instances accumulated.

Normalize both sides through LitellmParams(...).model_dump() before
diffing, and purge the callback from every callback list on delete.
@CLAassistant

ghost commented Jun 16, 2026

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.

@codecov

ghost commented Jun 16, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 90.90909% with 2 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
litellm/proxy/guardrails/guardrail_registry.py 89.47% 2 Missing ⚠️

📢 Thoughts on this report? Let us know!

@greptile-apps

ghost commented Jun 16, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR fixes a memory leak where DB-backed guardrails were re-initialized on every poll cycle, accumulating stale callback instances in the success/failure/async lists until the pod was OOM-killed. Two independent bugs are addressed together.

  • Comparison mismatch fixed: _has_guardrail_params_changed now normalizes both the in-memory LitellmParams and the raw DB dict through LitellmParams(**params).model_dump() before diffing, so sparse DB rows (missing defaults) and fully-populated in-memory objects compare equal when the config is unchanged. Invalid DB rows fall back to "treat as changed" with a warning log.
  • Stale callbacks fixed: delete_in_memory_guardrail now calls remove_callback_from_all_lists instead of only removing from litellm.callbacks, ensuring re-initialization leaves nothing stranded in the success/failure/async lists that request handling promotes callbacks into. Five new unit tests cover each fix path, including an end-to-end accumulation regression test.

Confidence Score: 5/5

Safe to merge — the changes are narrowly scoped to the DB poll comparison and callback cleanup path, both of which are exercised by new unit tests that reproduce the original OOM scenario.

The normalization logic is correct: LitellmParams inherits extra="allow" from BaseLitellmParams, so both sides of the comparison go through the same Pydantic round-trip and produce identical model_dump() output for unchanged configs. The delete path change is additive — it removes from more lists than before, not fewer. The ValidationError fallback explicitly logs and treats malformed rows as changed, which is intentional and no longer causes accumulation because the delete is now thorough. Tests directly cover every new branch, including the end-to-end accumulation scenario.

No files require special attention.

Important Files Changed

Filename Overview
litellm/proxy/guardrails/guardrail_registry.py Adds _normalize_litellm_params_for_comparison to canonicalize both the in-memory LitellmParams and the raw DB dict through model_dump() before diffing; updates delete_in_memory_guardrail to purge callbacks from all five lists. Logic is correct and well-documented.
litellm/litellm_core_utils/logging_callback_manager.py Adds remove_callback_from_all_lists that iterates over all five callback lists and delegates to the existing remove_callback_from_list_by_object. Straightforward and consistent with existing patterns.
tests/test_litellm/proxy/guardrails/test_guardrail_registry.py Adds five new unit tests covering: unchanged DB params not triggering re-init, genuine changes still detected, malformed DB rows handled gracefully, delete purging from all lists, and an end-to-end accumulation regression test. All tests use mocks only — no real network calls.
tests/litellm_utils_tests/test_logging_callback_manager.py Adds test_remove_callback_from_all_lists verifying the new method removes from every callback list. Correct use of test setup/teardown pattern.

Reviews (4): Last reviewed commit: "refactor(callbacks): add remove_callback..." | Re-trigger Greptile

@yassin-berriai

ghost commented Jun 16, 2026

Copy link
Copy Markdown
Contributor Author

@greptileai

…ionError

The comparison normalizer caught a bare Exception and silently fell back
to the raw dict, which hid the cause and quietly degraded the affected
guardrail back to re-initializing on every poll. Catch only the
ValidationError that LitellmParams construction can raise, log a warning
so the offending row is diagnosable, and let any other error surface
instead of being swallowed.
@yassin-berriai

ghost commented Jun 16, 2026

Copy link
Copy Markdown
Contributor Author

@greptileai

…ager

Move the knowledge of which callback lists a callback can be promoted
into out of the guardrail registry and into LoggingCallbackManager, where
the rest of the callback-list bookkeeping already lives. delete_in_memory_guardrail
now delegates to the new helper instead of iterating the lists itself.
@yassin-berriai

ghost commented Jun 16, 2026

Copy link
Copy Markdown
Contributor Author

@greptileai

Comment on lines +402 to +407
for callback_list in (
litellm.callbacks,
litellm.success_callback,
litellm.failure_callback,
litellm._async_success_callback,
litellm._async_failure_callback,

ghost Jun 16, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

_get_all_callbacks returns a flattened concatenation (litellm.callbacks + litellm.success_callback + ...), which is a fresh list object, so removing from its result would mutate that temporary list and leave the underlying lists untouched.

@yassin-berriai
yassin-berriai enabled auto-merge (squash) June 16, 2026 18:16
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.

2 participants