Repository navigation
fix(spend-tracking): stop caching failed spend-log metadata lookups as confirmed misses - #43560
Conversation
…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>
|
I'll fix CI failures and address comments from users with write access. I'll skip comments containing "(aside)".
|
|
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. |
|
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
|
bugbot run |
… across usage routes
|
bugbot 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
|
bugbot run |
…overy_failure_cache # Conflicts: # tests/integration/_support/proxy.py
|
bugbot 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.
…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.
|
bugbot 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
|
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 1300ba7. Configure here.
TLDR
Problem this solves:
How it solves it:
AttributeErroron a dropped connectionUser 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
key_alias,user_idanduser_emailas null{"detail":{"error":"Failed to fetch analytics: 'NoneType' object has no attribute 'get'"}}with no usage rows at allAfter: 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
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
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@greptileaito 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 2each, 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 venvBefore (90e4962)
Key names after the spend-log lookup times out
Same retry on the paginated route
/user/daily/activityroute right after the retry aboveKey whose lookup never failed
Usage while the database drops every connection mid-lookup
After (390962b)
Key names after the spend-log lookup times out
Same retry on the paginated route
/user/daily/activityroute right after the retry aboveKey whose lookup never failed
Usage while the database drops every connection mid-lookup
The integration file behind CI's red, run locally
At 036b551 (the tip before these commits): 3 failed, 3 passed, the same three CI shows (the dropped connection answering 500,
/organization/new403 "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_LICENSEfrom 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 codeObservations
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 2each 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 queryBefore (90e4962, :58285 and :51923)
After (390962b, :50999 and :59230)
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)
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 changesBackward incompatible
GET /user/daily/activitywhile the database closes every connection during the alias lookup: before answers 500Failed to fetch analytics: 'NoneType' object has no attribute 'get', after answers 200 withkey_alias,user_id, anduser_emailnull 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 PRPOST /vantage/dry-rununder the same drop: before answers 500Failed to perform Vantage dry run export: Error retrieving usage data: 'NoneType' object has no attribute 'get', after answers 200 withapi_key_aliasnull anduser_emailfrom the daily spend join (drops at 23:48:56Z and 23:51:48Z above). 35 seconds later both sides still answerapi_key_aliasnull, since the exporters never run the spend-log alias lookup, so that part is not this PR's. Same commit, same standingRegression risk
get_daily_activity(/team/daily/activity,/organization/daily/activity,/tag/daily/activity,/end_user/daily/activity,/agent/daily/activity, andPOST /usage/ai/chat) were not driven under a drop. They share the one recovery call the/userroute showed, so this is an inference from the code path, not an observationfill_missing_api_key_aliasesas 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 drivenException, 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 aBaseExceptionand still propagatesCan't reach database serveron 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 sidesDependency graph
_db_or_empty(catch widened fromPrismaErrortoException, 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-beforestrike), and the new private_remember_short_lived_miss_db_or_empty:recover_cli_session_key_metadata,recover_double_hashed_key_metadata,recover_key_metadata_from_spend_logs,attach_user_details, andfill_missing_api_key_aliases. Entry points:get_daily_activityincommon_daily_activity.pybehind the seven daily-activity routes above, andfill_missing_api_key_aliasesfromintegrations/cloudzero/database.pyandintegrations/focus/database.pybehindPOST /vantage/dry-run,POST /vantage/export, the CloudZero export and dry run, the FOCUS export engine, and the mavvrik FOCUS loggerlitellm/,enterprise/, andui/litellm-dashboard/src/outside their module returns only the two importers above and the unchangedSPEND_LOG_KEY_METADATA_*constantskey_metadata_recovery.pyalone, while main still catches onlyPrismaErrorand still runs the two-strike_remember_spend_log_metadataon 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_emptywarning as the three older lookups during the drop, so the widened catch covers it tooNot verified
Audit round 1 of 3
Every cell below is a checked-in
tests/integrationtest run throughtests/integration/run.py(theaccountinggroup, each cell named by node id) against a two-worker proxy, Postgres and Redis that the audit owns, withwire_serverpeers from_support/wire.pystanding in for the provider behindPOST /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 throughowned_proxy_process, withDATABASE_URLpointed at a relay from_support/database_relay.py(the existingdatabase_relayfor the cells that drop every connection, the newdropped_connection_relayfor 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 base0d5ea45c86b9, 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_emptylets the Prisma client's plainAttributeErroron a dropped connection out as a 500, so every changed cell is expected red there. The head legs ran the same cells twice from2039af8255b6with--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_endsread 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_upexpected 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 ina6272b23256531db6349cfc29e2957db4a42b369. 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 shapetest_usage_ai_chat_timeout_then_second_timeout_still_recovers_key_alias_after_database_freesalready 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/chatistest_usage_ai_chat_timeout_then_second_timeout_still_recovers_key_alias_after_database_frees; a timeout followed by a genuine miss on/user/daily/activityistest_usage_page_timeout_then_genuine_miss_still_recovers_key_alias_once_spend_logs_return; two genuine misses still pinning blank istest_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 istest_usage_page_survives_a_dropped_database_connection_during_alias_recoveryandtest_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 istest_every_usage_route_names_spend_log_only_keys_again_once_an_outage_ends; the rejected JWT caller istest_usage_page_retries_the_spend_log_lookup_for_a_rejected_jwt_caller_once_spend_logs_free_up; two proxy instances on one database istest_second_proxy_instance_names_the_key_while_the_first_recovers_from_its_own_misses; a restart ending the outage istest_usage_page_names_the_key_at_once_after_a_restart_ends_the_outage; a worker SIGKILLed mid-outage istest_usage_page_keeps_serving_when_a_worker_dies_mid_outage; the sad params (a 5 KB, empty, repeated, int and listapi_key, a zero and a non-intpage_size) plus the unaffected routes under the lock (/gateway/daily/activity, both health routes, a chat completion) istest_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 istest_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 istest_usage_page_survives_a_dropped_database_connection_during_user_detail_recoveryandtest_team_usage_page_survives_a_dropped_database_connection_during_owner_recovery;POST /vantage/dry-runandPOST /cloudzero/dry-rununder the reverse-hash drop and under the user-detail drop is the twotest_vantage_and_cloudzero_dry_runs_survive_*cells;POST /vantage/export(unwindowed, then the scheduler's windowed call) under the drop with the multipartcosts.csvread at the sink, followed by the sink answering 403 and 404, istest_vantage_export_delivers_a_blank_alias_under_a_dropped_database_connection_and_reports_sink_errors;POST /cloudzero/exportthrough the HTTPS CONNECT tunnel under the drop, then the hourly job's windowed shape, istest_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.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_freestests/integration/spend/test_daily_activity_key_metadata_query_timeout.py::test_usage_page_timeout_then_genuine_miss_still_recovers_key_alias_once_spend_logs_returntests/integration/spend/test_daily_activity_key_metadata_query_timeout.py::test_usage_page_pins_a_key_blank_only_after_two_genuine_missestests/integration/spend/test_daily_activity_key_metadata_query_timeout.py::test_usage_page_survives_a_dropped_database_connection_during_alias_recoverytests/integration/spend/test_daily_activity_key_metadata_query_timeout.py::test_every_usage_route_names_spend_log_only_keys_again_once_an_outage_endstests/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_uptests/integration/spend/test_daily_activity_key_metadata_query_timeout.py::test_second_proxy_instance_names_the_key_while_the_first_recovers_from_its_own_missestests/integration/spend/test_daily_activity_key_metadata_query_timeout.py::test_usage_page_names_the_key_at_once_after_a_restart_ends_the_outagetests/integration/spend/test_daily_activity_key_metadata_query_timeout.py::test_usage_page_keeps_serving_when_a_worker_dies_mid_outagetests/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_tabletests/integration/spend/test_daily_activity_key_metadata_query_timeout.py::test_usage_ai_chat_survives_a_dropped_database_connection_during_alias_recoverytests/integration/spend/test_key_metadata_recovery_dropped_connection.py::test_every_usage_route_survives_a_dropped_database_connection_during_reverse_hash_recoverytests/integration/spend/test_key_metadata_recovery_dropped_connection.py::test_usage_page_survives_a_dropped_database_connection_during_user_detail_recoverytests/integration/spend/test_key_metadata_recovery_dropped_connection.py::test_team_usage_page_survives_a_dropped_database_connection_during_owner_recoverytests/integration/spend/test_key_metadata_recovery_dropped_connection.py::test_vantage_and_cloudzero_dry_runs_survive_a_dropped_database_connection_during_reverse_hash_recoverytests/integration/spend/test_key_metadata_recovery_dropped_connection.py::test_vantage_and_cloudzero_dry_runs_survive_a_dropped_database_connection_during_user_detail_recoverytests/integration/spend/test_key_metadata_recovery_dropped_connection.py::test_vantage_export_delivers_a_blank_alias_under_a_dropped_database_connection_and_reports_sink_errorstests/integration/spend/test_key_metadata_recovery_dropped_connection.py::test_cloudzero_export_delivers_a_blank_alias_under_a_dropped_database_connectionEvery inventory row is VERIFIED by a cell above; none is unverified. A run on a given leg is a
run.pyinvocation with its own results dir and log, named in the gist:r1-base(the 12 changed cells plus the two rewritten cells),r1-head-1andr1-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-2andr3-base-a5(the rewritten sweep cell before the second strike was added, green on all three),r4-head-a5-1,r4-head-a5-2andr4-base-a5(the sweep cell as committed),r3-base-controls(the four new controls on the base). Every row ran against the product code of2039af8255b6;a6272b23256531db6349cfc29e2957db4a42b369adds the audit's tests on top with no product diffRerun after the relay changes in
fb9fef7d48012f31829cad1b6a37b0d177de6afband1300ba707e099b7bd180c9d7de73f87784ccf99e: Greptile pointed out thatdropped_connection_relaychecked 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 smallTriggerScannerthat carries the tail of the previous read into the next check, the wayheld_statement_relayalready did inline, andtests/unit/integration_support/test_database_relay.pyfeeds 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 at1300ba707e09, 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-din the gist; ther5-*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 changedtests/integration/spend/test_key_metadata_recovery_dropped_connection.py::test_every_usage_route_survives_a_dropped_database_connection_during_reverse_hash_recoverytests/integration/spend/test_key_metadata_recovery_dropped_connection.py::test_usage_page_survives_a_dropped_database_connection_during_user_detail_recoverytests/integration/spend/test_key_metadata_recovery_dropped_connection.py::test_team_usage_page_survives_a_dropped_database_connection_during_owner_recoverytests/integration/spend/test_key_metadata_recovery_dropped_connection.py::test_vantage_and_cloudzero_dry_runs_survive_a_dropped_database_connection_during_reverse_hash_recoverytests/integration/spend/test_key_metadata_recovery_dropped_connection.py::test_vantage_and_cloudzero_dry_runs_survive_a_dropped_database_connection_during_user_detail_recoverytests/integration/spend/test_key_metadata_recovery_dropped_connection.py::test_vantage_export_delivers_a_blank_alias_under_a_dropped_database_connection_and_reports_sink_errorstests/integration/spend/test_key_metadata_recovery_dropped_connection.py::test_cloudzero_export_delivers_a_blank_alias_under_a_dropped_database_connectionType
🐛 Bug Fix
Caveats (if any)
Low
(api_key, startTime)index from perf(spend_tracking): index LiteLLM_SpendLogs by (api_key, startTime) #37983 helps but is not enoughAttributeErroron a dropped connection (P1017 with nometa), which the old catch let through as a 500 on the whole usage callBaseException, so it still propagatesosv-scan, a non-required job, is red at this tip onbraces3.0.3 (GHSA-vfj7-8cjw-p6xm, a dev dependency inui/litellm-dashboard/package-lock.json) and red the same way on main's own run 37104625295Final Attestation
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_emptynow catches anyException(not onlyPrismaError), 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_timewrites only a 30s short-lived miss via_remember_short_lived_missand skips the two-strike:missed-beforepath that previously escalated repeated failures to a long cache.Test support adds
DroppedConnectionRelaywithTriggerScanner(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.