Repository navigation
fix(proxy)!: support reload with multiple workers - #45909
Conversation
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
|
I'll fix CI failures and address comments from users with write access. I'll skip comments containing "(aside)".
|
Merging this PR will not alter performance1 warning
Comparing |
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
|
@litereview code-review |
✅ code-review5/5 · Ready for human reviewScope: full · Full PR review. No correctness findings. I fixed the scope of this review to the full PR ( Checks and execution details
Path traced: Boundary cases covered by tests:
Run: Manual E2E: I ran
View review · Reviewed |
There was a problem hiding this comment.
🔍 Devin Review: 1 flag
Not posted on this PR by your GitHub settings — view it in Devin Review. (Configure)
|
bugbot run |
…espawning it Workers now load the app through a factory that exits with uvicorn's STARTUP_FAILURE code on any import error, so the pool stops and the reloader waits for the next save, the same as single-worker reload. Multi-worker reload needs uvicorn>=0.50.0 for that, so older versions keep the single-worker reload with a warning.
…hutdown helper Main's TQ010 rule rejects a raw .terminate() under tests/integration, so the multi-worker reload test now calls OwnedProxy.begin_shutdown(), which sends the same SIGTERM
|
@litereview code-review |
|
bugbot run |
…fig the proxy loads
|
bugbot run |
|
@litereview code-review |
…to import the app
|
bugbot run |
|
@litereview code-review |
…s and cover single-worker trees
|
bugbot run |
|
@litereview code-review |
…icorn args to the reload pool
|
@litereview code-review |
|
@litereview code-review |
| raise AssertionError(log.read_text()) | ||
|
|
||
|
|
||
| def _start_pool(app_dir: Path, port: int, log: Path, runner: str = POOL_RUNNER) -> subprocess.Popen[bytes]: |
There was a problem hiding this comment.
Low · Subprocess and network pool tests placed in tests/unit, which forbids both
tests/unit/AGENTS.mdopens with: "In-process. No network or subprocess". It also says unit tests must not depend on execution speed.tests/unit/proxy/test_dev_reload.pystarts real uvicorn pools withsubprocess.Popen, binds sockets, and sendshttpx.getto the workers.- It also polls logs with
time.sleep(0.2)against 30 to 120 second timeouts. - The unit shard now carries an 18-case suite that took 107 s locally. It depends on free ports and machine speed, which is what the guide's split is meant to keep out of unit runs.
The smallest fix keeps the in-process cases (load_app_or_exit, pool_config, multi_worker_reload_supported) in tests/unit/proxy. Move the subprocess pool cases under tests/integration/configuration, next to test_multi_worker_reload.py.
Evidence
tests/unit/AGENTS.md line 3: In-process. No network or subprocess
tests/unit/AGENTS.md: Unit tests must not depend on the current time or execution speed
test_dev_reload.py:225 subprocess.Popen(, :251 httpx.get(f"http://127.0.0.1:{port}/", :203/:243 socket.socket(), :219/:309/:332/:356 time.sleep(0.2)
Local run: pytest tests/unit/proxy/test_dev_reload.py -> 18 passed in 106.92s
This breaks a documented repo standard, so it is not a smell judgement. Older files in tests/unit also break it, but this PR adds a new file.
Latest summary by code-review · View this review · Reviewed 9f397dbbf065
There was a problem hiding this comment.
This file only holds in-process tests now. The subprocess and socket pool tests already live in tests/integration/configuration/test_reload_worker_pool.py
The unit test guide keeps tests/unit in-process, so the subprocess pool cases now live in tests/integration/configuration and use the harness port allocator and process helpers
|
@litereview code-review |
|
bugbot run |
|
@litereview guide |
|
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…command Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…ory raises Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
|
bugbot run |
There was a problem hiding this comment.
✅ Bugbot reviewed your changes and found no new issues!
Comment @cursor review or bugbot run to trigger another review on this PR
Reviewed by Cursor Bugbot for commit ee4f337. Configure here.
Hot reload with several workers used to fall back to one, so local QA missed cross-worker bugs. Now every save restarts the whole pool, and the contributor guide's example runs two workers
Breaking change:
--reloadwith--num_workers,NUM_WORKERS, orDEFAULT_NUM_WORKERS_LITELLM_PROXYabove 1 on uvicorn 0.50.0 or newer now runs that many workers outside Windows, and each reload restarts all of them. Debug with--num_workers 1. Runs without--reloadare unaffectedDetails
TLDR
Problem this solves:
How it solves it:
Intentional product change: development
--reloadhonors--num_workerson uvicorn 0.50.0 or newer and restarts the whole pool together. Older uvicorn and Windows warn and keep one workerDesign decisions
AGENTS.md decision: the ask was to QA with two workers, Redis, and
--reload, and Redis matters there because it is how workers share state.router_settingsRedis alone keeps spend, budget, and rate-limit counters per worker, so the rule points bothrouter_settingsandgeneral_settings.coordination_redisat the QA Redis. The other options wererouter_settingsalone, which misses those counters, andREDIS_*environment variables, which reach coordination only through a last-resort fallback and never reach the router. The rule asks for no save-and-replace check, so later PRs never prove this reload againHealthcheck decision: the reload pool raises uvicorn's worker healthcheck from 5 to 30 seconds unless
--timeout_worker_healthcheckis passed. Under load, workers still importing the proxy missed the 5 second ping and were killed and respawned on reloads. The cost is that a worker that stops answering delays any shutdown, Ctrl-C included, by up to 30 seconds. The other options were keeping 5 seconds, which kills slow boots, and asking each developer to pass the flagReloader-exit decision: closing the terminal,
Ctrl-\, or a killed reloader would otherwise leave the pool holding the port. The pool waits onmultiprocessing.parent_process(), whose sentinel fires the moment the reloader exits, and then sets uvicorn's own exit flag, so each worker gets one SIGTERM and a normal shutdown. Terminating workers from the watcher thread would race the pool's main loop, which owns their pipes. The pool also exits on its own SIGQUIT, which uvicorn's pool ignores. Without that,Ctrl-\left the pool waiting on a ping to a worker that was still writing its core dump, so it held the port for the full 30 second healthcheck. Each worker also stops itself when its pool parent exits, since uvicorn's workers never check it, and a killed pool parent left old workers serving beside the next poolReload-cost decision: saves reload slower than on base, as the Caveats section measures, because the pool parent imports litellm before it starts the workers, and the two workers then boot at the same time. The import comes from the CLI module itself, which the spawned pool parent runs again, so moving the pool code would not avoid it. The other option was having the reloader start the workers itself, which drops uvicorn's worker healthchecks and respawns
Windows decision: Windows keeps one reloading worker, since uvicorn stops Windows workers with a console-wide
CTRL_BREAK_EVENTthat the reloader does not handle, and nothing here ran on Windows. The other option was shipping the pool there untestedUvicorn-args decision: the reload pool passes every uvicorn arg the CLI builds through to uvicorn, so an arg added to the CLI later reaches the workers, and a typo still fails at startup in uvicorn itself. The other option was rejecting args the pool does not list, which would crash
--reloadwith workers the day the CLI adds oneUser Flow
Before
A developer's two-worker QA proxy quietly runs one worker, so cross-worker bugs never show up locally
router_settingsat a dedicated Redispython litellm/proxy/proxy_cli.py --config config.yaml --num_workers 2 --reload"workers" flag is ignored when reloading is enabled.and starts one worker.env, and that one worker is replacedSyntaxError, and the next good save brings the worker backAfter
The same command runs two workers, reloads both on every save, and survives a typo without a restart loop
router_settingsat a dedicated Redispython litellm/proxy/proxy_cli.py --config config.yaml --num_workers 2 --reloadPOST http://localhost:<port>/v1/chat/completionsreturns 200.env, and both workers are replaced and keep serving requestsfailed to start, stopping the parent processonce, and the next good save restores both workersPre-Submission checklist
Delays in PR merge?
If you're seeing a delay in your PR being merged, ping the LiteLLM Team on Slack (#pr-review).
Meaningful tests
tests/integration/configuration/test_reload_worker_pool.pyruns the pool in a subprocess and checks that both workers start, a broken save stops the pool until a good one, and killing the reloader frees the port. The proxy integration test checks all three reload triggers and a clean shutdown with one and two workersWhat each test checks and which mutation fails it
tests/unit/proxy/test_dev_reload.pyloads the app through the same config each pool worker gets. A syntax error, a missing name, a runtime error, and a missing attribute in the app module each end in aSystemExitwith uvicorn's startup-failure code, which is what makes uvicorn stop the pool instead of respawning workers. A working app loads unchanged. Loading the plain app string instead fails 3 of these tests, and exiting with code 1 fails 4An
ImportErrororValueErrorraised while the app module imports must reach the log with its own traceback, so the logged frames must include the broken file and the line that raised. pydantic'sImportStringwraps both errors in aValidationErrorwith no file or line, so the worker now imports the module itself beforeImportStringresolves the attribute. Removing that import fails both cases, and importing the attribute part of the string instead fails 3 teststest_reload_worker_pool.pyrunsrun_multi_worker_reloadin a real subprocess with two workers on a tiny app that answers with its PID. Both workers must start, and a request must reach one of them. A broken save must logfailed to start, stopping the parent processand leave no old worker alive, and the next good save must bring back two new workers that serve. SIGINT must then exit 0 with no process left. Starting one worker instead of two fails it, and so do running a single server instead of the pool and re-raising the load error instead of exiting with the startup-failure codeThe real-process integration test checks the worker count, all three reload triggers, updated model configuration, old-worker exit, and clean shutdown, for one and two workers. It now edits the config file the proxy was started with. The CI job runs with worker isolation, which starts the proxy from a
worker-config-<hex>.yamlcopy, so editingconfig.yamlnever triggered a reload there. Both cases pass locally withINTEGRATION_WORKER_ISOLATION=1. Its shutdown call goes through the harness helper that sends the same SIGTERM, because main's test-quality gate rejects a raw.terminate()theretest_the_pool_stops_and_frees_the_port_when_the_reloader_dieskills the reloader three ways, with SIGKILL, with the SIGHUP a closed terminal sends its process group, and withCtrl-\'s SIGQUIT. Each time the pool parent must exit and the port must refuse connections. Removing the watcher fails all three.test_a_killed_pool_parent_takes_its_workers_with_it_so_the_next_save_serves_only_new_workersSIGKILLs the pool parent, then requires both of its workers to exit and the next save to serve from two new workers. Loading the app without the pool-parent watcher fails it.test_the_pool_is_told_to_stop_once_the_reloader_process_exitshands the watcher a real spawned process and requires no stop while it lives and a stop once it is killed. A watcher that never notices the exit, or never sets the flag, fails it. The healthcheck test requires the 30 second default and keeps an explicit value, and dropping the default fails it. A uvicorn arg the pool does not list,backlog, must reach the workers with reload off, and Windows must keep one worker. Rejecting unlisted args, passing the reload keys on, or dropping the Windows check each fails onetest_ctrl_backslash_frees_the_port_without_waiting_out_the_worker_healthcheck_when_core_dumps_are_slowsendsCtrl-\'s SIGQUIT to the process group while every process freezes for 3 seconds before it dies, the way a large process does while it writes a core dump. The pool parent must exit and the port must refuse connections within 15 seconds. Removing the pool's SIGQUIT handler fails it, since the pool then waits out its 30 second pingScreenshots / Proof of Fix
Last updated: 770c431. QA ran on 9f397db. Changes since QA: the pool tests moved to
tests/integration/configuration. Proof remains valid because no product file changed. Verification: 11 unit and 7 pool cases pass, and the pool-parent case fails without its watcherBoth legs ran
--num_workers 2 --reloadin tmux with a dedicated Redis, no database, and real OpenAI and Anthropic calls. The transcripts have every caseProxy config used by both legs
.envsaves, workers replacedCtrl-\, listenersCtrl-\, port free afterGRACEFUL_SHUTDOWN_TIMEOUT=2.5Before (3c28f4b)
Worker pool at launch, before
Commands and output
Proxy pane after the broken save, before
After (9f397db)
Worker pool at launch, after
Commands and output
Proxy pane after the broken save, after
Observations from the run
Type
Bug Fix, Documentation, Test
Caveats (if any)
Medium
--reloadnow starts every worker that--num_workers,NUM_WORKERS, orDEFAULT_NUM_WORKERS_LITELLM_PROXYasks for,.envincluded. Without Redis, rate-limit counters, cooldowns, and MCP sessions split per worker, andbreakpoint()needs--num_workers 1--num_workers 2on base after 5 secondsLow
Ctrl-\during a ping to a worker writing its core dump can still wait 30 secondstests/integration, which CI runs only on maindev_config.yaml, which has no RedisFinal Attestation
Link to Devin session: https://app.devin.ai/sessions/61c0cbdf73bb4fca9738df44537d47c7
Open in Devin Desktop: https://app.devin.ai/desktop/session/61c0cbdf73bb4fca9738df44537d47c7?variant=devin
Bugbot summary
Update after merging main at 7e0728c
Merged main and kept its light CLI imports and startup output, with the reload pool now loading the same child process app factory and overrides as plain multi-worker runs. AGENTS.md keeps main's proof rules and states the two-worker Redis reload QA command inline
Ctrl-\ now kills the pool workers right away instead of following the graceful path. Before the fix the strengthened
ctrl-backslashcase oftest_the_pool_stops_and_frees_the_port_when_the_reloader_diestook 31.6s to free the port, over its 10s bound. After the fix a live--num_workers 2 --reloadproxy refused connections 0.6s after SIGQUITLive run at the merged tip with Redis on both settings blocks. Two worker PIDs served, four real Anthropic
/v1/chat/completionscalls returned 200, and a config save replaced workers 52634 and 52635 with 53090 and 53091 that both loaded the new aliasThe reload pool now calls the worker app factory inside the same startup-failure handler as the import, so a broken save to the proxy server makes workers exit as startup failures and the pool waits for the next save instead of restarting them.
test_dev_reload.pycovers a factory with a missing import and one that raises, and both failed before the fix