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-12

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 with load, load_entries, save, branch, fork, list_conversations and delete, built on five primitives a backend implements: read_record, read_records, write_record, delete_record and read_entry. A backend that can read a whole history in one query overrides read_history.
    • The stored conversation only grows. save appends the messages from the conversation's new_message_index on (see below), so a run whose history a capability trimmed or rewrote, like ProcessHistory(lambda m: m[-2:]), still appends just what it added. Without a known index, save compares 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_history takes the same limit.
    • save returns the ConversationEntrys it stored, and load_entries loads a history as entries, so an app can tie a rating or billing row to a message's entry id.
    • 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 in ConversationRecord.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=), save and delete take the owner's scope. A conversation saved with another scope is treated as one the store doesn't have, so a guessed conversation_id can't reach it.
    • list_conversations(scope=..., limit=...) lists the most recently saved first. read_records takes both arguments, so a backend can order and limit in its query.
  • ConversationEntry: one message, with a minted id, the parent_id of the entry before it, and a kind, so other kinds of entries can join the log later without a migration.
  • ConversationRecord: what the store keeps for a conversation besides its log: the head_id its history ends at, the usage and deferred_tool_requests the messages can't carry, a scope saying 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), the branches it left, a revision, updated_at and a format_version.
  • InMemoryConversationStore: the reference store, for tests and examples. It keeps its own copies, as a serializing store would.
  • Conversation.revision: a new field. load sets it, a run carries it from the conversation it was given to its result, and save checks it and advances it.
    • A save from a stale copy, or a new Conversation under an ID that's already stored, raises ConversationConflict instead of overwriting. ConversationConflict subclasses UserError.
    • 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 AgentRunResult serialization gains a conversation_revision key.
  • Conversation.new_message_index: a new field, saying where the messages the store doesn't have yet start.
    • load sets it to the end of what it loaded, and save advances it.
    • A run sets it on result.conversation to 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's None, and save compares instead of guessing.
    • It's excluded from ==. AgentRunResult serialization 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), save compares 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 with conversation_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, like write_record, so a scoped delete can't remove a conversation recreated under another scope in between.

Decisions

  • save(result). save takes a run's result as well as a Conversation, and updates it, so result.conversation afterwards carries the new revision and can be continued or saved again. AgentRunResult.conversation still builds a new conversation on each access, as before.
    • Caching it on the result was considered, but it would change the property for every Agent user. Saving a result only changes results that are saved.
    • A realtime session's conversation carries 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.
  • 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 of LookupError.

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_index surviving result serialization;
  • the entries save returns and load_entries loads;
  • 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.py saves 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