Add `ConversationStore`, which keeps a conversation as a log of messages stored once, and `Conversation.revision` to catch conflicting saves
Merged
DO
18d ago+1914+1914+0123456789012345678901234567890123456789-12-12-01234567890123456789
Part of #9786. Saving a Conversation today means writing every message again on every save, with nothing to stop two writers overwriting each other. This adds a store that keeps a conversation as a log in which each message is stored once, and catches conflicting saves.
conversation = await store.load(conversation_id, scope=user_id) or Conversation(conversation_id=conversation_id)
result = await agent.run(prompt, conversation=conversation)
await store.save(result, scope=user_id) # raises ConversationConflict if someone saved in between
This PR is the core API and an in-memory reference store. SQLite, Postgres and MongoDB backends follow in #10473, which builds on it.
What's here
pydantic_ai.conversation_store, not exported from pydantic_ai yet:
ConversationStore: an ABC withload,load_entries,save,branch,fork,list_conversationsanddelete, built on five primitives a backend implements:read_record,read_records,write_record,delete_recordandread_entry. A backend that can read a whole history in one query overridesread_history.- The stored conversation only grows.
saveappends the messages from the conversation'snew_message_indexon (see below), so a run whose history a capability trimmed or rewrote, likeProcessHistory(lambda m: m[-2:]), still appends just what it added. Without a known index,savecompares with the stored history and stores what differs as a branch, keeping the old one. load(conversation_id, limit=N)loads only the last N messages, for runs that need only recent turns. Saving the result still appends to the whole conversation.read_historytakes the samelimit.savereturns theConversationEntrys it stored, andload_entriesloads a history as entries, so an app can tie a rating or billing row to a message's entryid.- Branches and forks are one tree.
branch(conversation_id, at=n | from_entry=id, expected_revision=...)continues the conversation from an earlier point, to regenerate or edit what came after or to switch back to a branch it left. The history it leaves is listed inConversationRecord.branches, by its last entry.fork(conversation_id, at=n | from_entry=id)starts a new conversation from any point instead, sharing the entries rather than copying them. Forking one point several times explores alternatives side by side (#9146). - Access:
load,load_entries,branch,fork(source_scope=),saveanddeletetake the owner'sscope. A conversation saved with another scope is treated as one the store doesn't have, so a guessedconversation_idcan't reach it. list_conversations(scope=..., limit=...)lists the most recently saved first.read_recordstakes both arguments, so a backend can order and limit in its query.
- The stored conversation only grows.
ConversationEntry: one message, with a mintedid, theparent_idof the entry before it, and akind, so other kinds of entries can join the log later without a migration.ConversationRecord: what the store keeps for a conversation besides its log: thehead_idits history ends at, theusageanddeferred_tool_requeststhe messages can't carry, ascopesaying whose conversation it is, for a fork the conversation it was copied from (forked_from, named like the Harness session store's #11614 field) and the entry it was copied up to (forked_at), thebranchesit left, arevision,updated_atand aformat_version.InMemoryConversationStore: the reference store, for tests and examples. It keeps its own copies, as a serializing store would.Conversation.revision: a new field.loadsets it, a run carries it from the conversation it was given to its result, andsavechecks it and advances it.- A save from a stale copy, or a new
Conversationunder an ID that's already stored, raisesConversationConflictinstead of overwriting.ConversationConflictsubclassesUserError. - The revision is an opaque token (a uuid7), not a counter, so a conversation deleted and created again can't match a stale copy.
- Realtime sessions carry it too, and
AgentRunResultserialization gains aconversation_revisionkey.
- A save from a stale copy, or a new
Conversation.new_message_index: a new field, saying where the messages the store doesn't have yet start.loadsets it to the end of what it loaded, andsaveadvances it.- A run sets it on
result.conversationto where its new messages start. Messages appended to a loaded conversation before the run, like a user's new turn, are carried through and saved with it. If a capability rewrote those, it'sNone, andsavecompares instead of guessing. - It's excluded from
==.AgentRunResultserialization carries the unsaved messages (conversation_unsaved) only for runs that continued a stored conversation, so other results keep their shape. - When the messages before it may have changed (one replaced, or the conversation serialized),
savecompares them with the same number of most recent stored messages, reading only those, and appends on a match or branches inside the window. A run carries this withconversation_unchecked, which also survives serialization. Editing a message in place isn't detected; the docs say to replace it with an edited copy.
delete_record(conversation_id, *, expected_revision)deletes only that revision, likewrite_record, so a scopeddeletecan't remove a conversation recreated under another scope in between.
Decisions
save(result).savetakes a run's result as well as aConversation, and updates it, soresult.conversationafterwards carries the new revision and can be continued or saved again.AgentRunResult.conversationstill builds a new conversation on each access, as before.- Caching it on the result was considered, but it would change the property for every
Agentuser. Saving a result only changes results that are saved. - A realtime session's
conversationcarries the revision of the one it handed out before it, so it can be saved again as the session goes on. A conversation taken while a save is still in flight carries the old revision, as the docstring says.
- Caching it on the result was considered, but it would change the property for every
- ABC rather than
Protocol, so the prefix diffing and forking logic lives in one place. - A durable log, as in #9001 (decided with Douwe after @rscholz98's review): what a capability does to the history a run is sent never changes what's stored.
- Compaction isn't recorded yet, and Douwe decided this merges first. #11454 will expose the accepted compactions on the run result, with the boundary, and a follow-up then stores each as an entry of its own, keeping the messages it summarized. Until then, a run that compacted appends what's left of its new messages. Only a portable compaction will be folded when the history is loaded. A provider's compaction part stays in place, since it's a boundary only for that provider.
- Entry IDs are minted, because the same message can appear twice in a history. A stored request that a run then sends isn't stored again: the run fills in its
run_id, but the save appends only what the run added. - Concurrent deletes: a load or save whose history a concurrent delete or rewrite removed reloads or raises
ConversationConflict, instead ofLookupError.
Tests
tests/test_conversation_store.py covers:
- appends through a trimming
ProcessHistory, a windowed load and a user turn added before the run; - the fallback when a capability rewrote that turn, and edits before the index (including serialized windows and edits before a run) branching inside the window;
- messages added while a save awaits the store, and a scoped delete racing a recreate;
new_message_indexsurviving result serialization;- the entries
savereturns andload_entriesloads; branch(back, and back again to a branch it left; conflicts, deferred requests, bounds),fork(from_entry=), and the branch a rewriting save leaves;- scope checks on every reading and changing method, and
save(result)across serialization; - prefix appends and branching, forks, listing, deletes;
- conflicts, including a conversation deleted and recreated, and a racing store;
- the store keeping its own copies.
tests/realtime/test_session.pysaves a session's conversation at the start, after a turn and after close.
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