Skip to content

fix(spend-tracking): stop caching failed spend-log metadata lookups as confirmed misses - #43560

Merged
mateo-berri merged 9 commits into
mainfrom
litellm_spend_log_recovery_failure_cache
Oct 5, 2026
Merged

mateo-berri merged 9 commits into
mainfrom
litellm_spend_log_recovery_failure_cache

Conversation

@devin-ai-integration

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

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves:

  • A failed spend-log alias lookup was cached as a confirmed miss
  • Two failures in a row hid key alias and user email for 10 minutes
  • A dropped database connection during the lookup failed the whole usage call with a 500

How it solves it:

  • A failed lookup keeps the 30 second retry backoff only
  • Only a lookup that ran and found nothing can escalate to the long cache
  • Any error out of the lookup counts as a failed lookup, not only Prisma's own error type, since the Prisma client raises a plain AttributeError on a dropped connection

User Flow

Before: a customer with a large spend-log table pulls usage and gets null key names and emails even though the data exists, and a database connection drop during that lookup fails the whole call

  1. They send GET https://litellm-domain/user/daily/activity/aggregated for a one-day range
  2. The alias lookup for hashed keys runs past its 5 second timeout and the response shows key_alias, user_id and user_email as null
  3. They retry within a minute, it times out again, and every retry for the next 10 minutes returns nulls without even trying
  4. On another day their database pooler restarts while the lookup is running, and the same GET answers HTTP 500 {"detail":{"error":"Failed to fetch analytics: 'NoneType' object has no attribute 'get'"}} with no usage rows at all

After: a slow lookup still returns nulls for that call, but it gets retried 30 seconds later, and a dropped connection costs one call its key names instead of the whole page

  1. They send the same GET https://litellm-domain/user/daily/activity/aggregated request
  2. The alias lookup times out and the response shows nulls
  3. A retry 30 seconds later runs the lookup again, and once it finishes in time the keys come back with alias, user_id and user_email filled in
  4. When the pooler restarts mid-lookup, the same GET still answers HTTP 200 with every usage row, nulls for that call only, and a retry 30 seconds later names the keys again

Relevant issues

Reported by a customer in Pylon #8154 and #9195

Linear ticket

Resolves LIT-8906

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
  • 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

Last updated: 1300ba7. QA and /live-pr-risk ran on 390962b, the last commit with a product diff; fb9fef7 and 1300ba7 change only the test relay (a trigger split across two TCP reads now trips it) and add a unit test for that, and the seven audit cells that use that relay reran on 1300ba7 below; 2039af8 merged main without changing this PR's delta and the merge-ref check below reran the scenarios on the merged tree; the audit below ran on that merged tree

Each leg boots the proxy twice from the same commit, on two random ports with --num_workers 2 each, against one shared Postgres database and no Redis, since the lookup cache lives in each worker's memory. Every usage round sends 16 concurrent requests to each instance, and the chat calls hit Anthropic for real. The proxies reach Postgres through a small TCP relay that forwards everything untouched until the last step arms it; armed, it closes every connection the moment it sees the alias lookup SQL go by and refuses the next 5 connects, standing in for a pooler restart or failover. The before and after legs run the same script and differ only in the commit the proxies booted from. The diff touches no dependency file, so both legs share one venv

model_list:
  - model_name: claude-haiku-4-5
    litellm_params:
      model: anthropic/claude-haiku-4-5
      api_key: os.environ/ANTHROPIC_API_KEY

general_settings:
  master_key: os.environ/LITELLM_MASTER_KEY
  proxy_batch_write_at: 5
python litellm/proxy/proxy_cli.py --config qa.yaml --port $A --num_workers 2
python litellm/proxy/proxy_cli.py --config qa.yaml --port $B --num_workers 2

D=$(date -u +%F)
AUTH="Authorization: Bearer $LITELLM_MASTER_KEY"
sleep_until() { local left=$(( $1 - $(date +%s) )); (( left > 0 )) && sleep $left; }
usage_round() {
  SECONDS=0
  echo "== $1 ($(date -u +%T)): 16 concurrent GETs to each of :$A and :$B"
  for i in {1..16}; do
    for p in $A $B; do
      curl -s "http://127.0.0.1:$p/user/daily/activity/aggregated?start_date=$D&end_date=$D" -H "$AUTH" \
        | jq -c --arg p ":$p" '.results[].breakdown.api_keys[].metadata | {port: $p, key_alias, user_id, user_email}' &
    done
  done | sort | uniq -c
  echo "   took ${SECONDS}s"
}

Before (90e4962)

Key names after the spend-log lookup times out

  1. Setup: create a user and a key, then make one real claude-haiku-4-5 call through each instance, :34715 and :20957
curl -s http://127.0.0.1:$A/user/new -H "$AUTH" -H 'Content-Type: application/json' \
  -d '{"user_id": "dev-8906", "user_email": "dev-8906@example.com"}' | jq -c '{user_id, user_email}'
KEY=$(curl -s http://127.0.0.1:$A/key/generate -H "$AUTH" -H 'Content-Type: application/json' \
  -d '{"user_id": "dev-8906", "key_alias": "dev-laptop-key"}' | jq -r .key)
for p in $A $B; do
  curl -s http://127.0.0.1:$p/v1/chat/completions -H "Authorization: Bearer $KEY" -H 'Content-Type: application/json' \
    -d '{"model": "claude-haiku-4-5", "messages": [{"role": "user", "content": "Say hi in two words"}]}' \
    | jq -c --arg p ":$p" '{port: $p, model, reply: .choices[0].message.content}'
done
{"user_id":"dev-8906","user_email":"dev-8906@example.com"}
{"port":":34715","model":"claude-haiku-4-5","reply":"Hey there!"}
{"port":":20957","model":"claude-haiku-4-5","reply":"Hey there!"}
  1. Pull usage while the key row still exists
curl -s "http://127.0.0.1:$A/user/daily/activity/aggregated?start_date=$D&end_date=$D" -H "$AUTH" \
  | jq -c '.results[].breakdown.api_keys[].metadata | {key_alias, user_id, user_email}'
{"key_alias":"dev-laptop-key","user_id":"dev-8906","user_email":"dev-8906@example.com"}
  1. Setup: drop the key row so its hash only lives in spend logs, like a CLI session token, then hold the spend-log table for 85 seconds so every alias lookup hits its 5 second timeout
