[cache] Add `CompactOnCacheExpiry`, which requests compaction once the prompt cache has expired
Takes over #10644 by @adtyavrdhn. Part of #11395 (step 3, the cache-expiry trigger). Stacked on #11581.
Why. Rewriting history moves the cached prompt prefix, so the next request pays a cache write for everything after the edit. Once a conversation has been idle for longer than the provider keeps the prefix, the next request pays that write anyway, so compacting then costs no extra cache spend. @adtyavrdhn built this as CompactOnCacheExpiry in #10644, with a core request event of its own. The core request API has since landed in #11454 (RunContext.request_compaction() and the compact_history hook), so his trigger is rebuilt on it, and his core parts (CompactionRequestedEvent, the request_compaction(ctx, request_context, ...) function, the strategy listeners and the OpenAICompaction listener) are dropped.
New public surface
pydantic_ai_harness.compaction.CompactOnCacheExpiry(fallback=<clear all but 5 tool results>, *, max_tokens=None, max_fraction=0.2, context_window=None, fallback_context_window=..., fallback_retention=None, tokenizer=None, id='compact_on_cache_expiry').- Also exported from the
pydantic_ai_harnessroot. compact_messagesspan attributecompaction.idle_seconds, on the fallback's span.
Behavior
- Trigger: in
prepare_model_request, for the model serving the attempt: when coreprompt_cache_outlook()is'cold'and the history is abovemax_fractionof the window (ormax_tokens), it callsctx.request_compaction(reason='cache_expiry'). Whichevercompact_historyhandler is in play serves it, likeNativeCompaction. - Fallback: when no other handler serves a
'cache_expiry'request, its owncompact_historyrunsfallback: by defaultClearToolResults(keep_pairs=5)with "Call the tool again if you need it." in place of each cleared result.Nonedisables it. It orders itselfinnermost, so it's asked last wherever it's listed. - Marker: core requires every compaction to leave a non-empty
CompactionPartwhere the compacted history starts. A strategy that writes no summary, like clearing, gets a request-sideCompactionPart("Earlier parts of this conversation were compacted to save context.") at the start of the post-compaction window, replacing one a previous fallback left. A summarizing fallback keeps its own summary. - Not requested: for a resumed (suspended) response; when a harness strategy already compacted the request on its own trigger; on unknown retention (unless
fallback_retention).
agent = Agent('anthropic:claude-sonnet-5', capabilities=[Caching(), NativeCompaction(), CompactOnCacheExpiry()])
# After a >5 min break: the next request compacts natively, reason 'cache_expiry'; without NativeCompaction, old tool results are cleared.
Verification: tests/harness/compaction/test_compact_on_cache_expiry.py (47 tests, 100% line and branch coverage of the module). It ports #10644's tests: real model classes with only the network call replaced, warm/cold one minute either side of each provider's retention, unknown retention, fallback_retention, SelectModel, resumed responses, the request's own timestamp as "now", CachePoint(ttl='1h'), once per expiry, the size floor. New: an agent handler listed after it serves the request, NativeCompaction serves it, a declining handler leaves it to the fallback, the marker and its replacement, other reasons left alone, run_stream, the span, and combining two instances (a stated fallback=None or size floor survives a default one). Also tests/harness/test_capability_combine.py, docs and skill examples, ruff, and pyright on the touched files. No cassette: whether the cache is cold depends on a wall-clock gap a replay doesn't have.
What changes for existing users: nothing; it's a new capability. CompactionReason's 'cache_expiry' docstring now also covers an expired cache.
Decisions and prior art (from #10644, adapted)
- Prior art. @adtyavrdhn checked Claude Code, Anthropic context editing, Codex, OpenCode, Gemini CLI, Goose, Cline and Aider. Only Claude Code is time-aware: its time-based microcompact clears all but the 5 newest tool results once the gap since the last assistant message passes the cache TTL. That's what the default fallback copies. The others trigger on tokens only; Aider pings to keep the cache warm.
- 20% floor (
max_fraction=0.2), the proportion Claude Code uses before summarizing an idle conversation, so a short chat on a 5-minute cache keeps its tool results over a coffee break.max_tokensreplaces it,max_fraction=Noneremoves it. - "Now" is the request's own timestamp, so the decision can be read back from the stored history. The gap starts at the last response's timestamp, which understates it by the generation time: the safe direction (documented, per DouweM's review on #10644).
- Resumed responses are never rewritten, nor is compaction requested for them: core skips compacting a resumed response, and the request would otherwise wait for the next step, when the cache is warm again.
- AG-UI histories carry no timestamps, so it never fires there (fails safe). Client-held histories resend the uncleared messages, so the fallback's edit only lasts with server-held history. Both documented.
- Durable replay: the run stamps requests with the wall clock, so a replay can find an expired cache the original run didn't. Documented as before; not re-verified against Temporal with the new API.
- Dropped:
estimate_request_tokens/exceeds(reclaimed=), since core does one compaction per attempt; thehas_on_eventchange, since nothing listens to an event any more. The existingget_compaction_reclaimstill stops it requesting after a harness strategy compacted the same request, until those strategies move ontocompact_history(step 4 of #11395). - Not covered: compacting shortly before expiry, so a summary can still read the warm cache (needs a timer between runs); #10643's
KeepCacheWarminteraction, which isn't merged.
Checklist
- Any AI generated code has been reviewed line-by-line by the human PR author, who stands by it.
- 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.
Opened by Claude (Douwe's coding agent).