Skip to content

fix(proxy-extras): backport the automatic SpendLogs index build (#43948, #44109, #44203) to stable/1.103.x - #50856

Merged
yuneng-berri merged 16 commits into
stable/1.103.xfrom
litellm_backport_43948_stable_1_103_x_devin
Nov 10, 2026
Merged

yuneng-berri merged 16 commits into
stable/1.103.xfrom
litellm_backport_43948_stable_1_103_x_devin

Conversation

@mateo-berri

@mateo-berri mateo-berri commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

Handwritten 1-3 sentence description

Builds the missing request-log indexes after migrations so log details can use indexed lookups on older installations. Keeps the 1.103 migration-only command's exit behavior and lets serving proxies start while indexing runs

TLDR

Problem this solves

  • Older deployments can lack the request lookup indexes
  • Opening request details can scan a large log history

How it solves it

  • Build missing indexes automatically after migrations
  • Use concurrent leaf builds and bounded parent lock waits
  • Keep 1.103 CLI exits tied to migrations
  • Handle partitioning, TLS URLs and PostgreSQL 10
  • Defer interrupted managed-index repairs during serving startup
  • Bump proxy extras from 0.4.100.post1 to 0.4.100.post2

User Flow

Before, the admin's migration command succeeds but request lookups still scan history

  1. The admin runs litellm --skip_server_startup --enforce_prisma_migration_check
  2. The command exits 0
  3. They inspect a request-detail lookup plan and see Seq Scan

After, the same command builds the missing indexes before exiting

  1. The admin runs litellm --skip_server_startup --enforce_prisma_migration_check
  2. The command exits 0
  3. They inspect the same lookup plan and see indexed lookups

Relevant issues

Backports #43948 with #44109, #44203, #46131 and #46592. Includes the missing migration coordination prerequisite from #40932 and the relevant recovery changes from #44312

Reconciles the release line's existing #44286 and #44397 drift behavior into one filter. Excludes the opt-in change #44124 and optional preflight feature #48493

Affected release

stable/1.103.x, including the reported v1.103.10 installation

Linear ticket

Pre-Submission checklist

  • I have added meaningful tests
  • The mapped test files pass locally
  • My PR passes all required CI/CD checks
  • My PR's scope is isolated to the SpendLogs index backport
  • I have received a Greptile Confidence Score of at least 4/5

Focused results at 162bb2e

Request-log, extras utility, proxy CLI and Prisma client units
289 passed, 3 warnings in 108.71s (0:01:48)

PostgreSQL 14 invalid-index repair tests, including three regressions
17 passed in 101.03s (0:01:41)

Live PostgreSQL 10 regression
2 passed, 1 skipped, 37 deselected in 5.98s
Live PostgreSQL 10 managed-index discovery passed for parent and differently named partition

git diff --check passed

Grype baseline matches 73
Grype final matches 65
New findings []
Removed findings 8
Remaining bumped-package findings 0

The PostgreSQL 10 skip covers INCLUDE indexes, which PostgreSQL 10 does not support. Earlier mutation checks restored the original catalog query and plain-pick CLI helper and failed their regressions. A new mutation disables the managed-index exclusion and fails the real database-setup regression

The original full migration, schema-drift and fail-fast gates passed at 8429729. This update reran the focused checks above. The lockfile is unchanged, so the earlier Grype comparison still applies

The ddtrace, oauthlib, pyasn1 and msgpack updates are confined to uv.lock in a chore(deps) commit. ddtrace-internal is a required transitive addition

Screenshots / Proof of Fix

Shared setup used a local PostgreSQL 14 database with 10,000 generated spend rows and the committed migrations. The lookup was request_id = $1 OR litellm_call_id = $1, using the same value on both sides. No provider request is needed to exercise this database migration path

The normal CLI ran in separate processes with each checkout's source on PYTHONPATH. No dependencies were mocked in this before/after run. The temporary database was dropped afterward

Before (b3287e3)

  1. In the release-base checkout, run the normal migration-only CLI against the prepared database

    python -c 'from litellm.proxy.proxy_cli import run_server; run_server()' \
      --skip_server_startup --enforce_prisma_migration_check --telemetry False

    Observed exit code 0

  2. Inspect the two managed indexes and explain the request lookup

    Live lookup before managed indexes []
    Seq Scan on "LiteLLM_SpendLogs"  (cost=0.00..435.00 rows=2 width=434)
      Filter: ((request_id = '24988d9aa627ea723a4769c83e481a76'::text) OR (litellm_call_id = '24988d9aa627ea723a4769c83e481a76'::text))
    

After (162bb2e)

  1. In the patched checkout, run the same migration-only CLI against the same database

    python -c 'from litellm.proxy.proxy_cli import run_server; run_server()' \
      --skip_server_startup --enforce_prisma_migration_check --telemetry False

    Observed exit code 0

  2. Inspect the same indexes and explain the same request lookup

    Live lookup after managed indexes [('LiteLLM_SpendLogs_api_key_startTime_idx', True), ('LiteLLM_SpendLogs_litellm_call_id_idx', True)]
    Bitmap Heap Scan on "LiteLLM_SpendLogs"  (cost=8.59..16.11 rows=2 width=434)
      Recheck Cond: ((request_id = '24988d9aa627ea723a4769c83e481a76'::text) OR (litellm_call_id = '24988d9aa627ea723a4769c83e481a76'::text))
      ->  BitmapOr  (cost=8.59..8.59 rows=2 width=0)
            ->  Bitmap Index Scan on "LiteLLM_SpendLogs_pkey"
            ->  Bitmap Index Scan on "LiteLLM_SpendLogs_litellm_call_id_idx"
    

Separate live CLI runs exercised a held migration lock and a 6,400-character API key. The before cases below restore the plain-pick helper in memory on the patched checkout, rather than using the release base

Live CLI held-lock before exit code 1
Live CLI held-lock after exit code 0
Live CLI oversized-api-key before exit code 1
Live CLI oversized-api-key after exit code 0

Type

Bug Fix

Caveats

Severe

  • Concurrent builds can consume disk and hours on big tables
  • Helm's five-minute pre-upgrade hook can time out
    • An open SpendLogs write transaction can delay completion
  • Live large-table QA was not run
  • Successful migration-only CLI exit does not guarantee completed indexes
  • Large upgrades need prebuilt indexes or longer rollout deadlines
    • Set both Helm's timeout and migrationJob.activeDeadlineSeconds

Medium

  • Gauntlet-mini is PARTIAL, without independent reviewer agents
  • The serving-proxy boot integration file was not run
  • Admin UI behavior and large-table lookup latency remain unverified
  • The focused test environment omits the optional ddtrace package

The migration-only CLI preserves 1.103's migration-based exit status. The separate migrations/run.py entrypoint retains upstream failure-on-incomplete-index behavior

Final Attestation

  • The tests check the right things, including the edge cases, and regressions in the respective real-world customer use-cases are not possible after this PR

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


Note

High Risk
Touches production database startup, Prisma migration ledger recovery, and concurrent DDL on high-volume SpendLogs tables (including partitioned deployments); mis-recovery or lock contention could block upgrades or leave indexes missing while migrations report success.

Overview
Request-log indexes (LiteLLM_SpendLogs_api_key_startTime_idx, LiteLLM_SpendLogs_litellm_call_id_idx) are removed from Prisma migration SQL (replaced with inert SELECT 1 steps) and built afterward by new request_log_indexes logic: CREATE INDEX CONCURRENTLY on plain tables, and per-partition attach flow on partitioned LiteLLM_SpendLogs. The migration Job (run_migration_job) waits for indexes; a serving proxy starts a daemon thread once migrations finish so readiness is not blocked.

The v2 migration resolver gains Postgres advisory-lock coordination, baseline / completed-migration recovery, credential redaction, and stricter P3009 handling (no longer auto-marking ambiguous failures as applied). Drift filtering, invalid-index repair, and Prisma→libpq URL handling were updated so pooled URLs and managed indexes do not fight migrations.

Proxy CLI wires setup → synchronous index build when --skip_server_startup, otherwise background build. Partitioning script renames the legacy litellm_call_id index; migration lint rejects new CREATE INDEX on request-log tables. litellm-proxy-extras bumps to 0.4.100.post2 with broad tests.

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

yuneng-berri and others added 14 commits November 10, 2026 05:45
…nstead of in migrations (#43948)

The two SpendLogs index migrations shipped in v1.103.0 each break one table shape: the plain CREATE INDEX holds a SHARE lock on a large unpartitioned table and the CONCURRENTLY one fails with 0A000 on a partitioned parent. Both files are now inert and the indexes are built by a table-driven, shape-aware step after migrate deploy: CONCURRENTLY on a plain table, ON ONLY the parent plus per-partition CONCURRENTLY and ATTACH PARTITION on a partitioned one. The migration job builds them synchronously and exits non-zero on failure; a serving proxy that ran migrate deploy itself builds them in the background off the readiness path. A valid index of the same definition under another name is renamed and reused, an invalid one is rebuilt, and extra copies are reported with their DROP INDEX statement instead of being dropped. The migration checker rejects any CREATE INDEX on LiteLLM_SpendLogs or LiteLLM_ErrorLogs in future migrations

Co-authored-by: yassin <yassin@berri.ai>
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
(cherry picked from commit c66c828)
…index build (#44109)

Co-authored-by: yassin <yassin@berri.ai>
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
(cherry picked from commit 123237c)
… the migration job builds indexes (#44203)

The migration job runs DatabaseURLSettings.apply_to_env(), which rewrites
DATABASE_SSLMODE=verify-full plus DATABASE_SSLROOTCERT into Prisma's TLS
dialect: sslmode=require&sslcert=<CA>&sslaccept=strict. The request-log
index build then hands that same URL to psycopg, and libpq reads sslcert
as a client certificate, failing with "certificate present, but not
private key file" on every verify-full deployment since #43948.

_strip_prisma_query_params now undoes the Prisma dialect before psycopg
sees the URL. sslaccept=strict (or any value Prisma treats as strict)
becomes sslrootcert=<CA> plus sslmode=verify-full whatever sslmode said,
since strict verifies chain and hostname and libpq only does that in
verify-full; sslmode=disable stays off. Without strict, Prisma verifies
nothing, so the CA is dropped and sslmode is kept as is. A URL that also
carries sslkey is libpq's own client-certificate form and is left alone.

Resolves LIT-9169

Co-authored-by: yassin <yassin@berri.ai>
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
(cherry picked from commit 4758fce)
)

* test: repair stale and polluting tests red on scheduled main CI (#44229)

Partial backport to rc/1.104.0: only the owned Redis port, Presidio stored-content check and event-loop lag logging fixes apply here. The other repairs target tests or behavior this line does not have

* test(proxy): stop the proxy_server app fixture leaking LITELLM_LOG

The session app fixture set LITELLM_LOG=ERROR with os.environ.setdefault and never removed it, so later tests on the same xdist worker inherited it. test_drop_params_env_var spawns a subprocess with os.environ and lost the warning it asserts on. Scope the variable to the import with a MonkeyPatch context

* test(secret-detection): give the hand-built redaction request an ASGI path

Since #43975 _read_request_body checks the route path via request.scope, and a scope without path raised KeyError that was swallowed into an empty body, so chat_completion failed with a missing messages parameter. Real ASGI scopes always carry path

* test(integration): isolate litellm callback lists per sdk test

usage-based-routing-v2 Routers register their selector in litellm.callbacks and nothing removes it, not even Router.reset(). The counter TTL and Redis service metrics tests left their selectors behind, and the next usage routing test ran their pre-call checks against its own rpm=1 deployments, raising "Deployment over defined rpm limit". An autouse fixture now gives each sdk test copies of the callback lists and restores the originals afterwards

* test(integration): keep the owner-lookup fault proxy off the shared read replica

The owned proxy points DATABASE_URL at a scratch database but inherited
DATABASE_URL_READ_REPLICA from the replica job, so auth read the shared
database and rejected the freshly created key with token_not_found_in_db.
Drop the replica variable like the other scratch-database owned proxies

* test(integration): request every seeded key in the team owner breakdown

The aggregated team activity endpoint now caps breakdown.api_keys at the top
100 keys by default (#43398), so the 300 seeded keys came back as 100 rows.
The test guarantees each key is reported with its own owner, so ask for an
api_key_limit that covers all seeded keys

* test(integration): give every owned Redis its own port in the redis-cache container

On CircleCI every owned Redis ran on the fixed port 16379 inside the shared
redis-cache container. When an earlier server still held that port, the new
one failed to bind, readiness pinged the old server, the pidfile read failed
and cleanup then reported "Owned Redis still serves after shutdown"

Reserve an ephemeral port for the docker-exec path the same way the local
binary path already does, and refuse to start when something already serves
the chosen port so the failure names the real cause

* test(e2e): skip the Vertex Mistral partner case the e2e project cannot reach

The e2e Vertex project gets a 404 publisher model not found for vertex_ai/mistral-small-2503, so the case can only fail

* test(e2e): skip the Vertex gpt-oss partner case the e2e project never serves

vertex_ai/openai/gpt-oss-120b-maas has hit a 60s read timeout with no response headers on every run in the e2e Vertex project since the case was ported, and no other Vertex partner chat model passes there to switch to

* test(e2e): check only stored message content for a leaked card number

The Presidio spend-log check ran the card-number pattern over the whole serialized response, so a Luhn-valid usage.cost float (0.0003466000000000001) failed the streaming /v1/messages case although the stored content was <CREDIT_CARD>. The check now reads the content and text strings of the stored response, which is where a raw card would land, and still requires the placeholder there

* test(e2e): assert the proxy decodes token-array embeddings for titan

The port in #44120 carried over a legacy SDK-direct test that expected Bedrock to reject token ids with a 400. Through the proxy, /embeddings decodes token arrays to text for providers that cannot embed tokens, so titan answers 200. The test now sends a token array and its decoded sentence and requires the two vectors to match, which fails if the proxy stops decoding or decodes with the wrong tokenizer

* test(e2e): run the Bedrock extended-thinking round trip on a model that honors enabled thinking

us.anthropic.claude-sonnet-5-5 is adaptive-only, so litellm sends thinking.type=enabled with a 1024 budget as adaptive with low effort, and Bedrock returned no reasoning blocks on 5 of 5 identical Converse calls (boto3 direct agreed). us.anthropic.claude-sonnet-4-6 accepts the legacy shape verbatim and returned reasoning on 5 of 5. The non-thinking Bedrock case stays on sonnet-5-5

* test(proxy): stop unit modules forcing DEBUG logging into the event-loop lag tests

Five tests/unit modules set verbose_proxy_logger to DEBUG at import, so every xdist worker that collected them logged the 2.4MB pass-through response from a worker thread, and secret redaction of that line held the GIL for ~0.8s+ inside the timed window. The lag tests now pin the LiteLLM loggers to WARNING and freeze gc while timing, and the module-level DEBUG overrides are removed

* test(e2e): cite the tokenizer and date behind the titan token-array fixture

* test(e2e): let migration seed replicas finish their request-log indexes before cloning

Since #43948 a serving proxy builds the two LiteLLM_SpendLogs indexes on a background thread after it reports ready. The seed fixtures stopped the replica at readiness, so every cloned legacy database lacked an index no real deployment would be missing, and the v2 baseline diff refused it. Seeds now wait until both indexes exist and are valid in the database's schema

* test(passthrough): give the pass-through MockRequest an httpx URL and ASGI scope

* test(integration): ignore foreign allow_all_keys MCP servers in the access matrix tool list

test_toolset_gateway_url_serves_a_team_granted_toolset_to_a_key_without_its_own_grant (#43908) registers an allow_all_keys server on the shared gateway, and allow_all_keys servers are listed to every key by design, so a matrix case running on another xdist worker at the same time saw its tools. The matrix now drops tools of allow_all_keys servers it did not create, read from LiteLLM_MCPServerTable before and after listing, and still compares everything else exactly

(cherry picked from commit 9b5562f)

* fix(proxy-extras): retry P3009 when a peer already recovered the named migration row (#44283)

* fix(proxy-extras): retry P3009 when a peer already recovered the named migration row

* fix(proxy-extras): pin P3009 recovery locals as Final and cover a recovered sibling row

* test(proxy-extras): stop the P3009 ledger fakes shadowing the partition detector cursor

* fix(proxy-extras): annotate the migration ledger reader locals as Final

---------

Co-authored-by: yuneng <yuneng@berri.ai>
(cherry picked from commit 8b11b68)

---------

Co-authored-by: devin-ai-integration[bot] <158243242+devin-ai-integration[bot]@users.noreply.github.com>
(cherry picked from commit 31d6c60)
Use the operator-class vector to count index keys across PostgreSQL versions and cover missing, equivalent and INCLUDE indexes with live catalog tests

Type the backported tests, construct environments without mutation and inject startup dependencies while preserving automatic index builds

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
(cherry picked from commit 7085864)
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>
…lock and redact its errors (#46592)

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
(cherry picked from commit 1ac9cb2)
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>
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@devin-ai-integration

devin-ai-integration Bot commented Nov 10, 2026 •

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

@CLAassistant

CLAassistant commented Nov 10, 2026 •

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you all sign our Contributor License Agreement before we can accept your contribution.
2 out of 4 committers have signed the CLA.

✅ yuneng-berri
✅ mateo-berri
❌ devin-ai-integration[bot]
❌ yassin-berriai
You have signed the CLA already but the status is still pending? Let us recheck it.

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

@veria-ai

veria-ai Bot commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

PR overview

Backports automatic SpendLogs index creation to stable/1.103.x, including PostgreSQL connection handling for index building and recovery.

One issue remains open: connections configured with strict TLS and system trust can lose certificate-verification requirements when no custom CA is supplied. This weakens server authentication for index-building and recovery connections, potentially allowing database impersonation by an attacker positioned to intercept traffic. No issues have been addressed yet.

Open issues (1)

Fixed/addressed: 0 · PR risk: 4/10

Reviews

@greptile-apps

greptile-apps Bot commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 5/5

[High impact] The requested fixes are present, and no new blocking issue was found

Summary

This backport builds missing request-log indexes after migrations while allowing serving proxies to build them in the background

  • SpendLogs lookup indexes are built after migrations, including on partitioned tables.
  • Serving proxies start index builds without waiting for them to finish.
  • Migration workers coordinate their recovery against the same database state.

Reviews (2) · Last reviewed commit: "refactor(proxy): inject CLI database sta..." · Reviewed by Greptile

Comment thread litellm/proxy/proxy_cli.py Resolved
A URL that also carries ``sslkey`` is libpq's own client-certificate form
and is kept."""
keys: Final = frozenset(k for k, _ in pairs)
if "sslcert" not in keys or "sslkey" in keys:

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.

Medium: Preserve strict TLS without a custom CA

For sslmode=require&sslaccept=strict without sslcert—a supported Prisma configuration using system trust—this early return causes _strip_prisma_query_params to discard sslaccept and pass only sslmode=require into the new index-building and recovery connections. (prisma.io) Libpq's require does not enforce hostname verification and, without a root-CA file, accepts untrusted certificates; apply strict-mode handling independently of sslcert, configuring an appropriate CA trust source and failing closed if it is unavailable. (postgresql.org)

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.

Reproduced, and main has the same behavior. Holding the change while we decide where the fix goes, since it applies to main and both release lines

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Filed as a follow-up for main and both release lines, since main has the same TLS behavior

mateo-berri and others added 2 commits November 10, 2026 06:57
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>
@mateo-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor Author

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.

Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit 162bb2e. Configure here.

build()
return True
start()
return True

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.

Index thread starts before worker fork

Medium Severity

The serving proxy starts the request-log index build on a daemon thread during database setup, before uvicorn/gunicorn forks workers. Forking while that thread holds a live psycopg connection and a session advisory lock can corrupt the socket in children or leave CREATE INDEX CONCURRENTLY interrupted and invalid.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 162bb2e. Configure here.

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.

Uvicorn starts its workers with spawn, not fork, so they never inherit the connection. Under Gunicorn the children do inherit the socket, but psycopg's finalizers check the creating PID and skip PQfinish() in a child, so no child can send Terminate on it. Checked live on Postgres 14 with both psycopg implementations. A build stuck in CREATE INDEX CONCURRENTLY lived through three forks plus child garbage collection, kept its advisory lock, and both indexes came out valid. A negative control that strips the PID check does break the parent, so the probe would have caught this failure. Main uses the same launch placement

@yuneng-berri
yuneng-berri merged commit 8f44f66 into stable/1.103.x Nov 10, 2026
10 of 12 checks passed
@yuneng-berri
yuneng-berri deleted the litellm_backport_43948_stable_1_103_x_devin branch November 10, 2026 17:27
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.

4 participants