Record Harness `Memory` snapshots in history once per changed run, so requests stay append-only
- Closes #8996
Memory re-rendered its <memory> snapshot on every request: it removed the previous copy and placed a fresh one with the latest user prompt, for that request only. Each time memory changed, or a new prompt moved the block, a request that had already been sent was rewritten. On Anthropic that meant the prompt's user message. On the OpenAI APIs it also pushed every later message back by one position. Either way, the cached prompt prefix was lost from that point on.
The snapshot is now recorded in message history and sent unchanged with every later request:
- Before the model's first response in a run,
Memorycompares the current snapshot with the latest snapshot of its own in history, after the latest compaction boundary. It enqueues a new one (ctx.enqueue) only when they differ, or when there is none yet. The snapshot lands in the request being sent and in history, and UI adapters stream it as anEnqueuedMessagesEvent. - It doesn't add new or changed memory after tool results. This keeps the fix from #10192: user-channel text there reads as a new message from the user.
- A run that continues from tool results without a prompt, such as after a deferred tool approval, adds nothing, and neither does a
Memoryloaded mid-run withdefer_loading=True. Memory waits for the next prompt. - If an earlier hook retries the first request, the snapshot follows the retry feedback, still ahead of any response.
- The one exception: when compaction drops the run's snapshot mid tool loop, the same snapshot is enqueued again at the end of that request, the one place every compaction keeps.
- A run that continues from tool results without a prompt, such as after a deferred tool approval, adds nothing, and neither does a
- When memory is emptied, the next snapshot says
[memory is empty], so the model doesn't keep reading the old one as current. - The default guidance (operator instructions) gains one sentence: a later
<memory>block supersedes earlier ones. - Snapshots are found by
TextContent.metadata,{'origin': 'pydantic-ai-harness.memory.v1', 'scope': <scope hash>, 'id': <capability id>}, never by their text. Theoriginfollows thepydantic-ai-harness.convention from #10833, soSummarizingCompactioncan summarize snapshots as harness data rather than as user messages. The legacy string markers are still read so older snapshots are recognized, but they are no longer written. - The
memory.injectspan gainsmemory.appended.memory.injected_charsnow counts only what was appended.
[!WARNING]
Compatibility impact: Code that reads a conversation's history (all_messages(), stores, UI adapters) will now find Memory snapshots in it. Previously it never did.
- A snapshot is a user-role
TextContent with the metadata above. UI adapters stream it as an EnqueuedMessagesEvent, so a UI may show it.
- History grows by one bounded snapshot (at most
max_tokens) for each run in which memory changed.
- Memory that changes during a run, through
write_memory or an external update, now reaches the model with the next user prompt rather than on the next request. The model's own writes are already in the conversation as its tool calls.
- Earlier snapshots are kept as they were sent, including ones that very old releases saved with a plain-string marker. Before this PR those were stripped.
- A history that loses the metadata on a round trip through a UI client gets a fresh snapshot on every run. That is still append-only, but costs tokens.
- If compaction drops the snapshot a run started with,
Memory puts that same snapshot back on that request, after the latest prompt compaction kept, without reloading the store. That way an older snapshot compaction kept never reads as current. Listing compaction before Memory is still recommended.
inject_memory=False adds no snapshots and leaves earlier ones in history.
Why this can ship in a minor release: No public API changes. The model still receives the same bounded <memory> block as user-role data, on a run's first request. What changes is that it persists instead of being re-sent per request. That is the cache-stability fix #8996 asks for, and it removes one of the documented KNOWN failures in the append-only check.
Migration: Code that inspects history and wants to skip memory snapshots can filter UserPromptParts whose TextContent.metadata['origin'] == 'pydantic-ai-harness.memory.v1'. To keep memory out of history entirely, use inject_memory=False, so the model reads memory on demand with read_memory and search_memory.
Escaping
Stored memory and listed file names go through core's pydantic_ai._framing.neutralize_tags, which covers every framing tag, system and context_diff included. The <memory> escaper then runs on top. That way memory can't close its own block or forge framework voice. Switching to the public pydantic_ai.framing.wrap(), with memory registered as a framing tag, is a follow-up in #11029.
SummarizingCompaction coverage
#10833 has merged. SummarizingCompaction now summarizes Memory snapshots as <harness_data origin="pydantic-ai-harness.memory.v1"> and never keeps them as user turns. Its code comment, compaction/README.md and docs/harness/compaction.md list Memory as covered. A test in tests/harness/compaction/test_compaction.py builds a real Memory history and checks this.
Tests
tests/harness/test_history_append_only.py: theMemoryKNOWNrows and_MEMORY_OPENAI_MOVESare removed.Memorynow passes on all three providers with noALLOWEDentry.tests/harness/memory/test_memory.pyuses realAgentruns to cover:- one snapshot per run, sent unchanged on every request, including after a change during the run;
- a new snapshot appended after the next prompt, with the earlier one kept;
- nothing added when memory hasn't changed;
- the metadata shape;
- the empty-memory transition;
- resuming after an approved deferred tool with changed memory;
- JSON round trip of the history;
- compaction dropping the snapshot;
inject_memory=Falsekeeping earlier snapshots;- two
Memoryinstances; - legacy-marker snapshots being recognized and superseded.
- Tests for the removed request-only stripping and for request-list divergence are dropped, because those code paths no longer exist.
docs/harness/memory.md, the memory README.md, and the harness skill's KNOWLEDGE-AND-MEMORY.md and TESTING-AND-DEBUGGING.md describe the new placement and its caching behavior.
Engine-backed replay coverage for DBOS and Prefect is tracked in #11191.
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.
- PR title is fit for the release changelog.
š¤ Generated with Claude Code