Add `KeepCacheWarm` harness capability to refresh an idle conversation's prompt cache

AD
15d ago
+948-2

Adds KeepCacheWarm, a harness capability that keeps a conversation's prompt cache from expiring during a long tool call, and optionally between turns.

Related: #10619 (closed as covered by WarnOnCacheBusts, which detects a cache bust after it happens. This capability prevents the expiry instead).

What changes for users

from pydantic_ai import Agent
from pydantic_ai.capabilities import Caching
from pydantic_ai_harness import KeepCacheWarm

# Warm while a run's tools take longer than the cache lasts:
agent = Agent('anthropic:claude-sonnet-4-5', capabilities=[Caching(), KeepCacheWarm()])

# Also warm between turns, for up to 30 minutes:
keep_warm = KeepCacheWarm(between_runs=True)

Anthropic keeps a cached prefix for 5 minutes from the start of the last request that used it, and restarts that timer on every read (docs). Bedrock documents the same for Claude and Nova (docs). A conversation that misses the window pays a full cache write (1.25x input) on its next request. A read costs 0.1x.

After each model request, a background task replays the same request with max_tokens=1 30 seconds before the cache would expire, and discards the response. The conversation's next model request cancels the pending refresh. Refresh usage is in keep_warm.usage, not in any run's usage, and the history is unchanged.

Lessons from pi's cache warmer

This follows the pi coding agent's warmer (earendil-works/pi#9668, packages/coding-agent/src/core/cache-warmer.ts), and the issues users filed against it since:

piHere
Warming is on only where it was measured to pay off. The maintainer turned it off for Codex: "it just drives up the cost for no benefit" (#9810).Only fixed-TTL caches that each read restarts, meaning a profile with a '5m' tier: Anthropic, Claude and Nova on Bedrock, OpenRouter's Anthropic routes. OpenAI's GPT-5.6 cache lives at least 30 minutes, so a refresh buys nothing certain, and it isn't warmed.
The default mode warms only during an active run, where the next request is certain. Idle warming is opt-in because the next turn often doesn't come (pi measured 15%).The default is the same. between_runs=True opts in, and the docs give the break-even: six 0.1x refreshes cost about half of one 1.25x rewrite.
Refreshes that rewrote the cache instead of reading it cost $1-$4 each, about $500 for one user (#10956).A refresh that reads back less than 95% of what the real request cached stops warming, with a CacheWarmingStoppedWarning.
The Codex backend ignores max_tokens, so a refresh would have run a full generation (#9845).A refresh producing more than 16 output tokens stops warming, with a warning.
The 1-hour tier was never refreshed because a fixed 30-minute idle cap came first (#9868, #10180), and the cap couldn't be changed (#11127).max_idle means "keep the cache alive until then". A 1-hour cache is refreshed only when max_idle is longer than an hour, and max_idle is configurable.
Warming stopped with no log line (#10700). An object-identity "context changed" check stopped it whenever an extension rebuilt messages (#10956, #10536).Every stop that means something is wrong warns. There's no context-identity check: the next real request cancels the refresh, so nothing can go stale between them.
Extensions couldn't tell refreshes from real requests (#10350).A refresh calls the model directly, so other capabilities' model request hooks don't see it. It shows up as its own keep_cache_warm span.
A refresh that fires late (after a sleep or a blocked loop) is dropped rather than paying for a rewrite.The same rule: dropped if it can't start within half the margin. The clock starts when the real request starts, matching the provider.

Limits

  • Needs a running event loop (async apps). Between run_sync() calls nothing is refreshed.
  • Not for durable execution: inside a durable workflow or flow it raises a UserError.
  • Between runs, the model must outlive the run. One built for a single run (agent.run(..., model='...')) is closed when the run ends, so its refresh fails and warming stops with a warning.
  • A history with a native tool call still awaiting its result isn't warmed: Anthropic runs a pending MCP server call when it gets the history (see the test_in_flight_mcp_call_history_is_accepted cassette), so each replay would run it again.
  • Anthropic extended thinking with a budget_tokens rejects max_tokens=1. That case warns once and stops.
  • One per agent: it has a default id, so two on one agent merge into one (the last wins) instead of each replaying the same request.
  • State is per instance and in-process, keyed by conversation_id. await keep_warm.stop() cancels pending refreshes on shutdown. Runs of one conversation are expected one at a time.

Verification

  • tests/harness/keep_cache_warm: 25 tests through Agent(..., capabilities=[...]) with a FunctionModel publishing a 2-second retention. They cover:
    • replay fidelity: same messages, history unchanged, usage tracked;
    • warming during a long tool call, and stopping at run end by default;
    • cancellation by the next request, and per-conversation tasks;
    • each skipped model kind, including OpenAI's minimum-lifetime cache;
    • the error, partial-read, and ignored-max_tokens stops;
    • skipping a history with a pending native tool call, and rejecting durable execution;
    • the late-wake drop, start-of-request timing, max_idle, a failed real request, and the root span.
  • No timing assertions: tests wait on the task or an event under a hang guard. 100% branch coverage on the module.
  • Each new guard was mutation-checked: removing it fails its test. Stable over repeated -n 4 runs.
  • Not yet run against the live Anthropic API.

Internals

  • before_model_request cancels the conversation's warmer and records the request's start time.
  • after_model_request snapshots request_context, the same messages, settings and parameters _agent_graph.model_request passes to model.request, and starts an asyncio task the capability owns.
  • on_model_request_error drops the start time. wrap_run cancels the warmer when the run ends, unless between_runs is set.

Checklist

  • No breaking changes in accordance with the version policy.
  • Any permitted compatibility impact has a label, warning, migration, release note, and exact API-check waiver.
  • PR title is fit for the release changelog.