Agent Memory Persistence Design: Append-Only Logs, Checkpoints, and Replay
This article breaks down the engineering principles behind persistent memory for AI agents. It explains why memory must be treated as an explicit engineering structure rather than an opaque context cache, and walks through a core equation: memory equals an append-only event log plus checkpoints plus replay. Key topics include a one-session-one-log-file layout, the four layers of append-only semantics, checkpoint placement at semantic boundaries, a five-step recovery flow, and edge cases around external side effects, file locking, and log retention. Readers will gain a practical blueprint for building a reliable, auditable, and resumable agent memory layer in production.
1. Why Agent Memory Must Be an Engineering Problem
When discussing the harness that runs coding agents or automation agents, the most underestimated component is the memory layer. Many people picture memory as some mysterious context cache inside the model. In reality, for an agent that can be delivered, operated, and audited, memory must be backed by explicit engineering structures: out-of-process persistent files, well-defined write semantics, and a verifiable recovery flow.
Consider a real scenario: an agent is working in a large codebase, has already modified three files, and is partway through the fourth step when the process is reclaimed by the system. After a restart, does it know which step it stopped at? Without persistent memory, three typical failures appear:
- Context break: when the user asks “where did we get to?”, the agent has no answer;
- Broken references: in a multi-turn conversation, “change that function again” loses its referent;
- No auditability: during an incident review, it is impossible to reconstruct which actions were actually executed.
Memory can therefore be summarized as an equation:
memory = append-only event ledger + append + checkpoint + replay
This article uses that equation as the main thread and expands the design principles layer by layer.
2. The Carrier of Memory: One Session, One Log File
The mainstream approach is “one file per session”: each session owns a separate directory under the session root, the directory name is derived from an escaped workspace path, the session identifier is the last-level directory, and a compressed JSONL event log lives inside.
The path design is not arbitrary; it serves three purposes at once:
- Isolation: different workspaces and sessions do not interfere with each other, which suits concurrency and parallelism;
- Addressability: the log location can be derived from the workspace path alone, with no extra index service;
- Portability: the directory travels with the workspace, so copying the workspace copies the history.
The first line of the log is the “session header”, which records metadata such as the session identifier, creation time, workspace path, and delegation depth (0 for a top-level session, incremented per level for sub-agents). Once written, the session header is immutable — identity is fixed at the first write, and only event appends are allowed afterward, never rewrites. This constraint is the foundation of the whole design: it gives history the status of a single source of truth.
3. Append: Four Layers of Semantics for an Append-Only Event Stream
Append-only is not an implementation detail but a deliberate architectural choice. It carries at least four layers of meaning.
First layer: written lines are never rewritten. Events are appended continuously with monotonically increasing sequence numbers; no existing event can be modified or deleted. Rewriting history is equivalent to forging memory and would make auditing and replay meaningless.
Second layer: an event is a semantic unit, not a byte unit. Each line is a JSON event; common types include session header, user input, model output chunks, tool call requests, tool results, and checkpoint markers. An illustrative structure:
{"seq": 7, "type": "tool_call", "name": "edit_file", "args": {"path": "src/a.ts"}}{"seq": 8, "type": "tool_result", "ok": true, "summary": "3 lines changed"}
Third layer: packing and compression save space. When many consecutive events of the same type appear (for example, model output split into dozens of chunks), the backend can pack them into a single stored line (chunk packing) and then compress the whole thing. The industry commonly uses a high-compression-ratio algorithm such as zstd, which typically yields considerable size savings on text-based event streams while keeping the decompressed output plain text that is readable line by line.
Fourth layer: the write path must distinguish “logical order” from “on-disk order”. Logically, events are strictly ordered by sequence number; physically, batch buffering and merged writes are allowed. This requires an explicit persistence policy: which events may be buffered, and which must be persisted immediately.
4. Checkpoints: Shrinking the Window of Possible Loss
An append-only log solves “never lose what has been written”, but events still sitting in the buffer can be lost. That is what checkpoints exist for: at critical moments, force the buffer to be flushed to disk and synced, forming an explicit “safe boundary”.
Critical moments typically include:
- after session creation and the first user input;
- after every tool call returns (the external world has changed and must be fixed in place);
- when a single model turn ends and before the next turn begins;
- before and after delegating to a sub-agent (the delegation depth changes);
- when the process receives an exit signal or detects an exception.
In engineering terms, the relationship between writes and checkpoints can be expressed with the following pseudocode:
def emit(evt):log.append(evt) # logical append, may enter the bufferif evt.type in CRITICAL: # critical events are persisted immediatelycheckpoint()def checkpoint():buffer.flush()os.fsync(log.fd) # persist and sync, forming a safe boundary
It is worth stressing that a checkpoint is not a “timed snapshot” but a “semantic boundary”. Its value lies in making the recovery point fall on a semantically complete position, avoiding inconsistencies such as “the tool has executed but the call record is lost”.
5. Recovery: Rebuilding the World from the Log
The goal of replay/recovery is not “reading text back” but rebuilding a runtime state that can continue working. The standard flow has five steps:
- Locate and decompress: find the log by workspace and session identifier, then decompress it into line-by-line text;
- Validate the session header: confirm the identifier, workspace, and delegation depth to prevent cross-session misuse;
- Replay in order: replay events sequentially by sequence number, rebuilding the conversation history and tool call trace;
- Handle a truncated tail: if the last line is incompletely written (a common consequence of a crash), discard that incomplete line and use the checkpoint as the safe boundary;
- Resume the turn: continue accepting new user input from the rebuilt state.
Illustrative implementation:
def recover(session_dir):lines = decompress(read(session_dir / "session.jsonl.zstd"))head, events = parse_head_and_events(lines)state = init_state(head)for e in events:if not e.is_complete(): # truncated tail, stop replaybreakstate.apply(e)return state
This shows the payoff of the append-only design: recovery needs no “reverse patching”, only forward replay, with complexity linear in the length of the history and naturally auditable.
6. Consistency and Fault Tolerance: Three Easily Overlooked Boundaries
- External side-effect consistency: a tool call may already have changed the external world. During recovery, use the tool result events in the log to decide “whether it already took effect”, avoiding duplicate execution that causes a second modification.
- Concurrency and file locks: the same session should not be written by multiple processes at the same time; different sessions can run in parallel with their own independent logs.
- Retention and cleanup: an append-only log grows without shrinking, so a strategy of “per-session archiving plus hot/cold tiering” can be used, sinking historical sessions to a low-cost medium such as object storage while keeping hot sessions locally.
7. Implementation Advice: Building a Reliable Memory Layer in the Cloud
To implement similar capabilities in production, the following practices can be followed:
- a local append-only log handles low-latency writes and fast recovery;
- archived logs are periodically synced to object storage, enabling cross-instance migration and long-term retention;
- log services plus monitoring and alerting provide observability for write failures, replay exceptions, and checkpoint delays;
- a container platform hosts the stateless compute layer, with memory decoupled from workspace volumes and archive storage for easy elastic scaling.
In related practice at Baidu AI Cloud, this pattern maps directly to a combination of “local log + object storage archiving + log service observability”, which both guarantees recovery speed and satisfies auditing and compliance requirements.
8. Summary
The essence of agent memory is turning “what happened” into an immutable stream of facts. Append-only guarantees it cannot be forged, checkpoints guarantee minimal loss at semantic boundaries, and recovery guarantees that state can be rebuilt and turns resumed. Only when the three are combined does an agent evolve from “an amnesiac one-off script” into an engineering system that can be trusted, investigated, and resumed.
