Skip to content

fix(proxy-extras): exit the 1.103 migration job by the migrations and fix three index build failures - #51009

Merged
mateo-berri merged 7 commits into
BerriAI:stable/1.103.xfrom
quietjules:litellm_backport_43948_followups_stable_1_103_x
Nov 11, 2026
Merged

mateo-berri merged 7 commits into
BerriAI:stable/1.103.xfrom
quietjules:litellm_backport_43948_followups_stable_1_103_x

Conversation

@quietjules

@quietjules quietjules commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

Handwritten 1-3 sentence description

Follow-up to #50856 on the 1.103 line. The helm migration job passes again whenever the migrations pass, even if the new SpendLogs indexes are not built yet. The index build also works on socket URLs, without psycopg, and with a timeout in the database URL

Details

TLDR

Problem this solves:

  • A helm upgrade fails when only the index build could not finish
  • Without psycopg, the index build crashes the migration job
  • A Prisma ?host= socket URL builds against the wrong host
  • A timeout in the database URL cancels the online index build and the invalid index repair
  • A pooled server connection keeps the build's zero timeouts afterwards
  • The integration lane cannot collect the new boot tests
  • v1.103.11 already shipped proxy-extras 0.4.100.post2, so pip installs would keep these bugs

How it solves it:

  • The job exits by the migrations' result, as 1.103 did before fix(proxy-extras): backport the automatic SpendLogs index build (#43948, #44109, #44203) to stable/1.103.x #50856
  • Without psycopg the build logs a warning and skips
  • Every psycopg connection in proxy-extras keeps a ?host= socket param
  • The build zeroes statement_timeout, lock_timeout, and transaction_timeout for its session, whatever set them, general_settings.database_lock_timeout included. The invalid index check zeroes all but lock_timeout. Both reset only those limits at the end
  • The boot tests get manifest entries, covers markers, and a 240 s timeout
  • proxy-extras goes to 0.4.100.post3

Intentional product change: migrations/run.py exits 0 when the migrations passed but an index is still missing, and the next job run builds it. On a ?host= URL with a partitioned LiteLLM_SpendLogs, prisma db push now stops with the partition error, as on TCP

User Flow

Before: a helm upgrade of a 1.103 deployment fails though every migration applied

  1. They run helm upgrade while another replica holds the migration lock
  2. The job applies the migrations, logs Migration job failed after retries., and exits 1
  3. Helm marks the upgrade failed. A ?host= URL or a URL timeout fails it the same way

After: the same upgrade goes through

  1. They run the same helm upgrade
  2. The job applies the migrations, logs Migration job completed successfully., and exits 0
  3. Helm finishes. With a ?host= URL or a URL timeout, the job builds both indexes on the first run

Relevant issues

Follow-up to #50856, the backport of #43948. main and stable/1.104.x have the same gaps

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

Delays in PR merge?

If you're seeing a delay in your PR being merged, ping the LiteLLM Team on Slack (#pr-review).

Screenshots / Proof of Fix

Each case runs the helm Job's entrypoint, python migrations/run.py with USE_V2_MIGRATION_RESOLVER=true, on both trees against a fresh Postgres 18.6 database

run_legs.py and how to run it

The helm image always has psycopg, so no_psycopg and the CLI and proxy runs below cover pip installs. no_psycopg runs on a fresh venv with litellm[proxy]==1.103.10 and prisma==0.11.0 and no psycopg. The other cases run on the branch's make bootstrap venv. socket_host tests libpq host resolution, which works the same inside a container

Each block below is the script's printed output for that leg, with only the local checkout path replaced. It prints each log line that matches SHOWN, then the index state

uv venv --python 3.13 nopg_venv
uv pip install --python nopg_venv/bin/python 'litellm[proxy]==1.103.10' prisma==0.11.0
BEFORE_TREE=<litellm at 8f44f66> AFTER_TREE=<litellm at c15ffdb> \
  JOB_PYTHON=<litellm at c15ffdb>/.venv/bin/python NO_PSYCOPG_PYTHON=nopg_venv/bin/python \
  <litellm at c15ffdb>/.venv/bin/python run_legs.py

The url_transaction_timeout and url_transaction_timeout_repair cases ran again on their own, run_legs.py <case>, with a 2000 ms timeout and a 5 s hold. In the full run their 200 ms timeout also cancelled prisma migrate deploy on a loaded box before the index work began. The after cases ran again at c15ffdb with SIDES=after

import os, subprocess, sys, threading, time, uuid
import psycopg

Q = os.path.dirname(os.path.abspath(__file__))
TREES = {"before": os.environ["BEFORE_TREE"], "after": os.environ["AFTER_TREE"]}
PY = os.environ["JOB_PYTHON"]
NO_PSYCOPG_PY = os.environ["NO_PSYCOPG_PYTHON"]
ADMIN = "postgresql://mateo@localhost:5432/postgres"
KEY = int.from_bytes(b"llm_mig2", "big")
INDEXES = ("LiteLLM_SpendLogs_api_key_startTime_idx", "LiteLLM_SpendLogs_litellm_call_id_idx")
HEALTH_INDEX = "LiteLLM_HealthCheckTable_model_id_model_name_checked_at_idx"
SHOWN = ("request-log", "Migration job", "Could not", "not in place", "psycopg", "Error", "timeout", "Building index")


def scratch_db():
    name = f"qa_r2_{uuid.uuid4().hex[:8]}"
    with psycopg.connect(ADMIN, autocommit=True) as c:
        c.execute(f'CREATE DATABASE "{name}"')
    return name


def drop_db(name):
    with psycopg.connect(ADMIN, autocommit=True) as c:
        c.execute(f'DROP DATABASE IF EXISTS "{name}" WITH (FORCE)')


def run_job(tree, url, label, python=PY, show=True):
    env = {k: v for k, v in os.environ.items() if not k.startswith("DATABASE_")}
    env.update(DATABASE_URL=url, PYTHONPATH=f"{tree}/litellm-proxy-extras", USE_V2_MIGRATION_RESOLVER="true")
    started = time.monotonic()
    p = subprocess.run([python, f"{tree}/migrations/run.py"], env=env, cwd=tree, capture_output=True, text=True, timeout=900)
    secs = time.monotonic() - started
    log = (p.stdout + p.stderr).splitlines()
    open(f"{Q}/{label}.log", "w").write("\n".join(log))
    if not show:
        return p.returncode
    print(f"--- {label}: exit {p.returncode} in {secs:.1f}s", flush=True)
    for line in (line for line in log if any(s in line for s in SHOWN)):
        print("   ", line[:240], flush=True)
    return p.returncode


def index_state(name):
    with psycopg.connect(f"{ADMIN.rsplit('/', 1)[0]}/{name}") as c:
        return c.execute(
            "SELECT c.relname, i.indisvalid FROM pg_index i JOIN pg_class c ON c.oid = i.indexrelid WHERE c.relname = ANY(%s) ORDER BY 1",
            (list(INDEXES) + [HEALTH_INDEX],),
        ).fetchall()


def migrate_only(name):
    run_job(TREES["after"], f"postgresql://mateo@localhost:5432/{name}", f"setup_{name}", show=False)
    with psycopg.connect(f"postgresql://mateo@localhost:5432/{name}", autocommit=True) as c:
        for index in INDEXES:
            c.execute(f'DROP INDEX IF EXISTS "{index}"')


def leave_health_index_invalid(name):
    url = f"postgresql://mateo@localhost:5432/{name}"
    with psycopg.connect(url, autocommit=True) as c:
        c.execute(f'DROP INDEX "{HEALTH_INDEX}"')
    pin = psycopg.connect(url)
    pin.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ")
    pin.execute('SELECT count(*) FROM "LiteLLM_HealthCheckTable"').fetchone()
    with psycopg.connect(url, autocommit=True) as builder:
        builder.execute("SET statement_timeout = '1s'")
        try:
            builder.execute(
                f'CREATE INDEX CONCURRENTLY "{HEALTH_INDEX}" ON "LiteLLM_HealthCheckTable" '
                '("model_id", "model_name", "checked_at" DESC)'
            )
        except psycopg.errors.QueryCanceled:
            pass
    pin.close()


def with_old_snapshot_until_build_waits(name, run, waiting_query="CREATE INDEX CONCURRENTLY%%", hold=3):
    pin = psycopg.connect(f"postgresql://mateo@localhost:5432/{name}")
    pin.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ")
    pin.execute('SELECT count(*) FROM "LiteLLM_SpendLogs"').fetchone()
    done = threading.Event()

    def release_after_build_starts():
        with psycopg.connect(ADMIN, autocommit=True) as watcher:
            while not done.is_set():
                seen = watcher.execute(
                    "SELECT 1 FROM pg_stat_activity WHERE datname = %s AND query ILIKE %s",
                    (name, waiting_query.replace("%%", "%")),
                ).fetchone()
                if seen:
                    print(f"    build started while the old snapshot is pinned, releasing it in {hold}s", flush=True)
                    done.wait(hold)
                    break
                done.wait(0.05)
        pin.close()

    releaser = threading.Thread(target=release_after_build_starts)
    releaser.start()
    try:
        return run()
    finally:
        done.set()
        releaser.join()


def leg(side, case):
    tree = TREES[side]
    name = scratch_db()
    url = f"postgresql://mateo@localhost:5432/{name}"
    label = f"{side}_{case}"
    try:
        if case == "lock_held":
            with psycopg.connect(url, autocommit=True) as other_replica:
                other_replica.execute("SELECT pg_advisory_lock(%s)", (KEY,))
                code = run_job(tree, url, label)
        elif case == "no_psycopg":
            code = run_job(tree, url, label, python=NO_PSYCOPG_PY)
        elif case == "socket_host":
            code = run_job(tree, f"postgresql://mateo@cloudsql.invalid:5432/{name}?host=/tmp", label)
        elif case == "url_lock_timeout":
            migrate_only(name)
            code = with_old_snapshot_until_build_waits(
                name, lambda: run_job(tree, f"{url}?options=-c%20lock_timeout%3D200", label)
            )
        elif case == "url_transaction_timeout":
            migrate_only(name)
            code = with_old_snapshot_until_build_waits(
                name, lambda: run_job(tree, f"{url}?options=-c%20transaction_timeout%3D2000", label), hold=5
            )
        elif case == "url_transaction_timeout_repair":
            run_job(TREES["after"], url, f"setup_{name}", show=False)
            leave_health_index_invalid(name)
            print(f"    before the job: {index_state(name)}", flush=True)
            code = with_old_snapshot_until_build_waits(
                name, lambda: run_job(tree, f"{url}?options=-c%20transaction_timeout%3D2000", label), "REINDEX%%", 5
            )
        print(f"    indexes: {index_state(name)}", flush=True)
        return code
    finally:
        drop_db(name)


SIDES = tuple(os.environ.get("SIDES", "before,after").split(","))
cases = sys.argv[1:] or [
    "lock_held", "no_psycopg", "socket_host", "url_lock_timeout", "url_transaction_timeout",
    "url_transaction_timeout_repair",
]
summary = {f"{side}_{case}": leg(side, case) for case in cases for side in SIDES}
summary.update(
    {
        f"{side}_migrations_fail": run_job(TREES[side], "postgresql://mateo@localhost:1/qa_r2_unreachable", f"{side}_migrations_fail")
        for side in SIDES
    }
)
print("SUMMARY", summary, flush=True)
Case Before (8f44f66) After (c15ffdb)
lock_held exit 1, job failed exit 0
no_psycopg exit 1, import error exit 0, warning
socket_host exit 1, wrong host exit 0, indexes valid
url_lock_timeout exit 1, build cancelled exit 0, indexes valid
url_transaction_timeout exit 1, session closed exit 0, indexes valid
url_transaction_timeout_repair exit 0, index left INVALID exit 0, index repaired
migrations_fail exit 1 exit 1
Before (8f44f66), output per case

lock_held

  1. python run_legs.py, another session holds the migration lock
  2. Exit 1, Some request-log indexes are not in place yet then Migration job failed after retries.
--- before_lock_held: exit 1 in 157.2s
    2026-11-10 17:46:33,152 - litellm_proxy_extras - INFO - Preparing the Prisma CLI toolchain (timeout 600.0s)
    Applying migration `20260605182307_add_timeout_to_mcp_server_table`
      └─ 20260605182307_add_timeout_to_mcp_server_table/
    2026-11-10 17:48:30,844 - litellm_proxy_extras - INFO - Another process holds the migration lock, leaving the request-log indexes to the next index build
    2026-11-10 17:48:30,871 - litellm_proxy_extras - INFO - Another process holds the migration lock, leaving the request-log indexes to the next index build
    2026-11-10 17:48:30,882 - litellm_proxy_extras - WARNING - Some request-log indexes are not in place yet, leaving them for the next index build
    2026-11-10 17:48:30,893 - litellm_proxy_extras - ERROR - Migration job failed after retries.
    indexes: [('LiteLLM_HealthCheckTable_model_id_model_name_checked_at_idx', True)]

no_psycopg

  1. python run_legs.py on the psycopg-free venv
  2. Exit 1, ModuleNotFoundError: No module named 'psycopg'
--- before_no_psycopg: exit 1 in 31.4s
    2026-11-10 17:50:56,922 - litellm_proxy_extras - INFO - Preparing the Prisma CLI toolchain (timeout 600.0s)
    Applying migration `20260605182307_add_timeout_to_mcp_server_table`
      └─ 20260605182307_add_timeout_to_mcp_server_table/
    2026-11-10 17:51:19,559 - litellm_proxy_extras - WARNING - psycopg is not installed; skipping the invalid index check. Install the litellm[extra_proxy] extra, which includes psycopg.
        import psycopg
    ModuleNotFoundError: No module named 'psycopg'
    indexes: [('LiteLLM_HealthCheckTable_model_id_model_name_checked_at_idx', True)]

socket_host

  1. python run_legs.py, postgresql://mateo@cloudsql.invalid:5432/<db>?host=/tmp
  2. Exit 1, failed to resolve host 'cloudsql.invalid' for the invalid index check and the build
--- before_socket_host: exit 1 in 133.4s
    2026-11-10 17:52:57,569 - litellm_proxy_extras - INFO - Preparing the Prisma CLI toolchain (timeout 600.0s)
    Applying migration `20260605182307_add_timeout_to_mcp_server_table`
      └─ 20260605182307_add_timeout_to_mcp_server_table/
    2026-11-10 17:54:27,696 - litellm_proxy_extras - WARNING - Could not check for invalid indexes, will retry on the next database setup run. Error: failed to resolve host 'cloudsql.invalid': [Errno 8] nodename nor servname provided, or not kn
    2026-11-10 17:54:27,758 - litellm_proxy_extras - WARNING - Could not build the request-log indexes, leaving them for the next index build: failed to resolve host 'cloudsql.invalid': [Errno 8] nodename nor servname provided, or not known
    2026-11-10 17:54:27,760 - litellm_proxy_extras - ERROR - Migration job failed after retries.
    indexes: [('LiteLLM_HealthCheckTable_model_id_model_name_checked_at_idx', True)]

url_lock_timeout

  1. python run_legs.py, ?options=-c%20lock_timeout%3D200, with an old snapshot held 3 s into the build
  2. Exit 1, canceling statement due to lock timeout, and LiteLLM_SpendLogs_api_key_startTime_idx is left INVALID
    build started while the old snapshot is pinned, releasing it in 3s
--- before_url_lock_timeout: exit 1 in 71.9s
    2026-11-10 18:00:48,489 - litellm_proxy_extras - INFO - Preparing the Prisma CLI toolchain (timeout 600.0s)
    2026-11-10 18:01:35,954 - litellm_proxy_extras - INFO - Building index LiteLLM_SpendLogs_api_key_startTime_idx on LiteLLM_SpendLogs concurrently
    2026-11-10 18:01:37,201 - litellm_proxy_extras - WARNING - Could not build the request-log indexes, leaving them for the next index build: canceling statement due to lock timeout
    2026-11-10 18:01:37,217 - litellm_proxy_extras - ERROR - Migration job failed after retries.
    indexes: [('LiteLLM_HealthCheckTable_model_id_model_name_checked_at_idx', True), ('LiteLLM_SpendLogs_api_key_startTime_idx', False)]

url_transaction_timeout

  1. python run_legs.py, ?options=-c%20transaction_timeout%3D2000, with an old snapshot held 5 s into the build
  2. Exit 1, the connection is closed, and LiteLLM_SpendLogs_api_key_startTime_idx is left INVALID
    build started while the old snapshot is pinned, releasing it in 5s
--- before_url_transaction_timeout: exit 1 in 81.9s
    2026-11-10 18:38:17,002 - litellm_proxy_extras - INFO - Preparing the Prisma CLI toolchain (timeout 600.0s)
    2026-11-10 18:39:08,319 - litellm_proxy_extras - INFO - Building index LiteLLM_SpendLogs_api_key_startTime_idx on LiteLLM_SpendLogs concurrently
    2026-11-10 18:39:10,879 - litellm_proxy_extras - WARNING - Could not build the request-log indexes, leaving them for the next index build: the connection is closed
    2026-11-10 18:39:10,894 - litellm_proxy_extras - ERROR - Migration job failed after retries.
    indexes: [('LiteLLM_HealthCheckTable_model_id_model_name_checked_at_idx', True), ('LiteLLM_SpendLogs_api_key_startTime_idx', False)]

url_transaction_timeout_repair

  1. python run_legs.py, a migrated database whose LiteLLM_HealthCheckTable_model_id_model_name_checked_at_idx an interrupted build left INVALID, ?options=-c%20transaction_timeout%3D2000, with an old snapshot held 5 s into the repair
  2. Exit 0, Could not repair invalid index then the connection is closed, and the index stays INVALID
    before the job: [('LiteLLM_HealthCheckTable_model_id_model_name_checked_at_idx', False), ('LiteLLM_SpendLogs_api_key_startTime_idx', True), ('LiteLLM_SpendLogs_litellm_call_id_idx', True)]
    build started while the old snapshot is pinned, releasing it in 5s
--- before_url_transaction_timeout_repair: exit 0 in 99.4s
    2026-11-10 18:25:39,622 - litellm_proxy_extras - INFO - Preparing the Prisma CLI toolchain (timeout 600.0s)
    2026-11-10 18:26:32,555 - litellm_proxy_extras - WARNING - Could not repair invalid index public.LiteLLM_HealthCheckTable_model_id_model_name_checked_at_idx, will retry on the next database setup run. If this keeps happening, run `REINDEX I
    2026-11-10 18:26:32,563 - litellm_proxy_extras - WARNING - Could not check for invalid indexes, will retry on the next database setup run. Error: the connection is closed
    2026-11-10 18:26:33,341 - litellm_proxy_extras - INFO - Migration job completed successfully.
    indexes: [('LiteLLM_HealthCheckTable_model_id_model_name_checked_at_idx', False), ('LiteLLM_SpendLogs_api_key_startTime_idx', True), ('LiteLLM_SpendLogs_litellm_call_id_idx', True)]

migrations_fail

  1. Runs at the end of every python run_legs.py, localhost:1
  2. Exit 1, P1001: Can't reach database server
--- before_migrations_fail: exit 1 in 62.2s
    2026-11-10 18:20:33,887 - litellm_proxy_extras - INFO - Preparing the Prisma CLI toolchain (timeout 600.0s)
            timeout=deploy_timeout,
        raise subprocess.CalledProcessError(process.returncode, process.args, out, err)
    subprocess.CalledProcessError: Command '('<litellm at c15ffdb>/.venv/bin/python', '-m', 'prisma', 'migrate', 'deploy')' returned non-zero exit status 1.
        raise RuntimeError(
    RuntimeError: Database migration failed and cannot be auto-recovered. Manual intervention required.
    Error: P1001: Can't reach database server at `localhost`:`1`
After (c15ffdb), output per case

lock_held

  1. python run_legs.py, another session holds the migration lock
  2. Exit 0, leaving the request-log indexes to the next index build then Migration job completed successfully.
--- after_lock_held: exit 0 in 61.0s
    2026-11-10 20:39:53,758 - litellm_proxy_extras - INFO - Preparing the Prisma CLI toolchain (timeout 600.0s)
    Applying migration `20260605182307_add_timeout_to_mcp_server_table`
      └─ 20260605182307_add_timeout_to_mcp_server_table/
    2026-11-10 20:40:32,059 - litellm_proxy_extras - INFO - Another process holds the migration lock, leaving the request-log indexes to the next index build
    2026-11-10 20:40:32,060 - litellm_proxy_extras - INFO - Another process holds the migration lock, leaving the request-log indexes to the next index build
    2026-11-10 20:40:32,060 - litellm_proxy_extras - WARNING - Some request-log indexes are not in place yet, leaving them for the next index build
    2026-11-10 20:40:32,060 - litellm_proxy_extras - INFO - Migration job completed successfully.
    indexes: [('LiteLLM_HealthCheckTable_model_id_model_name_checked_at_idx', True)]

no_psycopg

  1. python run_legs.py on the psycopg-free venv
  2. Exit 0, psycopg is not installed; skipping the request-log index build
--- after_no_psycopg: exit 0 in 24.7s
    2026-11-10 20:40:59,410 - litellm_proxy_extras - INFO - Preparing the Prisma CLI toolchain (timeout 600.0s)
    Applying migration `20260605182307_add_timeout_to_mcp_server_table`
      └─ 20260605182307_add_timeout_to_mcp_server_table/
    2026-11-10 20:41:11,312 - litellm_proxy_extras - WARNING - psycopg is not installed; skipping the invalid index check. Install the litellm[extra_proxy] extra, which includes psycopg.
    2026-11-10 20:41:11,313 - litellm_proxy_extras - WARNING - psycopg is not installed; skipping the request-log index build. Install the litellm[extra_proxy] extra, which includes psycopg.
    2026-11-10 20:41:11,313 - litellm_proxy_extras - INFO - Migration job completed successfully.
    indexes: [('LiteLLM_HealthCheckTable_model_id_model_name_checked_at_idx', True)]

socket_host

  1. python run_legs.py, postgresql://mateo@cloudsql.invalid:5432/<db>?host=/tmp
  2. Exit 0, and both indexes are valid
--- after_socket_host: exit 0 in 63.6s
    2026-11-10 20:41:36,787 - litellm_proxy_extras - INFO - Preparing the Prisma CLI toolchain (timeout 600.0s)
    Applying migration `20260605182307_add_timeout_to_mcp_server_table`
      └─ 20260605182307_add_timeout_to_mcp_server_table/
    2026-11-10 20:42:12,182 - litellm_proxy_extras - INFO - Building index LiteLLM_SpendLogs_api_key_startTime_idx on LiteLLM_SpendLogs concurrently
    2026-11-10 20:42:14,197 - litellm_proxy_extras - INFO - Building index LiteLLM_SpendLogs_litellm_call_id_idx on LiteLLM_SpendLogs concurrently
    2026-11-10 20:42:16,210 - litellm_proxy_extras - INFO - Migration job completed successfully.
    indexes: [('LiteLLM_HealthCheckTable_model_id_model_name_checked_at_idx', True), ('LiteLLM_SpendLogs_api_key_startTime_idx', True), ('LiteLLM_SpendLogs_litellm_call_id_idx', True)]

url_lock_timeout

  1. python run_legs.py, ?options=-c%20lock_timeout%3D200, with an old snapshot held 3 s into the build
  2. Exit 0, and both indexes are valid
    build started while the old snapshot is pinned, releasing it in 3s
--- after_url_lock_timeout: exit 0 in 41.7s
    2026-11-10 20:43:09,811 - litellm_proxy_extras - INFO - Preparing the Prisma CLI toolchain (timeout 600.0s)
    2026-11-10 20:43:31,560 - litellm_proxy_extras - INFO - Building index LiteLLM_SpendLogs_api_key_startTime_idx on LiteLLM_SpendLogs concurrently
    2026-11-10 20:43:36,581 - litellm_proxy_extras - INFO - Building index LiteLLM_SpendLogs_litellm_call_id_idx on LiteLLM_SpendLogs concurrently
    2026-11-10 20:43:38,636 - litellm_proxy_extras - INFO - Migration job completed successfully.
    indexes: [('LiteLLM_HealthCheckTable_model_id_model_name_checked_at_idx', True), ('LiteLLM_SpendLogs_api_key_startTime_idx', True), ('LiteLLM_SpendLogs_litellm_call_id_idx', True)]

url_transaction_timeout

  1. python run_legs.py, ?options=-c%20transaction_timeout%3D2000, with an old snapshot held 5 s into the build
  2. Exit 0, and both indexes are valid
    build started while the old snapshot is pinned, releasing it in 5s
--- after_url_transaction_timeout: exit 0 in 38.7s
    2026-11-10 20:44:44,998 - litellm_proxy_extras - INFO - Preparing the Prisma CLI toolchain (timeout 600.0s)
    2026-11-10 20:45:02,768 - litellm_proxy_extras - INFO - Building index LiteLLM_SpendLogs_api_key_startTime_idx on LiteLLM_SpendLogs concurrently
    2026-11-10 20:45:09,816 - litellm_proxy_extras - INFO - Building index LiteLLM_SpendLogs_litellm_call_id_idx on LiteLLM_SpendLogs concurrently
    2026-11-10 20:45:11,859 - litellm_proxy_extras - INFO - Migration job completed successfully.
    indexes: [('LiteLLM_HealthCheckTable_model_id_model_name_checked_at_idx', True), ('LiteLLM_SpendLogs_api_key_startTime_idx', True), ('LiteLLM_SpendLogs_litellm_call_id_idx', True)]

url_transaction_timeout_repair

  1. python run_legs.py, a migrated database whose LiteLLM_HealthCheckTable_model_id_model_name_checked_at_idx an interrupted build left INVALID, ?options=-c%20transaction_timeout%3D2000, with an old snapshot held 5 s into the repair
  2. Exit 0, and the invalid index check rebuilds the index valid
    before the job: [('LiteLLM_HealthCheckTable_model_id_model_name_checked_at_idx', False), ('LiteLLM_SpendLogs_api_key_startTime_idx', True), ('LiteLLM_SpendLogs_litellm_call_id_idx', True)]
    build started while the old snapshot is pinned, releasing it in 5s
--- after_url_transaction_timeout_repair: exit 0 in 55.6s
    2026-11-10 20:46:12,434 - litellm_proxy_extras - INFO - Preparing the Prisma CLI toolchain (timeout 600.0s)
    2026-11-10 20:46:53,570 - litellm_proxy_extras - INFO - Migration job completed successfully.
    indexes: [('LiteLLM_HealthCheckTable_model_id_model_name_checked_at_idx', True), ('LiteLLM_SpendLogs_api_key_startTime_idx', True), ('LiteLLM_SpendLogs_litellm_call_id_idx', True)]

migrations_fail

  1. Runs at the end of every python run_legs.py, localhost:1
  2. Exit 1, unchanged
--- after_migrations_fail: exit 1 in 54.4s
    2026-11-10 20:47:27,163 - litellm_proxy_extras - INFO - Preparing the Prisma CLI toolchain (timeout 600.0s)
            timeout=deploy_timeout,
        raise subprocess.CalledProcessError(process.returncode, process.args, out, err)
    subprocess.CalledProcessError: Command '('<litellm at c15ffdb>/.venv/bin/python', '-m', 'prisma', 'migrate', 'deploy')' returned non-zero exit status 1.
        raise RuntimeError(
    RuntimeError: Database migration failed and cannot be auto-recovered. Manual intervention required.
    Error: P1001: Can't reach database server at `localhost`:`1`
Run summary
SUMMARY {'before_lock_held': 1, 'after_lock_held': 0, 'before_no_psycopg': 1, 'after_no_psycopg': 0, 'before_socket_host': 1, 'after_socket_host': 0, 'before_url_lock_timeout': 1, 'after_url_lock_timeout': 0, 'before_url_transaction_timeout': 1, 'after_url_transaction_timeout': 0, 'before_url_transaction_timeout_repair': 0, 'after_url_transaction_timeout_repair': 0, 'before_migrations_fail': 1, 'after_migrations_fail': 1}

Migration-only CLI and serving proxy without psycopg

Flow Before (8f44f66) After (df1d862)
--skip_server_startup exit 1, import error exit 0, warning
Serving proxy thread traceback warning
/health/readiness, /v1/models 200, 200 200, 200
Commands, config, and output

c15ffdb changes only which settings the index build and the invalid index check reset when their sessions end, and 5725752 changes only version strings. These legs never reach that reset with a different outcome, so they carry from df1d862

litellm --config nopg_proxy.yaml --use_v2_migration_resolver, with and without --skip_server_startup, on the psycopg-free venv against a fresh database. The litellm package is the same on both sides, and only litellm-proxy-extras comes from each tree

nopg_venv/bin/python -m prisma generate --schema=<litellm at df1d862>/litellm/proxy/schema.prisma
BEFORE_TREE=<litellm at 8f44f66> AFTER_TREE=<litellm at df1d862> LITELLM_TREE=<litellm at df1d862> \
  NO_PSYCOPG_PYTHON=nopg_venv/bin/python <litellm at df1d862>/.venv/bin/python nopg_cli_proxy.py
model_list:
  - model_name: fake-gpt
    litellm_params:
      model: openai/fake-gpt
      api_key: fake-key
      api_base: http://127.0.0.1:9/v1
general_settings:
  master_key: sk-qa-1234
import os, socket, subprocess, sys, time, urllib.request, uuid
import psycopg

Q = os.path.dirname(os.path.abspath(__file__))
TREES = {"before": os.environ["BEFORE_TREE"], "after": os.environ["AFTER_TREE"]}
LITELLM = os.environ["LITELLM_TREE"]
PY = os.environ["NO_PSYCOPG_PYTHON"]
ADMIN = "postgresql://mateo@localhost:5432/postgres"
SHOWN = ("psycopg", "request-log", "Traceback", "Error", "index", "Application startup complete", "Uvicorn running")


def scratch_db():
    name = f"qa_nopg_{uuid.uuid4().hex[:6]}"
    with psycopg.connect(ADMIN, autocommit=True) as c:
        c.execute(f'CREATE DATABASE "{name}"')
    return name


def drop_db(name):
    with psycopg.connect(ADMIN, autocommit=True) as c:
        c.execute(f'DROP DATABASE IF EXISTS "{name}" WITH (FORCE)')


def env_for(side, name):
    env = {k: v for k, v in os.environ.items() if not k.startswith("DATABASE_")}
    env.update(
        DATABASE_URL=f"postgresql://mateo@localhost:5432/{name}",
        PYTHONPATH=f"{LITELLM}:{TREES[side]}/litellm-proxy-extras",
    )
    return env


def show(label, text):
    for line in (line for line in text.splitlines() if any(s in line for s in SHOWN)):
        print("   ", line[:240], flush=True)


def free_port():
    while True:
        port = 20000 + uuid.uuid4().int % 12768
        with socket.socket() as s:
            if s.connect_ex(("127.0.0.1", port)) != 0:
                return port


def cli_leg(side):
    name = scratch_db()
    try:
        args = [PY, f"{LITELLM}/litellm/proxy/proxy_cli.py", "--config", f"{Q}/nopg_proxy.yaml",
                "--use_v2_migration_resolver", "--skip_server_startup"]
        p = subprocess.run(args, env=env_for(side, name), cwd=Q, capture_output=True, text=True, timeout=900)
        out = p.stdout + p.stderr
        open(f"{Q}/{side}_nopg_cli.log", "w").write(out)
        print(f"--- {side} cli: litellm --skip_server_startup exit {p.returncode}", flush=True)
        show(side, out)
    finally:
        drop_db(name)


def get(url):
    request = urllib.request.Request(url, headers={"Authorization": "Bearer sk-qa-1234"})
    try:
        with urllib.request.urlopen(request, timeout=5) as r:
            return r.status, r.read().decode()[:160]
    except Exception as e:
        return None, f"{type(e).__name__}: {e}"[:160]


def proxy_leg(side):
    name = scratch_db()
    port = free_port()
    log_path = f"{Q}/{side}_nopg_proxy.log"
    args = [PY, f"{LITELLM}/litellm/proxy/proxy_cli.py", "--config", f"{Q}/nopg_proxy.yaml",
            "--use_v2_migration_resolver", "--port", str(port)]
    with open(log_path, "w") as log:
        proc = subprocess.Popen(args, env=env_for(side, name), cwd=Q, stdout=log, stderr=subprocess.STDOUT, text=True)
    try:
        deadline = time.monotonic() + 300
        status, body = None, ""
        while time.monotonic() < deadline and proc.poll() is None:
            status, body = get(f"http://127.0.0.1:{port}/health/readiness")
            if status == 200:
                break
            time.sleep(2)
        time.sleep(5)
        print(f"--- {side} proxy on port {port}: process {'running' if proc.poll() is None else f'exited {proc.returncode}'}", flush=True)
        print(f"    GET /health/readiness -> {status} {body[:100]}", flush=True)
        print(f"    GET /v1/models -> {' '.join(map(str, get(f'http://127.0.0.1:{port}/v1/models')))[:160]}", flush=True)
        show(side, open(log_path).read())
    finally:
        proc.terminate()
        try:
            proc.wait(timeout=20)
        except subprocess.TimeoutExpired:
            proc.kill()
        drop_db(name)


for leg in sys.argv[1:] or ["cli", "proxy"]:
    for side in ("before", "after"):
        (cli_leg if leg == "cli" else proxy_leg)(side)
--- before cli: litellm --skip_server_startup exit 1
    2026-11-10 17:47:14,203 - litellm_proxy_extras - WARNING - psycopg is not installed; skipping the invalid index check. Install the litellm[extra_proxy] extra, which includes psycopg.
    Traceback (most recent call last):
        setup_ok: Final = _setup_database_with_request_log_indexes(
      File "<litellm at df1d862>/litellm/proxy/proxy_cli.py", line 693, in _setup_database_with_request_log_indexes
      File "<litellm at df1d862>/litellm/proxy/db/prisma_client.py", line 989, in build_request_log_indexes
        return ProxyExtrasDBManager.build_request_log_indexes()
      File "<litellm at 8f44f66>/litellm-proxy-extras/litellm_proxy_extras/utils.py", line 1315, in build_request_log_indexes
      File "<litellm at 8f44f66>/litellm-proxy-extras/litellm_proxy_extras/request_log_indexes.py", line 168, in ensure_request_log_in
        import psycopg
    ModuleNotFoundError: No module named 'psycopg'
--- after cli: litellm --skip_server_startup exit 0
    2026-11-10 17:50:14,107 - litellm_proxy_extras - WARNING - psycopg is not installed; skipping the invalid index check. Install the litellm[extra_proxy] extra, which includes psycopg.
    2026-11-10 17:50:14,112 - litellm_proxy_extras - WARNING - psycopg is not installed; skipping the request-log index build. Install the litellm[extra_proxy] extra, which includes psycopg.
--- before proxy on port 26132: process running
    GET /health/readiness -> 200 {"status":"healthy","db":"connected"}
    GET /v1/models -> 200 {"data":[{"id":"fake-gpt","object":"model","created":1677610602,"owned_by":"openai"}],"object":"list"}
    2026-11-10 17:51:00,291 - litellm_proxy_extras - WARNING - psycopg is not installed; skipping the invalid index check. Install the litellm[extra_proxy] extra, which includes psycopg.
    Exception in thread litellm-request-log-indexes:
    Traceback (most recent call last):
      File "<litellm at 8f44f66>/litellm-proxy-extras/litellm_proxy_extras/utils.py", line 1315, in build_request_log_indexes
      File "<litellm at 8f44f66>/litellm-proxy-extras/litellm_proxy_extras/request_log_indexes.py", line 168, in ensure_request_log_in
        import psycopg
    ModuleNotFoundError: No module named 'psycopg'
    INFO:     Application startup complete.
    INFO:     Uvicorn running on http://0.0.0.0:26132 (Press CTRL+C to quit)
--- after proxy on port 21444: process running
    GET /health/readiness -> 200 {"status":"healthy","db":"connected"}
    GET /v1/models -> 200 {"data":[{"id":"fake-gpt","object":"model","created":1677610602,"owned_by":"openai"}],"object":"list"}
    2026-11-10 17:51:58,269 - litellm_proxy_extras - WARNING - psycopg is not installed; skipping the invalid index check. Install the litellm[extra_proxy] extra, which includes psycopg.
    2026-11-10 17:51:58,285 - litellm_proxy_extras - WARNING - psycopg is not installed; skipping the request-log index build. Install the litellm[extra_proxy] extra, which includes psycopg.
    INFO:     Application startup complete.
    INFO:     Uvicorn running on http://0.0.0.0:21444 (Press CTRL+C to quit)

Other ?host= socket callers

Call Before (8f44f66) After (df1d862)
Partition check False, no connection True
Migration ledger read None 184 rows
prisma db push setup push fails on the key partition error
socket_callers.py and output

c15ffdb changes only which settings the index build and the invalid index check reset when their sessions end, and 5725752 changes only version strings. These legs never reach that reset with a different outcome, so they carry from df1d862

A fresh database is migrated over TCP and partitioned with db_scripts/partition_spend_logs.sql. Each tree then calls the socket-reachable checks with DATABASE_URL=postgresql://mateo@cloudsql.invalid:5432/<db>?host=/tmp

import os, subprocess, sys, uuid
import psycopg

TREES = {"before": os.environ["BEFORE_TREE"], "after": os.environ["AFTER_TREE"]}
PY = os.environ["JOB_PYTHON"]
ADMIN = "postgresql://mateo@localhost:5432/postgres"
PROBE = r'''
import json
from litellm_proxy_extras.utils import ProxyExtrasDBManager as M
ledger = M._read_migration_ledger("SELECT count(*) FROM {}", ())
print("spend_logs_is_partitioned:", M.spend_logs_is_partitioned(), flush=True)
print("migration ledger rows:", ledger[0] if ledger else ledger, flush=True)
try:
    print("setup_database(use_migrate=False):", M.setup_database(use_migrate=False), flush=True)
except Exception as e:
    print("setup_database(use_migrate=False) raised", type(e).__name__ + ":", str(e)[:150], flush=True)
'''


def partitioned_db(side):
    name = f"qa_sock_{side}_{uuid.uuid4().hex[:6]}"
    with psycopg.connect(ADMIN, autocommit=True) as c:
        c.execute(f'CREATE DATABASE "{name}"')
    tcp = f"postgresql://mateo@localhost:5432/{name}"
    env = {k: v for k, v in os.environ.items() if not k.startswith("DATABASE_")}
    env.update(DATABASE_URL=tcp, PYTHONPATH=f"{TREES['after']}/litellm-proxy-extras", USE_V2_MIGRATION_RESOLVER="true")
    subprocess.run([PY, f"{TREES['after']}/migrations/run.py"], env=env, cwd=TREES["after"], capture_output=True, check=True)
    subprocess.run(
        ["psql", tcp, "-q", "-v", "ON_ERROR_STOP=1", "-f", f"{TREES['after']}/db_scripts/partition_spend_logs.sql"],
        check=True, capture_output=True,
    )
    return name


def probe(side):
    name = partitioned_db(side)
    url = f"postgresql://mateo@cloudsql.invalid:5432/{name}?host=/tmp"
    env = {k: v for k, v in os.environ.items() if not k.startswith("DATABASE_")}
    env.update(DATABASE_URL=url, PYTHONPATH=f"{TREES[side]}/litellm-proxy-extras")
    print(f"--- {side}: DATABASE_URL={url.replace(name, '<scratch db>')}", flush=True)
    p = subprocess.run([PY, "-c", PROBE], env=env, cwd=TREES[side], capture_output=True, text=True, timeout=600)
    shown = ("spend_logs_is_partitioned", "migration ledger", "setup_database", "Error:", "partitioned", "primary key")
    for line in (p.stdout + p.stderr).splitlines():
        if any(s in line for s in shown):
            print("   ", line[:260], flush=True)
    with psycopg.connect(f"postgresql://mateo@localhost:5432/{name}") as c:
        kind = c.execute("SELECT relkind FROM pg_class WHERE relname = 'LiteLLM_SpendLogs'").fetchone()
    print(f"    LiteLLM_SpendLogs relkind after: {kind[0] if kind else None} (p = partitioned)", flush=True)
    with psycopg.connect(ADMIN, autocommit=True) as c:
        c.execute(f'DROP DATABASE IF EXISTS "{name}" WITH (FORCE)')


for side in sys.argv[1:] or ["before", "after"]:
    probe(side)
--- before: DATABASE_URL=postgresql://mateo@cloudsql.invalid:5432/<scratch db>?host=/tmp
    spend_logs_is_partitioned: False
    migration ledger rows: None
    setup_database(use_migrate=False): False
    Error: ERROR: unique constraint on partitioned table must include all partitioning columns
    Error: ERROR: unique constraint on partitioned table must include all partitioning columns
    Error: ERROR: unique constraint on partitioned table must include all partitioning columns
    Error: ERROR: unique constraint on partitioned table must include all partitioning columns
    LiteLLM_SpendLogs relkind after: p (p = partitioned)
--- after: DATABASE_URL=postgresql://mateo@cloudsql.invalid:5432/<scratch db>?host=/tmp
    spend_logs_is_partitioned: True
    migration ledger rows: 184
    setup_database(use_migrate=False) raised RuntimeError: LiteLLM_SpendLogs is a partitioned table (see db_scripts/partition_spend_logs.sql), so its primary key must include the partition key ("startTime"). `
    LiteLLM_SpendLogs relkind after: p (p = partitioned)

Helm upgrade on kind

Case Before (8f44f66) After (6eb671b)
lock_held helm exit 1 at 5 min, 5 pods exit 1 helm exit 0 in 33 s
url_lock_timeout helm exit 0 in 70 s, pod 1 cancelled helm exit 0 in 41 s, 1 pod
Commands, values, and pod logs

Each tree's chart and its migrations/Dockerfile image ran on kind at 6eb671b, with Postgres 16. c09cd03, df1d862, and c15ffdb change only the index sessions' timeouts, their reset, and socket URL handling, which the job cases above run at c15ffdb

Before, a Job retry absorbed the 4.5 s lock wait in url_lock_timeout, so helm fails only when the old transaction outlasts every retry

helm upgrade --install <release> <tree>/helm/litellm --namespace qa --timeout 5m -f values.yaml
migrationJob:
  image:
    repository: litellm-migrations-qa
    tag: "8f44f66"
    pullPolicy: Never
database:
  writer:
    host: pg.qa.svc.cluster.local
    port: 5432
    dbname: lock_before
gateway:
  enabled: false
backend:
  enabled: false
ui:
  enabled: false

The after runs use tag 6eb671b. url_lock_timeout also sets migrationJob.extraEnv DATABASE_URL=postgresql://postgres:<password>@pg.qa.svc.cluster.local:5432/<db>?options=-c%20lock_timeout%3D200

lock_held holds pg_advisory_lock(7812739710205912882) from a psql session in the Postgres pod for the whole helm run. url_lock_timeout first applies the migrations and drops both indexes, then opens a REPEATABLE READ snapshot on LiteLLM_SpendLogs and commits it about 4.5 s after CREATE INDEX CONCURRENTLY shows in pg_stat_activity

Before lock_held, helm and each of the 5 pods

Error: failed pre-install: resource Job/qa/lock-before-litellm-migrations not ready. status: InProgress, message: Job in progress
context deadline exceeded

INFO - Another process holds the migration lock, leaving the request-log indexes to the next index build
WARNING - Some request-log indexes are not in place yet, leaving them for the next index build
ERROR - Migration job failed after retries.

After lock_held, the one pod

INFO - Another process holds the migration lock, leaving the request-log indexes to the next index build
WARNING - Some request-log indexes are not in place yet, leaving them for the next index build
INFO - Migration job completed successfully.

Before url_lock_timeout, pod 1 and then pod 2

INFO - Building index LiteLLM_SpendLogs_api_key_startTime_idx on LiteLLM_SpendLogs concurrently
WARNING - Could not build the request-log indexes, leaving them for the next index build: canceling statement due to lock timeout
ERROR - Migration job failed after retries.

INFO - Dropping the invalid index LiteLLM_SpendLogs_api_key_startTime_idx left by an interrupted build on LiteLLM_SpendLogs
INFO - Building index LiteLLM_SpendLogs_api_key_startTime_idx on LiteLLM_SpendLogs concurrently
INFO - Building index LiteLLM_SpendLogs_litellm_call_id_idx on LiteLLM_SpendLogs concurrently
INFO - Request-log indexes are all in place
INFO - Migration job completed successfully.

After url_lock_timeout, the one pod, whose build waited on Lock/virtualxid while the snapshot was open

INFO - Building index LiteLLM_SpendLogs_api_key_startTime_idx on LiteLLM_SpendLogs concurrently
INFO - Building index LiteLLM_SpendLogs_litellm_call_id_idx on LiteLLM_SpendLogs concurrently
INFO - Request-log indexes are all in place
INFO - Migration job completed successfully.

Index state after each run: lock_held has neither index on both sides, and url_lock_timeout has both valid on both sides

pip install of proxy-extras

Each leg installs one wheel in a clean venv, with no PYTHONPATH or psycopg

Leg Wheel Result
before PyPI 0.4.100.post2 ModuleNotFoundError
after post3 built at c15ffdb warning, returns False
Commands, pip_leg.py, and output
cd litellm-proxy-extras && uv build --wheel --out-dir /tmp/pip_r4/dist && cd /tmp/pip_r4
python3 -m venv venv_before && venv_before/bin/pip install -q litellm-proxy-extras==0.4.100.post2
python3 -m venv venv_after && venv_after/bin/pip install -q dist/litellm_proxy_extras-0.4.100.post3-py3-none-any.whl
env -u PYTHONPATH venv_before/bin/python -I pip_leg.py
env -u PYTHONPATH venv_after/bin/python -I pip_leg.py
import importlib.metadata
import logging
import sys

logging.basicConfig(level=logging.WARNING, format="%(levelname)s %(message)s")
print("litellm-proxy-extras", importlib.metadata.version("litellm-proxy-extras"))
print("psycopg installed:", importlib.util.find_spec("psycopg") is not None)
from litellm_proxy_extras import request_log_indexes

print("has lifted_time_limits:", hasattr(request_log_indexes, "lifted_time_limits"))
try:
    result = request_log_indexes.ensure_request_log_indexes("postgresql://qa:qa@127.0.0.1:1/qa", "public")
    print("ensure_request_log_indexes ->", result)
except Exception as exc:
    print("ensure_request_log_indexes raised", type(exc).__name__ + ":", exc)
    sys.exit(1)
== before: pip install litellm-proxy-extras==0.4.100.post2, no PYTHONPATH
litellm-proxy-extras 0.4.100.post2
psycopg installed: False
has lifted_time_limits: False
ensure_request_log_indexes raised ModuleNotFoundError: No module named 'psycopg'
exit=1

== after: pip install dist/litellm_proxy_extras-0.4.100.post3-py3-none-any.whl, no PYTHONPATH
2026-11-10 20:40:23,270 - litellm_proxy_extras - WARNING - psycopg is not installed; skipping the request-log index build. Install the litellm[extra_proxy] extra, which includes psycopg.
WARNING psycopg is not installed; skipping the request-log index build. Install the litellm[extra_proxy] extra, which includes psycopg.
litellm-proxy-extras 0.4.100.post3
psycopg installed: False
has lifted_time_limits: True
ensure_request_log_indexes -> False
exit=0

The unpacked post3 wheel's litellm_proxy_extras matches the tip tree (diff -rq -x __pycache__ prints nothing), and uv lock --check exits 0 at c15ffdb

Regression tests, each failing before its fix and passing here
  • test_a_prisma_socket_host_param_reaches_libpq: 'localhost' == '/cloudsql/...' on 8f44f66
  • test_without_psycopg_the_build_warns_and_reports_the_indexes_missing: ModuleNotFoundError on 8f44f66
  • the ?host= case of test_coordination_failure_labels_unreachable_hosts_named_like_tls_markers: the message named localhost:5432 on 8f44f66
  • test_a_timeout_the_database_url_sets_does_not_cancel_the_online_build: its lock_timeout case fails on 8f44f66 with canceling statement due to lock timeout, and its transaction_timeout case fails on 6eb671b with the connection is closed
  • test_repair_outlives_a_timeout_passed_through_database_url_options: its transaction_timeout case fails on c09cd03, where the invalid index check loses its session and the index stays INVALID
  • test_a_pooled_server_session_gets_its_timeout_back_after_the_build: all three cases fail without the reset with assert ('0',) == ('4s',), so the pooled session kept the build's zero timeout
  • test_a_pooled_server_session_keeps_the_search_path_another_client_set: assert ('"$user", public',) == ('public, pg_catalog',) on df1d862, whose RESET ALL dropped it
  • test_the_job_succeeds_by_the_migrations_when_an_index_could_not_be_built and test_a_migration_job_that_could_not_build_the_indexes_succeeds_and_a_rerun_builds_them replace the exit 1 expectations
Local checks and the database integration lane

tests/litellm-proxy-extras passes 155 of 155 at c15ffdb

Gauntlet-mini: SURVIVED, 5/5 lenses, 6 confirmed (all fixed), run 03347e01009b, reviewed the staged tree that became 6eb671b

make check BASE_REF=origin/stable/1.103.x at c15ffdb fails only on 13 ruff F811 and F821 errors that stable/1.103.x already has, in test_llm_cost_calc_utils.py, test_response_metadata.py, and test_gpt5_transformation.py. This branch does not touch those files

On the laptop, every boot test passed at 6eb671b in at least one of two runs. On the GCE box, 8f44f66 and 6eb671b passed the same 8 of 12, and the same 4 failed on both at the 70 s owned-proxy readiness deadline while the legacy prisma migrate deploy was still running at load average 25

At c15ffdb, test_invalid_index_repair.py and test_request_log_indexes.py pass 63 of 64 on local Postgres 18.6 at load average 20. test_a_role_that_may_not_create_indexes_is_logged_and_left_for_the_next_job_run fails locally because it builds its reader URL by replacing postgres:postgres@, which the local URL does not have

/live-pr-risk at df1d862 and c15ffdb

PASS at c15ffdb. No breaking or backward incompatible change beyond what this PR names

At df1d862 /live-pr-risk failed. On Postgres 17 behind PgBouncer 1.26.1 in transaction mode, with ?schema=lpr3s and no DIRECT_URL, the RESET ALL that ended the build and repair sessions also reset the search_path Prisma had set on the shared server connection. /key/info with keys not yet cached then returned 401 (relation "LiteLLM_VerificationToken" does not exist) on 7 of 8 after the migration job and 6 of 8 after the migration-only CLI, while base returned 200 on all of them. Postgres 18 reports search_path to PgBouncer, which sets it again, so it was not affected

c15ffdb resets only statement_timeout, lock_timeout, and transaction_timeout, and test_a_pooled_server_session_keeps_the_search_path_another_client_set fails without that change. Every df1d862 leg ran again on all three trees, with the same rig, config, and order on each side

Leg Server and pool 8f44f66 df1d862 c15ffdb
miss_job_pg17 PG17, tx pool 8/8 1/8, rerun 0/8 8/8
miss_job_pg17_pool5 PG17, tx pool of 5 8/8 1/8 8/8
miss_cli_pg17 PG17, tx pool 8/8 2/8 8/8
miss_cli_pg18 PG18, tx pool 8/8 no baseline 8/8
reader_job_pg17 PG17, tx pool 200 200 200
reader_cli_pg18 PG18, tx pool 200 200 200

The miss legs count /key/info calls with keys not yet cached that return 200 right after the job (the df1d862 run of miss_cli_pg18 got 0/8 on base too, so it has no baseline), and the reader legs show the first /key/info after it. In miss_job_pg17 the pooled server connection held 0/30s/0/lpr4s (statement, lock, and transaction timeout, then search_path) on base, 0/0/0/"$user", public on df1d862, and 0/0/0/lpr4s on c15ffdb

Breaking

None. Every boot, job, and CLI leg exits the same way on base and c15ffdb except the cases this PR fixes (no_psycopg 1 to 0, p3005_socket 2 to 0, and the index build markers)

Backward incompatible

None beyond the named reset. Base left the build's statement_timeout 0 and lock_timeout 30s on a shared transaction-mode server connection. c15ffdb returns them to that connection's defaults. With database-level values of 41 s, 7 s, and 3 s, the pooled connection read 0/30s/3s after the job on base and 41s/7s/3s on c15ffdb on PG18 and PG17 (pgb_tx_all_job, pgb_tx17_db), and 0/30s against 41s/7s on PG16 (pgb_tx16_db). The one-setting legs (pgb_tx_dbst, pgb_tx_dblt, pgb_tx_dbtt) and exc_cancel, a cancelled build, show the same. exc_terminate and session mode match on all trees

A client that ran SET search_path, SET work_mem, a custom setting, and SET statement_timeout = 45s on the same pooled backend (clientsetrb, PG16 and PG17) kept its search_path, work_mem, and custom setting after the job on base and c15ffdb, and lost all of them on df1d862. Its statement_timeout read 0 afterwards on base and c15ffdb alike

Regression risk

Through a transaction pooler without DIRECT_URL, the three SETs and RESETs can land on different server connections. That is the Low caveat above, and DIRECT_URL is the documented setup for transaction poolers. A grep of litellm_proxy_extras for SET, RESET, and set_config finds no other session setting on the build or repair connection. replica_identity.py uses SET LOCAL, which ends with its transaction and does not run under the helper. The advisory locks held after the job match on all three trees

Dependency graph

Dependent Status
Migration job index build verified-live
Migration-only CLI build verified-live
Boot-time background build verified-live
Invalid index repair verified-live
Serving Prisma queries on a shared pooled connection verified-live
Other clients' settings on that connection verified-live
Role and database timeouts on that connection verified-live
tests/litellm-proxy-extras tested, 155 of 155
Migration suites on PG17 and PG18 tested, 63 of 64

The one migration suite failure is test_a_role_that_may_not_create_indexes_is_logged_and_left_for_the_next_job_run, which builds its reader URL from postgres:postgres@ and fails on base too with the local URL

Not verified

The PG16 migration suite timed out under load, and the PG16 live legs above ran instead. Helm on kind did not run again at c15ffdb, and its earlier run at 6eb671b stands for the chart and image. Poolers other than PgBouncer 1.26.1, such as RDS Proxy or Supavisor, were not available

Decisions
  • Exit by the migrations' result, never main's exit 1 on a missing index
  • Missing psycopg reports the indexes missing and keeps the job green
    • Same as the sibling invalid index check, which already warns and skips
  • lock_timeout and transaction_timeout 0 for the build session, never the value from the URL, the role, or the database
    • Base already overrides statement_timeout from every source the same way
    • CREATE INDEX CONCURRENTLY takes SHARE UPDATE EXCLUSIVE, which never blocks app reads or writes
    • The DIRECT_URL serves migrations, which must not be cancelled midway
    • Honoring them leaves an INVALID index and rebuilds on every run
    • This was the gauntlet's strongest dissent, kept by that convention
  • The invalid index check lifts transaction_timeout the same way, since a cancelled REINDEX CONCURRENTLY leaves the index INVALID for the next boot
  • transaction_timeout is set only on Postgres 17 and later, since older servers reject the name
    • Dropping the URL's options instead would also drop the operator's other session settings
  • Reset only statement_timeout, lock_timeout, and transaction_timeout when each session ends, never RESET ALL
    • RESET ALL also dropped the search_path Prisma set on a shared PgBouncer server connection, so key auth on Postgres 17 failed until Prisma reconnected (/live-pr-risk at df1d862)
    • The three cover every setting the build and the check change, including the per-step lock_timeout
  • No deadline on the job's index build wait, as on main and 1.104
  • The job keeps the migration lock for the whole build wait
    • Releasing it mid-build would let a second job build the same index at the same time
    • A bounded retry leaves an INVALID index on each timeout, as 8f44f66 did with a URL timeout
  • Socket ?host= URLs now reach every psycopg caller, not only the build
    • They share one URL rewrite, and a socket URL on TCP-only callers silently skipped the partition check and the ledger reads

Type

🐛 Bug Fix
✅ Test

Caveats (if any)

Medium

  • A long open transaction on LiteLLM_SpendLogs or a slow build can still outlast Helm's five-minute hook
    • No lock_timeout or transaction_timeout from the URL, role, or database cuts that wait short
    • Meanwhile the job holds the migration lock and SHARE UPDATE EXCLUSIVE, so another replica's v2 resolver can exit 2 after 600 s, and VACUUM and DDL wait
  • Under helm, an index the job skips stays missing until the next upgrade
    • Serving pods set DISABLE_SCHEMA_UPDATE=true, and the job exits 0, so nothing retries the build
    • The only signal is a warning in a Job pod deleted after 120 s
    • A later upgrade to 1.104, which exits 1 on a missing index, fails if the cause lasts

Low

  • CI skips the changed tests on stable/* branches, and its Postgres 16 would skip the transaction_timeout cases
  • Under load, the boot tests failed 4 of 12 on both trees at the readiness deadline
  • In-container PgBouncer ignores ?host= socket URLs, as before
  • Through a transaction pooler without DIRECT_URL, the reset and the build's settings can land on different server connections
  • Without psycopg, a v2 baseline (P3005) or P3009 recovery still fails on the import, as before. fix(proxy-extras): tolerate unloadable psycopg #50527 fixes it on main
  • A URL transaction_timeout can still cancel the v2 migration lock transaction in a baseline or P3009 recovery, as before

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
Bugbot summary

[!NOTE]
Medium Risk
Changes migration job exit semantics and long-running DDL session settings on production databases; index gaps may persist until the next job run despite a successful Helm upgrade.

Overview
Helm migration jobs no longer fail when SpendLogs request-log indexes could not be built in the same run: run_migration_job (and migrations/run.py) now report success from setup_database / migrations alone, while the index build still runs synchronously and logs for a later attempt.

Index creation and invalid-index repair temporarily zero statement_timeout, lock_timeout, and (on Postgres 17+) transaction_timeout via a new lifted_time_limits context manager, so URL- or role-level timeouts do not cancel long CREATE INDEX CONCURRENTLY / REINDEX CONCURRENTLY work.

Socket and libpq URLs are fixed by keeping Prisma's ?host= when stripping query params (LIBPQ_URL_PARAMS), using that host in P1001 coordination errors, and warning instead of raising when psycopg is missing during the index build.

litellm-proxy-extras is bumped to 0.4.100.post3 with matching lockfile and integration/unit coverage for migration-job exit codes, timeouts, pooled sessions, and boot-time index behavior.

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

…ontract manifest

The database group stopped at collection on these nodes, so the lane never ran them. Each one boots a migration job and a proxy, so the file also gets a 240 s timeout
An index the job could not build, for example while another replica held the migration lock, failed a helm upgrade whose migrations had passed. The job still waits for the build and logs what is left, and the next run or a serving proxy builds it
…cket hosts, and past a URL lock_timeout

Without psycopg the build warns and reports the indexes missing instead of crashing the job. Prisma's ?host= socket param now reaches libpq, so socket URLs connect, and the unreachable-host message names that socket. The build session sets lock_timeout to 0 next to statement_timeout, so a lock_timeout in the URL no longer cancels an online build that waits on an old snapshot
@quietjules
quietjules requested a review from a team November 10, 2026 19:48
@veria-ai

veria-ai Bot commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

PR overview

No security issues were found in this pull request.

Reviews

@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@greptile-apps

greptile-apps Bot commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 5/5

[Medium impact] The changes since the previous review appear safe to merge

Summary

This PR lets the migration job succeed when migrations pass but request-log indexes remain missing. It also preserves socket hosts, skips index builds safely without psycopg, lifts index-build timeouts, and bumps proxy-extras to 0.4.100.post3

The latest change replaces RESET ALL with resets for the three timeout settings. A regression test checks that the build leaves an existing search_path untouched

quietjules explicitly keeps successful migrations green when indexes are missing, leaving the next job run to retry them. No new actionable issue was found in the changes since the previous review

  • Migration jobs succeed when migrations pass, even if an index must wait.
  • Database URLs with a socket host connect to that socket.
  • Index builds and repairs can outlast database session timeouts.
  • Index builds skip with a warning when psycopg is not installed.

Reviews (5) · Last reviewed commit: "fix(proxy-extras): reset only the index ..." · Reviewed by Greptile

@mateo-berri

Copy link
Copy Markdown
Contributor

bugbot run

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

…quest-log index build

On Postgres 17 and later a transaction_timeout in the database URL's options ends the build session in the middle of CREATE INDEX CONCURRENTLY. The build session now sets it to 0 next to statement_timeout and lock_timeout
@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor

bugbot run

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

✅ Bugbot reviewed your changes and found no new issues!

Comment @cursor review or bugbot run to trigger another review on this PR

Reviewed by Cursor Bugbot for commit c15ffdb. Configure here.

@quietjules quietjules closed this Nov 11, 2026
@quietjules

Copy link
Copy Markdown
Contributor Author

Closed to free an open-PR slot. Branch kept, and it reopens for final CI and bot reviews once ready

@quietjules quietjules reopened this Nov 11, 2026

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

LGTM

@mateo-berri
mateo-berri merged commit e990bba into BerriAI:stable/1.103.x Nov 11, 2026
13 checks passed
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