Skip to main content

Storage

A Storage holds one conversation between sends: every message, oldest first, and a small key-value slot that a memory uses to keep things such as a summary. Freyja ships Vec<Message>, InMemoryStorage and JsonlStorage, and the freyja-sqlx crate keeps conversations in Postgres, MySQL or SQLite. Write your own to keep them in another database, in a schema you already have, or anywhere else.

This page is the contract for an implementation. Storage covers the backends that exist and how a conversation uses one.

The trait​

pub type StorageError = Box<dyn std::error::Error + Send + Sync>;
pub type StorageFuture<'a, T> = Pin<Box<dyn Future<Output = Result<T, StorageError>> + Send + 'a>>;

pub trait Storage: Send {
fn load(&mut self) -> StorageFuture<'_, Vec<Message>>;
fn append(&mut self, messages: Vec<Message>) -> StorageFuture<'_, ()>;
fn clear(&mut self) -> StorageFuture<'_, ()>;

fn state<'a>(&'a mut self, key: &'a str) -> StorageFuture<'a, Option<Value>> {
Box::pin(async { Ok(None) })
}
fn set_state<'a>(&'a mut self, key: &'a str, value: Value) -> StorageFuture<'a, ()> {
Box::pin(async { Ok(()) })
}
}

One value is one conversation. A backend that stores many conversations takes the conversation's key when it is built, not on every call. Agent::conversation(storage) takes the value by ownership, which is why every method takes &mut self: a backend over a plain Vec needs no lock.

Freyja forwards Storage through &mut T and Box<T>, so a caller can lend a backend they keep, or choose one at run time behind Box<dyn Storage>.

A failure is any boxed standard error. Conversation::send wraps it in Error::InvalidRequest, so callers still see one error type.

load​

Returns the whole conversation, oldest first.

Order is the backend's responsibility. A tool result that comes back ahead of the call it answers loses both, because the conversation repairs the transcript before sending it and a result with no call is dropped. In a database, order by a strictly increasing sequence column. A timestamp is not enough: two rows written in the same second, or committed in a different order than their clocks read, come back in the wrong order.

A backend may return less than everything, the newest 200 rows for example, to bound what a long conversation costs to read. The cut can land anywhere, even between a tool call and its result, because the repair pass drops a half pair before the request is built. To cut cleanly on turn boundaries instead, load more and pass the result through window_by_groups or window_by_tokens. Most backends return everything and let the agent's memory decide what the model sees.

append​

Adds new messages to the end, in the order given. A send calls it once, after its run, with the user's turn followed by every assistant turn and tool result the run produced, so a backend that writes them in one transaction stores a send whole or not at all.

Message implements Serialize and Deserialize, so a backend can store each one as a JSON column or a JSON line and read it back unchanged.

clear​

Empties the conversation and everything stored with set_state.

It must succeed on a conversation that is already empty. A caller whose clear failed cannot ask what was deleted, so the only safe recourse is to clear again, and that only works if the second call succeeds. Conversation::clear tells callers a retry is safe, which is true only of backends that honour this.

state and set_state​

The state slot holds JSON values by key, for whatever a Memory keeps between sends. The built-in summary is the main user: a backend that keeps it saves a model call each time a conversation is reopened after a restart.

Both methods are optional. The defaults keep nothing, and that is always correct, because a memory that finds no state rebuilds it, and the conversation keeps a cache of its own in memory for a backend without state.

A backend that keeps state returns the latest value set for a key, and removes all of them on clear. A backend that several conversation handles share, such as one table read by many processes, should keep state. Without it, each handle caches its own summary, and a clear made through one handle is not seen by another.

Example: one store shared by many conversations​

This backend keeps every conversation in one map behind a lock, keyed by an id. Each SharedStorage is a cheap handle on one id, so two handles with the same id see the same conversation, the way two rows readers would in a database. It keeps state, so a summary survives being reopened.

use freyja::{Message, Storage, StorageFuture};
use serde_json::Value;
use std::collections::HashMap;
use std::sync::{Arc, Mutex};

#[derive(Default)]
struct Record {
messages: Vec<Message>,
state: HashMap<String, Value>,
}

#[derive(Clone, Default)]
struct Store {
records: Arc<Mutex<HashMap<String, Record>>>,
}

impl Store {
fn conversation(&self, id: impl Into<String>) -> SharedStorage {
SharedStorage { store: self.clone(), id: id.into() }
}
}

struct SharedStorage {
store: Store,
id: String,
}

impl SharedStorage {
fn with<T>(&self, f: impl FnOnce(&mut Record) -> T) -> T {
let mut records = self.store.records.lock().expect("store lock poisoned");
f(records.entry(self.id.clone()).or_default())
}
}

impl Storage for SharedStorage {
fn load(&mut self) -> StorageFuture<'_, Vec<Message>> {
let messages = self.with(|record| record.messages.clone());
Box::pin(async move { Ok(messages) })
}

fn append(&mut self, messages: Vec<Message>) -> StorageFuture<'_, ()> {
self.with(|record| record.messages.extend(messages));
Box::pin(async { Ok(()) })
}

fn clear(&mut self) -> StorageFuture<'_, ()> {
self.with(|record| *record = Record::default());
Box::pin(async { Ok(()) })
}

fn state<'a>(&'a mut self, key: &'a str) -> StorageFuture<'a, Option<Value>> {
let value = self.with(|record| record.state.get(key).cloned());
Box::pin(async move { Ok(value) })
}

fn set_state<'a>(&'a mut self, key: &'a str, value: Value) -> StorageFuture<'a, ()> {
self.with(|record| record.state.insert(key.to_string(), value));
Box::pin(async { Ok(()) })
}
}

The lock is taken and released before each future is built, so no MutexGuard is held across an await. A backend over a real database does its work inside the future instead, with a pool cloned into the struct. Storage shows one over Postgres with sqlx.

Use it like any backend:

let store = Store::default();
let agent = Agent::new(client);

let mut chat = agent.conversation(store.conversation("user-42"));
chat.send("Remember that my order number is 1182.").await?;

// Later, from anywhere holding the store.
let mut chat = agent.conversation(store.conversation("user-42"));
chat.send("What was my order number?").await?;

Sharing has a limit. &mut self stops two sends on one Conversation from overlapping, but two Conversation values over the same id can still interleave their writes. A backend built for that has to serialize it itself, with a per-id lock or a transaction.

Testing it​

freyja::testing::storage_conformance checks the rules on this page and panics on the first one broken, naming it. Pass a function that returns a new, empty backend each time it is called. A backend that shares one store gives each call its own id:

#[tokio::test]
async fn the_store_conforms() {
let store = Store::default();
let mut next = 0;
freyja::testing::storage_conformance(|| {
next += 1;
store.conversation(format!("test-{next}"))
})
.await;
}

It checks that a new backend loads empty, that load returns every appended message oldest first, that clear empties the conversation and succeeds when it is already empty, and that clear removes state. A database backend runs it against a scratch schema or a test container.

Stability​

Storage stays usable as dyn Storage. A method added to it later comes with a default, as state and set_state did, so an implementation written today keeps compiling.

See also​

  • Storage for the built-in backends, freyja-sqlx, and the repair pass
  • Memory for what reads and writes the state slot
  • Conversations for how a send loads and appends
  • Testing for the rest of freyja::testing