Skip to content

Optimize Anthropic chat caching for sliding history and agentic tool loops #10418

Closed

Description

@Git-on-my-level

Problem

Production Anthropic accounting shows that Omi chat prompt caching is functioning for the stable prefix, but a small heavy-tail population repeatedly sends very large uncached contexts. The gateway preserves Anthropic cache_control; this is a caller/context-management problem rather than a gateway passthrough failure.

Two current behaviors combine poorly:

  1. Chat loads a fixed sliding window of the latest 10 stored messages. Once the chat is full, each new user/assistant pair removes older messages from the front, so the historical-message prefix changes on every turn.
  2. Agentic chat places a one-hour cache breakpoint on the system block but no breakpoint on the pre-loop message history. Each tool-loop iteration resends the base history plus accumulated tool calls/results.

Anthropic caches cumulative prefixes in tools → system → messages order. A moving first historical message prevents inter-turn reuse of a message-level cache entry, while repeated tool rounds can re-bill an increasingly large uncached suffix.

This exact sliding-window concern was previously documented in #4692. It was closed when the expected benefit was small under the workload at that time. Current Anthropic production distribution shows a materially larger agentic-tail problem and justifies revisiting it.

Generalized production evidence

Privacy-safe aggregation over a matched post-rollout sample of 749 Anthropic attempts found:

Signal Distribution
Attempts with cache reads 526 / 749
Explicit one-hour cache misses/writes 223 / 749
Median cached input ~25.3K tokens
Median uncached input ~1.2K tokens
p75 uncached input ~2.7K tokens
p90 uncached input ~27.5K tokens
p95 uncached input ~331K tokens
Attempts above 300K uncached tokens 62
Top 10% share of uncached input ~94%
Top 10% share of estimated provider cost ~61%

The bottom 90% averaged only ~2.1K uncached tokens, so ordinary chats are not broadly broken. The problem is highly concentrated in long/agentic requests. The sample contained one first attempt per distinct invocation and no retry ordinals above one, ruling out retry amplification for this population.

No prompts, responses, raw logs, credentials, or user identifiers were used in these aggregates.

Code-grounded mechanism

  • backend/routers/chat.py persists the new human message, fetches chat_db.get_messages(..., limit=10, app_id=...), then reverses the newest-first result into chronological order before calling agentic chat.
  • backend/database/chat.py::get_messages orders by created_at DESC and applies the fixed limit. There is no token-aware budget, stable summary checkpoint, append-only growth phase, or turn-pair normalization on this path.
  • backend/utils/retrieval/agentic.py adds the one-hour cache breakpoint to the system block, then sends messages and tool_schemas through the native Anthropic tool loop.
  • Each tool round appends assistant tool-use content and tool results to the message list before sending the full list again.
  • backend/utils/llm/gateway_anthropic.py copies caller kwargs and changes only the model/header routing fields. The native gateway /v1/messages path forwards the Anthropic body without flattening or removing cache controls; existing passthrough tests cover this contract.

Important nuance: because Anthropic's hierarchy is tools → system → messages, the current system breakpoint cumulatively caches stable tools plus system content. A separate tools breakpoint is useful only to preserve the tool prefix when mutable system content changes; tools are not universally uncached today.

Desired outcome

Keep recent-chat behavior correct while preventing stable context from being reprocessed on every turn and every tool round.

The solution should:

  1. Preserve the latest user message and bounded recent conversational context in chronological, role-valid order.
  2. Reuse stable tools/system/history prefixes without assuming user content can be shared across users.
  3. Make repeated agentic tool rounds pay only for newly appended tool-use/results where possible.
  4. Avoid a permanently sliding prefix that invalidates historical-message caching after the ten-message boundary.
  5. Retain bounded context growth and explicit compaction/reset behavior.
  6. Expose low-cardinality cache/token distributions so regressions are visible without reading user content.

Proposed direction

Treat these as separate cache layers:

  1. Stable tools: evaluate an explicit breakpoint at the end of tools so mutable per-user system context does not invalidate the reusable tool-schema entry.
  2. Stable system: retain the existing one-hour system breakpoint, keeping volatile datetime/current-turn data outside it.
  3. Pre-loop history: put a breakpoint at the end of the historical messages loaded before the agentic loop. Later tool rounds should then reuse that base history and process only appended tool-use/results.
  4. Inter-turn history: replace the always-sliding fixed-ten prefix with either:

Do not implement only a trailing-message breakpoint while retaining the permanently sliding window: it would help within one tool loop and during short growing chats, but would lose inter-turn reuse once old messages start falling off the front.

Acceptance criteria

Context correctness

  • Tests prove the newest user message is always included.
  • Tests cover chats below, at, and above the current ten-message boundary.
  • Historical messages remain chronological and Anthropic-role-valid; malformed/reported-message filtering cannot silently create an invalid sequence.
  • Context remains bounded by an explicit message/token policy.
  • App/main-chat and session scoping behavior is documented and covered.

Cache behavior

  • A deterministic stateful test sends two consecutive turns with a shared prefix and proves the second request reports cache-read tokens for the stable portion.
  • A deterministic multi-round tool test proves the second provider call reuses the pre-loop history rather than reprocessing it as uncached input.
  • Tests cross the history-window reset/compaction boundary and prove cache misses occur only at the deliberate reset, not on every mature-chat turn.
  • Existing native /v1/messages gateway parity tests continue proving cache_control and TTL preservation.
  • Breakpoint count and TTL ordering comply with Anthropic's four-breakpoint and mixed-TTL rules.

Observability and validation

  • Add privacy-safe, low-cardinality histograms/counters for cached input, uncached input, cache writes, and cost estimates by provider/model/lane/outcome—never by user or request ID.
  • Compare p50/p75/p90/p95 uncached input and top-decile concentration before and after a development bake.
  • Demonstrate a substantial reduction in the extreme uncached tail without increasing error rate, latency, or context-correctness failures.
  • Confirm no user content, raw identifiers, or credential material enters metrics/log labels.

Non-goals

  • Changing gateway traffic, provider credentials, model selection, or fallback policy.
  • Treating this as a gateway cache-control passthrough bug.
  • Unboundedly increasing historical context.
  • Logging prompts, responses, tool results, or user identifiers for diagnosis.

References

Activity

  1. added
    bug
    backend
    on Jul 23, 2026
  2. added a commit that references this issue on Jul 24, 2026
    536406b
  3. added a commit that references this issue on Sep 29, 2026
    c9eb685
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    backendbughigh priorityperformance

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions