Measure harness `keep_tokens` and `clai2` `/compact` with provider-reported tokens, and trace every agent from `observability`

Merged
MP
2mo ago
+390-33

/compact reported Compacted 186 messages down to 187; about 0 tokens saved. #9923 stopped it from growing the history. But /compact and harness keep_tokens still measured the history with the ~4-chars-per-token heuristic, and that heuristic misses most of what the provider bills. This PR measures them with the provider-reported token counts every response already carries. It also makes the observability plugin trace every agent, so compaction is visible in Logfire.

[!WARNING]
Compatibility impact: Harness SummarizingCompaction and SlidingWindowCompaction with keep_tokens keep fewer messages on histories with provider usage. The same budget is now measured in the provider's tokens instead of the heuristic's.

Why this can ship in a minor release: pydantic-ai-harness is 0.x. Its version policy permits behavior changes between minor releases. No public signature changes. estimate_message_tokens is a new export.

Migration: Re-check keep_tokens. To keep roughly the history you kept before on a thinking-heavy history, raise it. Histories without provider usage (and keep_messages) are measured exactly as before.

Root cause

I loaded the affected session (73a74e3c, Claude Opus 5.5, 187 messages):

MeasureTokens
4-chars heuristic of all messages (what keep_tokens, the cut, and the report used)54,262
Same messages from provider usage122,530
...of which response output_tokens~63,000

The gap is mostly thinking. The provider returns it as an empty ThinkingPart with a signature, but counts it in output_tokens and on every resend. So protected_tokens=50_000 (heuristic) covered nearly the whole history. The harness cut landed at message 2, and the summary plus the re-added first prompt outweighed what it replaced.

Changes

Harness (compaction/_shared.py)

  • New estimate_message_tokens(messages, tokenizer=None) -> list[int]. A response counts at least its output_tokens. Between two responses with usage, the later input_tokens minus the earlier is exactly what that response and the requests after it added, so those messages share it in proportion to their estimates. Where input usage did not grow in between (an earlier compaction), and outside the first and last such responses, the text estimate stands.
  • find_token_cutoff measures the tail with it when any response reports input or output tokens. Without usage it behaves exactly as before.

CLAI /compact keeps #9923's design: a tail of at most half the history, and nothing is kept unless the result is smaller. All of it is now in real tokens. /compact also passes the global agent tracer to compact_now, so a compact_messages span is recorded.

On the affected session, /compact now goes 187 -> 81 messages, ~122k -> ~54k tokens.

observability points Agent.instrument_all at its Logfire instance while loaded. The compaction summarizer, sub-agents, and session naming build their own Agent, so before this they were never traced. runtime/agent_instrumentation.py keeps the live claims, newest in effect: unloading hands the setting to a remaining copy, and after the last it restores whatever was set before. The claims live outside the plugin module, because /plugins reload re-imports that module and, during a turn, the old instance releases only after the new one has claimed. It leaves alone a setting someone else replaced. CLAI turns still use the explicit per-run Instrumentation. Core has no getter for instrument_all, so runtime/agent_instrumentation.py reads Agent._instrument_default in one place.

Verification

  • New harness tests cover estimate_message_tokens (spans shared, remainder, shrunk history, no usage, tokenizer) and find_token_cutoff on a thinking-heavy history the heuristic would keep whole.
  • New CLAI tests:
    • /compact counts reported tokens (exact notice).
    • /compact is traced with compact_messages plus invoke_agent summarizing_compaction.
    • Agents built elsewhere are traced while loaded, and the previous setting is restored.
    • Instrumentation moves to the remaining copy.
    • A later outside setting is kept.
    • tracer() follows instrument_all(True/False).
  • #9923's 186-message regression now asserts in real tokens. The session-root test allows the browser's background session_namer its own traces, since it runs before a root is chosen.
  • Coverage: compaction/_shared.py is 100% (lines and branches). New and changed CLAI lines are fully covered.
  • ruff format --check ., ruff check ., and pyright on src/pydantic_clai2, tests/clai2, and harness compaction pass, apart from the existing DBOS errors in test_durable_summarizing_compaction.py.
  • tests/clai2 and tests/harness pass. The only local failures also fail on main here: optional pydantic_handlebars missing, and subprocess timeouts under parallel load that pass serially.
  • Fresh tmux, uv run clai2 -m test, isolated config:
    • /compact under the tail says Nothing to compact.
    • With protected_tokens: 2000: Compacted 6 messages down to 3; about 5,994 tokens saved.
    • Then /compact again declines rather than growing the history.

Written with Claude Opus 5.5.

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. Behavior-only change, no API-check waiver needed.
  • PR title is fit for the release changelog.