Skip to content

armgit / codex

Public Imported from GitHub
0

Lightweight coding agent that runs in your terminal

Rust

Prefetch sibling rollout paths when reading history pages (#55396)

ben zhange05028e7b0fd
diff --git a/codex-rs/rollout/src/lib.rs b/codex-rs/rollout/src/lib.rs
index 6a068945eb..66aac2dd24 100644
--- a/codex-rs/rollout/src/lib.rs
+++ b/codex-rs/rollout/src/lib.rs
@@ -129,6 +129,7 @@ pub use list::find_thread_path_by_id_str as find_conversation_path_by_id_str;
pub use list::get_threads;
pub use list::get_threads_in_root;
pub use list::parse_cursor;
+pub use list::prefetch_sibling_rollout_paths;
pub use list::read_head_for_summary;
pub use list::read_session_meta_line;
pub use list::read_thread_item_from_rollout;
diff --git a/codex-rs/rollout/src/list.rs b/codex-rs/rollout/src/list.rs
index bdead9e5cb..d66ceb8039 100644
--- a/codex-rs/rollout/src/list.rs
+++ b/codex-rs/rollout/src/list.rs
@@ -2,6 +2,7 @@
use codex_utils_path as path_utils;
use std::cmp::Reverse;
+use std::collections::HashMap;
use std::ffi::OsStr;
use std::fmt;
use std::io;
@@ -1546,6 +1547,65 @@ pub async fn find_rollout_path_by_rollout_id(
Ok(None)
}
+/// Prefetch a bounded set of active rollout paths for a history page.
+///
+/// The sibling directory supplies candidate IDs. They are resolved in the same traversal order as
+/// [`find_rollout_path_by_rollout_id`] to preserve duplicate-ID selection; missing or stale paths
+/// still require the normal lookup.
+pub async fn prefetch_sibling_rollout_paths(
+ codex_home: &Path,
+ child_path: &Path,
+ first_ancestor_id: RolloutId,
+) -> io::Result<HashMap<RolloutId, PathBuf>> {
+ let Some(child_name) = child_path
+ .file_name()
+ .and_then(OsStr::to_str)
+ .and_then(RolloutFileName::parse)
+ else {
+ return Ok(HashMap::new());
+ };
+ // A thread's original rollout ends the chain of same-thread ancestors.
+ if child_name.thread_id() == child_name.rollout_id()
+ || first_ancestor_id == child_name.thread_id()
+ {
+ return Ok(HashMap::new());
+ }
+ let active_root = codex_home.join(SESSIONS_SUBDIR);
+ let canonical_root = tokio::fs::canonicalize(&active_root).await?;
+ let canonical_child = tokio::fs::canonicalize(child_path).await?;
+ let Some(directory) = canonical_child
+ .parent()
+ .filter(|directory| directory.starts_with(&canonical_root))
+ else {
+ return Ok(HashMap::new());
+ };
+ let ids = files::collect_sibling_rollout_ids(
+ directory,
+ child_name.thread_id(),
+ child_name.rollout_id(),
+ )
+ .await?;
+ if ids.len() < 2 || !ids.contains(&first_ancestor_id) {
+ return Ok(HashMap::new());
+ }
+
+ let mut paths = HashMap::new();
+ visit_rollout_filenames(
+ &active_root,
+ |file_name| ids.contains(&file_name.rollout_id()),
+ |file_name, path| {
+ paths.entry(file_name.rollout_id()).or_insert(path);
+ if paths.len() == ids.len() {
+ ControlFlow::Break(())
+ } else {
+ ControlFlow::Continue(())
+ }
+ },
+ )
+ .await?;
+ Ok(paths)
+}
+
/// Extract the `YYYY/MM/DD` directory components from a rollout filename.
pub fn rollout_date_parts(file_name: &OsStr) -> Option<(String, String, String)> {
let name = file_name.to_string_lossy();
diff --git a/codex-rs/rollout/src/list_files.rs b/codex-rs/rollout/src/list_files.rs
index 38b62f86b8..2d6b96ca65 100644
--- a/codex-rs/rollout/src/list_files.rs
+++ b/codex-rs/rollout/src/list_files.rs
@@ -4,7 +4,10 @@
//! all candidates before sorting; creation-time listings retain directory-level early stopping.
//! Scans check cancellation between directory entries and candidate metadata lookups.
+use codex_protocol::RolloutId;
+use codex_protocol::ThreadId;
use std::cmp::Reverse;
+use std::collections::HashSet;
use std::io;
use std::path::Path;
use std::path::PathBuf;
@@ -16,6 +19,9 @@ use super::ThreadCandidate;
use super::parse_timestamp_uuid_from_filename;
use super::truncate_to_millis;
use crate::compression;
+use crate::rollout_file_name::RolloutFileName;
+
+const MAX_SIBLING_ROLLOUT_IDS: usize = 64;
/// Runs a scan whose worker observes cancellation when its async waiter is dropped.
async fn run_scan<T, F>(read: F) -> io::Result<T>
@@ -72,6 +78,33 @@ pub(super) async fn collect_rollout_day_files(
run_scan(move |scan| collect_rollout_day_files_sync(&day_path, scan)).await
}
+pub(super) async fn collect_sibling_rollout_ids(
+ directory: &Path,
+ thread_id: ThreadId,
+ child_rollout_id: RolloutId,
+) -> io::Result<HashSet<RolloutId>> {
+ let directory = directory.to_path_buf();
+ run_scan(move |scan| {
+ let mut ids = HashSet::new();
+ for entry in std::fs::read_dir(directory)?.take(MAX_SCAN_FILES) {
+ scan.check_cancelled()?;
+ let entry = entry?;
+ if entry.file_type()?.is_file()
+ && let Some(file_name) = entry.file_name().to_str().and_then(RolloutFileName::parse)
+ && file_name.thread_id() == thread_id
+ && file_name.rollout_id() != child_rollout_id
+ {
+ ids.insert(file_name.rollout_id());
+ if ids.len() >= MAX_SIBLING_ROLLOUT_IDS {
+ break;
+ }
+ }
+ }
+ Ok(ids)
+ })
+ .await
+}
+
pub(super) async fn collect_flat_rollout_files(
root: &Path,
scanned_files: &mut usize,
diff --git a/codex-rs/rollout/src/tests.rs b/codex-rs/rollout/src/tests.rs
index 79202c45bb..2c9f0fe4bc 100644
--- a/codex-rs/rollout/src/tests.rs
+++ b/codex-rs/rollout/src/tests.rs
@@ -247,6 +247,39 @@ async fn filesystem_lookup_distinguishes_thread_ids_from_rollout_ids() {
);
}
+#[tokio::test]
+async fn sibling_rollout_prefetch_preserves_first_match_for_duplicate_ids() -> Result<()> {
+ let home = TempDir::new()?;
+ let sessions = home.path().join("sessions");
+ let directory = sessions.join("2025/01/03");
+ fs::create_dir_all(&directory)?;
+ let owner = ThreadId::new();
+ let child = ThreadId::new();
+ let first = ThreadId::new();
+ let second = ThreadId::new();
+ let child_path = directory.join(format!("rollout-2025-01-03T12-00-00-{owner}_{child}.jsonl"));
+ let first_sibling =
+ directory.join(format!("rollout-2025-01-03T12-00-00-{owner}_{first}.jsonl"));
+ let second_sibling = directory.join(format!(
+ "rollout-2025-01-03T12-00-00-{owner}_{second}.jsonl"
+ ));
+ let earlier_duplicate = sessions.join(format!("rollout-2025-01-02T12-00-00-{first}.jsonl"));
+ for path in [
+ &child_path,
+ &first_sibling,
+ &second_sibling,
+ &earlier_duplicate,
+ ] {
+ fs::write(path, b"")?;
+ }
+
+ let paths = crate::prefetch_sibling_rollout_paths(home.path(), &child_path, first).await?;
+
+ assert_eq!(paths.get(&first), Some(&earlier_duplicate));
+ assert_eq!(paths.get(&second), Some(&second_sibling));
+ Ok(())
+}
+
#[tokio::test]
async fn read_thread_item_from_rollout_rejects_unknown_canonical_history_mode() {
let temp = TempDir::new().unwrap();
diff --git a/codex-rs/thread-store/src/local/rollout_lineage.rs b/codex-rs/thread-store/src/local/rollout_lineage.rs
index c38440a2dc..3008f3751b 100644
--- a/codex-rs/thread-store/src/local/rollout_lineage.rs
+++ b/codex-rs/thread-store/src/local/rollout_lineage.rs
@@ -1,3 +1,4 @@
+use std::collections::HashMap;
use std::collections::HashSet;
use std::path::Path;
use std::path::PathBuf;
@@ -35,50 +36,67 @@ impl LocalThreadStore {
requested_thread_id: ThreadId,
initial_path: Option<PathBuf>,
) -> ThreadStoreResult<RolloutLineage> {
- self.resolve_rollout_lineage_with_representation(
+ self.resolve_rollout_lineage_with_mode(
requested_thread_id,
- LineageRepresentation::Existing,
+ LineageResolutionMode::Existing,
initial_path,
)
.await
}
+ pub(super) async fn resolve_rollout_lineage_for_history_page(
+ &self,
+ requested_thread_id: ThreadId,
+ ) -> ThreadStoreResult<RolloutLineage> {
+ self.resolve_rollout_lineage_with_mode(
+ requested_thread_id,
+ LineageResolutionMode::HistoryPage,
+ /*initial_path*/ None,
+ )
+ .await
+ }
+
pub(super) async fn resolve_rollout_lineage_for_reference(
&self,
requested_thread_id: ThreadId,
) -> ThreadStoreResult<RolloutLineage> {
- self.resolve_rollout_lineage_with_representation(
+ self.resolve_rollout_lineage_with_mode(
requested_thread_id,
- LineageRepresentation::PlainForReference,
+ LineageResolutionMode::PlainForReference,
/*initial_path*/ None,
)
.await
}
- async fn resolve_rollout_lineage_with_representation(
+ async fn resolve_rollout_lineage_with_mode(
&self,
requested_thread_id: ThreadId,
- representation: LineageRepresentation,
+ mode: LineageResolutionMode,
mut initial_path: Option<PathBuf>,
) -> ThreadStoreResult<RolloutLineage> {
let mut segments = Vec::new();
let mut seen = HashSet::new();
let mut next_rollout_id = None;
let mut end = None;
+ let mut prefetched_paths = HashMap::new();
loop {
let coordination_id = next_rollout_id.unwrap_or(requested_thread_id);
- let _writer_guard = match representation {
- LineageRepresentation::Existing => None,
- LineageRepresentation::PlainForReference => {
+ let _writer_guard = match mode {
+ LineageResolutionMode::Existing | LineageResolutionMode::HistoryPage => None,
+ LineageResolutionMode::PlainForReference => {
Some(self.live_writer_locks.lock(coordination_id).await)
}
};
let (rollout_id, rollout_path) = match (next_rollout_id, initial_path.take()) {
(Some(rollout_id), _) => {
- let rollout_path = resolve_rollout_path_by_id(self, rollout_id)
- .await?
- .ok_or_else(|| malformed_lineage(rollout_id, "missing source rollout"))?;
+ let rollout_path = resolve_rollout_path_by_id(
+ self,
+ rollout_id,
+ prefetched_paths.remove(&rollout_id),
+ )
+ .await?
+ .ok_or_else(|| malformed_lineage(rollout_id, "missing source rollout"))?;
(rollout_id, rollout_path)
}
(None, Some(path)) => {
@@ -105,9 +123,11 @@ impl LocalThreadStore {
if !seen.insert(rollout_id) {
return Err(malformed_lineage(requested_thread_id, "cycle detected"));
}
- let rollout_path = match representation {
- LineageRepresentation::Existing => rollout_path,
- LineageRepresentation::PlainForReference => {
+ let rollout_path = match mode {
+ LineageResolutionMode::Existing | LineageResolutionMode::HistoryPage => {
+ rollout_path
+ }
+ LineageResolutionMode::PlainForReference => {
let outside_codex_home = || ThreadStoreError::InvalidRequest {
message: format!(
"rollout path `{}` must be in Codex home directory",
@@ -154,9 +174,11 @@ impl LocalThreadStore {
"source rollout is not paginated",
));
}
- let rollout_path = match representation {
- LineageRepresentation::Existing => rollout_path,
- LineageRepresentation::PlainForReference
+ let rollout_path = match mode {
+ LineageResolutionMode::Existing | LineageResolutionMode::HistoryPage => {
+ rollout_path
+ }
+ LineageResolutionMode::PlainForReference
if next_rollout_id.is_none() && meta.meta.history_base.is_none() =>
{
// A newly shared standalone source must remain readable by older binaries.
@@ -172,7 +194,7 @@ impl LocalThreadStore {
// Already-shared compressed history requires a compatible reader regardless of
// new forks. Read it without publishing decoded copies into ancestors' folders;
// their owners may concurrently archive or unarchive those immutable files.
- LineageRepresentation::PlainForReference => rollout_path,
+ LineageResolutionMode::PlainForReference => rollout_path,
};
if let Some(end) = end {
validate_cutoff_bounds(requested_thread_id, rollout_path.as_path(), &end).await?;
@@ -193,6 +215,17 @@ impl LocalThreadStore {
let Some(base) = meta.meta.history_base else {
break;
};
+ if matches!(mode, LineageResolutionMode::HistoryPage)
+ && let [child] = segments.as_slice()
+ {
+ prefetched_paths = codex_rollout::prefetch_sibling_rollout_paths(
+ &self.config.codex_home,
+ &child.rollout_path,
+ base.thread_id,
+ )
+ .await
+ .unwrap_or_default();
+ }
next_rollout_id = Some(base.thread_id);
end = Some(base);
}
@@ -205,7 +238,16 @@ impl LocalThreadStore {
async fn resolve_rollout_path_by_id(
store: &LocalThreadStore,
rollout_id: ThreadId,
+ prefetched_path: Option<PathBuf>,
) -> ThreadStoreResult<Option<PathBuf>> {
+ if let Some(path) = prefetched_path
+ && let Some(path) = codex_rollout::existing_rollout_path(&path).await
+ && tokio::fs::symlink_metadata(&path)
+ .await
+ .is_ok_and(|metadata| metadata.is_file())
+ {
+ return Ok(Some(path));
+ }
codex_rollout::find_rollout_path_by_rollout_id(store.config.codex_home.as_path(), rollout_id)
.await
.map_err(|err| ThreadStoreError::Internal {
@@ -214,8 +256,9 @@ async fn resolve_rollout_path_by_id(
}
#[derive(Clone, Copy)]
-enum LineageRepresentation {
+enum LineageResolutionMode {
Existing,
+ HistoryPage,
PlainForReference,
}
diff --git a/codex-rs/thread-store/src/local/thread_history/read.rs b/codex-rs/thread-store/src/local/thread_history/read.rs
index 5876992d3c..e2afaa6423 100644
--- a/codex-rs/thread-store/src/local/thread_history/read.rs
+++ b/codex-rs/thread-store/src/local/thread_history/read.rs
@@ -112,7 +112,7 @@ pub(in crate::local) async fn list_turns(
.await?;
validate_page_size(params.page_size)?;
let lineage = store
- .resolve_rollout_lineage(params.thread_id, /*initial_path*/ None)
+ .resolve_rollout_lineage_for_history_page(params.thread_id)
.await?;
let pool = store.thread_history_db().await?;
let page = page_turn_rows(
@@ -188,7 +188,7 @@ pub(in crate::local) async fn list_items(
}
validate_page_size(params.page_size)?;
let lineage = store
- .resolve_rollout_lineage(params.thread_id, /*initial_path*/ None)
+ .resolve_rollout_lineage_for_history_page(params.thread_id)
.await?;
let pool = store.thread_history_db().await?;
let page = page_item_rows(pool, &lineage, &params).await?;