[cache] Draft: `Caching` retention policies with a tunable `'auto'` default and a public `CachePolicy` interface
Proposal in code, not for merge as-is. This adds named cache-retention policies to Caching, with 'auto' as the default. The policies are built on a public CachePolicy interface that users can implement themselves. Coder uses 'auto'.
Open decision. Should Caching() itself default to 'auto', which changes what existing Caching() users pay? Or should the default stay True, with only Coder getting 'auto'?
Evidence
Replay: 220k recorded requests from a maintainer's coding-agent sessions, replayed against a local cost model (no API calls).
Live:
-
TTL (
results/cache/ttl_live-2026-10-31.jsonl, Haiku 5.5 and Opus 5.5, scripted 7 and 12 min gaps): every request's reads and writes match the replay model exactly.- 5m re-wrote the prefix after both long gaps.
- 1h re-wrote it after neither.
- Sticky re-wrote it after the first gap only.
Sticky ran as a user-written capability on public API (
StickyCachinginttl_live.py). -
Eviction timing (
eviction-2026-10-31.jsonl):- Anthropic 5m: warm at 4:30, 4:55 and 5:05 (3/3 each), cold at 5:30 (3/3).
- A read at 4:00 restarts the TTL: still warm at 8:30 (3/3).
- OpenAI GPT-6 Luna: warm at 5 and 10 min (3/3).
- Gemini 3.8 Flash implicit caching: 2/3 warm at 5 and 10 min, with misses even at 5 min, so treat it as probabilistic.
- The 20–60 min OpenAI and Anthropic-1h checks are still running.
-
5m→1h upgrade (
upgrade-2026-10-31.jsonl, Haiku 5.5): re-sending a warm 5m prefix withttl: '1h'reads the 5m entry and writes nothing. The prefix is cold at 7 and 12 min (2/2 each), and the check request then writes it fresh at 1h.There's no cheap upgrade. A read only restarts the entry's own 5m timer. Opus 5.5 confirmation is pending.
Replay results:
| Policy | vs all-5m, Haiku/Sonnet (reads 0.1x) | Opus 5.5 (0.05x) | Fable 5.1 (0.025x) |
|---|---|---|---|
| Claude Code / Hermes / Goose: main 1h, sub-agents 5m | −10% | −15% | −19% |
| Sticky | −24% | −35% | −43% |
| Pacing split (needs role knowledge) | −25% | −36% | −45% |
| Blind keep-alive to 60 min (pings after the session ends counted) | −16% | −34% | −49% |
| Known-wait keep-alive: ping only while a tool result is pending, cap 20 min | −8% | −13% | — |
| Sticky + known-wait keep-alive | −24.2% | −35.4% | — |
| Mixed TTL (1h on stable head, 5m on tail) | −3.4% | — | — |
| Oracle (floor) | −31% | −44% | −55% |
Notes:
- Gap predictor: after a response that ends the turn, 44% of gaps exceed 5 min. After a tool-call response, 1.4% do. Turn-ending responses precede 68% of all idles over 5 min.
- C9 compaction timing: warm pre-expiry compaction (Claude Code's trick) beats #11792's cold compaction by 1.4–1.9 points of total cost. It wastes a warm cache on 2.6% of compactions at a 15 s margin and 11% at 60 s.
- Caveat: these are coding-agent traces from one maintainer, backed by the live confirmations above.
1. The default
Caching.retention: bool | CacheRetention | CachePolicyName | CachePolicy = 'auto' (in the draft).
Stable modes:
True,False,'5m','30m','1h': unchanged.'sticky':StickyCachePolicy(), 5m until the conversation first idles longer than 5 min, then 1h.- Later, once
parent_run_idexists:'by_role'(Claude Code's split). - Later, with a host owner:
'keep_alive'(blind) and'known_wait'.
'auto': AutoCachePolicy(). It may change between releases, and the docs say so. Today it's sticky where the profile offers both '5m' and '1h', and the provider default elsewhere.
Coder: _DefaultCaching now sends AutoCachePolicy().retention(ctx) instead of True.
Compatibility, a decision for Douwe: Caching() today means the provider default. Making 'auto' the default changes what Caching() users pay: less on any conversation that idles, about +1–2% on short fan-out sub-agents. The alternative is to keep True as the default and give only Coder 'auto'.
What would justify each tuning of 'auto':
Change to 'auto' | Justified by |
|---|---|
| Today: sticky | The replay above, plus the live TTL confirmation |
| Blind keep-alive on reads ≤0.025x (Fable 5.1, Mythos) | Replay: −49% vs −43% for sticky on Fable. Needs a live keep-alive run on Fable 5.1 and a host that can ping |
| Add known-wait pings | +0.3–0.9 points on top of sticky in the replay. Worth it only if the ping is unrecorded and costs one read (live ping-cost check pending) |
| Idle threshold other than 5 min | A threshold sweep in the replay, on Coder traces once there are some |
OpenAI prompt_cache_options.ttl ('30m'/'12h') | A replay with OpenAI multipliers, plus a live eviction check at 30 min, 12 h and beyond. The live probe so far shows Luna warm at 10 min with no TTL set |
| Anything for Gemini implicit caching | Only a live cell with confidence intervals: the probe shows misses even at 5 min |
2. The public extension point
Built-in policies implement CachePolicy.retention(ctx) -> bool | CacheRetention. Caching.get_model_settings returns a callable, which core resolves before every request with ctx.messages filled in, so a user's policy plugs in through the same retention= argument.
| Need | Reachable today? | Smallest public addition |
|---|---|---|
| Timestamps of earlier requests and responses | Yes: ModelResponse.timestamp, and ModelRequest.timestamp when sent | pydantic_ai.messages.idle_gaps(messages, now=None), in the draft |
| Idle time since the last response | Yes: idle_gaps (the trailing gap) and core's existing prompt_cache_outlook(messages, profile=, retention=, now=), which returns 'warm'/'cold'/'unknown' | For C9: prompt_cache_remaining(messages, profile=, retention=, now=) -> timedelta | None, the time left before the entry is expected to expire. Plus a confidence margin from the eviction probe: Anthropic keeps 5m entries at least 5:05 and loses them by 5:30, so firing at T−15 s is safe |
| Sub-agent or background run | No. The harness holds it in private contextvars (_CHILD, _depth, RUN_OWNER) | RunContext.parent_run_id, set when Agent.run starts inside another run (core already has a private _CURRENT_RUN_CONTEXT contextvar). Only 'by_role' needs it; sticky doesn't. Not in the draft |
| Supported retentions | Partly: Model.profile['supported_cache_retentions'], but ctx.model is AbstractModel, so the draft uses the cast idiom from ReinjectSystemPrompt | AbstractModel.supported_cache_retentions, forwarded by wrappers. Policies that just pick a tier don't need it, because models snap |
| Cost model | Partly: genai_prices.calc_price works | Upstream genai-prices: a per-TTL write price (it has one cache_write price) |
| Firing work during idle time: keep-alive pings, pre-expiry compaction | No. Nothing on main fires while no run is active: no idle, timer or background hook in core or the harness | A host-side hook, not a capability: Coder's session loop (clai2, ACP) schedules on_idle(history, remaining) at T−Δ. To compact outside a run, Agent.compact(message_history, reason=...) runs the agent's compact_history capabilities without a model turn. Model.compact_messages is the provider-native piece and exists |
A ping re-sends the last request with max_tokens=1 and isn't recorded. wrap_model_request can capture that request; max_tokens=1 passthrough is untested in our Anthropic model.
3. Docs example
from datetime import timedelta
from pydantic_ai import Agent, RunContext
from pydantic_ai.capabilities import CachePolicy, Caching
from pydantic_ai.messages import idle_gaps
class LongAfterLunch(CachePolicy):
"""Keep the cache for an hour once anyone has stepped away for more than ten minutes."""
def retention(self, ctx: RunContext) -> str:
return '1h' if any(gap > timedelta(minutes=10) for gap in idle_gaps(ctx.messages)) else '5m'
agent = Agent('anthropic:claude-opus-5-5', capabilities=[Caching(LongAfterLunch())])
Not in the draft
- Docs page changes:
capabilities/caching.md's retention list, an "auto may change" note, and this example. 'by_role'andparent_run_id.- Keep-alive and known-wait (they need the host hook).
prompt_cache_remaining.
Checklist
- No breaking changes in accordance with the version policy.
- Any permitted compatibility impact has a label, warning, migration and release note, and an exact API-check waiver if the gate reports it.
- PR title is fit for the release changelog.
🤖 Generated with Claude Code