Skip to content

fix(proxy): coordinate v2 migration startup and qualify container recovery - #40932

Merged
yuneng-berri merged 6 commits into
mainfrom
litellm_v2_migration_startup
Sep 20, 2026
Merged

yuneng-berri merged 6 commits into
mainfrom
litellm_v2_migration_startup

Conversation

@yuneng-berri

@yuneng-berri yuneng-berri commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves:

  • Simultaneous v2 startups can exhaust retries while another replica migrates
  • Interrupted migration history needs evidence before automatic recovery

How it solves it:

  • Give lock contention its own bounded waiting budget
  • Coordinate verified recovery, then finish every pending migration
  • Explain ambiguous failures; warn when adopting matching legacy schemas
  • Qualify container startup in scheduled and release CircleCI workflows

User Flow

Before: two waiting replicas fail while the migration owner remains alive

  1. A platform admin starts three ordinary LiteLLM containers against PostgreSQL
  2. One migration takes two minutes; the other containers wait
  3. Both waiting containers exit with code 2 after four retries
  4. Requests to their /health/readiness endpoints fail to connect

After: contention delays startup until the migration completes

  1. A platform admin starts three ordinary LiteLLM containers against PostgreSQL
  2. One migration takes two minutes; the other containers wait
  3. All three containers stay alive without becoming ready early
  4. Each /health/readiness returns healthy with the database connected

Relevant issues

Related to #39178

Pre-Submission checklist

  • Meaningful permanent unit and Docker regression tests added
  • Focused local tests and make check pass
  • All required current-head CI checks pass
  • Changes concern v2 migration startup and its qualification only
  • Current-head Greptile confidence is 5/5

Screenshots / Proof of Fix

Real Docker containers, PostgreSQL, packaged migration SQL and HTTP endpoints; no provider credentials or model calls needed. A database advisory gate holds one test migration for 120 seconds. The same test image dependency set is used for the base and changed resolver

Before (d565031)

  1. While the SQL gate remains held for 120 seconds:

    docker inspect litellm-migration-497b12ea3cb64a7a --format "{{json .State}}"
    {"Running":true,"ExitCode":0}
    docker inspect litellm-migration-deb5c580a7f94ee7 --format "{{json .State}}"
    {"Running":false,"ExitCode":2}
    docker inspect litellm-migration-00052d24c9454543 --format "{{json .State}}"
    {"Running":false,"ExitCode":2}
    
  2. Release the gate and request each readiness endpoint:

    curl -sS --max-time 3 -H "Authorization: Bearer sk-migration-ci-fixture" http://127.0.0.1:62383/health/readiness
    {"status":"healthy","db":"connected"}
    curl -sS --max-time 3 -H "Authorization: Bearer sk-migration-ci-fixture" http://127.0.0.1:62420/health/readiness
    curl exited 7: connection refused
    curl -sS --max-time 3 -H "Authorization: Bearer sk-migration-ci-fixture" http://127.0.0.1:62421/health/readiness
    curl exited 7: connection refused
    

After (a37f0b4)

  1. While the SQL gate remains held for 120 seconds:

    docker inspect litellm-migration-6dbcb432846745df --format "{{json .State}}"
    {"Running":true,"ExitCode":0}
    docker inspect litellm-migration-19923b66a13c4c68 --format "{{json .State}}"
    {"Running":true,"ExitCode":0}
    docker inspect litellm-migration-982699410fa04698 --format "{{json .State}}"
    {"Running":true,"ExitCode":0}
    
  2. Release the gate and request each readiness endpoint:

    curl -sS --max-time 3 -H "Authorization: Bearer sk-migration-ci-fixture" http://127.0.0.1:62809/health/readiness
    {"status":"healthy","db":"connected"}
    curl -sS --max-time 3 -H "Authorization: Bearer sk-migration-ci-fixture" http://127.0.0.1:62845/health/readiness
    {"status":"healthy","db":"connected"}
    curl -sS --max-time 3 -H "Authorization: Bearer sk-migration-ci-fixture" http://127.0.0.1:62846/health/readiness
    {"status":"healthy","db":"connected"}
    

