diff --git a/codex-rs/core/tests/suite/multi_agent_restore_tests.rs b/codex-rs/core/tests/suite/multi_agent_restore_tests.rs index 7c19369b86..10654543b6 100644 --- a/codex-rs/core/tests/suite/multi_agent_restore_tests.rs +++ b/codex-rs/core/tests/suite/multi_agent_restore_tests.rs @@ -90,8 +90,6 @@ impl ThreadStore for GatedChildMetadataStore { fn flush_thread(thread_id: ThreadId) -> (); fn shutdown_thread(thread_id: ThreadId) -> (); fn discard_thread(thread_id: ThreadId) -> (); - fn load_history(params: LoadThreadHistoryParams) -> StoredThreadHistory; - fn load_latest_model_context(params: LoadThreadHistoryParams) -> StoredModelContext; fn read_thread_by_rollout_path(params: ReadThreadByRolloutPathParams) -> StoredThread; fn list_threads(params: ListThreadsParams) -> ThreadPage; fn update_thread_metadata(params: UpdateThreadMetadataParams) -> Option; @@ -100,6 +98,40 @@ impl ThreadStore for GatedChildMetadataStore { fn delete_thread(params: DeleteThreadParams) -> (); } + fn load_history( + &self, + params: LoadThreadHistoryParams, + ) -> ThreadStoreFuture<'_, StoredThreadHistory> { + Box::pin(async move { + if params.thread_id != self.failed_child { + return self.inner.load_history(params).await; + } + // Emulate a store that exposes this saved child's header through load_history. + let context = self.inner.load_latest_model_context(params).await?; + Ok(StoredThreadHistory { + thread_id: context.thread_id, + items: context.items, + revision: context.revision, + }) + }) + } + + fn load_latest_model_context( + &self, + params: LoadThreadHistoryParams, + ) -> ThreadStoreFuture<'_, StoredModelContext> { + Box::pin(async move { + let omit_header = params.thread_id == self.failed_child; + let mut context = self.inner.load_latest_model_context(params).await?; + if omit_header { + context + .items + .retain(|item| !matches!(item, RolloutItem::SessionMeta(_))); + } + Ok(context) + }) + } + fn resume_thread( &self, params: ResumeThreadParams, @@ -262,6 +294,12 @@ async fn cold_root_resume_overlaps_child_reads_and_applies_identities_in_graph_o started: started_tx, completed: completed_tx, }); + let params = LoadThreadHistoryParams { + thread_id: failed, + include_archived: false, + }; + let meta = store.read_session_meta(params).await?; + assert_eq!((meta.id, meta.session_id), (failed, root.into())); let resume_url = format!("{}/v1", server.uri()); let mut resume_builder = test_codex() .with_thread_store(store) diff --git a/codex-rs/thread-store/src/in_memory.rs b/codex-rs/thread-store/src/in_memory.rs index befc4281bc..30add0439c 100644 --- a/codex-rs/thread-store/src/in_memory.rs +++ b/codex-rs/thread-store/src/in_memory.rs @@ -365,6 +365,18 @@ mod tests { assert_eq!(thread.history_mode, ThreadHistoryMode::Paginated); assert!(thread.history.is_none()); + let meta = store + .read_session_meta(LoadThreadHistoryParams { + thread_id, + include_archived: false, + }) + .await + .expect("canonical metadata without a legacy history read"); + assert_eq!( + (meta.id, meta.history_mode), + (thread_id, ThreadHistoryMode::Paginated) + ); + let thread = store .read_thread_by_rollout_path(ReadThreadByRolloutPathParams { rollout_path, diff --git a/codex-rs/thread-store/src/local/archive_thread.rs b/codex-rs/thread-store/src/local/archive_thread.rs index 928c8cbdb6..eede2ef77c 100644 --- a/codex-rs/thread-store/src/local/archive_thread.rs +++ b/codex-rs/thread-store/src/local/archive_thread.rs @@ -368,5 +368,57 @@ mod tests { assert_eq!(updated.rollout_path, archived_path); assert!(updated.archived_at.is_some()); assert_eq!(updated.recency_at, metadata.recency_at); + let contents = std::fs::read_to_string(&archived_path).expect("archived rollout"); + let (header, history) = contents.split_once('\n').expect("header and history"); + let mut header: serde_json::Value = serde_json::from_str(header).expect("header"); + let mut metadata = metadata; + for mode in [ThreadHistoryMode::Legacy, ThreadHistoryMode::Paginated] { + metadata.history_mode = mode; + header["payload"]["history_mode"] = serde_json::to_value(mode).expect("history mode"); + std::fs::write(&archived_path, format!("{header}\n{history}")).expect("update header"); + // The file moved, but SQLite still points to its old location. + runtime + .upsert_thread(&metadata) + .await + .expect("stale SQLite path"); + let meta = store + .read_session_meta(crate::LoadThreadHistoryParams { + thread_id, + include_archived: true, + }) + .await + .expect("metadata before SQLite update"); + let expected = codex_rollout::read_session_meta_line(&archived_path) + .await + .expect("archived header") + .meta; + assert_eq!( + serde_json::to_value(meta).expect("metadata"), + serde_json::to_value(&expected).expect("header") + ); + let params = crate::LoadThreadHistoryParams { + thread_id, + include_archived: false, + }; + assert!(matches!( + store.read_session_meta(params.clone()).await, + Err(ThreadStoreError::ThreadNotFound { .. }) + )); + runtime + .mark_archived(thread_id, &archived_path, Utc::now()) + .await + .expect("archived SQLite path"); + std::fs::rename(&archived_path, &active_path) + .expect("move before unarchive SQLite update"); + let meta = store + .read_session_meta(params) + .await + .expect("visible unarchived metadata"); + assert_eq!( + serde_json::to_value(meta).expect("metadata"), + serde_json::to_value(expected).expect("header") + ); + std::fs::rename(&active_path, &archived_path).expect("restore archived rollout"); + } } } diff --git a/codex-rs/thread-store/src/local/mod.rs b/codex-rs/thread-store/src/local/mod.rs index 6b7166a267..987a91aad2 100644 --- a/codex-rs/thread-store/src/local/mod.rs +++ b/codex-rs/thread-store/src/local/mod.rs @@ -47,6 +47,7 @@ mod test_support; mod timestamp_metadata_tests; use codex_protocol::ThreadId; +use codex_protocol::protocol::SessionMeta; use codex_protocol::protocol::ThreadHistoryMode; use codex_protocol::realtime::RealtimeItem; use codex_rollout::ResponseItemEnvelope; @@ -675,6 +676,13 @@ impl ThreadStore for LocalThreadStore { Box::pin(LocalThreadStore::load_history(self, params)) } + fn read_session_meta( + &self, + params: LoadThreadHistoryParams, + ) -> ThreadStoreFuture<'_, SessionMeta> { + Box::pin(read_thread::read_session_meta(self, params)) + } + fn load_latest_model_context( &self, params: LoadThreadHistoryParams, diff --git a/codex-rs/thread-store/src/local/read_thread.rs b/codex-rs/thread-store/src/local/read_thread.rs index 393b5bcaf6..b6c5936aa8 100644 --- a/codex-rs/thread-store/src/local/read_thread.rs +++ b/codex-rs/thread-store/src/local/read_thread.rs @@ -22,6 +22,7 @@ use super::helpers::set_thread_name; use super::helpers::sqlite_thread_name; use super::helpers::stored_thread_from_rollout_item; use super::thread_rollout_resolver; +use crate::LoadThreadHistoryParams; use crate::ReadThreadParams; use crate::StoredThread; use crate::StoredThreadHistory; @@ -29,6 +30,76 @@ use crate::ThreadStoreError; use crate::ThreadStoreResult; use crate::error::reject_paginated_history_mode; +pub(super) async fn read_session_meta( + store: &LocalThreadStore, + params: LoadThreadHistoryParams, +) -> ThreadStoreResult { + match session_meta_path(store, ¶ms).await? { + (_, Some(meta)) => Ok(meta), + (path, None) => read_session_meta_from_path(store, params, &path).await, + } +} + +async fn session_meta_path( + store: &LocalThreadStore, + params: &LoadThreadHistoryParams, +) -> ThreadStoreResult<(std::path::PathBuf, Option)> { + if let Some(resolved) = thread_rollout_resolver::resolve_for_session_meta(store, params).await? + { + return Ok((resolved.path, resolved.session_meta)); + } + let metadata = read_sqlite_metadata(store, params.thread_id).await.ok_or( + ThreadStoreError::ThreadNotFound { + thread_id: params.thread_id, + }, + )?; + Ok((metadata.rollout_path, None)) +} + +pub(super) async fn read_session_meta_from_path( + store: &LocalThreadStore, + params: LoadThreadHistoryParams, + path: &std::path::Path, +) -> ThreadStoreResult { + let mut path = path.to_path_buf(); + let meta = match read_session_meta_line(&path).await { + Err(err) if err.kind() == std::io::ErrorKind::NotFound => { + // Archive moves precede SQLite updates; follow the selected immutable rollout. + path = match codex_rollout::rollout_id_from_path(&path) { + Some(rollout_id) => codex_rollout::find_rollout_path_by_rollout_id( + store.config.codex_home.as_path(), + rollout_id, + ) + .await + .map_err(|err| ThreadStoreError::Internal { + message: err.to_string(), + })? + .ok_or(ThreadStoreError::ThreadNotFound { + thread_id: params.thread_id, + })?, + None => match session_meta_path(store, ¶ms).await? { + (_, Some(meta)) => return Ok(meta), + (path, None) => path, + }, + }; + read_required_session_meta_line(&path).await? + } + result => result.map_err(|err| ThreadStoreError::Internal { + message: err.to_string(), + })?, + } + .meta; + if meta.id != params.thread_id + || (!params.include_archived + && rollout_path_is_archived(store.config.codex_home.as_path(), &path)) + { + return Err(ThreadStoreError::ThreadNotFound { + thread_id: params.thread_id, + }); + } + Ok(meta) +} + pub(super) async fn read_thread( store: &LocalThreadStore, params: ReadThreadParams, diff --git a/codex-rs/thread-store/src/local/read_thread_tests.rs b/codex-rs/thread-store/src/local/read_thread_tests.rs index d0a54a827b..2e56cb7991 100644 --- a/codex-rs/thread-store/src/local/read_thread_tests.rs +++ b/codex-rs/thread-store/src/local/read_thread_tests.rs @@ -1,7 +1,8 @@ -//! Regression coverage for metadata reads without SQLite. +//! Regression coverage for rollout metadata reads and SQLite fallback. use std::fs; use std::fs::FileTimes; +use std::sync::Arc; use chrono::DateTime; use chrono::Utc; @@ -12,10 +13,13 @@ use codex_protocol::protocol::ThreadSource; use codex_rollout::RolloutItem; use codex_rollout::RolloutLine; use pretty_assertions::assert_eq; +use serde_json::to_value; use tempfile::TempDir; use super::LocalThreadStore; use super::test_support::test_config; +use crate::ArchiveThreadParams; +use crate::LoadThreadHistoryParams; use crate::ReadThreadParams; use crate::ThreadStore; @@ -58,6 +62,7 @@ async fn empty_archived_reads_without_sqlite_preserve_source_and_file_time() include_history: false, }) .await?; + let stale_path = path.clone(); let by_path = store .read_thread_by_rollout_path( path, /*include_archived*/ true, /*include_history*/ false, @@ -85,5 +90,31 @@ async fn empty_archived_reads_without_sqlite_preserve_source_and_file_time() ), ); } + let other = LocalThreadStore::new(test_config(home.path()), /*state_db*/ None); + let moved = other + .unarchive_thread(ArchiveThreadParams { thread_id }) + .await?; + let config = test_config(home.path()); + let state_db = codex_state::StateRuntime::init( + config.sqlite.clone(), + config.default_model_provider_id.clone(), + ) + .await?; + let indexed_store = LocalThreadStore::new(config, Some(Arc::clone(&state_db))); + let params = LoadThreadHistoryParams { + thread_id, + include_archived: true, + }; + assert!(state_db.get_thread(thread_id).await?.is_none()); + let meta = indexed_store.read_session_meta(params.clone()).await?; + let expected = to_value(&line.item)?; + assert_eq!(to_value(meta)?, expected["payload"]); + assert!(state_db.get_thread(thread_id).await?.is_none()); + fs::write( + moved.rollout_path.expect("unarchived rollout"), + [serde_json::to_vec(&line)?.as_slice(), b"\n\xff"].concat(), + )?; + let meta = super::read_thread::read_session_meta_from_path(&store, params, &stale_path).await?; + assert_eq!(to_value(meta)?, expected["payload"]); Ok(()) } diff --git a/codex-rs/thread-store/src/local/thread_rollout_resolver.rs b/codex-rs/thread-store/src/local/thread_rollout_resolver.rs index 5fad0edd50..90e729589f 100644 --- a/codex-rs/thread-store/src/local/thread_rollout_resolver.rs +++ b/codex-rs/thread-store/src/local/thread_rollout_resolver.rs @@ -3,10 +3,12 @@ //! Most threads have one rollout file. `thread/revert` keeps the thread ID stable while switching //! the thread to a new rollout file, so callers cannot infer the selected path from the thread ID //! alone. This module centralizes live-writer, SQLite, and filesystem fallback resolution. +//! Session metadata reads skip read repair to avoid parsing the rest of the rollout. use std::path::PathBuf; use codex_protocol::ThreadId; +use codex_protocol::protocol::SessionMeta; use codex_protocol::protocol::ThreadHistoryMode; use codex_rollout::find_archived_thread_path_by_id_str; use codex_rollout::find_thread_path_by_id_str; @@ -14,6 +16,7 @@ use codex_rollout::find_thread_path_by_id_str; use super::LocalThreadStore; use super::helpers::rollout_path_is_archived; use super::live_writer; +use crate::LoadThreadHistoryParams; use crate::ThreadStoreError; use crate::ThreadStoreResult; @@ -21,12 +24,14 @@ use crate::ThreadStoreResult; /// /// For ordinary threads, `thread_id` and `rollout_id` are the same. After `thread/revert`, /// `thread_id` stays stable while `rollout_id` identifies the new immutable rollout file. -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Debug)] pub(super) struct ResolvedThreadRollout { pub(super) thread_id: ThreadId, pub(super) rollout_id: ThreadId, pub(super) path: PathBuf, pub(super) location: RolloutLocation, + /// Header already read to verify the SQLite path belongs to this thread. + pub(super) session_meta: Option, } #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -39,14 +44,38 @@ pub(super) async fn resolve_current( store: &LocalThreadStore, thread_id: ThreadId, ) -> ThreadStoreResult> { - resolve(store, thread_id, LookupScope::ExcludeArchived).await + resolve( + store, + thread_id, + LookupScope::ExcludeArchived, + ReadRepair::Enabled, + ) + .await } pub(super) async fn resolve_current_including_archived( store: &LocalThreadStore, thread_id: ThreadId, ) -> ThreadStoreResult> { - resolve(store, thread_id, LookupScope::IncludeArchived).await + resolve( + store, + thread_id, + LookupScope::IncludeArchived, + ReadRepair::Enabled, + ) + .await +} + +pub(super) async fn resolve_for_session_meta( + store: &LocalThreadStore, + params: &LoadThreadHistoryParams, +) -> ThreadStoreResult> { + let scope = if params.include_archived { + LookupScope::IncludeArchived + } else { + LookupScope::ExcludeArchived + }; + resolve(store, params.thread_id, scope, ReadRepair::Disabled).await } #[derive(Clone, Copy)] @@ -64,6 +93,11 @@ impl LookupScope { } } +enum ReadRepair { + Enabled, + Disabled, +} + /// Resolves a thread's selected rollout in this order: /// /// 1. The live writer, when one exists. @@ -74,12 +108,14 @@ async fn resolve( store: &LocalThreadStore, thread_id: ThreadId, scope: LookupScope, + read_repair: ReadRepair, ) -> ThreadStoreResult> { if let Ok(path) = live_writer::rollout_path(store, thread_id).await && codex_rollout::existing_rollout_path(path.as_path()) .await .is_some() - && let Some(resolved) = resolve_path_in_scope(store, thread_id, path, scope).await? + && let Some(resolved) = + resolve_path_in_scope(store, thread_id, path, scope, /*session_meta*/ None).await? { return Ok(Some(resolved)); } @@ -95,13 +131,16 @@ async fn resolve( if let Some(path) = codex_rollout::existing_rollout_path(metadata.rollout_path.as_path()).await { - let belongs_to_thread = - match codex_rollout::read_session_meta_line(path.as_path()).await { - Ok(session_meta) => session_meta.meta.id == thread_id, - Err(_) => true, - }; - if belongs_to_thread { - return resolve_path_in_scope(store, thread_id, path, scope).await; + let session_meta = codex_rollout::read_session_meta_line(&path) + .await + .ok() + .map(|line| line.meta); + if session_meta + .as_ref() + .is_none_or(|meta| meta.id == thread_id) + { + return resolve_path_in_scope(store, thread_id, path, scope, session_meta) + .await; } } if metadata.history_mode == ThreadHistoryMode::Paginated { @@ -116,15 +155,21 @@ async fn resolve( } } } + // The fallback can deserialize the full rollout while reseeding a missing SQLite row. + let fallback_state_db = match read_repair { + ReadRepair::Enabled => state_db_ctx.as_deref(), + ReadRepair::Disabled => None, + }; if let Some(path) = find_thread_path_by_id_str( store.config.codex_home.as_path(), &thread_id.to_string(), - state_db_ctx.as_deref(), + fallback_state_db, ) .await .map_err(|err| ThreadStoreError::InvalidRequest { message: format!("failed to locate thread id {thread_id}: {err}"), - })? && let Some(resolved) = resolve_path_in_scope(store, thread_id, path, scope).await? + })? && let Some(resolved) = + resolve_path_in_scope(store, thread_id, path, scope, /*session_meta*/ None).await? { return Ok(Some(resolved)); } @@ -134,14 +179,16 @@ async fn resolve( let path = find_archived_thread_path_by_id_str( store.config.codex_home.as_path(), &thread_id.to_string(), - state_db_ctx.as_deref(), + fallback_state_db, ) .await .map_err(|err| ThreadStoreError::InvalidRequest { message: format!("failed to locate archived thread id {thread_id}: {err}"), })?; match path { - Some(path) => resolve_path_in_scope(store, thread_id, path, scope).await, + Some(path) => { + resolve_path_in_scope(store, thread_id, path, scope, /*session_meta*/ None).await + } None => Ok(None), } } @@ -151,12 +198,40 @@ async fn resolve_path_in_scope( thread_id: ThreadId, path: PathBuf, scope: LookupScope, + session_meta: Option, ) -> ThreadStoreResult> { let location = location_for_path(store, path.as_path()); if !scope.accepts(location) { return Ok(None); } - resolve_path(thread_id, path, location).await.map(Some) + let rollout_id = match codex_rollout::rollout_id_from_path(path.as_path()) { + Some(rollout_id) => rollout_id, + None => { + let history_mode = match &session_meta { + Some(meta) => meta.history_mode, + None => { + codex_rollout::read_session_meta_line(&path) + .await + .map_err(|err| ThreadStoreError::Internal { + message: format!( + "failed to read session metadata {}: {err}", + path.display() + ), + })? + .meta + .history_mode + } + }; + rollout_id_from_path_or_legacy_thread_id(path.as_path(), thread_id, history_mode)? + } + }; + Ok(Some(ResolvedThreadRollout { + thread_id, + rollout_id, + path, + location, + session_meta, + })) } fn location_for_path(store: &LocalThreadStore, path: &std::path::Path) -> RolloutLocation { @@ -167,32 +242,6 @@ fn location_for_path(store: &LocalThreadStore, path: &std::path::Path) -> Rollou } } -async fn resolve_path( - thread_id: ThreadId, - path: PathBuf, - location: RolloutLocation, -) -> ThreadStoreResult { - let rollout_id = match codex_rollout::rollout_id_from_path(path.as_path()) { - Some(rollout_id) => rollout_id, - None => { - let history_mode = codex_rollout::read_session_meta_line(path.as_path()) - .await - .map_err(|err| ThreadStoreError::Internal { - message: format!("failed to read session metadata {}: {err}", path.display()), - })? - .meta - .history_mode; - rollout_id_from_path_or_legacy_thread_id(path.as_path(), thread_id, history_mode)? - } - }; - Ok(ResolvedThreadRollout { - thread_id, - rollout_id, - path, - location, - }) -} - /// Returns the immutable rollout ID for a path while preserving legacy noncanonical filenames. pub(super) fn rollout_id_from_path_or_legacy_thread_id( path: &std::path::Path, diff --git a/codex-rs/thread-store/src/store.rs b/codex-rs/thread-store/src/store.rs index 31eb852fc6..d41bc56374 100644 --- a/codex-rs/thread-store/src/store.rs +++ b/codex-rs/thread-store/src/store.rs @@ -1,4 +1,5 @@ use codex_protocol::ThreadId; +use codex_protocol::protocol::SessionMeta; use codex_protocol::protocol::ThreadHistoryMode; use codex_protocol::realtime::RealtimeItem; use codex_rollout::ResponseItemEnvelope; @@ -287,6 +288,33 @@ pub trait ThreadStore: Any + Send + Sync { params: LoadThreadHistoryParams, ) -> ThreadStoreFuture<'_, StoredThreadHistory>; + /// Returns canonical session metadata; filesystem stores read only the rollout header. + fn read_session_meta( + &self, + params: LoadThreadHistoryParams, + ) -> ThreadStoreFuture<'_, SessionMeta> { + Box::pin(async move { + let thread_id = params.thread_id; + let find_meta = |items: Vec| { + items.into_iter().find_map(|item| match item { + RolloutItem::SessionMeta(meta) if meta.meta.id == thread_id => Some(meta.meta), + _ => None, + }) + }; + match self.load_latest_model_context(params.clone()).await { + Ok(context) => { + if let Some(meta) = find_meta(context.items) { + return Ok(meta); + } + } + Err(ThreadStoreError::Unsupported { .. }) => {} + Err(err) => return Err(err), + } + find_meta(self.load_history(params).await?.items) + .ok_or(ThreadStoreError::ThreadNotFound { thread_id }) + }) + } + /// Loads one logical call from authoritative persisted history. Separated-frame stores /// must override this method to include their frame table; a lagging projection must fail /// rather than report that the session is absent.