Repository navigation
fix(proxy-extras): backport the automatic SpendLogs index build (#43948, #44109, #44203) to stable/1.103.x - #50856
Conversation
…ion CI (cherry picked from commit 9403201)
…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)
… 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>
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>
|
I'll fix CI failures and address comments from users with write access. I'll skip comments containing "(aside)".
|
|
|
PR overviewBackports 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 |
[High impact] The requested fixes are present, and no new blocking issue was found SummaryThis backport builds missing request-log indexes after migrations while allowing serving proxies to build them in the background
Reviews (2) · Last reviewed commit: "refactor(proxy): inject CLI database sta..." · Reviewed by Greptile |
| 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: |
There was a problem hiding this comment.
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)
There was a problem hiding this comment.
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
There was a problem hiding this comment.
Filed as a follow-up for main and both release lines, since main has the same TLS behavior
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>
|
bugbot run |
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.
❌ 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 |
There was a problem hiding this comment.
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)
Reviewed by Cursor Bugbot for commit 162bb2e. Configure here.
There was a problem hiding this comment.
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


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
How it solves it
User Flow
Before, the admin's migration command succeeds but request lookups still scan history
litellm --skip_server_startup --enforce_prisma_migration_checkSeq ScanAfter, the same command builds the missing indexes before exiting
litellm --skip_server_startup --enforce_prisma_migration_checkRelevant 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
Focused results at 162bb2e
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 pathThe 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)
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 FalseObserved exit code 0
Inspect the two managed indexes and explain the request lookup
After (162bb2e)
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 FalseObserved exit code 0
Inspect the same indexes and explain the same request lookup
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
Type
Bug Fix
Caveats
Severe
Medium
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
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 inertSELECT 1steps) and built afterward by newrequest_log_indexeslogic:CREATE INDEX CONCURRENTLYon plain tables, and per-partition attach flow on partitionedLiteLLM_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 legacylitellm_call_idindex; migration lint rejects newCREATE INDEXon request-log tables.litellm-proxy-extrasbumps to0.4.100.post2with broad tests.Reviewed by Cursor Bugbot for commit 162bb2e. Bugbot is set up for automated code reviews on this repo. Configure here.