Add a `compact_history()` capability hook, `RunContext.request_compaction()` and first-party compaction events

Merged
DO
8d ago
+9360-191

Part of #11395 and #11494 (the hook path; see this comment for what stays open) (step 1 of the core compaction design, plus the context-overflow addition and the compaction records for conversation storage). Builds on #9348 (ModelFallback and the per-attempt prepare_model_request hook), now in main. Supersedes #7801's events, which are now core events rather than CapabilityEvents.

This PR now also contains #11581 (step 2: NativeCompaction, compact= on runs, and generic compaction profile flags), which was squash-merged into this branch (b14b92b3fc), so both steps land together. Its surface and behavior are summarized in the collapsed section below; the full description, review and decisions are on #11581.

[!WARNING]
Compatibility impact: AgentStreamEvent gains CompactionStartEvent and CompactionEndEvent. They're only emitted when something calls request_compaction() or a compact_history hook exists, so no existing run's stream changes. Code that matches the union exhaustively (assert_never) sees two new members.

Why this can ship in a minor release: the version policy allows new event members, as #11111 did for ModelSettingsDeltaEvent.

From #11581: DEFAULT_PROFILE gains the supports_compaction_on_demand, compaction_instructions and compaction_result_readable keys, and the agent-spec capability registry gains NativeCompaction. AnthropicModelProfile.anthropic_supports_on_demand_compaction is deprecated in favor of supports_compaction_on_demand, and still works with a warning.

Migration: handle or skip the two events in exhaustive matches, expect the new profile keys when comparing DEFAULT_PROFILE exactly, and rename the deprecated profile key. The API check is waived for the union change and the DEFAULT_PROFILE additions in .github/api-compatibility-waivers/ (against v2.74.0).

Why. Today each strategy decides on compaction on its own, before the serving model is known. This PR adds one core mechanism for the built-ins to build on: triggers ask for compaction, a capability hook compacts for the candidate actually serving the attempt, and core enforces the events, the invariants and the bookkeeping once.

