Skip to content

fix(caching): preserve usage details on streaming cache hits - #42244

Open
yyobject wants to merge 7 commits into
BerriAI:mainfrom
yyobject:codex/cache-stream-usage-details
Open

yyobject wants to merge 7 commits into
BerriAI:mainfrom
yyobject:codex/cache-stream-usage-details

Conversation

@yyobject

@yyobject yyobject commented Sep 21, 2026 •

Copy link
Copy Markdown

TLDR

Problem this solves:

  • Streaming cache hits lose token usage breakdowns
  • Reasoning counts become zero while completion totals remain unchanged

How it solves it:

  • Reconstruct complete cached usage in both streaming iterators
  • Preserve final-chunk placement and legacy usage defaults

User Flow

Before, a streaming response-cache hit loses usage details

  1. POST http://localhost:4000/v1/chat/completions with stream: true and stream_options.include_usage: true
  2. Repeat the identical request. Reasoning tokens become zero even though the completion total is unchanged

After, a streaming response-cache hit preserves usage details

  1. POST http://localhost:4000/v1/chat/completions with stream: true and stream_options.include_usage: true
  2. Repeat the identical request. The full usage object matches the first response, including reasoning tokens

Relevant issues

Related to #32068 and #32096, which concern reasoning text during cache replay. This PR fixes usage counts separately

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
  • My PR's scope is isolated to one problem
  • Automated reviews have completed on the current tip

Screenshots / Proof of Fix

Fresh runs on October 14, 2026 used a local proxy, a real reasoning-model upstream, and a fresh in-memory response cache for each revision. Credentials, private endpoints, upstream model identifiers, and response IDs are omitted

Set REPRO_UPSTREAM_MODEL, REPRO_UPSTREAM_BASE_URL, and REPRO_UPSTREAM_API_KEY locally for an OpenAI-compatible reasoning upstream. The nested cache controls request bypassing the upstream gateway's response cache. Omit them for a direct provider without those controls

cache-repro.yaml

model_list:
  - model_name: cache-test-model
    litellm_params:
      model: os.environ/REPRO_UPSTREAM_MODEL
      api_base: os.environ/REPRO_UPSTREAM_BASE_URL
      api_key: os.environ/REPRO_UPSTREAM_API_KEY
      extra_body:
        cache:
          no-cache: true
          no-store: true
litellm_settings:
  cache: true
  cache_params:
    type: local
    ttl: 600
  num_retries: 0
  request_timeout: 45
  telemetry: false

request.json

{
  "model": "cache-test-model",
  "messages": [{
    "role": "user",
    "content": "Find the smallest positive integer n such that n mod 17 = 3 and n mod 19 = 5. Verify the answer briefly."
  }],
  "temperature": 0,
  "max_tokens": 1024,
  "stream": true,
  "stream_options": {"include_usage": true}
}

Start a fresh proxy at each commit with a generated local-only key

export LITELLM_MASTER_KEY="sk-$(openssl rand -hex 32)"
LITELLM_MODE=PRODUCTION LITELLM_LOCAL_MODEL_COST_MAP=True LITELLM_LOG=ERROR \
  uv run --no-sync python -m litellm.proxy.proxy_cli --config cache-repro.yaml \
  --host 127.0.0.1 --port 4000 --num_workers 1

From another terminal with the same local key, run this command twice. Inspect the terminal usage and the presence of x-litellm-cache-key, without publishing private headers

printf 'header = "Authorization: Bearer %s"\n' "$LITELLM_MASTER_KEY" | \
  curl --silent --show-error --no-buffer --config - --max-time 50 \
    --header 'Content-Type: application/json' \
    --data-binary @request.json --dump-header response.headers \
    http://localhost:4000/v1/chat/completions | \
  sed -n 's/^data: //p' | \
  jq -Rc 'fromjson? | select(.usage != null) | .usage |
    {prompt_tokens, completion_tokens, total_tokens,
     prompt_tokens_details, completion_tokens_details}'

Before (a5d0535)

  1. Run the shared curl command. HTTP 200, [DONE] received, cache-key header absent

    {"prompt_tokens":59,"completion_tokens":281,"total_tokens":340,"prompt_tokens_details":{"cached_tokens":0},"completion_tokens_details":{"reasoning_tokens":188}}
  2. Repeat the command. HTTP 200, [DONE] received, cache-key header present, same response ID. Reasoning drops from 188 to 0

    {"prompt_tokens":59,"completion_tokens":281,"total_tokens":340,"prompt_tokens_details":null,"completion_tokens_details":{"reasoning_tokens":0,"text_tokens":281}}

After (3765999)

  1. Run the shared curl command against the restarted proxy. HTTP 200, [DONE] received, cache-key header absent

    {"prompt_tokens":59,"completion_tokens":306,"total_tokens":365,"prompt_tokens_details":{"cached_tokens":0},"completion_tokens_details":{"reasoning_tokens":231}}
  2. Repeat the command. HTTP 200, [DONE] received, cache-key header present, same response ID. The full usage object matches

    {"prompt_tokens":59,"completion_tokens":306,"total_tokens":365,"prompt_tokens_details":{"cached_tokens":0},"completion_tokens_details":{"reasoning_tokens":231}}

