Distinguish rollout IDs from thread IDs (#38127)

## Why

`thread/revert` preserves a thread ID while creating a new immutable rollout. Rollout persistence and filesystem fallback therefore need to distinguish the logical thread from each physical history file.

## What changed

- Add a `RolloutId` alias and canonical filename parsing for both ordinary rollouts and reverted rollouts with a distinct rollout ID.
- Allow the recorder to create a replacement rollout without changing the thread ID, and add lookup by either the stable thread ID or an exact rollout ID.
- Index history references and compression safety checks by rollout ID so multiple rollouts for one thread remain distinct.
- Preserve the rollout path selected in SQLite when filesystem repair encounters another rollout for the same thread.

## Testing

Add coverage for filename round trips, replacement rollout metadata, thread and rollout lookup, reference indexing, compression, and database path preservation.

GitOrigin-RevId: 14b1d0b4a9432b341a1307afc0abadd507e7ae7d
This commit is contained in:
Owen Lin authored and copyberry committed 2026-08-12 05:20:32 +00:00
1 parent 2230d64464
commit 4ef836f883
18 files changed
+513 -178

No files matched your search

+43 -43
View File
@@ -14,6 +14,7 @@ use std::sync::Arc;
use std::sync::Mutex;
use chrono::SecondsFormat;
use codex_protocol::RolloutId;
use codex_protocol::SessionId;
use codex_protocol::ThreadId;
use codex_protocol::capabilities::SelectedCapabilityRoot;
@@ -51,6 +52,7 @@ use super::list::parse_timestamp_uuid_from_filename;
use super::metadata;
use super::ordinal::RolloutOrdinalState;
use super::ordinal::ordinal_state_for_rollout;
use super::rollout_file_name::RolloutFileName;
use super::session_index::find_thread_names_by_ids;
use crate::InitialHistory;
use crate::ResumedHistory;
@@ -94,6 +96,13 @@ pub enum RolloutRecorderParams {
Create {
session_id: SessionId,
conversation_id: ThreadId,
/// Overrides the rollout ID encoded in the filename.
///
/// Normally this is `None`, so the filename is
/// `rollout-<timestamp>-<conversation_id>.jsonl`. `thread/revert` sets it, producing
/// `rollout-<timestamp>-<conversation_id>_<rollout_id>.jsonl`, because revert keeps the
/// thread ID stable while creating a new immutable rollout file.
rollout_id_override: Option<RolloutId>,
forked_from_id: Option<ThreadId>,
parent_thread_id: Option<ThreadId>,
source: Box<SessionSource>,
@@ -189,6 +198,7 @@ impl RolloutRecorderParams {
Self::Create {
session_id: conversation_id.into(),
conversation_id,
rollout_id_override: None,
forked_from_id,
parent_thread_id,
source: Box::new(source),
@@ -212,6 +222,20 @@ impl RolloutRecorderParams {
self
}
/// Override the rollout ID while preserving the thread ID.
///
/// This is for creating a new immutable rollout file for an existing thread.
pub fn with_rollout_id(mut self, rollout_id: RolloutId) -> Self {
if let Self::Create {
rollout_id_override,
..
} = &mut self
{
*rollout_id_override = Some(rollout_id);
}
self
}
pub fn with_selected_capability_roots(
mut self,
selected_capability_roots: Vec<SelectedCapabilityRoot>,
@@ -800,6 +824,7 @@ impl RolloutRecorder {
RolloutRecorderParams::Create {
session_id,
conversation_id,
rollout_id_override,
forked_from_id,
parent_thread_id,
source,
@@ -816,10 +841,8 @@ impl RolloutRecorder {
} => {
let ordinal_state =
RolloutOrdinalState::for_new_rollout(history_mode, history_base);
let log_file_info = precompute_log_file_info(config, conversation_id)?;
let path = log_file_info.path.clone();
let thread_id = log_file_info.conversation_id;
let started_at = log_file_info.timestamp;
let (path, started_at) =
precompute_new_rollout_path(config, conversation_id, rollout_id_override)?;
let timestamp_format: &[FormatItem] = format_description!(
"[year]-[month]-[day]T[hour]:[minute]:[second].[subsecond digits:3]Z"
@@ -831,7 +854,7 @@ impl RolloutRecorder {
let session_meta = SessionMeta {
session_id,
id: thread_id,
id: conversation_id,
forked_from_id,
parent_thread_id,
timestamp,
@@ -861,7 +884,7 @@ impl RolloutRecorder {
RolloutWriterState {
writer: None,
deferred_log_file_info: Some(log_file_info),
deferred_creation: true,
pending_items: Vec::new(),
meta: Some(session_meta),
cwd: cwd.clone(),
@@ -874,7 +897,7 @@ impl RolloutRecorder {
let (path, file, ordinal_state) = open_rollout_for_append(path.as_path()).await?;
RolloutWriterState {
writer: Some(JsonlWriter { file }),
deferred_log_file_info: None,
deferred_creation: false,
pending_items: Vec::new(),
meta: None,
cwd: cwd.clone(),
@@ -1575,21 +1598,11 @@ fn cursor_from_thread_item(item: &ThreadItem, sort_key: ThreadSortKey) -> Option
}
}
struct LogFileInfo {
/// Full path to the rollout file.
path: PathBuf,
/// Session ID (also embedded in filename).
conversation_id: ThreadId,
/// Timestamp for the start of the session.
timestamp: OffsetDateTime,
}
fn precompute_log_file_info(
fn precompute_new_rollout_path(
config: &impl RolloutConfigView,
conversation_id: ThreadId,
) -> std::io::Result<LogFileInfo> {
thread_id: ThreadId,
rollout_id_override: Option<RolloutId>,
) -> std::io::Result<(PathBuf, OffsetDateTime)> {
// Resolve ~/.codex/sessions/YYYY/MM/DD path.
let timestamp = OffsetDateTime::now_local()
.map_err(|e| IoError::other(format!("failed to get local time: {e}")))?;
@@ -1599,23 +1612,14 @@ fn precompute_log_file_info(
dir.push(format!("{:02}", u8::from(timestamp.month())));
dir.push(format!("{:02}", timestamp.day()));
// Custom format for YYYY-MM-DDThh-mm-ss. Use `-` instead of `:` for
// compatibility with filesystems that do not allow colons in filenames.
let format: &[FormatItem] =
format_description!("[year]-[month]-[day]T[hour]-[minute]-[second]");
let date_str = timestamp
.format(format)
let rollout_id = rollout_id_override.unwrap_or(thread_id);
let filename = RolloutFileName::new(timestamp, thread_id, rollout_id)
.render()
.map_err(|e| IoError::other(format!("failed to format timestamp: {e}")))?;
let filename = format!("rollout-{date_str}-{conversation_id}.jsonl");
let path = dir.join(filename);
Ok(LogFileInfo {
path,
conversation_id,
timestamp,
})
Ok((path, timestamp))
}
fn open_log_file(path: &Path) -> std::io::Result<File> {
@@ -1647,7 +1651,8 @@ fn open_log_file(path: &Path) -> std::io::Result<File> {
/// unwritten suffix so the next barrier can reopen the file and retry.
struct RolloutWriterState {
writer: Option<JsonlWriter>,
deferred_log_file_info: Option<LogFileInfo>,
/// True until a newly created rollout is first materialized.
deferred_creation: bool,
pending_items: Vec<RolloutItem>,
meta: Option<SessionMeta>,
cwd: PathBuf,
@@ -1716,7 +1721,7 @@ impl RolloutWriterState {
}
fn is_deferred(&self) -> bool {
self.writer.is_none() && self.deferred_log_file_info.is_some()
self.writer.is_none() && self.deferred_creation
}
fn enter_recovery_mode(&mut self, err: &IoError) {
@@ -1739,16 +1744,11 @@ impl RolloutWriterState {
return Ok(());
}
let path = self
.deferred_log_file_info
.as_ref()
.map(|info| info.path.as_path())
.unwrap_or(self.rollout_path.as_path());
let file = open_log_file(path)?;
let file = open_log_file(self.rollout_path.as_path())?;
self.writer = Some(JsonlWriter {
file: tokio::fs::File::from_std(file),
});
self.deferred_log_file_info = None;
self.deferred_creation = false;
Ok(())
}