Skip to content

fix: cap cold MCP schema workers at usable CPUs and deflake wall-clock unit tests - #45791

Merged
mateo-berri merged 12 commits into
mainfrom
litellm_deflake_20261010
Oct 15, 2026
Merged

mateo-berri merged 12 commits into
mainfrom
litellm_deflake_20261010

Conversation

@devin-ai-integration

@devin-ai-integration devin-ai-integration Bot commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves:

  • Eleven unit tests flaked on unrelated PRs across the 2026-10-10 to 2026-10-15 runs
  • Most asserted on real wall-clock time on a shared CI runner
  • The MCP cold schema validation test failed 72 runs in one day, main included

How it solves it:

  • MCP schema validation starts at most one cold worker per CPU the proxy can run on
  • The key metadata recovery tests drive the cache through an injected clock
  • The MCP nested-method lock test waits on lock contention instead of 1s deadlines
  • Langfuse prompt tests record the generated client's sleeps instead of timing the call
  • A generic API test still covers automatic sending without timing assumptions
  • The autorouter count test jumps the event loop clock instead of waiting 2.05 real seconds
  • The router shared-Redis header and Redis prefetch tests pin the usage minute
  • The GitLab fork lookup test drops its 1s deadlines and waits on the events
  • The MCP discovery drain test drops its 1s deadlines the same way
  • The MCP change is the only production change, and no assertion was loosened

User Flow

Before: an MCP client on a one-CPU proxy pod calls a tool through the gateway's tool proxy and every call times out

  1. The proxy runs pinned to one CPU (a --cpuset-cpus container) with --num_workers 2 and one MCP server configured
  2. The client opens a session on POST http://localhost:4000/mcp/proxy and finds the tool with search_tools
  3. It sends 8 concurrent tools/call of call_tool with valid arguments on the freshly started proxy
  4. Every call returns HTTP 504 {"detail":"MCP handler did not respond in time"} after about 30s, and a second batch does the same

After: the same calls reach the MCP server and return its result

  1. The proxy runs pinned to one CPU (a --cpuset-cpus container) with --num_workers 2 and one MCP server configured
  2. The client opens a session on POST http://localhost:4000/mcp/proxy and finds the tool with search_tools
  3. It sends 8 concurrent tools/call of call_tool with valid arguments on the freshly started proxy
  4. All 8 return the tool's text in about 16s, and the next batch returns in about 0.5s

Main went red (2026-10-15)

mcp-elicitation failed on main at f08840579e in https://github.com/BerriAI/litellm/actions/runs/38692812376. Attempt 1 (job 116282572497) failed tests/unit/proxy/_experimental/mcp_server/test_operations.py::test_discovery_concurrent_listings_drain_on_failure_and_cancellation[cancel] and the rerun (job 116287762627) failed tests/unit/proxy/_experimental/mcp_server/test_mcp_server_tool_calls_and_headers.py::test_truncated_jsonrpc_response_with_nested_method_skips_lock[False-é-1-result], both with a TimeoutError from a 1s asyncio.wait_for. The same job passed on the five previous main commits and the tip commit only touched cost calculation tests, so there is no culprit commit. Mechanism is the same hard 1s wall-clock deadline on in-process async work on a loaded runner that the nested-method lock fix below already covers

The discovery test now awaits the four listing events and the gateway task directly, keeping every assertion, and the CI pytest timeout still bounds a hang. With the production drain broken (sibling listings neither cancelled nor awaited) its [failure] case fails at the closed-events assertion. Neither test reproduced locally (45 of 45 and 100 of 100), so the proof is this PR's own mcp-elicitation run at the tip

Earlier flake evidence (2026-10-10 to 2026-10-14)

Flake evidence (run date 2026-10-14)

tests/unit/proxy/_experimental/mcp_server/test_mcp_server_tool_calls_and_headers.py::test_truncated_jsonrpc_response_with_nested_method_skips_lock flaked 4 times in the window, always a cancel_request=True case in the mcp-elicitation job, failing on attempt 1 and passing on attempt 2 at the same sha in https://github.com/BerriAI/litellm/actions/runs/38464336690, https://github.com/BerriAI/litellm/actions/runs/38493778792, https://github.com/BerriAI/litellm/actions/runs/38524037967 and https://github.com/BerriAI/litellm/actions/runs/38524026698. Every failure was a TimeoutError from asyncio.wait_for(request_in_handle.wait(), timeout=1.0), the wait for the first request POST to reach the fake handler, before the response POST under test was even sent. Mechanism is a hard 1s wall-clock deadline on in-process async work on a loaded runner. The fix waits on the event directly, and for the deadlock check it puts a recording lock into the session's lock slot (the server looks it up with setdefault) and waits for whichever comes first, the response being handled or the response contending for the request's lock, then asserts it was the former. Replacing the top-level method check with a flat substring check makes the fixed test fail on the contention assertion right away instead of after a timeout. Hang protection is left to the CI pytest timeout. The test also now clears the _stateful_session_auth_context_last_seen entry it created

tests/unit/proxy/spend_tracking/test_key_metadata_recovery.py::test_recover_key_metadata_from_spend_logs_retries_a_failed_query_only_after_the_miss_ttl flaked once, on attempt 1 of https://github.com/BerriAI/litellm/actions/runs/38526405036, with assert (1791961913.553274 - 1791961882.199863) <= (30 + 1), and attempt 2 at the same sha passed. Mechanism is wall-clock dependence. The test compared the cache's real expiry timestamp with a time.time() taken before the call, with 1s of slack, so a slow runner broke it. InMemoryCache already accepts a clock, so this test and its sibling test_recover_key_metadata_from_spend_logs_never_caches_repeated_query_failures_as_long_as_a_hit now build the cache with a fake clock, assert the miss expires exactly at now + SPEND_LOG_KEY_METADATA_MISS_CACHE_TTL, and advance the clock past it instead of rewriting ttl_dict by hand. They also assert how many times the spend log query ran. Dropping the short miss TTL in _remember_short_lived_miss makes both fail

test_cold_concurrent_schema_validation_accepts_valid_arguments kept failing on attempt 1 on main's unfixed copy in this window, which this PR already fixes

Neither new candidate reproduced locally, the MCP test passing 400 of 400 including under 16 CPU busy loops, so both mechanisms come from the CI logs. After the fix each test passed 20 of 20 repeats and its owning file passed, and every test this PR already carried passed 20 of 20 on the combined branch

Dropped while merging main (2026-10-14)

#46261 landed equivalent fixes on main for test_vertex_gemini_gcs_uri_mime.py::test_async_transform_request_body_offloads_extensionless_gs_not_plain_text and the generic API callback tests, so this PR now takes main's version of both files and drops its own fixes there. It keeps test_generic_api_callback_sends_queued_events_on_its_own, because main also flushes those tests by hand and has nothing else covering the automatic flush. The 2026-10-10 and 2026-10-12 sections below still describe the original flakes

Not flakes in the 2026-10-14 window

On CircleCI, tests/integration/messages_endpoint/providers/anthropic/test_anthropic_messages_pre_content_retry_wire.py::test_stream_failing_before_content_is_retried_on_the_same_group_and_completes[error_frame-429-request] failed twice with State did not converge: [], meaning no spend log row showed up for the retried request within 70s, in [REDACTED SECRET]/gh/BerriAI/litellm/2259644 and [REDACTED SECRET]/gh/BerriAI/litellm/2259479, and passed in neighboring integration workflows. The mechanism is not pinned, so this PR leaves it alone. The rest of the CircleCI integration failures repeated across workflows and are breakages or rig issues, not flakes. On GitHub Actions the other red jobs were checkout timeouts, a CodeQL result set over its 2 GiB limit and a migration lock_timeout check, which are infra or real failures

Flake evidence (run date 2026-10-13)

tests/unit/proxy/_experimental/mcp_server/test_mcp_tool_search.py::test_cold_concurrent_schema_validation_accepts_valid_arguments failed in 72 workflow runs in the window, on main and on many unrelated PR branches. On main it failed on attempt 1 and passed on attempt 2 at the same sha in https://github.com/BerriAI/litellm/actions/runs/38298557060 (e12bc629), https://github.com/BerriAI/litellm/actions/runs/38299209693 (19327a60) and https://github.com/BerriAI/litellm/actions/runs/38307417758 (fead47fa). It failed on both attempts of https://github.com/BerriAI/litellm/actions/runs/38350698434 (c3ca8a51). Every failure returned "Tool argument validation exceeded its time limit" for all eight calls after about 30.15s, and the passing attempts took 28.15s and 29.67s against the same 30s limit

Mechanism is CPU oversubscription during cold worker startup, which is a real product bug. The test pins the proxy to one CPU, the way a --cpuset-cpus container or a static CPU manager pod does, and fires eight valid validations. _tool_argument_validation_error always allowed four process workers, so four cold workers each imported litellm on the same core and every call took about four imports' worth of CPU before validating anything. On a GitHub runner that lands right at the 30s validation deadline, so valid tool arguments got rejected. The fix sizes the validation limiter to the CPUs in the process affinity, capped at the old 4. On one CPU the first call pays one cold import and the other seven reuse the warm worker, and hosts with 4 or more CPUs keep 4 workers. The test also checks that no more than one worker was started while pinned. Hardcoding the limiter back to 4 makes it fail with assert 4 <= 1, and pinned to one CPU locally the call drops from 14.7s to 2.6s

tests/unit/integrations/langfuse/test_langfuse_sdk.py::test_cold_prompt_miss_never_sleeps_when_langfuse_is_down[http-500] flaked again on main's unfixed copy in https://github.com/BerriAI/litellm/actions/runs/38228185072 (litellm_win_wheel_uv_python_4b8e at 3c696ed5). This PR already carries its fix from 2026-10-10

The fixed MCP test passed 20 of 20 repeats. Its owning file and the whole mcp-server shard passed under -n 4 --dist loadscope, apart from 21 test_semantic_tool_filter.py tests that need the optional semantic_router package this box lacks. The seven tests this PR already carried passed 20 of 20 on the combined branch, with the whole Langfuse and generic API files each run 20 times

Not flakes in the 2026-10-13 window

Three unit tests timed out together at the 120s pytest limit in one job of https://github.com/BerriAI/litellm/actions/runs/38301603657 and passed on attempt 2, namely test_poller_releases_budget_reservation_when_interaction_ends_without_usage, test_proxy_process_request_forwards_decoded_container_id and test_pass_through_request_stream_param_override. All three hit the timeout at the same second, which points at a stalled runner rather than the tests, so they are left unfixed and unreproduced. Other unit failures followed what their branches changed and failed on every run of those branches, e.g. the OCI Cohere tests on fix/oci-cohere-tool-result-turn and the Anthropic error format tests on litellm_messages_529_overloaded_error. The rest of the red jobs were lint, title, cost map guard and CodeQL checks on PR branches, which are not test flakes

Flake evidence (run date 2026-10-12)

tests/unit/caching/test_request_redis_batch_pre_call.py::test_the_prefetch_mget_carries_only_the_keys_whose_read_is_due flaked once, on attempt 1 of https://github.com/BerriAI/litellm/actions/runs/38165618919 (litellm_fix_openapi_yaml at 812a899f). The next run on that branch at f834cb74 passed it in https://github.com/BerriAI/litellm/actions/runs/38167491546, and the only change in between was the MCP server manager. The second pipeline MGET carried extra dep-a:anthropic/claude-x:rpm:18-55 and tpm keys. Mechanism is wall-clock dependence. The test pins the cache clock but the usage-based routing v2 rpm and tpm keys come from get_utc_datetime() in lowest_tpm_rpm_v2, so a real minute rollover between the two requests made the second one read fresh minute keys. A scratch clock that rolls 12:00:59 to 12:01:00 between the two scopes reproduces the extra keys on unfixed code. The fix pins lowest_tpm_rpm_v2.get_utc_datetime the same way router_minute_pinned does. Setting the usage cache expiry to zero makes the fixed test fail with the extra keys

tests/unit/llms/vertex_ai/test_vertex_gemini_gcs_uri_mime.py::test_async_transform_request_body_offloads_extensionless_gs_not_plain_text flaked once, on attempt 1 of https://github.com/BerriAI/litellm/actions/runs/38227361814 (feature/smtp-email-spend-reports at 4a08515c), with Event loop blocked for 0.448s ... assert 0.448 < 0.4. The adjacent sha 4987e9dc passed in https://github.com/BerriAI/litellm/actions/runs/38224815634 and the diff between them only touched spend report email code. Mechanism is an assertion on elapsed wall-clock time, where a fake GCS call slept 0.5s and a concurrent 0.05s sleep had to finish under 0.4s. The fix uses two thread events. The fake GCS call signals it started and then waits for the event loop to set a second event, and the test asserts that wait succeeded. Making the transform call the GCS lookup synchronously makes the fixed test fail

tests/unit/proxy/roi_calculator/test_gitlab.py::test_fork_lookups_overlap_with_a_bounded_number_of_requests flaked once, on attempt 1 of https://github.com/BerriAI/litellm/actions/runs/38135356356 (litellm_any_sweep_20261011 at b2bdd597), with a TimeoutError from asyncio.wait_for(started.get(), timeout=1) on the first wave. The next sha 8cf53e54 passed in https://github.com/BerriAI/litellm/actions/runs/38136696998 and only changed OpenRouter and SageMaker code. Mechanism is a hard 1s wall-clock deadline on in-process async work on a loaded runner. The fix awaits the queue and the task directly and leaves hang protection to the CI pytest timeout. Raising the fork lookup semaphore from 8 to 9 makes the fixed test fail at started.empty(), and lowering it to 7 makes it hang until the pytest timeout

None of these three failed in 20 local repeats except the Redis prefetch test, which failed once with an IndexError on a missing second pipeline rather than the CI key mismatch. That local failure did not recur in 20 repeats after the fix, but its mechanism is not confirmed to be the same minute rollover. After the fix each test passed 20 of 20 repeats and each owning file passed alone and under CPU burn. The five tests this PR already carried also passed 20 of 20 each on the combined branch

Not flakes in the 2026-10-12 window

The other unit and smoke failures in the window failed on every run of their branch and followed what those branches changed, e.g. test_unit_of_work.py on feat/team-token-budget, the vertex passthrough billing tests on fix/gemini-tool-use-tokens-billing and the prisma span tests on a fork main. The rest were infra, namely checkout timeouts, a Rust maturin build failure during uv sync, an artifact upload timeout, and the scheduled E2E replay failing to resolve its fixtures bundle (unexpected end of JSON input)

Flake evidence (run date 2026-10-11)

tests/unit/test_router/test_router_helper_utils.py::test_headers_on_fresh_worker_reflect_shared_redis_usage flaked once. Attempt 1 of https://github.com/BerriAI/litellm/actions/runs/38105284067 (router shard at a192f28e) failed with assert 99 == 93 on x-ratelimit-remaining-requests, and attempt 2 of the same run at the same sha passed. Mechanism is wall-clock dependence. Router usage counters are keyed by the current UTC minute from litellm.router.get_utc_datetime, and unlike its siblings this test did not use the router_minute_pinned fixture, so a minute rollover between the earlier calls and the streaming call left the streaming call counting into a fresh minute bucket. A scratch run that rolls the clock from 12:00:59 to 12:01:00 right before the streaming call reproduces the exact 99 == 93 failure on unfixed code. The fix adds @pytest.mark.usefixtures("router_minute_pinned"). Making the header computation read only the worker's in-memory cache instead of the shared store makes the fixed test fail, so it still guards cross-worker usage. The same commit also drops redundant comments from test_generic_api_callback.py

tests/unit/integrations/test_custom_callback_input.py::test_logging_async_cache_hit_sync_call[True] also flaked once, on attempt 1 of https://github.com/BerriAI/litellm/actions/runs/38112337328 (integrations shard at 1af25069), with an unredacted message in a cache_hit=True standard logging payload, and attempt 2 at the same sha passed. It did not reproduce in 20 single-test repeats, 10 runs of its file under -n 4 --dist loadscope, or 5 runs of the whole integrations shard set, and forcing a delay into the async callback path did not trigger it either. The mechanism is not pinned, so this PR does not touch it and it is left for a human to look at

Not flakes in the 2026-10-11 window

The root job in https://github.com/BerriAI/litellm/actions/runs/38121026296 failed on every attempt on a stale tests/audio_tests path and a CircleCI step-count check, which is a real breakage and not a flake. Other failed jobs in the window were checkout timeouts and artifact upload or finalization errors, which are infra

Flake evidence (run date 2026-10-10)

tests/unit/integrations/langfuse/test_langfuse_sdk.py::test_cold_prompt_miss_never_sleeps_when_langfuse_is_down[http-404] flaked twice, on attempt 1 of https://github.com/BerriAI/litellm/actions/runs/37981580881 (fix/responses-reasoning-item-shape at 8cd669aa) and attempt 1 of https://github.com/BerriAI/litellm/actions/runs/38036500873 (litellm_techdebt_20261010 at bffd6e32). Neither branch touches Langfuse, and the first branch went green at the adjacent sha adcf7cc1 in https://github.com/BerriAI/litellm/actions/runs/38000967073. The failures were assert (142.47 - 141.27) < 0.5 and assert (143.11 - 142.08) < 0.5 with the request count already correct, so nothing slept and the runner was just slow. Mechanism is wall-clock dependence. The fix records time.sleep calls in the generated Langfuse HTTP client the same way the neighboring auth-check test already does and asserts there were none. The same change goes into test_one_transient_failure_on_a_cold_prompt_miss_does_not_fail_the_call, which used the same monotonic() < 0.5 check. Removing request_options=_NO_REST_RETRIES from _request_prompt makes both tests fail

tests/unit/integrations/generic_api/test_generic_api_callback.py::test_generic_api_callback_json_array_format_explicit flaked once, on attempt 1 of https://github.com/BerriAI/litellm/actions/runs/37989105125 (litellm_bedrock_grok_4_7_native_chat_completions at c4684ddb, a Bedrock-only change that passed this test at 02d9c165 in https://github.com/BerriAI/litellm/actions/runs/37973323615). The post was Called 2 times, and the second batch held an event whose mock completion took 1.3s on the runner. Mechanism is wall-clock dependence. The 1s periodic_flush fired partway through the five calls and split the batch. The fix gives the logger a flush interval that never fires during a test, waits until every success event is in log_queue, and then calls flush_queue() once. The other five tests in the file that used flush_interval plus a fixed asyncio.sleep get the same change. Sending each json_array entry as its own post makes the test fail with Called 5 times. Since these tests now flush explicitly, a new test_generic_api_callback_sends_queued_events_on_its_own keeps automatic sending covered. It uses a 0.05s flush interval, never calls flush_queue, waits until all three events have been posted, and asserts on what was sent rather than how many posts it took. Dropping the periodic_flush task from the constructor makes it fail

tests/unit/proxy/hooks/test_autorouter_baseline_cache.py::test_native_count_finishing_after_quarter_worker_budget_keeps_plan_and_spend flaked once, on attempt 1 of https://github.com/BerriAI/litellm/actions/runs/37914443287 (fix/router-latency-callback-registration at fe106a48, which leaves the autorouter hook and the logging worker alone). It failed with reason='token_count_timeout'. The fake token counter waited a real 2.05s inside the planner's 3.0s budget, so about 0.95s of runner lag was enough to trip it, and an earlier deflake that moved the wait from 2.3s to 2.05s only narrowed the window. Mechanism is wall-clock dependence. The fix patches time on the running loop object so the loop clock reads 2.05s later once counting starts, which still lands past a quarter of the 8s worker budget, and the counter yields once so an already expired deadline gets to fire. The test now takes about 0.1s instead of 2.2s. Changing the planner's fraction=0.75 to 0.25 makes it fail with token_count_timeout, the same failure CI showed

None of the three reproduced locally in 20 repeats, whole-file xdist runs, or runs next to an 8 core CPU burn on main. The mechanisms come from the CI logs above. After the fix each test passed 20 of 20 repeats, and each whole owning file also passed both alone and under CPU burn

Not flakes in the 2026-10-10 window

tests/unit/harness/sandbox/test_docker.py::test_real_docker_roundtrip failed 35 times across many branches because docker run alpine:3.20 could not pull from Docker Hub. That is infra and was left alone. The failures that only showed up on one branch, every run of it, followed what those branches changed, e.g. test_every_wif_kwarg_key_is_refused_from_a_client_router_config on litellm_lit_6898_openai_wif_routes and test_generation__input_reference_attached on feature/bytedance-video-adapter. Those are branch breakages, not flakes. No job in the window was re-run, so there was no same-sha attempt evidence

Other open deflake PRs

#43437, #42936 and #41219 each carry a human approval, so they stay open and untouched under the human-reviewed exception. This PR is the rolling PR and now also carries the 2026-10-11 through 2026-10-14 fixes

Pre-Submission checklist

  • I have added meaningful tests
  • The handful of test files covering my change pass locally, e.g. 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 more
  • My PR passes all required CI/CD checks (e.g., lint, schema.d.ts sync check, etc.)
  • My PR's scope is as isolated as possible; it only solves 1 specific problem
  • Every automated review on my PR's latest commit has finished, and I have addressed or replied to each of its findings before requesting a maintainer review

Screenshots / Proof of Fix

Setup and client loop

Setup shared by both legs: a real FastMCP streamable HTTP server exposing lookup_order(order_id, quantity), and a proxy booted with taskset -c 0 python -m litellm.proxy.proxy_cli --config config.yaml --num_workers 2 (one process, two workers, no DB) next to three taskset -c 0 python -c 'while True: pass' loops standing in for a busy single-CPU pod. The config only registers the server (mcp_servers.qa_orders, transport: http) and a master key. The client does initialize, notifications/initialized, tools/list and search_tools on /mcp/proxy, then fires two batches of 8 concurrent curls

for i in $(seq 1 8); do
  curl -s -w '%{time_total}\t%{http_code}\n' -H "Authorization: Bearer $KEY" -H "MCP-Session-Id: $SID" \
    -H 'Accept: application/json, text/event-stream' -H 'Content-Type: application/json' \
    -d '{"jsonrpc":"2.0","id":'$((100+i))',"method":"tools/call","params":{"name":"call_tool","arguments":{"tool_id":"'$TOOL_ID'","arguments":{"order_id":"QA-cold-'$i'","quantity":'$i'}}}}' \
    http://127.0.0.1:$PORT/mcp/proxy &
done; wait

Before (f088405)

  1. Cold batch, 8 calls: 0 of 8 succeed, each returns HTTP 504 {"detail":"MCP handler did not respond in time"}, median 30.03s
  2. Warm batch right after, 8 calls: 0 of 8 succeed, same 504, median 30.04s

After (58c6565)

  1. Cold batch, 8 calls: 8 of 8 return HTTP 200 with "text":"LOOKUP_OK order_id=QA-cold-1 quantity=1" and "isError":false, median 16.21s, max 16.32s
  2. Warm batch right after, 8 calls: 8 of 8 return LOOKUP_OK, median 0.49s, max 0.54s

call_tool argument validation is the only caller of the changed limiter, so this A/B also covers its whole live blast radius. Hosts whose affinity shows 4 or more CPUs keep the old 4 workers

  • Both legs logged stale MCP session warnings from worker hopping, unrelated to this PR
  • Cold calls still take 16s on a saturated single CPU, left alone here

The red main jobs pass at the tip: mcp-elicitation https://github.com/BerriAI/litellm/actions/runs/38698304869/job/116300269993 and router https://github.com/BerriAI/litellm/actions/runs/38698304869/job/116300270133

Type

🐛 Bug Fix
✅ Test

Caveats (if any)

Medium

  • On a one CPU cpuset host, one hostile schema now holds the only validation worker
    • Before, it took four concurrent hostile payloads to fill all four workers
    • Either way validation is bounded by the 30s deadline

