Skip to content

fix(health): skip background health check DB writes when the latest-row read fails - #40993

Merged
yassin-berriai merged 1 commit into
litellm_internal_stagingfrom
litellm_health_check_skip_save_on_failed_read
Sep 14, 2026
Merged

yassin-berriai merged 1 commit into
litellm_internal_stagingfrom
litellm_health_check_skip_save_on_failed_read

Conversation

@devin-ai-integration

@devin-ai-integration devin-ai-integration Bot commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves:

  • Background health checks kept appending rows to the health check table
  • The "only write on status change" gate reads the latest row per model first
  • When that read failed, it was treated as "no rows", so every model was written, every cycle, on every pod
  • The table grew without bound while the database was struggling, which made it struggle more

How it solves it:

  • The background save now uses a read that raises instead of returning an empty result
  • A failed read skips that cycle's writes and logs a warning; the next cycle retries
  • The read paths that only decorate other responses (model hub, /health/latest) keep degrading to no rows

User Flow

Before: an admin with background health checks on sees the health check table fill up with duplicate rows

  1. The admin runs the proxy with background_health_checks: true and health_check_interval: 15
  2. Their database is under load and the "latest health check per model" read starts failing
  3. Every 15 seconds the proxy logs Error getting all latest health checks and then writes one new row per model, even though nothing changed
  4. GET http://localhost:4000/health/latest still says every model is healthy, while the table behind it keeps growing on every pod

After: the same failing read costs nothing but a warning

  1. The admin runs the proxy with the same config
  2. The same read fails under load
  3. Every 15 seconds the proxy logs Failed to save background health checks to database: ... and writes nothing
  4. GET http://localhost:4000/health/latest still says every model is healthy, and once the read works again the proxy goes back to writing a row only when a status changes or the hourly refresh is due

Relevant issues

Affected release

Linear ticket

Resolves LIT-2457

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/test_litellm/<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
  • I have received a Greptile Confidence Score of at least 4/5 before requesting a maintainer review (Greptile reviews automatically once the PR is opened; only comment @greptileai to re-request a review after pushing changes)

Delays in PR merge?

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

Screenshots / Proof of Fix

Shared setup. Local Postgres, schema pushed, two real OpenAI deployments, background health checks every 15 seconds. To make the latest-row read fail the way it does on an overloaded database, the proxy connects as a non-superuser role and a row level security policy raises whenever that specific DISTINCT ON read runs. Plain inserts and plain selects from that role keep working, and the policy is evaluated per row, so the very first cycle against an empty table reads fine and writes one row per model on both sides. That first cycle is the control: the write path works. Every cycle after it hits the failing read.

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

general_settings:
  master_key: sk-1234
  background_health_checks: true
  health_check_interval: 15
  disable_prisma_schema_update: true
CREATE ROLE hc_probe LOGIN PASSWORD 'hc_probe';
GRANT ALL ON SCHEMA public TO hc_probe;
GRANT ALL ON ALL TABLES IN SCHEMA public TO hc_probe;
GRANT ALL ON ALL SEQUENCES IN SCHEMA public TO hc_probe;
CREATE OR REPLACE FUNCTION hc_probe_guard() RETURNS boolean LANGUAGE plpgsql STABLE AS $$
BEGIN
  IF current_query() LIKE '%DISTINCT ON%' THEN
    RAISE EXCEPTION 'simulated failure of the latest-health-check read';
  END IF;
  RETURN true;
END;
$$;
ALTER TABLE "LiteLLM_HealthCheckTable" ENABLE ROW LEVEL SECURITY;
CREATE POLICY hc_probe_guard ON "LiteLLM_HealthCheckTable" FOR ALL TO hc_probe USING (hc_probe_guard()) WITH CHECK (true);
psql "$DATABASE_URL" -c 'DELETE FROM "LiteLLM_HealthCheckTable";'
DATABASE_URL="postgresql://hc_probe:hc_probe@localhost:5432/litellm" PYTHONPATH=$HOME/repos/litellm \
  uv run --no-sync litellm --config config.yaml --detailed_debug --port 4000 > proxy.log 2>&1 &
sleep 95

Before (c2c2a62)

  1. Count rows per model after about 95 seconds (roughly 7 cycles)
$ psql "$DATABASE_URL" -c 'SELECT model_name, status, count(*) AS rows_written, min(checked_at)::time(0) AS first, max(checked_at)::time(0) AS last FROM "LiteLLM_HealthCheckTable" GROUP BY 1,2 ORDER BY 1;'
 model_name  | status  | rows_written |  first   |   last
-------------+---------+--------------+----------+----------
 gpt-4o-mini | healthy |            7 | 09:02:09 | 09:03:46
 gpt-5.5     | healthy |            7 | 09:02:09 | 09:03:46
  1. The log shows the failing read followed by a write for every model, every cycle, with the status never changing
$ grep -E "Error getting all latest health checks|Saving health check data" proxy.log | cut -c1-140
09:02:41 - LiteLLM Proxy:ERROR: health_check_latest.py:82 - Error getting all latest health checks: ERROR: simulated failure of the latest-health-check read
09:02:41 - LiteLLM Proxy:DEBUG: utils.py:6456 - Saving health check data: {'model_name': 'gpt-5.5', 'status': 'healthy', 'healthy_count': 1, ...
09:02:41 - LiteLLM Proxy:DEBUG: utils.py:6456 - Saving health check data: {'model_name': 'gpt-4o-mini', 'status': 'healthy', 'healthy_count': 1, ...
09:02:57 - LiteLLM Proxy:ERROR: health_check_latest.py:82 - Error getting all latest health checks: ERROR: simulated failure of the latest-health-check read
09:02:57 - LiteLLM Proxy:DEBUG: utils.py:6456 - Saving health check data: {'model_name': 'gpt-5.5', 'status': 'healthy', 'healthy_count': 1, ...
09:02:57 - LiteLLM Proxy:DEBUG: utils.py:6456 - Saving health check data: {'model_name': 'gpt-4o-mini', 'status': 'healthy', 'healthy_count': 1, ...
(repeats every 15 seconds; 6 failed reads, 6 extra rows per model)

After (6d2c489; captured on 75825c6, whose production code is byte for byte the same, the follow-up only repointed one legacy test mock)

  1. Same setup, same wait. Only the first cycle (clean read of the empty table) wrote anything
$ psql "$DATABASE_URL" -c 'SELECT model_name, status, count(*) AS rows_written FROM "LiteLLM_HealthCheckTable" GROUP BY 1,2 ORDER BY 1;'
 model_name  | status  | rows_written
-------------+---------+--------------
 gpt-4o-mini | healthy |            1
 gpt-5.5     | healthy |            1
  1. The log shows the failing read now skips the cycle instead of writing
$ grep -E "Failed to save background health checks|Saving health check data" proxy.log | cut -c1-140
09:06:25 - LiteLLM Proxy:DEBUG: utils.py:6456 - Saving health check data: {'model_name': 'gpt-5.5', 'status': 'healthy', 'healthy_count': 1, ...
09:06:25 - LiteLLM Proxy:DEBUG: utils.py:6456 - Saving health check data: {'model_name': 'gpt-4o-mini', 'status': 'healthy', 'healthy_count': 1, ...
09:06:41 - LiteLLM Proxy:WARNING: _health_endpoints.py:899 - Failed to save background health checks to database: ERROR: simulated failure of the latest-health-check read
09:06:57 - LiteLLM Proxy:WARNING: _health_endpoints.py:899 - Failed to save background health checks to database: ERROR: simulated failure of the latest-health-check read
09:07:13 - LiteLLM Proxy:WARNING: _health_endpoints.py:899 - Failed to save background health checks to database: ERROR: simulated failure of the latest-health-check read
09:07:29 - LiteLLM Proxy:WARNING: _health_endpoints.py:899 - Failed to save background health checks to database: ERROR: simulated failure of the latest-health-check read
09:07:45 - LiteLLM Proxy:WARNING: _health_endpoints.py:899 - Failed to save background health checks to database: ERROR: simulated failure of the latest-health-check read
  1. Control: restart the same fixed build as the normal postgres user (read works, table already holds one row per model) and wait another 95 seconds. Nothing new is written because nothing changed, and /health/latest still serves the rows
$ curl -s -H "Authorization: Bearer sk-1234" http://localhost:4000/health/latest | python3 -c "import json,sys; d=json.load(sys.stdin)['latest_health_checks']; print({v['model_name']: v['status'] for v in d.values()})"
{'gpt-4o-mini': 'healthy', 'gpt-5.5': 'healthy'}

$ psql "$DATABASE_URL" -c 'SELECT count(*) AS total_rows FROM "LiteLLM_HealthCheckTable";'
 total_rows
------------
          2

$ grep -cE "Failed to save background|Error getting all latest|Saving health check data" proxy.log
0

Type

🐛 Bug Fix

Caveats (if any)

Medium

  • The ticket title reads as "never persist background health checks". Doing that literally would empty the model hub health badges and /health/latest, so this PR fixes the write storm behind the customer report instead. If the team wants persistence off entirely, that is a product call and a follow-up
  • A failing read now means no writes for that cycle. If the read fails for a long stretch, the table stops reflecting new status changes until it recovers. Before, those changes were buried in duplicate rows anyway
  • The manual POST /health save path writes one row per call and is unchanged; only the background loop is affected
  • The Verify schema.d.ts matches the proxy OpenAPI spec check is red on the base. litellm_internal_staging carries b9ba808, which dropped the soft_budget docstring from the user endpoints without regenerating ui/litellm-dashboard/src/lib/http/schema.d.ts, so any PR touching litellm/proxy/ regenerates the file and sees that two-line drift. This PR does not touch those endpoints and leaves the generated file alone rather than folding an unrelated regeneration into a health check fix
  • The proxy-behavior check fails on tests/proxy_behavior/auth/test_auth_object_prefetch.py::test_join_binds_the_membership_to_the_requested_team (object MagicMock can't be used in 'await' expression). The same test fails the same way on unrelated open PRs against the same base (runs 34750112885, 34749974493, 34749801203), it passed on this PR's first run with identical production code, and the whole tests/proxy_behavior suite passes locally on this branch (848 passed). This PR does not touch auth or the prefetch path

Low

  • Taxonomy audit. D4/Z2 (fail closed on a lookup failure): checked that the exception path is not the ordinary path, an empty table returns no rows without raising, verified live in the first cycle of both runs. F3/O4 (sibling surfaces): the model hub and /health/latest reads keep the swallowing fetch_latest_health_checks; the manual /health save is a separate path and out of scope as stated above. C (silent behavior change): the only change is that a failing read skips the cycle and logs a warning. T1 (fails on unfixed code): the new save-path test reads (True, 1) with the old read and (False, 0) with the fix. H: no new source comments, no Optional, no bare dict or Any, lines within 120

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/7b18ae4f7a1e4187b400e7fe04b32742
Open in Devin Desktop: https://app.devin.ai/desktop/session/7b18ae4f7a1e4187b400e7fe04b32742?variant=devin
Requested by: @yassin-berriai

@devin-ai-integration

Copy link
Copy Markdown
Contributor Author

🤖 Devin AI Engineer

I'll be helping with this pull request! Here's what you should know:

✅ I will automatically:

  • Address comments on this PR. Add '(aside)' to your comment to have me ignore it.
  • Look at CI failures and help fix them

Note: I can only respond to comments from users who have write access to this repository.

⚙️ Control Options:

  • Disable automatic comment, CI, and merge conflict monitoring

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

@devin-ai-integration

Copy link
Copy Markdown
Contributor Author

@greptileai

@greptile-apps

greptile-apps Bot commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR separates the latest-health-check database read into strict and fault-tolerant paths

  • Background persistence now skips all writes when the deduplication read fails
  • Response-decoration callers continue degrading failed reads to an empty result
  • Regression tests cover propagation from the strict query and verify that failed reads produce no writes
  • The follow-up fixes the legacy exception test to mock the database call actually used by the save path

Confidence Score: 5/5

The PR appears safe to merge because a failed latest-row read now prevents duplicate background writes while non-persistence reads retain their existing fallback

No actionable new issues remain. The previously reported stale mock was corrected to intercept the exact awaited database call, and its thread is resolved

Important Files Changed

Filename Overview
litellm/proxy/db/health_check_latest.py Adds a strict typed query function while preserving fault-tolerant behavior for decorative read callers
litellm/proxy/health_endpoints/_health_endpoints.py Uses the strict query in background persistence so read failures abort the write cycle
tests/test_litellm/proxy/db/test_health_check_latest.py Verifies strict query failures propagate while the existing fetch wrapper still degrades gracefully
tests/test_litellm/proxy/test_health_check_functions.py Covers write suppression after read failure and correctly targets the live db.query_raw call in legacy tests

Reviews (2): Last reviewed commit: "fix(health): skip background health chec..." | Re-trigger Greptile

@codspeed

codspeed Bot commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

✅ 31 untouched benchmarks


Comparing litellm_health_check_skip_save_on_failed_read (6d2c489) with litellm_internal_staging (c2c2a62)

Open in CodSpeed

@codecov

codecov Bot commented Sep 13, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

…ow read fails

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@devin-ai-integration
devin-ai-integration Bot force-pushed the litellm_health_check_skip_save_on_failed_read branch from 75825c6 to 6d2c489 Compare September 13, 2026 09:44
@devin-ai-integration

Copy link
Copy Markdown
Contributor Author

@greptileai please re-review 6d2c489: the legacy exception test now mocks db.query_raw, the read the save path actually makes

@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 6d2c489. Configure here.

@yassin-berriai
yassin-berriai merged commit af6dc1d into litellm_internal_staging Sep 14, 2026
89 of 92 checks passed
@yassin-berriai
yassin-berriai deleted the litellm_health_check_skip_save_on_failed_read branch September 14, 2026 22:58
mateo-berri added a commit to mayank-affirm/litellm that referenced this pull request Sep 29, 2026
Rebuilds the branch on current main so the PR diff is only the Mantle overflow
mapping and its test. Drops the stale litellm_internal_staging drift (BerriAI#37762,
BerriAI#40993, BerriAI#34939) the branch had picked up.
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