Type

Bug Fix · Test · Infrastructure

Caveats

Severe

  • Unconfirmed migration completion stops startup with explicit recovery guidance
  • Matching legacy schemas start without replaying historical data backfills

Medium

  • Release enforcement requires the companion release change and service-account secret
  • Scheduled execution activates after the workflow lands on staging
  • Candidate image checks currently cover the database image on amd64

QA runbook

Use disposable PostgreSQL databases and the built database image. Core scenarios use three regular proxy containers directly connected to PostgreSQL; PgBouncer is confined to its own compatibility cases. Successful startup means every replica reports healthy database readiness, can generate a management key and read it back, and has the expected persisted database state. Failure cases require nonzero exit, no ready endpoint, and the specific migration error. Gates synchronize on observed PostgreSQL state; automatic test retries are disabled

  • tests/e2e/migrations/test_startup.py::TestMigrationStartup::test_fresh_database - Fresh v2 (one/three replicas) and v1 (one replica)

    • Start the selected replicas with an empty database
    • Expect healthy readiness and a generated key readable through /key/info; all migration rows are finished
    • Sanity check: observe the stated database boundary and final HTTP/data result; do not treat elapsed sleep or a live process as success
  • tests/e2e/migrations/test_startup.py::TestMigrationStartup::test_concurrent_upgrade - One execution across three replicas

    • Add SQL creating migration_effect with primary-key row 1; start three replicas together
    • Expect three usable replicas, exactly one finished step-1 migration row, and exactly row 1
    • Sanity check: observe the stated database boundary and final HTTP/data result; do not treat elapsed sleep or a live process as success
  • tests/e2e/migrations/test_startup.py::TestMigrationStartup::test_waiters_survive_prolonged_contention - Contention does not exhaust ordinary retries

    • Hold the migration SQL advisory gate, observe two followers waiting on the Prisma lock, then keep it held for 120 seconds
    • Expect all three alive and unready while blocked, then usable after release; verify one SQL execution
    • Sanity check: observe the stated database boundary and final HTTP/data result; do not treat elapsed sleep or a live process as success
  • tests/e2e/migrations/test_startup.py::TestMigrationStartup::test_lock_deadline_then_restart - Bounded wait fails loudly and restart succeeds

    • Hold the Prisma advisory lock; start a replica with LITELLM_MIGRATION_LOCK_TIMEOUT=12
    • Expect timeout, nonzero exit and unchanged history/data; release the lock and restart successfully
    • Sanity check: observe the stated database boundary and final HTTP/data result; do not treat elapsed sleep or a live process as success
  • tests/e2e/migrations/test_startup.py::TestMigrationStartup::test_fatal_sql - Real SQL failure stops every new replica

    • Add SQL raising MIGRATION_TEST_FATAL and start three replicas
    • Expect no ready endpoint and nonzero exits naming the migration; verify one unfinished error row
    • Sanity check: observe the stated database boundary and final HTTP/data result; do not treat elapsed sleep or a live process as success
  • tests/e2e/migrations/test_startup.py::TestMigrationStartup::test_duplicate_object_does_not_hide_incomplete_sql - Duplicate objects do not prove later SQL completed

    • Precreate migration_existing with row 42; add SQL recreating it before creating migration_effect
    • Expect startup failure, preserved row 42, absent migration_effect and no finished migration record
    • Sanity check: observe the stated database boundary and final HTTP/data result; do not treat elapsed sleep or a live process as success
  • tests/e2e/migrations/test_startup.py::TestMigrationStartup::test_restart_preserves_history_and_data - No-op restarts preserve v1/v2 history

    • Save migration history and existing keys; restart twice, separately for v1 and v2
    • Expect usable proxies after each restart, identical migration history, and every original key retained
    • Sanity check: observe the stated database boundary and final HTTP/data result; do not treat elapsed sleep or a live process as success
  • tests/e2e/migrations/test_startup.py::TestMigrationStartup::test_disabled_migrations - Explicitly disabled migration behavior is preserved

    • Use a migrated database, add a fatal pending script and start with DISABLE_SCHEMA_UPDATE=true
    • Expect usable startup and unchanged migration history
    • Sanity check: observe the stated database boundary and final HTTP/data result; do not treat elapsed sleep or a live process as success
  • tests/e2e/migrations/test_startup.py::TestMigrationStartup::test_insufficient_privileges - Permissions failures do not silently succeed

    • Start against a read-only application role with pending CREATE TABLE SQL
    • Expect a permission error and nonzero exit; verify no migration effect and unchanged history
    • Sanity check: observe the stated database boundary and final HTTP/data result; do not treat elapsed sleep or a live process as success
  • tests/e2e/migrations/test_recovery.py::TestMigrationRecovery::test_owner_and_database_session_crash - Recovery depends on durable SQL proof

    • Block the owner before SQL or before its completion-history update; kill the container and terminate its captured database backend
    • Require backend absence and unfinished history with step count 0/1; replacements must fail loudly for 0 and start for 1 without replaying SQL
    • Sanity check: observe the stated database boundary and final HTTP/data result; do not treat elapsed sleep or a live process as success
  • tests/e2e/migrations/test_recovery.py::TestMigrationRecovery::test_container_owner_crash - Container-only death uses the recorded outcome

    • Repeat both boundaries, kill only the container, release the SQL gate and wait for the captured backend to disappear naturally
    • With no recorded SQL completion, replacements must fail without editing history; after recorded SQL completion, replacements must start with one preserved SQL effect
    • Sanity check: observe the stated database boundary and final HTTP/data result; do not treat elapsed sleep or a live process as success
  • tests/e2e/migrations/test_recovery.py::TestMigrationRecovery::test_remaining_migrations_after_recovery - No readiness before subsequent migrations finish

    • Seed one confirmed unfinished row and gate a second migration; start the recovering owner alone, then two followers once it reaches the next SQL
    • Expect none ready before gate release; afterwards all start for successful SQL or all fail for fatal SQL, preserving the original completion proof
    • Sanity check: observe the stated database boundary and final HTTP/data result; do not treat elapsed sleep or a live process as success
  • tests/e2e/migrations/test_recovery.py::TestMigrationRecovery::test_second_crash_during_recovery_is_atomic - A second interruption cannot erase completion proof

    • Gate the repair update of a confirmed unfinished row, then terminate that backend
    • Expect failed startup and the original unfinished step-1 row unchanged; three later replicas must recover successfully
    • Sanity check: observe the stated database boundary and final HTTP/data result; do not treat elapsed sleep or a live process as success
  • tests/e2e/migrations/test_recovery.py::TestMigrationRecovery::test_competing_recovery_rechecks_stale_failures - Competing repairs recheck database state

    • Hold the coordinator lock until three replicas observe the same unfinished migration, then release it
    • Expect all usable and the original row completed exactly once without replacing its ID or SQL proof
    • Sanity check: observe the stated database boundary and final HTTP/data result; do not treat elapsed sleep or a live process as success
  • tests/e2e/migrations/test_recovery.py::TestMigrationRecovery::test_unproven_history_is_never_repaired - Six ambiguous history variants reject startup

    • Individually set steps=0, steps=2, failure logs, wrong checksum, duplicate unfinished records, or remove the corresponding script
    • Expect nonzero startup and explicit migration name/time and verification guidance; history and existing SQL data must remain unchanged
    • Sanity check: observe the stated database boundary and final HTTP/data result; do not treat elapsed sleep or a live process as success
  • tests/e2e/migrations/test_recovery.py::TestMigrationRecovery::test_coordinator_timeout_preserves_proof - Coordinator timeout is recoverable

    • Hold the coordinator lock; start with a three-second migration lock timeout
    • Expect a named timeout and unchanged proof; after releasing the lock, restart and verify successful atomic completion
    • Sanity check: observe the stated database boundary and final HTTP/data result; do not treat elapsed sleep or a live process as success
  • tests/e2e/migrations/test_legacy.py::TestLegacyMigrations::test_matching_schema_warns_and_starts - Matching legacy schema starts with an honest warning

    • Preserve an existing key and a historical backfill fixture, remove migration history, then start three replicas
    • Expect usable startup and the missing-history/backfill warning; baseline records have step count 0, existing keys remain, and historical stopped_by stays NULL
    • Sanity check: observe the stated database boundary and final HTTP/data result; do not treat elapsed sleep or a live process as success
  • tests/e2e/migrations/test_legacy.py::TestLegacyMigrations::test_unrecognized_legacy_state_is_not_baselined - Unrecognized schemas are not silently adopted

    • Separately try missing history with schema drift, missing history with custom scripts, and an existing empty ledger
    • Expect startup failure with the relevant diagnostic, no pending SQL effect and no fabricated baseline completions
    • Sanity check: observe the stated database boundary and final HTTP/data result; do not treat elapsed sleep or a live process as success
  • tests/e2e/migrations/test_legacy.py::TestLegacyMigrations::test_non_default_schema - Schema selection survives all recovery paths

    • Use schema "migration tenant" and separately perform upgrade, confirmed recovery and matching legacy adoption
    • Verify each expected success/history/data result in that schema; public must not acquire LiteLLM tables or migration history
    • Sanity check: observe the stated database boundary and final HTTP/data result; do not treat elapsed sleep or a live process as success
  • tests/e2e/migrations/test_pooling.py::TestMigrationPooling::test_direct_migrations_with_one_application_backend - Optional pooling does not become the migration route

    • Configure PgBouncer transaction mode with one backend and an application role lacking CREATE; DIRECT_URL uses the migration owner. Try fresh/upgrade/legacy with three replicas and upgrade with six
    • Expect every replica usable; upgrade SQL executes once, and legacy adoption warns with baseline step counts 0
    • Sanity check: observe the stated database boundary and final HTTP/data result; do not treat elapsed sleep or a live process as success

Validation

The complete local Docker suite passed 38 cases without retries in 668.89 seconds. Production and container-test behavior is unchanged by the final formatting and unit-boundary cleanup, verified through parsed-code comparison. The latest image also passed the three-container, 120-second startup proof above. The focused unit/selector/CI-runner checks passed 145 cases, and make check passed

All eight selected deliberately broken images were rejected by their targeted assertions. These checks cover stale lock-contention behavior, checksum and SQL-step evidence, error logs, pending migrations, direct database selection, original history preservation, and legacy warnings

CircleCI pipeline 89544 passed all 38 cases at the latest commit: startup 12, recovery 15, and legacy/pooling 11. All three uploaded verdicts identify source a37f0b4 and the same immutable image, sha256:135066e44390d5cee3553a5b8b424d48ef2d59f357cac2be228e1bae4b269cac. Test-result uploads, diagnostic uploads, and teardown passed. The release verifier accepted this complete result and rejected the earlier canceled workflow. The full release-gate dispatch and verification repeat also passed all 38 cases without retries in pipeline 89545, taking 17 minutes 32 seconds including its shared image build. The real release-gate code dispatched and polled that run, downloaded the private verdicts, and accepted all three suites. Independently inspected JUnit results contain exactly 12/15/11 cases with no failures, errors or skips, and all artifact uploads and cleanup steps succeeded. That repeat rebuilt the same source and used image sha256:5f832b25f9323227a794c973cad2e7f9ee3e5d27a0096798d1da5225861892a6 across all three suites. The prior in-progress pipeline was superseded during iteration; it is not counted as a complete pass. Greptile posted 5/5 for the current head. All required GitHub checks passed, and the shared access-control/JWT canaries passed 28 cases in each of three runs

The six-hour workflow is separate from the normal PR test graph. Release publication is gated by companion project-releaser #239; activation requires merging both changes and provisioning CIRCLECI_API_TOKEN in that repository

Final Attestation

The listed scenarios and deliberate regression checks passed as reported. These checks do not guarantee that every possible production regression is impossible

@yuneng-berri

Copy link
Copy Markdown
Contributor Author

@greptileai Please review the current head, including the migration-workflow HTTPS checkout fix.

@greptile-apps

greptile-apps Bot commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 5/5

The migration behavior appears safe to merge, with one non-blocking CI isolation issue that can run unrelated integration suites during qualification

Findings

  1. P2 Integration Workflow Runs Unnecessarily ▶

Summary

This PR coordinates concurrent v2 migration startup, restricts automatic recovery to histories with durable completion evidence, supports verified legacy-schema adoption, and adds container-level migration qualification

  • Separates lock-contention waiting from ordinary migration failure retries
  • Adds transactional coordination for recovery and legacy baselining
  • Exercises startup, recovery, pooling, and legacy scenarios with packaged Docker images
  • Adds scheduled and parameter-driven CircleCI qualification workflows
  • The latest main-branch merge preserved both migration and general integration workflow additions, but left integration qualification active during migration-only pipelines

Reviews (5) · Last reviewed commit: "Merge remote-tracking branch 'origin/mai..."

