Skip to content

test(e2e): keep the prompt-caching affinity test on the live provider - #47072

Merged
yuneng-berri merged 1 commit into
mainfrom
litellm_test_c97533
Oct 17, 2026
Merged

yuneng-berri merged 1 commit into
mainfrom
litellm_test_c97533

Conversation

@yuneng-berri

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves:

  • The prompt-cache affinity e2e test goes red on Buildkite for a day at a time
  • Its Anthropic calls were served from the shared provider-response cache
  • A replayed follow-up reports cache creation, so the cache-read assertion fails

How it solves it:

  • Mark the test provider_live, so its deployments always call the real provider
  • Same convention PROVIDER_CACHE.md already sets for prompt-caching tests
  • Every assertion stays exactly as strict

User Flow

Before: a release engineer reading the litellm-e2e full suite sees this test fail even though routing worked

  1. Buildkite runs the suite with E2E_PROVIDER_CACHE=1 against rc/1.107.0 (build 707)
  2. The test's three Anthropic calls are all answered from recordings, none from Anthropic
  3. Follow-up 1's recording was captured on a cold provider cache, so it reports cache_read_input_tokens=0 cache_creation_input_tokens=14400
  4. The test fails with "follow-up 1 stayed on but read nothing from the cache" and stays red until the recording expires 24 hours later

After: the same run calls Anthropic for real, so the result reflects what the router and provider actually did

  1. Buildkite runs the suite with E2E_PROVIDER_CACHE=1
  2. The test's deployments skip the response cache and call Anthropic live
  3. Every follow-up stays on the cached deployment and reads the prompt cache back
  4. The test passes, and would only fail if affinity or provider caching really broke

Pre-Submission checklist

  • I have added meaningful tests
  • The handful of test files covering my change pass locally
  • 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

Shared setup. A local proxy from this branch on a free port, a throwaway Postgres, store_model_in_db: true, a random master key, and router_settings.optional_pre_call_checks: ["prompt_caching"]. Real Anthropic Haiku 4.5 and OpenAI keys. For the cache-on runs, a throwaway Redis plus E2E_PROVIDER_CACHE=1, E2E_PROVIDER_CACHE_REDIS_URL, a random 32-byte E2E_PROVIDER_CACHE_HMAC_KEY, a private namespace and a metrics dir. Every run is

E2E_PROMPT_CACHING_STACK=1 LITELLM_PROXY_URL=http://localhost:<port> LITELLM_MASTER_KEY=<key> <cache env> \
  uv run pytest "tests/e2e/router/test_reliability_prompt_caching_e2e.py::TestReliabilityPromptCachingAffinity::test_cached_conversation_stays_on_deployment_holding_its_cache" -q

Before (355dea2)

Build 707 on Buildkite

  1. Downloaded the full-suite job's artifacts with bk artifacts download --pipeline berriai-1/litellm-e2e --build 707 --job-uuid 01a147b1-5713-4240-8138-764b19d0f858
  2. attempt-0/provider-cache/keys-135.json lists this test's three Anthropic calls, with outcome hit, hit, hit. Every call was a replay
  3. junit.xml holds the failure follow-up 1 stayed on 22aa365e-... but read nothing from the cache, usage=prompt_tokens=14419 ... cache_read_input_tokens=0 cache_creation_input_tokens=14400

Local reproduction with the cache on

  1. Run A records every call: 1 passed, edge metrics show 4 misses and 4 writes. The body digests match build 707's for the same slots
  2. Deleted only follow-up 1's recording from Redis, as if it alone had expired
  3. Run B: edge outcomes hit, hit, miss. The first call replayed, so Anthropic never saw this run's cache write, and the live follow-up 1 hit a cold cache
E   AssertionError: follow-up 1 stayed on a5e4d8f3-... but read nothing from the cache, usage=prompt_tokens=16221 completion_tokens=131 total_tokens=16352 cache_read_input_tokens=0 cache_creation_input_tokens=16200
1 failed in 37.59s
  1. Run C: edge outcomes hit, hit, hit, and the poisoned recording now fails on pure replay, the same shape as build 707
E   AssertionError: follow-up 1 stayed on b99794be-... but read nothing from the cache, ... cache_read_input_tokens=0 cache_creation_input_tokens=16200
1 failed in 33.93s

After (4841cc0)

Local reproduction with the cache on

  1. Same Redis, still holding the poisoned recording from Before, three runs in a row
=== cache on, with marker, run D1
1 passed in 40.45s
=== cache on, with marker, run D2
1 passed in 38.39s
=== cache on, with marker, run D3
1 passed in 41.10s
  1. No edge metrics file was written in any of the three runs, so no call touched the cache. Redis still holds the same 4 recordings

Live with the cache off

  1. Three runs with E2E_PROVIDER_CACHE=0: 1 passed in 43.14s, 1 passed in 39.86s, 1 passed in 39.30s

Negative control

  1. Stripped cache_control from the follow-ups' system turn only, then ran live twice
  2. Both fail on the routing assertion, because the follow-ups shuffle onto the 20x-weighted OpenAI deployment
E   AssertionError: follow-up 0 landed on 'c7abca37-...' instead of the deployment holding the cache (fc0ae616-...), even though the heavier-weighted newcomer holds no cache for this conversation
1 failed in 36.36s
  1. Restored the file. The committed diff is the one marker line

Type

✅ Test

Caveats (if any)

Low

  • With the marker, both of the test's deployments go live, including the OpenAI one
    • Affinity keeps it idle, so it only costs money if routing breaks

QA runbook

  • tests/e2e/router/test_reliability_prompt_caching_e2e.py::TestReliabilityPromptCachingAffinity::test_cached_conversation_stays_on_deployment_holding_its_cache - a conversation that wrote an Anthropic prompt cache keeps landing on that deployment and reads the cache back, even after a 20x heavier deployment joins its group. Needs a proxy with store_model_in_db: true, router_settings.optional_pre_call_checks: ["prompt_caching"], and ANTHROPIC_API_KEY plus OPENAI_API_KEY in its env
    • Confirm the setting is live: curl http://localhost:4000/router/settings -H "Authorization: Bearer $LITELLM_MASTER_KEY" and expect "optional_pre_call_checks":["prompt_caching"]
    • Add the cached deployment: curl -X POST http://localhost:4000/model/new -H "Authorization: Bearer $LITELLM_MASTER_KEY" -d '{"model_name": "qa-cache", "litellm_params": {"model": "anthropic/claude-haiku-4-5", "api_key": "os.environ/ANTHROPIC_API_KEY", "weight": 1}}'
    • Send POST /v1/chat/completions with model qa-cache, a system turn of roughly 14k tokens whose text part carries "cache_control": {"type": "ephemeral"}, and a short user turn. Expect 200 and usage.cache_creation_input_tokens above 0
    • Add a second deployment under the same name: POST /model/new with "model": "openai/gpt-5.5", "api_key": "os.environ/OPENAI_API_KEY", "weight": 20
    • Send the same system turn three more times, each with a new user turn. Expect each response's x-litellm-model-id header to name the Anthropic deployment and usage.cache_read_input_tokens above 0
    • When running the suite with E2E_PROVIDER_CACHE=1, expect no provider-cache metrics entry for this test, since its deployments never go through the cache
    • Sanity check: this test makes sense to add and is not hand-wavey (e.g., assert actual expected spend instead of just spend > 0) or potentially flaky

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

With E2E_PROVIDER_CACHE=1 the test's Anthropic deployment went through the
shared response cache. Each call's recording expires on its own, so a run
could replay the cache-writing call while a follow-up went live against a
cold provider cache, recording creation instead of a read. That recording
then replayed as a failure for 24 hours. Mark the test provider_live, as
PROVIDER_CACHE.md requires for prompt-caching tests
@codecov

codecov Bot commented Oct 17, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@yuneng-berri
yuneng-berri enabled auto-merge (squash) October 17, 2026 06:26
@yuneng-berri

Copy link
Copy Markdown
Contributor Author

@litellm-stampbot

@litellm-stampbot

litellm-stampbot Bot commented Oct 17, 2026 •

Copy link
Copy Markdown

litellm-stampbot: risk low

Approved at 4841cc0.

Rules (stampbot/risk_rules.yml):

  • low: no rule flagged it

Judge (gpt-6-luna): low, probability of high 0.00 (high at or above 0.75)

  • risk: low (probability of high 0.00)

Pushes do not re-run this check. Comment @litellm-stampbot again to re-check the new head.

@litellm-stampbot litellm-stampbot Bot added the risk:low Small, isolated, low-risk change label Oct 17, 2026

@kerry-berri kerry-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.

Low risk by rule and by judgement at 4841cc0

@yuneng-berri
yuneng-berri merged commit 6b45a19 into main Oct 17, 2026
86 checks passed
@yuneng-berri
yuneng-berri deleted the litellm_test_c97533 branch October 17, 2026 06:27
yuneng-berri added a commit that referenced this pull request Oct 17, 2026
…in (#47090)

* fix(bedrock)!: block realtime replay after an input-first start and reject malformed Nova Sonic session settings (#46936)

* fix(bedrock): block realtime replay after input starts the session and reject non-string instructions and voice

* test(bedrock): name the malformed realtime setting test for its string cases

* fix(bedrock): replay the opening realtime message until Bedrock accepts the stream and refuse any fallback after commit

Also rejects a malformed modalities, input_sample_rate_hertz or tools setting with invalid_type, dropped under drop_params.

* fix(bedrock): replay a refused opening message on any fallback and reject OpenAI voices and non-string audio formats

* fix(realtime): read the client scope only when the websocket has one and reject any-case OpenAI and empty Bedrock voices

* test(bedrock): cover realtime replay, refusal and committed failure through a real proxy

Fix the scripted Bedrock peer's port import and the nested tool call cell's stale expected events, so the Nova Sonic integration file collects again

(cherry picked from commit 3ef0b35)

* test(integration): write worker configs beside test-supplied configs (#47066)

Under worker isolation the harness rewrote every proxy config into the owned proxy's directory, so modules a test placed next to its own config (custom_auth) no longer resolved and the proxy died at boot. The copy now lands next to a test-supplied config, while configs inside the checkout still go to the worker directory so nothing is written into the repo tree

(cherry picked from commit e754857)

* test(e2e): keep the prompt-caching affinity test on the live provider (#47072)

With E2E_PROVIDER_CACHE=1 the test's Anthropic deployment went through the
shared response cache. Each call's recording expires on its own, so a run
could replay the cache-writing call while a follow-up went live against a
cold provider cache, recording creation instead of a read. That recording
then replayed as a failure for 24 hours. Mark the test provider_live, as
PROVIDER_CACHE.md requires for prompt-caching tests

(cherry picked from commit 6b45a19)

* test(integration): send post-kill requests on a fresh connection in two worker-kill tests (#47080)

kill() returns once the killed worker's main thread is a zombie, but its other threads can
still be exiting and holding its sockets open. A keep-alive connection pooled to that worker
still looks healthy, so the next request goes out on it and the closing socket answers with
a reset. The old reap wait used to hide this. A new connection can only be accepted by a
live worker, so the surviving-worker assertions now run on a fresh client

(cherry picked from commit c32eea6)

* fix(caching): keep prompt cache usage on streamed cache hits (#47073)

* fix(caching): keep prompt cache usage on streamed cache hits

A stream=true request served from the response cache rebuilt its usage from
the prompt, completion and total counts only, so prompt_tokens_details and the
cache read and creation counts were dropped on the replayed stream. /v1/messages
clients routed to Bedrock Converse saw input_tokens equal to the whole prompt
and no cache tokens on a hit.

Both replays now build the usage through one helper that also restores
prompt_tokens_details and the integer cache read and creation counts, skipping
cached values that do not validate.

* fix(caching): coerce replayed token counts the way the live usage does

The replay accepted only exact ints for the token counts, so an integral float
or numeric string in a cached entry became 0 where the previous replay kept it.
Counts now go through pydantic int coercion and fall back only when they do not
validate.

(cherry picked from commit d346d76)

* fix(logging): keep the async request's logging payload when the sync success thread runs late (#47019)

* fix(logging): keep the async request's logging payload when sync callbacks run late

Treat the "cache" success callback as internal when deciding whether to start
the sync success thread for async requests. It has no branch in the sync
handler, so with `cache: true` that thread did nothing except rebuild and
overwrite model_call_details["standard_logging_object"].

When the sync handler does run for an async request (a real sync-only logger
is configured), it now builds its own payload and hands it only to its own
callbacks. The async handler keeps sole ownership of the shared payload, so
edits made by async logging hooks (for example the v3 rate limiter's mirrored
x-ratelimit headers that Prometheus reads) are no longer discarded. Sync
requests keep their existing behavior.

* fix(logging): keep sync cache hits logged and isolate the async-request payload build

The sync completion cache-hit path reused handle_sync_success_callbacks_for_async_calls,
so treating "cache" as internal silently dropped sync callbacks on sync cache hits. It now
submits the sync handler through its own method, as it effectively always did.

For async requests the sync handler builds its payload from a copy of the call details, so
message redaction cannot rewrite the shared standard_logging_object, and when it builds no
payload its callbacks keep the shared one instead of getting None.

* test(caching): lock sync cache-hit logging for completion, embedding and text_completion

* test(logging): keep sync hook edits off a caller-supplied payload for async requests

* fix(logging): give sync hooks a copy of the async payload when the thread builds none

* test(logging): check every legacy sync logger gets the thread's own payload

* test(logging): cover traceloop and supabase sync logging for async requests

(cherry picked from commit a4e0570)

* fix(cost): price exact cost-map names before price-free capability rules, and fix SCIM and MCP integration tests on CircleCI (#47037)

* fix(test-harness): preserve sibling auth modules in isolated worker configs

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

* test(integration): expect servers in MCP connect-flow descriptions

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

* test(integration): expect ptu_hours in daily activity metrics after #43043

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

* test(integration): kill every serving worker once the SCIM push blocks on the row lock

* fix(cost): price exact cost-map names before price-free capability rule matches

* test(streaming): price a priced alias stream at its deployment model and keep the unpriceable case unmapped

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

* fix(cost): price an explicit base_model under its own provider after candidate reordering

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

* fix(cost): retain priced generalized candidates and skip explicit-pricing lookups

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

* test(cost): assert custom pricing makes no remote model-info requests

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

* refactor(cost): keep the per-candidate pricing provider final

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

* fix(router): pin a Bedrock application profile prompt for the one-hour ttl its base model sends

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

* test(integration): assert the Nova Sonic tool-call argument delta carries the full arguments

* fix(cost): sort cost candidates from the static cost map and rules, without provider lookups

* test(integration): bill route-priced Bedrock chat streams and responses, and pin application profiles for an hour on messages and cache hits

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: Yuneng Jiang <yuneng@berri.ai>
(cherry picked from commit 4a58784)

* test(e2e): warm the memory test up with two batches before the measured one (#47087)

* test(e2e): warm the memory test up with two batches before the measured one

On a cold worker the second batch of failing requests can still raise the
allocator's high-water mark by about 50 MB while the live Python heap stays
flat, so the 48 MB budget failed about 1 in 10 Buildkite runs without a leak.
The test now runs two warmup batches, measures the third against the same
budget, and records every batch's settled growth per worker as an
rss_batch_growth JUnit property for later calibration

* test(e2e): record each memory batch's growth as soon as it settles

A failure in a later batch no longer drops the growth already measured, and
the worker keys are no longer sorted, which raised on a mix of named and
unnamed hosts

* test(e2e): silence the xunit2 record_property warning on the memory test

(cherry picked from commit 1fd7f81)

* test: import pytest and Final for the backported #47073 test on rc

On main these imports came from an earlier commit that is not on rc/1.107.0, so the
picked test failed collection with NameError

---------

Co-authored-by: Mateo Wang <277851410+mateo-berri@users.noreply.github.com>
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

risk:low Small, isolated, low-risk change

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants