Repository navigation
fix(guardrails): stop re-initializing DB guardrails on every poll - #30542
Conversation
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.
commented
Jun 16, 2026
|
|
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
Greptile SummaryThis 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.
Confidence Score: 5/5Safe 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.
|
| 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
commented
Jun 16, 2026
…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.
commented
Jun 16, 2026
…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.
commented
Jun 16, 2026
| for callback_list in ( | ||
| litellm.callbacks, | ||
| litellm.success_callback, | ||
| litellm.failure_callback, | ||
| litellm._async_success_callback, | ||
| litellm._async_failure_callback, |
There was a problem hiding this comment.
_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.
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
make test-unit@greptileaiand received a Confidence Score of at least 4/5 before requesting a maintainer reviewDelays 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 sparselitellm_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:
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:
After the fix, it is initialized once when first loaded and never re-initialized again, even as polling continues:
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_changedcompared the in-memoryLitellmParamsagainst the raw dict loaded from the database. The in-memory side is aLitellmParamswhosemodel_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 likeversionreads as2on 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_guardrailonly removed the old callback fromlitellm.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 failsLitellmParamsvalidation the normalizer catches that specificValidationError, 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_guardrailnow purges the callback from every callback list, so a rebuild leaves nothing stranded.Tests in
tests/test_litellm/proxy/guardrails/test_guardrail_registry.pycover 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.