Why Do AI Agents "Forget"? How Session Logs Enable Crash Recovery and Resumable Execution
AI agents lose their work when a process crashes unless the runtime persists memory. This article explains a practical memory model built from four parts: an append-only event log, recording, checkpointing, and recovery. It walks through the on-disk layout of per-session logs, the append-only semantics that keep history trustworthy, how checkpoints force data to disk at critical moments, and how replay rebuilds state after a crash. It closes with design trade-offs, common pitfalls (log growth, sensitive data, concurrent writes, recursion limits), and a step-by-step plan for building the mechanism into your own system.
1. Why Agents Need Memory
Picture an agent editing a large codebase. It has already modified three files when the process crashes. After a restart, can it pick up where it left off? The answer depends on whether the runtime has persistent memory.
An agent without memory runs into three problems. First, when the user asks “what step were you on?”, it cannot answer. Second, in a multi-turn conversation, when the user says “change that function again,” it does not know which function “that” refers to. Third, when something goes wrong and you need to investigate “what did it actually do?”, there is no record to consult.
A workable memory design can be summarized as the following equation:
Memory = append-only event log + recording + checkpointing + recovery
The event log is the single source of truth. Recording writes events into the log, checkpointing ensures data is truly flushed to disk at critical moments, and recovery rebuilds runtime state from the log. Each has a clear role. The sections below cover them one by one.
2. The Physical Form of Memory: One Log per Session
On disk, memory is usually just an ordinary file. A common directory layout looks like this:
sessions/<escaped workspace path>/<session ID>/session.jsonl.compressed
Here is what each part means. sessions is the root directory for all sessions. The middle level is a directory name derived by escaping the absolute workspace path, used to distinguish different projects. The session ID identifies a single task. The log file itself uses the JSONL format (one JSON object per line) and is stored compressed. Once decompressed, it is plain text you can read directly with ordinary text tools.
The first line of the log is the session header, which records metadata such as the session ID, creation time, workspace path, and delegation depth. Delegation depth indicates whether the current session is a top-level session or a sub-session spawned by another agent. A top-level session is 0, and each level of delegation increments it by one.
The session header has one key constraint: it is written when the session is created and never modified afterward. The identity of the session is fixed from the first line, and everything after it can only be appended.
An illustrative log might look like the following (formatted for readability; in the actual file each event occupies a single line):
{"type":"session_header","seq":0,"sessionId":"demo-001","delegationDepth":0,"workspace":"/home/user/project"}{"type":"user_message","seq":1,"content":"Fix the null pointer issue in the login endpoint"}{"type":"tool_call","seq":2,"tool":"read_file","args":{"path":"src/auth.py"}}{"type":"file_write","seq":3,"path":"src/auth.py","summary":"Added null check"}{"type":"turn_end","seq":4,"status":"ok"}
3. Recording: An Append-Only Event Stream
“Append-only” is the core semantic of this log, and it shows up at three levels.
First, records that are already written are never rewritten. Events have strictly increasing seq numbers, and no event that has been flushed to disk is ever modified or deleted. This is deliberate. If rewriting history were allowed, the log would no longer be trustworthy, and the so-called “memory” would become something you could fabricate at will.
Second, events carry monotonically increasing sequence numbers. The sequence number lets recovery detect missing or out-of-order events, and lets you pinpoint a specific step when investigating a problem.
Third, consecutive events of the same type can be merged into one record. When a model streams output, the content is often split into many small chunks. If each chunk occupies its own line, the log grows quickly and becomes slow to read. A reasonable approach is to merge consecutive chunks of the same type into a single event, closing the current merged block at a type switch or a checkpoint. On read, they are restored into complete content. This saves space without breaking the append-only semantics.
Below is a simplified illustration of the recording logic:
import jsonimport osimport timeclass SessionLog:def __init__(self, path):self.path = pathself.seq = self._last_seq()def _last_seq(self):# Illustrative: read the existing log and take the last sequence numberif not os.path.exists(self.path):return 0last = 0with open(self.path, encoding="utf-8") as f:for line in f:if line.strip():last = json.loads(line)["seq"]return lastdef append(self, event_type, payload):self.seq += 1record = {"seq": self.seq,"ts": time.time(),"type": event_type,"payload": payload,}with open(self.path, "a", encoding="utf-8") as f:f.write(json.dumps(record, ensure_ascii=False) + "\n")
This code only demonstrates the semantics; it is not a production implementation. A real system also needs to handle sealing compressed segments, concurrent writes, and error recovery.
4. Checkpointing: Forcing Data to Disk at Critical Moments
Appending a write does not mean the data is already safe. The operating system typically buffers data first and flushes it to disk asynchronously. If the process crashes during that window, the most recent events may be lost. Checkpointing is designed to solve this: at specific moments it explicitly requires data to be truly flushed to disk before execution continues.
Technically, a checkpoint is usually done in two steps: first flush the application-level buffer, then make a system call to force a sync to the storage device. For compressed segments, you also need to seal the current block first, then write a new compressed file.
4.1 When to Checkpoint
Checkpoints should be placed at points that are hard to recover from afterward. Common positions include:
- Before calling a tool, to record the intent so you can tell after a crash whether the operation already ran;
- After writing a file, to record the result;
- At the end of a conversation turn, to form a stable state boundary;
- Before and after delegating a sub-task, to keep parent and child session state consistent.
4.2 Separating Checkpoint Policy from Storage
Separating “when to checkpoint” from “how to store” is better engineering practice. The policy layer only decides which event types require a forced flush, while the storage layer handles the actual writing and syncing. This way, a team can tune the policy for its latency and reliability requirements without touching the storage implementation.
CHECKPOINT_POLICY = {"before_tool_call": True,"after_file_write": True,"turn_end": True,"before_delegate": True,"text_chunk": False, # High-frequency chunks are not force-flushed; the turn-end checkpoint covers them}
4.3 Trade-offs in Checkpoint Frequency
The more frequent the checkpoints, the smaller the loss window on a crash, but each sync adds I/O latency. The sparser the checkpoints, the better the performance, but the more work must be redone after a crash. A reasonable approach is to checkpoint operations that have side effects (writing files, running commands, calling external services) and rely on turn-boundary checkpoints as a fallback for plain text chunks.
5. Recovery: Rebuilding State from the Log
Recovery is the inverse of recording. Its goal is to read the log, replay events, arrive at a conversation history and runtime state identical to those before the crash, and then continue from the interruption point.
Recovery generally has four steps.
- Read and decompress the log file.
- Validate the session header, confirming the session ID and workspace path match, to prevent loading one project’s memory into another.
- Parse events line by line, checking continuity by sequence number.
- Apply each event in order, rebuilding the conversation history and task state.
Fault tolerance is the part of recovery most often overlooked. On a crash, the last line of the log may be only half written. Such an incomplete trailing line should be detected and discarded, because the operation it corresponds to never actually completed. Corruption in the middle of the log, however, means the storage layer may have a problem, and should raise an error rather than be silently skipped.
import jsondef replay(path):state = {"history": [], "last_seq": 0}with open(path, encoding="utf-8") as f:lines = [line for line in f if line.strip()]for i, line in enumerate(lines):try:event = json.loads(line)except json.JSONDecodeError:if i == len(lines) - 1:break # Trailing half-line: treat as an incomplete write and discardraise RuntimeError(f"Log line {i + 1} is corrupted")if event["seq"] != state["last_seq"] + 1:raise RuntimeError(f"Non-contiguous sequence number: expected {state['last_seq'] + 1}")apply_event(state, event)state["last_seq"] = event["seq"]return statedef apply_event(state, event):if event["type"] == "user_message":state["history"].append({"role": "user", "content": event["content"]})elif event["type"] == "turn_end":pass # Illustrative: turn state could be updated here
After recovery, the runtime state should be identical to what it was before the crash. This can serve as an acceptance criterion for testing: replaying the same log multiple times must produce exactly the same result.
6. Design Trade-offs and Common Pitfalls
6.1 Log Growth and Snapshots
An append-only log grows continuously over time. Rewriting old records to shrink its size would break the append-only semantics. A safer approach is to periodically produce a snapshot that captures the complete state at a given sequence number, then start a new log segment after it. On recovery, load the most recent snapshot first, then replay the events that follow it. The original history segments can be archived for auditing.
6.2 Sensitive Information
The log records user input, tool arguments, and file contents, which may contain secrets, tokens, or personal information. Such data should be redacted before writing. Secrets should only be read through environment variables or a secrets manager, and must never be written to the log or to code. The access permissions on the log file should also follow the principle of least privilege.
6.3 Concurrent Writes
Only one writer may write to the same session at the same time. In practice you need a file lock or process-level mutex to guarantee this. Otherwise two writers could assign the same sequence number, causing the log to fork so that recovery cannot determine which version is correct.
6.4 Recursion Boundaries for Sub-Agents
The delegation depth field exists to limit recursion. Each level of sub-session spawned increments the depth, and an upper bound is set. Delegation without a bound could lead to infinite nesting and exhaust resources.
7. Implementation Recommendations
If you want to build a similar memory mechanism into your own system, proceed in the following order.
- Define the event model first. Decide which event types exist, which fields each event contains, and assign every event a monotonically increasing sequence number.
- Implement an append-only write interface, and flush the buffer immediately after each write.
- Set checkpoints for operations with side effects, and keep the policy in configuration so it is easy to tune.
- Implement the recovery logic, handling the two exception cases of an incomplete trailing line and non-contiguous sequence numbers.
- Write tests: simulate interrupting a write at an arbitrary position and verify that the recovered state matches expectations.
- Before going live, add redaction, access control, and concurrency mutual exclusion.
Follow this path and memory stops being an elusive black box. It becomes an event record you can inspect, replay, and audit.
