AI Agent Session Persistence: Append-Only Logs, Checkpoints, and Recovery
A production-grade AI Agent needs more than a context window to maintain memory across failures and long-running tasks. This article explains how to build session persistence with append-only JSONL event logs, crash-resistant checkpoints, and deterministic recovery through event replay. It also covers storage layout, event granularity, compression, integrity checks, tail truncation, auditing, and debugging.
Why an Agent Needs Memory
Consider a common scenario: an agent is helping modify a large codebase. It edits three files, and the process suddenly crashes. After restarting, the user asks, “Where did you get to?” Without persistence in the harness—the runtime layer that manages the agent—the agent has effectively lost its memory.
Several problems follow:
- In a multi-turn conversation, it cannot determine what the user means by “change that function again.”
- During troubleshooting, there is no reliable record of which operations were actually executed.
- If a long-running task is interrupted, the agent may have to start over, wasting time and compute.
A mature agent harness must therefore implement memory as a real engineering subsystem rather than relying on temporary model context. A common design can be summarized as:
Memory = an append-only event log + recording, checkpointing, and recovery
Recording writes everything that happens to a chronological log. Checkpointing forces important data to storage at critical points to reduce the risk of data loss. Recovery reconstructs the conversation and resumes interrupted work after a restart. This article focuses on these three mechanisms.
What a Session Leaves on Disk
After a session ends, a file may appear outside the workspace at a path similar to:
sessions/<escaped-workspace-path>/<session-id>/session.jsonl.zstd
This layout has three purposes:
sessionsis the root directory for all session history.- The middle component is an escaped version of the workspace’s absolute path—for example, replacing
/with-. This groups sessions from the same workspace and makes project-based lookup easier. - The file is compressed JSONL. After decompression, it is plain text with one JSON event per line. Standard tools such as
cat,grep, andjqcan analyze it without a proprietary toolchain.
The first line of the decompressed file is the session header. It contains metadata such as the session ID, creation time, workspace path, and delegation depth. The depth distinguishes top-level sessions from child-agent sessions: the top-level session has depth 0, and the depth increases whenever the primary session creates a child task session. This makes it possible to trace the task hierarchy later.
The session header has one important constraint: it is immutable. The session’s identity is fixed in the first line. Subsequent data is appended as events and is never rewritten. This is similar to the append-only write-ahead log used in databases. Once the beginning of the history can be modified, the history is no longer fully trustworthy.
Recording: The Append-Only Event Stream
“Append-only” is the core semantic property of the memory design. It can be understood at three levels.
1. Written Lines Are Never Rewritten
Events are appended sequentially with continuous sequence numbers. Once written, an event is never modified or deleted. This is a deliberate design choice rather than an implementation shortcut:
- The log is the source of truth. Auditing, replay, and debugging all depend on the assumption that the log reflects what happened. Allowing historical edits effectively allows memory to be fabricated.
- The write path remains O(1) append. The system does not need to maintain complex in-place updates or handle concurrent modifications to existing records. Sequential writes are efficient on both disks and SSDs.
- Replay becomes straightforward. Applying events one by one from the session header allows the system to deterministically rebuild the in-memory conversation state at a given point. This is the foundation of recovery.
A typical event contains a sequence number, timestamp, event type—such as a user message, assistant response, tool call, tool result, or checkpoint marker—and a payload:
{"seq": 7, "ts": "2025-06-01T10:32:11Z", "type": "tool_call","name": "edit_file", "payload": {"path": "src/a.py", "line": 42}}{"seq": 8, "ts": "2025-06-01T10:32:12Z", "type": "tool_result","name": "edit_file", "payload": {"ok": true}}
2. Events Must Be Fine-Grained Enough
A robust design records each minimally auditable action as an event, including user input, model output, every tool call and its arguments, tool results, errors, and checkpoint markers.
Fine-grained events provide several benefits:
- Failures can be replayed precisely to identify which call caused the agent to go off course.
- The log supports offline analysis, such as tool success rates and context-hit analysis.
- The system preserves the possibility of future time-travel debugging.
3. Compression and Storage Management
Writing every event to disk can produce substantial repetition. Two common approaches help control storage:
- Batch and compress events. At flush time, multiple buffered events can be combined and compressed. JSONL typically compresses well because field names and message templates are repeated.
- Use one file per session. Each session remains independent, so expired sessions can be archived or removed as a whole instead of allowing one file to grow indefinitely.
The compression format should support streaming or block-based reading after decompression. Otherwise, inspecting a single event may require decompressing the entire file, increasing the cost of analysis.
Checkpoints: Protecting Against Crashes and Data Loss
An append-only log prevents already-written content from being overwritten, but two problems remain:
- Data in the operating system’s page cache may not yet have reached persistent storage when the process crashes.
- As the event stream grows, replaying the entire history becomes increasingly expensive.
Checkpointing addresses both issues.
1. Why Ordinary write Is Not Enough
When a program writes a file, the data may remain in user-space buffers or the kernel page cache. A process termination does not necessarily discard page-cache data, but a power failure or kernel crash can. Critical checkpoints must therefore perform an explicit storage flush, such as an fsync-style operation, to ensure that the data has reached the storage device.
2. Choosing a Checkpoint Strategy
Checkpointing too frequently adds flush overhead and reduces performance. Checkpointing too rarely increases the amount of data that may be lost after a crash. Common strategies include:
- Event-count thresholds: Force a flush after every N events.
- Time thresholds: Force a flush every T seconds.
- Semantic boundaries: Flush after a conversation turn, a complete tool-call cycle, or a completed child task.
Semantic boundaries are especially valuable because they represent logically complete recovery points. After restarting, the agent can resume from the end of a complete turn rather than from an ambiguous intermediate operation.
The log can explicitly include a checkpoint event to indicate that all preceding events have been persisted and form a semantically consistent point. During recovery, the system can replay up to the latest checkpoint instead of guessing how to handle unfinished operations.
3. The Harness Controls Persistence
The model itself cannot reliably observe or control storage flushing. The harness must decide when data is flushed and when checkpoints are created. This is a major distinction between a toy agent and a production-grade agent: the former depends on memory and the context window, while the latter relies on durable event logging.
Recovery: Rebuilding the World After a Restart
Once the log exists, recovery should rebuild state through replay rather than introducing another state store:
- Locate the session directory and read the session header to verify the session ID, workspace path, and delegation depth.
- Decompress and stream the events, checking that sequence numbers are continuous. If a sequence gap appears or the final line is incomplete—as can happen when a process crashes during a write—the system should truncate the log to the latest complete event or checkpoint instead of loading corrupted data.
- Apply the events in memory to reconstruct the conversation history, tool state, and task queue. The agent can then continue from where it was interrupted.
Two engineering details are particularly important:
- Atomicity: The final line of an NDJSON or zstd stream may be incomplete after a crash. The parser must tolerate a truncated tail, report it clearly, and discard incomplete or corrupted events so that the recovered state does not include partially written data.
- Deterministic replay versus self-healing: Replay should be as deterministic as possible: the same log should produce the same state. Deciding where to truncate is a self-healing policy and should be implemented separately. Keeping these concerns apart makes testing and troubleshooting easier.
Traceability: The Second Value of Memory
An event log is not only a recovery mechanism. It is also a powerful tool for auditing and debugging:
- Replay debugging: Replaying a failed task can identify the exact tool call where the agent made a mistake, helping engineers improve rules, prompts, or tool implementations.
- Accountability: The log provides a detailed record of file modifications, commands, and other operations performed by the agent, creating an evidence trail for later review.
- Long-term learning: Accumulated session logs can become evaluation data or distillation sources that support future improvements to the agent.
Practical Design Checklist
A reliable agent session persistence system should follow these principles:
- Use append-only JSONL with continuous sequence numbers. Never rewrite history, and keep the session header immutable.
- Organize files by session root, escaped workspace directory, and session ID so they can be searched by project and session.
- Choose a compression format that remains stream-readable after decompression, balancing storage efficiency with analysis convenience.
- At semantic boundaries—such as conversation turns and task completion points—perform a forced flush and write a checkpoint marker to balance performance and reliability.
- Base recovery on replay, sequence validation, and tail-truncation self-healing rather than introducing a separate state store.
- Record events at sufficient granularity to cover user input, model output, complete tool-call cycles, results, and errors.
An agent’s memory should not be a black box. It should be an honest, replayable, crash-resistant record of what happened. When recording, checkpointing, and recovery are designed properly, an agent can remain reliable across long-running tasks, multi-turn interactions, and process failures.
