Repository navigation
feat(proxy): elect one owner per auxiliary DB job and add a worker role - #47878
devin-ai-integration[bot] wants to merge 1 commit into
Conversation
Every proxy process registers the same scheduler, and it registers it once per uvicorn worker process rather than once per pod, so a job with a shared side effect runs replicas times processes. The jobs that did elect an owner each hand-rolled it, and the dialects disagree on the one case that matters: acquire_lock reports contention and an unreachable Redis identically, so the PTU rollup ran unguarded while key rotation, spend log cleanup and UI session cleanup skipped, meaning a Redis outage silently stopped those three everywhere at once. Adds run_as_single_owner and claim_once_per_window, which name that decision as WhenLockUnavailable and carry the two lease shapes the proxy actually uses: a mutex held for one run, and a done-marker sized to a reporting window. The lease is now renewed while the body runs, so the TTL is a failover deadline rather than a run budget. On a live proxy that is the difference between a spend log cleanup losing its 60s lock partway through a multi-minute sweep, which a challenger could take at 75s, 120s and 180s, and holding it to completion. LITELLM_JOB_ROLE=serving registers none of these jobs, so an operator can run them on a dedicated worker deployment instead of on every replica taking traffic. A serving pod keeps the jobs that drain its own in-memory queues and refresh its own model registry, so it still writes spend. The default is unchanged, and an unrecognised value falls back to it with a warning. Both Helm charts gain an opt-in worker Deployment, off by default and pinned to one process. Live-Redis integration tests cover election, failover, renewal, rolling restart and once-per-window claims. Also fixes the ownership gauge, which only ever fired on a reentrant re-acquisition and so was driven to 0 by every release and never back up.
|
|
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using high effort and found 2 potential issues.
❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.
Reviewed by Cursor Bugbot for commit 2ad9e53. Configure here.
| timezone=None, | ||
| ) | ||
|
|
||
| job_role: Final = JobRole.from_env_value(LITELLM_JOB_ROLE) |
There was a problem hiding this comment.
Serving pods re-register cleanup on reload
High Severity
Startup now skips spend_log_cleanup_job when LITELLM_JOB_ROLE=serving, but _reschedule_spend_log_cleanup_job never checks that role. Serving pods still run periodic config reload, and any DB change to a retention setting (or a YAML/DB mismatch on first reload) calls this path and puts the sweep back on every serving replica.
Additional Locations (2)
Reviewed by Cursor Bugbot for commit 2ad9e53. Configure here.
| - {{ .Values.numWorkers | quote }} | ||
| {{- end }} | ||
| {{- end }} | ||
| {{- end }} |
There was a problem hiding this comment.
Custom args skip worker process pin
Medium Severity
The worker Deployment only injects --num_workers 1 on the default args path. When top-level args is set, the worker inherits that list unchanged, so a serving --num_workers N override is copied onto the job pod and each process registers the single-owner jobs again.
Reviewed by Cursor Bugbot for commit 2ad9e53. Configure here.


TLDR
Problem this solves:
How it solves it:
LITELLM_JOB_ROLE=servingregisters no single-owner jobUser Flow
Before: an operator running the proxy across many replicas finds their database saturated by retention cleanup, and cannot move that work off the pods answering inference requests
maximum_spend_logs_retention_periodand roll out 10 replicas--num_workers 4registers it four more timesmaximum_spend_logs_retention_period, which turns retention off everywhere rather than moving itAfter: the same operator runs one small worker deployment, and the cleanup holds its lease for the whole sweep
maximum_spend_logs_retention_periodand roll out 10 replicas withLITELLM_JOB_ROLE=serving, plus a single replica withLITELLM_JOB_ROLE=workerLITELLM_JOB_ROLE=serving: registering no single-owner background job on this processand register none of itspend_log_cleanup: pod <id> owns this runwhen it takes the leaselitellm_pod_lock_manager_sizecarries aspend_log_cleanup:<pod>label naming the current ownerRelevant issues
Linear ticket
Resolves LIT-5434
Pre-Submission checklist
Please complete all items before asking a LiteLLM maintainer to review your PR
@greptileaito re-request a review after pushing changes)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
Live proxy, real Postgres, real Redis. Retention cleanup with 3000 expired rows and a
BEFORE DELETEtrigger doingpg_sleep(0.1)per row, so one sweep genuinely outlives the 60 second lease. At three offsets, all past that TTL, a challengerPodLockManagerasks the lease exactly the question a second pod's cron would ask. Each sample first asserts a sweep is actually in flight inpg_stat_activityand is discarded if not, so a sample cannot pass by measuring nothing.Before, on
bea31871fc(staging tip this branch was cut from). Thegrepcounts are the assertion that this tree really lacks the change:After, on
2d0823abf7, this PR's head. Re-taken whenever a push could change what it measures, most recently for the lint fix that converted the Lua invocation's arguments to tuples, since a tuple redis-py rejected would show up as renewal silently failing, which is the exact defect this proof exists to exclude:Three for three in each direction, and the holder in the after run is the same pod at every sample. Both legs had deleted the same 1000 of 3000 rows by the end of the window, and every sample in both legs had a sweep confirmed in flight before the challenge, which is the property the comparison rests on.
The role gate, same head, a pod started with
LITELLM_JOB_ROLE=serving, watched over three cron minutes:The serving pod registers none of the cleanup and still runs its own spend flush eight times, which is the reassurance an operator needs before moving to this topology.
Live-Redis integration tests, run against a real Redis container rather than a fake. This is the CI run's own log, not a local one, because a suite gated on a reachable Redis goes green identically whether it ran or skipped everything:
The
collected 7 itemsline is the part that matters: it is the difference between the gate working and the gate being vacuously green.Type
🆕 New Feature
Caveats (if any)
Review notes
Why a shared helper rather than one more hand-rolled lock. There are fifteen
acquire_lockcall sites today across seven jobs, and they have grown five incompatible dialects. Two opposite philosophies share one function name: most treat the lock as a mutex, acquiring and releasing in afinally, while the Slack reports treat it as a sent-this-window marker that is never released and whose TTL is the reporting window. Three different answers to a Redis outage: the spend commit skips, cleanup and key rotation and UI cleanup skip when Redis is wired but erroring and run unguarded when it is absent entirely, and the PTU rollup runs but disables its destructive prune. Four idioms for reading the same tri-state return, each treating theNonethat means "no Redis configured" differently.acquire_lockcannot distinguish contention from an outage, which is why the PTU rollup had to hand-roll a_lock_is_heldread-back that the open reset-budget PR then independently rewrote.WhenLockUnavailableis that decision named once.What is deliberately not changed. Each migrated job keeps its existing outage policy exactly, including ones I would argue with: key rotation still skips a cycle during a Redis outage, because rotating a key twice hands out two replacements and invalidates the first. The point of this PR is to make each policy explicit and reviewable, not to change any of them silently.
Jobs a serving pod keeps. The spend flush, daily tag spend flush, gateway request counter flush, periodic config reload, and the DB model and credential reloads all stay on every pod, because they drain that pod's own in-memory queues or refresh its own router state. Gating those would drop request counts and freeze model hot-reload. Note the spend flush is already the split-stage shape this generalizes: stage one drains the local queue on every pod, stage two commits Redis to Postgres under a lease.
On the Redis integration workflow. GitHub Actions has no Redis service anywhere, and the ten workflows sharing
_test-unit-base.ymlcannot get a conditionalservices:block, so a container would start for every unrelated shard. CircleCI'sredis_caching_unit_testsdoes run pytest against a live Redis, but against the shared remote instance with-n 2 --reruns 2. This suite gates on a 0.5 second acquisition window and a renewal interval floored at one second, so reruns there would convert a real intermittent regression into a green check. The repo's ownstart_redishelper is documented as isolating a job so concurrent pipelines do not contend for pod locks, which is the same argument.Mutation testing. 12 mutants on the Python unit tests, 8 on the live-Redis suite, 21 on the Helm templates. Two worth naming. Mutating
_COMPARE_AND_EXPIRE_LOCK_SCRIPTto an unconditionalEXPIREsurvives every unit test, because a fake cache emulates the comparison in Python and never executes the Lua; only the live-Redis suite kills it. Mutating_COMPARE_AND_DELETE_LOCK_SCRIPTto an unconditionalDELsurvived the first version of the live suite too, because nothing there had a non-owner callrelease_lockwhile another pod held the lease. That gap was reported rather than papered over, andtest_release_lock_never_frees_a_lease_another_pod_has_taken_overwas added to close it.Greptile round 1, 4/5. All three findings addressed, two by changing the code.
The P1 was real and is fixed.
renew_lockfell back to a GET-then-SET when the Lua compare-and-expire could not run, and that SET is unconditional, so a lease that lapsed and was taken over between the two calls would be written back to the pod that lost it, leaving that pod and its successor both believing they owned the job. That is worse than the delete fallback it was modelled on, whose failure mode is a lock nobody holds rather than one two pods hold. Renewal now has no non-atomic fallback at all: where compare-and-expire cannot run it reports False and the lease expires into the failover it already describes. Release keeps its GET-then-DEL fallback, which predates this PR and whose worst case is milder.The regression test for it took two attempts, which is worth stating because the first one looked fine. It asserted the outcome (the successor still holds the lease) and the mutant that restores the unsafe fallback survived it, because the ownership guard above the fallback already produced that outcome. The race only appears when the read is stale relative to the store, so the test now drives exactly that and the mutant dies.
The commentary finding was fair and the two inline comments are now docstrings, which is where that reasoning belongs. The module has no inline comments left.
The Helm README finding I do not think holds, and I would rather say so than quietly comply.
helm/litellm-helm/README.mdis already a 65-row values reference under a## Parametersheading, and it is the filehelm show readmeserves to chart consumers. The docs-location rule covers user-facing product documentation, which is why the prose for this feature is in the docs repo instead. Addingworker.*rows to a chart's own values table is that file doing its only job.Where the two test layers stop, stated rather than implied. The mutant that reintroduces the unsafe renewal fallback SURVIVES the live-Redis suite, and that is expected rather than a gap in it. Real Redis has scripting, so the Lua branch always returns and the fallback is dead code there; the two script mutants dying is what proves the Lua path is the live one rather than merely present. It would still survive even if the rig could force the fallback, because
_act_if_ownerdoes its ownership read before calling the fallback at all, so a non-owner is refused either way and the only difference is the window between that read and the write. Driving that interleaving deterministically needs a fake cache whose read disagrees with its store, which is what the unit test does. So the unit layer owns the interleaving and the live layer owns whether the Lua executes correctly against a real server, and neither can cover the other's half.There is a third line to that, and it is the strongest argument for the P1 fix beyond the race it closes. A green live suite is weak evidence on its own here, because a Lua invocation redis-py rejects fails silently rather than loudly, so the suite was checked with a positive control: passing an unencodable argument, and confirming the suite goes red with
Lua compare-and-act failed ... falling back to GET then actin the log. Under that control the RELEASE path stays green, because its fallback does the ownership read and deletes correctly regardless. Only renewal fails, and it fails precisely because renewal now hasfallback=None. Had the unsafe fallback been kept, the owner's read would have matched, the write would have landed,renew_lockwould have returned True, and the suite would have passed against a completely broken script. Removing it did not only close the takeback race; it leftrenew_lockas the one call here with no silent degradation path, which is the only reason a live rig can detect a broken invocation at all.That fix has a cost worth naming here rather than leaving a reviewer to find it. Because
renew_locknow reports False whenever the Lua cannot execute, a Redis scripting outage stops renewal on a pod that still holds its lease and is working normally, so the TTL lapses and a second pod can take the job mid-run._run_holding_leasedeliberately does not cancel the body when that happens: aborting a partially complete prune or a half-finished key rotation is worse than a duplicate pass, which is whyrun_as_single_ownerrequiresrunto be idempotent and why release is compare-and-delete, so the displaced pod cannot steal the lease back on its way out. The exposure is a scripting outage rather than ordinary contention, and Greptile raised exactly this as a P1 on the current headOn the 4/5 badge.
single_owner_job.pyis the same blobcf60bc32dbat both69c8a914e9, which scored 5/5, and the current head, which scored 4/5. The file did not change between those two reviews, so the score delta is scorer variance on identical bytes rather than anything the rebases alteredRelationship to #36589, which landed on staging while this was open and which this is rebased onto. That PR offsets each job's firing instant by a hash of job id plus pod and worker identity, so simultaneous ticks across pods become rare. That reduces how often two pods contend, which overlaps part of the motivation here, and it is worth saying so rather than presenting these as unrelated. It does not address either thing this PR is about: a lease that expires while its holder is still working is a function of how long the work takes, not of when it started, and staggering cannot keep auxiliary work off the pods serving traffic. The two compose, and the live capture in this PR was re-taken on top of #36589 rather than before it.
An interaction with #36589 that this PR does not cause and does not fix. A lease is released when its body returns, so it dedupes for the body's runtime rather than for the TTL. Two pods whose ticks land further apart than that will both run. #36589 bounds an interval job's offset at
min(window_seconds, period_seconds)and itsDEFAULT_CRON_DEDUPE_SECONDSmap holds only the three cron ids, so the two daily interval jobs here, key rotation and expired UI session cleanup, get offsets spread across the default 300s while their bodies finish in seconds. A large fleet can therefore run a once-a-day job more than once a day.This predates this PR rather than arriving with it: key rotation already acquired with a TTL and released in a
finally, so its dedupe span was already the body's runtime, and the migration preserved that exactly. What changed is that the spread went from incidental pod-start skew to a deliberate 300s. It is also low severity, because both bodies are idempotent in practice, a second rotation pass finds nothing due and both cleanups delete by age. What was missing is that the idempotence requirement was unwritten, sorun_as_single_ownernow states it and points atclaim_once_per_window, whose marker outlives the run, for work that genuinely must happen once per period. A follow-up PR against the stagger module will fix it, and not by giving interval jobs a dedupe bound: any nonzero spread still permits the second run, because the lease is released on completion rather than held for the horizon. The fix is to derive a single-owner job's offset from the job id alone, dropping the pod and worker identity, so every replica lands on the same instant for that job and contends on the lease as it did before #36589, while different jobs keep the different offsets that PR exists to give them. Worth noting thatPTU_ROLLUP_JOB_IDalready carries a horizon derived from its lock TTL and also releases on completion, so that existing entry rests on the same premise.Helm. Off by default, and rendering with the worker disabled is byte-identical to base for the serving Deployment across three value sets including a hardening kitchen sink. The one non-empty line in the whole-chart diff is the migrations Job's
checksum/config, which hashes the entire values map, so any new values key moves it; that was verified by hashing the unmodified base chart with an unrelated--set. The worker takes its ownapp.kubernetes.io/namebecause the classic chart's Service, PDB and ServiceMonitor select on name and instance with no component key, so a worker sharing the name would be enrolled as a Service endpoint and take live inference traffic. It pins one uvicorn process, since the scheduler registers per process and a worker at four processes would relocate the contention rather than remove it.Rebased onto current staging at
69c8a91. Two conflicts, both in files staging rewrote underneath this branch.spend_log_cleanup.pypicked up a metrics layer, a run budget and the_clean_spend_log_tables/_clean_session_rollupsplit after this branch was cut, so the resolution keeps every bit of that and swaps only the manual acquire, skip and release plumbing forrun_as_single_owner. Theskipped_lockedoutcome now reads off the helper'sNonereturn, and staging's owntest_a_run_skipped_because_another_pod_holds_the_lock_is_reportedkills a mutant that drops that branch, so the resolution is checked rather than asserted.ptu_flat_cost_rollup.pywas an import-block collision and nothing moreRebased again onto current staging at
2ad9e53. Two conflicts, both from staging landing in the same two places a second time.spend_log_cleanup.pygained a health-check retention group and a_group_deadlinethat splits the run budget evenly across the configured groups, so the resolution moves all three groups plus that budget split inside the_sweepbody the lease now wraps, leaving the group logic exactly as staging wrote it.helm/litellm-helm/templates/deployment.yamlis the file this branch replaces with aninclude "litellm.podSpec", and staging added aDATABASE_READER_HOSTenv sourced fromdb.secret.readReplicaEndpointKeyto the inline body, so that block moves into_deployment.tplat the same position ahead ofDATABASE_URL_READ_REPLICA, which is what staging's ownenv[7]/env[8]ordering assertions indeployment_tests.yamlpinOne further fix the rebase forced: #37491 changed the classic chart's default image from
ghcr.io/berriai/litellm-databasetoghcr.io/berriai/litellm, which left the worker suite's "shares the proxy image" assertion stale. It now matches its neighbours indeployment_tests.yaml, and mutating the tag out of_deployment.tplstill kills it. Both charts pass the workflow's own declared-vs-executed wrapper on the pinned helm-unittest 0.8.2, at 18/18 and 12/12 suitesThe rebase also broke this PR's own CI in a way no merge conflict could catch, since the new workflow file is an add rather than an edit. #37559 renamed
.github/actions/detect-backend-changesto.github/actions/detect-changes, andtest-integration-redis.ymlstill pointed at the old path, so the job died in 21 seconds on a missing local action. Same interface, so the fix is a path rename, and every other local action and pinned SHA in that workflow was re-checked against current staging and matchesThe round-two P2 on
single_owner_job.pyis addressed by deleting the docstrings that restated names and control flow, keeping only the lock-ambiguity and renewal rationale the code cannot express. Docs PR BerriAI/litellm-docs#874 has merged, so the env-key gate no longer blocks thisQA runbook
Final Attestation
Link to Devin session: https://app.devin.ai/sessions/d9bc4446498b493493d785708e09be64
Requested by: @yassin-berriai
Continues #36618, moved to a head on the fork
yassin-berriai/litellmNote
Medium Risk
Changes multi-replica behavior for DB/Redis-backed background jobs and introduces deployment topology via job roles; defaults preserve prior behavior but misconfigured
servingwithout a worker could stop cluster-wide jobs.Overview
Adds single-owner election for auxiliary proxy jobs (budget resets, spend-log cleanup, key rotation, PTU rollup, Slack spend reports, etc.) via a shared
run_as_single_ownerhelper with renewable Redis leases, plusLITELLM_JOB_ROLE(all/serving/worker) so serving pods skip registering those jobs while per-pod flushes and reloads still run.PodLockManagergains atomicrenew_lock(Lua compare-and-expire, no unsafe fallback) and emits the ownership gauge on fresh lock acquisition. Several managers are refactored off hand-rolled acquire/release; window-style reports useclaim_once_per_window.Helm (both charts): opt-in
workerDeployment setsLITELLM_JOB_ROLE=workerandservingon inference pods, with shared pod spec inlitellm-helm, distinct selectors so workers are not in Service/HPA traffic, and one uvicorn worker on the worker role.CI: new workflow runs
tests/redis_integration_testsagainst a real Redis service container.Reviewed by Cursor Bugbot for commit 2ad9e53. Bugbot is set up for automated code reviews on this repo. Configure here.