Repository navigation
fix(proxy-extras): build the SpendLogs indexes in the migration job instead of in migrations - #43948
Conversation
|
I'll fix CI failures and address comments from users with write access. I'll skip comments containing "(aside)".
|
|
|
|
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
0fc3a51 to
d45adc8
Compare
d45adc8 to
8b797b9
Compare
|
bugbot run |
8b797b9 to
d49aee6
Compare
|
bugbot run |
d49aee6 to
f67caac
Compare
|
bugbot run |
dc19f09 to
31b021c
Compare
|
bugbot run |
… the migration job builds indexes The migration job runs DatabaseURLSettings.apply_to_env(), which rewrites DATABASE_SSLMODE=verify-full plus DATABASE_SSLROOTCERT into Prisma's TLS dialect: sslmode=require&sslcert=<CA>&sslaccept=strict. The request-log index build then hands that same URL to psycopg, and libpq reads sslcert as a client certificate, failing with "certificate present, but not private key file" on every verify-full deployment since #43948. _strip_prisma_query_params now undoes the Prisma dialect before psycopg sees the URL. sslaccept=strict (or any value Prisma treats as strict) becomes sslrootcert=<CA> plus sslmode=verify-full whatever sslmode said, since strict verifies chain and hostname and libpq only does that in verify-full; sslmode=disable stays off. Without strict, Prisma verifies nothing, so the CA is dropped and sslmode is kept as is. A URL that also carries sslkey is libpq's own client-certificate form and is left alone. Resolves LIT-9169 Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
… the migration job builds indexes (#44203) The migration job runs DatabaseURLSettings.apply_to_env(), which rewrites DATABASE_SSLMODE=verify-full plus DATABASE_SSLROOTCERT into Prisma's TLS dialect: sslmode=require&sslcert=<CA>&sslaccept=strict. The request-log index build then hands that same URL to psycopg, and libpq reads sslcert as a client certificate, failing with "certificate present, but not private key file" on every verify-full deployment since #43948. _strip_prisma_query_params now undoes the Prisma dialect before psycopg sees the URL. sslaccept=strict (or any value Prisma treats as strict) becomes sslrootcert=<CA> plus sslmode=verify-full whatever sslmode said, since strict verifies chain and hostname and libpq only does that in verify-full; sslmode=disable stays off. Without strict, Prisma verifies nothing, so the CA is dropped and sslmode is kept as is. A URL that also carries sslkey is libpq's own client-certificate form and is left alone. Resolves LIT-9169 Co-authored-by: yassin <yassin@berri.ai> Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…es before cloning Since #43948 a serving proxy builds the two LiteLLM_SpendLogs indexes on a background thread after it reports ready. The seed fixtures stopped the replica at readiness, so every cloned legacy database lacked an index no real deployment would be missing, and the v2 baseline diff refused it. Seeds now wait until both indexes exist and are valid in the database's schema
* test(proxy): stop the proxy_server app fixture leaking LITELLM_LOG The session app fixture set LITELLM_LOG=ERROR with os.environ.setdefault and never removed it, so later tests on the same xdist worker inherited it. test_drop_params_env_var spawns a subprocess with os.environ and lost the warning it asserts on. Scope the variable to the import with a MonkeyPatch context * test(secret-detection): give the hand-built redaction request an ASGI path Since #43975 _read_request_body checks the route path via request.scope, and a scope without path raised KeyError that was swallowed into an empty body, so chat_completion failed with a missing messages parameter. Real ASGI scopes always carry path * test(integration): isolate litellm callback lists per sdk test usage-based-routing-v2 Routers register their selector in litellm.callbacks and nothing removes it, not even Router.reset(). The counter TTL and Redis service metrics tests left their selectors behind, and the next usage routing test ran their pre-call checks against its own rpm=1 deployments, raising "Deployment over defined rpm limit". An autouse fixture now gives each sdk test copies of the callback lists and restores the originals afterwards * test(integration): keep the owner-lookup fault proxy off the shared read replica The owned proxy points DATABASE_URL at a scratch database but inherited DATABASE_URL_READ_REPLICA from the replica job, so auth read the shared database and rejected the freshly created key with token_not_found_in_db. Drop the replica variable like the other scratch-database owned proxies * test(integration): request every seeded key in the team owner breakdown The aggregated team activity endpoint now caps breakdown.api_keys at the top 100 keys by default (#43398), so the 300 seeded keys came back as 100 rows. The test guarantees each key is reported with its own owner, so ask for an api_key_limit that covers all seeded keys * test(integration): give every owned Redis its own port in the redis-cache container On CircleCI every owned Redis ran on the fixed port 16379 inside the shared redis-cache container. When an earlier server still held that port, the new one failed to bind, readiness pinged the old server, the pidfile read failed and cleanup then reported "Owned Redis still serves after shutdown" Reserve an ephemeral port for the docker-exec path the same way the local binary path already does, and refuse to start when something already serves the chosen port so the failure names the real cause * test(e2e): skip the Vertex Mistral partner case the e2e project cannot reach The e2e Vertex project gets a 404 publisher model not found for vertex_ai/mistral-small-2503, so the case can only fail * test(e2e): skip the Vertex gpt-oss partner case the e2e project never serves vertex_ai/openai/gpt-oss-120b-maas has hit a 60s read timeout with no response headers on every run in the e2e Vertex project since the case was ported, and no other Vertex partner chat model passes there to switch to * test(e2e): check only stored message content for a leaked card number The Presidio spend-log check ran the card-number pattern over the whole serialized response, so a Luhn-valid usage.cost float (0.0003466000000000001) failed the streaming /v1/messages case although the stored content was <CREDIT_CARD>. The check now reads the content and text strings of the stored response, which is where a raw card would land, and still requires the placeholder there * test(e2e): assert the proxy decodes token-array embeddings for titan The port in #44120 carried over a legacy SDK-direct test that expected Bedrock to reject token ids with a 400. Through the proxy, /embeddings decodes token arrays to text for providers that cannot embed tokens, so titan answers 200. The test now sends a token array and its decoded sentence and requires the two vectors to match, which fails if the proxy stops decoding or decodes with the wrong tokenizer * test(e2e): run the Bedrock extended-thinking round trip on a model that honors enabled thinking us.anthropic.claude-sonnet-5-5 is adaptive-only, so litellm sends thinking.type=enabled with a 1024 budget as adaptive with low effort, and Bedrock returned no reasoning blocks on 5 of 5 identical Converse calls (boto3 direct agreed). us.anthropic.claude-sonnet-4-6 accepts the legacy shape verbatim and returned reasoning on 5 of 5. The non-thinking Bedrock case stays on sonnet-5-5 * test(proxy): stop unit modules forcing DEBUG logging into the event-loop lag tests Five tests/unit modules set verbose_proxy_logger to DEBUG at import, so every xdist worker that collected them logged the 2.4MB pass-through response from a worker thread, and secret redaction of that line held the GIL for ~0.8s+ inside the timed window. The lag tests now pin the LiteLLM loggers to WARNING and freeze gc while timing, and the module-level DEBUG overrides are removed * test(e2e): cite the tokenizer and date behind the titan token-array fixture * test(e2e): let migration seed replicas finish their request-log indexes before cloning Since #43948 a serving proxy builds the two LiteLLM_SpendLogs indexes on a background thread after it reports ready. The seed fixtures stopped the replica at readiness, so every cloned legacy database lacked an index no real deployment would be missing, and the v2 baseline diff refused it. Seeds now wait until both indexes exist and are valid in the database's schema * test(passthrough): give the pass-through MockRequest an httpx URL and ASGI scope #43626 made get_request_route read request.scope during pass-through kwarg setup; the MockRequest in tests/unit/passthrough had neither a scope nor a URL object, so both stream-param tests raised before reaching the code they check. Mirrors the repair #43626 made to the tests/pass_through_unit_tests fake * test(integration): ignore foreign allow_all_keys MCP servers in the access matrix tool list test_toolset_gateway_url_serves_a_team_granted_toolset_to_a_key_without_its_own_grant (#43908) registers an allow_all_keys server on the shared gateway, and allow_all_keys servers are listed to every key by design, so a matrix case running on another xdist worker at the same time saw its tools. The matrix now drops tools of allow_all_keys servers it did not create, read from LiteLLM_MCPServerTable before and after listing, and still compares everything else exactly
…) (#44254) * test(proxy): stop the proxy_server app fixture leaking LITELLM_LOG The session app fixture set LITELLM_LOG=ERROR with os.environ.setdefault and never removed it, so later tests on the same xdist worker inherited it. test_drop_params_env_var spawns a subprocess with os.environ and lost the warning it asserts on. Scope the variable to the import with a MonkeyPatch context * test(secret-detection): give the hand-built redaction request an ASGI path Since #43975 _read_request_body checks the route path via request.scope, and a scope without path raised KeyError that was swallowed into an empty body, so chat_completion failed with a missing messages parameter. Real ASGI scopes always carry path * test(integration): isolate litellm callback lists per sdk test usage-based-routing-v2 Routers register their selector in litellm.callbacks and nothing removes it, not even Router.reset(). The counter TTL and Redis service metrics tests left their selectors behind, and the next usage routing test ran their pre-call checks against its own rpm=1 deployments, raising "Deployment over defined rpm limit". An autouse fixture now gives each sdk test copies of the callback lists and restores the originals afterwards * test(integration): keep the owner-lookup fault proxy off the shared read replica The owned proxy points DATABASE_URL at a scratch database but inherited DATABASE_URL_READ_REPLICA from the replica job, so auth read the shared database and rejected the freshly created key with token_not_found_in_db. Drop the replica variable like the other scratch-database owned proxies * test(integration): request every seeded key in the team owner breakdown The aggregated team activity endpoint now caps breakdown.api_keys at the top 100 keys by default (#43398), so the 300 seeded keys came back as 100 rows. The test guarantees each key is reported with its own owner, so ask for an api_key_limit that covers all seeded keys * test(integration): give every owned Redis its own port in the redis-cache container On CircleCI every owned Redis ran on the fixed port 16379 inside the shared redis-cache container. When an earlier server still held that port, the new one failed to bind, readiness pinged the old server, the pidfile read failed and cleanup then reported "Owned Redis still serves after shutdown" Reserve an ephemeral port for the docker-exec path the same way the local binary path already does, and refuse to start when something already serves the chosen port so the failure names the real cause * test(e2e): skip the Vertex Mistral partner case the e2e project cannot reach The e2e Vertex project gets a 404 publisher model not found for vertex_ai/mistral-small-2503, so the case can only fail * test(e2e): skip the Vertex gpt-oss partner case the e2e project never serves vertex_ai/openai/gpt-oss-120b-maas has hit a 60s read timeout with no response headers on every run in the e2e Vertex project since the case was ported, and no other Vertex partner chat model passes there to switch to * test(e2e): check only stored message content for a leaked card number The Presidio spend-log check ran the card-number pattern over the whole serialized response, so a Luhn-valid usage.cost float (0.0003466000000000001) failed the streaming /v1/messages case although the stored content was <CREDIT_CARD>. The check now reads the content and text strings of the stored response, which is where a raw card would land, and still requires the placeholder there * test(e2e): assert the proxy decodes token-array embeddings for titan The port in #44120 carried over a legacy SDK-direct test that expected Bedrock to reject token ids with a 400. Through the proxy, /embeddings decodes token arrays to text for providers that cannot embed tokens, so titan answers 200. The test now sends a token array and its decoded sentence and requires the two vectors to match, which fails if the proxy stops decoding or decodes with the wrong tokenizer * test(e2e): run the Bedrock extended-thinking round trip on a model that honors enabled thinking us.anthropic.claude-sonnet-5-5 is adaptive-only, so litellm sends thinking.type=enabled with a 1024 budget as adaptive with low effort, and Bedrock returned no reasoning blocks on 5 of 5 identical Converse calls (boto3 direct agreed). us.anthropic.claude-sonnet-4-6 accepts the legacy shape verbatim and returned reasoning on 5 of 5. The non-thinking Bedrock case stays on sonnet-5-5 * test(proxy): stop unit modules forcing DEBUG logging into the event-loop lag tests Five tests/unit modules set verbose_proxy_logger to DEBUG at import, so every xdist worker that collected them logged the 2.4MB pass-through response from a worker thread, and secret redaction of that line held the GIL for ~0.8s+ inside the timed window. The lag tests now pin the LiteLLM loggers to WARNING and freeze gc while timing, and the module-level DEBUG overrides are removed * test(e2e): cite the tokenizer and date behind the titan token-array fixture * test(e2e): let migration seed replicas finish their request-log indexes before cloning Since #43948 a serving proxy builds the two LiteLLM_SpendLogs indexes on a background thread after it reports ready. The seed fixtures stopped the replica at readiness, so every cloned legacy database lacked an index no real deployment would be missing, and the v2 baseline diff refused it. Seeds now wait until both indexes exist and are valid in the database's schema * test(passthrough): give the pass-through MockRequest an httpx URL and ASGI scope #43626 made get_request_route read request.scope during pass-through kwarg setup; the MockRequest in tests/unit/passthrough had neither a scope nor a URL object, so both stream-param tests raised before reaching the code they check. Mirrors the repair #43626 made to the tests/pass_through_unit_tests fake * test(integration): ignore foreign allow_all_keys MCP servers in the access matrix tool list test_toolset_gateway_url_serves_a_team_granted_toolset_to_a_key_without_its_own_grant (#43908) registers an allow_all_keys server on the shared gateway, and allow_all_keys servers are listed to every key by design, so a matrix case running on another xdist worker at the same time saw its tools. The matrix now drops tools of allow_all_keys servers it did not create, read from LiteLLM_MCPServerTable before and after listing, and still compares everything else exactly (cherry picked from commit 9b5562f)
) * test: repair stale and polluting tests red on scheduled main CI (#44229) Partial backport to rc/1.104.0: only the owned Redis port, Presidio stored-content check and event-loop lag logging fixes apply here. The other repairs target tests or behavior this line does not have * test(proxy): stop the proxy_server app fixture leaking LITELLM_LOG The session app fixture set LITELLM_LOG=ERROR with os.environ.setdefault and never removed it, so later tests on the same xdist worker inherited it. test_drop_params_env_var spawns a subprocess with os.environ and lost the warning it asserts on. Scope the variable to the import with a MonkeyPatch context * test(secret-detection): give the hand-built redaction request an ASGI path Since #43975 _read_request_body checks the route path via request.scope, and a scope without path raised KeyError that was swallowed into an empty body, so chat_completion failed with a missing messages parameter. Real ASGI scopes always carry path * test(integration): isolate litellm callback lists per sdk test usage-based-routing-v2 Routers register their selector in litellm.callbacks and nothing removes it, not even Router.reset(). The counter TTL and Redis service metrics tests left their selectors behind, and the next usage routing test ran their pre-call checks against its own rpm=1 deployments, raising "Deployment over defined rpm limit". An autouse fixture now gives each sdk test copies of the callback lists and restores the originals afterwards * test(integration): keep the owner-lookup fault proxy off the shared read replica The owned proxy points DATABASE_URL at a scratch database but inherited DATABASE_URL_READ_REPLICA from the replica job, so auth read the shared database and rejected the freshly created key with token_not_found_in_db. Drop the replica variable like the other scratch-database owned proxies * test(integration): request every seeded key in the team owner breakdown The aggregated team activity endpoint now caps breakdown.api_keys at the top 100 keys by default (#43398), so the 300 seeded keys came back as 100 rows. The test guarantees each key is reported with its own owner, so ask for an api_key_limit that covers all seeded keys * test(integration): give every owned Redis its own port in the redis-cache container On CircleCI every owned Redis ran on the fixed port 16379 inside the shared redis-cache container. When an earlier server still held that port, the new one failed to bind, readiness pinged the old server, the pidfile read failed and cleanup then reported "Owned Redis still serves after shutdown" Reserve an ephemeral port for the docker-exec path the same way the local binary path already does, and refuse to start when something already serves the chosen port so the failure names the real cause * test(e2e): skip the Vertex Mistral partner case the e2e project cannot reach The e2e Vertex project gets a 404 publisher model not found for vertex_ai/mistral-small-2503, so the case can only fail * test(e2e): skip the Vertex gpt-oss partner case the e2e project never serves vertex_ai/openai/gpt-oss-120b-maas has hit a 60s read timeout with no response headers on every run in the e2e Vertex project since the case was ported, and no other Vertex partner chat model passes there to switch to * test(e2e): check only stored message content for a leaked card number The Presidio spend-log check ran the card-number pattern over the whole serialized response, so a Luhn-valid usage.cost float (0.0003466000000000001) failed the streaming /v1/messages case although the stored content was <CREDIT_CARD>. The check now reads the content and text strings of the stored response, which is where a raw card would land, and still requires the placeholder there * test(e2e): assert the proxy decodes token-array embeddings for titan The port in #44120 carried over a legacy SDK-direct test that expected Bedrock to reject token ids with a 400. Through the proxy, /embeddings decodes token arrays to text for providers that cannot embed tokens, so titan answers 200. The test now sends a token array and its decoded sentence and requires the two vectors to match, which fails if the proxy stops decoding or decodes with the wrong tokenizer * test(e2e): run the Bedrock extended-thinking round trip on a model that honors enabled thinking us.anthropic.claude-sonnet-5-5 is adaptive-only, so litellm sends thinking.type=enabled with a 1024 budget as adaptive with low effort, and Bedrock returned no reasoning blocks on 5 of 5 identical Converse calls (boto3 direct agreed). us.anthropic.claude-sonnet-4-6 accepts the legacy shape verbatim and returned reasoning on 5 of 5. The non-thinking Bedrock case stays on sonnet-5-5 * test(proxy): stop unit modules forcing DEBUG logging into the event-loop lag tests Five tests/unit modules set verbose_proxy_logger to DEBUG at import, so every xdist worker that collected them logged the 2.4MB pass-through response from a worker thread, and secret redaction of that line held the GIL for ~0.8s+ inside the timed window. The lag tests now pin the LiteLLM loggers to WARNING and freeze gc while timing, and the module-level DEBUG overrides are removed * test(e2e): cite the tokenizer and date behind the titan token-array fixture * test(e2e): let migration seed replicas finish their request-log indexes before cloning Since #43948 a serving proxy builds the two LiteLLM_SpendLogs indexes on a background thread after it reports ready. The seed fixtures stopped the replica at readiness, so every cloned legacy database lacked an index no real deployment would be missing, and the v2 baseline diff refused it. Seeds now wait until both indexes exist and are valid in the database's schema * test(passthrough): give the pass-through MockRequest an httpx URL and ASGI scope * test(integration): ignore foreign allow_all_keys MCP servers in the access matrix tool list test_toolset_gateway_url_serves_a_team_granted_toolset_to_a_key_without_its_own_grant (#43908) registers an allow_all_keys server on the shared gateway, and allow_all_keys servers are listed to every key by design, so a matrix case running on another xdist worker at the same time saw its tools. The matrix now drops tools of allow_all_keys servers it did not create, read from LiteLLM_MCPServerTable before and after listing, and still compares everything else exactly (cherry picked from commit 9b5562f) * fix(proxy-extras): retry P3009 when a peer already recovered the named migration row (#44283) * fix(proxy-extras): retry P3009 when a peer already recovered the named migration row * fix(proxy-extras): pin P3009 recovery locals as Final and cover a recovered sibling row * test(proxy-extras): stop the P3009 ledger fakes shadowing the partition detector cursor * fix(proxy-extras): annotate the migration ledger reader locals as Final --------- Co-authored-by: yuneng <yuneng@berri.ai> (cherry picked from commit 8b11b68) --------- Co-authored-by: devin-ai-integration[bot] <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…nstead of in migrations (BerriAI#43948) The two SpendLogs index migrations shipped in v1.103.0 each break one table shape: the plain CREATE INDEX holds a SHARE lock on a large unpartitioned table and the CONCURRENTLY one fails with 0A000 on a partitioned parent. Both files are now inert and the indexes are built by a table-driven, shape-aware step after migrate deploy: CONCURRENTLY on a plain table, ON ONLY the parent plus per-partition CONCURRENTLY and ATTACH PARTITION on a partitioned one. The migration job builds them synchronously and exits non-zero on failure; a serving proxy that ran migrate deploy itself builds them in the background off the readiness path. A valid index of the same definition under another name is renamed and reused, an invalid one is rebuilt, and extra copies are reported with their DROP INDEX statement instead of being dropped. The migration checker rejects any CREATE INDEX on LiteLLM_SpendLogs or LiteLLM_ErrorLogs in future migrations Co-authored-by: yassin <yassin@berri.ai> Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> (cherry picked from commit c66c828)
… the hand-built SpendLogs indexes schema.prisma still declares the LiteLLM_SpendLogs (api_key, startTime) and (litellm_call_id) indexes while their migrations are now SELECT 1, so the v1 resolver's drift script recreated both with a blocking CREATE INDEX at boot. The drift script now drops those two statements before it is applied, matching filter_request_log_index_diff on main. The schema sync test exempts the two indexes Ported to rc/1.104.0 from stable/1.103.x (BerriAI#44286), which is not on main: main carries filter_request_log_index_diff from BerriAI#43948 instead, and its backport here was reverted in BerriAI#44212. The key metadata recovery hunk is dropped because this line's test file has no Postgres-backed index fixture (cherry picked from commit 4d245e1)
…nstead of in migrations (BerriAI#43948) The two SpendLogs index migrations shipped in v1.103.0 each break one table shape: the plain CREATE INDEX holds a SHARE lock on a large unpartitioned table and the CONCURRENTLY one fails with 0A000 on a partitioned parent. Both files are now inert and the indexes are built by a table-driven, shape-aware step after migrate deploy: CONCURRENTLY on a plain table, ON ONLY the parent plus per-partition CONCURRENTLY and ATTACH PARTITION on a partitioned one. The migration job builds them synchronously and exits non-zero on failure; a serving proxy that ran migrate deploy itself builds them in the background off the readiness path. A valid index of the same definition under another name is renamed and reused, an invalid one is rebuilt, and extra copies are reported with their DROP INDEX statement instead of being dropped. The migration checker rejects any CREATE INDEX on LiteLLM_SpendLogs or LiteLLM_ErrorLogs in future migrations Co-authored-by: yassin <yassin@berri.ai> Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> (cherry picked from commit c66c828)
… the migration job builds indexes (BerriAI#44203) The migration job runs DatabaseURLSettings.apply_to_env(), which rewrites DATABASE_SSLMODE=verify-full plus DATABASE_SSLROOTCERT into Prisma's TLS dialect: sslmode=require&sslcert=<CA>&sslaccept=strict. The request-log index build then hands that same URL to psycopg, and libpq reads sslcert as a client certificate, failing with "certificate present, but not private key file" on every verify-full deployment since BerriAI#43948. _strip_prisma_query_params now undoes the Prisma dialect before psycopg sees the URL. sslaccept=strict (or any value Prisma treats as strict) becomes sslrootcert=<CA> plus sslmode=verify-full whatever sslmode said, since strict verifies chain and hostname and libpq only does that in verify-full; sslmode=disable stays off. Without strict, Prisma verifies nothing, so the CA is dropped and sslmode is kept as is. A URL that also carries sslkey is libpq's own client-certificate form and is left alone. Resolves LIT-9169 Co-authored-by: yassin <yassin@berri.ai> Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> (cherry picked from commit 4758fce)
TLDR
Problem this solves:
CREATE INDEXblocks spend-log writes for the whole build on big tablesCREATE INDEX CONCURRENTLYfails on a partitioned parent, P3018, then P3009 foreverHow it solves it:
SELECT 1;migrate deploy, synchronously, and exits non-zero when one is missingmigrate deployitself (DISABLE_SCHEMA_UPDATEunset) starts the same build on a background thread right after its deploy, so readiness never waits on itCREATE INDEX CONCURRENTLY IF NOT EXISTS, writes keep flowingON ONLY, each partitionCONCURRENTLY, thenATTACH PARTITIONDROP INDEXfor the operator, never droppedOne-sentence RCA: the two shipped SpendLogs index migrations each assume one table shape, a plain
CREATE INDEXholds a SHARE lock across a large unpartitioned table whileCREATE INDEX CONCURRENTLYis refused outright by Postgres on a partitioned parent (SQLSTATE 0A000), and a migration file has no way to pick the online build sequence the table actually needsUser Flow
Before: an admin upgrading a proxy whose spend logs are partitioned never gets a healthy pod
Error: P3018 ... cannot create index on partitioned table "LiteLLM_SpendLogs" concurrentlyGET https://litellm-domain/health/readinessnever returns 200, the pod restarts, and every later start printsP3009 migrate found failed migrationsAfter: the same rollout applies two no-op migrations, the migration job builds the indexes online, and the pods come up
litellm --skip_server_startup) runs first, as todayBuilding index LiteLLM_SpendLogs_p2026_07_litellm_call_id_idx on LiteLLM_SpendLogs_p2026_07 concurrentlyandAttached index ... to LiteLLM_SpendLogs_litellm_call_id_idxper partition (oneBuilding index ... concurrentlyline per index on a plain table), thenRequest-log indexes are all in placeandMigration job completed successfully., while spend logs keep being written the whole timeGET https://litellm-domain/health/readinesson the new pods returns 200{"status":"healthy","db":"connected"}as soon as theirmigrate deployfinishes, which now never fails on these two files; the pods' background build then finds the indexes in place and prints onlyRequest-log indexes are all in placemigrate deployitself, gets the same indexes: the pod answers readiness 200 while its log prints theBuilding index ... concurrentlyandAttached indexlines, andRequest-log indexes are all in placefollows a few seconds laterRelevant issues
Fixes #41548
Affected release
Regression since v1.103.0 (both migrations shipped in that release)
Linear ticket
Resolves LIT-9091
Also covers LIT-9062
Files changed
litellm-proxy-extras/.../20260823000000_add_spend_logs_api_key_starttime_index/migration.sqlSELECT 1;. Databases that already applied the original file keep their row and checksum untouched (proven below), databases that have not applied it run a no-oplitellm-proxy-extras/.../20260831120001_spend_logs_litellm_call_id_index/migration.sqlCREATE INDEX CONCURRENTLYthat Postgres refuses on a partitioned parent is gone, replaced by a comment andSELECT 1;litellm-proxy-extras/litellm_proxy_extras/request_log_indexes.pylitellm.proxyimports).REQUEST_LOG_INDEXESis the single table-driven list of indexes the migration job owns, named exactly as Prisma derives them from@@index.ensure_request_log_indexesbuilds each missing or invalid one:CREATE INDEX CONCURRENTLY IF NOT EXISTSon a plain table; on a partitioned parentCREATE INDEX IF NOT EXISTS ... ON ONLY parentunder a 2slock_timeoutwith retries, thenCREATE INDEX CONCURRENTLY IF NOT EXISTSper partition with a deterministic child name within 63 bytes, thenALTER INDEX ... ATTACH PARTITION, recursing into partitioned children; attaching a child another job already attached is a no-op in Postgres. A valid index of the Prisma name is reused, an invalid one is dropped and rebuilt, a same-name index on another table is left alone and logged. A valid index of the same definition (default btree over the same columns in order, no expression, predicate,DESC, opclass or collation) under another name, on the parent or a partition, is renamed to the expected name withALTER INDEX ... RENAMEinstead of being built again; every remaining index of the same definition is logged as a second copy with theDROP INDEX CONCURRENTLY(plainDROP INDEXfor a partitioned parent) that removes it, and left in place. Each statement runs under the existing migration lock, held per statement so a resolver on another replica gets in between partitions, and the catalog state that decides between reuse, rebuild and leave-alone is read under that lock. The connection factory is injectable so the real-Postgres tests can interleave a second process deterministically. Never raises: it returns False and the next job run retries.filter_request_log_index_diffdrops exactly these indexes from the migrations-vs-schema drift difflitellm-proxy-extras/litellm_proxy_extras/utils.pysetup_databaseonly migrates (both resolvers), repairs invalid indexes and returns, so a serving proxy's readiness never waits on an index build. Newbuild_request_log_indexesresolves the writer URL and schema and runs the builder synchronously; newrun_migration_jobissetup_databasethenbuild_request_log_indexes, False when either fails so the Job exits non-zero and is rerun; newstart_request_log_index_buildruns the same builder on a daemon thread for a serving proxy that ran the migrations itself, so readiness never waits on it and a build that did not finish is retried on the next boot.check_schema_syncappliesfilter_request_log_index_diffso the drift check tolerates the two job-owned indexes and nothing else.repair_invalid_indexestakes the migration lock too, one hold per index like the builder, so it never rebuilds an index a job is still building concurrentlylitellm-proxy-extras/litellm_proxy_extras/migration_lock.pyheld_migration_lock: a session-level, non-blocking hold of the sameMIGRATION_LOCK_KEYthe v2 resolver takes per transaction, for DDL that cannot run inside a transaction (CREATE INDEX CONCURRENTLY)litellm-proxy-extras/litellm_proxy_extras/migration_recovery.pyis_inert_migration(comments plusSELECT 1only) androll_back_failed_inert_migration: when the v2 resolver finds a failed_prisma_migrationsrow for a migration whose file in this build is inert, it marks that row rolled back somigrate deployapplies the inert file. Only applies to inert files, so no database change can be repeated or skipped. The legacy resolver already rolls back failed rows and retries, so it needs no change. This only matters for a database an earlier v1.103+ build already left stuck; a first-time upgrade on this build never runs the old SQLmigrations/run.pyrun_migration_job, so it migrates, then builds the indexes, and exits 1 when either step failslitellm/proxy/db/prisma_client.py,litellm/proxy/proxy_cli.pyPrismaManager.build_request_log_indexes(wait for the build) andstart_request_log_index_build(daemon thread) forward to proxy-extras. After a successfulsetup_databasethe CLI waits for the build on--skip_server_startup, exiting 1 when an index could not be built, and starts it in the background when it goes on to serve, so a proxy that runs the migrations itself (DISABLE_SCHEMA_UPDATEunset) also gets the indexestests/code_coverage_tests/check_migrations_no_data_rewrites.pyCREATE INDEX, concurrent or not, onLiteLLM_SpendLogsorLiteLLM_ErrorLogsinside a migration now fails CI (schema-qualified, lower-case,ONLY, comment-separated andEXECUTEforms included) with a message pointing atREQUEST_LOG_INDEXESand the migration job. A-- data-migration-okmarker does not exempt such an index, unlike the bounded rewrites the marker exists for. Only the two shipped file names are grandfathered, and only while inertPre-Submission checklist
uv run pytest tests/unit/<your_test_file>.py -vScreenshots / Proof of Fix
Shared setup: PostgreSQL 14.24 on localhost with Prisma 5.4.2, one fresh database per case. The migration job is
USE_V2_MIGRATION_RESOLVER=true python migrations/run.py(v2) orUSE_V2_MIGRATION_RESOLVER=false(legacy) withDATABASE_URLpointing at that database, exactly as the migrations image runs it. The serving proxy ispython -m litellm.proxy.proxy_cli --config config.yaml --port 41xx --enforce_prisma_migration_checkwith--use_v2_migration_resolveror--use_legacy_migration_resolver, readiness polled withcurl http://127.0.0.1:41xx/health/readiness. The config has oneopenai/fakemodel behind an unreachableapi_baseandmaster_key: sk-proof, so no provider is called; the bug is in the migration step before the proxy serves anything. Cases b and c run a second session doing oneINSERT INTO "LiteLLM_SpendLogs"every 50 ms while the job runs and samplepg_stat_activity(inserts withwait_event_type = 'Lock'),pg_stat_progress_create_indexandpg_locksevery 100 ms. The v1.102.1 schema databases come fromprisma migrate deploywith the migrations shipped up to that release; the partitioned one then randb_scripts/partition_spend_logs.sqland got three monthly partitions of 1,000,000 rows plus 300,000 rows in the default partition, the unpartitioned one got 3,000,000 rows. Every After case ran once per resolver; numbers quoted are the v2 run unless marked legacy. Harness:python3 proof/proof3.pyandpython3 proof/proof4.py, per-case JSON inproof/out3/andproof/out4/Before (c168199)
Captured on
mainat that commit; both migration files are byte-identical at the current merge base, so the Before legs still describe itCase a: fresh database
curl http://127.0.0.1:4101/health/readiness200 {"status":"healthy","db":"connected"}after 16.6 s, both SpendLogs indexes valid (a fresh table is small and unpartitioned, so the old files work here)Case b: unpartitioned v1.102.1 database with 3,000,000 spend logs and a concurrent insert loop
pg_stat_activityshowsCREATE INDEX IF NOT EXISTS "LiteLLM_SpendLogs_api_key_startTime_idx" ...(no CONCURRENTLY) holding aShareLockon"LiteLLM_SpendLogs"wait_event_type = 'Lock', slowest insert 1859.8 ms, 1 insert over one secondCase c: partitioned v1.102.1 database with three populated partitions plus default, concurrent insert loop
Migration name: 20260831120001_spend_logs_litellm_call_id_index/Database error code: 0A000/ERROR: cannot create index on partitioned table "LiteLLM_SpendLogs" concurrently/Error: P3018curl .../health/readinessnever answersLiteLLM_SpendLogs_litellm_call_id_idxdoes not exist, the20260831120001ledger row hasfinished_at IS NULLCase d: partitioned database whose ledger already holds the failed P3018 row for the call_id migration
Error: P3009 migrate found failed migrations in the target database, process exits with code 2 after 16.5 s, readiness never answersSELECT finished_at IS NOT NULL, rolled_back_at IS NOT NULL, left(checksum, 12) FROM _prisma_migrations WHERE migration_name LIKE '20260831120001%'returns one row(false, false, ff5de5c63466), unchangedCase e: database that already applied the shipped migration files
prisma migrate deploywith the shipped files frommainon a plain v1.102.1 database: both index migrations apply (the blockingCREATE INDEXand theCREATE INDEX CONCURRENTLY), both ledger rows finished with the shipped checksumsCase f: serving proxy rolled out without the migration job, on the partitioned database
migrate deploy, hits P3018 on the partitioned parent, exits with code 2, readiness never answersAfter (065c059)
Case a: fresh database
Building index LiteLLM_SpendLogs_api_key_startTime_idx on LiteLLM_SpendLogs concurrently, the same forLiteLLM_SpendLogs_litellm_call_id_idx, thenRequest-log indexes are all in placeandMigration job completed successfully., exit 0 after 18.4 s (26.5 s legacy)SELECT indisvalid FROM pg_index WHERE indexrelid = '"LiteLLM_SpendLogs_api_key_startTime_idx"'::regclassreturnstruefor both indexes; both ledger rows carry the checksums of the inert filescurl http://127.0.0.1:41xx/health/readiness:200 {"status":"healthy","db":"connected"}after 40.8 s (16.5 s legacy), the proxy's background build then prints onlyRequest-log indexes are all in place, noBuilding indexline, index OIDs unchanged by the bootCase b: unpartitioned v1.102.1 database with 3,000,000 spend logs and a concurrent insert loop
pg_stat_activityshows onlyCREATE INDEX CONCURRENTLY IF NOT EXISTS ...statements,pg_locksshows them holdingShareUpdateExclusiveLock, neverShareLockprisma migrate deployafterwards printsNo pending migrations to apply.andprisma migrate statusprintsDatabase schema is up to date!Request-log indexes are all in place, index OIDs unchangedCase c: partitioned v1.102.1 database with three populated partitions plus default, concurrent insert loop
pg_stat_activityshowsCREATE INDEX CONCURRENTLY IF NOT EXISTS "LiteLLM_SpendLogs_p2026_07_litellm_call_id_idx" ON "public"."LiteLLM_SpendLogs_p2026_07" ...and the same forp2026_08andp2026_09(the 300,000-rowpdefaultbuild finished between two samples); the log printsBuilding index ... concurrentlyfor all 4 partitions andAttached index LiteLLM_SpendLogs_p2026_07_litellm_call_id_idx on partition LiteLLM_SpendLogs_p2026_07 to LiteLLM_SpendLogs_litellm_call_id_idxonce per partition. No builder lock on the parent inpg_locksSELECT indisvalid FROM pg_index WHERE indexrelid = '"LiteLLM_SpendLogs_litellm_call_id_idx"'::regclassreturnstruefor both parents; thepg_inheritsjoin onpg_indexlists all 4 partitions attached under each parent indexCREATE TABLE "LiteLLM_SpendLogs_p2026_10" PARTITION OF "LiteLLM_SpendLogs" FOR VALUES FROM ('2026-10-01') TO ('2026-11-01'): the new partition shows up attached under both parent indexes with no further actionBuilding indexline, catalog and index OIDs unchanged.prisma migrate deployprintsNo pending migrations to apply.,prisma migrate statusprintsDatabase schema is up to date!Request-log indexes are all in place, index OIDs unchangedCase d: partitioned database whose ledger already holds the failed P3018 row for the call_id migration
Rolled back the failed history row of 20260831120001_spend_logs_litellm_call_id_index: this build ships it as an inert migration, its index is built by the migration job. Legacy log: its existingFound failed migration: 20260831120001_spend_logs_litellm_call_id_index, marking as rolled back(plus its usual P3009 line from the deploy attempt it makes before rolling the row back). Exit 0 on both (24.5 s v2, 31.0 s legacy)SELECT finished_at IS NOT NULL, rolled_back_at IS NOT NULL, left(checksum, 12) FROM _prisma_migrations WHERE migration_name LIKE '20260831120001%'returns the original row as(false, true, ff5de5c63466)and a new row(true, false, 7166fd213126), the checksum of the inert file. The20260823000000row keeps its original checksumprisma migrate deployprintsNo pending migrations to apply.,prisma migrate statusprintsDatabase schema is up to date!. So the exact outcome is: the job clears the stuck row itself, noresolve --rolled-backby the operatorRequest-log indexes are all in placeCase e: database that already applied the shipped migration files
Building indexline, onlyRequest-log indexes are all in placeprisma migrate deployfrom this branch printsNo pending migrations to apply.,prisma migrate statusprintsDatabase schema is up to date!ledger_checksums_unchanged: true) and the index OIDs are unchanged (index_oids_unchanged: true), so Prisma did not re-check applied rows and the job reused the existing valid indexesRequest-log indexes are all in placeCase f: serving proxy rolled out without the migration job, on the partitioned database
Building index LiteLLM_SpendLogs_p2026_07_litellm_call_id_idx on LiteLLM_SpendLogs_p2026_07 concurrently, the background build running while it servesON ONLYparentLiteLLM_SpendLogs_litellm_call_id_idx(invalid, nothing attached yet) and the finishedp2026_07child, while the api_key index is exactly what the partition script createdAttached index LiteLLM_SpendLogs_p2026_07_litellm_call_id_idx ...with noBuilding indexline for it), builds and attaches the other three, exit 0 after 19.2 s (20.1 s legacy), both parent indexes valid with all 4 partitions attached. A proxy left running instead finishes the same build itself (integration testtests/integration/database/test_request_log_indexes_at_boot.py)Tests and mutation run
tests/unit/litellm_proxy_extras/test_request_log_indexes.py: index naming within 63 bytes, the column list read from the definition, drift filtering keeps unrelated drift, the inert-migration detector, the Prisma-name invariant againstschema.prismatests/unit/litellm_proxy_extras/test_litellm_proxy_extras_utils.py:build_request_log_indexesforwards the writer URL and schema, falls back toDATABASE_URL, is a no-op without one, returns the builder's False;run_migration_jobbuilds only after a successful setup and returns False when either step fails;start_request_log_index_buildreturns before the build runs and runs it on a daemon threadtests/unit/proxy/test_proxy_cli.py:--skip_server_startupwaits for the build once after setup and exits 1 when it fails, a serving proxy starts the background build once after a successful setup and never after a failed onetests/unit/proxy/db/test_prisma_client.py: without proxy-extras installed the waited build reports False and the background start returns, neither raisestests/proxy_migration_tests/test_request_log_indexes.py(real Postgres, both resolvers): plain, partitioned and nested-partitioned builds throughrun_migration_job, invalid-index rebuild, same-name collision left alone, idempotent reruns with stable OIDs, lock handover, a second process making the index valid right before the lock is taken (kept, not rebuilt), a second process attaching the same child first, a valid index of the same definition under another name renamed and kept (same OID) on a plain table, on a partition then attached, and on a partitioned parent with its children staying attached and nothing built, indexes of another definition (DESC, the columns in the other order, an extra column,text_pattern_ops) left alone while the managed one is built, a second copy logged with itsDROP INDEX CONCURRENTLYstatement and left in place, a job that could not build the indexes reporting failure and succeeding when rerun, andsetup_databasealone applying the inert files while leaving the indexes exactly as they weretests/proxy_migration_tests/test_invalid_index_repair.py(real Postgres): the invalid index repair yields while another process holds the migration lock and finishes on the next run, and releases the lock between two rebuilds so a resolver queued for it gets intests/proxy_migration_tests/test_db_schema_migration.py: the drift check filters exactly the job-owned indexes and still fails on any other drifttests/integration/database/test_request_log_indexes_at_boot.py(live proxy and the realmigrations/run.py, both resolvers): the job on a partitioned pre-index schema, the job healing the stuck failed ledger row, the job on already-applied original files, the serving proxy on each of those databases answering readiness and then finding the indexes in place without building, a serving proxy alone on the partitioned pre-index schema answering readiness and then building both indexes per partition in the background and the CLI--skip_server_startuppath building both before it exitstests/unit/test_check_migrations_no_data_rewrites.py: every index form the checker must reject on the two tables, including under adata-migration-okmarkerSELECT 1no longer counted as inert, invalid index kept instead of rebuilt, same-name index on another table treated as ours, drift filter keeping the job-ownedCREATE INDEXlines, checker lettingCREATE INDEX CONCURRENTLYthrough, migration lock ignored, parent built withoutON ONLY, catalog state read before the lock instead of under it, checker accepting a schema-qualified table, checker letting a marker exempt an index, repair skipping the migration lock, repair holding the migration lock across every rebuild,run_migration_jobignoring the build result,build_request_log_indexesdropping the builder's result,run_migration_jobnever building, the CLI building for a serving proxy too, the CLI exiting 0 when an index could not be built,setup_databasebuilding the indexes in the serving proxy, the equivalent index never renamed, the column order ignored when matching an equivalent index,DESCignored, a non-default opclass ignored, second copies never reported, the leaf adoption dropped, the parent adoption droppedThe integration repro was written first and shown red on
mainat c168199:ERROR: cannot create index on partitioned table "LiteLLM_SpendLogs" concurrently, P3018, readiness never answeredType
🐛 Bug Fix
Caveats (if any)
Severe
migrate deployitself builds these indexes in the background while it servesDISABLE_SCHEMA_UPDATEunset) and they succeeded; a proxy with schema updates disabled never buildsCREATE INDEX CONCURRENTLYon a serving pod, with writes flowing the whole time; a pod killed mid-build leaves an invalid index the next build drops and rebuildslitellm --skip_server_startup) insteadMedium
lock_timeoutwith 30 retries, then left for the next job run--skip_server_startupwait for the build before exiting and exit non-zero when an index is not in placeLow
REQUEST_LOG_INDEXES, not in a migrationALTER INDEX ... RENAMEtakesSHARE UPDATE EXCLUSIVEon the index, writes keep flowing), so an operator's hand-built workaround index is adopted rather than duplicated. Any other index of the same definition is logged as a second copy with itsDROP INDEXstatement and never dropped by this codeREINDEX, not all of themFinal Attestation
Link to Devin session: https://app.devin.ai/sessions/72b61b21adc1405c9529942972bd58f6
Open in Devin Desktop: https://app.devin.ai/desktop/session/72b61b21adc1405c9529942972bd58f6?variant=devin
Requested by: @yassin-berriai
Note
High Risk
Changes shipped Prisma migration files and the database setup/migration-job contract for high-traffic spend-log tables, including partitioned deployments and concurrent DDL under advisory locks.
Overview
SpendLogs index migrations are now no-ops (
SELECT 1plus comments) somigrate deployno longer runs blockingCREATE INDEXorCREATE INDEX CONCURRENTLYon a partitioned parent. The real indexes are built afterward fromREQUEST_LOG_INDEXESin newrequest_log_indexes.py: concurrent builds on plain tables, andON ONLY+ per-partition concurrent builds +ATTACH PARTITIONwhenLiteLLM_SpendLogsis partitioned.Orchestration changes:
run_migration_jobruns migrations then waits for indexes (Helmmigrations/run.py,--skip_server_startup). Serving proxies callstart_request_log_index_buildon a daemon thread after a successful migrate so readiness is not blocked. Index and invalid-index repair steps useheld_migration_lock(session advisory lock) so they coordinate with the v2 resolver and each other.Recovery and guardrails: v2 recovery can
roll_back_failed_inert_migrationfor stuck failed rows (e.g. old P3018 on the call_id migration). Drift resolution filters job-owned index DDL; CIcheck_migrations_no_data_rewritesnow rejects anyCREATE INDEXon request-log tables and points authors atREQUEST_LOG_INDEXES.Reviewed by Cursor Bugbot for commit 065c059. Bugbot is set up for automated code reviews on this repo. Configure here.