Skip to content

fix(proxy): requeue spend logs when a Postgres restart tears down the prisma engine mid-write - #47571

Merged
klu-berri merged 1 commit into
mainfrom
litellm_spend_rows_requeue_on_postgres_restart
Oct 20, 2026
Merged

klu-berri merged 1 commit into
mainfrom
litellm_spend_rows_requeue_on_postgres_restart

Conversation

@klu-berri

@klu-berri klu-berri commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves:

  • A spend-log flush that runs in the instant Postgres restarts drops its whole batch
  • Those requests never get a LiteLLM_SpendLogs row, so spend is under-reported

How it solves it:

  • _is_transient_spend_log_write_error now also treats PrismaDBExceptionHandler.is_prisma_engine_internal_error as transient
  • The batch then goes through the existing retry and requeue_spend_logs path instead of being raised away

In the instant Postgres tears its connections down, prisma's query engine answers the write with a P1001 payload whose meta is null. prisma-client-py's handle_response_errors trips on that (AttributeError: 'NoneType' object has no attribute 'get') before it can raise a typed DataError, so the error is neither a transport error nor a PrismaError and update_spend_logs raised it without putting the dequeued rows back. The auth path already classified this exact error with is_prisma_engine_internal_error, the writer just did not use it. One second later the same outage produces the typed DataError P1001, which the writer already retried and requeued, which is why a long outage lost nothing and only the restart instant did

User Flow

Before: a proxy admin restarts Postgres while traffic is flowing and some of those requests never show up in spend

  1. Traffic hits POST http://localhost:4000/v1/chat/completions with "model": "gpt-4o-mini" and every request returns 200 with a chatcmpl-... id
  2. The admin runs sudo service postgresql restart (about one second of downtime) while the requests keep flowing
  3. Minutes later SELECT 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=logs

After: the same restart loses nothing

  1. Traffic hits POST http://localhost:4000/v1/chat/completions with "model": "gpt-4o-mini" and every request returns 200 with a chatcmpl-... id
  2. The admin runs sudo service postgresql restart while the requests keep flowing
  3. SELECT 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 page

Relevant issues

Closes the gap left by #47364, which removed the pytest.skip("BUG: ...") on tests/integration/observability/test_guardrail_stream_scope_chaos.py::test_h6_spend_rows_for_requests_served_during_postgres_restart_land_once while the writer bug behind the skip was still there. That test passes on main only 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:

14:05:09 - LiteLLM Proxy:INFO: utils.py:7813 - Spend tracking - processing 5 spend logs for DB write
14:05:09 - LiteLLM Proxy:ERROR: spend_log_error_logger.py:81 - Error in spend logs queue monitor: 'NoneType' object has no attribute 'get'

On this branch the same h6 run (green, 80 s) shows the restart-instant flush retried instead of dropped:

14:24:05 - LiteLLM Proxy:INFO: utils.py:7813 - Spend tracking - processing 5 spend logs for DB write
14:24:05 - LiteLLM Proxy:WARNING: utils.py:7880 - Spend tracking - transient DB error writing spend logs, retry 1/3. logs_count=5, error='NoneType' object has no attribute 'get'
14:24:06 - LiteLLM Proxy:DEBUG: utils.py:7859 - Flushed 5 logs to the DB.

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

  • 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

Real proxy, local Postgres, real OpenAI gpt-4o-mini calls. Shared setup:

# /home/ubuntu/repro/live/config.yaml
model_list:
  - model_name: gpt-4o-mini
    litellm_params:
      model: openai/gpt-4o-mini
      api_key: os.environ/OPENAI_API_KEY
general_settings:
  master_key: sk-litellm-restart-proof-9f3c2a1b7d
  database_url: os.environ/DATABASE_URL
  allow_requests_on_db_unavailable: true
  proxy_batch_write_at: 5
export DATABASE_URL="postgresql://postgres:postgres@127.0.0.1:5432/litellm"
export SPEND_LOG_QUEUE_POLL_INTERVAL=0.5   # flush often enough that a flush lands inside the restart window
python litellm/proxy/proxy_cli.py --config /home/ubuntu/repro/live/config.yaml --port 4000 --detailed_debug > proxy.log 2>&1 &

# 60 requests, one every 0.5 s, ids collected into ids.txt
for i in $(seq 1 60); do
  curl -s http://localhost:4000/v1/chat/completions -H "Authorization: Bearer sk-litellm-restart-proof-9f3c2a1b7d" \
    -H "Content-Type: application/json" \
    -d "{\"model\":\"gpt-4o-mini\",\"messages\":[{\"role\":\"user\",\"content\":\"say ok $i\"}],\"max_tokens\":3}" \
    | python3 -c "import json,sys; print(json.load(sys.stdin)['id'])" >> ids.txt &
  sleep 0.5
done &
# four Postgres restarts while the requests flow
for r in 1 2 3 4; do sleep 6; echo "--- postgres restart $r: $(date +%T.%N)"; sudo service postgresql restart; done
wait
IDS=$(sed "s/.*/'&'/" ids.txt | paste -sd, -)
psql "$DATABASE_URL" -tAc "select count(*) from \"LiteLLM_SpendLogs\" where request_id in ($IDS)"

Before (5145250)

  1. Ran the commands above against main

    proxy up, git: 5145250d83, SPEND_LOG_QUEUE_POLL_INTERVAL=0.5
    --- postgres restart 1: 14:16:01.689
    --- postgres restart 2: 14:16:10.043
    --- postgres restart 3: 14:16:18.376
    --- postgres restart 4: 14:16:26.714
    --- 60 requests answered, 60 with a 200 id
    t+30s LiteLLM_SpendLogs rows for those request_ids: 53
    t+40s LiteLLM_SpendLogs rows for those request_ids: 53
    t+50s LiteLLM_SpendLogs rows for those request_ids: 53
    t+60s LiteLLM_SpendLogs rows for those request_ids: 53
    t+70s LiteLLM_SpendLogs rows for those request_ids: 53
    t+80s LiteLLM_SpendLogs rows for those request_ids: 53
    
  2. grep -n "Spend tracking - processing\|Error in spend logs queue monitor\|Flushed" proxy.log shows the flush that ran three seconds after restart 1 and took its batch with it, with no retry and no requeue line

    2851:14:16:04 - LiteLLM Proxy:INFO: utils.py:7813 - Spend tracking - processing 14 spend logs for DB write
    2852:14:16:04 - LiteLLM Proxy:ERROR: spend_log_error_logger.py:81 - Error in spend logs queue monitor: 'NoneType' object has no attribute 'get'
    5351:14:16:12 - LiteLLM Proxy:INFO: utils.py:7813 - Spend tracking - processing 32 spend logs for DB write
    5352:14:16:12 - LiteLLM Proxy:DEBUG: utils.py:7859 - Flushed 32 logs to the DB.
    

    The traceback under that ERROR line ends in prisma, not in litellm code:

      File ".../prisma/engine/http.py", line 141, in request
        return utils.handle_response_errors(resp, errors_data)
      File ".../prisma/engine/utils.py", line 184, in handle_response_errors
        kind = user_facing.get('meta', {}).get('kind')
    AttributeError: 'NoneType' object has no attribute 'get'
    

After (f91a18a)

  1. Same commands against this branch

    proxy up, git: f91a18a74d, SPEND_LOG_QUEUE_POLL_INTERVAL=0.5
    --- postgres restart 1: 14:18:50.914
    --- postgres restart 2: 14:18:59.251
    --- postgres restart 3: 14:19:07.588
    --- postgres restart 4: 14:19:15.926
    --- 60 requests answered, 60 with a 200 id
    t+30s LiteLLM_SpendLogs rows for those request_ids: 60
    t+40s LiteLLM_SpendLogs rows for those request_ids: 60
    t+50s LiteLLM_SpendLogs rows for those request_ids: 60
    t+60s LiteLLM_SpendLogs rows for those request_ids: 60
    t+70s LiteLLM_SpendLogs rows for those request_ids: 60
    t+80s LiteLLM_SpendLogs rows for those request_ids: 60
    
  2. The same grep shows the same error hitting the same-sized batch, now retried and written once Postgres is back

    2913:14:18:53 - LiteLLM Proxy:INFO: utils.py:7813 - Spend tracking - processing 14 spend logs for DB write
    2914:14:18:53 - LiteLLM Proxy:WARNING: utils.py:7880 - Spend tracking - transient DB error writing spend logs, retry 1/3. logs_count=14, error='NoneType' object has no attribute 'get'
    3300:14:18:54 - LiteLLM Proxy:WARNING: utils.py:7880 - Spend tracking - transient DB error writing spend logs, retry 2/3. logs_count=14, error='NoneType' object has no attribute 'get'
    3923:14:18:56 - LiteLLM Proxy:DEBUG: utils.py:7859 - Flushed 14 logs to the DB.
    

Regression test, red on main and 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_engine makes create_many raise through prisma's own handle_response_errors with the meta: None payload. On main:

>       assert [row["request_id"] for row in mock_prisma_client.spend_log_transactions] == ["a", "b", "c"]
E       AssertionError: assert ['c'] == ['a', 'b', 'c']
E         At index 0 diff: 'c' != 'a'
E         Right contains 2 more items, first extra item: 'b'
1 failed, 31 deselected in 0.71s

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_error matches by prisma.engine traceback origin, so any non-PrismaError raised inside prisma's engine layer during a spend-log write is now retried like a transport error, not only this meta: null payload
  • The requeue reuses the existing bound, SPEND_LOG_QUEUE_MAX_BYTES via enqueue_spend_logs, so nothing new is held in memory during a long outage

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/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 an AttributeError inside prisma.engine instead of a typed PrismaError. Those failures were not treated as transient, so update_spend_logs raised without requeueing the dequeued rows.

_is_transient_spend_log_write_error now also classifies PrismaDBExceptionHandler.is_prisma_engine_internal_error as transient, aligning spend writes with auth and routing the batch through the existing retry and requeue_spend_logs path. A unit test simulates create_many failing via Prisma’s handle_response_errors with meta: None and 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.

@devin-ai-integration

Copy link
Copy Markdown
Contributor

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

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

@codspeed

codspeed Bot commented Oct 20, 2026

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

⚠️ 1 benchmark spent significant time in system calls

System calls cannot be consistently instrumented, so they are not included in the measure, which understates the real cost. Please switch to the Walltime instrument to accurately measure system calls.

Measurement and system calls

✅ 32 untouched benchmarks


Comparing litellm_spend_rows_requeue_on_postgres_restart (f91a18a) with main (b88f64e)

Open in CodSpeed

@codecov

codecov Bot commented Oct 20, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@klu-berri

Copy link
Copy Markdown
Contributor Author

@litellm-stampbot

@kerry-berri

kerry-berri commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

litellm-stampbot: risk high

Not approved at f91a18a. risk is high, a human reviewer is needed.

Rules (stampbot/risk_rules.yml):

  • low: no rule flagged it

Cursor Bugbot: Medium Risk at f91a18a. 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. Bugbot run requested, finished in 3 min.
Bugbot Low is low, Medium and High are high. The judge model was not called.

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

@kerry-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 f91a18a. Configure here.

@kerry-berri kerry-berri added the risk:high Sensitive, broad, or high-risk change label Oct 20, 2026
@klu-berri
klu-berri merged commit ccd0d4e into main Oct 20, 2026
93 checks passed
@klu-berri
klu-berri deleted the litellm_spend_rows_requeue_on_postgres_restart branch October 20, 2026 16:08
pamanseau pushed a commit to KubeTEE-AI/litellm that referenced this pull request Oct 25, 2026
… prisma engine mid-write (BerriAI#47571)

Backport of BerriAI#47571 to stable/1.103.x

Cherry-picked from ccd0d4e (main)
Cartofante pushed a commit to CartoDB/litellm that referenced this pull request Oct 26, 2026
… 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)
yuneng-berri pushed a commit that referenced this pull request Oct 28, 2026
… prisma engine mid-write (#47571)

Co-authored-by: devin-ai-integration[bot] <158243242+devin-ai-integration[bot]@users.noreply.github.com>
(cherry picked from commit ccd0d4e)
haowang1013 pushed a commit to directivegames/litellm that referenced this pull request Nov 3, 2026
… 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).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

risk:high Sensitive, broad, or high-risk change

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants