Repository navigation
fix(proxy): unset DB environment variables removed from the row on every worker by row revision - #46709
Conversation
…ery worker by row revision
|
I'll fix CI failures and address comments from users with write access. I'll skip comments containing "(aside)".
|
|
bugbot run |
|
@litereview code-review |
Merging this PR will not alter performance
|
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
✅ code-review5/5 · Ready for human reviewScope: full · Full PR review. No correctness findings. Checks and execution details
No
Paths traced:
Boundary cases checked:
Prior finding
Then I ran Result: 1760 passed.
On Postgres 15, 7 passed. On Postgres 16, the version CI pins ( View review · Reviewed |
| 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: |
There was a problem hiding this comment.
Medium · Cleared UI logo comes back on the worker that cleared it
- A worker starts with no
environment_variablesrow inLiteLLM_Config, which is the normal state for a fresh install._update_config_from_dbskips the missing row, so_captured_environment_before_db()takes no snapshot yet. - An admin sets a logo with
PATCH /update/ui_theme_settings. That endpoint writesos.environ["UI_LOGO_PATH"]inline on the worker that served the request, thensave_environment_variablescreates the row (revision 1). - On that worker's next sync,
_apply_db_environment_variablestakes the snapshot for the first time.os.environalready holds the logo URL, so the snapshot records it as the worker's own pre-DB value. - The admin clears the logo. The endpoint pops
UI_LOGO_PATHinline, and the row drops the key (revision 2). - On the next sync,
_restore_environmentrestoresUI_LOGO_PATHfrom 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
There was a problem hiding this comment.
Fixed in 2888f0c. The snapshot is now taken at the first DB sync whether or not the row exists, with a regression test
There was a problem hiding this comment.
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
…main's and set its lock timeout
…o environment_variables row exists yet
|
bugbot run |
|
@litereview code-review |
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.
|
@litereview code-review |
|
bugbot 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
|
bugbot run |
|
@litereview code-review |
| ); | ||
| ELSE | ||
| NEW."reload_revision" := nextval('"litellm_environment_variables_revision_seq"'); | ||
| END IF; |
There was a problem hiding this comment.
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.
Reviewed by Cursor Bugbot for commit c9bd16d. Configure here.
There was a problem hiding this comment.
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
|
@litereview code-review |
|
bugbot run |
…tabase is out of connections
|
@litereview code-review |
|
bugbot run |
…r integration tests
|
@litereview code-review |
|
bugbot run |
There was a problem hiding this comment.
✅ Bugbot reviewed your changes and found no new issues!
1 issue from previous review remains unresolved.
Comment @cursor review or bugbot run to trigger another review on this PR
Reviewed by Cursor Bugbot for commit eee7456. Configure here.
…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


TLDR
Problem this solves:
How it solves it:
User Flow
Before: an admin removes a stored Anthropic key, and every worker keeps using it
{"environment_variables": {"ANTHROPIC_API_KEY": "sk-ant-..."}}and gets success{"environment_variables": {"ANTHROPIC_API_KEY": null}}to the same route, which also returns successAfter: each worker drops the removed key on its next config sync
Missing Anthropic API Keyon every worker, or uses the pod's own env or config.yaml keyRelevant 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
environment_variablesconfig row bumps on every insert and update/config/update(concurrent writers race, direct SQL writes skip it) and anupdated_atclock (pod clock skew, the approach fix(proxy): unset environment variables removed from the DB row on the next config sync #46241 took)USAGEon that sequence toPUBLIC, since the trigger runs as whichever role writes the row and a writer role often has table grants onlySELECT, INSERT, UPDATEon the tables getspermission denied for sequenceon every env var saveSECURITY DEFINERtrigger function (runs with the owner's rights and depends onsearch_path) and anOLD + 1counter (starts over after a row delete and re-insert)TG_TABLE_SCHEMA), so a direct SQL write from a session whosesearch_pathleaves out that schema, or is empty, still gets a revisionSET search_path FROM CURRENTon the function, which pins whateversearch_paththe migration session had instead of following the tableenvironment_variablesload, sinceload_configruns before Prisma connects, so a value set at runtime later never becomes a restore targetget_config()still answers from the other rows. It tries again on the next syncget_config()caller during a writer outage, including the publicGET /get/ui_theme_settingsandGET /v2/model/infoGET /v2/model/info, can run at the same timeGOOGLE_CLIENT_IDand 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 themsupported_db_objectsleaves outsso_settings, that table is never read, so the dropped SSO keys are unset right after the same sync instead/config/update, the theme save, the SSO settings save and master key rotation/config/updateapplies 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 podsprisma db pushonly syncs schema.prisma, so after a push the proxy also runs the trigger migration's SQL withprisma db execute. If that fails, the proxy logs a warning and keeps booting, and removals then behave as on mainPre-Submission checklist
Please complete all items before asking a LiteLLM maintainer to review your PR
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 moreDelays 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 redirectAfter 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 thesso_code=andsso_url=lines zsh prints when a loop declares a local againBefore leg, full output (8bb8ac7)
After leg, full output (6cd1c1a)
The harness is the
1-main-*files in the gistSide paths
A replica-reading proxy unsets a removed key, SSO clears without
sso_settings, and rotation keeps a plaintext keySide paths setup and results
A primary Postgres streams to a hot standby made with
pg_basebackup, andpg_stat_replicationshowsstreaming. Proxy A reads the primary withsupported_db_objects: ["models"], so it never loadssso_settingsfrom the DB. Proxy B pointsDATABASE_URL_READ_REPLICAat the standby. A DBA also writes a plaintextOPENAI_API_KEYinto the row from psql. The admin removes the Anthropic key and the SSO client through B, then rotates the master key throughPOST /key/regenerate, and proxy C boots on the new master key. Both configs carry a fakeOPENAI_API_KEYinenvironment_variablesSide paths after leg, full output (6cd1c1a)
Side paths before leg, full output (8bb8ac7)
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
lit9489a3bon the GCE box ran base 8bb8ac7 and head 6cd1c1a. Lanessel-base,sel-head-1,sel-head-2,ctl-head,cap-base,cap-head-1,cap-head-2andcap-ctl-at-45da29d09aranrun.py managementwith 2 workers, seed 46709 and order seed 9489. Nothing inside the proxy is mocked. The base leg carries the head's tests and trigger migrationNode ids, all in
tests/integration/configuration/test_effective_settings.pytest_removing_db_environment_variables_restores_process_and_config_file_values_on_every_proxytest_a_read_replica_back_on_an_older_row_does_not_bring_back_a_removed_db_environment_variabletest_an_sso_client_removed_from_db_environment_variables_stops_sign_in_on_every_proxytest_a_proxy_that_pushes_its_own_schema_unsets_a_removed_db_environment_variabletest_db_environment_variables_saved_from_a_session_outside_the_tables_schema_still_get_a_revisiontest_db_environment_variables_revision_keeps_rising_after_its_sequence_falls_behind_the_rowtest_a_database_role_with_no_sequence_grants_can_still_save_db_environment_variablestest_a_writer_database_out_of_connections_keeps_the_applied_db_environment_variables(new)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_providerThe 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 logsCould not read environment_variables from the writer database, keeping the current environment variables,/get/config/callbacksanswers 200 and the removed key stays unset. Once the limit is lifted, a newer writer row appliesBase red evidence
With only
proxy_server.pyat 45da29d, the new cell fails at the config readUnit evidence ran on the box over the 9 mapped files. At the tip 1944 passed and 12 skipped. With
proxy_server.pyat 45da29d, 2 failed, bothtest_a_writer_that_cannot_answer_keeps_the_applied_environment_variables_when_the_cached_row_is_behind[out_of_connections-*]withFATAL: 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 atmax_connections, so every new writer connection getssorry, 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_pushon a fresh database. The harness is the3-lpr-*files in the same gistBoth trees sampled every call on all 4 workers. Config reads are
GET /get/ui_theme_settingsandGET /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 loggedCould 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 proxiesBreaking 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/updatecan 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 belowMaster 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_pushnow also runsprisma db executeon 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 onlyRegression 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_failure26 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 connectionsWhile 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 variableis 108 on both merged proxies and 126 on both base proxies, from the same non-string H1 valuesDependency 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_dbfromget_config, which has 38 call sites underlitellm/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_settingsmove, 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 afterdb push, recovery after the revision went backwards, and odd stored values. The side path QA adds a real streaming replica, SSO withsso_settingsleft out ofsupported_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 otherget_config_paramcallers read other config rows and are unaffectedLegacy 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
search_path, so a save from a session outside the table's schema failedTG_TABLE_SCHEMAMedium
/config/update, the theme save, the SSO save and master key rotation--use_prisma_db_pushnever got the triggerprisma db executeafterdb pushsso_settings, and a streaming replica had no live proofLow
modelsinsupported_db_objects, a removal reaches workers only when an admin route reloads the config, the same as mainUSAGEon the revision sequence toPUBLIC, so any role can callnextval, which only skips revision numbersDROP TRIGGER IF EXISTSbriefly locksLiteLLM_Configat boot, bounded bylock_timeout = '10s'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