Skip to content

fix(router): key prompt caching affinity on tools and the /v1/messages system prompt - #46411

Merged
klu-berri merged 3 commits into
mainfrom
litellm_prompt_caching_affinity_tools_system
Oct 20, 2026
Merged

klu-berri merged 3 commits into
mainfrom
litellm_prompt_caching_affinity_tools_system

Conversation

@yassin-berriai

@yassin-berriai yassin-berriai commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves:

  • Prompt caching affinity ignored tools when building its routing key
  • A cache breakpoint on a tool or a list /v1/messages system wrote no pin
  • A string /v1/messages system wrote a pin the lookup never computed

How it solves it:

  • Lookup and write both prepend the top-level system the same way
  • Lookup and write both pass the request tools into the key
  • The last tool carrying cache_control now counts as a prefix boundary

User 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

  1. The admin configures two deployments under one model_name with optional_pre_call_checks: ["prompt_caching"]
  2. The client sends POST http://localhost:4000/v1/messages with a long system (string or list form) or tools carrying cache_control, six times
  3. x-litellm-model-id flips between deployment-A and deployment-B across the six calls
  4. http://localhost:4000/ui/?page=logs shows the same request served by both deployments

After: the same six calls stick to one deployment

  1. Same config
  2. Same six requests
  3. x-litellm-model-id is the same on all six calls
  4. The Logs page shows every request on the same Model ID

Before, request 5 on deployment-A
Before, request 3 of the same tool-marked request on deployment-B
After, request 2 on deployment-B
After, request 6 on deployment-B

Relevant 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

File What changed and why
litellm/router_utils/pre_call_checks/prompt_caching_deployment_check.py async_filter_deployments and async_log_success_event now prepend the top-level system via PromptCachingCache.prepend_system_prompt and pass the request tools into the token gate and into async_get_model_id / async_add_model_id, which were both called with tools=None
litellm/router_utils/prompt_caching_cache.py New prepend_system_prompt (dedupes the string copy standard logging already prepends). _seed treats None and [] alike and ignores tool cache_control (top level and function.cache_control) so a moved marker keeps the key. New _tool_boundary_position emits a position for the tools up to the last marked one, so a tool-only breakpoint produces a pin. pin_ttl_seconds reads a tool's cache_control nested under function too, so a 1h mark there writes a 1h pin (Bugbot finding at d34367d)
flowchart LR
  R[request: system, tools, messages] --> L[async_filter_deployments]
  L --> K1[prefix_positions on system+messages, tools]
  S[success event kwargs: system, tools, slo messages] --> W[async_log_success_event]
  W --> K2[prefix_positions on system+messages, tools]
  K1 -. same key .- K2
Loading

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

  • 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
  • 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

The new tests in test_prompt_caching_deployment_check.py drive the real write (async_log_success_event) and then the real read (async_filter_deployments) for six rows (chat tool mark, chat nested function.cache_control, /v1/messages string 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=None on either side, dropping the tool boundary, dropping the dedupe, dropping nested-mark detection or stripping

Taxonomy audit before push. F3 found that function.cache_control was 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_prompt builds a new list and never mutates the request. X1 checked, None and [] tools deliberately share a seed and empty or non str/list systems are ignored. G n/a, streaming success events carry the same tools / system kwargs, verified live below. C1-C7 n/a, no public field or default changes

Screenshots / Proof of Fix

Two deployments of anthropic/claude-haiku-4-5 behind one model_name, optional_pre_call_checks: ["prompt_caching"], real Anthropic calls. Each case sends the same body six times in a row with for 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, so cache_read_input_tokens is around 8000 in both arms

Cases: tools_chat is chat with cache_control only on an OpenAI-format tool. string_system_messages is /v1/messages with a string system and a breakpoint on the user block. list_system_messages is /v1/messages with the only breakpoint (ttl: 1h) on a list system block. control_messages is /v1/messages with no system and a breakpoint in messages. auto_* run with LITELLM_ENABLE_ANTHROPIC_PROMPT_CACHING=true and no client markers. stream_* add "stream": true

Before (b22a0bd, main)

  1. tools_chat: B B A A B A
  2. string_system_messages: A B B A A B
  3. list_system_messages: A A A B A A
  4. control_messages: A A A A A A
  5. auto_string_system_messages: B A B A B A
  6. auto_list_system_messages: A B A A B B
  7. auto_system_chat (system inside messages): A A A A A A
  8. stream_tools_chat: A A B B A A, time to first byte 0.42 to 0.86 s
  9. stream_list_system_messages: B A A A B A, time to first byte 0.40 to 0.45 s
  10. Logs page, same tool-marked chat request served by deployment-A and deployment-B (first two screenshots above)

After (ced2935, rebased to f897715 with no diff change)

  1. tools_chat: B B B B B B
  2. string_system_messages: A A A A A A
  3. list_system_messages: B B B B B B
  4. control_messages: A A A A A A
  5. auto_string_system_messages: A A A A A A
  6. auto_list_system_messages: A A A A A A
  7. auto_system_chat: A A A A A A
  8. stream_tools_chat: B B B B B B, time to first byte 0.45 to 0.89 s
  9. stream_list_system_messages: B B B B B B, time to first byte 0.40 to 0.55 s
  10. Logs page, every request of the same body on deployment-B (last two screenshots above)

The 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_ttl to the write path, so d34367d merges main in and keeps both: the tools and system go into the key, and the write still passes honors_one_hour_ttl. Same rig as above, Before is main at 0e7c490, After is d34367d, cache_read_input_tokens around 15000 on every call after the first

  1. tools_chat: Before B A A A A B, After A A A A A A
  2. string_system_messages: Before A B B B A B, After B B B B B B
  3. list_system_messages: Before A B B A B A, After A A A A A A
  4. control_messages: Before B B B B B B, After B B B B B B

Mutation for the nested TTL read: reverting _carrier_cache_control fails test_pin_ttl_follows_the_longest_breakpoint_ttl[1h-nested-under-function], 37 others pass

Type

🐛 Bug Fix

Caveats (if any)

Low

  • Requests carrying tools miss pins written by the old code for one TTL after deploy
  • A pre-call hook that rewrites system can still split read and write keys, same as for messages today

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/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

…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>
@devin-ai-integration

Copy link
Copy Markdown
Contributor

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

@devin-ai-integration

Copy link
Copy Markdown
Contributor

@greptileai please review head f897715, which keys prompt caching affinity on tools and the top-level system prompt

@codspeed

codspeed Bot commented Oct 14, 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

✅ 32 untouched benchmarks


Comparing litellm_prompt_caching_affinity_tools_system (00c4b37) with main (0e7c490)

Open in CodSpeed

@codecov

codecov Bot commented Oct 14, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 85.29412% with 10 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
...pre_call_checks/prompt_caching_deployment_check.py 64.28% 5 Missing ⚠️
litellm/router_utils/prompt_caching_cache.py 90.74% 5 Missing ⚠️

📢 Thoughts on this report? Let us know!

@devin-ai-integration

Copy link
Copy Markdown
Contributor

@litereview code-review

@github-actions

Copy link
Copy Markdown
Contributor

#28427 was fixed by #46084 on main, so this pull request is closed. Reopen it if something was missed.

@nuernber

Copy link
Copy Markdown
Contributor

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

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

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

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

@klu-berri

Copy link
Copy Markdown
Contributor

@litellm-stampbot

@kerry-berri

kerry-berri commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

litellm-stampbot: risk low

Approved at d34367d.

Rules (stampbot/risk_rules.yml):

  • low: no rule flagged it

Cursor Bugbot: run requested, finished in 5 min, no risk line for the head, so the judge decided.
Judge (gpt-6-luna): low, probability of high 0.09 (high at or above 0.75)

  • risk: low (probability of high 0.09)

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

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

Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.

Fix All in Cursor

❌ 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
)

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.

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.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit d34367d. Configure here.

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.

Fixed in 00c4b37. pin_ttl_seconds now reads cache_control nested under function too, with a 1h-nested-under-function test case

@kerry-berri kerry-berri added the risk:low Small, isolated, low-risk change label Oct 20, 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 d34367d

@klu-berri
klu-berri merged commit d56ff28 into main Oct 20, 2026
87 of 88 checks passed
@klu-berri
klu-berri deleted the litellm_prompt_caching_affinity_tools_system branch October 20, 2026 02:59
@mateo-berri

Copy link
Copy Markdown
Contributor

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)

mateo-berri added a commit that referenced this pull request Oct 20, 2026
…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
yuneng-berri added a commit that referenced this pull request Oct 20, 2026
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
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.

[Bug]: Prompt caching router affinity TTL is hardcoded to 5 minutes — breaks 1-hour ephemeral cache routing

6 participants