New public surface

  • AbstractCapability.compact_history(ctx, request) -> CompactionResult | None, asked in capability order through combined and wrapper capabilities; the first result wins.
  • RunContext.request_compaction(*, reason='manual', focus=None). A call while a request is pending merges into it: the more important reason wins (manual > model_requested > context_overflow > model_switch > threshold > cache_expiry > a custom reason; the earlier on a tie), and every focus is kept, joined with a blank line, so an automatic request can't drop a /compact focus.
  • In pydantic_ai.capabilities: CompactionRequest (reason, messages, conversation_request: CompactionModelRequest, focus), CompactionModelRequest (frozen: model, settings, parameters, the conversation's own request, built by core) and CompactionResult (messages, part, handler, usage, kept_from, metadata).
  • In pydantic_ai.messages: CompactionStartEvent (immediate dispatch, cancel()), CompactionEndEvent (record: CompactionRecord, the same object result.compactions gets, plus tokens_before, summary_tokens, usage), CompactionReason (with 'model_requested' and 'context_overflow') and CompactionRecord.
  • compactions: list[CompactionRecord] on AgentRunResult, StreamedRunResult, StreamedRunResultSync and AgentRun. CompactionRecord has part, handler, reason, model_name, provider_name, messages_before, messages_after, kept_from and metadata, plus replaced (in-memory only, not serialized) and a summarized property.

Behavior. The compaction step runs per attempt in _prepare_attempt: after the prepare_model_request chain, before the batch wrapper and token counting, and skipped when resuming a suspended response.

  • The hooks run for the candidate as durability left it. The result is checked: its part is the latest CompactionPart, it ends with the request being answered, the summary isn't empty (#7773), and the kept_from tail is unchanged. The default kept_from is the longest matching tail after the part.
  • What the handler sees and what's committed: the handler gets the run's history as this request shows it, with hooks' request-only substitutions and without their insertions or what they leave out; the history gets the compacted result with the persistent originals of what it kept; the request sent gets this request's changes back. Request-scoped prompts keep their scope.
  • Commit: the run's history is replaced only when the attempt is accepted, and then the record is added to compactions. A discarded compaction's usage counts like a rejected attempt's. A ModelAPIError from the hooks fails the attempt, so ModelFallback moves on. Token and cost limits are checked before the request is sent.
  • Context overflow: a ModelContextWindowExceededError raised before any output, with a compact_history hook present, is compacted with reason 'context_overflow' and sent to the same model once more. This happens before on_model_request_error, so the fallback chain doesn't advance. A second overflow, or no result, reaches the error hooks as today. Streamed requests are primed when a compact_history hook exists, so their overflow is retried too.
  • Batch: a pending batch result is a suspended response, so it isn't compacted. The hooks get the model before BatchModelRequests wraps it, so the compaction call is never batched. Both are locked in by a test.
  • Capability loads: a deferred capability load the compaction dropped is recorded again right after it, through #11394's helper, and kept_from is adjusted for the inserted messages.
  • Durable execution: request_compaction raises inside a durable unit, as enqueue does. The overflow retry stays within the attempt, in workflow code.

What changes for existing users: nothing at runtime unless something calls request_compaction() or defines compact_history. AgentRunResult's serialized shape only gains a compactions key when the run compacted.

From #11581: NativeCompaction, compact= on runs, generic profile flags
  • pydantic_ai.capabilities.NativeCompaction(focus_as_system_prompt=False): a compact_history handler that calls request.conversation_request.model.compact_messages() with the request's messages, settings and parameters (so it reads the prompt cache), when the serving model's profile says supports_compaction_on_demand, and returns None otherwise. It keeps the turn being answered after the provider's CompactionPart response.
  • ModelProfile.supports_compaction_on_demand, compaction_instructions ('replaces_prompt' / 'system_prompt') and compaction_result_readable, set for the OpenAI Responses API on OpenAI and Azure OpenAI and for the Claude models that compact on demand; off for OpenAIChatModel and through the Pydantic AI Gateway.
  • compact: bool | CompactionOptions = False on run(), run_sync(), run_stream(), run_stream_events() and iter() (and the wrapper and durable agents): compacts before the run's first request, with the full lifecycle and a record on result.compactions.
  • AgentRun.request_compaction() and AgentRunEvents.request_compaction(): the same request as RunContext.request_compaction(), from the run handle.
  • A focus goes to Anthropic as instructions; on OpenAI it would replace the system prompt and lose the cache, so NativeCompaction declines unless focus_as_system_prompt=True.
  • OpenAICompaction(stateless=True) now requests compaction from its trigger and serves it through the hook, so it emits the compaction events and records result.compactions. Under Temporal or DBOS with an event_stream_handler, that adds two handler activities or steps per compaction, so in-flight workflows that compact this way need worker versioning or a patch.
  • Tests: tests/test_capability_native_compaction.py, recorded OpenAI and Anthropic runs in tests/models/test_native_compaction.py, run(compact=...) as DBOS steps, and the legacy profile key.
Notes for later steps and decisions
  • #11424 is separable, so it's left for a follow-up. This PR never builds ModelCompactMessagesParams, and fixing it changes that public params shape, which needs a deprecation path. The existing durable compact_messages transport is untouched.
  • #11394's helper moved from pydantic_ai_harness.compaction._capability_loads to core (pydantic_ai._capability_loads, private), and the harness strategies import it from there. Since main merged it, it's keep_loaded_state, which records both deferred capability loads and tool search discoveries again. The core step calls it once per attempt, after whichever hook compacted; the harness strategies still call it too, which is a no-op the second time.
  • Sticky fallback (#11330) isn't merged. It reads its pin in prepare_model_request, before this step, and stamps the accepted response, which is appended after the commit, so an in-run compaction can't reset the pin. A history that ends in a compaction (agent.compact_history(), #14827) still needs the pin, through CompactionRecord.metadata or #7449 provenance.
  • Hooks support (hooks.on.compact_history / compact_history=) is left for a follow-up, to keep this PR's surface to the hook itself.
  • Anthropic cache point after the CompactionPart is deferred to the native-compaction step. The empty-summary check relaxes for a truncation marker once #7449's kind field lands.
  • Request-only changes never become history (decision, option A with a split). CompactionView aligns the request's view with the history by object identity:
    • a hook's substitution (a copy standing in for a history message, like a described file or a redaction) is what the handler sees, but the persistent original is committed for every kept message;
    • an insertion (only this request has it, like Planning's reminder) is never shown to the handler or committed, and is re-applied to the request sent after the compaction;
    • a removal (content the request leaves out) isn't given to the handler either, and stays in history unless it sits among the summarized messages;
    • substitutes standing in for several originals are sent, and those originals committed, if any is kept.
      CompactionRecord.replaced is the persistent history. The same leak in the existing OpenAICompaction is filed as #11637.
  • The overflow retry re-prepares the attempt from its post-prepare_model_request snapshot, without re-running those hooks. ModelFallback's state and the attempt number stay as they are.
  • CompactionRequest carries model_settings and model_request_parameters: compact_messages() takes a ModelRequestContext, and a request matching the conversation's is what reads the prompt cache.

Verification: tests/test_capability_compaction.py covers:

  • hook order and first-wins;
  • accepted vs discarded attempts under ModelFallback, and compaction failure → fallback;
  • context overflow (retry succeeds, overflows twice, no handler, cancelled, chain not advanced, streamed);
  • records (fields, serialization without replaced, streamed and iterated runs, kept_from default and checks) and a stored-log reconstruction across two runs;
  • the batch guards, events and invariants.

Also covered: the durable codec round trip, the restore guard, and a DBOS workflow (test_dbos_durability_compaction_runs_model_calls_as_steps) where the overflow retry and the hook's request.model call are recorded as steps and a workflow-side listener cancels a compaction. The local pre-push review subagent wasn't run, per Douwe's instructions for this task.

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.

(Claude, Douwe's coding agent)