Skip to content

feat(proxy): elect one owner per auxiliary DB job and add a worker role - #36618

Closed
yassin-berriai wants to merge 1 commit into
mainfrom
litellm_lit_5434_single_owner_jobs
Closed

yassin-berriai wants to merge 1 commit into
mainfrom
litellm_lit_5434_single_owner_jobs

Conversation

@yassin-berriai

@yassin-berriai yassin-berriai commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves:

  • Auxiliary DB jobs run once per pod, times uvicorn workers
  • Seven jobs hand-roll election, with four incompatible outage policies
  • A lease has no renewal, so a slow job loses it mid-run
  • No way to keep aux work off pods serving traffic
  • The job-ownership gauge only ever reports zero

How it solves it:

  • One shared helper, two lease shapes, one named outage policy
  • The lease renews while the job runs, so TTL means failover
  • LITELLM_JOB_ROLE=serving registers no single-owner job
  • Both Helm charts gain an opt-in worker Deployment
  • Fresh lock acquisitions now emit the ownership gauge

User 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

  1. They set maximum_spend_logs_retention_period and roll out 10 replicas
  2. Every replica registers the cleanup job, and each pod running --num_workers 4 registers it four more times
  3. One process wins the Redis lock and starts deleting; the rest skip that tick
  4. The sweep takes longer than the 60 second lock, so the lock expires while the delete is still running
  5. The next process to fire its cron acquires the now free lock and starts a second concurrent sweep against the same rows
  6. They open http://litellm-domain/ui/?page=logs during the window and see request latency climb while the database works through overlapping deletes
  7. Their only lever is maximum_spend_logs_retention_period, which turns retention off everywhere rather than moving it

After: the same operator runs one small worker deployment, and the cleanup holds its lease for the whole sweep

  1. They set maximum_spend_logs_retention_period and roll out 10 replicas with LITELLM_JOB_ROLE=serving, plus a single replica with LITELLM_JOB_ROLE=worker
  2. The serving replicas log LITELLM_JOB_ROLE=serving: registering no single-owner background job on this process and register none of it
  3. The worker registers the cleanup and logs spend_log_cleanup: pod <id> owns this run when it takes the lease
  4. The lease is renewed every 20 seconds while the sweep runs, so it never lapses mid delete
  5. Nothing else acquires it, so there is never a second concurrent sweep
  6. The serving replicas keep flushing their own spend and keep serving requests at http://litellm-domain/v1/chat/completions with unchanged latency
  7. litellm_pod_lock_manager_size carries a spend_log_cleanup:<pod> label naming the current owner

Relevant issues

Linear ticket

Resolves LIT-5434

Pre-Submission checklist

