Report prompt-cache health per conversation via `pydantic_ai.cache.*` span attributes and collapse events

Merged
DO
2mo ago
+2216-457

This pull request was posted by Codex Desktop using gpt-6-luna on behalf of David.

Depends on #9746, which closes #9745. After it merges, preserve its guard for message and compaction iterations when moving WarnOnCacheBusts onto _cache_health.py; when the provider reports one call to the main model and no compaction, normal cache accounting applies; a healthy cache read confirms recovery. A clean merge alone does not verify the replacement detector. Before #6534 lands, cover warnings and instrumentation for aggregated native-tool usage including compaction, separately reported tool-use prompt input, the compaction regression in #9746, and the continuation-aggregation case.

  • Part of #6528 (slice B — default-on cache health in instrumentation)
  • Builds on #6337 (ModelProfile.default_cache_retention, Model.resolve_cache_retention()), now merged.

Instrumented agent runs now report prompt-cache health with zero configuration, and harness's WarnOnCacheBusts is rebuilt on the same detector, so the span attributes and the warning always agree on what counts as a cache miss and why it happened.

[!WARNING]
Compatibility impact (Pydantic AI Harness): WarnOnCacheBusts no longer warns on every collapse. It now warns only when the provider's cache retention window doesn't explain it (reason='unexpected' or 'unknown'): collapses after the retention window elapsed (ttl_expired), after provider-native compaction (compacted), and on responses that report no cache usage at all (unreported, which includes caching being switched off mid-run) are silent. A collapse is now a read-back more than 5% and at least 2,000 tokens short of the established prefix, rather than below half of it, so smaller partial misses that used to be silent now warn.

Why this can ship in a minor release: Pydantic AI Harness is on 0.x versioning, where behavior may change between minor releases with deprecation warnings where practical; every removed constructor argument still works and warns.

Migration: replace collapse_ratio=x with min_missed_ratio=1 - x and min_prefix_tokens=n with min_missed_tokens=n (both still honored, with a HarnessDeprecationWarning), and remove cache_ttl_seconds (ignored, with a warning): the retention window now comes from the model's settings, its profile's default_cache_retention, and CachePoint TTLs. To silence a warning you expect, use the stdlib warnings filters as before; CacheBustWarning.reason says how the collapse was classified.

Span attributes

Every chat <model> span gets, when caching is in play:

  • pydantic_ai.cache.hit_ratio: cache_read_tokens / input_tokens, where input tokens include cache reads and writes.
  • pydantic_ai.cache.established_tokens: the conversation's established cacheable prefix for the response's (provider_name, provider_url, model_name), taken from the response so FallbackModel failover and model switches never read as misses, and switching back is judged against that model's own mark.

When a request reads back more than 5% and at least 2,000 tokens less than the established prefix (the rule Claude Code uses for a prompt-cache miss; history is append-only, so any real shortfall means the prefix moved or the cache expired, including a partial move deep in the history):

  • pydantic_ai.cache.collapsed, pydantic_ai.cache.missed_tokens (mirroring Anthropic's cache_missed_input_tokens and OpenAI's cache_missed_tokens)
  • pydantic_ai.cache.collapse_reason, classified rather than just flagged:
    • unexpected: the retention window should still have been active. Only this emits a pydantic_ai.cache.collapse span event, once per sustained collapse, until a healthy read-back re-stabilizes the cache.
    • ttl_expired: the idle gap since the same model's previous request exceeded the retention in effect: what the request's settings ask for (Model.resolve_cache_retention()), else the provider's default_cache_retention, extended by CachePoint TTLs.
    • compacted: a CompactionPart appeared in the request's history or its response since the mark (Anthropic's and OpenAI's server-side compaction, OpenAI's stateless compaction), which shrinks the prefix by design.
    • unknown: no retention window is known, so the collapse can't be attributed.
    • unreported: the response reported no cache usage at all (see below).

collapse_reason is Pydantic AI's own classification and may gain values. Provider-reported miss causes (Anthropic's cache_miss_reason, OpenAI's diagnostics) belong in a separate attribute in a follow-up, e.g. pydantic_ai.cache.provider_miss_reason, so the two never clash.

Agent-run spans get no cache attributes: a ratio aggregated across requests to different models isn't interpretable (the OTel GenAI conventions dropped cache attributes from invoke_agent spans for this reason, semantic-conventions-genai#469), and backends can compute one from the gen_ai.aggregated_usage.* counts already there.

Zero-usage responses are reported, never attributed

A response with cache_read_tokens == 0 and cache_write_tokens == 0 is ambiguous: on providers that report cache writes (Anthropic, Bedrock) the cache wasn't engaged for that request, while on providers that only report reads (OpenAI's implicit caching) it is a full miss. So a 0/0 response after an established prefix is recorded as a collapse with collapse_reason='unreported' and its missed_tokens, but never alerts, and the mark and its idle clock are left untouched. Before anything is cached, such responses are ignored.

One detector, two outputs

pydantic_ai/_cache_health.py (private) holds the state machine, the miss rule, the keying, the retention source (_expected_cache_retention, consumed as-is), the classification, and the alert latch. Instrumentation and harness's WarnOnCacheBusts are outputs over it: span attributes and an event versus a CacheBustWarning. Harness is pinned to the exact pydantic-ai-slim release it's built with, so a private shared module is safe.

  • Marks per conversation, not per run. The first request of a run that continues a conversation re-sends the prefix the previous run cached, which is where a moved prefix most often shows (#7900). Marks are keyed by RunContext.conversation_id, which a serialized-and-reloaded history carries along.
  • Each output owns its marks. Instrumentation keeps them in a process-wide store, because the Instrumentation injected by Agent(instrument=...) / Agent.instrument_all() is rebuilt every run. WarnOnCacheBusts keeps them on its instance, as before. Sharing one set would be wrong when both are on one agent: whichever observed a response first would re-baseline the mark past the collapse, and the other would miss it. Both classify identically, so a collapse is reported through both.
  • Bounded memory. Stores are least-recently-updated ordered and drop conversations idle for more than 24h (the longest documented retention) or beyond 4,096. Marks outliving the provider cache are harmless: the continuation's collapse is classified ttl_expired.
  • Re-baseline and latch. After a collapse the mark drops to what that request established, so an intentional bust is judged once. The alert (event or warning) fires once per collapse episode and re-arms on a healthy read-back, so a prefix that moves on every request alerts once. Only an alerted collapse latches: an unexpected collapse after a ttl_expired one still alerts.
  • Marks update even when the span isn't recording (sampling).

WarnOnCacheBusts (harness)

  • Classifies like instrumentation and warns on unexpected and unknown collapses. Instrumentation's event is unexpected-only because it is for production alerting; the warning also covers unknown so it keeps catching moved prefixes on providers that publish no retention window (Google, DeepSeek) and under FallbackModel, which would otherwise make it a silent no-op there.
  • CacheBustWarning carries reason, established_tokens, cache_read_tokens and missed_tokens.
  • Keys by provider_url too, and keeps keyword-only min_missed_ratio=0.05 / min_missed_tokens=2000 knobs. collapse_ratio, min_prefix_tokens and cache_ttl_seconds keep their positions, so positional calls keep their meaning.

FallbackModel

Under a FallbackModel, request_context.model is the wrapper and its .profile raises NotImplementedError by design, and the serving model isn't reachable from a capability (the response only carries its names). Collapses under a fallback are classified unknown rather than failing the run. Keying is unaffected.

Tests

Core (tests/test_instrumentation_cache_health.py): the miss thresholds (both floors, and a 10% partial move that the old half rule missed), every classification including compacted from the response and from the history, the event latch and re-arm, unreported reporting without alerting and without refreshing the idle clock, sampled-out spans, FallbackModel, no cache attributes on the run span, and the cross-run cases (continuation, JSON round trip, injected instrumentation, new conversation, retention resolver matrix, eviction and LRU order, marks restored after mid-run eviction).

Harness (tests/harness/warn_on_cache_busts/): classification per reason (warns on unexpected and unknown, silent on ttl_expired, compacted and unreported), retention from settings and per-key timing, the latch within and across runs, per-conversation continuation across message_history, the three deprecations (warn once at construction, not again from for_run, and still honored where documented), and, with instrumentation on the same agent, identical classification for the same sequences and neither output missing a collapse.

šŸ¤– Generated with Claude Code