Validation

Synced with main at a5d05355b680506890034dc23a1cdfd2513697fd. Resolved the test-import conflict while retaining upstream tests and helper renames. Only the conversion module and its mapped regression test file differ from main

The two focused test files pass on Python 3.12, with 127 tests and no retries. Both changed executable lines have 100% diff coverage. Ruff checks pass for the production file and the test file using the repository's ruff-tests.toml configuration

The current tip uses Usage.model_validate rather than expanding an untyped dictionary into constructor arguments. This preserves the tested defaults and usage fields without adding unknown-argument diagnostics. No type-check ceilings were changed

Against the merge-base implementation, the four details-preservation cases fail as expected. The ten missing, null, empty, partial, and totals-only usage cases pass before and after the fix. The updated branch passes all fourteen cases

uv run --no-sync pytest \
  tests/unit/litellm_core_utils/llm_response_utils/test_convert_dict_to_response.py \
  tests/unit/litellm_core_utils/llm_response_utils/test_convert_to_streaming_response.py \
  --record-mode=none -q --reruns 0 \
  --cov=litellm.litellm_core_utils.llm_response_utils.convert_dict_to_response \
  --cov-report=xml:coverage.xml
uv run --no-sync diff-cover coverage.xml --compare-branch origin/main --fail-under 100

The October 14 update corrects only the author and committer identity on the two latest commits, using my GitHub-associated privacy address. Both commit trees are unchanged, and the merge commit keeps both original parents. CLA Assistant now confirms all committers have signed

A previous full local make check BASE_REF=origin/main attempt could not download build dependencies because PyPI DNS resolution timed out. It is not recorded as a full local pass. This update reran the focused tests, repository-scoped Ruff checks, diff coverage, and the live before/after replay above

The previous code-identical revision passed all four required hosted checks and Veria review. CI and automated reviews are rerunning on the current tip. Pending or unavailable results are not counted as passes

The same missing-details behavior was previously reproduced on v1.102.0. The first affected release is not established

Type

Bug Fix

Caveats

Low

  • Reasoning text replay is separate work
  • Nonzero prompt-cache counts have synthetic regression coverage
  • Live proof covers async replay, sync has regression coverage

Final Attestation

  • Regression tests check preserved fields, final-chunk placement, and legacy usage

@yyobject
yyobject requested a review from a team September 21, 2026 14:47
@codspeed

codspeed Bot commented Sep 21, 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

✅ 31 untouched benchmarks


Comparing yyobject:codex/cache-stream-usage-details (3765999) with main (1aee1a2)1

Open in CodSpeed

Footnotes

  1. No successful run was found on main (30b8db3) during the generation of this report, so 1aee1a2 was used instead as the comparison base. There might be some changes unrelated to this pull request in this report. ↩

@greptile-apps

greptile-apps Bot commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 5/5

[Medium risk] Simplifies usage object construction in streaming response conversion.

The PR appears safe to merge; no outstanding findings remain.

Summary

The PR preserves cached usage details in synchronous and asynchronous streaming replay and adds regression tests. Since the previous review, it removed a duplicate CI shard; the existing core-utils shard still runs the replay tests and uploads coverage.

Reviews (5) · Last reviewed commit: "ci(caching): reuse upstream replay test ..."

@codecov

codecov Bot commented Sep 21, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@yyobject

Copy link
Copy Markdown
Author

@greptileai Please review the latest commit, which adds an isolated coverage job for the existing streaming cache replay regression tests

@yyobject

Copy link
Copy Markdown
Author

@greptileai Please review the updated tip after merging main to include the new lint script required by the upstream workflow

@yyobject

Copy link
Copy Markdown
Author

@greptileai Please review the updated tip after syncing main. Fresh live cache-replay evidence and regression results are in the description

Comment thread .github/workflows/test-unit.yml Resolved
@yyobject

Copy link
Copy Markdown
Author

@greptileai Removed the duplicate replay shard. Standard core-utils coverage includes both files. Please review the updated tip and refreshed live evidence

@yyobject

Copy link
Copy Markdown
Author

@greptileai Please review this update after syncing main. Fresh live cache-replay evidence and regression results are in the description

@CLAassistant

CLAassistant commented Oct 13, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@yyobject

Copy link
Copy Markdown
Author

@greptileai Replaced untyped usage expansion with schema validation to satisfy the updated type gate. Regression tests and fresh live replay still pass

@yyobject

Copy link
Copy Markdown
Author

@ishaan-jaff Could you review this cache-usage fix when available? Required CI and security review pass, with fresh before/after evidence included

@yyobject
yyobject force-pushed the codex/cache-stream-usage-details branch from c7decee to 3765999 Compare October 14, 2026 11:13

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants