Repository navigation
perf(reset_budget_job): elect one sweeper per tick and bound the window scan - #36497
yassin-berriai merged 3 commits into
Conversation
|
|
Greptile SummaryThe PR elects one budget-reset worker per tick, paginates window-budget scans, and reduces event-loop serialization while preserving complete reset coverage
Confidence Score: 5/5The PR appears safe to merge No blocking failure remains
|
| Filename | Overview |
|---|---|
| litellm/constants.py | Adds the reset-job lock name and fixed lease TTL used for cross-pod election |
| litellm/proxy/common_utils/reset_budget_job.py | Implements lease election, lazy debug serialization, count-only hook metadata, and complete keyset-paginated window scans |
| litellm/proxy/proxy_server.py | Injects the existing pod lock manager into the scheduled reset-budget job |
| tests/litellm_utils_tests/test_proxy_budget_reset.py | Updates service-hook expectations for intentionally omitted row payloads |
| tests/test_litellm/proxy/common_utils/test_reset_budget_job.py | Covers leader election, Redis failure behavior, pagination, full-table traversal, and independent worker instances |
Reviews (4): Last reviewed commit: "perf(reset_budget_job): elect one sweepe..." | Re-trigger Greptile
PR overviewAll previously flagged issues have been addressed. No open security concerns remain on this pull request. Security reviewNo open security issues remain on this pull request. Fixed/addressed: 1 · PR risk: 0/10 |
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
eecee20 to
e90f3f9
Compare
|
@greptileai the starvation finding was correct and is fixed on head |
e90f3f9 to
f378455
Compare
|
@greptileai correct on both rounds; the per-run cap is now gone entirely on head |
|
Confirmed — removing the cap entirely is the right resolution. A cap is only safe if the resume position survives pod re-election, which it can't: the lease is released after each sweep, so the next tick can elect any pod, and that pod's cursor starts at Paging alone bounds the memory to one page at a time. The walk terminates when the table drains. Nothing needs to be shared. The concern is resolved. |
f378455 to
453a979
Compare
|
@greptileai please re-review f3115e2. Rebased onto staging, the pod-local cursor is gone, and the narrating comment on the lock wiring is deleted. |
…ow scan Every pod schedules the budget reset job, so a fleet re-read the whole due population and wrote it back against one Postgres at the same calendar boundary, multiplying a single sweep by its replica count. The job now takes the shared PodLockManager lease, so one pod sweeps per tick. A deployment with no Redis keeps its previous behavior, and a Redis that cannot answer sweeps unguarded rather than stranding every expired budget at its cap. The per-window scan read every row carrying budget_limits in one statement, so its cost grew with the deployment's key count. It is now keyset-paginated and walks to the end of the table on every sweep. A per-run cap would need a resume position, and no pod can hold one because the lease rotates between ticks, so the strictly advancing cursor is what terminates the walk. Found and updated rows were also JSON-serialized into the service hook's metadata and into debug lines on every chunk, on the event loop, whether or not anything consumed them. The hooks now carry counts, and the debug payload is deferred until a record is actually emitted. Resolves LIT-4793
453a979 to
f3115e2
Compare
|
@greptileai re-review f3115e2 please. Same tree as 453a9793e3, which an amend orphaned; only the commit message changed, so the anchor points nowhere. |
…der_election Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…itellm_reset_budget_leader_election
TLDR
Problem this solves:
How it solves it:
User Flow
Before: a developer whose classification service calls the proxy sees requests stall past their deadline every day just after the daily budget boundary
After: the same request keeps returning in tens of milliseconds across the boundary, because one replica does the reset and the others carry on serving
Relevant issues
Linear ticket
Resolves LIT-4793
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
Four proxy processes sharing one Postgres and one Redis, mirroring a fleet pointed at a single database. Flipping
budget_reset_atinto the past is exactly what the daily boundary does to a 24h budget, so the run below makes 40,000 keys come due at one instant and counts the reset writes the fleet actually issues. The minimum possible is one write per due key; anything above that is a second pod redoing work the first already did.Before captured at
05943b47a3, the base commit, and after ateecee2073f. Round two then removed the per-run cap from the windowed scan, so the after leg was re-run one90f3f95b2, and that run, reported at the end of this section, is where the AFTER v2 numbers come from. Head is now661d853da5, which isf3115e2f51merged with staging. Nothing in this section has been re-measured sincee90f3f95b2, which was still the capped, cursor-carrying build of the windowed scan.That change does not reach these counters. Keys still due and total spend read
budget_reset_atandspend, and the windowed scan writes neither: it rewrites only thebudget_limitsJSON. The write count is the one it could touch, since a window write lands on the same table the count greps, but the cap it lost reachedRESET_BUDGET_JOB_BATCH_SIZE * RESET_BUDGET_JOB_MAX_CHUNKS_PER_RUN, 50,000 rows at the defaults this rig ran, against the 40,000 seeded here, so it never bit and the capped and uncapped walks issue the same writes.budget_limitsis nullable with no default besides, so rows the seed leaves it unset on never enter that scanRig:
config.yamlcarriesstore_model_in_db: true, a Redis cache block, andproxy_budget_rescheduler_min_time: 15to compress the ten-minute production cycle.Make 40,000 keys due at once, then count reset writes over the next 150s:
Before, at
05943b47a3:After, at
eecee2073f:Both runs finish the reset: no key is left due and every key is zeroed, so the fix removes duplicate work without dropping any. The 2.56x figure is what four pods produce; it grows with replica count and with how long a sweep takes, which is why a 40-pod fleet on a large due population melts rather than merely spiking.
The pods that skipped a tick say so, and the lease is handed back after each sweep rather than held for its TTL:
Counted across the burst, the three non-leader pods yielded 4 times between them, which is the contention the lease converts into a skip instead of a duplicate sweep.
The event-loop cost the hooks used to pay, measured on the same 500-row chunk the job reads:
Re-run of the after leg on
e90f3f95b2. This one counts row updates frompg_stat_user_tablesrather than the statement log, because the log had grown large enough across runs that reading it returned an empty window; the previous script refused to compare that run rather than reporting a zero:pg_statcounters are sampled rather than exact, which is why this reads slightly under one write per key; the statement-log count above is the precise one. What matters is that it is nowhere near the 2.56x the unfixed build produces, and the reset still completes.Review notes
Three review rounds, and the last two each shrank the diff.
Round one: capping the window scan without remembering where it stopped meant every tick restarted at the first row, so a deployment with more windowed rows than one run's cap would never reach the rest, leaving them pinned at their cap indefinitely. The unbounded original could not starve, so the cap created that. First fix carried the position across ticks in the job instance.
Round two: that was still wrong, because the lease is released after every sweep, so consecutive ticks routinely run on different pods and a fresh pod's position is unset. It would restart at the first row and the tail would starve anyway. Rather than move the position into Redis, the per-run cap is gone: paging is what bounds the memory, and the cursor strictly advances so the walk terminates without a bound. That removes the cursor state, the resume logic, the wrap logic and the truncation warning, and with them the whole starvation question. Against the previous unbounded single-statement read this is strictly better on memory and identical on coverage.
Coverage for it: one test walks a table needing far more pages than a per-run cap would allow and asserts the last row is reached, and one runs two independent job instances, standing in for two pods, and requires each to cover the table end to end. Both were mutation-checked against reintroducing the cap, and both initially SURVIVED that mutant because the fixture tables were smaller than the default cap, so the tests now force the cap low to make it bite.
Round three: rebased onto current staging after the PR went conflicting, and deleted the review comments rather than defending them. Staging had independently added the same
db_spend_update_writermock line totests/test_litellm/proxy/test_proxy_server.py, so that file drops out of the diff entirely, and the only comment left to remove was the one on the lock wiring inproxy_server.py._acquire_leasealready carries that rationale in its docstring, so the comment was restating it in a second placeThe pod-local cursor finding is already resolved at this head, and was resolved before it was filed: it is anchored to
e90f3f95b2, the commit round two replaced._reset_windows_forstarts every walk at an empty cursor and loops until a page comes back short, with no per-run cap and no position on the instance, so which pod won the lease cannot change what gets swept.test_every_tick_sweeps_the_whole_window_table_whichever_pod_wonruns two separate job objects over one table and requires each to reach the last row, and reintroducing the cap fails it along withtest_reset_budget_windows_pages_to_the_end_of_a_large_tableType
🐛 Bug Fix
Caveats (if any)
Final Attestation
Link to Devin session: https://app.devin.ai/sessions/4f559acee90644a1bca9ad024785fb53
Requested by: @yassin-berriai