Skip to content

fix(cache): keep cache hits free of unset fields, and follow intentional behavior changes in CircleCI suites - #46359

Merged
mateo-berri merged 10 commits into
mainfrom
litellm_circleci_heal_count_tokens_decisions_cost
Oct 14, 2026
Merged

mateo-berri merged 10 commits into
mainfrom
litellm_circleci_heal_count_tokens_decisions_cost

Conversation

@mateo-berri

@mateo-berri mateo-berri commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves:

  • CircleCI integration on main is red in seven jobs
  • A cache hit adds system_fingerprint: null the provider never sent
  • Several suites still pin behavior that merged PRs changed on purpose

How it solves it:

User Flow

Before: a developer with response caching on gets a different body on a cache hit than on the original call

  1. They send POST https://litellm-domain/v1/chat/completions to an Anthropic model with caching on
  2. The first response has no system_fingerprint key, matching what the provider returned
  3. They send the same request again and get a cache hit
  4. The hit carries "system_fingerprint": null, so a client diffing or strictly parsing responses sees a new field

After: the cache hit has exactly the same keys as the original response

  1. They send the same POST https://litellm-domain/v1/chat/completions with caching on
  2. The first response has no system_fingerprint key
  3. The repeated request is a cache hit with the same key set, and an explicit null from the provider still comes back as null

Failing tests, culprits, mechanism

Red on main in pipeline 91228 (checkout 7fa52b2) and the runs before it

  1. tests/integration/observability/test_logging_only_scope_runtime.py::test_cache_hit_directional_scope_uses_measured_base_default[C1-chat-cache-output] and [C2-chat-cache-input] in integration-extensions (job 2259639)

    • Culprit 74e5dc9 (fix(proxy): keep provider refusal, logprobs and system_fingerprint in chat completions #44788) keeps a field in the response only when it was set on the model
    • The cache stored model_dump_json() with every default, so the rebuilt hit marked system_fingerprint and refusal as set
    • Fix: both cache writes in litellm/caching/caching.py and litellm/caching/caching_handler.py use exclude_unset=True, with a regression test in tests/unit/caching/test_caching_handler.py covering omitted and explicit-null fields
  2. About 20 Arize OTel v2 tests in integration-extensions (test_arize_otel_v2_openinference_chaos.py, _family.py, _modes.py) expected provider_specific_fields: {"refusal": None} on chat messages

  3. tests/integration/observability/test_apply_guardrail_endpoint.py::test_apply_guardrail_forwards_messages_to_the_guardrail expected the Akto URL without ingest_data=true

  4. tests/integration/authorization/test_team_admin_gate.py::test_only_proxy_admin_reads_or_changes_credentials[*] in integration-management (job 2259618) and integration-management-replica

  5. tests/integration/mcp/test_mcp_accounting_guardrails.py::test_a_schema_past_the_scan_depth_is_not_published_while_one_at_the_limit_is_scanned_on_the_call in integration-mcp (job 2259632)

  6. tests/integration/providers/test_decisions_openai_format_wire.py::test_each_provider_gets_its_own_path_key_and_body_and_is_billed[openai/gpt-6-luna] in integration-providers

  7. tests/integration/messages_endpoint/providers/anthropic/test_pdf_document_count_tokens_wire.py and test_pdf_document_count_tokens_chaos.py got 400 count_tokens is not supported

  8. tests/integration/spend/test_cache_and_quota.py::test_repeated_count_tokens_on_budgeted_key_does_not_reserve_budget_or_block_later_completion in integration-accounting got 404 Unknown scenario

  9. tests/integration/providers/test_cursor_responses_wire.py::test_cursor_messages_body_uses_chat_completions_wire[False-*] in integration-providers, red on main in pipeline 91231 at 30b8db3

Mutation checks: restoring the default cache dump turns the new unit test and the cache-hit integration cases red, and reverting each test-contract change turns its test red against current main

Deferred

  • integration-accounting test_shutdown_flush.py::test_daily_spend_batch_cancelled_while_waiting_for_a_pool_connection_is_written_by_the_final_flush
  • integration-providers test_cache_control_tool_call_marks_wire.py [breakpoint-dialect], two test_chat_completions_basic_openrouter cases, bedrock mantle count_tokens [int] and the pre-content retry wire test
  • integration-cost bridge cost parity dictionary changed size during iteration, seen once
  • integration-management and -replica revocation tests from test(integration): cover orgs_users_customers endpoint contracts #44725 (test_end_user_block, test_user_delete_revokes_keys, test_access_group_model_listing, test_organization_lifecycle), equally red on main in pipeline 91231 and green locally on both sides
  • integration-accounting test_team_member_spend.py::test_member_update_lowering_the_budget_below_spend_blocks_the_next_call fails in peer setup on main and here
  • test_user_updates_wedged_coordination_redis.py and test_prometheus_shared_custom_labels.py, flaky on main and at the merge base
  • e2e_ui_testing, flaky on main and owned by the deflake automation
  • One-off reds in pipeline 91232 that passed in 91230, test_messages_stream_retry_budget_sources_owned_proxy, test_team_model_tpm_limit concurrent reservation, test_cli_sso_login_ui_disabled login burst, test_background_interaction_settlement Gemini 404 and test_logging_only_scope_chaos K2, left to the deflake automation
  • osv-scan for mlflow 3.15.0 PYSEC-2026-3865 in uv.lock, no fixed release, unrelated to this diff

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

Screenshots / Proof of Fix

Setup is the same on both sides. A proxy with 2 workers, its own Postgres DB, and a shared local Redis cache (cache: true, type: redis) serves claude-qa (anthropic/claude-haiku-5-5), gpt-qa (openai/gpt-5.4-mini) and embed-qa (openai/text-embedding-3-small) against the real providers. Each case sends one request with a fresh uuid in the prompt, then repeats it for a cache hit

curl -sS -X POST "http://127.0.0.1:$PORT/v1/chat/completions" -H "Authorization: Bearer sk-qa-1234" -H "Content-Type: application/json" \
  -d '{"model":"claude-qa","messages":[{"role":"user","content":"Say hi <uuid>"}],"max_tokens":20}'

Before (14e820e)

Claude chat cache hit

  1. First call returns top-level keys choices, created, id, model, object, usage
  2. Repeated call is a hit (x-litellm-cache-key set, spend log cache_hit=true) and returns the same keys plus "system_fingerprint": null

OpenAI chat cache hit

  1. First call returns system_fingerprint as sent by OpenAI (null for this model)
  2. Hit returns the same key set and value

Streaming and embeddings cache hits

  1. Claude "stream": true hit has the same first and last chunk keys as the miss
  2. Embeddings hit has keys data, model, object, usage and a 1536 long vector, same as the miss

After (57a1ea8)

Claude chat cache hit

  1. First call returns top-level keys choices, created, id, model, object, usage
  2. Repeated call is a hit (x-litellm-cache-key set, spend log cache_hit=true) and returns exactly choices, created, id, model, object, usage

OpenAI chat cache hit

  1. First call returns system_fingerprint as sent by OpenAI (null for this model)
  2. Hit still returns "system_fingerprint": null, so an explicit provider null survives the cache

Streaming and embeddings cache hits

  1. Claude "stream": true hit has the same first and last chunk keys as the miss
  2. Embeddings hit has keys data, model, object, usage and a 1536 long vector, same as the miss

Every hit made no provider call on either side, and spend logs show cache_hit=true with 0 spend

Observations from the run

  • Claude hit adds empty choices[0].provider_specific_fields, also on before, left alone
  • Cached streams replay with a different chunk count, also on before, text matches

CircleCI pipelines on this branch

  • Pipeline 91232 at 81661df, where every claimed test passed including the Cursor wire file, and integration-security went green on rerun after one connection reset
  • Pipeline 91230 at 57a1ea8, where every claimed job's tests passed
  • Pipeline 91227 at 719e877, where the PDF, decisions and budget count_tokens fixes passed

Bugbot found no issues at 81661df and LiteReview scored it 5/5 with no correctness findings

Type

🐛 Bug Fix
✅ Test

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
  • 81661df passes /live-pr-risk

mateo-berri and others added 3 commits October 14, 2026 02:44
…pricing in CircleCI suites

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
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

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review

@litereview

litereview Bot commented Oct 14, 2026 •

Copy link
Copy Markdown

✅ code-review

5/5 · Ready for human review

Scope: full · Full PR review.

Completed · Some checks not run.

No correctness findings.

Both cache writers now use model_dump_json(exclude_unset=True). On cache hits, I confirmed that omitted optional fields stay absent, while explicit provider nulls and fields the response set after construction, such as usage, are still kept. The test-side edits match the upstream behavior changes listed in the PR description.

Checks and execution details
  • Passed · Real testing evidence (required): Not applicable: no LLM translation changes in the scoped paths. The PR touches only litellm/caching/caching.py, litellm/caching/caching_handler.py and files under tests/. Nothing changed under litellm/llms/** or litellm/litellm_core_utils/prompt_templates/**.
  • Passed · Caching unit suite (optional): uv run pytest -q tests/unit/caching -n 8 at head 81661df: 700 passed. This run includes the new test_async_cache_preserves_presence_of_provider_optional_fields[False|True].
  • Passed · exclude_unset round-trip probe (optional): I ran local scripts on head. For a litellm.completion(mock_response=...) result and a convert_to_model_response_object result with tool calls and usage details, model_dump_json(exclude_unset=True) kept usage, tool_calls, prompt_tokens_details and completion_tokens_details. Rebuilding the response from the cached JSON produced no field-value differences beyond the intended removal of unset fields.
  • Not run · Integration suites (CircleCI) (optional): I did not run the edited integration tests locally because they need the Postgres/Redis proxy harness. The PR cites CircleCI pipelines 91230 and 91232 for them.

View review · Reviewed 81661df21eeb

@mateo-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

@codecov

codecov Bot commented Oct 14, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

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

Stale Bugbot comment from a previous run.

mateo-berri and others added 6 commits October 14, 2026 08:10
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@mateo-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review

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

Stale Bugbot comment from a previous run.

@mateo-berri mateo-berri changed the title test(integration): follow count_tokens error surfacing and decisions pricing in CircleCI suites fix(cache): keep cache hits free of unset fields, and follow intentional behavior changes in CircleCI suites Oct 14, 2026
)
else:
result_json: Final = result.model_dump_json()
result_json: Final = result.model_dump_json(exclude_unset=True)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Low · Undisclosed production change to cached response serialization in a test-only PR

  1. The title is test(integration): .... The description covers only three test suites. The attached Bugbot summary says "Test-only changes; no production code paths modified."
  2. The diff also changes two production writers to model_dump_json(exclude_unset=True): LLMCachingHandler.async_set_cache and Cache._add_cache_logic.
  3. With that change, every cached ModelResponse, ResponsesAPIResponse, TranscriptionResponse and RerankResponse loses its unset fields in the stored payload. Examples are system_fingerprint, message.provider_specific_fields, transcription usage and rerank meta. Cache hits now return a different body shape than before.
  4. The new unit test and the edited observability and team-admin assertions depend on this behavior. Nothing in the PR explains why the change belongs here, how it affects callers, or what happens to cache entries written before it.

I found no functional break with a local cache: completion, streaming-from-cache and Responses round-trips still work. The fix is to split the cache change into its own PR with a fix:/feat: title and an explanation, or to document it in this PR's title and description.

Evidence

Diff: litellm/caching/caching.py:712 and litellm/caching/caching_handler.py:1183 change model_dump_json() to model_dump_json(exclude_unset=True).

Local script (uv env, local cache): fields dropped by exclude_unset: ModelResponse -> system_fingerprint, message.provider_specific_fields; TranscriptionResponse -> usage; RerankResponse -> meta; ResponsesAPIResponse -> error, instructions, tools, tool_choice, temperature, top_p, ....

Mutation: reverting caching_handler.py to model_dump_json() makes test_async_cache_preserves_presence_of_provider_optional_fields[False] fail, so the new test depends on the production change.

PR body lists only the decisions, PDF count_tokens and budget count_tokens fixes. It does not mention the caching edit or the team-admin, MCP and observability assertion edits.

Latest summary by code-review · View this review · Reviewed 57a1ea8423d1

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Title and TLDR now name the cache change, and item 1 explains it. Hits rebuild unset defaults on load, so only presence-aware dumps change shape

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Finding withdrawn

I'm withdrawing this finding because the PR now covers what it said was missing. The finding didn't claim the cache change was functionally broken. It flagged a production change hidden inside a test(...)-titled PR with no explanation. The PR has since been updated:

  1. The title is now fix(cache): keep cache hits free of unset fields, ..., so it names the production change.
  2. The TLDR says "Cache writes keep only fields the response actually set". A User Flow section covers the caller-visible effect: a cache hit no longer adds system_fingerprint: null, and a provider's explicit null still comes back as null.
  3. Item 1 under "Failing tests, culprits, mechanism" ties the change to fix(proxy): keep provider refusal, logprobs and system_fingerprint in chat completions #44788 and names both writers, caching.py and caching_handler.py. It also names the regression test.

Entries written before this change still store every field. On load they behave as they did before the PR, so no migration is needed. The code is unchanged since the finding: both writers still use exclude_unset=True.

Evidence

litellm/caching/caching.py:712: result = result.model_dump_json(exclude_unset=True)

litellm/caching/caching_handler.py:1183: result_json: Final = result.model_dump_json(exclude_unset=True)

PR title: fix(cache): keep cache hits free of unset fields, and follow intentional behavior changes in CircleCI suites

PR description, item 1: "Fix: both cache writes in litellm/caching/caching.py and litellm/caching/caching_handler.py use exclude_unset=True, with a regression test in tests/unit/caching/test_caching_handler.py covering omitted and explicit-null fields"

GitHub does not allow this App to resolve this thread. A repository maintainer must do it manually.

Reviewed 81661df21eeb · View follow-up

@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

✅ 31 untouched benchmarks


Comparing litellm_circleci_heal_count_tokens_decisions_cost (81661df) 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. ↩

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@mateo-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review

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

✅ 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 81661df. Configure here.

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review

@mateo-berri
mateo-berri enabled auto-merge (squash) October 14, 2026 12:10
@mateo-berri
mateo-berri merged commit d81a571 into main Oct 14, 2026
112 of 118 checks passed
@mateo-berri
mateo-berri deleted the litellm_circleci_heal_count_tokens_decisions_cost branch October 14, 2026 15:56
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