Low

  • CPU quotas without a cpuset still see every core and keep 4 workers
  • The autorouter fix sets time on the shared session event loop object, and monkeypatch puts it back at teardown
  • The 2026-10-10 fixes come from CI logs because none of those three reproduced locally
  • The callback redaction flake from 2026-10-11 is unreproduced and left unfixed
  • The GitLab and MCP nested-method lock tests rely on the CI pytest timeout to bound a hang
  • The 2026-10-14 and 2026-10-15 fixes come from CI logs because none reproduced locally
  • The CircleCI Anthropic retry flake from 2026-10-14 is unreproduced and left unfixed

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

  • 58c6565 passes /live-pr-risk

Link to Devin session: https://app.devin.ai/sessions/0be17c11676f4b398feaf8236149ee1e
Open in Devin Desktop: https://app.devin.ai/desktop/session/0be17c11676f4b398feaf8236149ee1e?variant=devin
Requested by: @mateo-berri


Note

Low Risk
The only runtime change tightens MCP schema validation concurrency on low-CPU hosts; remaining edits are test-only and do not alter production paths.

Overview
Production: MCP tool argument schema validation no longer always allows four process workers. The anyio capacity limiter is sized from os.sched_getaffinity (when available), capped at four, so CPU-pinned proxies (e.g. one-core containers) avoid oversubscribing cold to_process workers and hitting the 30s validation timeout on valid payloads.

Tests: Deflakes CI by replacing brittle wall-clock assumptions—fake clocks for spend-log metadata miss TTL, pinned UTC minute for Redis prefetch and shared-Redis rate-limit headers, recorded Langfuse HTTP sleeps instead of monotonic() bounds, event-loop time advance for autorouter token counting, direct event waits (and lock-contention checks) for MCP session lock tests, and a Generic API test that polls until periodic flush posts all events. The concurrent schema validation test now asserts spawned worker count stays within the affinity cap.

Reviewed by Cursor Bugbot for commit 58c6565. Bugbot is set up for automated code reviews on this repo. Configure here.

…unit tests

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@devin-ai-integration

Copy link
Copy Markdown
Contributor Author

I'll fix CI failures and address comments from users with write access. I'll skip comments containing "(aside)".

  • Disable automatic comment, CI, and merge conflict monitoring

@CLAassistant

CLAassistant commented Oct 10, 2026 •

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 all sign our Contributor License Agreement before we can accept your contribution.
1 out of 2 committers have signed the CLA.

✅ mateo-berri
❌ devin-ai-integration[bot]
You have signed the CLA already but the status is still pending? Let us recheck it.

@greptile-apps

greptile-apps Bot commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 5/5

[Low impact] The PR appears safe to merge; both previous findings are fixed and no new blocking issue was found.

Summary

This PR replaces elapsed-time assertions and fixed waits across three test files.

  • Generic API logger tests flush complete batches on demand and still check automatic sending.
  • Langfuse prompt tests check retry sleeps instead of elapsed call time.
  • The autorouter timing test advances loop time instead of waiting in real time.

The latest changes fix Python 3.10 support and restore a separate check for automatic sending. Both previous findings are addressed. No new actionable issues were found.

Reviews (2) · Last reviewed commit: "test: keep generic API logger tests on 3..." · Reviewed by Greptile

@codecov

codecov Bot commented Oct 10, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@devin-ai-integration

Copy link
Copy Markdown
Contributor Author

@greptileai

@devin-ai-integration devin-ai-integration Bot changed the title test: inject clocks and wait on conditions in three wall-clock-flaky unit tests test: inject clocks and wait on conditions in four wall-clock-flaky unit tests Oct 11, 2026
@devin-ai-integration devin-ai-integration Bot changed the title test: inject clocks and wait on conditions in four wall-clock-flaky unit tests test: inject clocks and wait on conditions in seven wall-clock-flaky unit tests Oct 12, 2026
@devin-ai-integration

Copy link
Copy Markdown
Contributor Author

@greptileai

@devin-ai-integration devin-ai-integration Bot changed the title test: inject clocks and wait on conditions in seven wall-clock-flaky unit tests fix: cap cold MCP schema workers at usable CPUs and deflake seven wall-clock unit tests Oct 13, 2026
@codspeed

codspeed Bot commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

⚠️ 1 benchmark spent significant time in system calls

System calls cannot be consistently instrumented, so they are not included in the measure, which understates the real cost. Please switch to the Walltime instrument to accurately measure system calls.

Measurement and system calls

✅ 31 untouched benchmarks


Comparing litellm_deflake_20261010 (58c6565) with main (3cc9e7e)

Open in CodSpeed

@devin-ai-integration

Copy link
Copy Markdown
Contributor Author

@greptileai

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…s deadlines

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@devin-ai-integration devin-ai-integration Bot changed the title fix: cap cold MCP schema workers at usable CPUs and deflake seven wall-clock unit tests fix: cap cold MCP schema workers at usable CPUs and deflake wall-clock unit tests Oct 14, 2026
mateo-berri and others added 2 commits October 15, 2026 07:02
…overy drain test

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@greptile-apps

greptile-apps Bot commented Oct 15, 2026

Copy link
Copy Markdown
Contributor

Automatic reviews are disabled for this repository.

@mateo-berri

Copy link
Copy Markdown
Contributor

@litereview code-review

@litereview

litereview Bot commented Oct 15, 2026

Copy link
Copy Markdown

✅ code-review

5/5 · Ready for human review

Scope: full · Full PR review.

No correctness findings.

The one production change caps the cold MCP schema validation limiter at min(4, usable CPUs). It reads the CPU count from os.sched_getaffinity(0) and falls back to os.cpu_count(). Its only caller is _tool_argument_validation_error, reached from tool_search.py:661. The cap applies when the per-loop RunVar limiter is first created and never raises the old limit of 4, so the change breaks no API or default. The test edits replace wall-clock deadlines with injected clocks, events, or recorded sleeps. Each rewritten test still asserts the behavior it guarded before.

Checks and execution details
  • Passed · Real testing evidence (required): Not applicable: no LLM translation changes in the scoped paths. The PR changes litellm/proxy/_experimental/mcp_server/tool_search.py and files under tests/unit/**. It touches nothing under litellm/llms/** or litellm/litellm_core_utils/prompt_templates/**.
  • Passed · Targeted unit tests for every changed test file (optional): I ran uv sync --frozen --all-extras --group dev, then uv run pytest on the changed tests and their owning files: MCP tool search cold validation, the nested-method lock test, key metadata recovery, the router shared-Redis header test, the Redis prefetch test, generic API callback, langfuse SDK, gitlab, autorouter baseline cache and MCP operations. Result: 460 passed, 1 failed. The failure was ModuleNotFoundError: psutil because my first sync left out the ci group. The unit-test CI jobs install that group with --group ci, and it pins psutil==7.2.2. After uv pip install psutil==7.2.2, test_cold_concurrent_schema_validation_accepts_valid_arguments passed 3 of 3 runs on a 2-CPU sandbox.
  • Passed · Caller trace for schema validation limiter (optional): _tool_argument_validation_error is the only consumer of _SCHEMA_VALIDATION_LIMITER and _schema_validation_worker_count, and it is called from tool_search.py:661. The limiter stays per event loop (RunVar) and is capped at 4 as before. On hosts with 4 or more usable CPUs, behavior does not change.

View review · Reviewed 58c6565651c4

@mateo-berri

Copy link
Copy Markdown
Contributor

bugbot run

@cursor cursor Bot left a comment

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.

✅ 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 58c6565. Configure here.

@mateo-berri mateo-berri left a comment

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.

LGTM

@mateo-berri
mateo-berri merged commit bf56719 into main Oct 15, 2026
109 of 110 checks passed
@mateo-berri
mateo-berri deleted the litellm_deflake_20261010 branch October 15, 2026 07:48

This branch was successfully deployed

No deployments
e2e-changed — 58c65656 Deployed Oct 15, 2026 by devin-ai-integration[bot] via oauth #5219
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.

2 participants