Repository navigation
fix(proxy): requeue spend logs when a Postgres restart tears down the prisma engine mid-write - #47571
Conversation
… prisma engine mid-write
|
I'll fix CI failures and address comments from users with write access. I'll skip comments containing "(aside)".
|
|
|
Merging this PR will not alter performance
|
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
|
@litellm-stampbot |
litellm-stampbot: risk highNot approved at Rules (
Cursor Bugbot: Medium Risk at Pushes do not re-run this check. Comment |
|
bugbot run |
There was a problem hiding this comment.
✅ 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 f91a18a. Configure here.
… prisma engine mid-write (BerriAI#47571) Backport of BerriAI#47571 to stable/1.103.x Cherry-picked from ccd0d4e (main)
… prisma engine mid-write (BerriAI#47571) Co-authored-by: devin-ai-integration[bot] <158243242+devin-ai-integration[bot]@users.noreply.github.com> Backport of BerriAI#47571 to stable/1.106.x Cherry-picked from ccd0d4e (main)
… prisma engine mid-write (BerriAI#47571) Co-authored-by: devin-ai-integration[bot] <158243242+devin-ai-integration[bot]@users.noreply.github.com> Backport of BerriAI#47571 to stable/1.105.x. Cherry-picked from ccd0d4e (main).
TLDR
Problem this solves:
LiteLLM_SpendLogsrow, so spend is under-reportedHow it solves it:
_is_transient_spend_log_write_errornow also treatsPrismaDBExceptionHandler.is_prisma_engine_internal_erroras transientrequeue_spend_logspath instead of being raised awayIn the instant Postgres tears its connections down, prisma's query engine answers the write with a P1001 payload whose
metaisnull. prisma-client-py'shandle_response_errorstrips on that (AttributeError: 'NoneType' object has no attribute 'get') before it can raise a typedDataError, so the error is neither a transport error nor aPrismaErrorandupdate_spend_logsraised it without putting the dequeued rows back. The auth path already classified this exact error withis_prisma_engine_internal_error, the writer just did not use it. One second later the same outage produces the typedDataErrorP1001, which the writer already retried and requeued, which is why a long outage lost nothing and only the restart instant didUser Flow
Before: a proxy admin restarts Postgres while traffic is flowing and some of those requests never show up in spend
"model": "gpt-4o-mini"and every request returns 200 with achatcmpl-...idsudo service postgresql restart(about one second of downtime) while the requests keep flowingSELECT count(*) FROM "LiteLLM_SpendLogs" WHERE request_id IN (...)for the 60 ids returns 53, and the 7 missing requests never appear at http://localhost:4000/ui/?page=logsAfter: the same restart loses nothing
"model": "gpt-4o-mini"and every request returns 200 with achatcmpl-...idsudo service postgresql restartwhile the requests keep flowingSELECT count(*) FROM "LiteLLM_SpendLogs" WHERE request_id IN (...)for the 60 ids returns 60 within half a minute, and every request is on the logs pageRelevant issues
Closes the gap left by #47364, which removed the
pytest.skip("BUG: ...")ontests/integration/observability/test_guardrail_stream_scope_chaos.py::test_h6_spend_rows_for_requests_served_during_postgres_restart_land_oncewhile the writer bug behind the skip was still there. That test passes onmainonly by timing (two runs here, 65 s and 81 s, both green), and the owned proxy's log from those runs still shows the dropped flush:On this branch the same h6 run (green, 80 s) shows the restart-instant flush retried instead of dropped:
Related: LIT-9050 is the original ticket behind that skipped test. This PR does not claim to resolve it
Pre-Submission checklist
Please complete all items before asking a LiteLLM maintainer to review your PR
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 moreScreenshots / Proof of Fix
Real proxy, local Postgres, real OpenAI
gpt-4o-minicalls. Shared setup:Before (5145250)
Ran the commands above against
maingrep -n "Spend tracking - processing\|Error in spend logs queue monitor\|Flushed" proxy.logshows the flush that ran three seconds after restart 1 and took its batch with it, with no retry and no requeue lineThe traceback under that ERROR line ends in prisma, not in litellm code:
After (f91a18a)
Same commands against this branch
The same grep shows the same error hitting the same-sized batch, now retried and written once Postgres is back
Regression test, red on
mainand green here.tests/unit/proxy/utils/prisma_and_spend/test_proxy_update_spend.py::test_update_spend_logs_retries_and_requeues_batch_when_postgres_restart_tears_down_prisma_enginemakescreate_manyraise through prisma's ownhandle_response_errorswith themeta: Nonepayload. Onmain:Mutation check: reverting the one-line classifier change turns that test red again with the same output, and the other 31 tests in the file stay green on both sides
Type
🐛 Bug Fix
Caveats (if any)
Low
is_prisma_engine_internal_errormatches byprisma.enginetraceback origin, so any non-PrismaErrorraised inside prisma's engine layer during a spend-log write is now retried like a transport error, not only thismeta: nullpayloadSPEND_LOG_QUEUE_MAX_BYTESviaenqueue_spend_logs, so nothing new is held in memory during a long outageFinal Attestation
Link to Devin session: https://app.devin.ai/sessions/79bea2ba35454729962124b73bc97f3f
Open in Devin Desktop: https://app.devin.ai/desktop/session/79bea2ba35454729962124b73bc97f3f?variant=devin
Requested by: @kerrylu-berri
Note
Medium Risk
Changes error classification for spend-log DB writes so more engine-layer exceptions retry and requeue; scope is narrow but affects billing/observability data durability during outages.
Overview
Fixes spend-log batches being dropped when Postgres restarts mid-flush. During a brief outage, Prisma’s engine can return a malformed P1001 payload (
meta: null), which surfaces as anAttributeErrorinsideprisma.engineinstead of a typedPrismaError. Those failures were not treated as transient, soupdate_spend_logsraised without requeueing the dequeued rows._is_transient_spend_log_write_errornow also classifiesPrismaDBExceptionHandler.is_prisma_engine_internal_erroras transient, aligning spend writes with auth and routing the batch through the existing retry andrequeue_spend_logspath. A unit test simulatescreate_manyfailing via Prisma’shandle_response_errorswithmeta: Noneand asserts retries plus requeue of the batch.Reviewed by Cursor Bugbot for commit f91a18a. Bugbot is set up for automated code reviews on this repo. Configure here.