Skip to content

fix(proxy-extras): build the SpendLogs indexes in the migration job instead of in migrations - #43948

Merged
yassin-berriai merged 1 commit into
mainfrom
litellm_concurrent_spend_logs_api_key_index
Oct 1, 2026
Merged

yassin-berriai merged 1 commit into
mainfrom
litellm_concurrent_spend_logs_api_key_index

Conversation

@devin-ai-integration

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

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves:

  • Two v1.103.0 SpendLogs index migrations each break one deployment shape
  • Plain CREATE INDEX blocks spend-log writes for the whole build on big tables
  • CREATE INDEX CONCURRENTLY fails on a partitioned parent, P3018, then P3009 forever
  • First-time upgraders hit the failing migration before any fix could run

How it solves it:

  • Both migration files are now inert: a comment and SELECT 1;
  • The migration job builds the indexes after migrate deploy, synchronously, and exits non-zero when one is missing
  • A serving proxy that ran migrate deploy itself (DISABLE_SCHEMA_UPDATE unset) starts the same build on a background thread right after its deploy, so readiness never waits on it
  • Plain table: CREATE INDEX CONCURRENTLY IF NOT EXISTS, writes keep flowing
  • Partitioned: parent ON ONLY, each partition CONCURRENTLY, then ATTACH PARTITION
  • An existing valid index of the same definition under another name (a hand-built workaround) is renamed and used, never duplicated; a second copy is logged with its DROP INDEX for the operator, never dropped
  • One table-driven index list; the checker rejects future index migrations on these tables

One-sentence RCA: the two shipped SpendLogs index migrations each assume one table shape, a plain CREATE INDEX holds a SHARE lock across a large unpartitioned table while CREATE INDEX CONCURRENTLY is 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 needs

User Flow

Before: an admin upgrading a proxy whose spend logs are partitioned never gets a healthy pod

  1. The admin rolls out v1.103.0 or later against a database partitioned with the documented partition script
  2. The pod log prints Error: P3018 ... cannot create index on partitioned table "LiteLLM_SpendLogs" concurrently
  3. GET https://litellm-domain/health/readiness never returns 200, the pod restarts, and every later start prints P3009 migrate found failed migrations
  4. The admin has to hand-build the index and edit the migration history before any pod comes up. On a large unpartitioned database the same rollout instead stalls every spend-log write for the whole index build

After: the same rollout applies two no-op migrations, the migration job builds the indexes online, and the pods come up

  1. The admin rolls out the fixed build against the same partitioned database, or against a plain one with millions of rows; the helm migration Job (or litellm --skip_server_startup) runs first, as today
  2. The job log prints Building index LiteLLM_SpendLogs_p2026_07_litellm_call_id_idx on LiteLLM_SpendLogs_p2026_07 concurrently and Attached index ... to LiteLLM_SpendLogs_litellm_call_id_idx per partition (one Building index ... concurrently line per index on a plain table), then Request-log indexes are all in place and Migration job completed successfully., while spend logs keep being written the whole time
  3. GET https://litellm-domain/health/readiness on the new pods returns 200 {"status":"healthy","db":"connected"} as soon as their migrate deploy finishes, which now never fails on these two files; the pods' background build then finds the indexes in place and prints only Request-log indexes are all in place
  4. A database that already applied the original files reports no pending migrations and the job builds nothing; a database an earlier v1.103+ boot left stuck on the failed 20260831120001 row has that row rolled back by the job and the inert file applied, with no operator action
  5. A deployment with no migration job, where the serving proxy runs migrate deploy itself, gets the same indexes: the pod answers readiness 200 while its log prints the Building index ... concurrently and Attached index lines, and Request-log indexes are all in place follows a few seconds later

Relevant 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

File What changed and why
litellm-proxy-extras/.../20260823000000_add_spend_logs_api_key_starttime_index/migration.sql Now inert: a comment pointing at the post-deploy index build and SELECT 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-op
litellm-proxy-extras/.../20260831120001_spend_logs_litellm_call_id_index/migration.sql Same: the CREATE INDEX CONCURRENTLY that Postgres refuses on a partitioned parent is gone, replaced by a comment and SELECT 1;
litellm-proxy-extras/litellm_proxy_extras/request_log_indexes.py New leaf module (no litellm.proxy imports). REQUEST_LOG_INDEXES is the single table-driven list of indexes the migration job owns, named exactly as Prisma derives them from @@index. ensure_request_log_indexes builds each missing or invalid one: CREATE INDEX CONCURRENTLY IF NOT EXISTS on a plain table; on a partitioned parent CREATE INDEX IF NOT EXISTS ... ON ONLY parent under a 2s lock_timeout with retries, then CREATE INDEX CONCURRENTLY IF NOT EXISTS per partition with a deterministic child name within 63 bytes, then ALTER 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 with ALTER INDEX ... RENAME instead of being built again; every remaining index of the same definition is logged as a second copy with the DROP INDEX CONCURRENTLY (plain DROP INDEX for 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_diff drops exactly these indexes from the migrations-vs-schema drift diff
litellm-proxy-extras/litellm_proxy_extras/utils.py setup_database only migrates (both resolvers), repairs invalid indexes and returns, so a serving proxy's readiness never waits on an index build. New build_request_log_indexes resolves the writer URL and schema and runs the builder synchronously; new run_migration_job is setup_database then build_request_log_indexes, False when either fails so the Job exits non-zero and is rerun; new start_request_log_index_build runs 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_sync applies filter_request_log_index_diff so the drift check tolerates the two job-owned indexes and nothing else. repair_invalid_indexes takes the migration lock too, one hold per index like the builder, so it never rebuilds an index a job is still building concurrently
litellm-proxy-extras/litellm_proxy_extras/migration_lock.py New held_migration_lock: a session-level, non-blocking hold of the same MIGRATION_LOCK_KEY the v2 resolver takes per transaction, for DDL that cannot run inside a transaction (CREATE INDEX CONCURRENTLY)
litellm-proxy-extras/litellm_proxy_extras/migration_recovery.py is_inert_migration (comments plus SELECT 1 only) and roll_back_failed_inert_migration: when the v2 resolver finds a failed _prisma_migrations row for a migration whose file in this build is inert, it marks that row rolled back so migrate deploy applies 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 SQL
migrations/run.py The migrations image entrypoint (helm migration Job) calls run_migration_job, so it migrates, then builds the indexes, and exits 1 when either step fails
litellm/proxy/db/prisma_client.py, litellm/proxy/proxy_cli.py PrismaManager.build_request_log_indexes (wait for the build) and start_request_log_index_build (daemon thread) forward to proxy-extras. After a successful setup_database the 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_UPDATE unset) also gets the indexes
tests/code_coverage_tests/check_migrations_no_data_rewrites.py Any CREATE INDEX, concurrent or not, on LiteLLM_SpendLogs or LiteLLM_ErrorLogs inside a migration now fails CI (schema-qualified, lower-case, ONLY, comment-separated and EXECUTE forms included) with a message pointing at REQUEST_LOG_INDEXES and the migration job. A -- data-migration-ok marker 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 inert

Pre-Submission checklist

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

Screenshots / 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) or USE_V2_MIGRATION_RESOLVER=false (legacy) with DATABASE_URL pointing at that database, exactly as the migrations image runs it. The serving proxy is python -m litellm.proxy.proxy_cli --config config.yaml --port 41xx --enforce_prisma_migration_check with --use_v2_migration_resolver or --use_legacy_migration_resolver, readiness polled with curl http://127.0.0.1:41xx/health/readiness. The config has one openai/fake model behind an unreachable api_base and master_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 one INSERT INTO "LiteLLM_SpendLogs" every 50 ms while the job runs and sample pg_stat_activity (inserts with wait_event_type = 'Lock'), pg_stat_progress_create_index and pg_locks every 100 ms. The v1.102.1 schema databases come from prisma migrate deploy with the migrations shipped up to that release; the partitioned one then ran db_scripts/partition_spend_logs.sql and 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.py and python3 proof/proof4.py, per-case JSON in proof/out3/ and proof/out4/

Before (c168199)

Captured on main at that commit; both migration files are byte-identical at the current merge base, so the Before legs still describe it

Case a: fresh database

  1. Start the proxy with the v2 resolver on an empty database, then curl http://127.0.0.1:4101/health/readiness
  2. 200 {"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

  1. Start the proxy with the v2 resolver, insert loop and sampler running
  2. pg_stat_activity shows CREATE INDEX IF NOT EXISTS "LiteLLM_SpendLogs_api_key_startTime_idx" ... (no CONCURRENTLY) holding a ShareLock on "LiteLLM_SpendLogs"
  3. Sampler: 19 of 125 samples caught the insert loop in wait_event_type = 'Lock', slowest insert 1859.8 ms, 1 insert over one second
  4. Readiness 200 after 18.6 s, so the proxy boots, but writes were blocked for the build (3,000,000 rows here; a production table was measured at 3.3 s per insert)

Case c: partitioned v1.102.1 database with three populated partitions plus default, concurrent insert loop

  1. Start the proxy with the v2 resolver, insert loop and sampler running
  2. Log: Migration name: 20260831120001_spend_logs_litellm_call_id_index / Database error code: 0A000 / ERROR: cannot create index on partitioned table "LiteLLM_SpendLogs" concurrently / Error: P3018
  3. Process exits with code 2 after 16.5 s, curl .../health/readiness never answers
  4. Catalog: LiteLLM_SpendLogs_litellm_call_id_idx does not exist, the 20260831120001 ledger row has finished_at IS NULL

Case d: partitioned database whose ledger already holds the failed P3018 row for the call_id migration

  1. Start the proxy with the v2 resolver on the database case c left behind
  2. Log: Error: P3009 migrate found failed migrations in the target database, process exits with code 2 after 16.5 s, readiness never answers
  3. SELECT 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), unchanged

Case e: database that already applied the shipped migration files

  1. prisma migrate deploy with the shipped files from main on a plain v1.102.1 database: both index migrations apply (the blocking CREATE INDEX and the CREATE INDEX CONCURRENTLY), both ledger rows finished with the shipped checksums
  2. This is the starting state for case e After; nothing fails here on base

Case f: serving proxy rolled out without the migration job, on the partitioned database

  1. Same as case c: the proxy itself runs migrate deploy, hits P3018 on the partitioned parent, exits with code 2, readiness never answers

After (065c059)

Case a: fresh database

  1. Run the migration job on an empty database: log prints Building index LiteLLM_SpendLogs_api_key_startTime_idx on LiteLLM_SpendLogs concurrently, the same for LiteLLM_SpendLogs_litellm_call_id_idx, then Request-log indexes are all in place and Migration job completed successfully., exit 0 after 18.4 s (26.5 s legacy)
  2. SELECT indisvalid FROM pg_index WHERE indexrelid = '"LiteLLM_SpendLogs_api_key_startTime_idx"'::regclass returns true for both indexes; both ledger rows carry the checksums of the inert files
  3. Start the serving proxy on that database, then curl 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 only Request-log indexes are all in place, no Building index line, index OIDs unchanged by the boot

Case b: unpartitioned v1.102.1 database with 3,000,000 spend logs and a concurrent insert loop

  1. Run the migration job, insert loop and sampler running: exit 0 after 19.5 s (22.9 s legacy), both indexes valid when it exits. pg_stat_activity shows only CREATE INDEX CONCURRENTLY IF NOT EXISTS ... statements, pg_locks shows them holding ShareUpdateExclusiveLock, never ShareLock
  2. Sampler, v2: 382 inserts, 0 errors, slowest insert 19.0 ms, p99 4.8 ms, 0 inserts over one second, 0 of 193 samples with an insert waiting on a lock. Legacy: 449 inserts, 0 errors, slowest 6.0 ms, p99 4.6 ms, 0 of 226 samples waiting
  3. prisma migrate deploy afterwards prints No pending migrations to apply. and prisma migrate status prints Database schema is up to date!
  4. Serving proxy on that database: readiness 200 after 18.6 s (16.5 s legacy), its background build prints only Request-log indexes are all in place, index OIDs unchanged

Case c: partitioned v1.102.1 database with three populated partitions plus default, concurrent insert loop

  1. Run the migration job, insert loop and sampler running: exit 0 after 21.4 s (25.0 s legacy), both parent indexes valid with every child attached when it exits. pg_stat_activity shows CREATE INDEX CONCURRENTLY IF NOT EXISTS "LiteLLM_SpendLogs_p2026_07_litellm_call_id_idx" ON "public"."LiteLLM_SpendLogs_p2026_07" ... and the same for p2026_08 and p2026_09 (the 300,000-row pdefault build finished between two samples); the log prints Building index ... concurrently for all 4 partitions and Attached index LiteLLM_SpendLogs_p2026_07_litellm_call_id_idx on partition LiteLLM_SpendLogs_p2026_07 to LiteLLM_SpendLogs_litellm_call_id_idx once per partition. No builder lock on the parent in pg_locks
  2. Sampler, v2: 421 inserts, 0 errors, slowest insert 6.3 ms, p99 3.4 ms, 0 inserts over one second, 0 of 212 samples with an insert waiting on a lock. Legacy: 491 inserts, 0 errors, slowest 4.1 ms, p99 2.6 ms, 0 of 248 samples waiting
  3. SELECT indisvalid FROM pg_index WHERE indexrelid = '"LiteLLM_SpendLogs_litellm_call_id_idx"'::regclass returns true for both parents; the pg_inherits join on pg_index lists all 4 partitions attached under each parent index
  4. CREATE 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 action
  5. Run the job again: exit 0 after 12.7 s (12.4 s legacy), no Building index line, catalog and index OIDs unchanged. prisma migrate deploy prints No pending migrations to apply., prisma migrate status prints Database schema is up to date!
  6. Serving proxy on that database: readiness 200 after 16.5 s on both resolvers, its background build prints only Request-log indexes are all in place, index OIDs unchanged

Case d: partitioned database whose ledger already holds the failed P3018 row for the call_id migration

  1. Run the migration job on a copy of the database case c Before left behind. v2 log: 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 existing Found 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)
  2. 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. The 20260823000000 row keeps its original checksum
  3. Both parent indexes valid with all 4 partitions attached; prisma migrate deploy prints No pending migrations to apply., prisma migrate status prints Database schema is up to date!. So the exact outcome is: the job clears the stuck row itself, no resolve --rolled-back by the operator
  4. Serving proxy on that database: readiness 200 after 17.6 s on both resolvers, its background build prints only Request-log indexes are all in place

Case e: database that already applied the shipped migration files

  1. Run the migration job on the database case e Before produced: exit 0 on both resolvers (12.8 s v2, 19.5 s legacy), log prints no Building index line, only Request-log indexes are all in place
  2. prisma migrate deploy from this branch prints No pending migrations to apply., prisma migrate status prints Database schema is up to date!
  3. Both ledger rows still carry the original files' checksums (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 indexes
  4. Serving proxy on that database: readiness 200 after 16.6 s on both resolvers, its background build prints only Request-log indexes are all in place

Case f: serving proxy rolled out without the migration job, on the partitioned database

  1. Start only the serving proxy on a fresh copy of the partitioned v1.102.1 database: readiness 200 after 16.5 s (20.7 s legacy), both inert migrations applied, and right after readiness its log prints Building index LiteLLM_SpendLogs_p2026_07_litellm_call_id_idx on LiteLLM_SpendLogs_p2026_07 concurrently, the background build running while it serves
  2. The harness stops that proxy a few seconds after readiness, mid-build: the catalog then holds the ON ONLY parent LiteLLM_SpendLogs_litellm_call_id_idx (invalid, nothing attached yet) and the finished p2026_07 child, while the api_key index is exactly what the partition script created
  3. Run the migration job afterwards: it attaches the child the proxy built (Attached index LiteLLM_SpendLogs_p2026_07_litellm_call_id_idx ... with no Building index line 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 test tests/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 against schema.prisma
  • tests/unit/litellm_proxy_extras/test_litellm_proxy_extras_utils.py: build_request_log_indexes forwards the writer URL and schema, falls back to DATABASE_URL, is a no-op without one, returns the builder's False; run_migration_job builds only after a successful setup and returns False when either step fails; start_request_log_index_build returns before the build runs and runs it on a daemon thread
  • tests/unit/proxy/test_proxy_cli.py: --skip_server_startup waits 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 one
  • tests/unit/proxy/db/test_prisma_client.py: without proxy-extras installed the waited build reports False and the background start returns, neither raises
  • tests/proxy_migration_tests/test_request_log_indexes.py (real Postgres, both resolvers): plain, partitioned and nested-partitioned builds through run_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 its DROP INDEX CONCURRENTLY statement and left in place, a job that could not build the indexes reporting failure and succeeding when rerun, and setup_database alone applying the inert files while leaving the indexes exactly as they were
  • tests/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 in
  • tests/proxy_migration_tests/test_db_schema_migration.py: the drift check filters exactly the job-owned indexes and still fails on any other drift
  • tests/integration/database/test_request_log_indexes_at_boot.py (live proxy and the real migrations/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_startup path building both before it exits
  • tests/unit/test_check_migrations_no_data_rewrites.py: every index form the checker must reject on the two tables, including under a data-migration-ok marker
  • Mutation check, one mutation at a time against the focused unit and real-Postgres tests, 26 of 26 killed: child index never attached, SELECT 1 no longer counted as inert, invalid index kept instead of rebuilt, same-name index on another table treated as ours, drift filter keeping the job-owned CREATE INDEX lines, checker letting CREATE INDEX CONCURRENTLY through, migration lock ignored, parent built without ON 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_job ignoring the build result, build_request_log_indexes dropping the builder's result, run_migration_job never building, the CLI building for a serving proxy too, the CLI exiting 0 when an index could not be built, setup_database building the indexes in the serving proxy, the equivalent index never renamed, the column order ignored when matching an equivalent index, DESC ignored, a non-default opclass ignored, second copies never reported, the leaf adoption dropped, the parent adoption dropped

The integration repro was written first and shown red on main at c168199: ERROR: cannot create index on partitioned table "LiteLLM_SpendLogs" concurrently, P3018, readiness never answered

Type

🐛 Bug Fix

Caveats (if any)

Severe

  • Two shipped migration files are edited in place to become inert
    • Rows already applied keep their checksum; Prisma does not re-check them (case e)
    • A database stuck on the old file's failed row is cleared by the job (case d)
  • A serving proxy that runs migrate deploy itself builds these indexes in the background while it serves
    • Only when it ran the migrations (DISABLE_SCHEMA_UPDATE unset) and they succeeded; a proxy with schema updates disabled never builds
    • On a large table that is minutes of CREATE INDEX CONCURRENTLY on a serving pod, with writes flowing the whole time; a pod killed mid-build leaves an invalid index the next build drops and rebuilds
    • Every replica starts the build; the migration lock makes all but one find the indexes in place or step aside, logged, until the next boot
    • An operator who wants the build off the serving pods runs the migration job (litellm --skip_server_startup) instead

Medium

  • The metadata-only parent index takes a SHARE lock on the parent for one statement
    • Bounded by a 2s lock_timeout with 30 retries, then left for the next job run
  • The migration job and --skip_server_startup wait for the build before exiting and exit non-zero when an index is not in place
    • On a large table that is minutes of job runtime, with writes flowing the whole time; a job killed mid-build leaves an invalid index the next run drops and rebuilds
    • A job whose build lost the migration lock to another process or hit a same-name index on another table fails and gets rerun by its Job controller, rather than exiting 0 with the table unindexed

Low

  • Future SpendLogs or ErrorLogs indexes go in REQUEST_LOG_INDEXES, not in a migration
    • The migration checker enforces this
  • A same-name index on another table is logged and left alone, never dropped
  • A valid index of the same definition under another name is renamed to the expected name, which is a catalog change (ALTER INDEX ... RENAME takes SHARE UPDATE EXCLUSIVE on 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 its DROP INDEX statement and never dropped by this code
  • The invalid index repair skips a run while another process holds the migration lock
    • A genuinely invalid index waits for the next database setup run, as before when the repair lock was taken
    • The lock is held per rebuild, so a v2 resolver waiting on another replica queues behind one REINDEX, not all of them

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/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 1 plus comments) so migrate deploy no longer runs blocking CREATE INDEX or CREATE INDEX CONCURRENTLY on a partitioned parent. The real indexes are built afterward from REQUEST_LOG_INDEXES in new request_log_indexes.py: concurrent builds on plain tables, and ON ONLY + per-partition concurrent builds + ATTACH PARTITION when LiteLLM_SpendLogs is partitioned.

Orchestration changes: run_migration_job runs migrations then waits for indexes (Helm migrations/run.py, --skip_server_startup). Serving proxies call start_request_log_index_build on a daemon thread after a successful migrate so readiness is not blocked. Index and invalid-index repair steps use held_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_migration for stuck failed rows (e.g. old P3018 on the call_id migration). Drift resolution filters job-owned index DDL; CI check_migrations_no_data_rewrites now rejects any CREATE INDEX on request-log tables and points authors at REQUEST_LOG_INDEXES.

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

@devin-ai-integration

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

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you sign our Contributor License Agreement before we can accept your contribution.
You have signed the CLA already but the status is still pending? Let us recheck it.

@greptile-apps

greptile-apps Bot commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 5/5

[Critical risk] Moves database index creation from migrations to a separate job.

The PR appears safe to merge based on this review; no outstanding or newly established blocking issue remains.

Summary

The PR moves SpendLogs index creation out of migrations and into the migration job, with concurrent builds for plain tables and per-partition builds for partitioned tables. Changes since the previous review add equivalent-index reuse and duplicate-index reporting, alongside CI, test, and model-insights updates.

Reviews (16) · Last reviewed commit: "fix(proxy-extras): build the SpendLogs i..."

@codecov

codecov Bot commented Oct 1, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 90.00000% with 2 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
litellm/proxy/db/prisma_client.py 87.50% 2 Missing ⚠️

📢 Thoughts on this report? Let us know!

@devin-ai-integration
devin-ai-integration Bot force-pushed the litellm_concurrent_spend_logs_api_key_index branch from 0fc3a51 to d45adc8 Compare October 1, 2026 00:27
@devin-ai-integration devin-ai-integration Bot added the backport-stable P0 regression fix only (Urgent ticket): cherry-pick onto the baking rc line before the stable tag label Oct 1, 2026
@devin-ai-integration
devin-ai-integration Bot force-pushed the litellm_concurrent_spend_logs_api_key_index branch from d45adc8 to 8b797b9 Compare October 1, 2026 02:51
@devin-ai-integration devin-ai-integration Bot changed the title fix(proxy-extras): build the SpendLogs (api_key, startTime) index concurrently fix(proxy-extras): build SpendLogs indexes concurrently, per partition when the table is partitioned Oct 1, 2026
@mateo-berri

Copy link
Copy Markdown
Contributor

bugbot run

@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

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

@devin-ai-integration
devin-ai-integration Bot force-pushed the litellm_concurrent_spend_logs_api_key_index branch from 8b797b9 to d49aee6 Compare October 1, 2026 03:26
@mateo-berri

Copy link
Copy Markdown
Contributor

bugbot run

@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

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

@devin-ai-integration
devin-ai-integration Bot force-pushed the litellm_concurrent_spend_logs_api_key_index branch from d49aee6 to f67caac Compare October 1, 2026 04:57
@devin-ai-integration devin-ai-integration Bot reopened this Oct 1, 2026
@devin-ai-integration devin-ai-integration Bot changed the title fix(proxy-extras): build SpendLogs indexes concurrently, per partition when the table is partitioned fix(proxy-extras): build the SpendLogs indexes at startup instead of in migrations Oct 1, 2026
@mateo-berri

Copy link
Copy Markdown
Contributor

bugbot run

@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

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

@codspeed

codspeed Bot commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

✅ 31 untouched benchmarks


Comparing litellm_concurrent_spend_logs_api_key_index (065c059) with main (ba8cd1e)1

Open in CodSpeed

Footnotes

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

@devin-ai-integration
devin-ai-integration Bot force-pushed the litellm_concurrent_spend_logs_api_key_index branch from dc19f09 to 31b021c Compare October 1, 2026 05:54
@mateo-berri

Copy link
Copy Markdown
Contributor

bugbot run

yuneng-berri added a commit that referenced this pull request Oct 2, 2026
devin-ai-integration Bot added a commit that referenced this pull request Oct 2, 2026
… 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>
yuneng-berri added a commit that referenced this pull request Oct 2, 2026
…4212)

This reverts merge commit dea6fb9, reversing changes made to 61876f2
yassin-berriai added a commit that referenced this pull request Oct 2, 2026
… 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>
yuneng-berri added a commit that referenced this pull request Oct 2, 2026
…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
yuneng-berri added a commit that referenced this pull request Oct 2, 2026
* 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
yuneng-berri added a commit that referenced this pull request Oct 2, 2026
…) (#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)
yuneng-berri added a commit that referenced this pull request Oct 3, 2026
)

* 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>
DeoLeung pushed a commit to aiyou178/litellm that referenced this pull request Oct 4, 2026
…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)
DeoLeung pushed a commit to aiyou178/litellm that referenced this pull request Oct 4, 2026
… 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)
yuneng-berri added a commit that referenced this pull request Nov 10, 2026
…1_103_x_devin

fix(proxy-extras): backport the automatic SpendLogs index build (#43948, #44109, #44203) to stable/1.103.x
yuneng-berri added a commit that referenced this pull request Nov 10, 2026
…1_104_x_devin

fix(proxy-extras): backport the automatic SpendLogs index build (#43948, #44109, #44203) to stable/1.104.x
Lineaje-DepFixer pushed a commit to lineaje-labs-gos/BerriAI-litellm that referenced this pull request Nov 18, 2026
…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)
Lineaje-DepFixer pushed a commit to lineaje-labs-gos/BerriAI-litellm that referenced this pull request Nov 18, 2026
… 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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

backport-stable P0 regression fix only (Urgent ticket): cherry-pick onto the baking rc line before the stable tag

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Migration 20260831120001 fails on partitioned "LiteLLM_SpendLogs" table (cannot create index concurrently)

4 participants