Implement a storage adapter#
The runtime needs three operations from storage: restore what the model should see, append one immutable message, and save a compaction checkpoint. Implementing those turns any database, object store, or file format into session storage.
Reach for this page when the shipped SQL backends do not fit. For SQLite, MySQL, or PostgreSQL, Store sessions in a database already covers them.
Keep lifecycle integration in the base extension#
Do not duplicate context restoration, Raw Log events, or compaction bookkeeping inside a new database extension. Implement the SessionStorage contract and pass it to BaseSessionPersistenceExtension. The base already knows when to load, append, snapshot, and clean up request bookkeeping.
The three runtime storage operations#
Method |
Returns |
Invariants |
|---|---|---|
load |
SessionView: optional checkpoint and ordered raw tail |
A consistent view; unknown sessions are empty. |
append |
Assigned per-session sequence number |
Original messages are immutable; appends advance sequence atomically. |
snapshot |
ContextSnapshot with a new version |
Check expected_version and advancing Raw Log boundary; never rewrite raw messages. |
CRUD for session titles and paginated UI history is provided by concrete storage
implementations such as SQLSessionStorage. It is separate
from the three operations required by the runtime persistence extension.
Step 1: decide what one stored message holds#
A replay needs the original message, its sequence, and the request it belonged to. Timing, metadata, tags, and token counts are for display and analysis; store them if your UI shows them. Encode the message with the runtime codec rather than writing your own serializer, so replay blocks, tool calls, and images survive:
from zett_agent.storage import decode_messages, encode_messages
text = encode_messages([message]) # a JSON string
restored = decode_messages(text)[0] # the original message object
Step 2: implement load#
Return the latest checkpoint and every message after its boundary. An unknown session returns an empty view, not an error: the first append creates it. Read both parts from one consistent snapshot, or two requests can observe different versions.
async def load(self, session_id: str) -> SessionView:
"""Return the latest checkpoint and every message after its boundary."""
data = self._session(session_id)
snapshot = ContextSnapshot.model_validate(data["snapshot"]) if data["snapshot"] else None
boundary = snapshot.compacted_through_sequence if snapshot is not None else 0
tail = [
RawMessageRecord(
id=item["id"],
session_id=session_id,
request_id=item["request_id"],
sequence=item["sequence"],
message=decode_messages(item["message"])[0],
metadata=item["metadata"],
tags=item["tags"],
started_at=datetime.fromisoformat(item["started_at"]),
completed_at=datetime.fromisoformat(item["completed_at"]),
duration_ns=item["duration_ns"],
reasoning_started_at=None,
reasoning_completed_at=None,
reasoning_duration_ns=None,
content_started_at=None,
content_completed_at=None,
content_duration_ns=None,
input_tokens=None,
output_tokens=None,
cache_read_tokens=None,
cache_write_tokens=None,
reasoning_tokens=None,
created_at=datetime.fromisoformat(item["completed_at"]),
updated_at=datetime.fromisoformat(item["completed_at"]),
)
for item in data["messages"]
if item["sequence"] > boundary
]
return SessionView(
parent_session_id=data["parent_session_id"],
session_type=data["session_type"],
title=data["title"],
agent_name=data["agent_name"],
snapshot=snapshot,
raw_tail=tail,
)
Step 3: implement append#
Allocate the next per-session sequence and write the message in one transaction. The returned number is what a later snapshot boundary refers to. Messages are immutable: an edit is a new append, never a rewrite. Session attributes arrive on the first append; keep the parent ID immutable.
async def append(
self,
session_id: str,
request_id: str,
message: AnyMessage,
timing: MessageTiming | None = None,
parent_session_id: str | None = None,
title: str | None = None,
agent_name: str | None = None,
metadata: Mapping[str, JsonValue] | None = None,
tags: Mapping[str, JsonValue] | None = None,
usage: ModelUsage | None = None,
) -> int:
"""Append one immutable message and return its new sequence number."""
data = self._session(session_id)
if data["parent_session_id"] is None:
data["parent_session_id"] = parent_session_id
data["title"] = title
data["agent_name"] = agent_name
moment = datetime.now(timezone.utc)
started = timing.started_at if timing is not None else moment
completed = timing.completed_at if timing is not None else moment
sequence = len(data["messages"]) + 1
data["messages"].append(
{
"id": new_uuid7(),
"request_id": request_id,
"sequence": sequence,
"message": encode_messages([message]),
"metadata": dict(metadata or {}),
"tags": dict(tags or {}),
"started_at": started.isoformat(),
"completed_at": completed.isoformat(),
"duration_ns": timing.duration_ns if timing is not None else 0,
}
)
self._save()
return sequence
Step 4: implement snapshot#
A checkpoint replaces the Raw Log prefix through an inclusive sequence. Reject a
stale expected_version instead of overwriting it, reject a boundary past the end
of the log, and advance the version by one. Never delete the messages it summarizes;
a UI still displays them.
async def snapshot(
self,
session_id: str,
compacted_message: CompactedMessage,
compacted_through_sequence: int,
expected_version: int,
) -> ContextSnapshot:
"""Create one checkpoint, refusing a stale version."""
data = self._session(session_id)
current = ContextSnapshot.model_validate(data["snapshot"]).version if data["snapshot"] else 0
if expected_version != current:
raise ValueError(f"Snapshot version changed: expected {expected_version}, stored {current}")
sequences = [item["sequence"] for item in data["messages"]]
if compacted_through_sequence > (max(sequences) if sequences else 0):
raise ValueError("compacted_through_sequence is past the end of the Raw Log")
moment = datetime.now(timezone.utc)
snapshot = ContextSnapshot(
id=new_uuid7(),
session_id=session_id,
version=current + 1,
compacted_message=compacted_message,
compacted_through_sequence=compacted_through_sequence,
created_at=moment,
updated_at=moment,
)
data["snapshot"] = snapshot.model_dump(mode="json")
self._save()
return snapshot
Step 5: hand it to the base extension#
The extension stays a constructor. Every lifecycle decision stays in the base class.
class JsonPersistence(BaseSessionPersistenceExtension[JsonFileStorage]):
"""Only choose the storage; the base owns every lifecycle hook."""
def __init__(self, path: Path) -> None:
super().__init__(JsonFileStorage(path))
The complete program, including the offline model and the reopen-after-write check, is Implement session storage from scratch. One request against it produces three appends (system, user, assistant) and a second instance reads them back from the file.
Snapshot consistency checklist#
Read the checkpoint and its tail consistently; do not combine different database versions.
Treat compacted_through_sequence as an inclusive represented boundary.
Start the replay tail strictly after that boundary.
Reject stale expected_version rather than silently overwriting a checkpoint.
Do not store a checkpoint after every successful response.
Preserve message roles, attributes, replay blocks, timing, metadata, tags, and usage.
Do not treat request_id as an automatic idempotency key.
Testing a storage implementation#
Write the tests against the contract, not the database driver:
An unknown session loads as empty, and the first append creates it.
Two appends in one request keep their order, and a later load returns them in sequence.
A tool round trip stores and restores replay blocks and tool results unchanged.
A snapshot with a stale version is rejected, and the stored one is untouched.
A snapshot boundary past the end of the Log is rejected.
A compacted session loads the checkpoint plus the tail after its boundary, not the messages it summarized.
A second storage instance over the same file or database sees the same conversation.
Deleting a session removes its messages and checkpoints, and leaves other sessions alone.
Use a temporary directory or a dedicated test schema, and release every connection before the test ends.
Supporting checkpoint type#
The snapshot contract uses this class from its defining module:
from zett_agent.extensions.compaction import CompactedMessage
checkpoint = CompactedMessage(content="The user prefers Python.")
CompactedMessage is a specialized system message marking a context checkpoint.
Its content contains the summary; inherited attributes holds optional
message annotations. It is not exported from the package root. Store this
checkpoint separately from the original Raw Log, together with the inclusive
sequence boundary described above.
Related API: SessionStorage,
BaseSessionPersistenceExtension,
SessionView,
SQLSessionStorage,
SQLSessionExtension.