Repository navigation
fix: apply configured cache_control_injection_points beside client cache_control marks - #41956
Conversation
…che_control marks Configured injection points were dropped whenever the request already carried a client-set cache_control anywhere, so an operator's rolling tail checkpoint silently never landed once a caller marked its own system prompt. Only the automatic defaults stand down now. Configured points skip a target the client already marked and stay under the provider's 4-block cap, counting the client's marks on messages, system, tools and the root cache_control first. The chat path carries the tool count as a stamp on the points because the prompt-management hook never receives tools. Fixes #40675
|
I'll fix CI failures and address comments from users with write access. I'll skip comments containing "(aside)".
|
|
| # rather than spending them on a list that is still missing some of their targets. | ||
| CARRY_UNMATCHED_MESSAGE_POINTS: Final = "_litellm_carry_unmatched_cache_control_points" | ||
|
|
||
| EXTERNAL_BREAKPOINTS_STAMP: Final = "_litellm_external_breakpoints" |
There was a problem hiding this comment.
Inline Stamp Violates Placement
This sentinel-like stamp is defined inline, violating the requirement to centralize such values in constants.py before merging
Rule Used: What: Require sentinel-like variables (e.g., _NEGATIVE_TEAM_SENTINEL) to be defined in constants.py instead of inline or in other modules. Why: Centralizing shared constants prevents duplication, inconsistencies, and makes future changes safer ... (source)
Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!
There was a problem hiding this comment.
Keeping it inline: sibling stamps CARRY_UNMATCHED_MESSAGE_POINTS and _litellm_openai_dialect already live here, and this one is private wire between the hook's two passes.
There was a problem hiding this comment.
That’s fair. Since CARRY_UNMATCHED_MESSAGE_POINTS and _litellm_openai_dialect are sibling hook-local stamps, and this value is only used for the hook’s private two-pass handoff, keeping EXTERNAL_BREAKPOINTS_STAMP in this module is consistent. I’m withdrawing the finding; no change is needed.
| def count_external_cache_breakpoints(tools: Iterable[object] | None, cache_control: object = None) -> int: | ||
| """Client breakpoints outside messages and system that the provider cap still counts. | ||
|
|
||
| A tool carries its mark at the top level (Anthropic shape) or under ``function`` | ||
| (OpenAI shape); the Anthropic chat transform forwards both. A top-level | ||
| ``cache_control`` is Anthropic's automatic caching, which places one breakpoint | ||
| of its own on top of the explicit ones. | ||
| """ | ||
| automatic_blocks: Final = 1 if cache_control is not None else 0 | ||
| tool_blocks: Final = sum(1 for tool in tools if _tool_carries_cache_breakpoint(tool)) if tools else 0 | ||
| return automatic_blocks + tool_blocks | ||
|
|
||
| @staticmethod | ||
| def _blocks_reserved_outside_messages( | ||
| remaining_points: Sequence[CacheControlInjectionPoint], external_breakpoints: int, openai_dialect: bool | ||
| ) -> int: | ||
| """Slots of the provider cap that the message census cannot see. | ||
|
|
||
| The client's breakpoints on tools and its automatic top-level ``cache_control`` | ||
| are already on the wire, and a ``tool_config`` point becomes one more cachePoint | ||
| in the Bedrock converse transform. OpenAI's cap counts only its own block markers. | ||
| """ | ||
| if openai_dialect: | ||
| return 0 | ||
| tool_config_blocks: Final = 1 if any(p.get("location") == "tool_config" for p in remaining_points) else 0 |
There was a problem hiding this comment.
This adds Anthropic-specific cap accounting outside llms/, violating the provider-code placement requirement that must be satisfied before merging
Rule Used: What: Avoid writing provider-specific code outside of the llms/ directory. Why: This practice ensures better maintainability and reduces complexity over time. Good: ```python # Handle provider-specific logic within llms/vertex_ai/transformation.py ... (source)
Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!
There was a problem hiding this comment.
Keeping it here: this hook is Anthropic-specific by name and its four-block cap accounting already lived in this module before this PR.
There was a problem hiding this comment.
You're right. This is an existing Anthropic-specific integration hook, and the four-block accounting already belongs to this module; the change extends that established responsibility rather than introducing provider logic into a general/shared layer. I withdraw the placement concern.
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
|
bugbot run |
|
bugbot run |
…e_injection_points_survive_client_marks Main's #41920 scoped the automatic breakpoints to supported Claude transports and taught the client-mark check to read the extra_body envelope. Both changes are kept: the defaults still stand down on any client mark, extra_body included. Configured injection points keep applying beside client marks, and the cap census now counts extra_body marks too, so a configured point never lands as a fifth block. test_new_transports_preserve_client_controls now expects configured points to apply beside client marks instead of standing down
…e_injection_points_survive_client_marks
|
bugbot run |
|
bugbot run |
| return max( | ||
| AnthropicCacheControlHook.count_external_cache_breakpoints(tools, cache_control), | ||
| AnthropicCacheControlHook.count_external_cache_breakpoints(tools, cache_control, request_kwargs), | ||
| ) |
There was a problem hiding this comment.
When extra_body replaces a marked direct tool with an unmarked one on a bridge route, taking the larger census still reserves the obsolete tool's slot. The configured system checkpoint is then skipped even though the provider request has capacity, reducing the intended cache coverage.
There was a problem hiding this comment.
The hook runs before the route splits: native drops extra_body, the bridge merges it. Reserving more costs one point in that shape, never a 400
There was a problem hiding this comment.
You're right — given that the hook runs before the route split, the max() is an intentional conservative reservation. The native /v1/messages path drops extra_body and needs the direct-tool census, while the bridge path merges extra_body and needs the envelope census. Reserving the larger count guarantees neither path exceeds Anthropic's cap; in the opposite shape it can only suppress one configured point, not produce a 400. I withdraw the comment.
|
bugbot run |
There was a problem hiding this comment.
✅ 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 f567fe2. Configure here.
* fix: apply configured cache_control_injection_points beside client cache_control marks (#41956) (cherry picked from commit d8267d5) * fix(token_counter): count replayed redacted_thinking blocks so prompt_caching keeps pinning (#42069) (cherry picked from commit 0e7cf51) * fix(mcp): return camelCase tool keys from /v1/mcp/tools after the SDK 2 upgrade (#42352) (cherry picked from commit 5eb4e30) * fix(rust_bridge): keep the Messages route on Python until the Rust path is ready (#42517) rc/1.103.0 has no token counter or tokenizer routes in the catalog, so only the Messages rule moves to PYTHON_ONLY (cherry picked from commit 85ed18e) * fix(proxy): stop leaking periodic tasks on every DB config reload (#42784) (cherry picked from commit fc87a06) --------- Co-authored-by: Mateo Wang <277851410+mateo-berri@users.noreply.github.com> Co-authored-by: devin-ai-integration[bot] <158243242+devin-ai-integration[bot]@users.noreply.github.com>
TLDR
Problem this solves:
cache_control_injection_pointsvanish whenever the client marks anycache_controlitselfHow it solves it:
cache_control, and the same fields sent insideextra_bodycount toward Anthropic's 4-block cap firstenable_anthropic_prompt_caching) still stand down on client marksUser Flow
Before: the operator's configured tail checkpoint is dropped the moment the client marks anything, so the conversation is billed at full price on every turn
sonnet-tail-cachedforanthropic/claude-sonnet-5withcache_control_injection_points: [{location: message, index: -1}]and restarts the gatewayPOST https://litellm-domain/v1/chat/completionsforsonnet-tail-cachedwith a 6.5k-token system message it markedcache_control: {type: ephemeral}itself, followed by a 5k-token conversation200,usage.prompt_tokens_details.cached_tokensis0andcache_creation_input_tokensis6563: only the system block was written to the cachecached_tokensis6563and the 5k-token conversation is billed uncached againPOST https://litellm-domain/v1/messagesseescache_read_input_tokens6563andinput_tokens4974on every turnAfter: the configured tail checkpoint lands beside the client's own mark, so the second turn reads the whole prefix from cache
sonnet-tail-cachedforanthropic/claude-sonnet-5withcache_control_injection_points: [{location: message, index: -1}]and restarts the gatewayPOST https://litellm-domain/v1/chat/completionsforsonnet-tail-cachedwith a 6.5k-token system message it markedcache_control: {type: ephemeral}itself, followed by a 5k-token conversation200,cache_creation_input_tokensis11535: the system block and the conversation up to the last user turn were both written to the cachecached_tokensis11535and only the new tokens are billedPOST https://litellm-domain/v1/messagesseescache_read_input_tokens11535andinput_tokens2200, because a configured point that would be the fifth block is skipped instead of tripping Anthropic's "A maximum of 4 blocks with cache_control may be provided" errorRelevant issues
Fixes #40675
Related: #38684 counts client-marked tools in the chat/completions census; this PR carries that count on both endpoints, so #38684 is superseded once this lands
Affected release
Introduced in v1.95.0 by #33886, which made configured points stand down the same way the automatic defaults do, and present in every release since
Linear ticket
Resolves LIT-7586
Pre-Submission checklist
uv run pytest tests/test_litellm/<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@greptileaito re-request a review after pushing changes)Screenshots / Proof of Fix
Both legs are a real proxy booted from that exact commit with 2 uvicorn workers, hitting Anthropic, OpenAI, and Bedrock for real. The hook keeps no state between requests, so one 2-worker process per leg is the topology on both sides. Before ran on port 20641 from the merge base 1fcef68 and After on port 37384 from the PR tip f567fe2
Config, identical on both legs:
Boot command, identical on both legs apart from the checkout and the port:
Payloads, with the long filler text elided. Each leg got its own salt inside the filler so neither leg could read the other's cache. Within a leg,
chat.jsonandmessages.jsonshare a prefix (the same goes for each chat and messages pair below), which is why the/v1/messagescases already read from cache on their first request:The Bedrock
tool_configcases were added after Bugbot's review. At the previous tip 171b33a the Bedrock/v1/chat/completionsrequest below returned400with "A maximum of 4 blocks with cache_control may be provided. Found 5.", and the PR tip f567fe2 carries the fixBefore (1fcef68)
/v1/chat/completions: client-marked system block plus the configured tail pointSend the request
Send the same request again
/v1/messages: client-marked system block plus the configured tail pointSend the request
Send the same request again
/v1/responses: client-marked user turn plus the configured tail pointSend the request
Send the same request again
/v1/chat/completions: four client marks already fill the capSend the request
Send the same request again
/v1/messages: four client marks already fill the capSend the request
Send the same request again
/v1/chat/completionsto OpenAIgpt-5.6Send the request
Send the same request again
/v1/messagesto OpenAIgpt-5.6Send the request
Send the same request again
/v1/chat/completionsto Bedrock:tool_configpoint with four client marksSend the request
Send the same request again
/v1/messagesto Bedrock:tool_configpoint with four client marksSend the request
Send the same request again
After (f567fe2)
/v1/chat/completions: client-marked system block plus the configured tail pointSend the request
Send the same request again
/v1/messages: client-marked system block plus the configured tail pointSend the request
Send the same request again
/v1/responses: client-marked user turn plus the configured tail pointSend the request
Send the same request again
/v1/chat/completions: four client marks already fill the capSend the request
Send the same request again
/v1/messages: four client marks already fill the capSend the request
Send the same request again
/v1/chat/completionsto OpenAIgpt-5.6Send the request
Send the same request again
/v1/messagesto OpenAIgpt-5.6Send the request
Send the same request again
/v1/chat/completionsto Bedrock:tool_configpoint with four client marksSend the request
Send the same request again
/v1/messagesto Bedrock:tool_configpoint with four client marksSend the request
Send the same request again
Regression check:
/v1/messageswith a direct marked tool and anextra_bodycopy that unmarks itThe request marks the system block, two user turns, and the
lookup_clausetool directly, and repeats the tool list unmarked insideextra_body. The native/v1/messagesroute keeps the direct tool and drops the envelope, so the wire already carries four client marks and a configured point would be the fifth. Each row is that request through a proxy booted from the named commit, with a recorder in front of Anthropic counting thecache_controlblocks the gateway actually sentType
🐛 Bug Fix
Caveats (if any)
Low
prompt_cache_options: {mode: implicit}on the deployment to opt out/v1/responsesalready applied configured points at the merge base/v1/messagesto OpenAI sometimes returns zero usage/v1/messages, not on chat seedingtool_configpoint has no effect on/v1/messagesto Bedrocktool_configcases pass on both legs/v1/messagesthe cap reserves the larger of the direct andextra_bodycensusesextra_bodyloses one point on a bridged deployment, never a 400extra_body_unmarks/v1/messagescase now expects the configured system point skippedintegration-extensionsandlogging_testingare red at the tip;mainfixed both after the merge base 1fcef68integration-extensions: four tests fail importingmcp.server.fastmcpunder mcp 2.2.0;maincommit 479360a (test(mcp): restore scoped execution and credential isolation regressions #42050) movedtests/integration/_support/mcp.pytoMCPServerlogging_testing:test_async_gcs_pub_sub_v1sees two extraautorouter_*metadata keys;maincommit 144cf9a (test(logging): add autorouter estimate keys to the GCS pub/sub spend-log golden #42061) added them to the goldenmain's latest six pipelines pass both jobsFinal Attestation
Note
Medium Risk
Changes prompt-caching behavior for deployments that mix client marks with gateway-configured injection points; cap logic touches Bedrock and extra_body merging, though behavior is heavily tested.
Overview
Configured
cache_control_injection_pointsare no longer dropped when the client already setcache_controlon messages, system, tools, or a rootcache_control(including the same fields viaextra_body). They are applied in config order, skip targets the client already marked, and stay within Anthropic’s four-block limit. Automatic defaults fromenable_anthropic_prompt_cachingstill stand down when any client breakpoint is present.The hook now censuses “external” breakpoints (
count_external_cache_breakpoints), reserves that budget plus Bedrocktool_configslots (_blocks_reserved_outside_messages), and drops a forwardedtool_configpoint when the cap is full (_points_with_a_slot_left). Chat seeding stamps the external count on points (_litellm_external_breakpoints) and ignores tool-search tool types that never carry marks upstream. The old_litellm_judged/ stand-down path for configured points is removed.Reviewed by Cursor Bugbot for commit 827d1c9. Bugbot is set up for automated code reviews on this repo. Configure here.