Please complete all items before asking a LiteLLM maintainer to review your PR

  • I have added meaningful tests
  • My PR passes all CI/CD checks (e.g., lint, format, unit tests)
  • My PR's scope is as isolated as possible; it only solves 1 specific problem
  • I have received a Greptile Confidence Score of at least 4/5 before requesting a maintainer review (Greptile reviews automatically once the PR is opened; only comment @greptileai to 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 DELETE trigger doing pg_sleep(0.1) per row, so one sweep genuinely outlives the 60 second lease. At three offsets, all past that TTL, a challenger PodLockManager asks the lease exactly the question a second pod's cron would ask. Each sample first asserts a sweep is actually in flight in pg_stat_activity and is discarded if not, so a sample cannot pass by measuring nothing.

Before, on bea31871fc (staging tip this branch was cut from). The grep counts are the assertion that this tree really lacks the change:

### BEFORE  tree=.../lit5434-base  LITELLM_JOB_ROLE=<unset>
### fix present in this tree: role gate=0, lease renewal=0
### seeded 3000 expired rows, ~0.1s each to delete, lease TTL is 60s
### sweep started at 17:50:01
t+75s  (sweep in flight, 2 pid): ACQUIRED  a second pod could have started a concurrent sweep here
t+120s (sweep in flight, 1 pid): ACQUIRED  a second pod could have started a concurrent sweep here
t+180s (sweep in flight, 1 pid): ACQUIRED  a second pod could have started a concurrent sweep here
### rows remaining: 2000 of 3000

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:

### AFTER  tree=.../valiant-popping-lighthouse
### fix present in this tree: role gate=8, lease renewal=1
### seeded 3000 expired rows at ~0.1s each to delete, against a 60s lease TTL
### sweep started at 09:48:01
t+75s  (sweep in flight): REFUSED   lease still held by 10291fde
t+120s (sweep in flight): REFUSED   lease still held by 10291fde
t+180s (sweep in flight): REFUSED   lease still held by 10291fde
### rows remaining: 2000 of 3000

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:

role line logged:            1   (LITELLM_JOB_ROLE=serving: registering no single-owner background job on this process)
spend log cleanup registered: 0
cleanup ticks fired:          0
its own spend flush ran:      8
cleanup lease key in redis:   absent

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:

collected 7 items
test_only_one_pod_of_five_runs_the_tick PASSED
test_successor_runs_only_after_the_dead_owner_lease_expires PASSED
test_renewal_holds_the_lease_past_the_ttl_and_frees_it_on_completion PASSED
test_rolling_restart_never_skips_or_doubles_a_tick PASSED
test_window_claim_is_taken_once_even_by_the_pod_that_won_it PASSED
test_renew_lock_extends_the_lease_only_for_its_owner PASSED
test_release_lock_never_frees_a_lease_another_pod_has_taken_over PASSED
7 passed

The collected 7 items line 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_lock call 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 a finally, 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 the None that means "no Redis configured" differently. acquire_lock cannot distinguish contention from an outage, which is why the PTU rollup had to hand-roll a _lock_is_held read-back that the open reset-budget PR then independently rewrote. WhenLockUnavailable is 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.yml cannot get a conditional services: block, so a container would start for every unrelated shard. CircleCI's redis_caching_unit_tests does 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 own start_redis helper 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_SCRIPT to an unconditional EXPIRE survives 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_SCRIPT to an unconditional DEL survived the first version of the live suite too, because nothing there had a non-owner call release_lock while another pod held the lease. That gap was reported rather than papered over, and test_release_lock_never_frees_a_lease_another_pod_has_taken_over was 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_lock fell 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.md is already a 65-row values reference under a ## Parameters heading, and it is the file helm show readme serves 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. Adding worker.* 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_owner does 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 act in 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 has fallback=None. Had the unsafe fallback been kept, the owner's read would have matched, the write would have landed, renew_lock would have returned True, and the suite would have passed against a completely broken script. Removing it did not only close the takeback race; it left renew_lock as 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_lock now 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_lease deliberately 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 why run_as_single_owner requires run to 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 head

On the 4/5 badge. single_owner_job.py is the same blob cf60bc32db at both 69c8a914e9, 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 altered

Relationship 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 its DEFAULT_CRON_DEDUPE_SECONDS map 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, so run_as_single_owner now states it and points at claim_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 that PTU_ROLLUP_JOB_ID already 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 own app.kubernetes.io/name because 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.py picked up a metrics layer, a run budget and the _clean_spend_log_tables / _clean_session_rollup split after this branch was cut, so the resolution keeps every bit of that and swaps only the manual acquire, skip and release plumbing for run_as_single_owner. The skipped_locked outcome now reads off the helper's None return, and staging's own test_a_run_skipped_because_another_pod_holds_the_lock_is_reported kills a mutant that drops that branch, so the resolution is checked rather than asserted. ptu_flat_cost_rollup.py was an import-block collision and nothing more

Rebased again onto current staging at 2ad9e53. Two conflicts, both from staging landing in the same two places a second time. spend_log_cleanup.py gained a health-check retention group and a _group_deadline that splits the run budget evenly across the configured groups, so the resolution moves all three groups plus that budget split inside the _sweep body the lease now wraps, leaving the group logic exactly as staging wrote it. helm/litellm-helm/templates/deployment.yaml is the file this branch replaces with an include "litellm.podSpec", and staging added a DATABASE_READER_HOST env sourced from db.secret.readReplicaEndpointKey to the inline body, so that block moves into _deployment.tpl at the same position ahead of DATABASE_URL_READ_REPLICA, which is what staging's own env[7] / env[8] ordering assertions in deployment_tests.yaml pin

One further fix the rebase forced: #37491 changed the classic chart's default image from ghcr.io/berriai/litellm-database to ghcr.io/berriai/litellm, which left the worker suite's "shares the proxy image" assertion stale. It now matches its neighbours in deployment_tests.yaml, and mutating the tag out of _deployment.tpl still 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 suites

The 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-changes to .github/actions/detect-changes, and test-integration-redis.yml still 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 matches

The round-two P2 on single_owner_job.py is 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 this

QA runbook

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

Link to Devin session: https://app.devin.ai/sessions/d9bc4446498b493493d785708e09be64
Requested by: @yassin-berriai

@yassin-berriai
yassin-berriai requested a review from a team August 12, 2026 05:35
@CLAassistant

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you sign our Contributor License Agreement before we can accept your contribution.
You have signed the CLA already but the status is still pending? Let us recheck it.

@greptile-apps

greptile-apps Bot commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

The PR centralizes single-owner auxiliary-job election, adds renewable Redis leases and process roles, and introduces optional dedicated worker deployments in both Helm charts.

  • Migrates cleanup, rotation, and rollup jobs to shared ownership helpers.
  • Adds atomic lease renewal/release behavior and live-Redis integration coverage.
  • Allows serving pods to omit auxiliary jobs while a dedicated worker deployment owns them.
  • Preserves the latest staging changes while refactoring the classic chart’s shared pod specification.

Confidence Score: 4/5

The PR is not yet safe to merge because a transient renewal failure can allow a successor to start while the original single-owner job is still running.

The atomic renewal fix prevents a stale owner from overwriting a successor’s lease, but the caller treats every failed renewal as a reason to stop renewing without stopping the protected body; once the TTL expires, another pod can acquire the lease and overlap the original database job.

Files Needing Attention: litellm/proxy/common_utils/single_owner_job.py, litellm/proxy/db/db_transaction_queue/pod_lock_manager.py

Important Files Changed

Filename Overview
litellm/proxy/common_utils/single_owner_job.py Introduces shared job-role, lease acquisition, renewal, and outage-policy helpers; a failed renewal ends only the renewer and can leave the original job overlapping a successor.
litellm/proxy/db/db_transaction_queue/pod_lock_manager.py Adds atomic compare-and-expire renewal and compare-and-delete release, correctly removing the previously reported non-atomic renewal fallback.
litellm/proxy/db/db_transaction_queue/spend_log_cleanup.py Moves bounded retention cleanup under the shared renewable single-owner lease while retaining the rebased cleanup groups and deadlines.
litellm/proxy/proxy_server.py Applies the process-role gate when registering single-owner scheduled jobs while preserving per-process queue flushes and reload work.
helm/litellm-helm/templates/_deployment.tpl Extracts the shared proxy/worker pod specification and preserves the staging read-replica environment configuration.
helm/litellm/templates/worker/deployment.yaml Adds the optional worker deployment to the componentized chart with isolated labels and worker-specific scheduling configuration.
.github/workflows/test-integration-redis.yml Adds a dedicated live-Redis integration workflow using the current detect-changes action path.

Reviews (7): Last reviewed commit: "feat(proxy): elect one owner per auxilia..." | Re-trigger Greptile

Comment thread helm/litellm-helm/README.md Resolved
@codecov

codecov Bot commented Aug 12, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.26590% with 3 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
litellm/proxy/common_utils/single_owner_job.py 96.55% 3 Missing ⚠️

📢 Thoughts on this report? Let us know!

@codspeed

codspeed Bot commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will degrade performance by 10.04%

⚠️ Different runtime environments detected

Some benchmarks with significant performance changes were compared across different runtime environments,
which may affect the accuracy of the results.

Open the report in CodSpeed to investigate

❌ 1 regressed benchmark
✅ 30 untouched benchmarks

Warning

Please fix the performance issues or acknowledge them on CodSpeed.

Performance Changes

Benchmark BASE HEAD Efficiency
❌ test_token_counter_multi_turn 531.3 µs 590.6 µs -10.04%

Tip

Investigate this regression by commenting @codspeedbot fix this regression on this PR, or directly use the CodSpeed MCP with your agent.


Comparing litellm_lit_5434_single_owner_jobs (2ad9e53) with litellm_internal_staging (e07a712)1

Open in CodSpeed

Footnotes

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

@yassin-berriai

Copy link
Copy Markdown
Contributor Author

Docs are in BerriAI/litellm-docs#874 and must merge first, or the env-key gate stays red here.

@yassin-berriai
yassin-berriai force-pushed the litellm_lit_5434_single_owner_jobs branch 2 times, most recently from adcc5a2 to 7b828b6 Compare August 12, 2026 16:30
@yassin-berriai

Copy link
Copy Markdown
Contributor Author

@greptileai the renewal race is fixed, reasoning in the PR description under Review notes. Please review head 7b828b608a

@yassin-berriai
yassin-berriai force-pushed the litellm_lit_5434_single_owner_jobs branch from 7b828b6 to bf71107 Compare August 12, 2026 16:35
@yassin-berriai

Copy link
Copy Markdown
Contributor Author

@greptileai rebased onto staging after #36589 landed, and the live proof re-taken on top of it. Please review head bf7110765f

@yassin-berriai
yassin-berriai force-pushed the litellm_lit_5434_single_owner_jobs branch 2 times, most recently from a148a1c to 2d0823a Compare August 12, 2026 16:51
@yassin-berriai

Copy link
Copy Markdown
Contributor Author

@greptileai lint fix (tuples for the Lua args) and a docstring on the lease's dedupe span. Please review head 2d0823a

@yassin-berriai
yassin-berriai marked this pull request as draft August 12, 2026 23:16
@yassin-berriai

Copy link
Copy Markdown
Contributor Author

This PR should be tested extensively before merge, it's a major architectural change imo

@yassin-berriai
yassin-berriai force-pushed the litellm_lit_5434_single_owner_jobs branch from 2d0823a to e8872f7 Compare August 20, 2026 22:12
@yassin-berriai
yassin-berriai marked this pull request as ready for review August 20, 2026 22:12
@yassin-berriai

Copy link
Copy Markdown
Contributor Author

@greptileai please re-review e8872f7, the rebase onto current staging. Two conflicts resolved in spend_log_cleanup.py and ptu_flat_cost_rollup.py, plus trimmed comments

@yassin-berriai

Copy link
Copy Markdown
Contributor Author

@yucheng-berri your approval anchored to 2d0823a, which the rebase rewrote. New head is e8872f7 with two conflicts resolved. Mind re-reviewing?

@yassin-berriai
yassin-berriai force-pushed the litellm_lit_5434_single_owner_jobs branch from e8872f7 to 69c8a91 Compare August 20, 2026 22:15
@yassin-berriai

Copy link
Copy Markdown
Contributor Author

@greptileai please re-review 69c8a91. The 5/5 anchored to e8872f7, which a force-push replaced; the delta is one CI action path rename

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.
@devin-ai-integration
devin-ai-integration Bot force-pushed the litellm_lit_5434_single_owner_jobs branch from 69c8a91 to 2ad9e53 Compare August 20, 2026 23:10
@yassin-berriai

Copy link
Copy Markdown
Contributor Author

@greptileai please re-review 2ad9e53. Automation rebased this onto newer staging, so the 5/5 at 69c8a914e9 is now orphaned

Comment on lines +214 to +220
if not await manager.renew_lock(cronjob_id=job_name, ttl=ttl_seconds):
verbose_proxy_logger.warning(
"%s: pod %s lost the lease mid-run, a second pod may be running this job",
job_name,
manager.pod_id,
)
return

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.

P1 Lost lease leaves job running

When an atomic renewal fails during a long-running job, _renew_until_cancelled stops renewing but _run_holding_lease continues awaiting the protected body. After the TTL expires, another pod can acquire the lease and run the same cleanup, rotation, or rollup concurrently with the original pod.

Knowledge Base Used: Database Schema and Proxy DB Access Layer

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.

Documented: release is compare-and-delete, so it cannot steal the successor's lease, and run must be idempotent. Cancelling the body would tear a half-finished prune

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.

That's a sound trade-off. Cancelling mid-body would leave rows half-deleted or a key half-rotated, which is worse than a concurrent idempotent run. The compare-and-delete release ensures the original pod can't evict the successor, and the docstring's idempotency requirement is the right place to carry that contract.

Acknowledged — the design is intentional and the reasoning is solid.

@devin-ai-integration

Copy link
Copy Markdown
Contributor

Moved to #47878: same commit, head now on the fork yassin-berriai/litellm. Review and CI continue there.

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.

4 participants