Repository navigation
Description
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:
- 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.
- 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.pypersists the new human message, fetcheschat_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_messagesorders bycreated_at DESCand 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.pyadds the one-hour cache breakpoint to the system block, then sendsmessagesandtool_schemasthrough 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.pycopies caller kwargs and changes only the model/header routing fields. The native gateway/v1/messagespath 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:
- Preserve the latest user message and bounded recent conversational context in chronological, role-valid order.
- Reuse stable tools/system/history prefixes without assuming user content can be shared across users.
- Make repeated agentic tool rounds pay only for newly appended tool-use/results where possible.
- Avoid a permanently sliding prefix that invalidates historical-message caching after the ten-message boundary.
- Retain bounded context growth and explicit compaction/reset behavior.
- Expose low-cardinality cache/token distributions so regressions are visible without reading user content.
Proposed direction
Treat these as separate cache layers:
- 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.
- Stable system: retain the existing one-hour system breakpoint, keeping volatile datetime/current-turn data outside it.
- 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.
- Inter-turn history: replace the always-sliding fixed-ten prefix with either:
- a bounded append-only window with deliberate periodic reset, revisiting Optimize agentic chat message history for prompt cache reuse #4692; or
- a stable compacted/summary checkpoint plus a bounded recent suffix.
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/messagesgateway parity tests continue provingcache_controland 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
- Prior closed investigation: Optimize agentic chat message history for prompt cache reuse #4692
- Anthropic prompt caching: https://platform.claude.com/docs/en/build-with-claude/prompt-caching
Activity
perf(chat): reuse Anthropic context prefixes (BasedHardware#10422)
perf(chat): reuse Anthropic context prefixes (BasedHardware#10422)