Emit core `CompactionStartEvent` and `CompactionEndEvent` from Harness compaction strategies
- Part of pydantic/pydantic-ai-harness#711
Core's compaction step (#11454) emits CompactionStartEvent (cancellable, dispatched immediately) and CompactionEndEvent for OpenAICompaction, NativeCompaction and every other compact_history capability. Harness strategies compact in their own before_model_request, so they emitted nothing, and a listener that holds compaction mid-activity couldn't hold theirs. This PR makes every Harness strategy emit those same core events. It adds no event types and no public API: the PR's earlier COMPACTION_EVENT_NAMESPACE event family and its OpenAICompaction changes are dropped in favour of main's.
[!WARNING]
Compatibility impact: The compaction.strategy span attribute, the background_compaction span's compaction.strategy, and compaction.receipt.strategy now carry stable snake-case identifiers (summarizing, sliding_window, tiered, fallback, ...) instead of Python class names (SummarizingCompaction, ...). A custom strategy reports its strategy_id class attribute, or its snake-cased class name without a Compaction suffix. Dashboards or alerts that filter on the old values need updating.
Why this can ship in a minor release: These are telemetry attribute values, not Python API. The same identifier is now the handler of the CompactionEndEvent record, which core documents as "safe to persist and branch on, never a Python class name", so the span and the event agree.
Migration: Filter on the snake-case identifiers listed in the tracing table.
How it works
Agent run, before_model_request of a Harness strategy
trigger fires
+ ├─ emit core CompactionStartEvent (reason, model, messages_before), dispatched immediately
+ │ └─ a listener cancel(): skip this attempt, no span, no receipt, not counted
├─ compact history
+ └─ emit core CompactionEndEvent when the result holds a new CompactionPart
compact_messages span
- Emission lives in one place,
compact_with_spanincompaction/_shared.py, which every strategy already goes through. It publishes with the privateRunContext._publish_eventthat core's own compaction step uses, because the publicRunContext.emitonly takesCustomEvents andCapabilityEvents. This is in-family use of a core private, like the Harness' existingctx._calling_capability_id(). reasonis'threshold'for a strategy's own trigger and'model_requested'forCompactOnRequest(with the model'sfocus) andPruneToolResults.compact_nowandtake_background_compactionemit nothing: they run between runs, with no event stream and no listener that could cancel. The background work ofFallbackCompaction(background_start=...)also emits nothing; the run that swaps its summary in emits the pair.- Scope for composites:
TieredCompactionandFallbackCompactionemit one start/end pair for the whole compaction. Their tiers and candidates run throughcompact, not throughcompact_with_span, so they emit nothing of their own, and cancelling the start event skips every tier. Under durable execution, the tiers ofCompactOnRequest(TieredCompaction(...))run inside thecompactactivity and emit nothing there; the workflow emits the outer pair. - Cancelled attempts don't count: a cancelled attempt doesn't compact, records no
compact_messagesspan and no receipt, doesn't count againstCompactOnRequest(max_per_run=...), and leaves a strategy's own trigger to fire again on a later request. A cancelledCompactOnRequestrequest is dropped, as core drops one, and the model can callcompact_contextagain. A cancelledPruneToolResultsprune answers the modelNot pruned:with the listener's reason.
Departure from CompactionStartEvent's docstring (temporary)
CompactionEndEvent.record is a required CompactionRecord, which is located by a CompactionPart. So the end event follows only when the compacted history holds a new CompactionPart (a summary from SummarizingCompaction, a summarizing RelevanceCompaction, or a TieredCompaction / FallbackCompaction whose result holds one), with a real record: handler is the strategy id, plus the reason, model, messages_before / messages_after, kept_from and the part's position. Strategies that only drop or blank messages (SlidingWindowCompaction, ClearToolResults, DeduplicateFileReads, ClampOversizedMessages, PruneToolResults, ResetCompaction) emit a start event and no end event. CompactionStartEvent's docstring says an end event follows once the history was compacted, so this departs from it for prunes. A Harness record is also not on result.compactions, which lists the compactions of core's compact_history step. The docs say both explicitly.
This is temporary. Ruling 203 (A2) moves the Harness strategies onto core's compact_history hook, which emits these events by construction. Then the emission code in _CompactionEvents is replaced by core's, and tests/harness/compaction/test_events.py carries over as conformance tests. Emission is kept behind that one helper, so a different end-event design (an optional record, or a public publishing API) is a small change.
Durable execution
This touches event dispatch under durable engines. The start and end events are published workflow-side, from before_model_request and the prune hook, exactly where core's compaction step publishes them. No durable engine code changes, and nothing emits inside a durable operation. A durable re-sign may still be wanted. While writing the Temporal test, I found a separate bug on main: CompactOnRequest(TieredCompaction(tiers=[SummarizingCompaction(...)])) fails under Temporal, because SummarizingCompaction.compact reads ctx.capabilities, which the activity's TemporalRunContext doesn't carry. It's out of scope here, so the test uses a model-free summary tier.
Verification
- Harness strategy event tests: these run through
Agent.runwith@on_event,hooks.on.eventand@agent.on_eventlisteners. They cover the start and end events and their record, cancelling for a prune and a summary, one pair per composite, cancelling a composite (no tier runs), a cancelledCompactOnRequestrequest not counting againstmax_per_run, cancelledClearToolResults/DeduplicateFileReadsprunes recording no span and running on the next request, andcompact_nowstaying silent. - Cancelled prune answer and the Temporal composed-strategy test.
- Every
tests/harness/compaction/file passes locally, one file at a time. Ruff passes, and single-file pyright passes on the changed modules and tests. The compaction record reuses core's_latest_context_tokensand_default_kept_from, so itstokens_beforeandkept_frommatch core's. Full verification runs in CI.
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.