Skip to content

test(caching): baseline breaker metrics from live state after gc - #46652

Merged
mateo-berri merged 2 commits into
mainfrom
litellm_deflake_20261015
Oct 15, 2026
Merged

mateo-berri merged 2 commits into
mainfrom
litellm_deflake_20261015

Conversation

@devin-ai-integration

@devin-ai-integration devin-ai-integration Bot commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves:

  • test_breaker_metrics_track_state_and_failure_class flakes in the caching-local unit shard
  • It fails assert 0.0 == 2.0 on the open-state gauge, then passes on rerun

How it solves it:

  • Collect cyclic garbage before the test takes its baselines
  • Take the state baselines from redis_breaker_state_counts() instead of the stale gauge
  • Collect garbage the same way in test_prometheus_services_logger_starts_from_the_breakers_already_built, which reads the gauge the same way

User Flow

Before: a contributor whose PR touches no caching code gets a red required unit passed check

  1. They open a PR against main and the unit workflow runs its caching-local job
  2. The job fails test_breaker_metrics_track_state_and_failure_class with assert 0.0 == 2.0 or assert 0.0 == 1.0
  3. unit passed goes red and they rerun the job, sometimes more than once, until it passes

After: the same PR's caching-local job passes on the first run

  1. They open a PR against main and the unit workflow runs its caching-local job
  2. The test passes whatever earlier tests on that worker left behind
  3. unit passed goes green without a rerun

Mechanism

The litellm_redis_circuit_breaker_state gauge is a snapshot of every live RedisCircuitBreaker. It refreshes when a breaker is built, on every recorded failure, on every state change, and when the Prometheus services logger starts. Earlier tests on the same xdist worker can leave breakers behind as cyclic garbage. The test read its open and closed baselines while those breakers were still alive, and when the garbage collector freed them mid-test, the next refresh reported fewer breakers than baseline + delta expected. Which tests share the worker and when the collector runs decides whether it fails, which is why it flips on rerun

Calling gc.collect() before the baselines frees that garbage first, so nothing left by earlier tests can die during the test, and reading the baselines from redis_breaker_state_counts() uses the same live source the gauge refreshes from. test_prometheus_services_logger_starts_from_the_breakers_already_built compares the gauge the logger sets at startup with the live count, so garbage freed between those two reads failed it the same way, and it now collects first too. Production code is unchanged. The gauge bug behind the flake is pre-existing and filed as a follow-up, kept out of this tests-only PR

Pre-Submission checklist

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

  • I have added meaningful tests
  • The handful of test files covering my change pass locally, e.g. uv run pytest tests/unit/<your_test_file>.py -v. Leave the suites (make test-unit-*, make test-unit) to CI: it finishes in ~15 minutes where a laptop takes an hour or more
  • My PR passes all required CI/CD checks (e.g., lint, schema.d.ts sync check, etc.)
  • My PR's scope is as isolated as possible; it only solves 1 specific problem
  • Every automated review on my PR's latest commit has finished, and I have addressed or replied to each of its findings before requesting a maintainer review

Screenshots / Proof of Fix

The flake is a garbage collection that lands mid-test, so the repro forces exactly that. A probe test runs first on the same worker, leaves two open breakers as cyclic garbage, and runs the collector the moment the real test's breaker closes. The base leg runs main's copy of the test file, the after leg the PR's copy, both against the same unchanged product code

Probe test (scratch file, not part of this PR)
import gc
import sys

import litellm
from litellm._service_logger import ServiceLogging
from litellm.caching.redis_cache import RedisCircuitBreaker, redis_breaker_state_counts


def _collect_garbage_when_a_breaker_closes(frame, event, arg):
    if event == "call" and frame.f_code.co_name == "record_success":
        sys.setprofile(None)
        gc.enable()
        gc.collect()


def test_an_earlier_test_leaves_open_breakers_as_cyclic_garbage(monkeypatch):
    monkeypatch.setattr(litellm, "service_callback", ["prometheus_system"])
    service_logger = ServiceLogging()
    gc.disable()
    cycle = [RedisCircuitBreaker(failure_threshold=1, recovery_timeout=60, service_logger=service_logger) for _ in range(2)]
    for breaker in cycle:
        breaker.record_failure(is_timeout=False)
    cycle.append(cycle)
    del breaker, cycle
    print("\nlive open breakers left as garbage:", redis_breaker_state_counts().get("open", 0))
    sys.setprofile(_collect_garbage_when_a_breaker_closes)

Before (35970c3)

  1. git show 35970c3eac:tests/unit/caching/test_redis_cache.py > tests/unit/caching/test_redis_cache_at_base.py
  2. python -m pytest -p no:randomly -n 0 -q -s tests/unit/caching/test_zz_breaker_garbage_probe.py tests/unit/caching/test_redis_cache_at_base.py::test_breaker_metrics_track_state_and_failure_class
live open breakers left as garbage: 2
E       AssertionError: assert 0.0 == 2.0
E        +  where 0.0 = <function test_breaker_metrics_track_state_and_failure_class.<locals>.sample at 0x7eaaba26fba0>('litellm_redis_circuit_breaker_state', {'state': 'open'})
tests/unit/caching/test_redis_cache_at_base.py:1011: AssertionError
1 failed, 1 passed in 0.84s

That is the same assertion, line and label the CI runs below failed on

Run Branch SHA Attempts
38647726077 main ca2f99e attempt 1 and 2 failed, later main SHAs pass
38647747043 litellm_access_group_skills 90bde8a attempts 1 to 3 failed
38675970624 litellm_prompt_cache_pin_ttl_from_cache_control 9f7c1db attempt 1 failed, attempt 2 passed
38698273928 litellm_vertex_credentials_file_error 03e8193 attempt 1 failed, attempt 2 passed
38710667333 litellm_mcp_selector_scope 13f0f09 attempt 1 failed, attempt 2 passed

After (93163f3)

  1. python -m pytest -p no:randomly -n 0 -q -s tests/unit/caching/test_zz_breaker_garbage_probe.py tests/unit/caching/test_redis_cache.py::test_breaker_metrics_track_state_and_failure_class
live open breakers left as garbage: 2
2 passed in 1.85s

Sibling test, before (35970c3) and after (93163f3)

A second probe leaves two closed breakers as garbage and runs the collector right after the logger sets the gauge at startup

Sibling probe test (scratch file, not part of this PR)
import gc
import sys

import litellm
from litellm._service_logger import ServiceLogging
from litellm.caching.redis_cache import RedisCircuitBreaker


def _collect_garbage_once_the_gauge_is_set(frame, event, arg):
    if event == "call" and frame.f_code.co_name == "_get_service_metrics_initialize":
        sys.setprofile(None)
        gc.enable()
        gc.collect()


def test_an_earlier_test_leaves_closed_breakers_as_cyclic_garbage(monkeypatch):
    monkeypatch.setattr(litellm, "service_callback", [])
    gc.disable()
    cycle = [RedisCircuitBreaker(failure_threshold=3, recovery_timeout=60, service_logger=ServiceLogging()) for _ in range(2)]
    cycle.append(cycle)
    del cycle
    sys.setprofile(_collect_garbage_once_the_gauge_is_set)

Before, against main's copy of the test file

