Repository navigation
fix(caching): key the response cache on extra_body by default - #53898
Merged
Merged
Conversation
Two requests whose extra_body differed (for example chat_template_kwargs.enable_thinking) shared one cache entry unless enable_caching_on_provider_specific_optional_params was set. The default key now includes extra_body minus continuation_token and return_token_ids, which keep their existing keys. Omitted, empty and non-dict extra_body, and every key under the flag, are unchanged. Fixes #53729
Contributor
Author
|
bugbot run |
Contributor
Author
|
@greptileai review |
Contributor
Contributor
Author
|
@veria-ai |
Contributor
[Medium impact] The PR appears safe to merge, with no outstanding findings.
|
… pairs MappingProxyType, UserDict and list or tuple of (key, value) pairs reach the provider like a dict on OpenAI-SDK routes, but the default cache key still ignored them, so requests with different bodies shared one entry. They now key like the equivalent dict, with the last duplicate pair winning. Truthy token fields stay in the body for these shapes because the dict-only token fragment never sees them, and falsy ones still count as absent. Malformed sequences, strings and one-shot iterators are still ignored, and every key under the opt-in flag is unchanged.
…) does
dict(["ab"]) forwards {"a": "b"}, so a list or tuple of two-character strings now
keys like the equivalent dict instead of sharing the plain key. Shorter or longer
string items are still ignored.
Contributor
Author
|
bugbot run |
Contributor
Author
|
@greptileai review |
Contributor
Author
|
@veria-ai |
… items Move the existing cast from the dict guard, which now reuses as_str_mapping, to the list/tuple guard so basedpyright sees Sequence[object]. Runtime behavior is unchanged.
Contributor
Author
|
bugbot run |
Contributor
Author
|
@greptileai review |
Contributor
Author
|
@veria-ai |
Contributor
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 6409a88. Configure here.
Contributor
Author
|
@greptileai review |
5 of 7 tasks
4 of 6 tasks
This was referenced Nov 25, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Handwritten 1-3 sentence description
Details
TLDR
Problem this solves:
How it solves it:
User Flow
Before, disabling thinking can return a cached thinking response.
After, each extra_body configuration gets its own response.
Relevant issues
Fixes #53729.
Pre-Submission checklist
Screenshots / Proof of Fix
Baseline
62ede30f997f664cd7190815b8c0fb104ef6878c, final tested tip6409a88f3a6bfba3b0c1a3eb7a13ac85d1a1e3bd. Independent Devin Ultra verification found no in-scope regression.The original issue snippet prints
WITH-THINKING Truebefore andNO-THINKING Noneafter. The original local-vLLM request shape was tested with its mock response. Live proof useshosted_vllm/qwen-pluson DashScope withenable_thinking, including accepted mapping and pair-sequence inputs.Tests, coverage, gates at
6409a88fNO-THINKING Noneon default flag and flag true-n 4test_caching.py)62ede30ftype_check_gate.py_extra_body_mapping_concrete_sequence_extra_body_pair_extra_body_from_pairs_extra_body_beyond_always_keyed_params_keyed_provider_params_in_extra_bodyCache._keyed_param_valuesAll 91 added parametrizations passed. The prior tip's isolated logging failure did not recur in the final mapped suite. No thresholds, suppressions, or budgets were raised. Repository-wide coverage is not claimed. Codecov has no report for this tip (API returns 404: No Commit matches the given query). The affected CI workflows do not upload to Codecov. The requested completed-Codecov-report readiness requirement remains unmet; the executed line/branch evidence above is independently available.
Three-turn live conversation, direct-provider controls, and token counts
Run
FLAG=0 python live_conv3.pyfrom each source checkout withDASHSCOPE_API_KEYset. This uses three turns with resent history, then replays each conversation. Continuation IDs are not applicable to this/chat/completionsflow. The response-cache hit usage is stored usage, not a new provider charge.Baseline
62ede30f997f664cd7190815b8c0fb104ef6878c:Three-turn conversation,
6409a88f, default flag, history resent (FLAG=0 python live_conv3.py, script unchanged from the one I sent). Cells are prompt / cached / completion / reasoning tokens.falsewere cache hits on the thinking reply (647 and 223 reasoning tokens).key_lookups=0on all four turn-3 calls, same as baseline, so it is billed again on replay. Unrelated to the diff, not investigated./chat/completionswith resent history has none. I did not check other DashScope endpoints.The existing third-turn cache bypass appears on both revisions and is outside this fix. Provider cached-token counts were zero, so this proves response-cache isolation rather than provider prompt-cache behavior.
Supported body shapes, live and mock results
Mapping and pairs,
6409a88f(FLAG=0|1 LIVE=1 python shapes_eb.py, which ismapping_eb.pywith five wrappers:dict,MappingProxyType,UserDict,list(d.items()),tuple(d.items()))1db29bdea8b3beb5, false3d272581e4399997, omittedf12cd7aeba771634completionandacompletion, defaultqwen-pluscompletion, defaultfalsehas 0 reasoning chars and 3 completion tokens, repeats hite3e8559f9df59232/e0f551034492eed6, tuple4168f4582cb43e59/275ef94d3319c07d, mappings same as dict)Live reasoning chars at default, true then false: dict 1644 / 0,
MappingProxyType1796 / 0,UserDict1518 / 0, list 631 / 0, tuple 541 / 0.shapes_eb.py, complete (4,449 bytes), envDASHSCOPE_API_KEYonly. Run from the repo root asFLAG=0 LIVE=1 python shapes_eb.pyandFLAG=1 LIVE=1 python shapes_eb.py. WithoutLIVE=1it runs the key and mock legs only and needs no key.Test, coverage, lint, and mutation commands
Commands (from the repo root, existing
.venv, Python 3.12.16, uv 0.13.9)All seven gates exit 0. Mutation killed 11 of 13.
The 13-mutation run tested the first implementation. It caught 11 mutations, including removing the fix, dropping falsy values, and bypassing opt-in precedence. The two survivors sorted newly keyed fields or produced identical bytes. Final mapped tests and coverage above were rerun at
6409a88.Live async, streaming, and the two-worker shared-Redis proxy were also exercised at
af1a80aec0877ebb620d4c539b7ac0b444f1cc10. They produced two response IDs and correct repeat hits. The only subsequent change types the same runtime guards. All 176 corpus keys and 31 edge-shape keys per flag are identical betweenaf1a80aand6409a88; the original scenario, all five body shapes, and the three-turn conversation were independently rerun at the final tip.Two-worker Redis proxy setup and measured outputs
Two-worker proxy proof, head. Config
proxy_config_2w.yaml, one local Redis for router state, coordination and response cache:Two-worker proxy, baseline (same config, command and curl loop as the head block, message tag
nested-2w-base):Neither commit printed the "workers flag is ignored" warning, so the two-worker check stands for both.
Two-worker proxy at
af1a80aec0877ebb620d4c539b7ac0b444f1cc10, saved output, full ids and keysRedis held exactly 2 keys under
v53729-proxy*afterwards, and the log has no "workers flag is ignored" warning.Differences from what I sent before:
proxy_config_2w.yaml: none. The file is unchanged since 19:29 UTC and matches the block I sent byte for byte.python litellm/proxy/proxy_cli.py --config proxy_config_2w.yaml --port 4531 --num_workers 2 --detailed_debug --reload --use_v2_migration_resolverwithDATABASE_URLunset andDASHSCOPE_API_KEY,V53729_MASTER_KEYset.[nested-2w-tip-55505]in place of[nested-2w-head].Nothing was rerun for this. Coverage JSON and all logs are preserved in
~/verif-53729/logs.Private verification session. Commands and measured outcomes are included here so reviewers do not need access to it.
Type
Bug Fix
Caveats
Low
Final Attestation
Note
Medium Risk
Changes default cache key material for many requests; existing entries may miss until repopulated, but this fixes incorrect cache hits across differing provider options.
Overview
By default,
extra_bodynow participates in response cache keys, so requests that differ only by provider options (for examplechat_template_kwargs.enable_thinking) no longer share one cached completion.The cache layer parses
extra_bodyfrom plain dicts, other mappings, and list/tuple key–value pairs, ignores empty or meaningless values, and still routesreturn_token_idsandcontinuation_tokenthrough the existing dedicated key fragments. Whenenable_caching_on_provider_specific_optional_paramsis on, behavior for fullextra_bodyserialization is unchanged.Coverage adds parametrized key preimage, semantic-scope, and end-to-end
acompletiontests for these shapes and edge cases.Reviewed by Cursor Bugbot for commit 6409a88. Bugbot is set up for automated code reviews on this repo. Configure here.