Skip to content

fix(proxy): unset DB environment variables removed from the row on every worker by row revision - #46709

Merged
mateo-berri merged 15 commits into
mainfrom
litellm_unset_removed_db_env_vars_by_row_revision
Oct 17, 2026
Merged

mateo-berri merged 15 commits into
mainfrom
litellm_unset_removed_db_env_vars_by_row_revision

Conversation

@mateo-berri

@mateo-berri mateo-berri commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves:

  • Removing a stored environment variable never unsets it on running workers, so a removed provider key keeps serving traffic until every pod restarts

How it solves it:

  • A DB trigger stamps the env var row with an ordered revision
  • Each worker applies a newer row and puts a dropped key back to its own env or config.yaml value
  • A stale cached row is checked against the writer before it applies

User Flow

Before: an admin removes a stored Anthropic key, and every worker keeps using it

  1. The admin sends POST https://litellm-domain/config/update with {"environment_variables": {"ANTHROPIC_API_KEY": "sk-ant-..."}} and gets success
  2. Within two minutes, POST https://litellm-domain/v1/chat/completions to an Anthropic model returns 200 on every worker
  3. The admin removes the key by sending {"environment_variables": {"ANTHROPIC_API_KEY": null}} to the same route, which also returns success
  4. Minutes later, the same chat request still returns 200 on every worker until every pod restarts

After: each worker drops the removed key on its next config sync

  1. Steps 1 to 3 are the same as before
  2. Within two minutes, the same request returns 401 Missing Anthropic API Key on every worker, or uses the pod's own env or config.yaml key

Relevant issues

Supersedes #46241

Linear ticket

Resolves LIT-9489

Design decisions

Why a DB trigger revision, what a dropped key goes back to, and the edge cases
  • Ordering comes from a dedicated Postgres sequence that a row trigger on the environment_variables config row bumps on every insert and update
    • The trigger fires after the row lock, so revision order matches commit order, and the sequence keeps going up across a row delete and re-insert
    • Rejected a counter written by /config/update (concurrent writers race, direct SQL writes skip it) and an updated_at clock (pod clock skew, the approach fix(proxy): unset environment variables removed from the DB row on the next config sync #46241 took)
    • On update the trigger stores at least the old revision plus one, so a row copied into a database whose sequence is behind (a single-table dump, a replication cutover) still gets a higher revision on its next save
  • The migration grants USAGE on that sequence to PUBLIC, since the trigger runs as whichever role writes the row and a writer role often has table grants only
    • Without the grant, a role with only SELECT, INSERT, UPDATE on the tables gets permission denied for sequence on every env var save
    • Rejected a SECURITY DEFINER trigger function (runs with the owner's rights and depends on search_path) and an OLD + 1 counter (starts over after a row delete and re-insert)
  • The trigger function finds the sequence in the schema of the table it fires on (TG_TABLE_SCHEMA), so a direct SQL write from a session whose search_path leaves out that schema, or is empty, still gets a revision
    • Rejected SET search_path FROM CURRENT on the function, which pins whatever search_path the migration session had instead of following the table
  • A dropped key is restored from a snapshot of the worker's environment taken at its first DB config sync, whether or not the row exists yet. At startup that sync runs after the config.yaml environment_variables load, since load_config runs before Prisma connects, so a value set at runtime later never becomes a restore target
    • Rejected always popping the key, which would lose a process or config.yaml value the DB value shadowed
  • A revision other than the applied one is applied in full and unsets the keys it dropped. An equal revision only sets values
  • A cached row older than the applied one, or without a revision once one was applied, is never applied as it is. The worker reads the row again from the writer database and applies that
    • A stale cached copy (a pod still on the old version caches rows without a revision during a rollout) cannot bring back a key a newer revision removed
    • When the writer row is older too, the database itself went back (a restore), so the worker applies it instead of skipping every save until a restart
    • Rejected skipping older rows, which left workers ignoring every save after a restore until they restarted
    • When the writer cannot be reached or is out of connections for that re-read, the worker keeps the env vars it already applied and skips the env var row for that sync, so get_config() still answers from the other rows. It tries again on the next sync
    • Rejected applying the stale row, which can bring back a removed key, and raising, which fails every get_config() caller during a writer outage, including the public GET /get/ui_theme_settings and GET /v2/model/info
  • When two syncs overlap in one worker, a sync never applies its env var row after a sync that started later already applied one. The periodic sync and request handlers that reload config, such as GET /v2/model/info, can run at the same time
    • The check that a row is older than the applied one runs right before the apply, not when the row is read, so a row read before an overlapping sync applied a newer one goes through the writer re-read. A writer row read while another sync applied a newer one is dropped, and the next sync applies the current row
    • Rejected a lock around the read and the apply, which would make those handlers wait behind a slow writer re-read
  • A cached row without a revision only sets values until the worker has applied a revision
  • A key whose stored value fails to decrypt still counts as stored, so a wrong salt key never unsets it
  • SSO env vars (GOOGLE_CLIENT_ID and the rest of the SSO fields) that the row dropped are unset right after the same sync reads the SSO settings table, unless that table still holds them
    • The SSO settings save moves these keys from the env row into its own table, so unsetting them before that read would blank a live SSO login until the read sets it again
    • When supported_db_objects leaves out sso_settings, that table is never read, so the dropped SSO keys are unset right after the same sync instead
  • Master key rotation now re-encrypts only the env values it can decrypt and keeps the rest (plaintext, or encrypted with another key) exactly as stored, the same skip rule as the AES credential migration
    • Main drops those keys from the row, which this PR would turn into an unset on every worker
    • Rejected encrypting them under the new key, which wraps an old ciphertext in a second layer that then decrypts to the ciphertext
  • Every path that rewrites the env var row reads the current row from the writer database, not the read replica: /config/update, the theme save, the SSO settings save and master key rotation
    • A save during replica lag would otherwise write back a row missing a key another save just added, or holding one it just removed, and this PR turns that into an unset or a set on every worker
  • A missing row changes nothing, the same as main. Treating it as empty would strip every key on a transient read miss or a pod pointed at the wrong database
  • A row value that is not a JSON object raises, the same as main
  • The worker that served /config/update applies the removal before it answers when the read replica has caught up, because that endpoint reloads through the same DB sync. Under replica lag it applies it on its next sync, like the other workers and pods
  • prisma db push only syncs schema.prisma, so after a push the proxy also runs the trigger migration's SQL with prisma db execute. If that fails, the proxy logs a warning and keeps booting, and removals then behave as on main
    • Rejected failing the boot, since the trigger only matters for removals and every other setting still syncs without it
  • No litellm-proxy-extras version bump, the same as other migration-only changes

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

Last updated: 6cd1c1a (eee7456 adds only a test)

Proxies A, B and C run 2 workers each on one Postgres and one Redis, and C boots after the save with its own fake ANTHROPIC_API_KEY. Each check calls both providers on three routes on every worker, then reads the logo and login redirect

Step Before (8bb8ac7) After (6cd1c1a)
1. Nothing stored 401 401
2. Store keys, SSO client, logo via A success success
3. 150 s later on A and B 200 200
4. C boots with its own key 200 200
5. Null keys and SSO, clear logo via B success success
6. Chat 150 s later 200 on 6 of 6 401 on 6 of 6
6. Anthropic key on C the removed key C's own key
6. Logo set on 5 of 6 gone on 6 of 6
6. SSO login Google on 6 of 6 none on 6 of 6
Integration tests fail pass
After leg, step 6 on every worker (6cd1c1a)

The OpenAI 401 shows the fake config.yaml OPENAI_API_KEY, and C's Anthropic 401 rejects C's own fake key. The outputs drop the sso_code= and sso_url= lines zsh prints when a loop declares a local again

### 6. After 150 seconds, every worker on A, B and C
proxy A worker 12675: chat/claude 401 messages/claude 401 responses/claude 401 chat/gpt 401
proxy A worker 12676: chat/claude 401 messages/claude 401 responses/claude 401 chat/gpt 401
proxy B worker 13090: chat/claude 401 messages/claude 401 responses/claude 401 chat/gpt 401
proxy B worker 13091: chat/claude 401 messages/claude 401 responses/claude 401 chat/gpt 401
proxy C worker 16089: chat/claude 401 messages/claude 401 responses/claude 401 chat/gpt 401
proxy C worker 16090: chat/claude 401 messages/claude 401 responses/claude 401 chat/gpt 401
error seen, proxy A claude 401: litellm.AuthenticationError: Missing Anthropic API Key - A call is being made to anthropic but no key is set e
error seen, proxy A gpt 401: litellm.AuthenticationError: AuthenticationError: OpenAIException - Incorrect API key provided: sk-proj-******
error seen, proxy B claude 401: litellm.AuthenticationError: Missing Anthropic API Key - A call is being made to anthropic but no key is set e
error seen, proxy B gpt 401: litellm.AuthenticationError: AuthenticationError: OpenAIException - Incorrect API key provided: sk-proj-******
error seen, proxy C claude 401: litellm.AuthenticationError: AnthropicException - {"type":"error","error":{"type":"authentication_error","mess
error seen, proxy C gpt 401: litellm.AuthenticationError: AuthenticationError: OpenAIException - Incorrect API key provided: sk-proj-******
Before leg, full output (8bb8ac7)
### Setup: commit 8bb8ac7f18, proxies A (:35139) and B (:41711), 2 workers each, one Postgres database and one Redis. Proxy C (:42265) boots later
listener pid 12450 on :35139 started with ANTHROPIC_API_KEY: 0 OPENAI_API_KEY: 0 GOOGLE_CLIENT_ID: 0
listener pid 12699 on :35139 started with ANTHROPIC_API_KEY: 0 OPENAI_API_KEY: 0 GOOGLE_CLIENT_ID: 0
listener pid 12700 on :35139 started with ANTHROPIC_API_KEY: 0 OPENAI_API_KEY: 0 GOOGLE_CLIENT_ID: 0
listener pid 12897 on :41711 started with ANTHROPIC_API_KEY: 0 OPENAI_API_KEY: 0 GOOGLE_CLIENT_ID: 0
listener pid 13148 on :41711 started with ANTHROPIC_API_KEY: 0 OPENAI_API_KEY: 0 GOOGLE_CLIENT_ID: 0
listener pid 13149 on :41711 started with ANTHROPIC_API_KEY: 0 OPENAI_API_KEY: 0 GOOGLE_CLIENT_ID: 0
### 1. Before anything is stored, every worker on A and B
proxy A worker 12699: chat/claude 401 messages/claude 401 responses/claude 401 chat/gpt 401
proxy A worker 12700: chat/claude 401 messages/claude 401 responses/claude 401 chat/gpt 401
proxy B worker 13148: chat/claude 401 messages/claude 401 responses/claude 401 chat/gpt 401
proxy B worker 13149: chat/claude 401 messages/claude 401 responses/claude 401 chat/gpt 401
error seen, proxy A claude 401: litellm.AuthenticationError: Missing Anthropic API Key - A call is being made to anthropic but no key is set e
error seen, proxy A gpt 401: litellm.AuthenticationError: AuthenticationError: OpenAIException - Incorrect API key provided: sk-proj-******
error seen, proxy B claude 401: litellm.AuthenticationError: Missing Anthropic API Key - A call is being made to anthropic but no key is set e
error seen, proxy B gpt 401: litellm.AuthenticationError: AuthenticationError: OpenAIException - Incorrect API key provided: sk-proj-******
proxy A worker 12699: GET /get/ui_theme_settings logo_url=none, GET /sso/key/generate 200 -> no redirect no client_id
proxy A worker 12700: GET /get/ui_theme_settings logo_url=none, GET /sso/key/generate 200 -> no redirect no client_id
proxy B worker 13148: GET /get/ui_theme_settings logo_url=none, GET /sso/key/generate 200 -> no redirect no client_id
proxy B worker 13149: GET /get/ui_theme_settings logo_url=none, GET /sso/key/generate 200 -> no redirect no client_id
### 2. Admin stores both provider keys and a Google SSO client through proxy A, then sets a logo
$ curl -s -X POST http://127.0.0.1:$PORT_A/config/update -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H "Content-Type: application/json" -d "{\"environment_variables\": {\"ANTHROPIC_API_KEY\": \"$ANTHROPIC_KEY_TO_STORE\", \"OPENAI_API_KEY\": \"$OPENAI_KEY_TO_STORE\", \"GOOGLE_CLIENT_ID\": \"qa-google-client-$LEG\", \"GOOGLE_CLIENT_SECRET\": \"qa-google-secret\"}}"; echo
{"message":"Config updated successfully"}
$ curl -s -X PATCH http://127.0.0.1:$PORT_A/update/ui_theme_settings -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H "Content-Type: application/json" -d "{\"logo_url\": \"$LOGO\"}" | jq -c "{message}"
{"message":"UI theme settings updated successfully."}
### 3. After 150 seconds, every worker on A and B
proxy A worker 12699: chat/claude 200 messages/claude 200 responses/claude 200 chat/gpt 200
proxy A worker 12700: chat/claude 200 messages/claude 200 responses/claude 200 chat/gpt 200
proxy B worker 13148: chat/claude 200 messages/claude 200 responses/claude 200 chat/gpt 200
proxy B worker 13149: chat/claude 200 messages/claude 200 responses/claude 200 chat/gpt 200
proxy A worker 12699: GET /get/ui_theme_settings logo_url=https://example.com/qa-logo-before_8bb.png, GET /sso/key/generate 303 -> https://accounts.google.com client_id=qa-google-client-before_8bb
proxy A worker 12700: GET /get/ui_theme_settings logo_url=https://example.com/qa-logo-before_8bb.png, GET /sso/key/generate 303 -> https://accounts.google.com client_id=qa-google-client-before_8bb
proxy B worker 13149: GET /get/ui_theme_settings logo_url=https://example.com/qa-logo-before_8bb.png, GET /sso/key/generate 303 -> https://accounts.google.com client_id=qa-google-client-before_8bb
proxy B worker 13148: GET /get/ui_theme_settings logo_url=https://example.com/qa-logo-before_8bb.png, GET /sso/key/generate 303 -> https://accounts.google.com client_id=qa-google-client-before_8bb
### 4. Proxy C boots now with its own ANTHROPIC_API_KEY (sk-ant-process-env-not-a-real-key) in its process environment, after everything is stored, and every worker on C
listener pid 15804 on :42265 started with ANTHROPIC_API_KEY=sk-ant-process-env-not-a-real-key
listener pid 16080 on :42265 started with ANTHROPIC_API_KEY=sk-ant-process-env-not-a-real-key
listener pid 16081 on :42265 started with ANTHROPIC_API_KEY=sk-ant-process-env-not-a-real-key
proxy C worker 16080: chat/claude 200 messages/claude 200 responses/claude 200 chat/gpt 200
proxy C worker 16081: chat/claude 200 messages/claude 200 responses/claude 200 chat/gpt 200
proxy C worker 16081: GET /get/ui_theme_settings logo_url=https://example.com/qa-logo-before_8bb.png, GET /sso/key/generate 303 -> https://accounts.google.com client_id=qa-google-client-before_8bb
proxy C worker 16080: GET /get/ui_theme_settings logo_url=https://example.com/qa-logo-before_8bb.png, GET /sso/key/generate 303 -> https://accounts.google.com client_id=qa-google-client-before_8bb
### 5. Admin removes the keys and the SSO client through proxy B by sending null, then clears the logo
$ curl -s -X POST http://127.0.0.1:$PORT_B/config/update -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H "Content-Type: application/json" -d "{\"environment_variables\": {\"ANTHROPIC_API_KEY\": null, \"OPENAI_API_KEY\": null, \"GOOGLE_CLIENT_ID\": null, \"GOOGLE_CLIENT_SECRET\": null}}"; echo
{"message":"Config updated successfully"}
$ curl -s -X PATCH http://127.0.0.1:$PORT_B/update/ui_theme_settings -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H "Content-Type: application/json" -d "{}" | jq -c "{message}"
{"message":"UI theme settings updated successfully."}
### 6. After 150 seconds, every worker on A, B and C
proxy A worker 12699: chat/claude 200 messages/claude 200 responses/claude 200 chat/gpt 200
proxy A worker 12700: chat/claude 200 messages/claude 200 responses/claude 200 chat/gpt 200
proxy B worker 13148: chat/claude 200 messages/claude 200 responses/claude 200 chat/gpt 200
proxy B worker 13149: chat/claude 200 messages/claude 200 responses/claude 200 chat/gpt 200
proxy C worker 16080: chat/claude 200 messages/claude 200 responses/claude 200 chat/gpt 200
proxy C worker 16081: chat/claude 200 messages/claude 200 responses/claude 200 chat/gpt 200
proxy A worker 12699: GET /get/ui_theme_settings logo_url=https://example.com/qa-logo-before_8bb.png, GET /sso/key/generate 303 -> https://accounts.google.com client_id=qa-google-client-before_8bb
proxy A worker 12700: GET /get/ui_theme_settings logo_url=https://example.com/qa-logo-before_8bb.png, GET /sso/key/generate 303 -> https://accounts.google.com client_id=qa-google-client-before_8bb
proxy B worker 13148: GET /get/ui_theme_settings logo_url=https://example.com/qa-logo-before_8bb.png, GET /sso/key/generate 303 -> https://accounts.google.com client_id=qa-google-client-before_8bb
proxy B worker 13149: GET /get/ui_theme_settings logo_url=none, GET /sso/key/generate 303 -> https://accounts.google.com client_id=qa-google-client-before_8bb
proxy C worker 16081: GET /get/ui_theme_settings logo_url=https://example.com/qa-logo-before_8bb.png, GET /sso/key/generate 303 -> https://accounts.google.com client_id=qa-google-client-before_8bb
proxy C worker 16080: GET /get/ui_theme_settings logo_url=https://example.com/qa-logo-before_8bb.png, GET /sso/key/generate 303 -> https://accounts.google.com client_id=qa-google-client-before_8bb
DONE 23:43:03Z
After leg, full output (6cd1c1a)
### Setup: commit 6cd1c1adce, proxies A (:39751) and B (:52413), 2 workers each, one Postgres database and one Redis. Proxy C (:52647) boots later
listener pid 12262 on :39751 started with ANTHROPIC_API_KEY: 0 OPENAI_API_KEY: 0 GOOGLE_CLIENT_ID: 0
listener pid 12675 on :39751 started with ANTHROPIC_API_KEY: 0 OPENAI_API_KEY: 0 GOOGLE_CLIENT_ID: 0
listener pid 12676 on :39751 started with ANTHROPIC_API_KEY: 0 OPENAI_API_KEY: 0 GOOGLE_CLIENT_ID: 0
listener pid 12809 on :52413 started with ANTHROPIC_API_KEY: 0 OPENAI_API_KEY: 0 GOOGLE_CLIENT_ID: 0
listener pid 13090 on :52413 started with ANTHROPIC_API_KEY: 0 OPENAI_API_KEY: 0 GOOGLE_CLIENT_ID: 0
listener pid 13091 on :52413 started with ANTHROPIC_API_KEY: 0 OPENAI_API_KEY: 0 GOOGLE_CLIENT_ID: 0
### 1. Before anything is stored, every worker on A and B
proxy A worker 12675: chat/claude 401 messages/claude 401 responses/claude 401 chat/gpt 401
proxy A worker 12676: chat/claude 401 messages/claude 401 responses/claude 401 chat/gpt 401
proxy B worker 13090: chat/claude 401 messages/claude 401 responses/claude 401 chat/gpt 401
proxy B worker 13091: chat/claude 401 messages/claude 401 responses/claude 401 chat/gpt 401
error seen, proxy A claude 401: litellm.AuthenticationError: Missing Anthropic API Key - A call is being made to anthropic but no key is set e
error seen, proxy A gpt 401: litellm.AuthenticationError: AuthenticationError: OpenAIException - Incorrect API key provided: sk-proj-******
error seen, proxy B claude 401: litellm.AuthenticationError: Missing Anthropic API Key - A call is being made to anthropic but no key is set e
error seen, proxy B gpt 401: litellm.AuthenticationError: AuthenticationError: OpenAIException - Incorrect API key provided: sk-proj-******
proxy A worker 12676: GET /get/ui_theme_settings logo_url=none, GET /sso/key/generate 200 -> no redirect no client_id
proxy A worker 12675: GET /get/ui_theme_settings logo_url=none, GET /sso/key/generate 200 -> no redirect no client_id
proxy B worker 13090: GET /get/ui_theme_settings logo_url=none, GET /sso/key/generate 200 -> no redirect no client_id
proxy B worker 13091: GET /get/ui_theme_settings logo_url=none, GET /sso/key/generate 200 -> no redirect no client_id
### 2. Admin stores both provider keys and a Google SSO client through proxy A, then sets a logo
$ curl -s -X POST http://127.0.0.1:$PORT_A/config/update -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H "Content-Type: application/json" -d "{\"environment_variables\": {\"ANTHROPIC_API_KEY\": \"$ANTHROPIC_KEY_TO_STORE\", \"OPENAI_API_KEY\": \"$OPENAI_KEY_TO_STORE\", \"GOOGLE_CLIENT_ID\": \"qa-google-client-$LEG\", \"GOOGLE_CLIENT_SECRET\": \"qa-google-secret\"}}"; echo
{"message":"Config updated successfully"}
$ curl -s -X PATCH http://127.0.0.1:$PORT_A/update/ui_theme_settings -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H "Content-Type: application/json" -d "{\"logo_url\": \"$LOGO\"}" | jq -c "{message}"
{"message":"UI theme settings updated successfully."}
### 3. After 150 seconds, every worker on A and B
proxy A worker 12675: chat/claude 200 messages/claude 200 responses/claude 200 chat/gpt 200
proxy A worker 12676: chat/claude 200 messages/claude 200 responses/claude 200 chat/gpt 200
proxy B worker 13090: chat/claude 200 messages/claude 200 responses/claude 200 chat/gpt 200
proxy B worker 13091: chat/claude 200 messages/claude 200 responses/claude 200 chat/gpt 200
proxy A worker 12675: GET /get/ui_theme_settings logo_url=https://example.com/qa-logo-after_cap.png, GET /sso/key/generate 303 -> https://accounts.google.com client_id=qa-google-client-after_cap
proxy A worker 12676: GET /get/ui_theme_settings logo_url=https://example.com/qa-logo-after_cap.png, GET /sso/key/generate 303 -> https://accounts.google.com client_id=qa-google-client-after_cap
proxy B worker 13091: GET /get/ui_theme_settings logo_url=https://example.com/qa-logo-after_cap.png, GET /sso/key/generate 303 -> https://accounts.google.com client_id=qa-google-client-after_cap
proxy B worker 13090: GET /get/ui_theme_settings logo_url=https://example.com/qa-logo-after_cap.png, GET /sso/key/generate 303 -> https://accounts.google.com client_id=qa-google-client-after_cap
### 4. Proxy C boots now with its own ANTHROPIC_API_KEY (sk-ant-process-env-not-a-real-key) in its process environment, after everything is stored, and every worker on C
listener pid 15830 on :52647 started with ANTHROPIC_API_KEY=sk-ant-process-env-not-a-real-key
listener pid 16089 on :52647 started with ANTHROPIC_API_KEY=sk-ant-process-env-not-a-real-key
listener pid 16090 on :52647 started with ANTHROPIC_API_KEY=sk-ant-process-env-not-a-real-key
proxy C worker 16089: chat/claude 200 messages/claude 200 responses/claude 200 chat/gpt 200
proxy C worker 16090: chat/claude 200 messages/claude 200 responses/claude 200 chat/gpt 200
proxy C worker 16089: GET /get/ui_theme_settings logo_url=https://example.com/qa-logo-after_cap.png, GET /sso/key/generate 303 -> https://accounts.google.com client_id=qa-google-client-after_cap
proxy C worker 16090: GET /get/ui_theme_settings logo_url=https://example.com/qa-logo-after_cap.png, GET /sso/key/generate 303 -> https://accounts.google.com client_id=qa-google-client-after_cap
### 5. Admin removes the keys and the SSO client through proxy B by sending null, then clears the logo
$ curl -s -X POST http://127.0.0.1:$PORT_B/config/update -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H "Content-Type: application/json" -d "{\"environment_variables\": {\"ANTHROPIC_API_KEY\": null, \"OPENAI_API_KEY\": null, \"GOOGLE_CLIENT_ID\": null, \"GOOGLE_CLIENT_SECRET\": null}}"; echo
{"message":"Config updated successfully"}
$ curl -s -X PATCH http://127.0.0.1:$PORT_B/update/ui_theme_settings -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H "Content-Type: application/json" -d "{}" | jq -c "{message}"
{"message":"UI theme settings updated successfully."}
### 6. After 150 seconds, every worker on A, B and C
proxy A worker 12675: chat/claude 401 messages/claude 401 responses/claude 401 chat/gpt 401
proxy A worker 12676: chat/claude 401 messages/claude 401 responses/claude 401 chat/gpt 401
proxy B worker 13090: chat/claude 401 messages/claude 401 responses/claude 401 chat/gpt 401
proxy B worker 13091: chat/claude 401 messages/claude 401 responses/claude 401 chat/gpt 401
proxy C worker 16089: chat/claude 401 messages/claude 401 responses/claude 401 chat/gpt 401
proxy C worker 16090: chat/claude 401 messages/claude 401 responses/claude 401 chat/gpt 401
error seen, proxy A claude 401: litellm.AuthenticationError: Missing Anthropic API Key - A call is being made to anthropic but no key is set e
error seen, proxy A gpt 401: litellm.AuthenticationError: AuthenticationError: OpenAIException - Incorrect API key provided: sk-proj-******
error seen, proxy B claude 401: litellm.AuthenticationError: Missing Anthropic API Key - A call is being made to anthropic but no key is set e
error seen, proxy B gpt 401: litellm.AuthenticationError: AuthenticationError: OpenAIException - Incorrect API key provided: sk-proj-******
error seen, proxy C claude 401: litellm.AuthenticationError: AnthropicException - {"type":"error","error":{"type":"authentication_error","mess
error seen, proxy C gpt 401: litellm.AuthenticationError: AuthenticationError: OpenAIException - Incorrect API key provided: sk-proj-******
proxy A worker 12675: GET /get/ui_theme_settings logo_url=none, GET /sso/key/generate 200 -> no redirect no client_id
proxy A worker 12676: GET /get/ui_theme_settings logo_url=none, GET /sso/key/generate 200 -> no redirect no client_id
proxy B worker 13091: GET /get/ui_theme_settings logo_url=none, GET /sso/key/generate 200 -> no redirect no client_id
proxy B worker 13090: GET /get/ui_theme_settings logo_url=none, GET /sso/key/generate 200 -> no redirect no client_id
proxy C worker 16089: GET /get/ui_theme_settings logo_url=none, GET /sso/key/generate 200 -> no redirect no client_id
proxy C worker 16090: GET /get/ui_theme_settings logo_url=none, GET /sso/key/generate 200 -> no redirect no client_id
DONE 23:42:19Z

The harness is the 1-main-* files in the gist

Side paths

A replica-reading proxy unsets a removed key, SSO clears without sso_settings, and rotation keeps a plaintext key

Side paths setup and results

A primary Postgres streams to a hot standby made with pg_basebackup, and pg_stat_replication shows streaming. Proxy A reads the primary with supported_db_objects: ["models"], so it never loads sso_settings from the DB. Proxy B points DATABASE_URL_READ_REPLICA at the standby. A DBA also writes a plaintext OPENAI_API_KEY into the row from psql. The admin removes the Anthropic key and the SSO client through B, then rotates the master key through POST /key/regenerate, and proxy C boots on the new master key. Both configs carry a fake OPENAI_API_KEY in environment_variables

Step Before (8bb8ac7) After (6cd1c1a)
4. Stored via A, 120 s later 200 and Google login 200 and Google login
6. Claude after removal via B 200 on 4 of 4 workers 401 on 4 of 4 workers
6. SSO login after removal Google on 4 of 4 workers no redirect on 4 of 4 workers
6. Plaintext OpenAI key 200 on 4 of 4 workers 200 on 4 of 4 workers
7. OpenAI key after rotation dropped from the row kept in the row
8. C on the new key, OpenAI 401, config.yaml fake key 200
8. C on the new key, Claude 401 401
Side paths after leg, full output (6cd1c1a)
### Setup: commit 6cd1c1adce. Primary Postgres :55691 streams to a hot standby on :41095. Proxy A (:57327) reads the primary with supported_db_objects ["models"], so it never loads sso_settings from the DB. Proxy B (:34335) sets DATABASE_URL_READ_REPLICA to the standby. 2 workers each, one Redis
$ psql -h 127.0.0.1 -p $PG_PRIMARY_PORT -U mateo -d litellm -Atc "SELECT application_name, state FROM pg_stat_replication"
walreceiver|streaming
$ psql -h 127.0.0.1 -p $PG_REPLICA_PORT -U mateo -d litellm -Atc "SELECT pg_is_in_recovery()"
t
### 1. Before anything is stored, every worker on A and B
proxy A worker 14834: claude 401 gpt 401 sso 200 -> no redirect no client_id
  claude error: litellm.AuthenticationError: Missing Anthropic API Key - A call is being made to anthropic
  gpt error: litellm.AuthenticationError: AuthenticationError: OpenAIException - Incorrect API key prov
proxy A worker 14835: claude 401 gpt 401 sso 200 -> no redirect no client_id
  claude error: litellm.AuthenticationError: Missing Anthropic API Key - A call is being made to anthropic
  gpt error: litellm.AuthenticationError: AuthenticationError: OpenAIException - Incorrect API key prov
proxy B worker 17371: claude 401 gpt 401 sso 200 -> no redirect no client_id
  claude error: litellm.AuthenticationError: Missing Anthropic API Key - A call is being made to anthropic
  gpt error: litellm.AuthenticationError: AuthenticationError: OpenAIException - Incorrect API key prov
proxy B worker 17372: claude 401 gpt 401 sso 200 -> no redirect no client_id
  claude error: litellm.AuthenticationError: Missing Anthropic API Key - A call is being made to anthropic
  gpt error: litellm.AuthenticationError: AuthenticationError: OpenAIException - Incorrect API key prov
### 2. Admin stores the Anthropic key, a Google SSO client and a marker through proxy A
$ curl -s -X POST http://127.0.0.1:$PORT_A/config/update -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H "Content-Type: application/json" -d "{\"environment_variables\": {\"ANTHROPIC_API_KEY\": \"$ANTHROPIC_KEY_TO_STORE\", \"GOOGLE_CLIENT_ID\": \"qa-google-client-$LEG\", \"GOOGLE_CLIENT_SECRET\": \"qa-google-secret\", \"QA_MARKER\": \"kept\"}}"; echo
{"message":"Config updated successfully"}
### 3. A DBA writes OPENAI_API_KEY into the same row as plaintext from psql
$ psql -h 127.0.0.1 -p 55691 -U mateo -d litellm -v key=<OpenAI key> <<< 'UPDATE "LiteLLM_Config" SET param_value = param_value || jsonb_build_object('\''OPENAI_API_KEY'\'', :'\''key'\'') WHERE param_name = '\''environment_variables'\'';'
UPDATE 1
row keys: ANTHROPIC_API_KEY, GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET, OPENAI_API_KEY, QA_MARKER
### 4. After 120 seconds, every worker on A and B
proxy A worker 14835: claude 200 gpt 200 sso 303 -> https://accounts.google.com client_id=qa-google-client-after_cap
proxy A worker 14834: claude 200 gpt 200 sso 303 -> https://accounts.google.com client_id=qa-google-client-after_cap
proxy B worker 17372: claude 200 gpt 200 sso 303 -> https://accounts.google.com client_id=qa-google-client-after_cap
proxy B worker 17371: claude 200 gpt 200 sso 303 -> https://accounts.google.com client_id=qa-google-client-after_cap
### 5. Admin removes the Anthropic key and the SSO client through proxy B, which reads the standby
$ curl -s -X POST http://127.0.0.1:$PORT_B/config/update -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H "Content-Type: application/json" -d "{\"environment_variables\": {\"ANTHROPIC_API_KEY\": null, \"GOOGLE_CLIENT_ID\": null, \"GOOGLE_CLIENT_SECRET\": null}}"; echo
{"message":"Config updated successfully"}
row keys: ANTHROPIC_API_KEY, GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET, OPENAI_API_KEY, QA_MARKER
### 6. After 120 seconds, every worker on A and B
proxy A worker 14834: claude 401 gpt 200 sso 200 -> no redirect no client_id
  claude error: litellm.AuthenticationError: Missing Anthropic API Key - A call is being made to anthropic
proxy A worker 14835: claude 401 gpt 200 sso 200 -> no redirect no client_id
  claude error: litellm.AuthenticationError: Missing Anthropic API Key - A call is being made to anthropic
proxy B worker 17372: claude 401 gpt 200 sso 200 -> no redirect no client_id
  claude error: litellm.AuthenticationError: Missing Anthropic API Key - A call is being made to anthropic
proxy B worker 17371: claude 401 gpt 200 sso 200 -> no redirect no client_id
  claude error: litellm.AuthenticationError: Missing Anthropic API Key - A call is being made to anthropic
### 7. Admin rotates the master key through proxy A
$ curl -s -o /dev/null -w "%{http_code}\n" -X POST http://127.0.0.1:$PORT_A/key/regenerate -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H "Content-Type: application/json" -d "{\"key\": \"$LITELLM_MASTER_KEY\", \"new_master_key\": \"$NEW_MASTER_KEY\"}"
200
row keys: ANTHROPIC_API_KEY, GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET, OPENAI_API_KEY, QA_MARKER
### 8. Proxy C boots with the new master key against the primary, and every worker on C
proxy C worker 22384: claude 401 gpt 200 sso 200 -> no redirect no client_id
  claude error: litellm.AuthenticationError: Missing Anthropic API Key - A call is being made to anthropic
proxy C worker 22383: claude 401 gpt 200 sso 200 -> no redirect no client_id
  claude error: litellm.AuthenticationError: Missing Anthropic API Key - A call is being made to anthropic
DONE 23:46:52Z
Side paths before leg, full output (8bb8ac7)
### Setup: commit 8bb8ac7f18. Primary Postgres :52555 streams to a hot standby on :44481. Proxy A (:35681) reads the primary with supported_db_objects ["models"], so it never loads sso_settings from the DB. Proxy B (:45009) sets DATABASE_URL_READ_REPLICA to the standby. 2 workers each, one Redis
$ psql -h 127.0.0.1 -p $PG_PRIMARY_PORT -U mateo -d litellm -Atc "SELECT application_name, state FROM pg_stat_replication"
walreceiver|streaming
$ psql -h 127.0.0.1 -p $PG_REPLICA_PORT -U mateo -d litellm -Atc "SELECT pg_is_in_recovery()"
t
### 1. Before anything is stored, every worker on A and B
proxy A worker 14904: claude 401 gpt 401 sso 200 -> no redirect no client_id
  claude error: litellm.AuthenticationError: Missing Anthropic API Key - A call is being made to anthropic
  gpt error: litellm.AuthenticationError: AuthenticationError: OpenAIException - Incorrect API key prov
proxy A worker 14903: claude 401 gpt 401 sso 200 -> no redirect no client_id
  claude error: litellm.AuthenticationError: Missing Anthropic API Key - A call is being made to anthropic
  gpt error: litellm.AuthenticationError: AuthenticationError: OpenAIException - Incorrect API key prov
proxy B worker 17641: claude 401 gpt 401 sso 200 -> no redirect no client_id
  claude error: litellm.AuthenticationError: Missing Anthropic API Key - A call is being made to anthropic
  gpt error: litellm.AuthenticationError: AuthenticationError: OpenAIException - Incorrect API key prov
proxy B worker 17642: claude 401 gpt 401 sso 200 -> no redirect no client_id
  claude error: litellm.AuthenticationError: Missing Anthropic API Key - A call is being made to anthropic
  gpt error: litellm.AuthenticationError: AuthenticationError: OpenAIException - Incorrect API key prov
### 2. Admin stores the Anthropic key, a Google SSO client and a marker through proxy A
$ curl -s -X POST http://127.0.0.1:$PORT_A/config/update -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H "Content-Type: application/json" -d "{\"environment_variables\": {\"ANTHROPIC_API_KEY\": \"$ANTHROPIC_KEY_TO_STORE\", \"GOOGLE_CLIENT_ID\": \"qa-google-client-$LEG\", \"GOOGLE_CLIENT_SECRET\": \"qa-google-secret\", \"QA_MARKER\": \"kept\"}}"; echo
{"message":"Config updated successfully"}
### 3. A DBA writes OPENAI_API_KEY into the same row as plaintext from psql
$ psql -h 127.0.0.1 -p 52555 -U mateo -d litellm -v key=<OpenAI key> <<< 'UPDATE "LiteLLM_Config" SET param_value = param_value || jsonb_build_object('\''OPENAI_API_KEY'\'', :'\''key'\'') WHERE param_name = '\''environment_variables'\'';'
UPDATE 1
row keys: ANTHROPIC_API_KEY, GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET, OPENAI_API_KEY, QA_MARKER
### 4. After 120 seconds, every worker on A and B
proxy A worker 14903: claude 200 gpt 200 sso 303 -> https://accounts.google.com client_id=qa-google-client-before_8bb
proxy A worker 14904: claude 200 gpt 200 sso 303 -> https://accounts.google.com client_id=qa-google-client-before_8bb
proxy B worker 17642: claude 200 gpt 200 sso 303 -> https://accounts.google.com client_id=qa-google-client-before_8bb
proxy B worker 17641: claude 200 gpt 200 sso 303 -> https://accounts.google.com client_id=qa-google-client-before_8bb
### 5. Admin removes the Anthropic key and the SSO client through proxy B, which reads the standby
$ curl -s -X POST http://127.0.0.1:$PORT_B/config/update -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H "Content-Type: application/json" -d "{\"environment_variables\": {\"ANTHROPIC_API_KEY\": null, \"GOOGLE_CLIENT_ID\": null, \"GOOGLE_CLIENT_SECRET\": null}}"; echo
{"message":"Config updated successfully"}
row keys: ANTHROPIC_API_KEY, GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET, OPENAI_API_KEY, QA_MARKER
### 6. After 120 seconds, every worker on A and B
proxy A worker 14904: claude 200 gpt 200 sso 303 -> https://accounts.google.com client_id=qa-google-client-before_8bb
proxy A worker 14903: claude 200 gpt 200 sso 303 -> https://accounts.google.com client_id=qa-google-client-before_8bb
proxy B worker 17641: claude 200 gpt 200 sso 303 -> https://accounts.google.com client_id=qa-google-client-before_8bb
proxy B worker 17642: claude 200 gpt 200 sso 303 -> https://accounts.google.com client_id=qa-google-client-before_8bb
### 7. Admin rotates the master key through proxy A
$ curl -s -o /dev/null -w "%{http_code}\n" -X POST http://127.0.0.1:$PORT_A/key/regenerate -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H "Content-Type: application/json" -d "{\"key\": \"$LITELLM_MASTER_KEY\", \"new_master_key\": \"$NEW_MASTER_KEY\"}"
200
row keys: QA_MARKER
### 8. Proxy C boots with the new master key against the primary, and every worker on C
proxy C worker 22439: claude 401 gpt 401 sso 200 -> no redirect no client_id
  claude error: litellm.AuthenticationError: Missing Anthropic API Key - A call is being made to anthropic
  gpt error: litellm.AuthenticationError: AuthenticationError: OpenAIException - Incorrect API key prov
proxy C worker 22440: claude 401 gpt 401 sso 200 -> no redirect no client_id
  claude error: litellm.AuthenticationError: Missing Anthropic API Key - A call is being made to anthropic
  gpt error: litellm.AuthenticationError: AuthenticationError: OpenAIException - Incorrect API key prov
DONE 23:46:52Z

The harness is the 2-side-* files in the same gist

/audit round 3 of 3, run again at 6cd1c1a after the capacity-error fix

PASS. Each request-path row is red on the base and green twice on the head, the new capacity cell included

Matrix, node ids, red evidence and unit evidence

Rig lit9489a3b on the GCE box ran base 8bb8ac7 and head 6cd1c1a. Lanes sel-base, sel-head-1, sel-head-2, ctl-head, cap-base, cap-head-1, cap-head-2 and cap-ctl-at-45da29d09a ran run.py management with 2 workers, seed 46709 and order seed 9489. Nothing inside the proxy is mocked. The base leg carries the head's tests and trigger migration

Contract Base Head 1 Head 2
Removal reaches both proxies FAIL PASS PASS
Process and config.yaml values return FAIL PASS PASS
Replica on an older row FAIL PASS PASS
SSO client removed from env row FAIL PASS PASS
SSO client moved to SSO table not reached PASS PASS
db push proxy unsets a removed key FAIL PASS PASS
Save from outside the table's schema PASS PASS PASS
Revision rises past a lagging sequence PASS PASS PASS
Role without sequence grants saves PASS PASS PASS
Writer out of connections keeps env FAIL PASS PASS
5 controls on the head n/a PASS n/a

Node ids, all in tests/integration/configuration/test_effective_settings.py

  • test_removing_db_environment_variables_restores_process_and_config_file_values_on_every_proxy
  • test_a_read_replica_back_on_an_older_row_does_not_bring_back_a_removed_db_environment_variable
  • test_an_sso_client_removed_from_db_environment_variables_stops_sign_in_on_every_proxy
  • test_a_proxy_that_pushes_its_own_schema_unsets_a_removed_db_environment_variable
  • test_db_environment_variables_saved_from_a_session_outside_the_tables_schema_still_get_a_revision
  • test_db_environment_variables_revision_keeps_rising_after_its_sequence_falls_behind_the_row
  • test_a_database_role_with_no_sequence_grants_can_still_save_db_environment_variables
  • test_a_writer_database_out_of_connections_keeps_the_applied_db_environment_variables (new)
  • Controls test_multi_section_config_update_merges_sent_keys_normalizes_callbacks_and_applies_on_the_peer, test_deleted_callback_case_variant_stops_delivery_on_both_workers, test_dashboard_field_updates_preserve_plugin_key_and_apply_at_runtime, test_saved_retry_setting_controls_real_attempts_and_restores, test_credential_value_update_and_model_reload_reach_provider

The new cell makes the writer database belong to a non-superuser role and sets that role's connection limit to 0 after the replica goes back to the older row. Postgres then refuses the proxy's next writer connection with FATAL: too many connections for role. On the head the proxy logs Could not read environment_variables from the writer database, keeping the current environment variables, /get/config/callbacks answers 200 and the removed key stays unset. Once the limit is lifted, a newer writer row applies

Base red evidence

removal       State did not converge: ('database Bearer database-key-86aa3f0f…', 'database Bearer database-key-86aa3f0f…')
replica       State did not converge: 'database Bearer database-key-7d245ff3…'
sso           State did not converge: ('environment-row-client-f86501b1…', 'environment-row-client-f86501b1…')
db push       State did not converge: 'database Bearer database-key-ac04d1b9…'
capacity      State did not converge: 'database Bearer database-key-a84d8546…' (unset step)

With only proxy_server.py at 45da29d, the new cell fails at the config read

assert 400 == 200
"Authentication Error, Error in connector: Error querying the database: FATAL: too many connections for role ..."

Unit evidence ran on the box over the 9 mapped files. At the tip 1944 passed and 12 skipped. With proxy_server.py at 45da29d, 2 failed, both test_a_writer_that_cannot_answer_keeps_the_applied_environment_variables_when_the_cached_row_is_behind[out_of_connections-*] with FATAL: sorry, too many clients already. The cead870 swap cannot import in the merged tree, so the two race tests keep their d623028 result (2 red on the swap) and pass at this tip

/live-pr-risk at 6cd1c1a merged with main 7f603da (1ef1373501), against the merge base 8bb8ac7

Both legs ran on a dedicated GCE machine. Proxies A and B run 2 workers each on a writer database plus a read replica database through DATABASE_URL_READ_REPLICA, one Redis, and a recorder in front of api.anthropic.com. The proxies reach the writer through a TCP forwarder that the script stops to take the writer down, or slows to make config syncs overlap in K1 and K2. In W3 the writer is a real Postgres at max_connections, so every new writer connection gets sorry, too many clients already. After each change the script waits 75 seconds, two and a half config sync cycles, and then calls a real Anthropic model through chat completions, messages and responses on every worker. The read replica is a second database that the script copies from the writer, so it can also serve an older row or lag on purpose. Proxy C boots last with --use_prisma_db_push on a fresh database. The harness is the 3-lpr-* files in the same gist

Cell Base 8bb8ac7 Merged 1ef1373501
1. Nothing stored 401 401
R1. Store the key via A 200 200
R2. Null the key via B 200 401
R3. Replica back on the R1 row 200 401
R4. Control, replica revision +1000 200 200
R5. Replica matches the writer 200 401
S1. SSO client in the env row env row client env row client
S2. PATCH /update/sso_settings SSO table client SSO table client
H1. Key plus odd values 200 200
H2. Null all of them 200 401
W1. Writer down, replica on the R1 row 200 401
W1. Config reads, writer down 200 200
W2. Writer back 200 401
L1. Save via B, replica lags first key lost both keys kept
L2. Theme save via B, replica lags earlier keys lost all keys kept
P1. Trigger after db push 0 1
P1. Null the key on C 200 401
K1. Overlapping syncs, store via B 200 200
K2. Overlapping syncs, remove last 200 401
W3. Writer full, replica behind 200 401
W3. Config reads, writer full 200 200
W4. Writer free again 200 401
Writer revision at H2 0 11

Both trees sampled every call on all 4 workers. Config reads are GET /get/ui_theme_settings and GET /v2/model/info, which both run the config sync's DB read. In W1 and W3 the merged workers kept the removed key unset and logged Could not read environment_variables from the writer database, keeping the current environment variables until the next config sync, 18 and 12 times in W1 and 22 and 11 more in W3. Config reads during the K1 and K2 bursts answered 200 every time on both proxies

Breaking changes

None found. Every call that worked on the base still works on the merged tree, unless an admin removed the key it used. At d623028, W3's config reads answered 503 because a writer capacity error escaped the writer re-read. 6cd1c1a keeps the applied env vars on that error too, and the same cell now answers 200

Backward incompatible changes

When two env var saves race, the read, merge and upsert in /config/update can drop a key from the stored row. The stored row is the same on both trees. Main kept that key on every running worker until a restart, while this PR unsets it on every worker within one sync. That is the behavior LIT-9489's acceptance asks for, a key gone from the DB row is gone from every pod by the next sync, and the race itself is the Medium caveat below

Master key rotation now keeps env values it cannot decrypt, such as a plaintext key a DBA wrote into the row. Main dropped them, so a proxy booted on the new key lost that provider. The side path QA shows OpenAI at 401 on the base and 200 on the head in step 8

A proxy started with --use_prisma_db_push now also runs prisma db execute on the trigger migration. When the role cannot create the function or trigger, the proxy logs a warning and boots, and removals then wait for a restart as on main. That failure path is covered by a unit test only

Regression risk

During a writer outage, a worker whose replica row is behind runs the shared Prisma reconnect cycle from its config sync, bounded by the reconnect cooldown, and the merged proxies logged environment_variables_writer_read_failure 26 and 20 times across the run. A capacity error is not a transport error, so W3 fired no reconnect, and no traceback on either merged proxy comes from _update_config_from_db. Both trees served chat, config reads and saves again right after the writer came back or freed connections

While the replica is behind the applied revision, each config read also reads the env row from the writer. In K2 the forwarder held each writer reply chunk for 0.5 seconds, and the median config read took 0.52 seconds on the merged tree against 0.03 on the base. With a writer at normal speed that is one extra writer read per config read until the replica catches up

During a rolling deploy, pods on the old version write cached config rows without a revision. A new pod that reads one of those re-reads the row from the writer once per sync until the old pods are gone. This is reasoned from the code and not measured

The merged proxies logged 405 and 434 tracebacks against 136 and 213 on the base. 95 and 136 of the merged ones are the expected Anthropic 401s in the cells that now fail. Most of the rest are spend and request tracking writes that failed while the writer was down in W1 or full in W3, which the base logged too. Error setting env variable is 108 on both merged proxies and 126 on both base proxies, from the same non-string H1 values

Dependency graph

The tip's only product change turns a raise into a warning on one path, _environment_row_not_behind_the_applied_one, reached only through _update_config_from_db from get_config, which has 38 call sites under litellm/proxy. None depends on the raise, and every other error still raises. Verified live here are provider auth on chat completions, messages and responses, the restore of a process env or config.yaml value, /config/update, the theme logo, SSO through the env row, the PATCH /update/sso_settings move, the writer re-read for a stale replica row, the writer outage and writer capacity fallbacks, overlapping syncs during slow writer reads, saves reading the writer while the replica lags, the trigger after db push, recovery after the revision went backwards, and odd stored values. The side path QA adds a real streaming replica, SSO with sso_settings left out of supported_db_objects, and master key rotation. Covered by unit tests only are the SSO save and rotation while the replica lags, and the db push trigger failure warning. The credential migration, the periodic reload schedule, the MCP catalog, and the other get_config_param callers read other config rows and are unaffected

Legacy integration suites

Not rerun at 1ef1373501, since the changed lines run only when the writer read fails and these suites never make it fail. At 247e690596 the configuration lane passed 28 of 28 and observability passed 125 of 126, and its one failure also fails on the base

Not verified live

A mixed-version rollout, the SSO save and master key rotation while the replica lags, and the db push trigger failure warning

Type

🐛 Bug Fix

Caveats (if any)

Each High and Medium below is fixed except the save race, which main has too

High

  • A writer outage or a writer out of connections, while the replica served an older env row, broke config reads
    • Fixed. The worker keeps its env vars and retries on the next sync
  • The trigger found its sequence through search_path, so a save from a session outside the table's schema failed
    • Fixed. The trigger looks up the sequence in TG_TABLE_SCHEMA

Medium

  • Two env var saves at the same time can lose a key, since neither locks the row, the same as main
    • Saves now read the writer, and every worker unsets a lost key within one sync instead of at restart
  • Saves read the env row from the replica, so replica lag could drop a key just stored
    • Fixed for /config/update, the theme save, the SSO save and master key rotation
  • A proxy started with --use_prisma_db_push never got the trigger
    • Fixed. The proxy runs the trigger SQL with prisma db execute after db push
  • Master key rotation, SSO without sso_settings, and a streaming replica had no live proof
    • Fixed. Side path QA covers all three

Low

  • Under replica lag, the worker that served a save applies the removal on its next sync, within 30 seconds
  • Without models in supported_db_objects, a removal reaches workers only when an admin route reloads the config, the same as main
  • The migration grants USAGE on the revision sequence to PUBLIC, so any role can call nextval, which only skips revision numbers
  • The migration's DROP TRIGGER IF EXISTS briefly locks LiteLLM_Config at boot, bounded by lock_timeout = '10s'
  • While the read replica is behind, each config read also reads the env row from the writer

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

  • eee7456 passes /audit

  • 6cd1c1a passes /live-pr-risk

Bugbot summary

[!NOTE]
High Risk
Changes runtime application of DB-backed secrets and SSO-related env vars across pods, with new DB triggers and writer/replica read behavior; mis-sync could briefly affect auth or provider routing.

Overview
Fixes multi-worker proxies keeping DB-stored env vars (API keys, SSO clients, etc.) in os.environ after they are removed from LiteLLM_Config, by versioning the environment_variables row and teaching each worker to apply only current revisions.

A Postgres migration adds a sequence and before insert/update trigger on LiteLLM_Config when param_name = 'environment_variables', bumping reload_revision. prisma db push now runs that SQL via litellm-proxy-extras (warn-only on failure).

ProxyConfig no longer applies env vars through the generic settings path. It tracks applied revision, keys owned by the DB row, a first-sync env snapshot for restores, and overlapping-sync ordering. On a newer revision it applies decrypted values and unsets keys dropped from the row (restoring process/config.yaml values, with special handling for SSO env vars vs the SSO settings table). Stale cached or replica rows trigger a writer re-read; writer failures keep the last applied env until the next sync.

Config param cache and reads now carry reload_revision. Paths that merge or rotate the env row (/config/update, SSO cleanup, master key rotation) read from the writer and master-key rotation merges re-encrypted values instead of replacing the whole row (preserving plaintext or foreign-key ciphertext).

Integration and unit tests cover multi-proxy removal, replica lag, db push, writer capacity limits, SSO, and sequence/schema edge cases.

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

@devin-ai-integration

devin-ai-integration Bot commented Oct 15, 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

@mateo-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review

@codspeed

codspeed Bot commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

⚠️ 1 benchmark spent significant time in system calls

System calls cannot be consistently instrumented, so they are not included in the measure, which understates the real cost. Please switch to the Walltime instrument to accurately measure system calls.

Measurement and system calls

✅ 32 untouched benchmarks


Comparing litellm_unset_removed_db_env_vars_by_row_revision (eee7456) with main (fc484be)1

Open in CodSpeed

Footnotes

  1. No successful run was found on main (81a3802) during the generation of this report, so fc484be was used instead as the comparison base. There might be some changes unrelated to this pull request in this report. ↩

@codecov

codecov Bot commented Oct 15, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 80.00000% with 26 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
litellm/proxy/db/prisma_client.py 52.17% 11 Missing ⚠️
litellm/proxy/proxy_server.py 87.91% 11 Missing ⚠️
litellm/proxy/utils.py 69.23% 4 Missing ⚠️

📢 Thoughts on this report? Let us know!

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

Comment thread litellm/proxy/proxy_server.py Resolved
Comment thread litellm/proxy/proxy_server.py Resolved
@litereview

litereview Bot commented Oct 15, 2026 •

Copy link
Copy Markdown

✅ code-review

5/5 · Ready for human review

Scope: full · Full PR review.

No correctness findings.

Checks and execution details
  • Passed · Real testing evidence (required): Not applicable: no LLM translation changes in the scoped paths. The PR touches litellm/proxy/**, litellm-proxy-extras/** migrations and tests. Nothing under litellm/llms/** or litellm/litellm_core_utils/prompt_templates/** changes.

  • Passed · Compatibility requirements (required): No supported behavior breaks.

  • The migration adds a sequence, a function and a row trigger on the existing LiteLLM_Config.reload_revision column. That column already exists from migration 20260729000000.

  • Cached rows written without reload_revision unpack to None. They still apply until a revision has been applied, and after that they trigger a re-read from the writer.

  • Before this PR, a key removed from the row stayed in os.environ. After it, a newer revision restores the pre-DB value. That is the bug the PR sets out to fix.

  • Master key rotation used to drop entries it could not decrypt. It now keeps them, via {**environment_variables_dict, **encrypted_env_vars}, which removes data loss rather than rejecting a previously accepted input.

No ! marker is needed.

  • Passed · Changed behavior and result consistency (required): Standards read: root AGENTS.md, tests/AGENTS.md, tests/integration/AGENTS.md and tests/integration/README.md.

Paths traced:

  • _update_config_from_db → _captured_environment_before_db (taken before the missing-row skip) → _apply_db_environment_variables_row → _environment_row_not_behind_the_applied_one (writer re-read with transport/connection-error fallback) → _apply_db_environment_variables (read-number guard, revision compare, _restore_environment).
  • SSO deferral through _init_non_llm_objects_in_db and _init_sso_settings_in_db → _restore_sso_environment_removals.
  • Writer reads in save_environment_variables, update_config._read_section, update_sso_settings and rotate_master_key.
  • The db push path in setup_database → _apply_environment_variables_revision_trigger.

Boundary cases checked:

  • A lowercase stored key also sets and unsets its uppercase form.
  • A non-string JSON value fails os.environ assignment inside decrypt_and_set_db_env_variables and is skipped, as on main. Mapping[str, str] validation therefore cannot reject it.
  • A revision of None or an equal revision only adds keys.
  • An overlapping sync with an older read number is dropped.
  • A writer outage keeps the applied environment.

Prior finding 4085dc1b…:0 (UI logo) stays withdrawn. The snapshot still runs before the missing-row continue at proxy_server.py:8392.

  • Passed · Unit tests for changed proxy modules (optional): First I ran prisma generate against schema.prisma, because the archive ships without a generated client and that caused 9 import failures.

Then I ran pytest tests/unit/proxy/proxy_server/test_proxy_config.py tests/unit/proxy/db/test_prisma_client.py tests/unit/proxy/management_endpoints/test_key_management_endpoints.py tests/unit/proxy/test_proxy_server_endpoints_and_startup.py tests/unit/proxy/utils/prisma_and_spend/test_config_param_cache.py tests/unit/proxy/ui_crud_endpoints/test_proxy_setting_endpoints.py.

Result: 1760 passed.

  • Passed · New env-var revision integration tests (real proxy + Postgres + Redis) (optional): Command: tests/integration/run.py management --workers 2 on the 8 new tests in tests/integration/configuration/test_effective_settings.py, against local Postgres and Redis.

On Postgres 15, 7 passed. test_a_writer_database_out_of_connections_keeps_the_applied_db_environment_variables failed in setup. Its NOINHERIT capped role hit permission denied for schema public during prisma db push: on PG15, public is owned by pg_database_owner, and a NOINHERIT role cannot use that membership.

On Postgres 16, the version CI pins (postgres:16@​sha256:e17e…), the same db push succeeded and the test passed, together with test_removing_db_environment_variables_restores_process_and_config_file_values_on_every_proxy (2 passed). This is a test-environment limitation, not a product defect.


View review · Reviewed eee7456f160c

self.environment_variables.apply_db_row("environment_variables", _as_settings_mapping(applied))

def _captured_environment_before_db(self) -> Mapping[str, str]:
if self._environment_before_db is None:

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Medium · Cleared UI logo comes back on the worker that cleared it

  1. A worker starts with no environment_variables row in LiteLLM_Config, which is the normal state for a fresh install. _update_config_from_db skips the missing row, so _captured_environment_before_db() takes no snapshot yet.
  2. An admin sets a logo with PATCH /update/ui_theme_settings. That endpoint writes os.environ["UI_LOGO_PATH"] inline on the worker that served the request, then save_environment_variables creates the row (revision 1).
  3. On that worker's next sync, _apply_db_environment_variables takes the snapshot for the first time. os.environ already holds the logo URL, so the snapshot records it as the worker's own pre-DB value.
  4. The admin clears the logo. The endpoint pops UI_LOGO_PATH inline, and the row drops the key (revision 2).
  5. On the next sync, _restore_environment restores UI_LOGO_PATH from the snapshot, so that worker serves the old logo again until it restarts. On main, the pop stuck because the sync never re-added a key missing from the row.

The smallest fix is to take the snapshot right after _load_environment_variables runs in load_config, before any request can change the environment. Another fix is to take it on the first sync even when the row is missing.

Evidence

Executable reproducer, run as a temporary file under tests/unit/proxy/. It stubs get_config_param like the PR's own unit tests do and drives ProxyConfig._update_config_from_db. Sequence: sync with no row, set UI_LOGO_PATH inline plus a row at revision 1 holding it, sync, pop UI_LOGO_PATH plus a row at revision 2 without it, sync. Result: assert os.environ.get("UI_LOGO_PATH") is None FAILED, value 'https://example.com/logo.png'.

_update_config_from_db: if response is None or (param_value := ...) is None: continue. A missing row never reaches _captured_environment_before_db.

_captured_environment_before_db sets self._environment_before_db = MappingProxyType(dict(os.environ)) lazily, only on the first call.

proxy_setting_endpoints.py:1478-1488 (update_ui_theme_settings) mutates os.environ inline for UI_LOGO_PATH, UI_LOGO_PATH_DARK and LITELLM_FAVICON_URL, then calls save_environment_variables, which upserts the environment_variables row.

The PR description says the snapshot is 'taken right before its first DB apply, after config.yaml environment_variables load'. With no row, the 'first DB apply' can come long after request handling has started.

Peer workers are unaffected because they never set the value inline. Only the serving worker is affected, which code inspection plus the reproducer confirm.

Latest summary by code-review · View this review · Reviewed 61613a00b182

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.

Fixed in 2888f0c. The snapshot is now taken at the first DB sync whether or not the row exists, with a regression test

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Finding withdrawn

The fix holds against the current code. _update_config_from_db calls self._captured_environment_before_db() right after the store_model_in_db guard. That happens before the loop that skips a missing row, so the first DB sync takes the snapshot even when no row exists. The first sync runs during startup through load_config → get_config, or through the startup add_deployment when store_model_in_db is set from the DB. Both run before request handlers can write UI_LOGO_PATH inline, so a later restore cannot bring back a value set at runtime. The new test test_removed_key_does_not_come_back_with_a_value_set_after_the_first_sync_without_a_row replays the original reproducer: a sync with no row, an inline set plus revision 1, then an inline pop plus revision 2. It asserts the key stays unset, and it passes.

Evidence

litellm/proxy/proxy_server.py:8313: environment_before_db: Final = self._captured_environment_before_db() runs before the if response is None ... continue loop at 8316-8317.

litellm/proxy/proxy_server.py:8376-8379: the snapshot is captured lazily the first time this runs, which is now the first sync whether or not a row exists.

litellm/proxy/proxy_server.py:6315-6323: get_config calls _update_config_from_db during load_config at startup. proxy_server.py:11146 runs the startup add_deployment before the scheduler-driven syncs.

tests/unit/proxy/proxy_server/test_proxy_config.py:5141-5153: the regression test syncs with no row, sets the key and syncs revision 1, deletes the key and syncs revision 2, then asserts os.environ.get("REVISION_TEST_DB_ONLY") is None.

Ran uv run --frozen --extra proxy --group proxy-dev pytest -q tests/unit/proxy/proxy_server/test_proxy_config.py -k "revision or removed_key or sso_settings": 4 passed, including the regression test.

GitHub does not allow this App to resolve this thread. A repository maintainer must do it manually.

Reviewed 2888f0c7c766 · View follow-up

@mateo-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review

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

Grant the revision sequence to every role so a writer role with only
table grants can still save environment_variables. Unset SSO keys that
only the environment_variables row stored on the next SSO sync, while
keeping keys the SSO settings table holds. Skip a revision-less row once
a revision has been applied, so a stale cached row cannot bring a
removed key back. Keep plaintext and undecryptable values when rotating
the master key instead of dropping them from the row.
@mateo-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review

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

Stale Bugbot comment from a previous run.

…tores

Stamp at least the old revision plus one on update so a copied row keeps
rising, re-read a stale cached row from the writer and apply it when the
database itself went back, unset dropped SSO keys when sso_settings are not
loaded from the DB, and keep env values master key rotation cannot decrypt
exactly as stored
@mateo-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review

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

);
ELSE
NEW."reload_revision" := nextval('"litellm_environment_variables_revision_seq"');
END IF;

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.

Insert path can stamp a lower revision

Low Severity

The UPDATE trigger uses GREATEST(nextval(...), OLD.reload_revision + 1) so a restarted sequence cannot lower the row, but INSERT still assigns only nextval. A delete and re-insert after the sequence falls behind can persist a smaller reload_revision, which workers now apply instead of skipping.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit c9bd16d. Configure here.

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.

After a delete there is no old revision to compare against, and workers re-read the writer, so applying the re-inserted row is intended

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review

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

Stale Bugbot comment from a previous run.

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review

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

Stale Bugbot comment from a previous run.

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review

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

✅ Bugbot reviewed your changes and found no new issues!

1 issue from previous review remains unresolved.

Fix All in Cursor

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

Reviewed by Cursor Bugbot for commit eee7456. Configure here.

@mateo-berri
mateo-berri merged commit 6104435 into main Oct 17, 2026
108 of 110 checks passed
@mateo-berri
mateo-berri deleted the litellm_unset_removed_db_env_vars_by_row_revision branch October 17, 2026 03:51
yuneng-berri added a commit that referenced this pull request Oct 19, 2026
…lic internet (#47409)

The SSO removal test configured Google sign-in, which fetches its discovery
document from accounts.google.com before redirecting. CircleCI blocks that
egress, so the test failed on every main run since #46709 added it. Microsoft
sign-in builds its endpoints locally and goes through the same SSO environment
variable handling, so the test now uses it

This branch was successfully deployed

No deployments
e2e-changed — eee7456f Deployed Oct 17, 2026 by mateo-berri via oauth #5813
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.

3 participants