$ python -m pytest -p no:randomly -q tests/unit/caching/test_zz_sibling_probe.py tests/unit/caching/test_redis_cache_at_base.py::test_prometheus_services_logger_starts_from_the_breakers_already_built
>       assert REGISTRY.get_sample_value("litellm_redis_circuit_breaker_state", {"state": "closed"}) == (
E       AssertionError: assert 3.0 == 1
1 failed, 1 passed in 2.30s

After, against this PR's copy

$ python -m pytest -p no:randomly -q tests/unit/caching/test_zz_sibling_probe.py tests/unit/caching/test_redis_cache.py::test_prometheus_services_logger_starts_from_the_breakers_already_built
2 passed in 1.78s

Type

✅ Test

Caveats (if any)

Low

Final Attestation

  • The tests check the right things, including the edge cases, and regressions in the respective real-world customer use-cases are not possible after this PR

Link to Devin session: https://app.devin.ai/sessions/15f41c28ccbf40a095eeb626850220cd
Open in Devin Desktop: https://app.devin.ai/desktop/session/15f41c28ccbf40a095eeb626850220cd?variant=devin

  • 93163f3 passes /audit (skipped: tests-only change)
  • 93163f3 passes /live-pr-risk

Note

Low Risk
Tests-only change; no production code paths are modified.

Overview
Stabilizes flaky Redis circuit breaker Prometheus metric tests in test_redis_cache.py by accounting for leftover RedisCircuitBreaker instances on shared xdist workers.

test_breaker_metrics_track_state_and_failure_class now runs gc.collect() before recording baselines, and derives open/closed state baselines from redis_breaker_state_counts() (live weakref registry) instead of the litellm_redis_circuit_breaker_state gauge snapshot, so mid-test GC cannot drop phantom breakers and break baseline + delta assertions.

test_prometheus_services_logger_starts_from_the_breakers_already_built also calls gc.collect() before initializing the Prometheus services logger so gauge vs live-count comparison is not racy. Production behavior is unchanged.

Reviewed by Cursor Bugbot for commit 93163f3. Bugbot is set up for automated code reviews on this repo. Configure here.

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@devin-ai-integration

devin-ai-integration Bot commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor Author

I'll fix CI failures and address comments from users with write access. I'll skip comments containing "(aside)".

  • Disable automatic comment, CI, and merge conflict monitoring

@greptile-apps

greptile-apps Bot commented Oct 15, 2026

Copy link
Copy Markdown
Contributor

Automatic reviews are disabled for this repository.

@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.

@codecov

codecov Bot commented Oct 15, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@mateo-berri

Copy link
Copy Markdown
Contributor

@litereview code-review

@litereview

litereview Bot commented Oct 15, 2026 •

Copy link
Copy Markdown

✅ code-review

5/5 · Ready for human review

Scope: full · Full PR review.

No correctness findings. The change only touches tests. gc.collect() now runs before the baselines are read, and the baselines come from redis_breaker_state_counts(), which reads the same _LIVE_BREAKERS WeakSet the gauge refreshes from. Breakers left behind by earlier tests can therefore no longer disappear between the baseline read and the assertions.

Checks and execution details
  • Passed · Real testing evidence (required): Not applicable: no LLM translation changes in the scoped paths. The diff touches only tests/unit/caching/test_redis_cache.py, with nothing under litellm/llms/** or litellm/litellm_core_utils/prompt_templates/**.
  • Passed · Targeted tests on PR head (optional): python -m pytest -p no:randomly -q tests/unit/caching/test_redis_cache.py -k "breaker_metrics_track or starts_from_the_breakers" gave 2 passed, 95 deselected. I stopped a full-file run after several minutes with no output, so I have no full-file result.
  • Passed · Baseline source consistency (optional): Read through the code: redis_breaker_state_counts() (litellm/caching/redis_cache.py:469) counts states over _LIVE_BREAKERS, the same WeakSet the gauge refresh uses. That makes the new baselines consistent with the next gauge refresh.

View review · Reviewed 93163f3abfc8

@mateo-berri

Copy link
Copy Markdown
Contributor

@litereview code-review

@mateo-berri

Copy link
Copy Markdown
Contributor

bugbot run

@cursor cursor Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ Bugbot reviewed your changes and found no new issues!

Comment @cursor review or bugbot run to trigger another review on this PR

Reviewed by Cursor Bugbot for commit 93163f3. Configure here.

@mateo-berri

Copy link
Copy Markdown
Contributor

@litellm-stampbot

@litellm-stampbot

Copy link
Copy Markdown

litellm-stampbot: risk low

Approved at 93163f3.

Rules (stampbot/risk_rules.yml):

  • low: no rule flagged it

Judge (gpt-6-luna): low, probability of high 0.00 (high at or above 0.90)

  • risk: low (probability of high 0.00)

Pushes do not re-run this check. Comment @litellm-stampbot again to re-check the new head.

@litellm-stampbot litellm-stampbot Bot added the risk:low Small, isolated, low-risk change label Oct 15, 2026

@kerry-berri kerry-berri left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Low risk by rule and by judgement at 93163f3

@mateo-berri
mateo-berri merged commit 452ee4d into main Oct 15, 2026
92 checks passed
@mateo-berri
mateo-berri deleted the litellm_deflake_20261015 branch October 15, 2026 12:53
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

risk:low Small, isolated, low-risk change

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants