Skip to content

feat(proxy): refuse migrations that existing rows would make fail, before the first one runs - #48493

Merged
kerry-berri merged 13 commits into
mainfrom
litellm_db_preflight_before_migrations
Oct 27, 2026
Merged

kerry-berri merged 13 commits into
mainfrom
litellm_db_preflight_before_migrations

Conversation

@kerry-berri

@kerry-berri kerry-berri commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

Before any migration runs, the proxy now reads the rows a pending schema change depends on and refuses with a named report when they would make it fail, instead of applying the migrations and dying halfway with a Postgres error. The checks are derived from the statement text (an index over a text column, UNIQUE, SET NOT NULL, a NOT NULL column with no default, FOREIGN KEY, CHECK), so a future migration of one of those kinds gets its check without anyone writing one. litellm --check_migrations_against_existing_data runs the same checks against a database and exits without applying anything, so an operator can check production a week before the upgrade

Details

TLDR

Problem this solves:

  • Upgrading past v1.102 on a database with pre-v1.99.0 spend-log rows fails on the (api_key, startTime) index
  • Those rows hold the raw bearer token, some over Postgres's 2704-byte btree entry limit
  • Today the migrations apply, then the index build fails, the job exits 1 and the log says to check the connection
  • Nothing lets an operator check a database before they roll the new image

How it solves it:

  • migration_data_checks.py turns each pending statement into one read-only count query from its kind and the catalog column types
  • For a btree index it sizes each row's whole entry the way index_form_tuple lays it out (tuple header, null bitmap, every indexed column at its alignment, rounded to 8) against BTMaxItemSize for the server's block_size, so the line falls where Postgres draws it (2684 bytes of api_key next to startTime), not at octet_length > 2704
  • setup_database runs it before prisma migrate deploy; a hit raises the existing "Database migration cannot proceed" exit 2
  • The report names the table, columns, row count, largest entry and longest value, blocked statement and the SQL that clears it
  • The request-log index builder runs the same check and logs the report instead of leaving an INVALID index
  • --check_migrations_against_existing_data runs the checks alone, exit 0 or 2, writes nothing
  • A count that cannot finish within LITELLM_MIGRATION_DATA_CHECK_TIMEOUT (600 s) is reported as unverified, never passed

User Flow

Before: an operator upgrading a 1.101 deployment with old spend-log rows gets a failed migration job and no useful message

  1. They start the new image with --skip_server_startup (or the Helm migration job) against their database
  2. All pending migrations apply, then the log shows index row size 2976 exceeds btree version 4 maximum 2704 for index "LiteLLM_SpendLogs_api_key_startTime_idx"
  3. The job prints Database setup failed after multiple retries ... check your database connection and exits 1, every rerun fails the same way
  4. The database is on the new schema with an INVALID index, so rolling the pods back runs old code on a newer schema

After: the same job stops before the first migration and tells them which rows to fix

  1. They start the same image the same way
  2. Before any migration runs, it prints "LiteLLM_SpendLogs".api_key, startTime: 2 row(s) with an index entry over 2704 bytes, largest 3232 bytes (api_key up to 3207 bytes), the index it blocks, and the hashing UPDATE that clears it, then exits 2 with the schema untouched
  3. They run that UPDATE and start the job again, which applies the migrations and builds the index, exit 0
  4. Next time, they run the new image with --check_migrations_against_existing_data against production first and get the same report or an all-clear, nothing applied

Linear ticket

Resolves LIT-9634

Pre-Submission checklist

Please complete all items before asking a LiteLLM maintainer to review your PR

  • I have added meaningful tests
  • The handful of test files covering my change pass locally, e.g. uv run pytest tests/unit/<your_test_file>.py -v. Leave the suites (make test-unit-*, make test-unit) to CI: it finishes in ~15 minutes where a laptop takes an hour or more
  • My PR passes all required CI/CD checks (e.g., lint, schema.d.ts sync check, etc.)
  • My PR's scope is as isolated as possible; it only solves 1 specific problem
  • Every automated review on my PR's latest commit has finished, and I have addressed or replied to each of its findings before requesting a maintainer review

Screenshots / Proof of Fix

Rig: a database built by the ghcr.io/berriai/litellm-database:v1.101.0 image (165 migrations), then two spend-log rows inserted the way a pre-v1.99.0 proxy wrote them ('Bearer ' || random hex, 3207 and 2951 bytes), then the migration job from the commit under test run against it with python litellm/proxy/proxy_cli.py --skip_server_startup

Before (2e27a02)

Migration job on a database with two legacy rows

  1. DATABASE_URL=... python litellm/proxy/proxy_cli.py --skip_server_startup
  2. Log: All migrations have been successfully applied. then WARNING Could not build the request-log indexes, leaving them for the next index build: index row size 2976 exceeds btree version 4 maximum 2704 for index "LiteLLM_SpendLogs_api_key_startTime_idx"
  3. Output: Database setup failed after multiple retries. The proxy cannot start safely. Please check your database connection and migration status. exit 1
  4. _prisma_migrations finished rows: 165 -> 222. pg_index for LiteLLM_SpendLogs_api_key_startTime_idx: indisvalid = f

--check_migrations_against_existing_data

  1. python litellm/proxy/proxy_cli.py --check_migrations_against_existing_data
  2. Error: No such option: --check_migrations_against_existing_data exit 2

After (f8d5ccd)

Migration job on a database with two legacy rows

  1. Same command, same database (165 finished migrations, two legacy rows)
  2. Output, before any migration ran:
    LiteLLM Proxy: Database migration cannot proceed. Existing rows would make a pending schema change fail:
      "LiteLLM_SpendLogs".api_key, startTime: 2 row(s) with an index entry over 2704 bytes, largest 3232 bytes (api_key up to 3207 bytes)
        blocks: CREATE INDEX "LiteLLM_SpendLogs_api_key_startTime_idx" (request-log index)
        fix:    Rows written before v1.99.0 hold the raw key. Hash them in place (one-way, idempotent):
                UPDATE "LiteLLM_SpendLogs" SET api_key = encode(sha256(convert_to(regexp_replace(api_key, '^[Bb][Ee][Aa][Rr][Ee][Rr] ', ''), 'UTF8')), 'hex')
                WHERE api_key <> '' AND api_key !~ '^[0-9a-fA-F]{64}$' AND api_key !~ '^hashed-jwt-[0-9A-Fa-f]{64}$';
    No schema change was made. Fix the rows and start again, or run `litellm --check_migrations_against_existing_data` with the new image to check again.
    
    exit 2
  3. _prisma_migrations finished rows: still 165. pg_indexes rows for LiteLLM_SpendLogs_api_key_startTime_idx: 0
  4. Ran the printed UPDATE: UPDATE 2. Same job again: Building index LiteLLM_SpendLogs_api_key_startTime_idx on LiteLLM_SpendLogs concurrently ... Request-log indexes are all in place ... Setup complete, exit 0. Finished rows 222, indisvalid = t

--check_migrations_against_existing_data

  1. With the legacy rows: python litellm/proxy/proxy_cli.py --check_migrations_against_existing_data prints the same report, exit 2, ledger and indexes untouched
  2. After the UPDATE: LiteLLM Proxy: the pending migrations and indexes can be applied to the rows this database has. exit 0

Where the line is (Postgres 14, 8 KB page, psql)

  1. create table bt (b text, "startTime" timestamp(3)); insert into bt select <2684 random bytes>, now(); create index bt1 on bt (b, "startTime"); -> CREATE INDEX
  2. Same with 2685 bytes -> ERROR: index row size 2712 exceeds btree version 4 maximum 2704 for index "bt1"
  3. The check on the same two rows counts exactly the 2685-byte one: 1 row(s) with an index entry over 2704 bytes, largest 2712 bytes (b up to 2685 bytes). octet_length > 2704 would have passed both. Same for a 20-byte text column before the key (line at 2668) and a NULL before it (2684), in test_the_entry_size_check_draws_the_line_exactly_where_postgres_does

Type

🆕 New Feature

Caveats (if any)

Medium

  • ALTER COLUMN ... TYPE gets no check: counting rows that fail a cast needs pg_input_is_valid, which is Postgres 16+
  • A UNIQUE index or constraint over an expression gets no check, only plain column lists are derived
  • The byte-length count is conservative: Postgres compresses index entries, so a long but repetitive value can fit, and the preflight still refuses it
  • Partial indexes are counted without their WHERE, so a row the predicate excludes can still refuse the migration

Low

  • One count query per check, read-only and lock-free, but a count over a very large spend log can take minutes; the scan stops at LITELLM_MIGRATION_DATA_CHECK_TIMEOUT (default 600 s) and refuses as unverified
  • A fresh database with no _prisma_migrations table treats every migration as pending; every check then skips because its table does not exist yet, which costs one catalog query per derived check
  • The CI gate that would require a check or a precheck.sql for every new risky statement is a follow-up, not in this PR

Link to Devin session: https://app.devin.ai/sessions/14b2bd229edf4b11a3220d90993f6708
Open in Devin Desktop: https://app.devin.ai/desktop/session/14b2bd229edf4b11a3220d90993f6708?variant=devin
Requested by: @kerry-berri

kerry-berri and others added 3 commits October 26, 2026 23:03
…fore the first one runs

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…ase without the api_key index

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@devin-ai-integration

Copy link
Copy Markdown
Contributor

I'll fix CI failures and address comments from users with write access. I'll skip comments containing "(aside)".

  • Disable automatic comment, CI, and merge conflict monitoring

kerry-berri and others added 2 commits October 26, 2026 23:23
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@codecov

codecov Bot commented Oct 26, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 31.57895% with 13 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
litellm/proxy/proxy_cli.py 28.57% 10 Missing ⚠️
litellm/proxy/db/prisma_client.py 40.00% 3 Missing ⚠️

📢 Thoughts on this report? Let us know!

@codspeed

codspeed Bot commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

1 warning

⚠️ 1 benchmark is dominated by system calls

System calls cannot be simulated consistently and are left out of the measure. The reported value understates the real cost. Switch to the Walltime instrument to measure them.

Learn more about system calls

See affected benchmarks

✅ 35 untouched benchmarks


Comparing litellm_db_preflight_before_migrations (f8d5ccd) with main (3b8ad37)

Open in CodSpeed

kerry-berri and others added 8 commits October 26, 2026 23:46
…he type gate holds

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…e may be absent

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…ort variables

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…s unknown

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
… flag for what it does

The index check now lays out each row's entry the way index_form_tuple does (tuple header, null bitmap, every indexed column at its alignment, rounded to 8) and compares it with BTMaxItemSize for the server's block_size, so a key that passes octet_length > 2704 but still fails the (api_key, startTime) index is caught. --db_preflight becomes --check_migrations_against_existing_data, db_preflight.py becomes migration_data_checks.py and the timeout env var LITELLM_MIGRATION_DATA_CHECK_TIMEOUT

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants