Repository navigation
fix(router): key prompt caching affinity on tools and the /v1/messages system prompt - #46411
Conversation
…s system prompt Co-authored-by: nuernber <benjamin.nuernberger@jpl.nasa.gov> Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
|
I'll fix CI failures and address comments from users with write access. I'll skip comments containing "(aside)".
|
|
@greptileai please review head f897715, which keys prompt caching affinity on tools and the top-level system prompt |
Merging this PR will not alter performance
|
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
|
@litereview code-review |
|
Looks like this was accidentally closed by the bot? |
Resolves the conflicts with #46084: the write side now passes both the request tools and honors_one_hour_ttl to async_add_model_id, and the success-event fixture carries custom_llm_provider and model_map_information, which _honors_one_hour_cache_ttl reads
|
|
1 similar comment
|
|
|
@litellm-stampbot |
litellm-stampbot: risk lowApproved at Rules (
Cursor Bugbot: run requested, finished in 5 min, no risk line for the head, so the judge decided.
Pushes do not re-run this check. Comment |
|
bugbot run |
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.
❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.
Reviewed by Cursor Bugbot for commit d34367d. Configure here.
| return False | ||
| return _is_ephemeral_mark( | ||
| cast(Mapping[str, object], function).get("cache_control") # cast-ok: function is a plain JSON dict | ||
| ) |
There was a problem hiding this comment.
Nested tool TTL marks ignored
Medium Severity
The new tool logic treats nested function.cache_control as a breakpoint and strips it from the key, but pin_ttl_seconds still only reads top-level cache_control. A 1h nested mark therefore writes a 5-minute pin, so affinity drops while the provider cache is still warm.
Reviewed by Cursor Bugbot for commit d34367d. Configure here.
There was a problem hiding this comment.
Fixed in 00c4b37. pin_ttl_seconds now reads cache_control nested under function too, with a 1h-nested-under-function test case
kerry-berri
left a comment
There was a problem hiding this comment.
Low risk by rule and by judgement at d34367d
|
Main CircleCI job integration-providers fails test_chat_one_hour_mark_on_a_tool_definition_alone_writes_no_pin since this merged. The test still expects a tool-only mark to write no pin (pipeline 91419) |
…control Resolves the conflicts with #46411 and #46601. A prompt_cache_breakpoint on a tool now marks a tool boundary and is stripped from the tools affinity key like cache_control. The Claude cache planning in completion() now uses the resolved reasoning effort, thinking and output_config that the real call sends, and it moves into a helper so completion() stays under the type checker's complexity limit
The Gemini TTS billing and text completion guardrail tests read spend rows from the owned proxy's own database, which #47213 made private. The cursor wire test derives its effort levels from the gpt-5 cost map row that #43935 now enforces, and the Azure effort check accepts the unquoted level. The pin TTL test asserts the one hour pin #46411 writes for a tool-only mark, the video callback test decodes ids with the product decoder after #44614, and the two Gemini 3.8 flash stream cost cases bill audio at the text rate their rows imply


TLDR
Problem this solves:
/v1/messagessystem wrote no pin/v1/messagessystem wrote a pin the lookup never computedHow it solves it:
systemthe same waycache_controlnow counts as a prefix boundaryUser Flow
Before: a client that sends the same cached prompt to a model group with two deployments keeps landing on different deployments, so each deployment pays its own cache write
model_namewithoptional_pre_call_checks: ["prompt_caching"]system(string or list form) or tools carryingcache_control, six timesx-litellm-model-idflips betweendeployment-Aanddeployment-Bacross the six callsAfter: the same six calls stick to one deployment
x-litellm-model-idis the same on all six callsRelevant issues
Fixes #28427. This reimplements the idea from #40776 (system prompt prepend on both sides) on top of the current prefix-position keying, with the contributor credited as co-author
Linear ticket
Resolves LIT-9460
Files changed
litellm/router_utils/pre_call_checks/prompt_caching_deployment_check.pyasync_filter_deploymentsandasync_log_success_eventnow prepend the top-levelsystemviaPromptCachingCache.prepend_system_promptand pass the request tools into the token gate and intoasync_get_model_id/async_add_model_id, which were both called withtools=Nonelitellm/router_utils/prompt_caching_cache.pyprepend_system_prompt(dedupes the string copy standard logging already prepends)._seedtreatsNoneand[]alike and ignores toolcache_control(top level andfunction.cache_control) so a moved marker keeps the key. New_tool_boundary_positionemits a position for the tools up to the last marked one, so a tool-only breakpoint produces a pin.pin_ttl_secondsreads a tool'scache_controlnested underfunctiontoo, so a 1h mark there writes a 1h pin (Bugbot finding at d34367d)Existing pins stay readable: a request with no tools hashes with the same empty seed as before, so only requests that carry tools move to a new key, which is the fix
Pre-Submission checklist
uv run pytest tests/unit/<your_test_file>.py -vThe new tests in
test_prompt_caching_deployment_check.pydrive the real write (async_log_success_event) and then the real read (async_filter_deployments) for six rows (chat tool mark, chat nestedfunction.cache_control,/v1/messagesstring system, list system, Anthropic tool mark, and a no-system control). Each of these mutants fails at least one test: dropping the read-side or write-side system prepend,tools=Noneon either side, dropping the tool boundary, dropping the dedupe, dropping nested-mark detection or strippingTaxonomy audit before push. F3 found that
function.cache_controlwas invisible to the new tool logic and is fixed. H4 found two lines over 120 chars, fixed. H6 found a duplicated pin key format, extracted into_pin_cache_key. W1 n/a,prepend_system_promptbuilds a new list and never mutates the request. X1 checked,Noneand[]tools deliberately share a seed and empty or non str/list systems are ignored. G n/a, streaming success events carry the sametools/systemkwargs, verified live below. C1-C7 n/a, no public field or default changesScreenshots / Proof of Fix
Two deployments of
anthropic/claude-haiku-4-5behind onemodel_name,optional_pre_call_checks: ["prompt_caching"], real Anthropic calls. Each case sends the same body six times in a row withfor i in 1 2 3 4 5 6; do curl -s -D h.txt http://localhost:4000<path> -H "Authorization: Bearer $KEY" -H "Content-Type: application/json" -d @<case>.json; grep -i x-litellm-model-id h.txt; done. Bodies are byte-identical across Before and After. The long text is about 8k tokens (500 short rules), cached by Anthropic, socache_read_input_tokensis around 8000 in both armsCases:
tools_chatis chat withcache_controlonly on an OpenAI-format tool.string_system_messagesis/v1/messageswith a stringsystemand a breakpoint on the user block.list_system_messagesis/v1/messageswith the only breakpoint (ttl: 1h) on a listsystemblock.control_messagesis/v1/messageswith no system and a breakpoint in messages.auto_*run withLITELLM_ENABLE_ANTHROPIC_PROMPT_CACHING=trueand no client markers.stream_*add"stream": trueBefore (b22a0bd, main)
tools_chat: B B A A B Astring_system_messages: A B B A A Blist_system_messages: A A A B A Acontrol_messages: A A A A A Aauto_string_system_messages: B A B A B Aauto_list_system_messages: A B A A B Bauto_system_chat(system inside messages): A A A A A Astream_tools_chat: A A B B A A, time to first byte 0.42 to 0.86 sstream_list_system_messages: B A A A B A, time to first byte 0.40 to 0.45 sAfter (ced2935, rebased to f897715 with no diff change)
tools_chat: B B B B B Bstring_system_messages: A A A A A Alist_system_messages: B B B B B Bcontrol_messages: A A A A A Aauto_string_system_messages: A A A A A Aauto_list_system_messages: A A A A A Aauto_system_chat: A A A A A Astream_tools_chat: B B B B B B, time to first byte 0.45 to 0.89 sstream_list_system_messages: B B B B B B, time to first byte 0.40 to 0.55 sThe control rows pin in both arms, and the first request of a row picks a deployment at random, so the letter differs between arms. Time to first byte does not move because only the routing key changes
Rerun at d34367d (merged with main after #46084 landed)
The branch no longer merged cleanly once #46084 added
honors_one_hour_ttlto the write path, so d34367d merges main in and keeps both: the tools andsystemgo into the key, and the write still passeshonors_one_hour_ttl. Same rig as above, Before is main at 0e7c490, After is d34367d,cache_read_input_tokensaround 15000 on every call after the firsttools_chat: Before B A A A A B, After A A A A A Astring_system_messages: Before A B B B A B, After B B B B B Blist_system_messages: Before A B B A B A, After A A A A A Acontrol_messages: Before B B B B B B, After B B B B B BMutation for the nested TTL read: reverting
_carrier_cache_controlfailstest_pin_ttl_follows_the_longest_breakpoint_ttl[1h-nested-under-function], 37 others passType
🐛 Bug Fix
Caveats (if any)
Low
systemcan still split read and write keys, same as formessagestodayFinal Attestation
Link to Devin session: https://app.devin.ai/sessions/cd18f9b1c1eb4adbb2c663e2adc5246a
Open in Devin Desktop: https://app.devin.ai/desktop/session/cd18f9b1c1eb4adbb2c663e2adc5246a?variant=devin
Requested by: @yassin-berriai
Link to Devin session: https://app.devin.ai/sessions/dfc6fc5cc08f48e49da72d46abc3d599
Open in Devin Desktop: https://app.devin.ai/desktop/session/dfc6fc5cc08f48e49da72d46abc3d599?variant=devin
Requested by: @kerrylu-berri