psql "$PSQL_URL" -qAtc "DELETE FROM \"LiteLLM_VerificationToken\" WHERE key_alias = 'dev-laptop-key' RETURNING key_alias"
psql "$PSQL_URL" -qAtc 'BEGIN; LOCK TABLE "LiteLLM_SpendLogs" IN ACCESS EXCLUSIVE MODE; SELECT pg_sleep(85); COMMIT;' >/dev/null &
LOCK_PID=$!
START=$(date +%s)
dev-laptop-key
  1. Pull usage three times, 35 seconds apart, while the lookup times out
sleep 2
usage_round "timeout 1"
sleep_until $(( START + 37 )); usage_round "timeout 2, 35s later"
sleep_until $(( START + 72 )); usage_round "timeout 3, 35s later"
== timeout 1 (23:05:15): 16 concurrent GETs to each of :34715 and :20957
  16 {"port":":20957","key_alias":null,"user_id":null,"user_email":null}
  16 {"port":":34715","key_alias":null,"user_id":null,"user_email":null}
   took 6s
== timeout 2, 35s later (23:05:50): 16 concurrent GETs to each of :34715 and :20957
  16 {"port":":20957","key_alias":null,"user_id":null,"user_email":null}
  16 {"port":":34715","key_alias":null,"user_id":null,"user_email":null}
   took 5s
== timeout 3, 35s later (23:06:25): 16 concurrent GETs to each of :34715 and :20957
  16 {"port":":20957","key_alias":null,"user_id":null,"user_email":null}
  16 {"port":":34715","key_alias":null,"user_id":null,"user_email":null}
   took 5s
  1. Pull usage again 35 seconds after the table is free, and the keys are still unnamed on every worker
wait $LOCK_PID
echo "== $(date -u +%T): spend logs table is free again, waiting 35s"
sleep 35
usage_round "retry once the table is free"
== 23:06:38: spend logs table is free again, waiting 35s
== retry once the table is free (23:07:13): 16 concurrent GETs to each of :34715 and :20957
  16 {"port":":20957","key_alias":null,"user_id":null,"user_email":null}
  16 {"port":":34715","key_alias":null,"user_id":null,"user_email":null}
   took 1s

Same retry on the paginated route

  1. Pull the paginated /user/daily/activity route right after the retry above
for i in {1..8}; do
  for p in $A $B; do
    curl -s "http://127.0.0.1:$p/user/daily/activity?start_date=$D&end_date=$D" -H "$AUTH" \
      | jq -c --arg p ":$p" '.results[].breakdown.api_keys[].metadata | {port: $p, key_alias, user_id, user_email}' &
  done
done | sort | uniq -c
   8 {"port":":20957","key_alias":null,"user_id":null,"user_email":null}
   8 {"port":":34715","key_alias":null,"user_id":null,"user_email":null}

Key whose lookup never failed

  1. Setup: a second key makes one real call, then its row is dropped, with the table never locked
KEY2=$(curl -s http://127.0.0.1:$A/key/generate -H "$AUTH" -H 'Content-Type: application/json' \
  -d '{"user_id": "dev-8906", "key_alias": "dev-laptop-key-2"}' | jq -r .key)
curl -s http://127.0.0.1:$B/v1/chat/completions -H "Authorization: Bearer $KEY2" -H 'Content-Type: application/json' \
  -d '{"model": "claude-haiku-4-5", "messages": [{"role": "user", "content": "Say bye in two words"}]}' \
  | jq -c --arg p ":$B" '{port: $p, model, reply: .choices[0].message.content}'
psql "$PSQL_URL" -qAtc "DELETE FROM \"LiteLLM_VerificationToken\" WHERE key_alias = 'dev-laptop-key-2' RETURNING key_alias"
{"port":":20957","model":"claude-haiku-4-5","reply":"Bye now!"}
dev-laptop-key-2
  1. Pull usage for that key's hash through both instances
H2=$(printf %s "$KEY2" | shasum -a 256 | cut -d' ' -f1)
for i in {1..8}; do
  for p in $A $B; do
    curl -s "http://127.0.0.1:$p/user/daily/activity/aggregated?start_date=$D&end_date=$D" -H "$AUTH" \
      | jq -c --arg p ":$p" --arg h "$H2" '.results[].breakdown.api_keys[$h].metadata | {port: $p, key_alias, user_id, user_email}' &
  done
done | sort | uniq -c
   8 {"port":":20957","key_alias":"dev-laptop-key-2","user_id":"dev-8906","user_email":"dev-8906@example.com"}
   8 {"port":":34715","key_alias":"dev-laptop-key-2","user_id":"dev-8906","user_email":"dev-8906@example.com"}

Usage while the database drops every connection mid-lookup

  1. Setup: a third key makes one real call, its row is dropped, and the relay is armed
KEY3=$(curl -s http://127.0.0.1:$A/key/generate -H "$AUTH" -H 'Content-Type: application/json' \
  -d '{"user_id": "dev-8906", "key_alias": "dev-laptop-key-3"}' | jq -r .key)
curl -s http://127.0.0.1:$A/v1/chat/completions -H "Authorization: Bearer $KEY3" -H 'Content-Type: application/json' \
  -d '{"model": "claude-haiku-4-5", "messages": [{"role": "user", "content": "Say thanks in two words"}]}' \
  | jq -c --arg p ":$A" '{port: $p, model, reply: .choices[0].message.content}'
psql "$PSQL_URL" -qAtc "DELETE FROM \"LiteLLM_VerificationToken\" WHERE key_alias = 'dev-laptop-key-3' RETURNING key_alias"
H3=$(printf %s "$KEY3" | shasum -a 256 | cut -d' ' -f1)
touch $RELAY/arm
{"port":":34715","model":"claude-haiku-4-5","reply":"Thank you."}
dev-laptop-key-3
  1. Pull usage once while the database closes every connection as the alias lookup runs, and the whole call fails
curl -s -o drop.json -w 'HTTP %{http_code}\n' "http://127.0.0.1:$A/user/daily/activity/aggregated?start_date=$D&end_date=$D" -H "$AUTH"
jq -c --arg h "$H3" 'if .detail then {error: .detail.error} else (.results[].breakdown.api_keys[$h].metadata | {key_alias, user_id, user_email}) end' drop.json
HTTP 500
{"error":"Failed to fetch analytics: 'NoneType' object has no attribute 'get'"}
  1. Pull usage 35 seconds later through both instances (the header timestamp is when the wait began)
sleep 35
for i in {1..8}; do
  for p in $A $B; do
    curl -s "http://127.0.0.1:$p/user/daily/activity/aggregated?start_date=$D&end_date=$D" -H "$AUTH" \
      | jq -c --arg p ":$p" --arg h "$H3" '.results[].breakdown.api_keys[$h].metadata | {port: $p, key_alias, user_id, user_email}' &
  done
done | sort | uniq -c
== 35s later (23:07:32): 8 GETs to each of :34715 and :20957
   8 {"port":":20957","key_alias":"dev-laptop-key-3","user_id":"dev-8906","user_email":"dev-8906@example.com"}
   8 {"port":":34715","key_alias":"dev-laptop-key-3","user_id":"dev-8906","user_email":"dev-8906@example.com"}

After (390962b)

Key names after the spend-log lookup times out

  1. Setup: create a user and a key, then make one real claude-haiku-4-5 call through each instance, :38590 and :55375 (every After step runs the same command as Before)
{"user_id":"dev-8906","user_email":"dev-8906@example.com"}
{"port":":38590","model":"claude-haiku-4-5","reply":"Hi there!"}
{"port":":55375","model":"claude-haiku-4-5","reply":"Hey there"}
  1. Pull usage while the key row still exists
{"key_alias":"dev-laptop-key","user_id":"dev-8906","user_email":"dev-8906@example.com"}
  1. Setup: drop the key row and hold the spend-log table for 85 seconds
dev-laptop-key
  1. Pull usage three times, 35 seconds apart, while the lookup times out: nulls on every call, same as Before
== timeout 1 (23:09:26): 16 concurrent GETs to each of :38590 and :55375
  16 {"port":":38590","key_alias":null,"user_id":null,"user_email":null}
  16 {"port":":55375","key_alias":null,"user_id":null,"user_email":null}
   took 5s
== timeout 2, 35s later (23:10:01): 16 concurrent GETs to each of :38590 and :55375
  16 {"port":":38590","key_alias":null,"user_id":null,"user_email":null}
  16 {"port":":55375","key_alias":null,"user_id":null,"user_email":null}
   took 5s
== timeout 3, 35s later (23:10:36): 16 concurrent GETs to each of :38590 and :55375
  16 {"port":":38590","key_alias":null,"user_id":null,"user_email":null}
  16 {"port":":55375","key_alias":null,"user_id":null,"user_email":null}
   took 6s
  1. Pull usage again 35 seconds after the table is free, and every worker on both instances names the key again
== 23:10:49: spend logs table is free again, waiting 35s
== retry once the table is free (23:11:24): 16 concurrent GETs to each of :38590 and :55375
  16 {"port":":38590","key_alias":"dev-laptop-key","user_id":"dev-8906","user_email":"dev-8906@example.com"}
  16 {"port":":55375","key_alias":"dev-laptop-key","user_id":"dev-8906","user_email":"dev-8906@example.com"}
   took 0s

Same retry on the paginated route

  1. Pull the paginated /user/daily/activity route right after the retry above
   8 {"port":":38590","key_alias":"dev-laptop-key","user_id":"dev-8906","user_email":"dev-8906@example.com"}
   8 {"port":":55375","key_alias":"dev-laptop-key","user_id":"dev-8906","user_email":"dev-8906@example.com"}

Key whose lookup never failed

  1. Setup: a second key makes one real call, then its row is dropped, with the table never locked
{"port":":55375","model":"claude-haiku-4-5","reply":"Bye now."}
dev-laptop-key-2
  1. Pull usage for that key's hash through both instances
   8 {"port":":38590","key_alias":"dev-laptop-key-2","user_id":"dev-8906","user_email":"dev-8906@example.com"}
   8 {"port":":55375","key_alias":"dev-laptop-key-2","user_id":"dev-8906","user_email":"dev-8906@example.com"}

Usage while the database drops every connection mid-lookup

  1. Setup: a third key makes one real call, its row is dropped, and the relay is armed
{"port":":38590","model":"claude-haiku-4-5","reply":"Thank you."}
dev-laptop-key-3
  1. Pull usage once while the database closes every connection as the alias lookup runs, and the call comes back with every usage row, only that key unnamed
HTTP 200
{"key_alias":null,"user_id":null,"user_email":null}
  1. Pull usage 35 seconds later through both instances, and the key is named again
== 35s later (23:11:33): 8 GETs to each of :38590 and :55375
   8 {"port":":38590","key_alias":"dev-laptop-key-3","user_id":"dev-8906","user_email":"dev-8906@example.com"}
   8 {"port":":55375","key_alias":"dev-laptop-key-3","user_id":"dev-8906","user_email":"dev-8906@example.com"}
The integration file behind CI's red, run locally
python tests/integration/run.py accounting tests/integration/spend/test_daily_activity_key_metadata_query_timeout.py

At 036b551 (the tip before these commits): 3 failed, 3 passed, the same three CI shows (the dropped connection answering 500, /organization/new 403 "Organizations are only available for LiteLLM Enterprise users", and the JWT test getting 403 "JWT Auth is an enterprise only feature")

At 390962b, with no LITELLM_LICENSE set and the file's proxy patching its entitlement at import time: 6 passed in 828.93s

At 2039af8 (main merged in) that patch is gone: main now forwards LITELLM_LICENSE from the runner's environment into each proxy's environment (#43983), so the organization and JWT tests take the license the way the rest of the suite does, and the merge commit changes no product code

Observations

  • Before stopped retrying: rounds took 6s, 5s, 5s, then 1s
  • After's 0s round landed inside the 30 second miss window
  • Nulls during the timed-out call remain, this PR leaves that alone
  • The paginated route gets the same fix
  • Lookups that never failed resolve the same on both legs
  • Before answers 500 to the whole call on a dropped connection
  • After answers 200 with nulls there, and names the key 35s later
  • Reverting the fix fails the new regression tests

Live dependency check (390962b)

Verdict: pass. Every entry point that reaches the changed helpers was walked, the two families with no test through a dropped connection were driven live on both sides, and the only observable changes are the ones this PR sets out to make

Same rig as above, two proxies per leg with --num_workers 2 each and one shared Postgres behind the relay. One real claude-haiku-4-5 call seeds the spend log, then the key row is deleted so its hash only lives in spend logs, like a CLI session token. The relay's second arm keys on the key's hash digest instead of SQL text, since Prisma's prepared statements put the SQL on the wire only once per connection while the digest is a bind parameter of every recovery query

H=$(printf %s "$KEY" | shasum -a 256 | cut -d' ' -f1)
paginated() {
  curl -s -o page.json -w "HTTP %{http_code}\n" "http://127.0.0.1:$1/user/daily/activity?start_date=$D&end_date=$D" -H "$AUTH"
  jq -c --arg h "$H" 'if .detail then {error: .detail.error} else (.results[].breakdown.api_keys[$h].metadata | {key_alias, user_id, user_email}) end' page.json
}
vantage() {
  curl -s -o vantage.json -w "HTTP %{http_code}\n" http://127.0.0.1:$1/vantage/dry-run -H "$AUTH" -H 'Content-Type: application/json' -d '{"limit": 50}'
  jq -c --arg h "$H" 'if .detail then {error: .detail.error} else {status, rows: .summary.total_records, key: (.dry_run_data.usage_data[] | select(.api_key == $h) | {api_key_alias, user_email})} end' vantage.json
}
psql "$PSQL_URL" -qAtc "DELETE FROM \"LiteLLM_VerificationToken\" WHERE key_alias = 'ops-laptop-key' RETURNING key_alias"
arm_relay "AS digest, key_alias"; paginated $B
sleep 35
for i in {1..4}; do for p in $A $B; do paginated $p | tail -1 & done; done | sort | uniq -c
arm_relay "$H"; vantage $A
sleep 35
vantage $B; vantage $A

Before (90e4962, :58285 and :51923)

== baseline while the key row exists
GET :58285 /user/daily/activity?start_date=2026-09-30&end_date=2026-09-30
HTTP 200
{"key_alias":"ops-laptop-key","user_id":"ops-8906","user_email":"ops-8906@example.com"}
POST :58285 /vantage/dry-run {"limit": 50}
HTTP 200
{"status":"success","rows":1,"key":{"api_key_alias":"ops-laptop-key","user_email":"ops-8906@example.com"}}
== the database closes every connection while the paginated usage route looks the alias up
GET :51923 /user/daily/activity?start_date=2026-09-30&end_date=2026-09-30
HTTP 500
{"error":"Failed to fetch analytics: 'NoneType' object has no attribute 'get'"}
   (connections dropped mid-lookup: 23:48:20)
== 35s later: 4 GETs to each of :58285 and :51923
   4 {"port":":51923","key_alias":"ops-laptop-key","user_id":"ops-8906","user_email":"ops-8906@example.com"}
   4 {"port":":58285","key_alias":"ops-laptop-key","user_id":"ops-8906","user_email":"ops-8906@example.com"}
== the database closes every connection while the Vantage dry run looks the alias up
POST :58285 /vantage/dry-run {"limit": 50}
HTTP 500
{"error":"Failed to perform Vantage dry run export: Error retrieving usage data: 'NoneType' object has no attribute 'get'"}
   (connections dropped mid-lookup: 23:48:56)
== 35s later: the same dry run on :51923 then :58285
POST :51923 /vantage/dry-run {"limit": 50}
HTTP 200
{"status":"success","rows":1,"key":{"api_key_alias":null,"user_email":"ops-8906@example.com"}}
POST :58285 /vantage/dry-run {"limit": 50}
HTTP 200
{"status":"success","rows":1,"key":{"api_key_alias":null,"user_email":"ops-8906@example.com"}}

After (390962b, :50999 and :59230)

== baseline while the key row exists
GET :50999 /user/daily/activity?start_date=2026-09-30&end_date=2026-09-30
HTTP 200
{"key_alias":"ops-laptop-key","user_id":"ops-8906","user_email":"ops-8906@example.com"}
POST :50999 /vantage/dry-run {"limit": 50}
HTTP 200
{"status":"success","rows":1,"key":{"api_key_alias":"ops-laptop-key","user_email":"ops-8906@example.com"}}
== the database closes every connection while the paginated usage route looks the alias up
GET :59230 /user/daily/activity?start_date=2026-09-30&end_date=2026-09-30
HTTP 200
{"key_alias":null,"user_id":null,"user_email":null}
   (connections dropped mid-lookup: 23:51:11)
== 35s later: 4 GETs to each of :50999 and :59230
   4 {"port":":50999","key_alias":"ops-laptop-key","user_id":"ops-8906","user_email":"ops-8906@example.com"}
   4 {"port":":59230","key_alias":"ops-laptop-key","user_id":"ops-8906","user_email":"ops-8906@example.com"}
== the database closes every connection while the Vantage dry run looks the alias up
POST :50999 /vantage/dry-run {"limit": 50}
HTTP 200
{"status":"success","rows":1,"key":{"api_key_alias":null,"user_email":"ops-8906@example.com"}}
   (connections dropped mid-lookup: 23:51:48)
== 35s later: the same dry run on :59230 then :50999
POST :59230 /vantage/dry-run {"limit": 50}
HTTP 200
{"status":"success","rows":1,"key":{"api_key_alias":null,"user_email":"ops-8906@example.com"}}
POST :50999 /vantage/dry-run {"limit": 50}
HTTP 200
{"status":"success","rows":1,"key":{"api_key_alias":null,"user_email":"ops-8906@example.com"}}

Merged tree (390962b with origin/main ed4caeb merged in as 553f1e6372, :23034 and :23876, its own venv and Prisma client since main added a spend log column)

== baseline while the key row exists
GET :23034 /user/daily/activity?start_date=2026-10-01&end_date=2026-10-01
HTTP 200
{"key_alias":"ops-laptop-key","user_id":"ops-8906","user_email":"ops-8906@example.com"}
POST :23034 /vantage/dry-run {"limit": 50}
HTTP 200
{"status":"success","rows":1,"key":{"api_key_alias":"ops-laptop-key","user_email":"ops-8906@example.com"}}
== the database closes every connection while the paginated usage route looks the alias up
GET :23876 /user/daily/activity?start_date=2026-10-01&end_date=2026-10-01
HTTP 200
{"key_alias":null,"user_id":null,"user_email":null}
   (connections dropped mid-lookup: 00:56:39)
== 35s later: 4 GETs to each of :23034 and :23876
   4 {"port":":23034","key_alias":"ops-laptop-key","user_id":"ops-8906","user_email":"ops-8906@example.com"}
   4 {"port":":23876","key_alias":"ops-laptop-key","user_id":"ops-8906","user_email":"ops-8906@example.com"}
== the database closes every connection while the Vantage dry run looks the alias up
POST :23034 /vantage/dry-run {"limit": 50}
HTTP 200
{"status":"success","rows":1,"key":{"api_key_alias":null,"user_email":"ops-8906@example.com"}}
   (connections dropped mid-lookup: 00:57:18)
== 35s later: the same dry run on :23876 then :23034
POST :23876 /vantage/dry-run {"limit": 50}
HTTP 200
{"status":"success","rows":1,"key":{"api_key_alias":null,"user_email":"ops-8906@example.com"}}
POST :23034 /vantage/dry-run {"limit": 50}
HTTP 200
{"status":"success","rows":1,"key":{"api_key_alias":null,"user_email":"ops-8906@example.com"}}

Breaking

None observed. With the key row present both routes answer 200 with the same named fields on both sides (the baseline blocks above), and the product diff is 19 lines in one module whose only new definition is the private _remember_short_lived_miss: no signature, default, response field, config key, env var, or DB column changes

Backward incompatible

  • GET /user/daily/activity while the database closes every connection during the alias lookup: before answers 500 Failed to fetch analytics: 'NoneType' object has no attribute 'get', after answers 200 with key_alias, user_id, and user_email null and names the key on both instances 35 seconds later (drops at 23:48:20Z and 23:51:11Z above). Introduced on purpose by 390962b and awaiting the reviewer's call on this PR
  • POST /vantage/dry-run under the same drop: before answers 500 Failed to perform Vantage dry run export: Error retrieving usage data: 'NoneType' object has no attribute 'get', after answers 200 with api_key_alias null and user_email from the daily spend join (drops at 23:48:56Z and 23:51:48Z above). 35 seconds later both sides still answer api_key_alias null, since the exporters never run the spend-log alias lookup, so that part is not this PR's. Same commit, same standing
  • A lookup that keeps failing reruns every 30 seconds instead of every 10 minutes: the fix LIT-8906 asks for, shown by the timed-out rounds in the proof above

Regression risk

  • The six sibling routes behind the same get_daily_activity (/team/daily/activity, /organization/daily/activity, /tag/daily/activity, /end_user/daily/activity, /agent/daily/activity, and POST /usage/ai/chat) were not driven under a drop. They share the one recovery call the /user route showed, so this is an inference from the code path, not an observation
  • CloudZero export and dry run, the FOCUS export engine, and the mavvrik FOCUS logger call the same fill_missing_api_key_aliases as the Vantage dry run and were not driven. Every one of them goes through the one changed function, _db_or_empty, and the unit test added at this tip pins its None return on a non-Prisma exception; again an inference for the members not driven
  • The catch is now any Exception, so a genuine bug inside a lookup shows as nulls plus one warning per lookup instead of a 500. Observed on the after leg's :50999 log at 23:51:48Z: Failed reverse-hash recovery against active keys for 1 missing keys: 'NoneType' object has no attribute 'get' and its deleted-keys twin. Cancellation is a BaseException and still propagates
  • Queries outside the lookup can still fail in the refusal window right after a drop: the before leg's :58285 logged Can't reach database server on the daily tag spend flush 9 seconds after the first drop (23:48:29Z) and re-queued the rows. That is the Prisma pool's reconnect, already a Caveats row, and the integration test polls through it on both sides

Dependency graph

  • Changed: _db_or_empty (catch widened from PrismaError to Exception, still logs a warning and returns None), _spend_log_metadata_one_query_at_a_time (on a failed query it returns the settled entries and caches each pending digest as a 30 second miss without the :missed-before strike), and the new private _remember_short_lived_miss
  • Downstream of _db_or_empty: recover_cli_session_key_metadata, recover_double_hashed_key_metadata, recover_key_metadata_from_spend_logs, attach_user_details, and fill_missing_api_key_aliases. Entry points: get_daily_activity in common_daily_activity.py behind the seven daily-activity routes above, and fill_missing_api_key_aliases from integrations/cloudzero/database.py and integrations/focus/database.py behind POST /vantage/dry-run, POST /vantage/export, the CloudZero export and dry run, the FOCUS export engine, and the mavvrik FOCUS logger
  • No string dispatch, registry, subclass override, kwargs pass-through, or dashboard field reaches these helpers: a grep for their names across litellm/, enterprise/, and ui/litellm-dashboard/src/ outside their module returns only the two importers above and the unchanged SPEND_LOG_KEY_METADATA_* constants
  • Merge-ref check: main moved on both modules since the merge base (fix(proxy): recover session key owners from daily spend for usage attribution #43642 reordered the daily-activity recovery and fix(proxy): look up hashed key names with two spend log rows per key #43656 rewrote the spend-log probe SQL). The merge is clean and the PR's delta over merged main is the same 19 lines in key_metadata_recovery.py alone, while main still catches only PrismaError and still runs the two-strike _remember_spend_log_metadata on a failed query, so the fix is still needed there. The same two scenarios on that merged tree (drops at 00:56:39Z and 00:57:18Z above) answered exactly as the after leg, and its :23876 log shows main's new daily-spend key owner recovery from fix(proxy): recover session key owners from daily spend for usage attribution #43642 failing through the same _db_or_empty warning as the three older lookups during the drop, so the widened catch covers it too

Not verified

  • A real pooler restart or failover rather than a relay standing in for one. The audit round below covers the sibling daily-activity routes, the CloudZero export and dry run, the Vantage export and dry run and the scheduled FOCUS window under a dropped connection with checked-in cells, so those two items are gone from this list

Audit round 1 of 3

Every cell below is a checked-in tests/integration test run through tests/integration/run.py (the accounting group, each cell named by node id) against a two-worker proxy, Postgres and Redis that the audit owns, with wire_server peers from _support/wire.py standing in for the provider behind POST /usage/ai/chat, the JWKS endpoint, the Vantage sink and the CloudZero TLS sink. A cell that drops a database connection, kills a worker or starts a second instance boots its own two-worker proxy through owned_proxy_process, with DATABASE_URL pointed at a relay from _support/database_relay.py (the existing database_relay for the cells that drop every connection, the new dropped_connection_relay for the cells that close only the connection the recovery query runs on); every other cell runs against the rig's proxy with the spend-log table locked through Postgres. Nothing inside the proxy is mocked. The base leg ran the changed cells from the merge base 0d5ea45c86b9, where a failed spend-log lookup is remembered with a strike and the second failure pins the key blank for 600 seconds, and where _db_or_empty lets the Prisma client's plain AttributeError on a dropped connection out as a 500, so every changed cell is expected red there. The head legs ran the same cells twice from 2039af8255b6 with --seed 43560 --order-seed 8906, both legs collecting and passing the same 12 cells. The five controls expect the same outcome on both legs and ran once on the head; since every one of them is new in this PR and CircleCI main has no result for them, each also ran once on the base, where all five were green. Two cells the PR already carried came back red on the first head controls run because they were written against the PR's 2026-09-28 base and the 2026-10-02 merge of main changed what they read: test_every_usage_route_names_spend_log_only_keys_again_once_an_outage_ends read the team export route and the key search routes, but main's export now streams SQL-joined rows and never calls the recovery, and main's bounded search routes answer {api_keys: [{api_key, metrics, metadata}]} and find the deleted key by alias too; test_usage_page_retries_the_spend_log_lookup_for_a_rejected_jwt_caller_once_spend_logs_free_up expected every field blank under the lock, but main's #43642 now names the user from daily spend while only the alias stays blank. Both are tests-only changes in a6272b23256531db6349cfc29e2957db4a42b369. The second turned out green on both legs, because a single failure is a 30 second miss with a strike on the merge base too and only the second strike pins, so it is a control. The first, rewritten the same way, also came back green on the base (r3-base-a5): its one failed lookup per worker under the lock never reached the two-strike path the fix removes. The audit then gave it the shape test_usage_ai_chat_timeout_then_second_timeout_still_recovers_key_alias_after_database_frees already has, a second timed-out lookup on the pinned worker under the same lock once the 30 second miss expires, and reran it: red on the base, where that second strike pins the keys blank for 600 seconds, and green twice on the head, where the alias is named within 60 seconds of the release. Run logs, per-cell junit summaries and the owned proxies' logs for every leg are in this gist.

Surface inventory to cells: the two-timeout retry on POST /usage/ai/chat is test_usage_ai_chat_timeout_then_second_timeout_still_recovers_key_alias_after_database_frees; a timeout followed by a genuine miss on /user/daily/activity is test_usage_page_timeout_then_genuine_miss_still_recovers_key_alias_once_spend_logs_return; two genuine misses still pinning blank is test_usage_page_pins_a_key_blank_only_after_two_genuine_misses; a dropped connection during the spend-log query on the usage page and on the usage AI chat is test_usage_page_survives_a_dropped_database_connection_during_alias_recovery and test_usage_ai_chat_survives_a_dropped_database_connection_during_alias_recovery; the eleven usage routes (the user, team, organization, customer, end-user, tag and agent daily routes, the user and team aggregated routes, and the user and team searches) under a lock with a 16-call concurrent burst and the recovery after the release is test_every_usage_route_names_spend_log_only_keys_again_once_an_outage_ends; the rejected JWT caller is test_usage_page_retries_the_spend_log_lookup_for_a_rejected_jwt_caller_once_spend_logs_free_up; two proxy instances on one database is test_second_proxy_instance_names_the_key_while_the_first_recovers_from_its_own_misses; a restart ending the outage is test_usage_page_names_the_key_at_once_after_a_restart_ends_the_outage; a worker SIGKILLed mid-outage is test_usage_page_keeps_serving_when_a_worker_dies_mid_outage; the sad params (a 5 KB, empty, repeated, int and list api_key, a zero and a non-int page_size) plus the unaffected routes under the lock (/gateway/daily/activity, both health routes, a chat completion) is test_usage_page_rejects_bad_key_filters_and_unrelated_routes_ignore_a_locked_spend_log_table; every daily route (/user, /user/aggregated, /team, /organization, /tag, /customer, /end_user, /agent) with the one connection the reverse-hash query runs on closed under it is test_every_usage_route_survives_a_dropped_database_connection_during_reverse_hash_recovery; the same drop during the user-detail lookup and inside main's daily-spend owner transaction is test_usage_page_survives_a_dropped_database_connection_during_user_detail_recovery and test_team_usage_page_survives_a_dropped_database_connection_during_owner_recovery; POST /vantage/dry-run and POST /cloudzero/dry-run under the reverse-hash drop and under the user-detail drop is the two test_vantage_and_cloudzero_dry_runs_survive_* cells; POST /vantage/export (unwindowed, then the scheduler's windowed call) under the drop with the multipart costs.csv read at the sink, followed by the sink answering 403 and 404, is test_vantage_export_delivers_a_blank_alias_under_a_dropped_database_connection_and_reports_sink_errors; POST /cloudzero/export through the HTTPS CONNECT tunnel under the drop, then the hourly job's windowed shape, is test_cloudzero_export_delivers_a_blank_alias_under_a_dropped_database_connection. No row needs a real vendor verdict: the fix changes only what litellm answers and sends, and the payload shape on a successful lookup is the merge base's own, so there is no live cell.

Cell base 0d5ea45 head 2039af8 run 1 head 2039af8 run 2 Verdict
tests/integration/spend/test_daily_activity_key_metadata_query_timeout.py::test_usage_ai_chat_timeout_then_second_timeout_still_recovers_key_alias_after_database_frees FAIL PASS PASS PASS
tests/integration/spend/test_daily_activity_key_metadata_query_timeout.py::test_usage_page_timeout_then_genuine_miss_still_recovers_key_alias_once_spend_logs_return FAIL PASS PASS PASS
tests/integration/spend/test_daily_activity_key_metadata_query_timeout.py::test_usage_page_pins_a_key_blank_only_after_two_genuine_misses PASS PASS not run (control, once on the head) PASS
tests/integration/spend/test_daily_activity_key_metadata_query_timeout.py::test_usage_page_survives_a_dropped_database_connection_during_alias_recovery FAIL PASS PASS PASS
tests/integration/spend/test_daily_activity_key_metadata_query_timeout.py::test_every_usage_route_names_spend_log_only_keys_again_once_an_outage_ends FAIL PASS PASS PASS
tests/integration/spend/test_daily_activity_key_metadata_query_timeout.py::test_usage_page_retries_the_spend_log_lookup_for_a_rejected_jwt_caller_once_spend_logs_free_up PASS PASS not run (control, once on the head) PASS
tests/integration/spend/test_daily_activity_key_metadata_query_timeout.py::test_second_proxy_instance_names_the_key_while_the_first_recovers_from_its_own_misses FAIL PASS PASS PASS
tests/integration/spend/test_daily_activity_key_metadata_query_timeout.py::test_usage_page_names_the_key_at_once_after_a_restart_ends_the_outage PASS PASS not run (control, once on the head) PASS
tests/integration/spend/test_daily_activity_key_metadata_query_timeout.py::test_usage_page_keeps_serving_when_a_worker_dies_mid_outage PASS PASS not run (control, once on the head) PASS
tests/integration/spend/test_daily_activity_key_metadata_query_timeout.py::test_usage_page_rejects_bad_key_filters_and_unrelated_routes_ignore_a_locked_spend_log_table PASS PASS not run (control, once on the head) PASS
tests/integration/spend/test_daily_activity_key_metadata_query_timeout.py::test_usage_ai_chat_survives_a_dropped_database_connection_during_alias_recovery FAIL PASS PASS PASS
tests/integration/spend/test_key_metadata_recovery_dropped_connection.py::test_every_usage_route_survives_a_dropped_database_connection_during_reverse_hash_recovery FAIL PASS PASS PASS
tests/integration/spend/test_key_metadata_recovery_dropped_connection.py::test_usage_page_survives_a_dropped_database_connection_during_user_detail_recovery FAIL PASS PASS PASS
tests/integration/spend/test_key_metadata_recovery_dropped_connection.py::test_team_usage_page_survives_a_dropped_database_connection_during_owner_recovery FAIL PASS PASS PASS
tests/integration/spend/test_key_metadata_recovery_dropped_connection.py::test_vantage_and_cloudzero_dry_runs_survive_a_dropped_database_connection_during_reverse_hash_recovery FAIL PASS PASS PASS
tests/integration/spend/test_key_metadata_recovery_dropped_connection.py::test_vantage_and_cloudzero_dry_runs_survive_a_dropped_database_connection_during_user_detail_recovery FAIL PASS PASS PASS
tests/integration/spend/test_key_metadata_recovery_dropped_connection.py::test_vantage_export_delivers_a_blank_alias_under_a_dropped_database_connection_and_reports_sink_errors FAIL PASS PASS PASS
tests/integration/spend/test_key_metadata_recovery_dropped_connection.py::test_cloudzero_export_delivers_a_blank_alias_under_a_dropped_database_connection FAIL PASS PASS PASS

Every inventory row is VERIFIED by a cell above; none is unverified. A run on a given leg is a run.py invocation with its own results dir and log, named in the gist: r1-base (the 12 changed cells plus the two rewritten cells), r1-head-1 and r1-head-2 (the 12 changed cells), r1-head-controls (A3, A8, A9, A10 and the two cells before their rewrite), r1-head-fixed-1 (the rewritten JWT cell), r3-head-a5-1, r3-head-a5-2 and r3-base-a5 (the rewritten sweep cell before the second strike was added, green on all three), r4-head-a5-1, r4-head-a5-2 and r4-base-a5 (the sweep cell as committed), r3-base-controls (the four new controls on the base). Every row ran against the product code of 2039af8255b6; a6272b23256531db6349cfc29e2957db4a42b369 adds the audit's tests on top with no product diff

Rerun after the relay changes in fb9fef7d48012f31829cad1b6a37b0d177de6afb and 1300ba707e099b7bd180c9d7de73f87784ccf99e: Greptile pointed out that dropped_connection_relay checked each TCP read on its own, so a trigger split across two reads would never close the connection. The relay now feeds every read through a small TriggerScanner that carries the tail of the previous read into the next check, the way held_statement_relay already did inline, and tests/unit/integration_support/test_database_relay.py feeds that scanner the trigger split at every byte offset, in process and with no sockets (43 of its 44 cases fail when the scanner checks each read on its own). The seven cells that use that relay reran at 1300ba707e09, head twice and base once, on a fresh rig built the same way and with the same seeds as the rows above (r6-head-d-1, r6-head-d-2, r6-base-d in the gist; the r5-* runs there are the same cells on the first version of the relay patch); the other eleven rows keep their results above, since neither the product code nor their relay changed

Cell base 0d5ea45 head 1300ba7 run 1 head 1300ba7 run 2 Verdict
tests/integration/spend/test_key_metadata_recovery_dropped_connection.py::test_every_usage_route_survives_a_dropped_database_connection_during_reverse_hash_recovery FAIL PASS PASS PASS
tests/integration/spend/test_key_metadata_recovery_dropped_connection.py::test_usage_page_survives_a_dropped_database_connection_during_user_detail_recovery FAIL PASS PASS PASS
tests/integration/spend/test_key_metadata_recovery_dropped_connection.py::test_team_usage_page_survives_a_dropped_database_connection_during_owner_recovery FAIL PASS PASS PASS
tests/integration/spend/test_key_metadata_recovery_dropped_connection.py::test_vantage_and_cloudzero_dry_runs_survive_a_dropped_database_connection_during_reverse_hash_recovery FAIL PASS PASS PASS
tests/integration/spend/test_key_metadata_recovery_dropped_connection.py::test_vantage_and_cloudzero_dry_runs_survive_a_dropped_database_connection_during_user_detail_recovery FAIL PASS PASS PASS
tests/integration/spend/test_key_metadata_recovery_dropped_connection.py::test_vantage_export_delivers_a_blank_alias_under_a_dropped_database_connection_and_reports_sink_errors FAIL PASS PASS PASS
tests/integration/spend/test_key_metadata_recovery_dropped_connection.py::test_cloudzero_export_delivers_a_blank_alias_under_a_dropped_database_connection FAIL PASS PASS PASS

Type

🐛 Bug Fix

Caveats (if any)

Low

  • The call that times out still returns nulls
  • A lookup that keeps timing out reruns every 30 seconds, not every 10 minutes
  • The lookup now swallows any exception, not only Prisma's own error type
    • The Prisma client raises a plain AttributeError on a dropped connection (P1017 with no meta), which the old catch let through as a 500 on the whole usage call
    • Every failure still logs a warning with the error and keeps only the 30 second backoff, so a bug in the lookup shows as nulls plus a warning rather than a 500, and the regression test pins that backoff
    • Cancellation is a BaseException, so it still propagates
  • Calls in the seconds right after a dropped connection can still 500 on the main usage query until the connection pool reconnects
    • Seen in the integration test on both the base and this tip, so the test polls through that window
    • That is the Prisma pool's reconnect, outside the alias lookup this PR changes
  • osv-scan, a non-required job, is red at this tip on braces 3.0.3 (GHSA-vfj7-8cjw-p6xm, a dev dependency in ui/litellm-dashboard/package-lock.json) and red the same way on main's own run 37104625295

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/4ddd96b601de4a928c97b94b2fea5030
Open in Devin Desktop: https://app.devin.ai/desktop/session/4ddd96b601de4a928c97b94b2fea5030?variant=devin


Note

Medium Risk
Changes error handling and in-memory miss caching on hot usage/analytics paths; failures now surface as null metadata plus warnings instead of 500s, with more frequent retries under sustained DB stress.

Overview
Fixes spend-log key alias recovery so timeouts and DB errors no longer pin keys as blank for 10 minutes, and dropped connections no longer 500 whole usage/export calls.

In key_metadata_recovery.py, _db_or_empty now catches any Exception (not only PrismaError), logs a warning, and returns empty metadata so callers degrade to null aliases instead of crashing. When a spend-log batch query fails, _spend_log_metadata_one_query_at_a_time writes only a 30s short-lived miss via _remember_short_lived_miss and skips the two-strike :missed-before path that previously escalated repeated failures to a long cache.

Test support adds DroppedConnectionRelay with TriggerScanner (cross-chunk SQL matching) plus large integration suites for timeouts, dropped connections, multi-worker/restart, and Vantage/CloudZero paths; unit tests cover repeated failures and connection-drop errors.

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

gabriele-berri and others added 2 commits September 28, 2026 11:28
…s confirmed misses

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@devin-ai-integration
devin-ai-integration Bot requested a review from a team September 28, 2026 11:29
@devin-ai-integration

devin-ai-integration Bot commented Sep 28, 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

@CLAassistant

CLAassistant commented Sep 28, 2026 •

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 all sign our Contributor License Agreement before we can accept your contribution.
1 out of 2 committers have signed the CLA.

✅ mateo-berri
❌ gabriele


gabriele seems not to be a GitHub user. You need a GitHub account to be able to sign the CLA. If you have already a GitHub account, please add the email address used for this commit to your account.
You have signed the CLA already but the status is still pending? Let us recheck it.

@greptile-apps

greptile-apps Bot commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 5/5

[Medium risk] Fixes spend-log metadata caching logic for failed queries.

The PR appears safe to merge; no outstanding blocking finding was established

Summary

The PR keeps failed spend-log metadata lookups on a short retry window instead of escalating them to a confirmed long-lived miss. It also handles non-Prisma lookup exceptions and adds outage coverage for usage and export paths. The latest change extracts the relay’s trigger scanning into an in-process helper and tests split triggers without network activity

Reviews (8) · Last reviewed commit: "test(integration): scan relay triggers t..."

@codspeed

codspeed Bot commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

✅ 31 untouched benchmarks


Comparing litellm_spend_log_recovery_failure_cache (1300ba7) with main (9cdedf8)1

Open in CodSpeed

Footnotes

  1. No successful run was found on main (f0415ee) during the generation of this report, so 9cdedf8 was used instead as the comparison base. There might be some changes unrelated to this pull request in this report. ↩

@codecov

codecov Bot commented Sep 28, 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

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.

Stale Bugbot comment from a previous run.

@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@mateo-berri mateo-berri added run-ci and removed run-ci labels Sep 29, 2026
@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

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

Stale Bugbot comment from a previous run.

…ved miss

The Prisma client raises a plain AttributeError when the database drops
the connection mid-query, so the PrismaError catch let it through and
the whole usage call answered 500. Any failure now keeps the 30 second
backoff only, and the integration proxy patches its test entitlement at
import so uvicorn's spawned workers inherit it
@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

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

Stale Bugbot comment from a previous run.

…overy_failure_cache

# Conflicts:
#	tests/integration/_support/proxy.py
@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

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

Stale Bugbot comment from a previous run.

…nd dropped connections

Cover the daily activity routes, the usage AI chat, the Vantage and
CloudZero dry runs and exports under a locked spend-log table and under
a database connection dropped mid-lookup, on a two-worker proxy, with
the recovery after the outage asserted through the proxy's own miss TTL.

Add a dropped_connection_relay that closes only the connection whose
bytes carry a trigger, so a cell can drop the one connection the
recovery query runs on while the rest of the pool keeps serving. Rewrite
the sweep and JWT cells for the merged main: the export route reads
metadata by SQL join and never calls the recovery, the search routes
answer key rows and find deleted keys by alias, and the daily-spend
owner recovery names the user while the alias stays blank. The sweep
cell now times out a second lookup under the same lock, which pins the
keys blank on the merge base and recovers on this branch.
@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

…o reads

The dropped-connection relay checked each TCP read on its own, so a SQL
marker that straddled two reads never tripped it and the outage cells
would run without the outage they meant to exercise. Carry the tail of
the previous read into the next check, as the held-statement relay
already does, and pin that with a unit test that splits the trigger
across two writes.
@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

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

Stale Bugbot comment from a previous run.

The dropped-connection relay now matches its SQL trigger through a TriggerScanner that carries the previous read's tail, and the unit test exercises that scanner directly instead of opening loopback sockets, which tests/unit forbids. The relay's end to end behavior stays covered by the integration cells
@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@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 1300ba7. Configure here.

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

LGTM

@mateo-berri
mateo-berri merged commit a1a4276 into main Oct 5, 2026
92 of 93 checks passed
@mateo-berri
mateo-berri deleted the litellm_spend_log_recovery_failure_cache branch October 5, 2026 22:36
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