Part VII. Operating Codex

Where a thread is stored, how configuration and sign-in resolve, and how the project observes, tests, and ships itself.

24. Rollouts, State, and Resume

Codex stores every thread as an append-only JSON Lines file, the rollout, and treats that file as the source of truth. Two SQLite databases index and project the rollout so lists and pages are fast. The code calls that projection “a rebuildable view” that “must never get ahead of canonical history.”

When you quit Codex and later run codex resume, the engine has to rebuild the model’s history, the turn settings, and the context-window bookkeeping from disk. Everything it needs comes from one file per thread. That file is an event log: Codex appends one typed record per line and never rewrites an earlier line during normal operation. Replaying the log reconstructs the state. This is event sourcing, and it shapes every other storage decision in this chapter.

The chapter follows a record from the session to the disk and back. It covers where rollout files live, what a line contains, and the single writer task that owns each file. It then covers the policy function that decides what is durable, the two durable formats and the migration between them, and the thread store with its SQLite family. It ends with the prompt history file and four lifecycle operations: resume, fork, archive, and delete. For the turn loop that produces the records, see Chapter 5; for the compaction records that resume replays, see Chapter 8.

The picture

The session appends items to the local thread store, which filters them and sends them to the rollout recorder; the recorder writes JSONL rollout files, the store upserts thread metadata into state_5.sqlite, and in paginated mode a projector copies the flushed suffix into thread_history_1.sqlite; resume reads the rollout, list views read SQLite, and the TUI writes prompt text to history.jsonl.

Read the green path first. Session::persist_rollout_items hands items to the thread store, LocalThreadStore drops anything the policy calls transient, and RolloutRecorder writes the rest as JSON lines under sessions/. That file is what resume and fork read. The grey arrows are indexes: the store keeps one row per thread in state_5.sqlite, and pickers and the app server list threads from it. The dashed purple path exists only for paginated threads, where a projector copies each flushed suffix of the rollout into thread_history_1.sqlite so clients can page through turns and items. The TUI’s prompt recall file, history.jsonl, is separate and holds only the text you typed.

The rollout is an event log

Where the files live

All local state sits under CODEX_HOME, which defaults to ~/.codex (Chapter 25 covers how it resolves). precompute_new_rollout_path in codex-rs/rollout/src/recorder.rs builds the path from local time: CODEX_HOME/sessions/<year>/<MM>/<DD>/. The file name comes from RolloutFileName::render, which produces rollout-<YYYY-MM-DDTHH-MM-SS>-<thread_id>.jsonl. A reverted thread keeps its thread ID but gets a new immutable file, so the name gains a suffix: rollout-<timestamp>-<thread_id>_<rollout_id>.jsonl. The doc comment on rollout_id_override explains the reason: “revert keeps the thread ID stable while creating a new immutable rollout file.” Archived files move to a sibling tree, archived_sessions.

One line, one item

Each line is a RolloutLine: a timestamp, an optional ordinal, and one flattened RolloutItem. The item serializes with a type tag and a payload. This line comes from a test fixture in codex-rs/thread-store/src/local/original_history_tests.rs; on disk it is one line, wrapped here for width:

{"timestamp":"2025-01-03T10:00:01Z","ordinal":1,"type":"response_item",
 "payload":{"type":"message","role":"assistant",
  "content":[{"type":"output_text","text":"Original é🙂"}]}}

A rollout always opens with a session_meta line. RolloutRecorder::new_inner fills it with the thread ID, the working directory, the originator, the model provider, the base instructions, cli_version from CARGO_PKG_VERSION, the history mode, and fork lineage. The writer adds Git commit, branch, and remote when the working directory is inside a repository.

RolloutItem in codex-rs/history/src/lib.rs has 13 variants. The table groups them by what they record.

Group Variants Records
Header SessionMeta, DynamicToolsUpdated Thread identity, tool catalog
Model history ResponseItem, Compacted Items sent to or from the model
Turn state TurnContext, TokenUsageRecord, WorldState, RetainedContext Settings and budgets per turn
Agents and safety InterAgentCommunication, InterAgentCommunicationMetadata, SecurityRiskScore Multi-agent and risk facts
Events EventMsg, RealtimeItem Protocol events, realtime facts

RolloutLine derives Serialize but deliberately not Deserialize. Readers must go through decode_rollout_line in codex-rs/rollout/src/lib.rs, which pulls out timestamp and ordinal by hand before decoding the item. The doc comment explains why: with serde_json/arbitrary_precision, Serde’s flattened-envelope buffer cannot replay nested floating-point values. One decoder at the persistence boundary keeps resume and SQLite projection reading the same bytes the same way.

The recorder: one writer per thread

A bounded channel and a single task

RolloutRecorder is an actor with a submission queue. The struct holds only a channel sender, a handle to the writer task, and the path. new_inner creates mpsc::channel::<RolloutCmd>(256) and spawns rollout_writer, a Tokio task that owns the file handle. The source comment states the goal: when the buffer fills, “the send future will yield,” so callers never do blocking I/O on their own thread. The command set, from codex-rs/rollout/src/recorder.rs, is small:

enum RolloutCmd {
    AddItems(Vec<RolloutItem>),
    ReadUnpersistedSessionMeta {
        ack: oneshot::Sender<Option<SessionMeta>>,
    },
    Persist {
        ack: oneshot::Sender<std::io::Result<()>>,
    },
    /// Ensure all prior writes are processed; respond when flushed.
    Flush {
        ack: oneshot::Sender<std::io::Result<()>>,
    },
    Shutdown {
        ack: oneshot::Sender<std::io::Result<()>>,
    },
    Discard {
        ack: oneshot::Sender<()>,
    },
}

Every command except AddItems carries a oneshot acknowledgement, so a caller that needs durability awaits flush() and gets the I/O result back. Because one task processes the queue in order, writes for a thread are totally ordered without a mutex on the file.

Deferred creation

A new thread does not get a file at once. new_inner sets deferred_creation: true and keeps the SessionMeta in memory, so a thread that never runs a turn leaves no empty file behind. AddItems appends to pending_items and writes only if the file already exists. The first persist() opens the file, writes the session_meta line, then drains the pending items in order. On Unix the writer also remembers which new date directories it created and syncs them during a flush that carries realtime items. A resumed thread skips all of this: RolloutRecorderParams::Resume opens the existing file for append immediately.

Failures are handled at two levels. An ordinary I/O error inside write_pending_with_recovery drops the file handle, reopens, and retries once. If the retry fails, the error goes back through the acknowledgement, and the items stay buffered for a later flush. Only an error that ends the task is stored by RolloutWriterTask::mark_failed, and every later call returns that terminal error.

Who calls the recorder

The session never touches the recorder directly. Session::persist_rollout_items calls LiveThread::append_items, which delegates to the thread store. In the local store, write_and_project in codex-rs/thread-store/src/local/live_writer.rs takes a per-thread lock, filters the batch, stamps ordinals, calls record_canonical_items, and then awaits flush(). For paginated threads it normally projects the newly flushed suffix into SQLite after the flush returns. The comment beside that step states the invariant: “SQLite is a rebuildable view and must never get ahead of canonical history.”

Deciding what persists

One policy function

Live events outnumber durable facts by a wide margin: every streamed token is an event. persisted_rollout_item(item, history_mode) in codex-rs/rollout/src/policy.rs is the single place that decides which items survive. It returns None to drop an item, a borrowed item to keep it as is, or an owned copy when it must rewrite the item first. The match is exhaustive, so adding an EventMsg variant fails to compile until someone classifies it. This is a policy object at the persistence boundary.

The rules fall into five groups, summarized in the table.

Category Examples Durable?
Executive markers Compacted, TurnContext, TokenUsageRecord, SessionMeta Always
Model items ResponseItem All but CompactionTrigger and Other
Turn boundary events TurnStarted, TurnComplete, TurnAborted, TokenCount, ThreadRolledBack Always
Display events UserMessage, AgentMessage, PatchApplyEnd, McpToolCallEnd Legacy mode only
Transient events deltas, begin events, approval requests, ExecCommandEnd, Warning, Error Never

RawResponseCompleted is a special case: it persists only when it carries a guardian payload. A second filter, should_persist_response_item_for_memories, applies a stricter rule for the memories feature and excludes developer messages, reasoning, and compaction items.

Truncating large outputs

In paginated mode the policy also keeps ItemCompleted events, which carry full tool results. Two caps of 64 KiB keep a single noisy command from bloating the file: PERSISTED_COMMAND_OUTPUT_MAX_BYTES for command output and PERSISTED_MCP_RESULT_MAX_BYTES for MCP results. Command output is cut in the middle by truncate_middle_with_marker, which keeps the head and tail and inserts a marker line. The kept bytes split as follows:

where bytes is the cap, bytes is the length of the marker ... command output truncated for persistence ... with its two newlines, is the byte budget for the head, and is the budget for the tail. With these values bytes. The head boundary rounds down and the tail boundary rounds up to the nearest UTF-8 character, so the stored string never exceeds and never splits a character. Only the durable copy shrinks; the model saw the output under its own truncation rules (see Chapter 10).

Two durable formats

Legacy and Paginated

ThreadHistoryMode in codex-rs/protocol/src/protocol.rs has two values. Legacy is the Serde default, so an old file with no mode reads as legacy. In legacy files, lines carry no ordinal, and the display events from the table above stand in for UI items. Paginated files stamp a monotonically increasing ordinal on every line, starting at 0 or at the fork base, and persist ItemCompleted events with typed turn items instead of the legacy display events. Ordinals are what make paging possible: a client can ask for items after ordinal 4,000 without reading the first 4,000 lines.

The mode is fixed per thread. Session picks it through conversation_history.get_history_mode, which returns the persisted mode for a resumed thread and the store’s default_history_mode() for a new one. The ThreadStore trait defaults to Legacy so that other stores stay compatible, while LocalThreadStore overrides the default to Paginated. A new local thread is therefore paginated, and an old one stays legacy until you migrate it.

Migrating old rollouts

codex migrate-rollouts converts legacy files. Without --apply it only reports which threads are eligible; --thread limits it to given IDs, --max-mib-per-second throttles disk traffic, and --json prints the per-thread report. The engine behind it is codex-rs/thread-store/src/local/rollout_migration.rs. Its module comment lists the steps: take the maintenance and writer locks, canonicalize into a staged JSONL file, project the staged file into SQLite, verify the projection, then publish atomically. The stated invariant is that the run always leaves “either the original legacy rollout or a recoverable paginated rollout,” with a durable .pending journal for recovery after a crash. Migration 0047 adds rollout_migration_state and rollout_migration_skipped_rollouts so a run can resume where the last one stopped.

Two background jobs exist but stay off by default. When a state database is available and background_paginated_rollout_migration is on, the local store runs the same migration at startup. When local_thread_store_compression is on, a worker compresses rollouts older than 7 days with zstd level 3, runs at most 2 jobs at a time, and stops after 5 hours. Resuming a compressed thread first turns its .zst file back into plain JSONL, and the append path also repairs a missing final newline before it writes.

The thread store and SQLite

A storage-neutral boundary

ThreadStore in codex-rs/thread-store/src/store.rs is the seam between the engine and storage. The crate comment says application code “should treat ThreadId as the only durable thread handle”; an implementation decides whether that ID maps to local files, a remote service, or memory. The crate ships LocalThreadStore and InMemoryThreadStore. The trait gives default implementations for optional capabilities: list_turns and list_items return Unsupported unless a store overrides them, and LocalThreadStore reports supports_paginated_history_lists only when it has a state database. This is the strategy pattern with capability probes, and it lets the app server (see Chapter 21) serve the same thread API over either backend.

Seven databases

RUNTIME_DBS in codex-rs/state/src/sqlite.rs lists seven SQLite files. They sit in CODEX_HOME unless the sqlite_home key or CODEX_SQLITE_HOME points elsewhere, and logs_2.sqlite follows log_dir when you set that key. The table shows each file and what happens when a startup check finds corruption.

File Holds On corruption
state_5.sqlite Thread index, sections, projects Back up, rebuild
logs_2.sqlite Diagnostic logs Back up, rebuild
goals_1.sqlite Thread goals Back up, rebuild
memories_1.sqlite, memories_v2_1.sqlite Memories Back up, rebuild
queue_1.sqlite Queued user submissions Back up, rebuild
thread_history_1.sqlite Turns, items, realtime items Unavailable

At open, the state crate runs a SQLite quick check limited to 100 ms. For the six databases marked BackupAndRebuild, a corrupt file is preserved under a backup name and a fresh one is created. The thread-history database uses RecoveryMode::Unavailable instead. That file is a projection of the rollouts, so losing it loses no source data; this is an inference from the write path, not a stated rationale.

state_5.sqlite carries 64 migrations, from 0001_threads.sql to 0064_thread_listing_indexes.sql. The first creates the threads table keyed by thread ID, with rollout_path, timestamps, source, provider, working directory, title, token count, archive flags, and Git fields. The history of the directory shows features moving out over time: logs dropped in 0023, thread goals in 0034, and memories in 0035, each into its own file. Migration 0042 drops the agent-job tables outright, because the maintainers removed that feature.

Every migrator is built by runtime_migrator with ignore_missing: true. The doc comment gives the reason: it lets “an older Codex binary open a database that has already been migrated by a newer binary running in parallel.” Known migrations are still checked by checksum, so only the “database is ahead of me” case relaxes. This is forward compatibility by additive schema: a new binary may add columns and tables, and an old binary ignores what it does not know.

Prompt history

The up-arrow recall in the TUI reads CODEX_HOME/history.jsonl, one {"session_id", "ts", "text"} object per line, written by append_entry in codex-rs/message-history/src/lib.rs. The file is global across threads and holds only text you typed. Each append builds the full line first, opens the file in append mode with permissions 0o600 on Unix, and takes an advisory exclusive lock with up to 10 tries 100 ms apart. Setting [history] persistence = "none" turns writes off.

When max_bytes is set and the file grows past it, enforce_history_limit drops the oldest lines until the file fits a lower target, so the next append does not trim again at once:

where is the target size in bytes, is max_bytes, is HISTORY_SOFT_CAP_RATIO, and is the length of the newest line. The code also clamps to the range 1 to . With , a trim cuts the file to at most 800,000 bytes by whole lines, and the newest entry always survives.

Resume, fork, archive, and delete

Resume. codex resume opens a picker, or --last takes the most recent interactive thread. The store loads the rollout as InitialHistory::Resumed, and Session::reconstruct_history_from_rollout calls ContextManager::reconstruct_rollout. That function selects the newest usable compaction checkpoint, replays only the items after it, and scans backward for the last TurnStarted to recover the previous turn’s settings. The result, a RolloutReconstruction, holds the model history, the retained context, the guardian history, and the context-window IDs. The recorder then reopens the same file for append.

Fork. A fork copies a prefix of the rollout into a new thread with a new ID. fork_prefix_len(items, n) in codex-rs/core/src/thread_rollout_truncation.rs cuts before user message n, after applying any ThreadRolledBack markers so that rolled-back turns do not count. If n is out of range, the cut drops only the unfinished turn. A second mode, ForkSnapshot::Interrupted, keeps every item and closes the unfinished turn in the copy with a synthetic TurnAborted. The new SessionMeta records forked_from_id and forked_from_ordinal_exclusive.

Archive. Archiving renames every rollout file the thread owns into archived_sessions/ and marks the row archived in state_5.sqlite. It refuses a thread that has an active writer. If a later rename fails, restore_rollout_moves undoes the earlier ones, and archiving a parent also archives its spawned descendants. Unarchive moves the files back into the dated tree, using the date parsed from the file name.

Delete. codex delete is a hard delete. The module comment in delete_thread.rs gives the order: rollout files first, then state rows, under one lifecycle lock. A preflight rejects a thread that still has attached child threads and, when asked, a thread that other rollouts fork from.

Status at commit 081295be9d. Paginated history as the local default: IMPLEMENTED (LocalThreadStore::default_history_mode). codex migrate-rollouts: IMPLEMENTED, dry run unless --apply. background_paginated_rollout_migration: UNDER DEVELOPMENT, off by default. local_thread_store_compression: UNDER DEVELOPMENT, off by default. sqlite: REMOVED, on by default, so SQLite state is no longer optional. Fsync of newly created date directories and the 0o600 history file mode: PLATFORM-SPECIFIC (Unix). Read in code, not run.

What breaks

Symptom Cause Check
A new thread has no file on disk Creation is deferred until the first persist() deferred_creation in recorder.rs
Resume misses something you saw live The event is transient under the policy persisted_event_msg in policy.rs
Long command output looks cut after resume Paginated cap of 64 KiB PERSISTED_COMMAND_OUTPUT_MAX_BYTES
Thread list is empty after moving CODEX_HOME SQLite still lives at the old sqlite_home CODEX_SQLITE_HOME, sqlite_home
Archive fails with “already has an active writer” The thread is still loaded with a live recorder archive_thread.rs writer check
Fork after a given turn is rejected The turn ID is synthetic, from a legacy rollout truncate_rollout_after_turn_id
Delete is refused A child thread is attached, or a fork references it preflight_delete_threads

Code map

What it is Where it lives Identifier
Rollout writer actor codex:codex-rs/rollout/src/recorder.rs RolloutRecorder
Persistence policy codex:codex-rs/rollout/src/policy.rs persisted_rollout_item
Rollout item enum codex:codex-rs/history/src/lib.rs pub enum RolloutItem
Storage seam codex:codex-rs/thread-store/src/store.rs pub trait ThreadStore
Local write and projection codex:codex-rs/thread-store/src/local/live_writer.rs write_and_project
Legacy migration codex:codex-rs/thread-store/src/local/rollout_migration.rs Orchestrates legacy rollout migration
SQLite file list codex:codex-rs/state/src/sqlite.rs RUNTIME_DBS
Prompt history codex:codex-rs/message-history/src/lib.rs enforce_history_limit

Recall check

Which store is the source of truth for a thread, the rollout file or SQLite?
The rollout; SQLite projections are written only after a flush and can be rebuilt.

Why does a brand-new thread sometimes have no rollout file yet?
The recorder defers creation until persist(), so threads without a turn leave no empty files.

What does persisted_rollout_item do with an ExecCommandOutputDelta event?
It drops it; streaming deltas are transient in both history modes.

How does a paginated rollout differ from a legacy one on disk?
Every line carries an ordinal, and ItemCompleted events replace the legacy display events.

What lets an older Codex binary open a database that a newer binary migrated?
runtime_migrator sets ignore_missing: true, so unknown newer migrations are ignored.