@codecov

codecov Bot commented Sep 13, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@yuneng-berri

Copy link
Copy Markdown
Contributor Author

@greptileai Please review the latest head. V2 tests now exercise real methods, and the dedicated migration selector has regression coverage.

@yuneng-berri
yuneng-berri deleted the branch main September 13, 2026 04:53
@yuneng-berri yuneng-berri reopened this Sep 13, 2026
@yuneng-berri
yuneng-berri changed the base branch from litellm_internal_staging to main September 13, 2026 05:03
timeout=prisma_command_timeout(),
env=migration_environment(_get_prisma_env()),
)
except (subprocess.CalledProcessError, subprocess.TimeoutExpired):
@yuneng-berri

Copy link
Copy Markdown
Contributor Author

@greptileai Please review the latest head. This is a merge of origin/main (2480 commits) to clear conflicts in .circleci/config.yml and tests/e2e/conftest.py; both resolutions keep each side's additions rather than dropping either. No behavioral change to the resolver itself.

Comment thread .circleci/config.yml
Comment on lines 3153 to 3164
@@ -3022,6 +3163,7 @@ workflows:
- main
- /litellm_.*/

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.

P2 Integration Workflow Runs Unnecessarily

Migration qualification also runs this unguarded seven-suite integration matrix, adding unrelated CI cost and exposing qualification to unrelated failures

@yuneng-berri
yuneng-berri merged commit 776f8bc into main Sep 20, 2026
127 of 131 checks passed
@yuneng-berri
yuneng-berri deleted the litellm_v2_migration_startup branch September 20, 2026 07:21
pull Bot pushed a commit to abidkhan484/litellm that referenced this pull request Sep 21, 2026
The migrations Job entrypoint (migrations/run.py) has defaulted to v2 with
USE_V2_MIGRATION_RESOLVER=false as the opt-out, and the Helm chart documents
that knob. Proxy startup still defaulted to v1, so the two paths disagreed
about which resolver a deployment runs.

Proxy startup now resolves the same way: v2 unless USE_V2_MIGRATION_RESOLVER
is false or --use_legacy_migration_resolver is passed.

- --use_v2_migration_resolver stays accepted as a no-op that warns, so
  existing commands and Helm values do not fail on an unknown option.
- The dedicated Postgres smoke-test job is repointed at the legacy resolver
  so v1 keeps real-DB proxy-boot coverage, and the two jobs that deselected
  it by name are updated to match the rename.

BerriAI#39178 reverted an earlier flip because two replicas sharing a database
deadlocked (40P01 / P3018) with neither answering /health/liveliness. That
contention is what BerriAI#40932 coordinates, which is why this builds on it.

This branch had an error being deployed

1 failed deployment
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants