Base: codex-main originale (prima del fork aKode)
This commit is contained in:
86
codex-rs/thread-store/src/error.rs
Normal file
86
codex-rs/thread-store/src/error.rs
Normal file
@@ -0,0 +1,86 @@
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::protocol::ThreadHistoryMode;
|
||||
|
||||
/// Result type returned by thread-store operations.
|
||||
pub type ThreadStoreResult<T> = Result<T, ThreadStoreError>;
|
||||
|
||||
pub(crate) fn reject_paginated_history_mode(
|
||||
history_mode: ThreadHistoryMode,
|
||||
) -> ThreadStoreResult<()> {
|
||||
if matches!(history_mode, ThreadHistoryMode::Paginated) {
|
||||
return Err(ThreadStoreError::Unsupported {
|
||||
operation: "paginated_threads",
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Error type shared by thread-store implementations.
|
||||
///
|
||||
/// Implementations must explicitly distinguish known transient failures from writes whose
|
||||
/// outcome is unknown. These categories carry information only: the operation owner decides
|
||||
/// whether and how to recover, and no variant automatically triggers a retry.
|
||||
#[derive(Clone, Debug, thiserror::Error)]
|
||||
pub enum ThreadStoreError {
|
||||
/// The requested thread does not exist in this store.
|
||||
#[error("thread {thread_id} not found")]
|
||||
ThreadNotFound {
|
||||
/// Thread id requested by the caller.
|
||||
thread_id: ThreadId,
|
||||
},
|
||||
|
||||
/// The caller supplied invalid request data.
|
||||
#[error("invalid thread-store request: {message}")]
|
||||
InvalidRequest {
|
||||
/// User-facing explanation of the invalid request.
|
||||
message: String,
|
||||
},
|
||||
|
||||
/// The operation conflicted with current store state. This alone does not imply retryability.
|
||||
#[error("thread-store conflict: {message}")]
|
||||
Conflict {
|
||||
/// User-facing explanation of the conflict.
|
||||
message: String,
|
||||
},
|
||||
|
||||
/// The store implementation does not support this operation yet.
|
||||
#[error("thread-store unsupported operation: {operation}")]
|
||||
Unsupported {
|
||||
/// Stable operation name for callers that need to map unsupported operations.
|
||||
operation: &'static str,
|
||||
},
|
||||
|
||||
/// A transient failure for which retrying the operation is safe.
|
||||
///
|
||||
/// For a write, the implementation must know the failed attempt did not commit. Otherwise
|
||||
/// use [`Self::OutcomeUnknown`]. Retry scheduling and limits belong to the operation owner.
|
||||
#[error("thread-store retryable error: {message}")]
|
||||
Retryable {
|
||||
/// User-facing explanation of the transient failure.
|
||||
message: String,
|
||||
},
|
||||
|
||||
/// A write failed to report a definitive outcome and may already have committed.
|
||||
///
|
||||
/// The operation owner must reconcile the stored state or use an idempotent replay strategy
|
||||
/// before retrying. This must not be treated as an ordinary retryable failure.
|
||||
#[error("thread-store write outcome unknown: {message}")]
|
||||
OutcomeUnknown {
|
||||
/// User-facing explanation of why the write outcome is uncertain.
|
||||
message: String,
|
||||
},
|
||||
|
||||
/// Catch-all for implementation failures that do not fit a more specific category.
|
||||
///
|
||||
/// This includes unclassified failures: callers must not infer retryability or whether a
|
||||
/// write committed from this variant or its message.
|
||||
#[error("thread-store internal error: {message}")]
|
||||
Internal {
|
||||
/// User-facing explanation of the implementation failure.
|
||||
message: String,
|
||||
},
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "error_tests.rs"]
|
||||
mod tests;
|
||||
23
codex-rs/thread-store/src/error_tests.rs
Normal file
23
codex-rs/thread-store/src/error_tests.rs
Normal file
@@ -0,0 +1,23 @@
|
||||
//! Verifies conservative classification at the shared storage error boundary.
|
||||
|
||||
use super::ThreadStoreError;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn unclassified_sqlx_failures_remain_internal() {
|
||||
for error in [
|
||||
sqlx::Error::PoolTimedOut,
|
||||
sqlx::Error::Io(std::io::Error::new(
|
||||
std::io::ErrorKind::ConnectionReset,
|
||||
"connection lost after write",
|
||||
)),
|
||||
sqlx::Error::Protocol("retryable conflict; outcome unknown".to_owned()),
|
||||
] {
|
||||
let expected = format!("failed to access thread history: {error}");
|
||||
let error = ThreadStoreError::from(error);
|
||||
let ThreadStoreError::Internal { message } = error else {
|
||||
panic!("unclassified SQLx failure must remain internal: {error:?}");
|
||||
};
|
||||
assert_eq!(message, expected);
|
||||
}
|
||||
}
|
||||
1227
codex-rs/thread-store/src/in_memory.rs
Normal file
1227
codex-rs/thread-store/src/in_memory.rs
Normal file
File diff suppressed because it is too large
Load Diff
126
codex-rs/thread-store/src/lib.rs
Normal file
126
codex-rs/thread-store/src/lib.rs
Normal file
@@ -0,0 +1,126 @@
|
||||
//! Storage-neutral thread persistence interfaces.
|
||||
//!
|
||||
//! Application code should treat [`codex_protocol::ThreadId`] as the only durable thread handle.
|
||||
//! Implementations are responsible for resolving that id to local rollout files, RPC requests, or
|
||||
//! any other backing store.
|
||||
|
||||
mod error;
|
||||
mod in_memory;
|
||||
mod live_thread;
|
||||
mod local;
|
||||
mod local_history_account;
|
||||
mod original_history;
|
||||
mod projects;
|
||||
mod queue_store;
|
||||
mod store;
|
||||
mod thread_attachments;
|
||||
mod thread_metadata_sync;
|
||||
mod thread_sections;
|
||||
mod types;
|
||||
|
||||
pub use codex_state::AddThreadAttachmentOutcome;
|
||||
pub use codex_state::MAX_QUEUE_ITEMS;
|
||||
pub use codex_state::MAX_THREAD_ATTACHMENT_PAYLOAD_BYTES;
|
||||
pub use codex_state::ProjectSortKey;
|
||||
pub use codex_state::QueuedUserSubmissionRecord;
|
||||
pub use codex_state::RemoveThreadAttachmentOutcome;
|
||||
pub use codex_state::ThreadAttachment;
|
||||
pub use codex_state::ThreadAttachmentArchiveFilter;
|
||||
pub use codex_state::ThreadAttachmentOwner;
|
||||
pub use codex_state::ThreadAttachmentOwnerPage;
|
||||
pub use codex_state::ThreadAttachmentPage;
|
||||
pub use error::ThreadStoreError;
|
||||
pub use error::ThreadStoreResult;
|
||||
pub use in_memory::InMemoryThreadStore;
|
||||
pub use in_memory::InMemoryThreadStoreCalls;
|
||||
pub use live_thread::LiveThread;
|
||||
pub use live_thread::LiveThreadInitGuard;
|
||||
pub use local::LocalThreadStore;
|
||||
pub use local::LocalThreadStoreConfig;
|
||||
pub use local::RolloutMigrationFailureReason;
|
||||
pub use local::RolloutMigrationMode;
|
||||
pub use local::RolloutMigrationOptions;
|
||||
pub use local::RolloutMigrationOutcome;
|
||||
pub use local::RolloutMigrationProgress;
|
||||
pub use local::RolloutMigrationReport;
|
||||
pub use local::RolloutMigrationStatus;
|
||||
pub use local_history_account::LocalHistoryAccount;
|
||||
pub use original_history::OriginalHistoryItem;
|
||||
pub use original_history::OriginalHistoryRead;
|
||||
pub use original_history::OriginalHistoryRequest;
|
||||
pub use projects::CreateProjectParams;
|
||||
pub use projects::CreatedProject;
|
||||
pub use projects::DeletedProject;
|
||||
pub use projects::ListProjectsParams;
|
||||
pub use projects::MoveProjectParams;
|
||||
pub use projects::ProjectMoveOutcome;
|
||||
pub use projects::StoredProject;
|
||||
pub use projects::StoredProjectRoot;
|
||||
pub use projects::StoredProjectsPage;
|
||||
pub use projects::UpdateProjectParams;
|
||||
pub use projects::UpdatedProject;
|
||||
pub use queue_store::LocalQueueStore;
|
||||
pub use queue_store::QueueStore;
|
||||
pub use store::PersistContext;
|
||||
pub use store::ThreadStore;
|
||||
pub use store::ThreadStoreFuture;
|
||||
pub use store::ThreadStoreResumePreparation;
|
||||
pub use thread_attachments::AddThreadAttachmentParams;
|
||||
pub use thread_attachments::ListThreadAttachmentThreadsParams;
|
||||
pub use thread_attachments::ListThreadAttachmentsParams;
|
||||
pub use thread_attachments::RemoveThreadAttachmentParams;
|
||||
pub use thread_sections::CreateThreadSectionParams;
|
||||
pub use thread_sections::DeleteThreadSectionParams;
|
||||
pub use thread_sections::ListThreadSectionsParams;
|
||||
pub use thread_sections::RenameThreadSectionParams;
|
||||
pub use thread_sections::StoredThreadSection;
|
||||
pub use thread_sections::StoredThreadSectionsPage;
|
||||
pub use types::AppendThreadItemsParams;
|
||||
pub use types::ArchiveThreadParams;
|
||||
pub use types::ArchiveThreadsParams;
|
||||
pub use types::ClearableField;
|
||||
pub use types::CreateThreadParams;
|
||||
pub use types::DeleteThreadParams;
|
||||
pub use types::DeleteThreadsParams;
|
||||
pub use types::ExtraConfig;
|
||||
pub use types::ForkBoundary;
|
||||
pub use types::GitInfoPatch;
|
||||
pub use types::ItemPage;
|
||||
pub use types::ItemSortKey;
|
||||
pub use types::ListItemsParams;
|
||||
pub use types::ListItemsPosition;
|
||||
pub use types::ListThreadsParams;
|
||||
pub use types::ListTimelineParams;
|
||||
pub use types::ListTurnsParams;
|
||||
pub use types::LoadThreadHistoryParams;
|
||||
pub use types::MoveThreadToSectionParams;
|
||||
pub use types::PrepareForkParams;
|
||||
pub use types::PreparedFork;
|
||||
pub use types::ReadThreadByRolloutPathParams;
|
||||
pub use types::ReadThreadParams;
|
||||
pub use types::ResumeThreadParams;
|
||||
pub use types::RevertThreadParams;
|
||||
pub use types::SearchTextRange;
|
||||
pub use types::SearchThreadOccurrencesParams;
|
||||
pub use types::SearchThreadsParams;
|
||||
pub use types::SortDirection;
|
||||
pub use types::StoredModelContext;
|
||||
pub use types::StoredThread;
|
||||
pub use types::StoredThreadHistory;
|
||||
pub use types::StoredThreadItem;
|
||||
pub use types::StoredThreadOccurrence;
|
||||
pub use types::StoredThreadSearchResult;
|
||||
pub use types::StoredTurn;
|
||||
pub use types::StoredTurnError;
|
||||
pub use types::StoredTurnItemsView;
|
||||
pub use types::StoredTurnStatus;
|
||||
pub use types::ThreadMetadataPatch;
|
||||
pub use types::ThreadOccurrenceSearchPage;
|
||||
pub use types::ThreadPage;
|
||||
pub use types::ThreadPersistenceMetadata;
|
||||
pub use types::ThreadRelationFilter;
|
||||
pub use types::ThreadSearchPage;
|
||||
pub use types::ThreadSortKey;
|
||||
pub use types::TimelinePage;
|
||||
pub use types::TurnPage;
|
||||
pub use types::UpdateThreadMetadataParams;
|
||||
466
codex-rs/thread-store/src/live_thread.rs
Normal file
466
codex-rs/thread-store/src/live_thread.rs
Normal file
@@ -0,0 +1,466 @@
|
||||
use std::future::Future;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::protocol::ThreadHistoryMode;
|
||||
use codex_protocol::protocol::ThreadMemoryMode;
|
||||
use codex_rollout::RolloutItem;
|
||||
use codex_rollout::RolloutPersistenceTelemetry;
|
||||
use codex_rollout::measure_and_filter_rollout_items;
|
||||
use codex_rollout::persisted_rollout_items;
|
||||
use tokio::sync::Mutex;
|
||||
use tracing::warn;
|
||||
|
||||
use crate::AppendThreadItemsParams;
|
||||
use crate::CreateThreadParams;
|
||||
use crate::LoadThreadHistoryParams;
|
||||
use crate::LocalThreadStore;
|
||||
use crate::PersistContext;
|
||||
use crate::ReadThreadParams;
|
||||
use crate::ResumeThreadParams;
|
||||
use crate::StoredThread;
|
||||
use crate::StoredThreadHistory;
|
||||
use crate::ThreadMetadataPatch;
|
||||
use crate::ThreadStore;
|
||||
use crate::ThreadStoreError;
|
||||
use crate::ThreadStoreFuture;
|
||||
use crate::ThreadStoreResult;
|
||||
use crate::ThreadStoreResumePreparation;
|
||||
use crate::UpdateThreadMetadataParams;
|
||||
use crate::thread_metadata_sync::ThreadMetadataSync;
|
||||
|
||||
/// Handle for an active thread's persistence lifecycle.
|
||||
///
|
||||
/// `LiveThread` keeps lifecycle decisions with the caller while delegating storage details to
|
||||
/// [`ThreadStore`]. Local stores may use a rollout file internally and remote stores may use a
|
||||
/// service, but session code should only need this handle for the active thread.
|
||||
#[derive(Clone)]
|
||||
pub struct LiveThread {
|
||||
thread_id: ThreadId,
|
||||
history_mode: ThreadHistoryMode,
|
||||
thread_store: Arc<dyn ThreadStore>,
|
||||
metadata_sync: Arc<Mutex<ThreadMetadataSync>>,
|
||||
persistence_telemetry: RolloutPersistenceTelemetry,
|
||||
}
|
||||
|
||||
/// Owns persistence acquisition and its live thread while initialization is still fallible.
|
||||
///
|
||||
/// If initialization returns early after persistence has been opened, dropping this guard discards
|
||||
/// the live writer without forcing lazy in-memory state to become durable. Call [`commit`] once the
|
||||
/// session owns the live thread for normal operation. Cancellation leaves an in-flight acquisition
|
||||
/// owned by the guard: cleanup waits for it to finish before discarding any acquired writer.
|
||||
#[derive(Default)]
|
||||
pub struct LiveThreadInitGuard {
|
||||
live_thread: Option<LiveThread>,
|
||||
acquiring: Option<ThreadStoreFuture<'static, LiveThread>>,
|
||||
}
|
||||
|
||||
impl LiveThreadInitGuard {
|
||||
pub fn new(live_thread: Option<LiveThread>) -> Self {
|
||||
Self {
|
||||
live_thread,
|
||||
acquiring: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Retains the operation even if the caller stops waiting. Store operations may install a
|
||||
/// writer before returning or delegate to another runtime, so they cannot simply be dropped.
|
||||
pub async fn acquire(
|
||||
&mut self,
|
||||
acquisition: impl Future<Output = ThreadStoreResult<LiveThread>> + Send + 'static,
|
||||
) -> ThreadStoreResult<LiveThread> {
|
||||
assert!(self.live_thread.is_none() && self.acquiring.is_none());
|
||||
self.acquiring = Some(Box::pin(acquisition));
|
||||
self.finish_acquisition().await?;
|
||||
self.live_thread
|
||||
.clone()
|
||||
.ok_or_else(|| ThreadStoreError::Internal {
|
||||
message: "persistence acquisition returned no live thread".to_owned(),
|
||||
})
|
||||
}
|
||||
|
||||
async fn finish_acquisition(&mut self) -> ThreadStoreResult<()> {
|
||||
if let Some(acquiring) = self.acquiring.as_mut() {
|
||||
let result = acquiring.await;
|
||||
self.acquiring = None;
|
||||
self.live_thread = Some(result?);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn as_ref(&self) -> Option<&LiveThread> {
|
||||
self.live_thread.as_ref()
|
||||
}
|
||||
|
||||
pub fn commit(&mut self) {
|
||||
self.live_thread = None;
|
||||
}
|
||||
|
||||
pub async fn discard(&mut self) -> ThreadStoreResult<()> {
|
||||
self.finish_acquisition().await?;
|
||||
let Some(live_thread) = self.live_thread.take() else {
|
||||
return Ok(());
|
||||
};
|
||||
live_thread.discard().await
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for LiveThreadInitGuard {
|
||||
fn drop(&mut self) {
|
||||
if self.live_thread.is_none() && self.acquiring.is_none() {
|
||||
return;
|
||||
}
|
||||
let Ok(handle) = tokio::runtime::Handle::try_current() else {
|
||||
warn!("failed to discard thread persistence for failed session init: no Tokio runtime");
|
||||
return;
|
||||
};
|
||||
let acquiring = self.acquiring.take();
|
||||
let live_thread = self.live_thread.take();
|
||||
handle.spawn(async move {
|
||||
let live_thread = match acquiring {
|
||||
Some(acquiring) => acquiring.await.ok(),
|
||||
None => live_thread,
|
||||
};
|
||||
if let Some(live_thread) = live_thread
|
||||
&& let Err(err) = live_thread.discard().await
|
||||
{
|
||||
warn!("failed to discard thread persistence for failed session init: {err}");
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
impl LiveThread {
|
||||
pub async fn create(
|
||||
thread_store: Arc<dyn ThreadStore>,
|
||||
params: CreateThreadParams,
|
||||
) -> ThreadStoreResult<Self> {
|
||||
let thread_id = params.thread_id;
|
||||
let history_mode = params.history_mode;
|
||||
let metadata_sync = ThreadMetadataSync::for_create(¶ms).await;
|
||||
thread_store.create_thread(params).await?;
|
||||
Ok(Self {
|
||||
thread_id,
|
||||
history_mode,
|
||||
thread_store,
|
||||
metadata_sync: Arc::new(Mutex::new(metadata_sync)),
|
||||
persistence_telemetry: RolloutPersistenceTelemetry::new(thread_id),
|
||||
})
|
||||
}
|
||||
|
||||
/// Create a child thread with inherited model context already durable.
|
||||
///
|
||||
/// The boundary belongs in session metadata before the copied prefix is written so history
|
||||
/// projection can distinguish inherited context from the child's own records immediately.
|
||||
pub async fn create_with_inherited_model_context(
|
||||
thread_store: Arc<dyn ThreadStore>,
|
||||
mut params: CreateThreadParams,
|
||||
inherited_model_context: &[RolloutItem],
|
||||
guard: &mut LiveThreadInitGuard,
|
||||
) -> ThreadStoreResult<Self> {
|
||||
let persisted_prefix_item_count =
|
||||
persisted_rollout_items(inherited_model_context, params.history_mode).len();
|
||||
params.subagent_history_start_ordinal = Some(
|
||||
u64::try_from(persisted_prefix_item_count)
|
||||
.map_err(|_| ThreadStoreError::Internal {
|
||||
message: "inherited model context is too large".to_string(),
|
||||
})?
|
||||
.checked_add(1)
|
||||
.ok_or_else(|| ThreadStoreError::Internal {
|
||||
message: "inherited model context is too large".to_string(),
|
||||
})?,
|
||||
);
|
||||
let live_thread = guard.acquire(Self::create(thread_store, params)).await?;
|
||||
live_thread
|
||||
.persist_appended_items(inherited_model_context)
|
||||
.await?;
|
||||
Ok(live_thread)
|
||||
}
|
||||
|
||||
/// Reopens persistence and returns the replay history selected under writer ownership.
|
||||
pub async fn resume(
|
||||
thread_store: Arc<dyn ThreadStore>,
|
||||
history_mode: ThreadHistoryMode,
|
||||
mut params: ResumeThreadParams,
|
||||
resume_preparation: Option<ThreadStoreResumePreparation>,
|
||||
) -> ThreadStoreResult<(Self, Arc<Vec<RolloutItem>>)> {
|
||||
let thread_id = params.thread_id;
|
||||
let metadata = if history_mode == ThreadHistoryMode::Paginated
|
||||
&& let Some(local_store) = thread_store.as_any().downcast_ref::<LocalThreadStore>()
|
||||
&& let Some(state_db) = local_store.state_db().await
|
||||
{
|
||||
state_db
|
||||
.get_thread(thread_id)
|
||||
.await
|
||||
.map_err(|err| ThreadStoreError::Internal {
|
||||
message: format!("failed to read thread metadata for {thread_id}: {err}"),
|
||||
})?
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let history = match resume_preparation {
|
||||
Some(preparation) => {
|
||||
thread_store
|
||||
.resume_thread_with_preparation(params.clone(), preparation)
|
||||
.await?
|
||||
}
|
||||
None => thread_store.resume_thread(params.clone()).await?,
|
||||
};
|
||||
params.history = Some(Arc::clone(&history));
|
||||
let metadata_sync = ThreadMetadataSync::for_resume(¶ms, metadata.as_ref());
|
||||
Ok((
|
||||
Self {
|
||||
thread_id,
|
||||
history_mode,
|
||||
thread_store,
|
||||
metadata_sync: Arc::new(Mutex::new(metadata_sync)),
|
||||
persistence_telemetry: RolloutPersistenceTelemetry::new(thread_id),
|
||||
},
|
||||
history,
|
||||
))
|
||||
}
|
||||
|
||||
#[tracing::instrument(
|
||||
level = "trace",
|
||||
skip_all,
|
||||
fields(item_count = raw_items.len())
|
||||
)]
|
||||
pub async fn append_items(&self, raw_items: &[RolloutItem]) -> ThreadStoreResult<()> {
|
||||
let items = self.persist_appended_items(raw_items).await?;
|
||||
if items.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let update = self
|
||||
.metadata_sync
|
||||
.lock()
|
||||
.await
|
||||
.observe_appended_items(items.as_slice());
|
||||
if let Some(update) = update {
|
||||
self.thread_store
|
||||
.record_thread_metadata(UpdateThreadMetadataParams {
|
||||
thread_id: self.thread_id,
|
||||
patch: update.patch.clone(),
|
||||
include_archived: true,
|
||||
})
|
||||
.await?;
|
||||
self.metadata_sync
|
||||
.lock()
|
||||
.await
|
||||
.mark_pending_update_applied(&update);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn persist_appended_items(
|
||||
&self,
|
||||
raw_items: &[RolloutItem],
|
||||
) -> ThreadStoreResult<Vec<RolloutItem>> {
|
||||
// Empty appends are intentionally ignored rather than represented as zero-sized batches.
|
||||
if raw_items.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let (items, measurement) = if self.persistence_telemetry.is_enabled() {
|
||||
let (items, measurement) =
|
||||
measure_and_filter_rollout_items(raw_items, self.history_mode);
|
||||
(items, Some(measurement))
|
||||
} else {
|
||||
(persisted_rollout_items(raw_items, self.history_mode), None)
|
||||
};
|
||||
self.thread_store
|
||||
.append_items(AppendThreadItemsParams {
|
||||
thread_id: self.thread_id,
|
||||
items: raw_items.to_vec(),
|
||||
})
|
||||
.await?;
|
||||
if let Some(measurement) = measurement.as_ref() {
|
||||
self.persistence_telemetry
|
||||
.record_batch(raw_items, measurement);
|
||||
}
|
||||
Ok(items)
|
||||
}
|
||||
|
||||
pub async fn persist(&self, context: PersistContext) -> ThreadStoreResult<()> {
|
||||
if context.allows_background_persistence() {
|
||||
let update = self
|
||||
.metadata_sync
|
||||
.lock()
|
||||
.await
|
||||
.take_pending_update_for_existing_history();
|
||||
self.apply_pending_metadata_update(update, context).await?;
|
||||
}
|
||||
self.thread_store
|
||||
.persist_thread(self.thread_id, context)
|
||||
.await?;
|
||||
let update = self.metadata_sync.lock().await.take_pending_update();
|
||||
self.apply_pending_metadata_update(update, context).await
|
||||
}
|
||||
|
||||
pub async fn flush(&self) -> ThreadStoreResult<()> {
|
||||
self.thread_store.flush_thread(self.thread_id).await?;
|
||||
self.flush_pending_metadata_update_for_existing_history()
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn shutdown(&self) -> ThreadStoreResult<()> {
|
||||
let metadata_result = self
|
||||
.flush_pending_metadata_update_for_existing_history()
|
||||
.await;
|
||||
let shutdown_result = self.thread_store.shutdown_thread(self.thread_id).await;
|
||||
match (metadata_result, shutdown_result) {
|
||||
(Err(metadata_error), Err(shutdown_error)) => Err(ThreadStoreError::Internal {
|
||||
message: format!(
|
||||
"thread metadata update failed: {metadata_error}; thread shutdown failed: {shutdown_error}"
|
||||
),
|
||||
}),
|
||||
(Err(metadata_error), Ok(())) => Err(metadata_error),
|
||||
(Ok(()), result) => result,
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn discard(&self) -> ThreadStoreResult<()> {
|
||||
self.thread_store.discard_thread(self.thread_id).await
|
||||
}
|
||||
|
||||
pub async fn load_history(
|
||||
&self,
|
||||
include_archived: bool,
|
||||
) -> ThreadStoreResult<StoredThreadHistory> {
|
||||
self.thread_store
|
||||
.load_history(LoadThreadHistoryParams {
|
||||
thread_id: self.thread_id,
|
||||
include_archived,
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn read_thread(
|
||||
&self,
|
||||
include_archived: bool,
|
||||
include_history: bool,
|
||||
) -> ThreadStoreResult<StoredThread> {
|
||||
self.thread_store
|
||||
.read_thread(ReadThreadParams {
|
||||
thread_id: self.thread_id,
|
||||
include_archived,
|
||||
include_history,
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn update_memory_mode(
|
||||
&self,
|
||||
mode: ThreadMemoryMode,
|
||||
include_archived: bool,
|
||||
) -> ThreadStoreResult<()> {
|
||||
self.flush_pending_metadata_update().await?;
|
||||
self.thread_store
|
||||
.update_thread_metadata(UpdateThreadMetadataParams {
|
||||
thread_id: self.thread_id,
|
||||
patch: ThreadMetadataPatch {
|
||||
memory_mode: Some(mode),
|
||||
..Default::default()
|
||||
},
|
||||
include_archived,
|
||||
})
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Updates metadata while preserving this API's materialized-thread contract.
|
||||
///
|
||||
/// Stores may successfully return no thread for a no-op update, so this reads the thread as a
|
||||
/// fallback in that case.
|
||||
pub async fn update_metadata(
|
||||
&self,
|
||||
patch: ThreadMetadataPatch,
|
||||
include_archived: bool,
|
||||
) -> ThreadStoreResult<StoredThread> {
|
||||
self.flush_pending_metadata_update().await?;
|
||||
let updated = self
|
||||
.thread_store
|
||||
.update_thread_metadata(UpdateThreadMetadataParams {
|
||||
thread_id: self.thread_id,
|
||||
patch,
|
||||
include_archived,
|
||||
})
|
||||
.await?;
|
||||
match updated {
|
||||
Some(thread) => Ok(thread),
|
||||
None => {
|
||||
self.read_thread(include_archived, /*include_history*/ false)
|
||||
.await
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the live local rollout path for legacy local-only callers.
|
||||
///
|
||||
/// Remote stores do not expose rollout files, so they return `Ok(None)`.
|
||||
pub async fn local_rollout_path(&self) -> ThreadStoreResult<Option<PathBuf>> {
|
||||
let Some(local_store) = self
|
||||
.thread_store
|
||||
.as_any()
|
||||
.downcast_ref::<LocalThreadStore>()
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
local_store
|
||||
.live_rollout_path(self.thread_id)
|
||||
.await
|
||||
.map(Some)
|
||||
}
|
||||
|
||||
/// Selects a local feedback input only after its writer has materialized it.
|
||||
pub async fn feedback_rollout_path(&self) -> ThreadStoreResult<Option<PathBuf>> {
|
||||
let Some(local_store) = self
|
||||
.thread_store
|
||||
.as_any()
|
||||
.downcast_ref::<LocalThreadStore>()
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
local_store.feedback_rollout_path(self.thread_id).await
|
||||
}
|
||||
|
||||
async fn flush_pending_metadata_update(&self) -> ThreadStoreResult<()> {
|
||||
let update = self.metadata_sync.lock().await.take_pending_update();
|
||||
self.apply_pending_metadata_update(update, PersistContext::Standard)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn flush_pending_metadata_update_for_existing_history(&self) -> ThreadStoreResult<()> {
|
||||
let update = self
|
||||
.metadata_sync
|
||||
.lock()
|
||||
.await
|
||||
.take_pending_update_for_existing_history();
|
||||
self.apply_pending_metadata_update(update, PersistContext::Standard)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn apply_pending_metadata_update(
|
||||
&self,
|
||||
update: Option<crate::thread_metadata_sync::PendingThreadMetadataPatch>,
|
||||
context: PersistContext,
|
||||
) -> ThreadStoreResult<()> {
|
||||
let Some(update) = update else {
|
||||
return Ok(());
|
||||
};
|
||||
let params = UpdateThreadMetadataParams {
|
||||
thread_id: self.thread_id,
|
||||
patch: update.patch.clone(),
|
||||
include_archived: true,
|
||||
};
|
||||
if context == PersistContext::Standard {
|
||||
self.thread_store.update_thread_metadata(params).await?;
|
||||
} else {
|
||||
self.thread_store.record_thread_metadata(params).await?;
|
||||
}
|
||||
self.metadata_sync
|
||||
.lock()
|
||||
.await
|
||||
.mark_pending_update_applied(&update);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
371
codex-rs/thread-store/src/local/archive_thread.rs
Normal file
371
codex-rs/thread-store/src/local/archive_thread.rs
Normal file
@@ -0,0 +1,371 @@
|
||||
use super::LocalThreadStore;
|
||||
use super::helpers::owned_rollout_paths_from_index;
|
||||
use super::helpers::restore_rollout_moves;
|
||||
use super::helpers::rollout_path_is_archived;
|
||||
use super::helpers::scoped_rollout_path;
|
||||
use super::helpers::validated_rollout_file_name;
|
||||
use crate::ArchiveThreadsParams;
|
||||
use crate::ThreadStoreError;
|
||||
use crate::ThreadStoreResult;
|
||||
use chrono::Utc;
|
||||
use codex_rollout::RolloutReferenceIndex;
|
||||
use tracing::warn;
|
||||
|
||||
use super::thread_rollout_resolver;
|
||||
pub(super) async fn archive_threads(
|
||||
store: &LocalThreadStore,
|
||||
params: ArchiveThreadsParams,
|
||||
) -> ThreadStoreResult<Vec<codex_protocol::ThreadId>> {
|
||||
let thread_ids = params.thread_ids;
|
||||
if thread_ids.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
|
||||
let mut lock_thread_ids = params.writer_lock_thread_ids;
|
||||
lock_thread_ids.extend(thread_ids.iter().copied());
|
||||
lock_thread_ids.sort_unstable_by_key(ToString::to_string);
|
||||
lock_thread_ids.dedup();
|
||||
let mut _lifecycle_guards = Vec::with_capacity(lock_thread_ids.len());
|
||||
for thread_id in &lock_thread_ids {
|
||||
_lifecycle_guards.push(store.live_writer_locks.lock_lifecycle(*thread_id).await);
|
||||
}
|
||||
let mut _live_writer_guards = Vec::with_capacity(lock_thread_ids.len());
|
||||
for thread_id in &lock_thread_ids {
|
||||
_live_writer_guards.push(store.live_writer_locks.lock(*thread_id).await);
|
||||
if store.live_recorders.lock().await.contains_key(thread_id) {
|
||||
return Err(ThreadStoreError::Conflict {
|
||||
message: format!("thread {thread_id} already has an active writer"),
|
||||
});
|
||||
}
|
||||
}
|
||||
let _writer_guards = store.acquire_writer_locks(&lock_thread_ids).await?;
|
||||
// Only inspect active files whose names belong to the threads being archived.
|
||||
let reference_index = RolloutReferenceIndex::scan_unarchived_threads(
|
||||
store.config.codex_home.as_path(),
|
||||
&thread_ids,
|
||||
)
|
||||
.await
|
||||
.map_err(|err| ThreadStoreError::Internal {
|
||||
message: format!("failed to scan thread rollout files: {err}"),
|
||||
})?;
|
||||
|
||||
let parent_thread_id = thread_ids[0];
|
||||
let mut archived_thread_ids = Vec::new();
|
||||
for thread_id in thread_ids {
|
||||
let rollout_paths = owned_rollout_paths_from_index(&reference_index, thread_id);
|
||||
match archive_thread_with_paths(store, thread_id, rollout_paths).await {
|
||||
Ok(()) => archived_thread_ids.push(thread_id),
|
||||
Err(err) if archived_thread_ids.is_empty() => return Err(err),
|
||||
Err(err) => warn!(
|
||||
"failed to archive spawned descendant thread {thread_id} while archiving {parent_thread_id}: {err}"
|
||||
),
|
||||
}
|
||||
}
|
||||
Ok(archived_thread_ids)
|
||||
}
|
||||
|
||||
async fn archive_thread_with_paths(
|
||||
store: &LocalThreadStore,
|
||||
thread_id: codex_protocol::ThreadId,
|
||||
mut rollout_paths: Vec<std::path::PathBuf>,
|
||||
) -> ThreadStoreResult<()> {
|
||||
let state_db_ctx = store.state_db().await;
|
||||
let selected_rollout_path = thread_rollout_resolver::resolve_current(store, thread_id)
|
||||
.await?
|
||||
.map(|resolved| resolved.path)
|
||||
.ok_or_else(|| ThreadStoreError::InvalidRequest {
|
||||
message: format!("no rollout found for thread id {thread_id}"),
|
||||
})?;
|
||||
|
||||
let archive_folder = store
|
||||
.config
|
||||
.codex_home
|
||||
.join(codex_rollout::ARCHIVED_SESSIONS_SUBDIR);
|
||||
std::fs::create_dir_all(&archive_folder).map_err(|err| ThreadStoreError::Internal {
|
||||
message: format!("failed to archive thread: {err}"),
|
||||
})?;
|
||||
if !rollout_paths.contains(&selected_rollout_path) {
|
||||
rollout_paths.push(selected_rollout_path.clone());
|
||||
}
|
||||
let mut archived_path = None;
|
||||
let mut rollout_moves = Vec::new();
|
||||
for rollout_path in rollout_paths {
|
||||
if rollout_path_is_archived(store.config.codex_home.as_path(), rollout_path.as_path()) {
|
||||
continue;
|
||||
}
|
||||
let canonical_rollout_path = scoped_rollout_path(
|
||||
store.config.codex_home.join(codex_rollout::SESSIONS_SUBDIR),
|
||||
rollout_path.as_path(),
|
||||
"sessions",
|
||||
)?;
|
||||
let file_name =
|
||||
validated_rollout_file_name(canonical_rollout_path.as_path(), rollout_path.as_path())?;
|
||||
let destination = archive_folder.join(&file_name);
|
||||
if rollout_path == selected_rollout_path {
|
||||
archived_path = Some(destination.clone());
|
||||
}
|
||||
if !rollout_moves
|
||||
.iter()
|
||||
.any(|(source, _)| source == &canonical_rollout_path)
|
||||
{
|
||||
rollout_moves.push((canonical_rollout_path, destination));
|
||||
}
|
||||
}
|
||||
let archived_path = archived_path.ok_or_else(|| ThreadStoreError::Internal {
|
||||
message: format!("failed to archive selected rollout for thread {thread_id}"),
|
||||
})?;
|
||||
|
||||
for (index, (source, destination)) in rollout_moves.iter().enumerate() {
|
||||
if let Err(err) = std::fs::rename(source, destination) {
|
||||
if let Err(restore_err) = restore_rollout_moves(&rollout_moves[..index]) {
|
||||
return Err(ThreadStoreError::Internal {
|
||||
message: format!(
|
||||
"failed to archive thread: {err}; failed to restore moved rollouts: {restore_err}"
|
||||
),
|
||||
});
|
||||
}
|
||||
return Err(ThreadStoreError::Internal {
|
||||
message: format!("failed to archive thread: {err}"),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(ctx) = state_db_ctx
|
||||
&& let Err(err) = ctx
|
||||
.mark_archived(thread_id, archived_path.as_path(), Utc::now())
|
||||
.await
|
||||
{
|
||||
if let Err(restore_err) = restore_rollout_moves(&rollout_moves) {
|
||||
return Err(ThreadStoreError::Internal {
|
||||
message: format!(
|
||||
"failed to update archived thread metadata: {err}; failed to restore moved rollouts: {restore_err}"
|
||||
),
|
||||
});
|
||||
}
|
||||
return Err(ThreadStoreError::Internal {
|
||||
message: format!("failed to update archived thread metadata: {err}"),
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::time::Duration;
|
||||
|
||||
use chrono::Utc;
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::protocol::SessionSource;
|
||||
use codex_protocol::protocol::ThreadHistoryMode;
|
||||
use codex_rollout::ARCHIVED_SESSIONS_SUBDIR;
|
||||
use codex_utils_absolute_path::test_support::PathExt;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tempfile::TempDir;
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::*;
|
||||
use crate::ArchiveThreadParams;
|
||||
use crate::ListThreadsParams;
|
||||
use crate::ThreadSortKey;
|
||||
use crate::ThreadStore;
|
||||
use crate::local::LocalThreadStore;
|
||||
use crate::local::test_support::test_config;
|
||||
use crate::local::test_support::write_session_file;
|
||||
use crate::local::test_support::write_session_file_with_history_mode;
|
||||
|
||||
#[tokio::test]
|
||||
async fn archive_waits_for_fork_reservation_without_holding_writer_lock() {
|
||||
let home = TempDir::new().expect("temp dir");
|
||||
let store = LocalThreadStore::new(test_config(home.path()), /*state_db*/ None);
|
||||
let uuid = Uuid::from_u128(205);
|
||||
let thread_id = ThreadId::from_string(&uuid.to_string()).expect("valid thread id");
|
||||
let active_path = write_session_file_with_history_mode(
|
||||
home.path(),
|
||||
"2025-01-03T12-00-00",
|
||||
uuid,
|
||||
ThreadHistoryMode::Paginated,
|
||||
)
|
||||
.expect("session file");
|
||||
let reservation = store.live_writer_locks.reserve_lifecycle(thread_id).await;
|
||||
let mut archive = Box::pin(store.archive_thread(ArchiveThreadParams { thread_id }));
|
||||
|
||||
tokio::select! {
|
||||
biased;
|
||||
result = &mut archive => panic!("archive completed while the source was reserved: {result:?}"),
|
||||
_ = tokio::task::yield_now() => {}
|
||||
}
|
||||
let writer_guard = tokio::time::timeout(
|
||||
Duration::from_secs(1),
|
||||
store.live_writer_locks.lock(thread_id),
|
||||
)
|
||||
.await
|
||||
.expect("pending archive should not hold the writer lock");
|
||||
drop(writer_guard);
|
||||
drop(reservation);
|
||||
|
||||
archive.await.expect("archive reserved thread");
|
||||
assert!(!active_path.exists());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn archive_threads_rejects_owned_descendants_before_archiving_anything() {
|
||||
let home = TempDir::new().expect("temp dir");
|
||||
let store = LocalThreadStore::new(test_config(home.path()), /*state_db*/ None);
|
||||
let owner = LocalThreadStore::new(test_config(home.path()), /*state_db*/ None);
|
||||
for (parent_uuid, child_uuid, history_mode) in [
|
||||
(
|
||||
Uuid::from_u128(203),
|
||||
Uuid::from_u128(204),
|
||||
ThreadHistoryMode::Legacy,
|
||||
),
|
||||
(
|
||||
Uuid::from_u128(206),
|
||||
Uuid::from_u128(207),
|
||||
ThreadHistoryMode::Paginated,
|
||||
),
|
||||
] {
|
||||
let parent_thread_id =
|
||||
ThreadId::from_string(&parent_uuid.to_string()).expect("valid parent thread id");
|
||||
let parent_path = write_session_file_with_history_mode(
|
||||
home.path(),
|
||||
"2025-01-03T12-00-00",
|
||||
parent_uuid,
|
||||
history_mode,
|
||||
)
|
||||
.expect("parent session file");
|
||||
let child_thread_id =
|
||||
ThreadId::from_string(&child_uuid.to_string()).expect("valid child thread id");
|
||||
let child_path = write_session_file_with_history_mode(
|
||||
home.path(),
|
||||
"2025-01-03T12-00-01",
|
||||
child_uuid,
|
||||
history_mode,
|
||||
)
|
||||
.expect("child session file");
|
||||
let _owner_guard = owner
|
||||
.acquire_writer_lock(child_thread_id)
|
||||
.expect("acquire child writer lock");
|
||||
|
||||
let error = store
|
||||
.archive_threads(ArchiveThreadsParams {
|
||||
thread_ids: vec![parent_thread_id, child_thread_id],
|
||||
writer_lock_thread_ids: Vec::new(),
|
||||
})
|
||||
.await
|
||||
.expect_err("owned descendant should block archive");
|
||||
|
||||
assert!(matches!(error, ThreadStoreError::Conflict { .. }));
|
||||
assert!(parent_path.exists());
|
||||
assert!(child_path.exists());
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn archive_thread_moves_rollout_to_archived_collection() {
|
||||
let home = TempDir::new().expect("temp dir");
|
||||
let store = LocalThreadStore::new(test_config(home.path()), /*state_db*/ None);
|
||||
let uuid = Uuid::from_u128(201);
|
||||
let thread_id = ThreadId::from_string(&uuid.to_string()).expect("valid thread id");
|
||||
let active_path =
|
||||
write_session_file(home.path(), "2025-01-03T12-00-00", uuid).expect("session file");
|
||||
|
||||
store
|
||||
.archive_thread(ArchiveThreadParams { thread_id })
|
||||
.await
|
||||
.expect("archive thread");
|
||||
|
||||
assert!(!active_path.exists());
|
||||
let archived_path = home
|
||||
.path()
|
||||
.join(ARCHIVED_SESSIONS_SUBDIR)
|
||||
.join(active_path.file_name().expect("file name"));
|
||||
assert!(archived_path.exists());
|
||||
|
||||
let archived = store
|
||||
.list_threads(ListThreadsParams {
|
||||
page_size: 10,
|
||||
cursor: None,
|
||||
sort_key: ThreadSortKey::CreatedAt,
|
||||
sort_direction: crate::SortDirection::Desc,
|
||||
allowed_sources: Vec::new(),
|
||||
model_providers: None,
|
||||
cwd_filters: None,
|
||||
section: None,
|
||||
project_id: None,
|
||||
archived: true,
|
||||
search_term: None,
|
||||
relation_filter: None,
|
||||
use_state_db_only: false,
|
||||
})
|
||||
.await
|
||||
.expect("archived listing");
|
||||
assert_eq!(archived.items.len(), 1);
|
||||
assert_eq!(archived.items[0].thread_id, thread_id);
|
||||
assert_eq!(archived.items[0].rollout_path, Some(archived_path));
|
||||
assert_eq!(
|
||||
archived.items[0].archived_at,
|
||||
Some(archived.items[0].updated_at)
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn archive_thread_deduplicates_rollout_paths_and_updates_sqlite_metadata() {
|
||||
let home = TempDir::new().expect("temp dir");
|
||||
let config = test_config(home.path());
|
||||
let uuid = Uuid::from_u128(202);
|
||||
let thread_id = ThreadId::from_string(&uuid.to_string()).expect("valid thread id");
|
||||
let active_path =
|
||||
write_session_file(home.path(), "2025-01-03T12-00-00", uuid).expect("session file");
|
||||
let alternate_directory = active_path
|
||||
.parent()
|
||||
.expect("session directory")
|
||||
.join("alternate");
|
||||
std::fs::create_dir(&alternate_directory).expect("alternate session directory");
|
||||
let selected_rollout_path = alternate_directory
|
||||
.join("..")
|
||||
.join(active_path.file_name().expect("file name"));
|
||||
let runtime = codex_state::StateRuntime::init(
|
||||
codex_state::SqliteConfig::new_for_testing(home.path().abs()),
|
||||
config.default_model_provider_id.clone(),
|
||||
)
|
||||
.await
|
||||
.expect("state db should initialize");
|
||||
let store = LocalThreadStore::new(config.clone(), Some(runtime.clone()));
|
||||
runtime
|
||||
.mark_backfill_complete(/*last_watermark*/ None)
|
||||
.await
|
||||
.expect("backfill should be complete");
|
||||
let mut builder = codex_state::ThreadMetadataBuilder::new(
|
||||
thread_id,
|
||||
selected_rollout_path,
|
||||
Utc::now(),
|
||||
SessionSource::Cli,
|
||||
);
|
||||
builder.model_provider = Some(config.default_model_provider_id.clone());
|
||||
builder.cwd = home.path().to_path_buf();
|
||||
builder.cli_version = Some("test_version".to_string());
|
||||
let metadata = builder.build(config.default_model_provider_id.as_str());
|
||||
runtime
|
||||
.upsert_thread(&metadata)
|
||||
.await
|
||||
.expect("state db upsert should succeed");
|
||||
|
||||
store
|
||||
.archive_thread(ArchiveThreadParams { thread_id })
|
||||
.await
|
||||
.expect("archive thread");
|
||||
|
||||
let archived_path = home
|
||||
.path()
|
||||
.join(ARCHIVED_SESSIONS_SUBDIR)
|
||||
.join(active_path.file_name().expect("file name"));
|
||||
let updated = runtime
|
||||
.get_thread(thread_id)
|
||||
.await
|
||||
.expect("state db read should succeed")
|
||||
.expect("thread metadata should exist");
|
||||
assert_eq!(updated.rollout_path, archived_path);
|
||||
assert!(updated.archived_at.is_some());
|
||||
assert_eq!(updated.recency_at, metadata.recency_at);
|
||||
}
|
||||
}
|
||||
220
codex-rs/thread-store/src/local/compression_writer_tests.rs
Normal file
220
codex-rs/thread-store/src/local/compression_writer_tests.rs
Normal file
@@ -0,0 +1,220 @@
|
||||
//! Exercises compression through local-store ownership, including detached recorder work.
|
||||
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
use std::time::SystemTime;
|
||||
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::protocol::EventMsg;
|
||||
use codex_protocol::protocol::ThreadMemoryMode;
|
||||
use codex_protocol::protocol::UserMessageEvent;
|
||||
use codex_rollout::RolloutItem;
|
||||
use codex_rollout::RolloutRecorder;
|
||||
use codex_rollout::WriterLockCoordinator;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
use tempfile::TempDir;
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::LocalThreadStore;
|
||||
use super::test_support::test_config;
|
||||
use super::test_support::write_session_file;
|
||||
use crate::LoadThreadHistoryParams;
|
||||
use crate::ResumeThreadParams;
|
||||
use crate::ThreadMetadataPatch;
|
||||
use crate::ThreadPersistenceMetadata;
|
||||
use crate::ThreadStore;
|
||||
use crate::UpdateThreadMetadataParams;
|
||||
|
||||
type TestResult<T = ()> = Result<T, Box<dyn std::error::Error>>;
|
||||
|
||||
fn fixture() -> TestResult<(TempDir, ThreadId, PathBuf)> {
|
||||
let home = TempDir::new()?;
|
||||
let id = Uuid::new_v4();
|
||||
let path = write_session_file(home.path(), "2025-01-03T12-00-00", id)?;
|
||||
Ok((home, ThreadId::from_string(&id.to_string())?, path))
|
||||
}
|
||||
|
||||
fn age(path: &Path) -> TestResult<()> {
|
||||
fs::OpenOptions::new().write(true).open(path)?.set_times(
|
||||
fs::FileTimes::new().set_modified(SystemTime::now() - Duration::from_secs(8 * 86400)),
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn resume(thread_id: ThreadId, path: &Path, home: &Path) -> ResumeThreadParams {
|
||||
ResumeThreadParams {
|
||||
history_revision: None,
|
||||
thread_id,
|
||||
rollout_path: Some(path.to_path_buf()),
|
||||
history: None,
|
||||
include_archived: true,
|
||||
metadata: ThreadPersistenceMetadata {
|
||||
cwd: Some(home.to_path_buf()),
|
||||
model_provider: "test-provider".into(),
|
||||
memory_mode: ThreadMemoryMode::Enabled,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn message() -> RolloutItem {
|
||||
RolloutItem::EventMsg(EventMsg::UserMessage(UserMessageEvent {
|
||||
message: "acknowledged write".into(),
|
||||
..Default::default()
|
||||
}))
|
||||
}
|
||||
|
||||
async fn wait_until(ready: impl Fn() -> bool) {
|
||||
tokio::time::timeout(Duration::from_secs(10), async {
|
||||
while !ready() {
|
||||
tokio::time::sleep(Duration::from_millis(1)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("background file work completes");
|
||||
}
|
||||
|
||||
async fn compress(home: &Path) -> TestResult<()> {
|
||||
let marker = home.join(".tmp/rollout-compression.lock");
|
||||
if marker.exists() {
|
||||
fs::remove_file(&marker)?;
|
||||
}
|
||||
codex_rollout::spawn_rollout_compression_worker(
|
||||
home.to_path_buf(),
|
||||
codex_rollout::RolloutCompressionTrigger::Startup,
|
||||
);
|
||||
// The marker proves startup; the maintenance lock proves every blocking job finished.
|
||||
wait_until(|| {
|
||||
marker.exists()
|
||||
&& codex_rollout::try_acquire_rollout_maintenance_lock(home)
|
||||
.unwrap()
|
||||
.is_some()
|
||||
})
|
||||
.await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "current_thread")]
|
||||
async fn idle_recorder_retains_stable_thread_ownership_after_store_drop() -> TestResult<()> {
|
||||
let (home, thread_id, old_path) = fixture()?;
|
||||
let store = LocalThreadStore::new(test_config(home.path()), /*state_db*/ None);
|
||||
let path = old_path.with_file_name(format!(
|
||||
"rollout-2025-01-03T12-00-00-{thread_id}_{}.jsonl",
|
||||
Uuid::new_v4()
|
||||
));
|
||||
fs::rename(old_path, &path)?;
|
||||
let cold = write_session_file(home.path(), "2025-01-03T12-00-01", Uuid::new_v4())?;
|
||||
age(&cold)?;
|
||||
store
|
||||
.resume_thread(resume(thread_id, &path, home.path()))
|
||||
.await?;
|
||||
let recorder = store
|
||||
.live_recorders
|
||||
.lock()
|
||||
.await
|
||||
.get(&thread_id)
|
||||
.unwrap()
|
||||
.recorder
|
||||
.clone();
|
||||
drop(store);
|
||||
age(&path)?;
|
||||
let (mut expected, _, _) = RolloutRecorder::load_rollout_items(&path).await?;
|
||||
compress(home.path()).await?;
|
||||
assert!(path.exists());
|
||||
assert!(!path.with_extension("jsonl.zst").exists());
|
||||
assert!(cold.with_extension("jsonl.zst").exists());
|
||||
|
||||
recorder.record_canonical_items(&[message()]).await?;
|
||||
drop(recorder);
|
||||
let locks = Arc::new(WriterLockCoordinator::new(home.path()));
|
||||
// No yield since enqueueing: only the background task can own the pending write now.
|
||||
assert!(
|
||||
matches!(locks.acquire(thread_id), Err(err) if err.kind() == std::io::ErrorKind::WouldBlock)
|
||||
);
|
||||
wait_until(|| locks.acquire(thread_id).is_ok()).await;
|
||||
age(&path)?;
|
||||
compress(home.path()).await?;
|
||||
assert!(!path.exists());
|
||||
expected.push(message());
|
||||
let (actual, _, _) = RolloutRecorder::load_rollout_items(&path).await?;
|
||||
assert_eq!(json!(actual), json!(expected));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn metadata_updates_share_ownership_and_resume_compressed_rollouts() -> TestResult<()> {
|
||||
let (home, thread_id, path) = fixture()?;
|
||||
let config = test_config(home.path());
|
||||
let db = codex_state::StateRuntime::init(
|
||||
config.sqlite.clone(),
|
||||
config.default_model_provider_id.clone(),
|
||||
)
|
||||
.await?;
|
||||
let owner = LocalThreadStore::new(config.clone(), Some(db.clone()));
|
||||
owner
|
||||
.resume_thread(resume(thread_id, &path, home.path()))
|
||||
.await?;
|
||||
let competitor = LocalThreadStore::new(config, Some(db.clone()));
|
||||
let mut patch = UpdateThreadMetadataParams {
|
||||
thread_id,
|
||||
include_archived: true,
|
||||
patch: ThreadMetadataPatch {
|
||||
memory_mode: Some(ThreadMemoryMode::Enabled),
|
||||
..Default::default()
|
||||
},
|
||||
};
|
||||
owner.update_thread_metadata(patch.clone()).await?;
|
||||
let original = fs::read(&path)?;
|
||||
let indexed_mode = db.get_thread_memory_mode(thread_id).await?;
|
||||
patch.patch.memory_mode = Some(ThreadMemoryMode::Disabled);
|
||||
let error = competitor
|
||||
.update_thread_metadata(patch.clone())
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(matches!(error, crate::ThreadStoreError::Conflict { .. }));
|
||||
assert_eq!(fs::read(&path)?, original);
|
||||
assert_eq!(db.get_thread_memory_mode(thread_id).await?, indexed_mode);
|
||||
owner.update_thread_metadata(patch.clone()).await?;
|
||||
owner.shutdown_thread(thread_id).await?;
|
||||
let (items, _, _) = RolloutRecorder::load_rollout_items(&path).await?;
|
||||
let mut expected = codex_rollout::read_session_meta_line(&path).await?;
|
||||
expected.meta.memory_mode = Some("disabled".into());
|
||||
expected.git = None;
|
||||
assert_eq!(
|
||||
json!(items.last()),
|
||||
json!(Some(RolloutItem::SessionMeta(Box::new(expected.clone()))))
|
||||
);
|
||||
|
||||
age(&path)?;
|
||||
compress(home.path()).await?;
|
||||
let snapshot = competitor
|
||||
.load_history(LoadThreadHistoryParams {
|
||||
thread_id,
|
||||
include_archived: true,
|
||||
})
|
||||
.await?;
|
||||
let history = Arc::new(snapshot.items);
|
||||
let resumed = competitor
|
||||
.resume_thread(ResumeThreadParams {
|
||||
history: Some(Arc::clone(&history)),
|
||||
history_revision: snapshot.revision,
|
||||
..resume(thread_id, &path, home.path())
|
||||
})
|
||||
.await?;
|
||||
assert!(Arc::ptr_eq(&history, &resumed));
|
||||
competitor.shutdown_thread(thread_id).await?;
|
||||
age(&path)?;
|
||||
compress(home.path()).await?;
|
||||
patch.patch.memory_mode = Some(ThreadMemoryMode::Enabled);
|
||||
competitor.update_thread_metadata(patch).await?;
|
||||
expected.meta.memory_mode = Some("enabled".into());
|
||||
let (items, _, _) = RolloutRecorder::load_rollout_items(&path).await?;
|
||||
assert_eq!(
|
||||
json!(items.last()),
|
||||
json!(Some(RolloutItem::SessionMeta(Box::new(expected))))
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
73
codex-rs/thread-store/src/local/create_thread.rs
Normal file
73
codex-rs/thread-store/src/local/create_thread.rs
Normal file
@@ -0,0 +1,73 @@
|
||||
use super::LocalThreadStore;
|
||||
use crate::CreateThreadParams;
|
||||
use crate::ThreadStoreError;
|
||||
use crate::ThreadStoreResult;
|
||||
use codex_protocol::protocol::ThreadMemoryMode;
|
||||
use codex_rollout::RolloutConfig;
|
||||
use codex_rollout::RolloutRecorder;
|
||||
use codex_rollout::RolloutRecorderParams;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
|
||||
pub(super) async fn create_thread(
|
||||
store: &LocalThreadStore,
|
||||
params: CreateThreadParams,
|
||||
writer_lock: super::WriterLockGuard,
|
||||
) -> ThreadStoreResult<RolloutRecorder> {
|
||||
let cwd = params
|
||||
.metadata
|
||||
.cwd
|
||||
.clone()
|
||||
.ok_or_else(|| ThreadStoreError::InvalidRequest {
|
||||
message: "local thread store requires a cwd".to_string(),
|
||||
})?;
|
||||
let config = RolloutConfig {
|
||||
codex_home: store.config.codex_home.clone(),
|
||||
sqlite: store.config.sqlite.clone(),
|
||||
cwd,
|
||||
model_provider_id: params.metadata.model_provider.clone(),
|
||||
generate_memories: matches!(params.metadata.memory_mode, ThreadMemoryMode::Enabled),
|
||||
};
|
||||
RolloutRecorder::new_with_writer_lock(
|
||||
&config,
|
||||
RolloutRecorderParams::new(
|
||||
params.thread_id,
|
||||
params.forked_from_id,
|
||||
params.parent_thread_id,
|
||||
params.source,
|
||||
params.thread_source,
|
||||
params.originator,
|
||||
params.base_instructions,
|
||||
params.dynamic_tools,
|
||||
)
|
||||
.with_creator(
|
||||
params.creator_user_id,
|
||||
params.creator_account_id,
|
||||
/*account_scoped*/ true,
|
||||
)
|
||||
.with_session_id(params.session_id)
|
||||
.with_attached_thread(params.attached_thread)
|
||||
.with_selected_capability_roots(params.selected_capability_roots)
|
||||
.with_runtime_workspace_roots(params.runtime_workspace_roots.map(|roots| {
|
||||
roots
|
||||
.into_iter()
|
||||
.map(AbsolutePathBuf::into_path_buf)
|
||||
.collect()
|
||||
}))
|
||||
.with_multi_agent_version(params.multi_agent_version)
|
||||
.with_history_mode(params.history_mode)
|
||||
.with_history_base(params.history_base)
|
||||
.with_forked_from_ordinal_exclusive(
|
||||
params
|
||||
.forked_from_id
|
||||
.and(params.history_base)
|
||||
.map(|base| base.end_ordinal_exclusive),
|
||||
)
|
||||
.with_subagent_history_start_ordinal(params.subagent_history_start_ordinal)
|
||||
.with_initial_window_id(params.initial_window_id),
|
||||
writer_lock,
|
||||
)
|
||||
.await
|
||||
.map_err(|err| ThreadStoreError::Internal {
|
||||
message: format!("failed to initialize local thread recorder: {err}"),
|
||||
})
|
||||
}
|
||||
105
codex-rs/thread-store/src/local/daybreak_metadata_tests.rs
Normal file
105
codex-rs/thread-store/src/local/daybreak_metadata_tests.rs
Normal file
@@ -0,0 +1,105 @@
|
||||
//! Covers the saved Daybreak preference independently of transcript history.
|
||||
|
||||
use codex_protocol::ThreadId;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tempfile::TempDir;
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::LocalThreadStore;
|
||||
use super::test_support::test_config;
|
||||
use super::test_support::write_session_file;
|
||||
use crate::ReadThreadParams;
|
||||
use crate::ThreadMetadataPatch;
|
||||
use crate::ThreadStore;
|
||||
use crate::ThreadStoreError;
|
||||
use crate::UpdateThreadMetadataParams;
|
||||
|
||||
#[tokio::test]
|
||||
async fn daybreak_preference_survives_reconciliation_and_cold_reads()
|
||||
-> Result<(), Box<dyn std::error::Error>> {
|
||||
let home = TempDir::new()?;
|
||||
let config = test_config(home.path());
|
||||
let uuid = Uuid::new_v4();
|
||||
let thread_id = ThreadId::from_string(&uuid.to_string())?;
|
||||
let rollout_path = write_session_file(home.path(), "2025-01-03T14-20-00", uuid)?;
|
||||
let original_rollout = std::fs::read(&rollout_path)?;
|
||||
let runtime = codex_state::StateRuntime::init(
|
||||
config.sqlite.clone(),
|
||||
config.default_model_provider_id.clone(),
|
||||
)
|
||||
.await?;
|
||||
let store = LocalThreadStore::new(config.clone(), Some(runtime.clone()));
|
||||
for daybreak_enabled in [true, false] {
|
||||
let updated = store
|
||||
.update_thread_metadata(UpdateThreadMetadataParams {
|
||||
thread_id,
|
||||
patch: ThreadMetadataPatch {
|
||||
daybreak_enabled: Some(daybreak_enabled),
|
||||
..Default::default()
|
||||
},
|
||||
include_archived: false,
|
||||
})
|
||||
.await?
|
||||
.expect("updated thread");
|
||||
assert_eq!(updated.daybreak_enabled, Some(daybreak_enabled));
|
||||
}
|
||||
let mut stale_metadata = runtime
|
||||
.get_thread(thread_id)
|
||||
.await?
|
||||
.expect("saved metadata");
|
||||
stale_metadata.daybreak_enabled = Some(true);
|
||||
runtime.upsert_thread(&stale_metadata).await?;
|
||||
codex_rollout::state_db::reconcile_rollout(
|
||||
Some(runtime.as_ref()),
|
||||
&rollout_path,
|
||||
&config.default_model_provider_id,
|
||||
/*builder*/ None,
|
||||
&[],
|
||||
/*archived_only*/ None,
|
||||
/*new_thread_memory_mode*/ None,
|
||||
)
|
||||
.await;
|
||||
drop(store);
|
||||
drop(runtime);
|
||||
|
||||
let runtime = codex_state::StateRuntime::init(
|
||||
config.sqlite.clone(),
|
||||
config.default_model_provider_id.clone(),
|
||||
)
|
||||
.await?;
|
||||
let store = LocalThreadStore::new(config, Some(runtime));
|
||||
for include_history in [false, true] {
|
||||
let thread = store
|
||||
.read_thread(ReadThreadParams {
|
||||
thread_id,
|
||||
include_archived: false,
|
||||
include_history,
|
||||
})
|
||||
.await?;
|
||||
assert_eq!(thread.daybreak_enabled, Some(false));
|
||||
}
|
||||
assert_eq!(std::fs::read(rollout_path)?, original_rollout);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn daybreak_preference_requires_sqlite() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let home = TempDir::new()?;
|
||||
let uuid = Uuid::new_v4();
|
||||
let thread_id = ThreadId::from_string(&uuid.to_string())?;
|
||||
write_session_file(home.path(), "2025-01-03T14-20-00", uuid)?;
|
||||
let store = LocalThreadStore::new(test_config(home.path()), /*state_db*/ None);
|
||||
|
||||
let result = store
|
||||
.update_thread_metadata(UpdateThreadMetadataParams {
|
||||
thread_id,
|
||||
patch: ThreadMetadataPatch {
|
||||
daybreak_enabled: Some(false),
|
||||
..Default::default()
|
||||
},
|
||||
include_archived: false,
|
||||
})
|
||||
.await;
|
||||
assert!(matches!(result, Err(ThreadStoreError::Internal { .. })));
|
||||
Ok(())
|
||||
}
|
||||
915
codex-rs/thread-store/src/local/delete_thread.rs
Normal file
915
codex-rs/thread-store/src/local/delete_thread.rs
Normal file
@@ -0,0 +1,915 @@
|
||||
//! Local hard-delete support for persisted threads.
|
||||
//!
|
||||
//! Existing rollout files are deleted before this operation reports success. A rollout file that
|
||||
//! vanishes after discovery counts as already deleted. Main state DB rows are deleted after every
|
||||
//! associated rollout is removed, under the same lifecycle lock, so queued artifact mutations cannot
|
||||
//! use deleted thread metadata. Host-owned data is cleaned after reference and writer checks,
|
||||
//! before removing rollouts, so cleanup failures remain retryable even without a state DB.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::collections::HashSet;
|
||||
use std::io::ErrorKind;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_rollout::ARCHIVED_SESSIONS_SUBDIR;
|
||||
use codex_rollout::RolloutReferenceIndex;
|
||||
use codex_rollout::SESSIONS_SUBDIR;
|
||||
use codex_rollout::find_archived_thread_path_by_id_str;
|
||||
use codex_rollout::find_thread_path_by_id_str;
|
||||
use codex_rollout::remove_thread_name_entries;
|
||||
|
||||
use super::LocalThreadStore;
|
||||
use super::helpers::scoped_rollout_path;
|
||||
use super::helpers::validated_rollout_file_name;
|
||||
use crate::DeleteThreadParams;
|
||||
use crate::DeleteThreadsParams;
|
||||
use crate::ThreadStoreError;
|
||||
use crate::ThreadStoreResult;
|
||||
|
||||
struct ThreadRollouts {
|
||||
thread_id: codex_protocol::ThreadId,
|
||||
rollout_ids: HashSet<codex_protocol::ThreadId>,
|
||||
paths: Vec<PathBuf>,
|
||||
}
|
||||
|
||||
impl LocalThreadStore {
|
||||
/// Reject deletion while any candidate has attached threads. Call before stopping live work;
|
||||
/// deletion repeats this check under existing writer ownership to cover concurrent creation.
|
||||
pub async fn ensure_no_attached_threads(
|
||||
&self,
|
||||
thread_ids: &[ThreadId],
|
||||
) -> ThreadStoreResult<()> {
|
||||
let reference_index = scan_reference_index(self).await?;
|
||||
check_attached_children(&reference_index, thread_ids)
|
||||
}
|
||||
}
|
||||
|
||||
fn check_attached_children(
|
||||
reference_index: &RolloutReferenceIndex,
|
||||
thread_ids: &[ThreadId],
|
||||
) -> ThreadStoreResult<()> {
|
||||
let Some(child) = reference_index.attached_child(thread_ids) else {
|
||||
return Ok(());
|
||||
};
|
||||
Err(ThreadStoreError::InvalidRequest {
|
||||
message: format!(
|
||||
"cannot delete thread while attached thread {child} exists; delete the attached thread first"
|
||||
),
|
||||
})
|
||||
}
|
||||
|
||||
impl ThreadRollouts {
|
||||
fn from_index(
|
||||
reference_index: &RolloutReferenceIndex,
|
||||
thread_id: codex_protocol::ThreadId,
|
||||
) -> Self {
|
||||
let mut rollout_ids = HashSet::new();
|
||||
let paths = reference_index
|
||||
.rollouts_for_thread(thread_id)
|
||||
.map(|(rollout_id, path)| {
|
||||
rollout_ids.insert(rollout_id);
|
||||
path.to_path_buf()
|
||||
})
|
||||
.collect();
|
||||
Self {
|
||||
thread_id,
|
||||
rollout_ids,
|
||||
paths,
|
||||
}
|
||||
}
|
||||
|
||||
fn add_path(&mut self, path: PathBuf) {
|
||||
if let Some(rollout_id) = codex_rollout::rollout_id_from_path(path.as_path()) {
|
||||
self.rollout_ids.insert(rollout_id);
|
||||
}
|
||||
if !self.paths.contains(&path) {
|
||||
self.paths.push(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn delete_thread(
|
||||
store: &LocalThreadStore,
|
||||
params: DeleteThreadParams,
|
||||
) -> ThreadStoreResult<()> {
|
||||
let thread_id = params.thread_id;
|
||||
let _lifecycle_guard = store.live_writer_locks.lock_lifecycle(thread_id).await;
|
||||
let _live_writer_guard = store.live_writer_locks.lock(thread_id).await;
|
||||
let mut writer_guards = store.acquire_writer_locks(&[thread_id]).await?;
|
||||
let reference_index = scan_reference_index(store).await?;
|
||||
let thread_rollouts = ThreadRollouts::from_index(&reference_index, thread_id);
|
||||
check_attached_children(&reference_index, &[thread_id])?;
|
||||
ensure_no_external_references(&reference_index, std::slice::from_ref(&thread_rollouts))?;
|
||||
if let Some(cleanup) = &store.thread_data_cleanup {
|
||||
cleanup(vec![thread_id]).await?;
|
||||
}
|
||||
let found_rollout =
|
||||
match delete_thread_after_reference_check(store, thread_rollouts, &mut writer_guards).await
|
||||
{
|
||||
Ok(()) => true,
|
||||
Err(ThreadStoreError::ThreadNotFound { .. }) => false,
|
||||
Err(err) => return Err(err),
|
||||
};
|
||||
let deleted_state_rows = delete_state_rows(store, &[thread_id]).await?;
|
||||
if found_rollout || deleted_state_rows > 0 {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(ThreadStoreError::ThreadNotFound { thread_id })
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn delete_threads(
|
||||
store: &LocalThreadStore,
|
||||
params: DeleteThreadsParams,
|
||||
) -> ThreadStoreResult<()> {
|
||||
let thread_ids = params.thread_ids;
|
||||
if thread_ids.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let mut lock_thread_ids = thread_ids.clone();
|
||||
lock_thread_ids.sort_unstable_by_key(ToString::to_string);
|
||||
lock_thread_ids.dedup();
|
||||
let mut _lifecycle_guards = Vec::with_capacity(lock_thread_ids.len());
|
||||
for thread_id in &lock_thread_ids {
|
||||
_lifecycle_guards.push(store.live_writer_locks.lock_lifecycle(*thread_id).await);
|
||||
}
|
||||
let mut _live_writer_guards = Vec::with_capacity(lock_thread_ids.len());
|
||||
for &thread_id in &lock_thread_ids {
|
||||
_live_writer_guards.push(store.live_writer_locks.lock(thread_id).await);
|
||||
}
|
||||
|
||||
let mut writer_guards = store.acquire_writer_locks(&lock_thread_ids).await?;
|
||||
let reference_index = scan_reference_index(store).await?;
|
||||
let thread_rollouts = thread_ids
|
||||
.iter()
|
||||
.map(|thread_id| ThreadRollouts::from_index(&reference_index, *thread_id))
|
||||
.collect::<Vec<_>>();
|
||||
check_attached_children(&reference_index, &lock_thread_ids)?;
|
||||
ensure_no_external_references(&reference_index, thread_rollouts.as_slice())?;
|
||||
if let Some(cleanup) = &store.thread_data_cleanup {
|
||||
cleanup(thread_ids.clone()).await?;
|
||||
}
|
||||
for thread_rollouts in thread_rollouts {
|
||||
match delete_thread_after_reference_check(store, thread_rollouts, &mut writer_guards).await
|
||||
{
|
||||
Ok(()) | Err(ThreadStoreError::ThreadNotFound { .. }) => {}
|
||||
Err(err) => return Err(err),
|
||||
}
|
||||
}
|
||||
// Retain the complete retry graph until every rollout has been removed.
|
||||
delete_state_rows(store, &thread_ids).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) async fn delete_state_rows(
|
||||
store: &LocalThreadStore,
|
||||
thread_ids: &[codex_protocol::ThreadId],
|
||||
) -> ThreadStoreResult<u64> {
|
||||
let Some(state_db) = store.state_db.as_ref() else {
|
||||
return Ok(0);
|
||||
};
|
||||
state_db
|
||||
.delete_threads_strict(thread_ids)
|
||||
.await
|
||||
.map_err(|err| ThreadStoreError::Internal {
|
||||
message: format!("failed to delete thread state: {err}"),
|
||||
})
|
||||
}
|
||||
|
||||
fn ensure_no_external_references(
|
||||
reference_index: &RolloutReferenceIndex,
|
||||
thread_rollouts: &[ThreadRollouts],
|
||||
) -> ThreadStoreResult<()> {
|
||||
let deletion_rollout_ids = thread_rollouts
|
||||
.iter()
|
||||
.flat_map(|thread_rollouts| thread_rollouts.rollout_ids.iter().copied())
|
||||
.collect::<HashSet<_>>();
|
||||
let mut internal_reference_counts = HashMap::new();
|
||||
for source_rollout_id in &deletion_rollout_ids {
|
||||
if let Some(history_base) = reference_index.history_base(*source_rollout_id)
|
||||
&& history_base.thread_id != *source_rollout_id
|
||||
&& deletion_rollout_ids.contains(&history_base.thread_id)
|
||||
{
|
||||
*internal_reference_counts
|
||||
.entry(history_base.thread_id)
|
||||
.or_default() += 1;
|
||||
}
|
||||
}
|
||||
for thread_rollouts in thread_rollouts {
|
||||
if thread_rollouts.rollout_ids.iter().any(|rollout_id| {
|
||||
let internal_reference_count = internal_reference_counts
|
||||
.get(rollout_id)
|
||||
.copied()
|
||||
.unwrap_or_default();
|
||||
reference_index.reference_count(*rollout_id) > internal_reference_count
|
||||
}) {
|
||||
return Err(referenced_thread_error(thread_rollouts.thread_id));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn scan_reference_index(
|
||||
store: &LocalThreadStore,
|
||||
) -> ThreadStoreResult<RolloutReferenceIndex> {
|
||||
RolloutReferenceIndex::scan(store.config.codex_home.as_path())
|
||||
.await
|
||||
.map_err(|err| ThreadStoreError::Internal {
|
||||
message: format!("failed to scan fork history references: {err}"),
|
||||
})
|
||||
}
|
||||
|
||||
fn referenced_thread_error(thread_id: codex_protocol::ThreadId) -> ThreadStoreError {
|
||||
ThreadStoreError::InvalidRequest {
|
||||
message: format!("cannot delete thread {thread_id}: forked history still references it"),
|
||||
}
|
||||
}
|
||||
|
||||
async fn delete_thread_after_reference_check(
|
||||
store: &LocalThreadStore,
|
||||
mut thread_rollouts: ThreadRollouts,
|
||||
writer_guards: &mut Vec<super::WriterLockGuard>,
|
||||
) -> ThreadStoreResult<()> {
|
||||
let thread_id = thread_rollouts.thread_id;
|
||||
let thread_id_str = thread_id.to_string();
|
||||
let state_db_ctx = store.state_db().await;
|
||||
match find_thread_path_by_id_str(
|
||||
store.config.codex_home.as_path(),
|
||||
thread_id_str.as_str(),
|
||||
state_db_ctx.as_deref(),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(Some(path)) => thread_rollouts.add_path(path),
|
||||
Ok(None) => {}
|
||||
Err(err) => {
|
||||
return Err(ThreadStoreError::InvalidRequest {
|
||||
message: format!("failed to locate thread id {thread_id}: {err}"),
|
||||
});
|
||||
}
|
||||
}
|
||||
match find_archived_thread_path_by_id_str(
|
||||
store.config.codex_home.as_path(),
|
||||
thread_id_str.as_str(),
|
||||
state_db_ctx.as_deref(),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(Some(path)) => thread_rollouts.add_path(path),
|
||||
Ok(None) => {}
|
||||
Err(err) => {
|
||||
return Err(ThreadStoreError::InvalidRequest {
|
||||
message: format!("failed to locate archived thread id {thread_id}: {err}"),
|
||||
});
|
||||
}
|
||||
}
|
||||
thread_rollouts.rollout_ids.insert(thread_id);
|
||||
for rollout_id in thread_rollouts.rollout_ids {
|
||||
super::thread_history::delete_thread(store, rollout_id).await?;
|
||||
}
|
||||
|
||||
// Stop queued file work before removing files, retaining ownership until cleanup finishes.
|
||||
let live_entry = store.live_recorders.lock().await.remove(&thread_id);
|
||||
if let Some(entry) = live_entry {
|
||||
writer_guards.push(entry.writer_lock);
|
||||
entry
|
||||
.recorder
|
||||
.discard()
|
||||
.await
|
||||
.map_err(|err| ThreadStoreError::Internal {
|
||||
message: format!("failed to stop thread writer before deletion: {err}"),
|
||||
})?;
|
||||
}
|
||||
let found_rollout_path = !thread_rollouts.paths.is_empty();
|
||||
for rollout_path in thread_rollouts.paths {
|
||||
delete_rollout_file(store, rollout_path.as_path())?;
|
||||
}
|
||||
remove_thread_name_entries(store.config.codex_home.as_path(), thread_id)
|
||||
.await
|
||||
.map_err(|err| ThreadStoreError::Internal {
|
||||
message: format!("failed to delete thread name index entries for {thread_id}: {err}"),
|
||||
})?;
|
||||
|
||||
if !found_rollout_path {
|
||||
return Err(ThreadStoreError::ThreadNotFound { thread_id });
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn delete_rollout_file(
|
||||
store: &LocalThreadStore,
|
||||
rollout_path: &Path,
|
||||
) -> ThreadStoreResult<bool> {
|
||||
let plain_path = codex_rollout::plain_rollout_path(rollout_path);
|
||||
let compressed_path = plain_path.with_extension("jsonl.zst");
|
||||
let deleted_plain = delete_rollout_path(store, plain_path.as_path())?;
|
||||
let deleted_compressed = delete_rollout_path(store, compressed_path.as_path())?;
|
||||
Ok(deleted_plain || deleted_compressed)
|
||||
}
|
||||
|
||||
fn delete_rollout_path(store: &LocalThreadStore, rollout_path: &Path) -> ThreadStoreResult<bool> {
|
||||
let canonical_rollout_path = scoped_rollout_path(
|
||||
store.config.codex_home.join(SESSIONS_SUBDIR),
|
||||
rollout_path,
|
||||
"sessions",
|
||||
)
|
||||
.or_else(|_| {
|
||||
scoped_rollout_path(
|
||||
store.config.codex_home.join(ARCHIVED_SESSIONS_SUBDIR),
|
||||
rollout_path,
|
||||
"archived sessions",
|
||||
)
|
||||
})
|
||||
.or_else(|err| match rollout_path.try_exists() {
|
||||
Ok(false) => Ok(rollout_path.to_path_buf()),
|
||||
Ok(true) | Err(_) => Err(err),
|
||||
})?;
|
||||
validated_rollout_file_name(&canonical_rollout_path, rollout_path)?;
|
||||
match std::fs::remove_file(&canonical_rollout_path) {
|
||||
Ok(()) => Ok(true),
|
||||
Err(err) if err.kind() == ErrorKind::NotFound => Ok(false),
|
||||
Err(err) => Err(ThreadStoreError::Internal {
|
||||
message: format!(
|
||||
"failed to delete rollout file `{}`: {err}",
|
||||
canonical_rollout_path.display()
|
||||
),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::protocol::HistoryPosition;
|
||||
use codex_protocol::protocol::ThreadHistoryMode;
|
||||
use codex_protocol::protocol::ThreadMemoryMode;
|
||||
use codex_utils_absolute_path::test_support::PathExt;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tempfile::TempDir;
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::*;
|
||||
use crate::ResumeThreadParams;
|
||||
use crate::ThreadPersistenceMetadata;
|
||||
use crate::ThreadStore;
|
||||
use crate::local::LocalThreadStore;
|
||||
use crate::local::test_support::test_config;
|
||||
use crate::local::test_support::write_archived_session_file;
|
||||
use crate::local::test_support::write_session_file;
|
||||
use crate::local::test_support::write_session_file_with;
|
||||
use crate::local::test_support::write_session_file_with_history_mode;
|
||||
|
||||
#[tokio::test]
|
||||
async fn delete_thread_removes_active_and_archived_rollouts() {
|
||||
let home = TempDir::new().expect("temp dir");
|
||||
let store = LocalThreadStore::new(test_config(home.path()), /*state_db*/ None);
|
||||
let active_path =
|
||||
write_session_file(home.path(), "2025-01-03T12-00-00", Uuid::from_u128(301))
|
||||
.expect("session file");
|
||||
let compressed_path = active_path.with_extension("jsonl.zst");
|
||||
std::fs::write(&compressed_path, b"compressed sibling").expect("compressed sibling");
|
||||
let cases = [
|
||||
(Uuid::from_u128(301), active_path),
|
||||
(
|
||||
Uuid::from_u128(302),
|
||||
write_archived_session_file(
|
||||
home.path(),
|
||||
"2025-01-03T12-00-00",
|
||||
Uuid::from_u128(302),
|
||||
)
|
||||
.expect("archived session file"),
|
||||
),
|
||||
];
|
||||
|
||||
for (uuid, path) in cases {
|
||||
let thread_id = ThreadId::from_string(&uuid.to_string()).expect("valid thread id");
|
||||
store
|
||||
.delete_thread(DeleteThreadParams { thread_id })
|
||||
.await
|
||||
.expect("delete thread");
|
||||
|
||||
assert!(!path.exists());
|
||||
}
|
||||
assert!(!compressed_path.exists());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn delete_thread_rejects_referenced_paginated_history() {
|
||||
let home = TempDir::new().expect("temp dir");
|
||||
let store = LocalThreadStore::new(test_config(home.path()), /*state_db*/ None);
|
||||
let source_uuid = Uuid::from_u128(303);
|
||||
let source_thread_id =
|
||||
ThreadId::from_string(&source_uuid.to_string()).expect("valid source thread id");
|
||||
let source_path = write_session_file_with_history_mode(
|
||||
home.path(),
|
||||
"2025-01-03T12-00-00",
|
||||
source_uuid,
|
||||
ThreadHistoryMode::Paginated,
|
||||
)
|
||||
.expect("source session file");
|
||||
let child_path = write_session_file_with(
|
||||
home.path(),
|
||||
home.path().join(ARCHIVED_SESSIONS_SUBDIR),
|
||||
"2025-01-03T12-00-01",
|
||||
Uuid::from_u128(304),
|
||||
"Archived user message",
|
||||
Some("test-provider"),
|
||||
ThreadHistoryMode::Paginated,
|
||||
)
|
||||
.expect("child session file");
|
||||
set_history_base(
|
||||
child_path.as_path(),
|
||||
HistoryPosition {
|
||||
thread_id: source_thread_id,
|
||||
end_ordinal_exclusive: 1,
|
||||
end_byte_offset: std::fs::metadata(source_path.as_path())
|
||||
.expect("source rollout metadata")
|
||||
.len(),
|
||||
},
|
||||
);
|
||||
|
||||
let err = store
|
||||
.delete_thread(DeleteThreadParams {
|
||||
thread_id: source_thread_id,
|
||||
})
|
||||
.await
|
||||
.expect_err("referenced source should not be deleted");
|
||||
|
||||
assert_eq!(
|
||||
err.to_string(),
|
||||
format!(
|
||||
"invalid thread-store request: cannot delete thread {source_thread_id}: forked history still references it"
|
||||
)
|
||||
);
|
||||
assert!(source_path.exists());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn delete_thread_rejects_reference_to_reverted_rollout() {
|
||||
let home = TempDir::new().expect("temp dir");
|
||||
let store = LocalThreadStore::new(test_config(home.path()), /*state_db*/ None);
|
||||
let thread_uuid = Uuid::from_u128(320);
|
||||
let thread_id = ThreadId::from_string(&thread_uuid.to_string()).expect("thread id");
|
||||
let source_path = write_session_file_with_history_mode(
|
||||
home.path(),
|
||||
"2025-01-03T12-00-00",
|
||||
thread_uuid,
|
||||
ThreadHistoryMode::Paginated,
|
||||
)
|
||||
.expect("source session file");
|
||||
let replacement_uuid = Uuid::from_u128(321);
|
||||
let replacement_rollout_id =
|
||||
ThreadId::from_string(&replacement_uuid.to_string()).expect("replacement rollout id");
|
||||
let replacement_path = write_session_file_with_history_mode(
|
||||
home.path(),
|
||||
"2025-01-03T12-00-01",
|
||||
replacement_uuid,
|
||||
ThreadHistoryMode::Paginated,
|
||||
)
|
||||
.expect("replacement session file");
|
||||
set_thread_id(replacement_path.as_path(), thread_id);
|
||||
set_history_base(
|
||||
replacement_path.as_path(),
|
||||
HistoryPosition {
|
||||
thread_id,
|
||||
end_ordinal_exclusive: 1,
|
||||
end_byte_offset: std::fs::metadata(source_path.as_path())
|
||||
.expect("source rollout metadata")
|
||||
.len(),
|
||||
},
|
||||
);
|
||||
let child_path = write_session_file_with_history_mode(
|
||||
home.path(),
|
||||
"2025-01-03T12-00-02",
|
||||
Uuid::from_u128(322),
|
||||
ThreadHistoryMode::Paginated,
|
||||
)
|
||||
.expect("child session file");
|
||||
set_history_base(
|
||||
child_path.as_path(),
|
||||
HistoryPosition {
|
||||
thread_id: replacement_rollout_id,
|
||||
end_ordinal_exclusive: 1,
|
||||
end_byte_offset: std::fs::metadata(replacement_path.as_path())
|
||||
.expect("replacement rollout metadata")
|
||||
.len(),
|
||||
},
|
||||
);
|
||||
|
||||
let err = store
|
||||
.delete_thread(DeleteThreadParams { thread_id })
|
||||
.await
|
||||
.expect_err("referenced replacement should not be deleted");
|
||||
|
||||
assert_eq!(
|
||||
err.to_string(),
|
||||
format!(
|
||||
"invalid thread-store request: cannot delete thread {thread_id}: forked history still references it"
|
||||
)
|
||||
);
|
||||
assert!(source_path.exists());
|
||||
assert!(replacement_path.exists());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn delete_thread_ignores_unreadable_reference_metadata() {
|
||||
let home = TempDir::new().expect("temp dir");
|
||||
let store = LocalThreadStore::new(test_config(home.path()), /*state_db*/ None);
|
||||
let source_uuid = Uuid::from_u128(305);
|
||||
let source_thread_id =
|
||||
ThreadId::from_string(&source_uuid.to_string()).expect("valid source thread id");
|
||||
let source_path = write_session_file(home.path(), "2025-01-03T12-00-00", source_uuid)
|
||||
.expect("source session file");
|
||||
let unreadable_path = source_path.with_file_name(format!(
|
||||
"rollout-2025-01-03T12-00-01-{}.jsonl",
|
||||
Uuid::from_u128(306)
|
||||
));
|
||||
std::fs::write(unreadable_path, "{not json}\n").expect("unreadable rollout metadata");
|
||||
|
||||
store
|
||||
.delete_thread(DeleteThreadParams {
|
||||
thread_id: source_thread_id,
|
||||
})
|
||||
.await
|
||||
.expect("unreadable metadata should not block delete");
|
||||
|
||||
assert!(!source_path.exists());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn delete_threads_allows_internal_history_references() {
|
||||
let home = TempDir::new().expect("temp dir");
|
||||
let store = LocalThreadStore::new(test_config(home.path()), /*state_db*/ None);
|
||||
let source_uuid = Uuid::from_u128(307);
|
||||
let source_thread_id =
|
||||
ThreadId::from_string(&source_uuid.to_string()).expect("valid source thread id");
|
||||
let source_path = write_session_file_with_history_mode(
|
||||
home.path(),
|
||||
"2025-01-03T12-00-00",
|
||||
source_uuid,
|
||||
ThreadHistoryMode::Paginated,
|
||||
)
|
||||
.expect("source session file");
|
||||
let child_uuid = Uuid::from_u128(308);
|
||||
let child_thread_id =
|
||||
ThreadId::from_string(&child_uuid.to_string()).expect("valid child thread id");
|
||||
let child_path = write_session_file_with_history_mode(
|
||||
home.path(),
|
||||
"2025-01-03T12-00-01",
|
||||
child_uuid,
|
||||
ThreadHistoryMode::Paginated,
|
||||
)
|
||||
.expect("child session file");
|
||||
set_history_base(
|
||||
child_path.as_path(),
|
||||
HistoryPosition {
|
||||
thread_id: source_thread_id,
|
||||
end_ordinal_exclusive: 1,
|
||||
end_byte_offset: std::fs::metadata(source_path.as_path())
|
||||
.expect("source rollout metadata")
|
||||
.len(),
|
||||
},
|
||||
);
|
||||
|
||||
store
|
||||
.delete_threads(DeleteThreadsParams {
|
||||
thread_ids: vec![child_thread_id, source_thread_id],
|
||||
})
|
||||
.await
|
||||
.expect("internal references should not block batch delete");
|
||||
|
||||
assert!(!source_path.exists());
|
||||
assert!(!child_path.exists());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn delete_threads_rejects_owned_descendants_before_deleting_anything() {
|
||||
let home = TempDir::new().expect("temp dir");
|
||||
let store = LocalThreadStore::new(test_config(home.path()), /*state_db*/ None);
|
||||
let owner = LocalThreadStore::new(test_config(home.path()), /*state_db*/ None);
|
||||
for (parent_uuid, child_uuid, history_mode) in [
|
||||
(
|
||||
Uuid::from_u128(309),
|
||||
Uuid::from_u128(310),
|
||||
ThreadHistoryMode::Legacy,
|
||||
),
|
||||
(
|
||||
Uuid::from_u128(312),
|
||||
Uuid::from_u128(313),
|
||||
ThreadHistoryMode::Paginated,
|
||||
),
|
||||
] {
|
||||
let parent_thread_id =
|
||||
ThreadId::from_string(&parent_uuid.to_string()).expect("valid parent thread id");
|
||||
let parent_path = write_session_file_with_history_mode(
|
||||
home.path(),
|
||||
"2025-01-03T12-00-00",
|
||||
parent_uuid,
|
||||
history_mode,
|
||||
)
|
||||
.expect("parent session file");
|
||||
let child_thread_id =
|
||||
ThreadId::from_string(&child_uuid.to_string()).expect("valid child thread id");
|
||||
let child_path = write_session_file_with_history_mode(
|
||||
home.path(),
|
||||
"2025-01-03T12-00-01",
|
||||
child_uuid,
|
||||
history_mode,
|
||||
)
|
||||
.expect("child session file");
|
||||
let _owner_guard = owner
|
||||
.acquire_writer_lock(child_thread_id)
|
||||
.expect("acquire child writer lock");
|
||||
|
||||
let error = store
|
||||
.delete_threads(DeleteThreadsParams {
|
||||
thread_ids: vec![parent_thread_id, child_thread_id],
|
||||
})
|
||||
.await
|
||||
.expect_err("owned descendant should block deletion");
|
||||
|
||||
assert!(matches!(error, ThreadStoreError::Conflict { .. }));
|
||||
assert!(parent_path.exists());
|
||||
assert!(child_path.exists());
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn delete_threads_rejects_owned_thread_before_rollout_materializes() {
|
||||
let home = TempDir::new().expect("temp dir");
|
||||
let store = LocalThreadStore::new(test_config(home.path()), /*state_db*/ None);
|
||||
let owner = LocalThreadStore::new(test_config(home.path()), /*state_db*/ None);
|
||||
let thread_id = ThreadId::default();
|
||||
let _owner_guard = owner
|
||||
.acquire_writer_lock(thread_id)
|
||||
.expect("acquire writer lock before rollout exists");
|
||||
|
||||
let error = store
|
||||
.delete_threads(DeleteThreadsParams {
|
||||
thread_ids: vec![thread_id],
|
||||
})
|
||||
.await
|
||||
.expect_err("owned thread should block deletion before rollout exists");
|
||||
|
||||
assert!(matches!(error, ThreadStoreError::Conflict { .. }));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn delete_threads_removes_rollout_with_unreadable_metadata() {
|
||||
let home = TempDir::new().expect("temp dir");
|
||||
let store = LocalThreadStore::new(test_config(home.path()), /*state_db*/ None);
|
||||
let uuid = Uuid::from_u128(311);
|
||||
let thread_id = ThreadId::from_string(&uuid.to_string()).expect("valid thread id");
|
||||
let rollout_path =
|
||||
write_session_file(home.path(), "2025-01-03T12-00-00", uuid).expect("session file");
|
||||
std::fs::write(&rollout_path, "{not json}\n").expect("damage rollout metadata");
|
||||
|
||||
store
|
||||
.delete_threads(DeleteThreadsParams {
|
||||
thread_ids: vec![thread_id],
|
||||
})
|
||||
.await
|
||||
.expect("delete rollout with unreadable metadata");
|
||||
|
||||
assert!(!rollout_path.exists());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn delete_rollout_file_treats_vanished_path_as_already_deleted() {
|
||||
let home = TempDir::new().expect("temp dir");
|
||||
let store = LocalThreadStore::new(test_config(home.path()), /*state_db*/ None);
|
||||
let uuid = Uuid::from_u128(305);
|
||||
let path =
|
||||
write_session_file(home.path(), "2025-01-03T12-00-00", uuid).expect("session file");
|
||||
std::fs::remove_file(&path).expect("remove session file");
|
||||
|
||||
assert!(!delete_rollout_file(&store, path.as_path()).expect("delete rollout"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn delete_thread_without_state_db_preserves_materialized_thread_history() {
|
||||
let home = TempDir::new().expect("temp dir");
|
||||
let config = test_config(home.path());
|
||||
let store = LocalThreadStore::new(config.clone(), /*state_db*/ None);
|
||||
let uuid = Uuid::from_u128(312);
|
||||
let thread_id = ThreadId::from_string(&uuid.to_string()).expect("valid thread id");
|
||||
let rollout_path = write_session_file_with_history_mode(
|
||||
home.path(),
|
||||
"2025-01-03T12-00-00",
|
||||
uuid,
|
||||
ThreadHistoryMode::Paginated,
|
||||
)
|
||||
.expect("session file");
|
||||
let pool = codex_state::open_thread_history_db(&config.sqlite)
|
||||
.await
|
||||
.expect("open existing thread history database");
|
||||
let thread_id_string = thread_id.to_string();
|
||||
sqlx::query(
|
||||
"INSERT INTO thread_turns (thread_id, turn_id, rollout_ordinal, status) VALUES (?, 'turn-1', 1, 'completed')",
|
||||
)
|
||||
.bind(thread_id_string.as_str())
|
||||
.execute(&pool)
|
||||
.await
|
||||
.expect("insert turn");
|
||||
sqlx::query(
|
||||
"INSERT INTO thread_items (thread_id, turn_id, item_id, rollout_ordinal, created_at_ms, item_json) VALUES (?, 'turn-1', 'item-1', 2, 1, '{}')",
|
||||
)
|
||||
.bind(thread_id_string.as_str())
|
||||
.execute(&pool)
|
||||
.await
|
||||
.expect("insert item");
|
||||
sqlx::query(
|
||||
"INSERT INTO thread_realtime_items (thread_id, item_id, rollout_ordinal, created_at_ms, item_type, item_json) VALUES (?, 'realtime-1', 3, 1, 'realtime_session_started', '{}')",
|
||||
)
|
||||
.bind(thread_id_string.as_str())
|
||||
.execute(&pool)
|
||||
.await
|
||||
.expect("insert realtime item");
|
||||
sqlx::query(
|
||||
"INSERT INTO thread_history_projection_state (thread_id, next_rollout_byte_offset, next_rollout_ordinal) VALUES (?, 3, 3)",
|
||||
)
|
||||
.bind(thread_id_string.as_str())
|
||||
.execute(&pool)
|
||||
.await
|
||||
.expect("insert projection state");
|
||||
|
||||
let error = store
|
||||
.delete_thread(DeleteThreadParams { thread_id })
|
||||
.await
|
||||
.expect_err("projected history without a state database should prevent deletion");
|
||||
|
||||
assert!(matches!(
|
||||
error,
|
||||
ThreadStoreError::Unsupported {
|
||||
operation: "paginated_history"
|
||||
}
|
||||
));
|
||||
assert!(rollout_path.exists());
|
||||
let counts = sqlx::query_as::<_, (i64, i64, i64, i64)>(
|
||||
r#"
|
||||
SELECT
|
||||
(SELECT COUNT(*) FROM thread_turns WHERE thread_id = ?),
|
||||
(SELECT COUNT(*) FROM thread_items WHERE thread_id = ?),
|
||||
(SELECT COUNT(*) FROM thread_realtime_items WHERE thread_id = ?),
|
||||
(SELECT COUNT(*) FROM thread_history_projection_state WHERE thread_id = ?)
|
||||
"#,
|
||||
)
|
||||
.bind(thread_id_string.as_str())
|
||||
.bind(thread_id_string.as_str())
|
||||
.bind(thread_id_string.as_str())
|
||||
.bind(thread_id_string.as_str())
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.expect("read preserved history rows");
|
||||
assert_eq!(counts, (1, 1, 1, 1));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn delete_thread_removes_materialized_thread_history() {
|
||||
let home = TempDir::new().expect("temp dir");
|
||||
let config = test_config(home.path());
|
||||
let state_db = codex_state::StateRuntime::init(
|
||||
config.sqlite.clone(),
|
||||
config.default_model_provider_id.clone(),
|
||||
)
|
||||
.await
|
||||
.expect("initialize state database for materialized history");
|
||||
let store = LocalThreadStore::new(config, Some(state_db));
|
||||
let uuid = Uuid::from_u128(306);
|
||||
let thread_id = ThreadId::from_string(&uuid.to_string()).expect("valid thread id");
|
||||
let rollout_path = write_session_file_with_history_mode(
|
||||
home.path(),
|
||||
"2025-01-03T12-00-00",
|
||||
uuid,
|
||||
ThreadHistoryMode::Paginated,
|
||||
)
|
||||
.expect("session file");
|
||||
let pool = codex_state::open_thread_history_db(
|
||||
&codex_state::SqliteConfig::new_for_testing(home.path().abs()),
|
||||
)
|
||||
.await
|
||||
.expect("open thread history db");
|
||||
let thread_id_string = thread_id.to_string();
|
||||
sqlx::query(
|
||||
"INSERT INTO thread_turns (thread_id, turn_id, rollout_ordinal, status) VALUES (?, 'turn-1', 1, 'completed')",
|
||||
)
|
||||
.bind(thread_id_string.as_str())
|
||||
.execute(&pool)
|
||||
.await
|
||||
.expect("insert turn");
|
||||
sqlx::query(
|
||||
"INSERT INTO thread_items (thread_id, turn_id, item_id, rollout_ordinal, created_at_ms, item_json) VALUES (?, 'turn-1', 'item-1', 2, 1, '{}')",
|
||||
)
|
||||
.bind(thread_id_string.as_str())
|
||||
.execute(&pool)
|
||||
.await
|
||||
.expect("insert item");
|
||||
sqlx::query(
|
||||
"INSERT INTO thread_realtime_items (thread_id, item_id, rollout_ordinal, created_at_ms, item_type, item_json) VALUES (?, 'realtime-1', 3, 1, 'realtime_session_started', '{}')",
|
||||
)
|
||||
.bind(thread_id_string.as_str())
|
||||
.execute(&pool)
|
||||
.await
|
||||
.expect("insert realtime item");
|
||||
sqlx::query(
|
||||
"INSERT INTO thread_history_projection_state (thread_id, next_rollout_byte_offset, next_rollout_ordinal) VALUES (?, 3, 3)",
|
||||
)
|
||||
.bind(thread_id_string.as_str())
|
||||
.execute(&pool)
|
||||
.await
|
||||
.expect("insert projection state");
|
||||
|
||||
store
|
||||
.resume_thread(ResumeThreadParams {
|
||||
history_revision: None,
|
||||
thread_id,
|
||||
rollout_path: Some(rollout_path),
|
||||
history: None,
|
||||
include_archived: false,
|
||||
metadata: ThreadPersistenceMetadata {
|
||||
cwd: Some(home.path().to_path_buf()),
|
||||
model_provider: "test-provider".to_string(),
|
||||
memory_mode: ThreadMemoryMode::Enabled,
|
||||
},
|
||||
})
|
||||
.await
|
||||
.expect("resume paginated writer before deletion");
|
||||
let lock_path = home
|
||||
.path()
|
||||
.join("thread-writer-locks")
|
||||
.join(format!("{thread_id}.lock"));
|
||||
assert!(lock_path.exists());
|
||||
|
||||
store
|
||||
.delete_thread(DeleteThreadParams { thread_id })
|
||||
.await
|
||||
.expect("delete thread");
|
||||
assert!(!lock_path.exists());
|
||||
|
||||
let counts = sqlx::query_as::<_, (i64, i64, i64, i64)>(
|
||||
r#"
|
||||
SELECT
|
||||
(SELECT COUNT(*) FROM thread_turns WHERE thread_id = ?),
|
||||
(SELECT COUNT(*) FROM thread_items WHERE thread_id = ?),
|
||||
(SELECT COUNT(*) FROM thread_realtime_items WHERE thread_id = ?),
|
||||
(SELECT COUNT(*) FROM thread_history_projection_state WHERE thread_id = ?)
|
||||
"#,
|
||||
)
|
||||
.bind(thread_id_string.as_str())
|
||||
.bind(thread_id_string.as_str())
|
||||
.bind(thread_id_string.as_str())
|
||||
.bind(thread_id_string.as_str())
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.expect("read remaining history rows");
|
||||
assert_eq!(counts, (0, 0, 0, 0));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn delete_thread_reports_missing_thread() {
|
||||
let home = TempDir::new().expect("temp dir");
|
||||
let store = LocalThreadStore::new(test_config(home.path()), /*state_db*/ None);
|
||||
let thread_id =
|
||||
ThreadId::from_string("00000000-0000-0000-0000-000000000304").expect("valid thread id");
|
||||
|
||||
let err = store
|
||||
.delete_thread(DeleteThreadParams { thread_id })
|
||||
.await
|
||||
.expect_err("missing thread should fail");
|
||||
assert_eq!(
|
||||
err.to_string(),
|
||||
"thread 00000000-0000-0000-0000-000000000304 not found"
|
||||
);
|
||||
}
|
||||
|
||||
fn set_history_base(path: &Path, history_base: HistoryPosition) {
|
||||
let mut session_meta: serde_json::Value = serde_json::from_str(
|
||||
std::fs::read_to_string(path)
|
||||
.expect("read session file")
|
||||
.lines()
|
||||
.next()
|
||||
.expect("session metadata"),
|
||||
)
|
||||
.expect("parse session metadata");
|
||||
session_meta["payload"]["history_base"] =
|
||||
serde_json::to_value(history_base).expect("serialize history base");
|
||||
std::fs::write(path, format!("{session_meta}\n")).expect("write session file");
|
||||
}
|
||||
|
||||
fn set_thread_id(path: &Path, thread_id: ThreadId) {
|
||||
let mut session_meta: serde_json::Value = serde_json::from_str(
|
||||
std::fs::read_to_string(path)
|
||||
.expect("read session file")
|
||||
.lines()
|
||||
.next()
|
||||
.expect("session metadata"),
|
||||
)
|
||||
.expect("parse session metadata");
|
||||
session_meta["payload"]["id"] = serde_json::to_value(thread_id).expect("thread id");
|
||||
std::fs::write(path, format!("{session_meta}\n")).expect("write session file");
|
||||
}
|
||||
}
|
||||
393
codex-rs/thread-store/src/local/helpers.rs
Normal file
393
codex-rs/thread-store/src/local/helpers.rs
Normal file
@@ -0,0 +1,393 @@
|
||||
use std::collections::HashMap;
|
||||
use std::collections::HashSet;
|
||||
use std::ffi::OsStr;
|
||||
use std::fs::FileTimes;
|
||||
use std::fs::OpenOptions;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use std::time::SystemTime;
|
||||
|
||||
use chrono::DateTime;
|
||||
use chrono::Utc;
|
||||
use codex_git_utils::GitSha;
|
||||
use codex_protocol::SanitizedGitUrl;
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::models::PermissionProfile;
|
||||
use codex_protocol::protocol::AskForApproval;
|
||||
use codex_protocol::protocol::GitInfo;
|
||||
use codex_protocol::protocol::NetworkAccess;
|
||||
use codex_protocol::protocol::SandboxPolicy;
|
||||
use codex_protocol::protocol::SessionSource;
|
||||
use codex_protocol::protocol::ThreadHistoryMode;
|
||||
use codex_rollout::ARCHIVED_SESSIONS_SUBDIR;
|
||||
use codex_rollout::RolloutReferenceIndex;
|
||||
use codex_rollout::ThreadItem;
|
||||
use codex_rollout::find_thread_names_by_ids;
|
||||
use codex_state::ThreadMetadata;
|
||||
|
||||
use super::LocalThreadStore;
|
||||
use crate::StoredThread;
|
||||
use crate::ThreadStoreError;
|
||||
use crate::ThreadStoreResult;
|
||||
|
||||
pub(super) fn scoped_rollout_path(
|
||||
root: PathBuf,
|
||||
rollout_path: &Path,
|
||||
root_name: &str,
|
||||
) -> ThreadStoreResult<PathBuf> {
|
||||
let canonical_root =
|
||||
std::fs::canonicalize(&root).map_err(|err| ThreadStoreError::Internal {
|
||||
message: format!(
|
||||
"failed to resolve {root_name} directory `{}`: {err}",
|
||||
root.display()
|
||||
),
|
||||
})?;
|
||||
let canonical_rollout_path =
|
||||
std::fs::canonicalize(rollout_path).map_err(|_| ThreadStoreError::InvalidRequest {
|
||||
message: format!(
|
||||
"rollout path `{}` must be in {root_name} directory",
|
||||
rollout_path.display()
|
||||
),
|
||||
})?;
|
||||
if canonical_rollout_path.starts_with(&canonical_root) {
|
||||
Ok(canonical_rollout_path)
|
||||
} else {
|
||||
Err(ThreadStoreError::InvalidRequest {
|
||||
message: format!(
|
||||
"rollout path `{}` must be in {root_name} directory",
|
||||
rollout_path.display()
|
||||
),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn rollout_path_is_archived(codex_home: &Path, path: &Path) -> bool {
|
||||
path.starts_with(codex_home.join(ARCHIVED_SESSIONS_SUBDIR))
|
||||
|| path
|
||||
.components()
|
||||
.any(|component| component.as_os_str() == OsStr::new(ARCHIVED_SESSIONS_SUBDIR))
|
||||
}
|
||||
|
||||
pub(super) fn owned_rollout_paths_from_index(
|
||||
index: &RolloutReferenceIndex,
|
||||
thread_id: ThreadId,
|
||||
) -> Vec<PathBuf> {
|
||||
index
|
||||
.rollouts_for_thread(thread_id)
|
||||
.map(|(_, path)| path.to_path_buf())
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub(super) fn validated_rollout_file_name(
|
||||
rollout_path: &Path,
|
||||
display_path: &Path,
|
||||
) -> ThreadStoreResult<std::ffi::OsString> {
|
||||
let Some(file_name) = rollout_path.file_name().map(OsStr::to_owned) else {
|
||||
return Err(ThreadStoreError::InvalidRequest {
|
||||
message: format!(
|
||||
"rollout path `{}` missing file name",
|
||||
display_path.display()
|
||||
),
|
||||
});
|
||||
};
|
||||
if codex_rollout::rollout_id_from_path(rollout_path).is_some() {
|
||||
Ok(file_name)
|
||||
} else {
|
||||
Err(ThreadStoreError::InvalidRequest {
|
||||
message: format!(
|
||||
"rollout path `{}` has an invalid filename",
|
||||
display_path.display()
|
||||
),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn touch_modified_time(path: &Path) -> std::io::Result<()> {
|
||||
let times = FileTimes::new().set_modified(SystemTime::now());
|
||||
OpenOptions::new().append(true).open(path)?.set_times(times)
|
||||
}
|
||||
|
||||
pub(super) fn restore_rollout_moves(moves: &[(PathBuf, PathBuf)]) -> std::io::Result<()> {
|
||||
for (source, destination) in moves.iter().rev() {
|
||||
std::fs::rename(destination, source)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn stored_thread_from_rollout_item(
|
||||
item: ThreadItem,
|
||||
archived: bool,
|
||||
default_provider: &str,
|
||||
) -> Option<StoredThread> {
|
||||
let thread_id = item
|
||||
.thread_id
|
||||
.or_else(|| thread_id_from_rollout_path(item.path.as_path()))?;
|
||||
let created_at = parse_rfc3339(item.created_at.as_deref()).unwrap_or_else(Utc::now);
|
||||
let updated_at = parse_rfc3339(item.updated_at.as_deref()).unwrap_or(created_at);
|
||||
let recency_at = parse_rfc3339(item.recency_at.as_deref()).unwrap_or(updated_at);
|
||||
let archived_at = archived.then_some(updated_at);
|
||||
let git_info = git_info_from_parts(
|
||||
item.git_sha.clone(),
|
||||
item.git_branch.clone(),
|
||||
item.git_origin_url.clone(),
|
||||
);
|
||||
let source = item.source.unwrap_or(SessionSource::Unknown);
|
||||
let preview = item
|
||||
.preview
|
||||
.clone()
|
||||
.or_else(|| item.first_user_message.clone())
|
||||
.unwrap_or_default();
|
||||
let rollout_path = codex_rollout::plain_rollout_path(item.path.as_path());
|
||||
|
||||
Some(StoredThread {
|
||||
creator_user_id: None,
|
||||
creator_account_id: None,
|
||||
thread_id,
|
||||
extra_config: None,
|
||||
rollout_path: Some(rollout_path),
|
||||
forked_from_id: None,
|
||||
parent_thread_id: item.parent_thread_id,
|
||||
preview,
|
||||
name: codex_state::is_guardian_review_source(&source)
|
||||
.then(|| codex_state::GUARDIAN_THREAD_TITLE.to_string()),
|
||||
model_provider: item
|
||||
.model_provider
|
||||
.filter(|provider| !provider.is_empty())
|
||||
.unwrap_or_else(|| default_provider.to_string()),
|
||||
model: item.model,
|
||||
reasoning_effort: item.reasoning_effort,
|
||||
created_at,
|
||||
updated_at,
|
||||
recency_at,
|
||||
archived_at,
|
||||
section: item.section,
|
||||
section_position: None,
|
||||
section_entered_at: None,
|
||||
project_id: item.project_id,
|
||||
daybreak_enabled: item.daybreak_enabled,
|
||||
cwd: item.cwd.unwrap_or_default(),
|
||||
cli_version: item.cli_version.unwrap_or_default(),
|
||||
originator: item.originator,
|
||||
source,
|
||||
history_mode: item.history_mode,
|
||||
thread_source: None,
|
||||
agent_nickname: item.agent_nickname,
|
||||
agent_role: item.agent_role,
|
||||
agent_path: None,
|
||||
git_info,
|
||||
approval_mode: AskForApproval::OnRequest,
|
||||
permission_profile: PermissionProfile::read_only(),
|
||||
token_usage: None,
|
||||
first_user_message: item.first_user_message,
|
||||
history: None,
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn permission_profile_from_metadata_value(value: &str, cwd: &Path) -> PermissionProfile {
|
||||
serde_json::from_str::<PermissionProfile>(value)
|
||||
.or_else(|_| {
|
||||
parse_legacy_sandbox_policy(value)
|
||||
.map(|policy| PermissionProfile::from_legacy_sandbox_policy_for_cwd(&policy, cwd))
|
||||
})
|
||||
.unwrap_or_else(|_| PermissionProfile::read_only())
|
||||
}
|
||||
|
||||
pub(super) fn permission_profile_to_metadata_value(
|
||||
permission_profile: &PermissionProfile,
|
||||
) -> String {
|
||||
match serde_json::to_string(permission_profile) {
|
||||
Ok(value) => value,
|
||||
Err(err) => {
|
||||
tracing::warn!("failed to serialize permission profile metadata: {err}");
|
||||
String::new()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn sqlite_thread_name(metadata: &ThreadMetadata) -> Option<String> {
|
||||
metadata
|
||||
.name
|
||||
.as_deref()
|
||||
.map(str::trim)
|
||||
.filter(|name| !name.is_empty())
|
||||
.map(str::to_string)
|
||||
}
|
||||
|
||||
pub(super) async fn resolve_thread_section_metadata(
|
||||
state_db: &codex_state::StateRuntime,
|
||||
thread_ids: &[ThreadId],
|
||||
) -> HashMap<ThreadId, (Option<i64>, Option<DateTime<Utc>>)> {
|
||||
if thread_ids.is_empty() {
|
||||
return HashMap::new();
|
||||
}
|
||||
|
||||
state_db
|
||||
.get_thread_section_ordering(thread_ids)
|
||||
.await
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// DB-only listings require complete names; ordinary listings retain best-effort enrichment.
|
||||
pub(super) async fn resolve_thread_names(
|
||||
store: &LocalThreadStore,
|
||||
thread_history_modes: &HashMap<ThreadId, ThreadHistoryMode>,
|
||||
use_state_db_only: bool,
|
||||
) -> ThreadStoreResult<HashMap<ThreadId, String>> {
|
||||
let legacy_thread_ids = thread_history_modes
|
||||
.iter()
|
||||
.filter_map(|(&thread_id, &history_mode)| {
|
||||
(history_mode == ThreadHistoryMode::Legacy).then_some(thread_id)
|
||||
})
|
||||
.collect::<HashSet<_>>();
|
||||
let mut names =
|
||||
match find_thread_names_by_ids(store.config.codex_home.as_path(), &legacy_thread_ids).await
|
||||
{
|
||||
Ok(names) => names,
|
||||
Err(err) if use_state_db_only => {
|
||||
return Err(ThreadStoreError::Internal {
|
||||
message: format!("failed to read indexed thread names: {err}"),
|
||||
});
|
||||
}
|
||||
Err(_) => HashMap::new(),
|
||||
};
|
||||
if let Some(state_db_ctx) = store.state_db().await {
|
||||
let thread_ids = thread_history_modes.keys().copied().collect::<Vec<_>>();
|
||||
let metadata_by_id = match state_db_ctx.get_threads(&thread_ids).await {
|
||||
Ok(metadata) => metadata,
|
||||
Err(err) if use_state_db_only => {
|
||||
return Err(ThreadStoreError::Internal {
|
||||
message: format!("failed to read thread names from state DB: {err}"),
|
||||
});
|
||||
}
|
||||
Err(_) => return Ok(names),
|
||||
};
|
||||
for (&thread_id, &history_mode) in thread_history_modes {
|
||||
let Some(metadata) = metadata_by_id.get(&thread_id) else {
|
||||
continue;
|
||||
};
|
||||
let name = match history_mode {
|
||||
ThreadHistoryMode::Legacy => distinct_thread_metadata_title(metadata),
|
||||
ThreadHistoryMode::Paginated => sqlite_thread_name(metadata),
|
||||
};
|
||||
if let Some(name) = name {
|
||||
if history_mode == ThreadHistoryMode::Legacy && has_guardian_default_title(metadata)
|
||||
{
|
||||
names.entry(thread_id).or_insert(name);
|
||||
} else {
|
||||
names.insert(thread_id, name);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(names)
|
||||
}
|
||||
|
||||
/// Identifies the derived Guardian label, which must yield to legacy indexed names.
|
||||
pub(super) fn has_guardian_default_title(metadata: &ThreadMetadata) -> bool {
|
||||
metadata.title.trim() == codex_state::GUARDIAN_THREAD_TITLE
|
||||
&& serde_json::from_str::<SessionSource>(&metadata.source)
|
||||
.as_ref()
|
||||
.is_ok_and(codex_state::is_guardian_review_source)
|
||||
}
|
||||
|
||||
pub(super) fn distinct_thread_metadata_title(metadata: &ThreadMetadata) -> Option<String> {
|
||||
let title = metadata.title.trim();
|
||||
if title.is_empty() || metadata.first_user_message.as_deref().map(str::trim) == Some(title) {
|
||||
None
|
||||
} else {
|
||||
Some(title.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn set_thread_name(thread: &mut StoredThread, name: String) {
|
||||
if thread.history_mode == ThreadHistoryMode::Paginated || thread.preview.trim() != name.trim() {
|
||||
thread.name = Some(name);
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_rfc3339(value: Option<&str>) -> Option<DateTime<Utc>> {
|
||||
DateTime::parse_from_rfc3339(value?)
|
||||
.ok()
|
||||
.map(|dt| dt.with_timezone(&Utc))
|
||||
}
|
||||
|
||||
fn parse_legacy_sandbox_policy(value: &str) -> serde_json::Result<SandboxPolicy> {
|
||||
serde_json::from_str(value)
|
||||
.or_else(|_| serde_json::from_value(serde_json::Value::String(value.to_string())))
|
||||
.or_else(|_| match value {
|
||||
"danger-full-access" => Ok(SandboxPolicy::DangerFullAccess),
|
||||
"read-only" => Ok(SandboxPolicy::new_read_only_policy()),
|
||||
"workspace-write" => Ok(SandboxPolicy::new_workspace_write_policy()),
|
||||
"external-sandbox" => Ok(SandboxPolicy::ExternalSandbox {
|
||||
network_access: NetworkAccess::Restricted,
|
||||
}),
|
||||
_ => serde_json::from_value(serde_json::Value::String(value.to_string())),
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn git_info_from_parts(
|
||||
sha: Option<String>,
|
||||
branch: Option<String>,
|
||||
origin_url: Option<SanitizedGitUrl>,
|
||||
) -> Option<GitInfo> {
|
||||
if sha.is_none() && branch.is_none() && origin_url.is_none() {
|
||||
return None;
|
||||
}
|
||||
Some(GitInfo {
|
||||
commit_hash: sha.as_deref().map(GitSha::new),
|
||||
branch,
|
||||
repository_url: origin_url,
|
||||
})
|
||||
}
|
||||
|
||||
fn thread_id_from_rollout_path(path: &Path) -> Option<ThreadId> {
|
||||
let file_name = path.file_name()?.to_str()?;
|
||||
let file_name = file_name.strip_suffix(".zst").unwrap_or(file_name);
|
||||
let stem = file_name.strip_suffix(".jsonl")?;
|
||||
if stem.len() < 37 {
|
||||
return None;
|
||||
}
|
||||
let uuid_start = stem.len().saturating_sub(36);
|
||||
if !stem[..uuid_start].ends_with('-') {
|
||||
return None;
|
||||
}
|
||||
ThreadId::from_string(&stem[uuid_start..]).ok()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use codex_protocol::protocol::SubAgentSource;
|
||||
use codex_rollout::ThreadItem;
|
||||
use pretty_assertions::assert_eq;
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn guardian_rollout_conversion_preserves_name_and_logical_path() {
|
||||
let uuid = Uuid::from_u128(1);
|
||||
let compressed_path = PathBuf::from(format!(
|
||||
"/tmp/sessions/2025/01/03/rollout-2025-01-03T12-00-00-{uuid}.jsonl.zst"
|
||||
));
|
||||
let thread = stored_thread_from_rollout_item(
|
||||
ThreadItem {
|
||||
path: compressed_path.clone(),
|
||||
source: Some(SessionSource::SubAgent(SubAgentSource::Other(
|
||||
"guardian".to_string(),
|
||||
))),
|
||||
..Default::default()
|
||||
},
|
||||
/*archived*/ false,
|
||||
"test-provider",
|
||||
)
|
||||
.expect("stored thread");
|
||||
|
||||
assert_eq!(thread.name.as_deref(), Some("Guardian review"));
|
||||
assert_eq!(
|
||||
thread.rollout_path,
|
||||
Some(
|
||||
compressed_path.with_file_name(format!("rollout-2025-01-03T12-00-00-{uuid}.jsonl"))
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
28
codex-rs/thread-store/src/local/history_revision.rs
Normal file
28
codex-rs/thread-store/src/local/history_revision.rs
Normal file
@@ -0,0 +1,28 @@
|
||||
//! Validates snapshots of append-only local rollouts before reusing them for resume.
|
||||
//!
|
||||
//! Capture before and after reading; any change or unavailable metadata disables reuse. The
|
||||
//! selected path prevents reuse for a different rollout. Validate under writer ownership,
|
||||
//! before opening the recorder can materialize a compressed file.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
pub(super) async fn read(path: &Path) -> Option<String> {
|
||||
let path = codex_rollout::existing_rollout_path(path).await?;
|
||||
let path = tokio::fs::canonicalize(path).await.ok()?;
|
||||
let metadata = tokio::fs::metadata(&path).await.ok()?;
|
||||
let modified = metadata.modified().ok()?;
|
||||
let created = metadata.created().ok();
|
||||
#[cfg(unix)]
|
||||
let identity = {
|
||||
use std::os::unix::fs::MetadataExt;
|
||||
Some((
|
||||
metadata.dev(),
|
||||
metadata.ino(),
|
||||
metadata.ctime(),
|
||||
metadata.ctime_nsec(),
|
||||
))
|
||||
};
|
||||
#[cfg(not(unix))]
|
||||
let identity: Option<(u64, u64, i64, i64)> = None;
|
||||
serde_json::to_string(&("local", path, metadata.len(), modified, created, identity)).ok()
|
||||
}
|
||||
808
codex-rs/thread-store/src/local/list_threads.rs
Normal file
808
codex-rs/thread-store/src/local/list_threads.rs
Normal file
@@ -0,0 +1,808 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
use chrono::DateTime;
|
||||
use chrono::Utc;
|
||||
use codex_rollout::RolloutConfig;
|
||||
use codex_rollout::RolloutRecorder;
|
||||
use codex_rollout::parse_cursor;
|
||||
use codex_state::ThreadFilterOptions;
|
||||
|
||||
use super::LocalThreadStore;
|
||||
use super::helpers::resolve_thread_names;
|
||||
use super::helpers::resolve_thread_section_metadata;
|
||||
use super::helpers::set_thread_name;
|
||||
use super::helpers::stored_thread_from_rollout_item;
|
||||
use super::read_thread::stored_thread_from_state_metadata;
|
||||
use crate::ListThreadsParams;
|
||||
use crate::SortDirection;
|
||||
use crate::ThreadPage;
|
||||
use crate::ThreadRelationFilter;
|
||||
use crate::ThreadSortKey;
|
||||
use crate::ThreadStoreError;
|
||||
use crate::ThreadStoreResult;
|
||||
|
||||
pub(super) async fn list_threads(
|
||||
store: &LocalThreadStore,
|
||||
params: ListThreadsParams,
|
||||
) -> ThreadStoreResult<ThreadPage> {
|
||||
if params.sort_key == ThreadSortKey::SectionPosition {
|
||||
return list_section_threads(store, params).await;
|
||||
}
|
||||
let cursor = params
|
||||
.cursor
|
||||
.as_deref()
|
||||
.map(|cursor| {
|
||||
parse_cursor(cursor).ok_or_else(|| ThreadStoreError::InvalidRequest {
|
||||
message: format!("invalid cursor: {cursor}"),
|
||||
})
|
||||
})
|
||||
.transpose()?;
|
||||
let sort_key = match params.sort_key {
|
||||
ThreadSortKey::CreatedAt => codex_rollout::ThreadSortKey::CreatedAt,
|
||||
ThreadSortKey::UpdatedAt => codex_rollout::ThreadSortKey::UpdatedAt,
|
||||
ThreadSortKey::RecencyAt => codex_rollout::ThreadSortKey::RecencyAt,
|
||||
ThreadSortKey::SectionPosition => unreachable!("section order uses the state database"),
|
||||
};
|
||||
let sort_direction = match params.sort_direction {
|
||||
SortDirection::Asc => codex_rollout::SortDirection::Asc,
|
||||
SortDirection::Desc => codex_rollout::SortDirection::Desc,
|
||||
};
|
||||
let state_db = store.state_db().await;
|
||||
let rollout_config = RolloutConfig {
|
||||
codex_home: store.config.codex_home.clone(),
|
||||
sqlite: store.config.sqlite.clone(),
|
||||
cwd: store.config.codex_home.clone(),
|
||||
model_provider_id: store.config.default_model_provider_id.clone(),
|
||||
generate_memories: false,
|
||||
};
|
||||
let page = list_rollout_threads(
|
||||
state_db.clone(),
|
||||
&rollout_config,
|
||||
store.config.default_model_provider_id.as_str(),
|
||||
¶ms,
|
||||
cursor.as_ref(),
|
||||
sort_key,
|
||||
sort_direction,
|
||||
)
|
||||
.await?;
|
||||
|
||||
let next_cursor = page
|
||||
.next_cursor
|
||||
.as_ref()
|
||||
.and_then(|cursor| serde_json::to_value(cursor).ok())
|
||||
.and_then(|value| value.as_str().map(str::to_owned));
|
||||
let mut items = page
|
||||
.items
|
||||
.into_iter()
|
||||
.filter_map(|item| {
|
||||
stored_thread_from_rollout_item(
|
||||
item,
|
||||
params.archived,
|
||||
store.config.default_model_provider_id.as_str(),
|
||||
)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
let thread_history_modes = items
|
||||
.iter()
|
||||
.map(|thread| (thread.thread_id, thread.history_mode))
|
||||
.collect::<HashMap<_, _>>();
|
||||
let names =
|
||||
resolve_thread_names(store, &thread_history_modes, params.use_state_db_only).await?;
|
||||
for thread in &mut items {
|
||||
if let Some(name) = names.get(&thread.thread_id).cloned() {
|
||||
set_thread_name(thread, name);
|
||||
}
|
||||
}
|
||||
if let Some(state_db) = state_db {
|
||||
let sectioned_thread_ids = items
|
||||
.iter()
|
||||
.filter(|thread| thread.section.is_some())
|
||||
.map(|thread| thread.thread_id)
|
||||
.collect::<Vec<_>>();
|
||||
let section_metadata =
|
||||
resolve_thread_section_metadata(state_db.as_ref(), §ioned_thread_ids).await;
|
||||
for thread in items.iter_mut().filter(|thread| thread.section.is_some()) {
|
||||
if let Some((section_position, section_entered_at)) =
|
||||
section_metadata.get(&thread.thread_id)
|
||||
{
|
||||
thread.section_position = *section_position;
|
||||
thread.section_entered_at = *section_entered_at;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(project_id) = params.project_id.as_ref() {
|
||||
items.retain(|thread| &thread.project_id == project_id);
|
||||
}
|
||||
|
||||
Ok(ThreadPage { items, next_cursor })
|
||||
}
|
||||
|
||||
async fn list_section_threads(
|
||||
store: &LocalThreadStore,
|
||||
params: ListThreadsParams,
|
||||
) -> ThreadStoreResult<ThreadPage> {
|
||||
let section = params
|
||||
.section
|
||||
.as_ref()
|
||||
.and_then(Option::as_deref)
|
||||
.ok_or_else(|| ThreadStoreError::InvalidRequest {
|
||||
message: "section-position sorting requires a section filter".to_owned(),
|
||||
})?;
|
||||
let state_db = store
|
||||
.state_db()
|
||||
.await
|
||||
.ok_or_else(|| ThreadStoreError::Internal {
|
||||
message: "state DB unavailable for section-ordered thread listing".to_owned(),
|
||||
})?;
|
||||
|
||||
let anchor = params
|
||||
.cursor
|
||||
.as_deref()
|
||||
.map(|cursor| -> ThreadStoreResult<codex_state::Anchor> {
|
||||
let (position, thread_id) =
|
||||
cursor
|
||||
.split_once('|')
|
||||
.ok_or_else(|| ThreadStoreError::InvalidRequest {
|
||||
message: format!("invalid cursor: {cursor}"),
|
||||
})?;
|
||||
let timestamp = position
|
||||
.parse::<i64>()
|
||||
.ok()
|
||||
.and_then(DateTime::<Utc>::from_timestamp_millis)
|
||||
.ok_or_else(|| ThreadStoreError::InvalidRequest {
|
||||
message: format!("invalid cursor: {cursor}"),
|
||||
})?;
|
||||
let thread_id = codex_protocol::ThreadId::from_string(thread_id).map_err(|_| {
|
||||
ThreadStoreError::InvalidRequest {
|
||||
message: format!("invalid cursor: {cursor}"),
|
||||
}
|
||||
})?;
|
||||
Ok(codex_state::Anchor {
|
||||
ts: timestamp,
|
||||
id: Some(thread_id),
|
||||
})
|
||||
})
|
||||
.transpose()?;
|
||||
let allowed_sources = params
|
||||
.allowed_sources
|
||||
.iter()
|
||||
.map(|source| match serde_json::to_value(source) {
|
||||
Ok(serde_json::Value::String(source)) => source,
|
||||
Ok(source) => source.to_string(),
|
||||
Err(_) => String::new(),
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let normalized_cwd_filters = params.cwd_filters.as_ref().map(|filters| {
|
||||
filters
|
||||
.iter()
|
||||
.map(|cwd| codex_rollout::state_db::normalize_cwd_for_state_db(cwd))
|
||||
.collect::<Vec<_>>()
|
||||
});
|
||||
let filters = ThreadFilterOptions {
|
||||
archived_only: params.archived,
|
||||
allowed_sources: allowed_sources.as_slice(),
|
||||
model_providers: params.model_providers.as_deref(),
|
||||
cwd_filters: normalized_cwd_filters.as_deref(),
|
||||
section: Some(Some(section)),
|
||||
project_id: params
|
||||
.project_id
|
||||
.as_ref()
|
||||
.map(|project_id| project_id.as_deref()),
|
||||
anchor: anchor.as_ref(),
|
||||
sort_key: codex_state::SortKey::SectionPosition,
|
||||
sort_direction: match params.sort_direction {
|
||||
SortDirection::Asc => codex_state::SortDirection::Asc,
|
||||
SortDirection::Desc => codex_state::SortDirection::Desc,
|
||||
},
|
||||
search_term: params.search_term.as_deref(),
|
||||
};
|
||||
let page = match params.relation_filter.map(state_relation_filter) {
|
||||
Some(relation_filter) => {
|
||||
state_db
|
||||
.list_threads_by_relation(params.page_size, relation_filter, filters)
|
||||
.await
|
||||
}
|
||||
None => state_db.list_threads(params.page_size, filters).await,
|
||||
}
|
||||
.map_err(|err| ThreadStoreError::Internal {
|
||||
message: format!("failed to list section-ordered threads: {err}"),
|
||||
})?;
|
||||
|
||||
let codex_state::ThreadsPage {
|
||||
items: metadata_items,
|
||||
parent_thread_ids,
|
||||
next_anchor,
|
||||
..
|
||||
} = page;
|
||||
let items = metadata_items
|
||||
.into_iter()
|
||||
.map(|metadata| {
|
||||
let parent_thread_id = parent_thread_ids.get(&metadata.id).copied();
|
||||
stored_thread_from_state_metadata(store, metadata, parent_thread_id)
|
||||
})
|
||||
.collect();
|
||||
let next_cursor = next_anchor.and_then(|anchor| {
|
||||
anchor.id.map(|thread_id| {
|
||||
let position = anchor.ts.timestamp_millis();
|
||||
format!("{position}|{thread_id}")
|
||||
})
|
||||
});
|
||||
Ok(ThreadPage { items, next_cursor })
|
||||
}
|
||||
|
||||
pub(super) async fn list_rollout_threads(
|
||||
state_db: Option<codex_rollout::StateDbHandle>,
|
||||
config: &RolloutConfig,
|
||||
default_model_provider_id: &str,
|
||||
params: &ListThreadsParams,
|
||||
cursor: Option<&codex_rollout::Cursor>,
|
||||
sort_key: codex_rollout::ThreadSortKey,
|
||||
sort_direction: codex_rollout::SortDirection,
|
||||
) -> ThreadStoreResult<codex_rollout::ThreadsPage> {
|
||||
if params.relation_filter.is_some() || params.section.is_some() || params.project_id.is_some() {
|
||||
let page = codex_rollout::state_db::list_threads_db(
|
||||
state_db.as_deref(),
|
||||
&config.sqlite,
|
||||
params.page_size,
|
||||
cursor,
|
||||
sort_key,
|
||||
sort_direction,
|
||||
params.allowed_sources.as_slice(),
|
||||
params.model_providers.as_deref(),
|
||||
params.cwd_filters.as_deref(),
|
||||
params.relation_filter.map(state_relation_filter),
|
||||
params.archived,
|
||||
params.section.as_ref().map(Option::as_deref),
|
||||
params.project_id.as_ref().map(Option::as_deref),
|
||||
params.search_term.as_deref(),
|
||||
)
|
||||
.await
|
||||
.ok_or_else(|| ThreadStoreError::Internal {
|
||||
message: "state DB unavailable for filtered thread listing".to_string(),
|
||||
})?;
|
||||
return Ok(page.into());
|
||||
}
|
||||
|
||||
let page = if params.use_state_db_only && params.archived {
|
||||
RolloutRecorder::list_archived_threads_from_state_db(
|
||||
state_db,
|
||||
config,
|
||||
params.page_size,
|
||||
cursor,
|
||||
sort_key,
|
||||
sort_direction,
|
||||
params.allowed_sources.as_slice(),
|
||||
params.model_providers.as_deref(),
|
||||
params.cwd_filters.as_deref(),
|
||||
default_model_provider_id,
|
||||
params.search_term.as_deref(),
|
||||
)
|
||||
.await
|
||||
} else if params.use_state_db_only {
|
||||
RolloutRecorder::list_threads_from_state_db(
|
||||
state_db,
|
||||
config,
|
||||
params.page_size,
|
||||
cursor,
|
||||
sort_key,
|
||||
sort_direction,
|
||||
params.allowed_sources.as_slice(),
|
||||
params.model_providers.as_deref(),
|
||||
params.cwd_filters.as_deref(),
|
||||
default_model_provider_id,
|
||||
params.search_term.as_deref(),
|
||||
)
|
||||
.await
|
||||
} else if params.archived {
|
||||
RolloutRecorder::list_archived_threads(
|
||||
state_db,
|
||||
config,
|
||||
params.page_size,
|
||||
cursor,
|
||||
sort_key,
|
||||
sort_direction,
|
||||
params.allowed_sources.as_slice(),
|
||||
params.model_providers.as_deref(),
|
||||
params.cwd_filters.as_deref(),
|
||||
default_model_provider_id,
|
||||
params.search_term.as_deref(),
|
||||
)
|
||||
.await
|
||||
} else {
|
||||
RolloutRecorder::list_threads(
|
||||
state_db,
|
||||
config,
|
||||
params.page_size,
|
||||
cursor,
|
||||
sort_key,
|
||||
sort_direction,
|
||||
params.allowed_sources.as_slice(),
|
||||
params.model_providers.as_deref(),
|
||||
params.cwd_filters.as_deref(),
|
||||
default_model_provider_id,
|
||||
params.search_term.as_deref(),
|
||||
)
|
||||
.await
|
||||
};
|
||||
page.map_err(|err| ThreadStoreError::Internal {
|
||||
message: format!("failed to list threads: {err}"),
|
||||
})
|
||||
}
|
||||
|
||||
fn state_relation_filter(filter: ThreadRelationFilter) -> codex_state::ThreadRelationFilter {
|
||||
match filter {
|
||||
ThreadRelationFilter::DirectChildrenOf(id) => {
|
||||
codex_state::ThreadRelationFilter::DirectChildrenOf(id)
|
||||
}
|
||||
ThreadRelationFilter::DescendantsOf(id) => {
|
||||
codex_state::ThreadRelationFilter::DescendantsOf(id)
|
||||
}
|
||||
ThreadRelationFilter::AttachedThreadsOf(id) => {
|
||||
codex_state::ThreadRelationFilter::AttachedThreadsOf(id)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use chrono::Utc;
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::protocol::SessionSource;
|
||||
use codex_protocol::protocol::ThreadHistoryMode;
|
||||
use codex_state::PINNED_THREAD_SECTION_ID;
|
||||
use codex_utils_absolute_path::test_support::PathExt;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::fs;
|
||||
use tempfile::TempDir;
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::*;
|
||||
use crate::MoveThreadToSectionParams;
|
||||
use crate::ThreadStore;
|
||||
use crate::local::LocalThreadStore;
|
||||
use crate::local::test_support::test_config;
|
||||
use crate::local::test_support::write_archived_session_file;
|
||||
use crate::local::test_support::write_session_file;
|
||||
use crate::local::test_support::write_session_file_with;
|
||||
|
||||
#[tokio::test]
|
||||
async fn list_threads_uses_default_provider_when_rollout_omits_provider() {
|
||||
let home = TempDir::new().expect("temp dir");
|
||||
let store = LocalThreadStore::new(test_config(home.path()), /*state_db*/ None);
|
||||
write_session_file_with(
|
||||
home.path(),
|
||||
home.path().join("sessions/2025/01/03"),
|
||||
"2025-01-03T12-00-00",
|
||||
Uuid::from_u128(102),
|
||||
"Hello from user",
|
||||
/*model_provider*/ None,
|
||||
ThreadHistoryMode::Legacy,
|
||||
)
|
||||
.expect("session file");
|
||||
|
||||
let page = store
|
||||
.list_threads(ListThreadsParams {
|
||||
page_size: 10,
|
||||
cursor: None,
|
||||
sort_key: ThreadSortKey::CreatedAt,
|
||||
sort_direction: SortDirection::Desc,
|
||||
allowed_sources: Vec::new(),
|
||||
model_providers: None,
|
||||
cwd_filters: None,
|
||||
section: None,
|
||||
project_id: None,
|
||||
archived: false,
|
||||
search_term: None,
|
||||
relation_filter: None,
|
||||
use_state_db_only: false,
|
||||
})
|
||||
.await
|
||||
.expect("thread listing");
|
||||
|
||||
assert_eq!(page.items.len(), 1);
|
||||
assert_eq!(page.items[0].model_provider, "test-provider");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn list_threads_preserves_sqlite_title_search_results() {
|
||||
let home = TempDir::new().expect("temp dir");
|
||||
let config = test_config(home.path());
|
||||
let uuid = Uuid::from_u128(103);
|
||||
let thread_id = ThreadId::from_string(&uuid.to_string()).expect("valid thread id");
|
||||
let rollout_path = home.path().join("rollout-title-search.jsonl");
|
||||
fs::write(&rollout_path, "").expect("placeholder rollout file");
|
||||
|
||||
let runtime = codex_state::StateRuntime::init(
|
||||
codex_state::SqliteConfig::new_for_testing(home.path().abs()),
|
||||
config.default_model_provider_id.clone(),
|
||||
)
|
||||
.await
|
||||
.expect("state db should initialize");
|
||||
let store = LocalThreadStore::new(config.clone(), Some(runtime.clone()));
|
||||
runtime
|
||||
.mark_backfill_complete(/*last_watermark*/ None)
|
||||
.await
|
||||
.expect("backfill should be complete");
|
||||
let created_at = Utc::now();
|
||||
let mut builder = codex_state::ThreadMetadataBuilder::new(
|
||||
thread_id,
|
||||
rollout_path,
|
||||
created_at,
|
||||
SessionSource::Cli,
|
||||
);
|
||||
builder.model_provider = Some(config.default_model_provider_id.clone());
|
||||
builder.cwd = home.path().to_path_buf();
|
||||
builder.cli_version = Some("test_version".to_string());
|
||||
let mut metadata = builder.build(config.default_model_provider_id.as_str());
|
||||
metadata.title = "needle title".to_string();
|
||||
metadata.first_user_message = Some("plain preview".to_string());
|
||||
metadata.preview = metadata.first_user_message.clone();
|
||||
runtime
|
||||
.upsert_thread(&metadata)
|
||||
.await
|
||||
.expect("state db upsert should succeed");
|
||||
|
||||
let page = store
|
||||
.list_threads(ListThreadsParams {
|
||||
page_size: 10,
|
||||
cursor: None,
|
||||
sort_key: ThreadSortKey::CreatedAt,
|
||||
sort_direction: SortDirection::Desc,
|
||||
allowed_sources: Vec::new(),
|
||||
model_providers: None,
|
||||
cwd_filters: None,
|
||||
section: None,
|
||||
project_id: None,
|
||||
archived: false,
|
||||
search_term: Some("needle".to_string()),
|
||||
relation_filter: None,
|
||||
use_state_db_only: true,
|
||||
})
|
||||
.await
|
||||
.expect("thread listing");
|
||||
|
||||
let ids = page
|
||||
.items
|
||||
.iter()
|
||||
.map(|item| item.thread_id)
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(ids, vec![thread_id]);
|
||||
assert_eq!(
|
||||
page.items[0].first_user_message.as_deref(),
|
||||
Some("plain preview")
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn list_paginated_threads_uses_sqlite_name_over_legacy_compatibility() {
|
||||
let home = TempDir::new().expect("temp dir");
|
||||
let config = test_config(home.path());
|
||||
let uuid = Uuid::from_u128(104);
|
||||
let thread_id = ThreadId::from_string(&uuid.to_string()).expect("valid thread id");
|
||||
let rollout_path = home.path().join("rollout-paginated-name-search.jsonl");
|
||||
fs::write(&rollout_path, "").expect("placeholder rollout file");
|
||||
|
||||
let runtime = codex_state::StateRuntime::init(
|
||||
config.sqlite.clone(),
|
||||
config.default_model_provider_id.clone(),
|
||||
)
|
||||
.await
|
||||
.expect("state db should initialize");
|
||||
let store = LocalThreadStore::new(config.clone(), Some(runtime.clone()));
|
||||
runtime
|
||||
.mark_backfill_complete(/*last_watermark*/ None)
|
||||
.await
|
||||
.expect("backfill should be complete");
|
||||
let mut builder = codex_state::ThreadMetadataBuilder::new(
|
||||
thread_id,
|
||||
rollout_path,
|
||||
Utc::now(),
|
||||
SessionSource::Cli,
|
||||
);
|
||||
builder.history_mode = ThreadHistoryMode::Paginated;
|
||||
builder.model_provider = Some(config.default_model_provider_id.clone());
|
||||
builder.cwd = home.path().to_path_buf();
|
||||
builder.cli_version = Some("test_version".to_string());
|
||||
let mut metadata = builder.build(config.default_model_provider_id.as_str());
|
||||
metadata.name = Some("canonical paginated name".to_string());
|
||||
metadata.title = "stale title name".to_string();
|
||||
metadata.first_user_message = Some("plain preview".to_string());
|
||||
metadata.preview = metadata.first_user_message.clone();
|
||||
runtime
|
||||
.upsert_thread(&metadata)
|
||||
.await
|
||||
.expect("state db upsert should succeed");
|
||||
codex_rollout::append_thread_name(home.path(), thread_id, "stale index name")
|
||||
.await
|
||||
.expect("append legacy thread name");
|
||||
|
||||
let page = store
|
||||
.list_threads(ListThreadsParams {
|
||||
page_size: 10,
|
||||
cursor: None,
|
||||
sort_key: ThreadSortKey::CreatedAt,
|
||||
sort_direction: SortDirection::Desc,
|
||||
allowed_sources: Vec::new(),
|
||||
model_providers: None,
|
||||
cwd_filters: None,
|
||||
section: None,
|
||||
project_id: None,
|
||||
archived: false,
|
||||
search_term: Some("canonical".to_string()),
|
||||
relation_filter: None,
|
||||
use_state_db_only: true,
|
||||
})
|
||||
.await
|
||||
.expect("thread listing");
|
||||
|
||||
assert_eq!(page.items.len(), 1);
|
||||
assert_eq!(page.items[0].thread_id, thread_id);
|
||||
assert_eq!(
|
||||
page.items[0].name.as_deref(),
|
||||
Some("canonical paginated name")
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn list_threads_selects_active_or_archived_collection() {
|
||||
let home = TempDir::new().expect("temp dir");
|
||||
let store = LocalThreadStore::new(test_config(home.path()), /*state_db*/ None);
|
||||
let active_uuid = Uuid::from_u128(105);
|
||||
let archived_uuid = Uuid::from_u128(106);
|
||||
write_session_file(home.path(), "2025-01-03T12-00-00", active_uuid)
|
||||
.expect("active session file");
|
||||
write_archived_session_file(home.path(), "2025-01-03T13-00-00", archived_uuid)
|
||||
.expect("archived session file");
|
||||
|
||||
let active = store
|
||||
.list_threads(ListThreadsParams {
|
||||
page_size: 10,
|
||||
cursor: None,
|
||||
sort_key: ThreadSortKey::CreatedAt,
|
||||
sort_direction: SortDirection::Desc,
|
||||
allowed_sources: Vec::new(),
|
||||
model_providers: None,
|
||||
cwd_filters: None,
|
||||
section: None,
|
||||
project_id: None,
|
||||
archived: false,
|
||||
search_term: None,
|
||||
relation_filter: None,
|
||||
use_state_db_only: false,
|
||||
})
|
||||
.await
|
||||
.expect("active listing");
|
||||
let archived = store
|
||||
.list_threads(ListThreadsParams {
|
||||
page_size: 10,
|
||||
cursor: None,
|
||||
sort_key: ThreadSortKey::CreatedAt,
|
||||
sort_direction: SortDirection::Desc,
|
||||
allowed_sources: Vec::new(),
|
||||
model_providers: None,
|
||||
cwd_filters: None,
|
||||
section: None,
|
||||
project_id: None,
|
||||
archived: true,
|
||||
search_term: None,
|
||||
relation_filter: None,
|
||||
use_state_db_only: false,
|
||||
})
|
||||
.await
|
||||
.expect("archived listing");
|
||||
|
||||
let active_id = ThreadId::from_string(&active_uuid.to_string()).expect("valid thread id");
|
||||
let archived_id =
|
||||
ThreadId::from_string(&archived_uuid.to_string()).expect("valid thread id");
|
||||
assert_eq!(
|
||||
active
|
||||
.items
|
||||
.iter()
|
||||
.map(|item| item.thread_id)
|
||||
.collect::<Vec<_>>(),
|
||||
vec![active_id]
|
||||
);
|
||||
assert_eq!(
|
||||
archived
|
||||
.items
|
||||
.iter()
|
||||
.map(|item| item.thread_id)
|
||||
.collect::<Vec<_>>(),
|
||||
vec![archived_id]
|
||||
);
|
||||
assert_eq!(active.items[0].archived_at, None);
|
||||
assert_eq!(
|
||||
archived.items[0].archived_at,
|
||||
Some(archived.items[0].updated_at)
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn list_threads_returns_local_rollout_summary() {
|
||||
let home = TempDir::new().expect("temp dir");
|
||||
let config = test_config(home.path());
|
||||
let runtime = codex_state::StateRuntime::init(
|
||||
config.sqlite.clone(),
|
||||
config.default_model_provider_id.clone(),
|
||||
)
|
||||
.await
|
||||
.expect("initialize state DB");
|
||||
let store = LocalThreadStore::new(config, Some(runtime.clone()));
|
||||
let uuid = Uuid::from_u128(101);
|
||||
let path =
|
||||
write_session_file(home.path(), "2025-01-03T12-00-00", uuid).expect("session file");
|
||||
|
||||
let params = ListThreadsParams {
|
||||
page_size: 10,
|
||||
cursor: None,
|
||||
sort_key: ThreadSortKey::CreatedAt,
|
||||
sort_direction: SortDirection::Desc,
|
||||
allowed_sources: vec![SessionSource::Cli],
|
||||
model_providers: Some(vec!["test-provider".to_string()]),
|
||||
cwd_filters: None,
|
||||
section: None,
|
||||
project_id: None,
|
||||
archived: false,
|
||||
search_term: None,
|
||||
relation_filter: None,
|
||||
use_state_db_only: false,
|
||||
};
|
||||
let page = store
|
||||
.list_threads(params.clone())
|
||||
.await
|
||||
.expect("thread listing");
|
||||
|
||||
let thread_id = ThreadId::from_string(&uuid.to_string()).expect("valid thread id");
|
||||
assert_eq!(page.next_cursor, None);
|
||||
assert_eq!(page.items.len(), 1);
|
||||
assert_eq!(page.items[0].thread_id, thread_id);
|
||||
assert_eq!(page.items[0].rollout_path, Some(path));
|
||||
assert_eq!(page.items[0].preview, "Hello from user");
|
||||
assert_eq!(
|
||||
page.items[0].first_user_message.as_deref(),
|
||||
Some("Hello from user")
|
||||
);
|
||||
assert_eq!(page.items[0].model_provider, "test-provider");
|
||||
assert_eq!(page.items[0].cli_version, "test_version");
|
||||
assert_eq!(page.items[0].source, SessionSource::Cli);
|
||||
|
||||
// Name query errors must abort DB-only lookup while ordinary listing keeps its fallback.
|
||||
let history_modes = HashMap::from([(thread_id, ThreadHistoryMode::Legacy)]);
|
||||
codex_rollout::append_thread_name(home.path(), thread_id, "indexed name")
|
||||
.await
|
||||
.expect("write indexed name");
|
||||
runtime.close().await;
|
||||
resolve_thread_names(&store, &history_modes, /*use_state_db_only*/ true)
|
||||
.await
|
||||
.expect_err("name query errors must be reported");
|
||||
let fallback = store
|
||||
.list_threads(params)
|
||||
.await
|
||||
.expect("ordinary listing must preserve filesystem fallback");
|
||||
assert_eq!(fallback.items[0].thread_id, thread_id);
|
||||
assert_eq!(fallback.items[0].name.as_deref(), Some("indexed name"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn section_listing_uses_sqlite_metadata_without_reading_rollouts() {
|
||||
let home = TempDir::new().expect("temp dir");
|
||||
let config = test_config(home.path());
|
||||
let state = codex_state::StateRuntime::init(
|
||||
config.sqlite.clone(),
|
||||
config.default_model_provider_id.clone(),
|
||||
)
|
||||
.await
|
||||
.expect("initialize state");
|
||||
let store = LocalThreadStore::new(config, Some(state.clone()));
|
||||
let mut thread_ids = Vec::new();
|
||||
let mut first_rollout_path = None;
|
||||
|
||||
for index in 0..3 {
|
||||
let uuid = Uuid::from_u128(975 + index);
|
||||
let thread_id = ThreadId::from_string(&uuid.to_string()).expect("valid thread id");
|
||||
let timestamp = format!("2025-01-03T16-{index:02}-00");
|
||||
let rollout_path =
|
||||
write_session_file(home.path(), ×tamp, uuid).expect("write rollout");
|
||||
codex_rollout::state_db::reconcile_rollout(
|
||||
Some(state.as_ref()),
|
||||
rollout_path.as_path(),
|
||||
"test-provider",
|
||||
/*builder*/ None,
|
||||
&[],
|
||||
/*archived_only*/ None,
|
||||
/*new_thread_memory_mode*/ None,
|
||||
)
|
||||
.await;
|
||||
store
|
||||
.move_thread_to_section(MoveThreadToSectionParams {
|
||||
thread_id,
|
||||
section: Some(PINNED_THREAD_SECTION_ID.to_owned()),
|
||||
before_thread_id: None,
|
||||
})
|
||||
.await
|
||||
.expect("append section member");
|
||||
thread_ids.push(thread_id);
|
||||
if index == 0 {
|
||||
first_rollout_path = Some(rollout_path);
|
||||
}
|
||||
}
|
||||
fs::remove_file(first_rollout_path.expect("first rollout path"))
|
||||
.expect("remove rollout without invalidating SQLite metadata");
|
||||
|
||||
let params = ListThreadsParams {
|
||||
page_size: 2,
|
||||
cursor: None,
|
||||
sort_key: ThreadSortKey::SectionPosition,
|
||||
sort_direction: SortDirection::Asc,
|
||||
allowed_sources: Vec::new(),
|
||||
model_providers: None,
|
||||
cwd_filters: None,
|
||||
section: Some(Some(PINNED_THREAD_SECTION_ID.to_owned())),
|
||||
project_id: None,
|
||||
archived: false,
|
||||
search_term: None,
|
||||
relation_filter: None,
|
||||
use_state_db_only: true,
|
||||
};
|
||||
let page = store
|
||||
.list_threads(params.clone())
|
||||
.await
|
||||
.expect("section listing should use SQLite metadata");
|
||||
|
||||
assert_eq!(
|
||||
page.items
|
||||
.iter()
|
||||
.map(|thread| thread.thread_id)
|
||||
.collect::<Vec<_>>(),
|
||||
vec![thread_ids[0], thread_ids[1]]
|
||||
);
|
||||
assert_eq!(page.next_cursor, Some(format!("2000000|{}", thread_ids[1])));
|
||||
|
||||
let next_page = store
|
||||
.list_threads(ListThreadsParams {
|
||||
cursor: page.next_cursor,
|
||||
..params
|
||||
})
|
||||
.await
|
||||
.expect("section cursor should continue listing from SQLite metadata");
|
||||
|
||||
assert_eq!(
|
||||
next_page
|
||||
.items
|
||||
.iter()
|
||||
.map(|thread| thread.thread_id)
|
||||
.collect::<Vec<_>>(),
|
||||
vec![thread_ids[2]]
|
||||
);
|
||||
assert_eq!(next_page.next_cursor, None);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn list_threads_rejects_invalid_cursor() {
|
||||
let home = TempDir::new().expect("temp dir");
|
||||
let store = LocalThreadStore::new(test_config(home.path()), /*state_db*/ None);
|
||||
|
||||
let err = store
|
||||
.list_threads(ListThreadsParams {
|
||||
page_size: 10,
|
||||
cursor: Some("not-a-cursor".to_string()),
|
||||
sort_key: ThreadSortKey::CreatedAt,
|
||||
sort_direction: SortDirection::Desc,
|
||||
allowed_sources: Vec::new(),
|
||||
model_providers: None,
|
||||
cwd_filters: None,
|
||||
section: None,
|
||||
project_id: None,
|
||||
archived: false,
|
||||
search_term: None,
|
||||
relation_filter: None,
|
||||
use_state_db_only: false,
|
||||
})
|
||||
.await
|
||||
.expect_err("invalid cursor should fail");
|
||||
|
||||
assert!(matches!(err, ThreadStoreError::InvalidRequest { .. }));
|
||||
}
|
||||
}
|
||||
471
codex-rs/thread-store/src/local/live_writer.rs
Normal file
471
codex-rs/thread-store/src/local/live_writer.rs
Normal file
@@ -0,0 +1,471 @@
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::protocol::SessionMeta;
|
||||
use codex_protocol::protocol::ThreadHistoryMode;
|
||||
use codex_protocol::protocol::ThreadMemoryMode;
|
||||
use codex_rollout::RolloutConfig;
|
||||
use codex_rollout::RolloutItem;
|
||||
use codex_rollout::RolloutRecorder;
|
||||
use codex_rollout::RolloutRecorderParams;
|
||||
use codex_rollout::into_persisted_rollout_items;
|
||||
use tracing::warn;
|
||||
|
||||
use super::LocalThreadStore;
|
||||
use super::create_thread;
|
||||
use crate::AppendThreadItemsParams;
|
||||
use crate::CreateThreadParams;
|
||||
use crate::ResumeThreadParams;
|
||||
use crate::ThreadStoreError;
|
||||
use crate::ThreadStoreResult;
|
||||
use crate::types::canonical_history_mode_from_rollout_items;
|
||||
|
||||
const ROLLOUT_SIZE_BYTES_METRIC: &str = "codex.rollout.size_bytes";
|
||||
|
||||
pub(super) async fn create_thread(
|
||||
store: &LocalThreadStore,
|
||||
params: CreateThreadParams,
|
||||
) -> ThreadStoreResult<()> {
|
||||
let thread_id = params.thread_id;
|
||||
let attachment = if params.attached_thread {
|
||||
let parent = params
|
||||
.forked_from_id
|
||||
.filter(|parent| *parent != thread_id)
|
||||
.ok_or_else(|| ThreadStoreError::InvalidRequest {
|
||||
message: "attached threads require a distinct fork source".to_string(),
|
||||
})?;
|
||||
let state = store
|
||||
.state_db
|
||||
.as_ref()
|
||||
.ok_or(ThreadStoreError::Unsupported {
|
||||
operation: "attached_threads",
|
||||
})?;
|
||||
// Keep parent deletion out until the child's canonical metadata is durable.
|
||||
let source_ownership = (
|
||||
store.live_writer_locks.lock(parent).await,
|
||||
store.acquire_writer_locks(&[parent]).await?,
|
||||
);
|
||||
super::thread_rollout_resolver::resolve_current_including_archived(store, parent)
|
||||
.await?
|
||||
.ok_or(ThreadStoreError::ThreadNotFound { thread_id: parent })?;
|
||||
Some((state, source_ownership))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let _live_writer_guard = store.live_writer_locks.lock(thread_id).await;
|
||||
let history_mode = params.history_mode;
|
||||
store.ensure_live_recorder_absent(thread_id).await?;
|
||||
let writer_lock = store.acquire_writer_lock(thread_id)?;
|
||||
let recorder = create_thread::create_thread(store, params, writer_lock.clone()).await?;
|
||||
if let Some((state, _source_ownership)) = attachment {
|
||||
recorder.persist().await.map_err(thread_store_io_error)?;
|
||||
if let Err(error) = index_attached_thread(store, state, recorder.rollout_path()).await {
|
||||
recorder.discard().await.map_err(thread_store_io_error)?;
|
||||
super::delete_thread::delete_rollout_file(store, recorder.rollout_path())?;
|
||||
super::delete_thread::delete_state_rows(store, &[thread_id]).await?;
|
||||
return Err(error);
|
||||
}
|
||||
}
|
||||
store
|
||||
.insert_live_recorder(thread_id, recorder, thread_id, history_mode, writer_lock)
|
||||
.await
|
||||
}
|
||||
|
||||
pub(super) async fn resume_thread(
|
||||
store: &LocalThreadStore,
|
||||
params: ResumeThreadParams,
|
||||
) -> ThreadStoreResult<Arc<Vec<RolloutItem>>> {
|
||||
let _live_writer_guard = store.live_writer_locks.lock(params.thread_id).await;
|
||||
store.ensure_live_recorder_absent(params.thread_id).await?;
|
||||
let writer_lock = store.acquire_writer_lock(params.thread_id)?;
|
||||
let rollout_path = match params.rollout_path {
|
||||
Some(rollout_path) => rollout_path,
|
||||
None => {
|
||||
let resolved = if params.include_archived {
|
||||
super::thread_rollout_resolver::resolve_current_including_archived(
|
||||
store,
|
||||
params.thread_id,
|
||||
)
|
||||
.await?
|
||||
} else {
|
||||
super::thread_rollout_resolver::resolve_current(store, params.thread_id).await?
|
||||
};
|
||||
resolved
|
||||
.ok_or(ThreadStoreError::ThreadNotFound {
|
||||
thread_id: params.thread_id,
|
||||
})?
|
||||
.path
|
||||
}
|
||||
};
|
||||
let rollout_path =
|
||||
super::read_thread::resolve_requested_rollout_path(store, rollout_path).await?;
|
||||
if !params.include_archived
|
||||
&& super::helpers::rollout_path_is_archived(&store.config.codex_home, &rollout_path)
|
||||
{
|
||||
return Err(ThreadStoreError::InvalidRequest {
|
||||
message: format!("thread {} is archived", params.thread_id),
|
||||
});
|
||||
}
|
||||
let history = match params.history {
|
||||
Some(history)
|
||||
if !matches!(
|
||||
history.first(),
|
||||
Some(RolloutItem::SessionMeta(meta)) if meta.meta.id == params.thread_id
|
||||
) =>
|
||||
{
|
||||
history
|
||||
}
|
||||
Some(history)
|
||||
if params.history_revision.is_some()
|
||||
&& params.history_revision
|
||||
== super::history_revision::read(&rollout_path).await =>
|
||||
{
|
||||
history
|
||||
}
|
||||
_ => Arc::new(
|
||||
super::model_context::load_from_rollout_path(store, params.thread_id, &rollout_path)
|
||||
.await?
|
||||
.items,
|
||||
),
|
||||
};
|
||||
let history_mode = canonical_history_mode_from_rollout_items(&history);
|
||||
let cwd = params
|
||||
.metadata
|
||||
.cwd
|
||||
.clone()
|
||||
.ok_or_else(|| ThreadStoreError::InvalidRequest {
|
||||
message: "local thread store requires a cwd".to_string(),
|
||||
})?;
|
||||
let config = RolloutConfig {
|
||||
codex_home: store.config.codex_home.clone(),
|
||||
sqlite: store.config.sqlite.clone(),
|
||||
cwd,
|
||||
model_provider_id: params.metadata.model_provider.clone(),
|
||||
generate_memories: matches!(params.metadata.memory_mode, ThreadMemoryMode::Enabled),
|
||||
};
|
||||
let rollout_id = super::thread_rollout_resolver::rollout_id_from_path_or_legacy_thread_id(
|
||||
rollout_path.as_path(),
|
||||
params.thread_id,
|
||||
history_mode,
|
||||
)?;
|
||||
let recorder = RolloutRecorder::new_with_writer_lock(
|
||||
&config,
|
||||
RolloutRecorderParams::resume(rollout_path),
|
||||
writer_lock.clone(),
|
||||
)
|
||||
.await
|
||||
.map_err(|err| ThreadStoreError::Internal {
|
||||
message: format!("failed to resume local thread recorder: {err}"),
|
||||
})?;
|
||||
store
|
||||
.insert_live_recorder(
|
||||
params.thread_id,
|
||||
recorder,
|
||||
rollout_id,
|
||||
history_mode,
|
||||
writer_lock,
|
||||
)
|
||||
.await?;
|
||||
Ok(history)
|
||||
}
|
||||
|
||||
#[tracing::instrument(
|
||||
level = "trace",
|
||||
skip_all,
|
||||
fields(item_count = params.items.len())
|
||||
)]
|
||||
pub(super) async fn append_items(
|
||||
store: &LocalThreadStore,
|
||||
params: AppendThreadItemsParams,
|
||||
) -> ThreadStoreResult<()> {
|
||||
write_and_project(
|
||||
store,
|
||||
params.thread_id,
|
||||
RolloutWriteOp::AppendItems(params.items),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
pub(super) async fn persist_thread(
|
||||
store: &LocalThreadStore,
|
||||
thread_id: ThreadId,
|
||||
) -> ThreadStoreResult<()> {
|
||||
write_and_project(store, thread_id, RolloutWriteOp::Persist).await
|
||||
}
|
||||
|
||||
pub(super) async fn flush_thread(
|
||||
store: &LocalThreadStore,
|
||||
thread_id: ThreadId,
|
||||
) -> ThreadStoreResult<()> {
|
||||
write_and_project(store, thread_id, RolloutWriteOp::Flush).await
|
||||
}
|
||||
|
||||
pub(super) async fn shutdown_thread(
|
||||
store: &LocalThreadStore,
|
||||
thread_id: ThreadId,
|
||||
) -> ThreadStoreResult<()> {
|
||||
let mut pending_metadata = store.pending_thread_metadata.lock(thread_id).await;
|
||||
let _live_writer_guard = store.live_writer_locks.lock(thread_id).await;
|
||||
let (recorder, rollout_id, history_mode) = live_writer_parts(store, thread_id).await?;
|
||||
let rollout_path = recorder.rollout_path().to_path_buf();
|
||||
if matches!(history_mode, ThreadHistoryMode::Legacy) {
|
||||
recorder.shutdown().await.map_err(thread_store_io_error)?;
|
||||
} else {
|
||||
recorder.shutdown().await.map_err(thread_store_io_error)?;
|
||||
if let Err(err) = super::thread_history_materialization::materialize_to_sqlite(
|
||||
store,
|
||||
rollout_id,
|
||||
rollout_path.as_path(),
|
||||
)
|
||||
.await
|
||||
{
|
||||
warn!("failed to project durable rollout during shutdown for {thread_id}: {err}");
|
||||
}
|
||||
}
|
||||
sync_materialized_rollout_path(store, thread_id, rollout_path.as_path()).await?;
|
||||
if let Some(metrics) = codex_otel::global()
|
||||
&& let Ok(metadata) = tokio::fs::metadata(&rollout_path).await
|
||||
{
|
||||
let size_bytes = i64::try_from(metadata.len()).unwrap_or(i64::MAX);
|
||||
let _ = metrics.histogram(ROLLOUT_SIZE_BYTES_METRIC, size_bytes, &[]);
|
||||
}
|
||||
let rollout_exists = match tokio::fs::try_exists(&rollout_path).await {
|
||||
Ok(rollout_exists) => rollout_exists,
|
||||
Err(err) => {
|
||||
warn!(
|
||||
"failed to check rollout path after shutdown for {thread_id}; preserving pending metadata: {err}"
|
||||
);
|
||||
true
|
||||
}
|
||||
};
|
||||
store.live_recorders.lock().await.remove(&thread_id);
|
||||
drop(_live_writer_guard);
|
||||
if !rollout_exists && pending_metadata.take().is_some() {
|
||||
store.pending_thread_metadata.remove(thread_id).await;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) async fn discard_thread(
|
||||
store: &LocalThreadStore,
|
||||
thread_id: ThreadId,
|
||||
) -> ThreadStoreResult<()> {
|
||||
let mut pending_metadata = store.pending_thread_metadata.lock(thread_id).await;
|
||||
let _live_writer_guard = store.live_writer_locks.lock(thread_id).await;
|
||||
if pending_metadata.take().is_some() {
|
||||
store.pending_thread_metadata.remove(thread_id).await;
|
||||
}
|
||||
let entry = store
|
||||
.live_recorders
|
||||
.lock()
|
||||
.await
|
||||
.remove(&thread_id)
|
||||
.ok_or(ThreadStoreError::ThreadNotFound { thread_id })?;
|
||||
entry
|
||||
.recorder
|
||||
.discard()
|
||||
.await
|
||||
.map_err(thread_store_io_error)
|
||||
}
|
||||
|
||||
async fn index_attached_thread(
|
||||
store: &LocalThreadStore,
|
||||
state: &codex_state::StateRuntime,
|
||||
path: &std::path::Path,
|
||||
) -> ThreadStoreResult<()> {
|
||||
let meta = codex_rollout::read_session_meta_line(path)
|
||||
.await
|
||||
.map_err(thread_store_io_error)?;
|
||||
let memory_mode = meta.meta.memory_mode.clone();
|
||||
let items = [RolloutItem::SessionMeta(Box::new(meta))];
|
||||
let mut builder = codex_rollout::builder_from_items(&items, path).ok_or_else(|| {
|
||||
ThreadStoreError::Internal {
|
||||
message: format!("invalid attached thread metadata at {}", path.display()),
|
||||
}
|
||||
})?;
|
||||
if super::helpers::rollout_path_is_archived(&store.config.codex_home, path) {
|
||||
builder.archived_at = Some(builder.updated_at.unwrap_or(builder.created_at));
|
||||
}
|
||||
state
|
||||
.apply_rollout_items(
|
||||
&builder,
|
||||
&items,
|
||||
memory_mode.as_deref(),
|
||||
/*updated_at_override*/ None,
|
||||
)
|
||||
.await
|
||||
.map_err(|err| ThreadStoreError::Internal {
|
||||
message: format!(
|
||||
"failed to index attached thread at {}: {err}",
|
||||
path.display()
|
||||
),
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) async fn rollout_path(
|
||||
store: &LocalThreadStore,
|
||||
thread_id: ThreadId,
|
||||
) -> ThreadStoreResult<PathBuf> {
|
||||
Ok(store
|
||||
.live_recorders
|
||||
.lock()
|
||||
.await
|
||||
.get(&thread_id)
|
||||
.ok_or(ThreadStoreError::ThreadNotFound { thread_id })?
|
||||
.recorder
|
||||
.rollout_path()
|
||||
.to_path_buf())
|
||||
}
|
||||
|
||||
async fn sync_materialized_rollout_path(
|
||||
store: &LocalThreadStore,
|
||||
thread_id: ThreadId,
|
||||
rollout_path: &std::path::Path,
|
||||
) -> ThreadStoreResult<()> {
|
||||
if codex_rollout::existing_rollout_path(rollout_path)
|
||||
.await
|
||||
.is_none()
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
let Some(state_db) = store.state_db().await else {
|
||||
return Ok(());
|
||||
};
|
||||
let result: ThreadStoreResult<()> = async {
|
||||
let Some(mut metadata) =
|
||||
state_db
|
||||
.get_thread(thread_id)
|
||||
.await
|
||||
.map_err(|err| ThreadStoreError::Internal {
|
||||
message: format!("failed to read thread metadata for {thread_id}: {err}"),
|
||||
})?
|
||||
else {
|
||||
return Ok(());
|
||||
};
|
||||
if metadata.rollout_path != rollout_path {
|
||||
metadata.rollout_path = rollout_path.to_path_buf();
|
||||
state_db
|
||||
.upsert_thread(&metadata)
|
||||
.await
|
||||
.map_err(|err| ThreadStoreError::Internal {
|
||||
message: format!("failed to update thread metadata for {thread_id}: {err}"),
|
||||
})?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
.await;
|
||||
if let Err(err) = result {
|
||||
warn!("failed to sync materialized rollout path for thread {thread_id}: {err}");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn thread_store_io_error(err: std::io::Error) -> ThreadStoreError {
|
||||
ThreadStoreError::Internal {
|
||||
message: err.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The rollout writer has three distinct lifecycle moments:
|
||||
/// - `AppendItems` is normal turn/event persistence and adds new rollout records.
|
||||
/// - `Persist` makes the thread durable before any turn items exist; locally this can write the
|
||||
/// initial `SessionMeta`.
|
||||
/// - `Flush` writes any rollout records already queued in the recorder and ensures they are
|
||||
/// durably persisted.
|
||||
///
|
||||
/// Each can advance the rollout JSONL file on disk, so we need to make sure we materialize the
|
||||
/// new data into the SQLite history tables (turns and items) as necessary.
|
||||
enum RolloutWriteOp {
|
||||
AppendItems(Vec<RolloutItem>),
|
||||
Persist,
|
||||
Flush,
|
||||
}
|
||||
|
||||
pub(super) async fn live_writer_parts(
|
||||
store: &LocalThreadStore,
|
||||
thread_id: ThreadId,
|
||||
) -> ThreadStoreResult<(RolloutRecorder, ThreadId, ThreadHistoryMode)> {
|
||||
let live_recorders = store.live_recorders.lock().await;
|
||||
let entry = live_recorders
|
||||
.get(&thread_id)
|
||||
.ok_or(ThreadStoreError::ThreadNotFound { thread_id })?;
|
||||
Ok((entry.recorder.clone(), entry.rollout_id, entry.history_mode))
|
||||
}
|
||||
|
||||
/// Uses the writer's creation record only until its rollout has been materialized.
|
||||
pub(super) async fn unpersisted_session_meta(
|
||||
store: &LocalThreadStore,
|
||||
thread_id: ThreadId,
|
||||
) -> Option<(PathBuf, SessionMeta)> {
|
||||
let (recorder, _, _) = live_writer_parts(store, thread_id).await.ok()?;
|
||||
// Materialized reads should not queue behind unrelated transcript writes.
|
||||
if codex_rollout::existing_rollout_path(recorder.rollout_path())
|
||||
.await
|
||||
.is_some()
|
||||
{
|
||||
return None;
|
||||
}
|
||||
// A writer may finish shutdown after lookup; durable reads remain the fallback.
|
||||
let meta = recorder.unpersisted_session_meta().await.ok()??;
|
||||
Some((recorder.rollout_path().to_path_buf(), meta))
|
||||
}
|
||||
|
||||
async fn write_and_project(
|
||||
store: &LocalThreadStore,
|
||||
thread_id: ThreadId,
|
||||
write_op: RolloutWriteOp,
|
||||
) -> ThreadStoreResult<()> {
|
||||
// Every live write should have a recorder: create/resume installs one, while
|
||||
// shutdown/discard/delete removes it. Keep the lookup defensive so late writes fail after
|
||||
// teardown.
|
||||
let _live_writer_guard = store.live_writer_locks.lock(thread_id).await;
|
||||
let (recorder, rollout_id, history_mode) = live_writer_parts(store, thread_id).await?;
|
||||
let sync_rollout_path = matches!(&write_op, RolloutWriteOp::Persist | RolloutWriteOp::Flush);
|
||||
let write_op = match write_op {
|
||||
RolloutWriteOp::AppendItems(items) => {
|
||||
let items = into_persisted_rollout_items(items, history_mode);
|
||||
if items.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
RolloutWriteOp::AppendItems(items)
|
||||
}
|
||||
RolloutWriteOp::Persist => RolloutWriteOp::Persist,
|
||||
RolloutWriteOp::Flush => RolloutWriteOp::Flush,
|
||||
};
|
||||
if matches!(history_mode, ThreadHistoryMode::Legacy) {
|
||||
durable_write(&recorder, write_op).await?;
|
||||
} else {
|
||||
let rollout_path = recorder.rollout_path();
|
||||
// SQLite is a rebuildable view. The flush barrier must win before projection starts so it
|
||||
// can lag JSONL after failure, but can never get ahead of canonical history.
|
||||
durable_write(&recorder, write_op).await?;
|
||||
if let Err(err) = super::thread_history_materialization::materialize_to_sqlite(
|
||||
store,
|
||||
rollout_id,
|
||||
rollout_path,
|
||||
)
|
||||
.await
|
||||
{
|
||||
warn!("failed to project durable rollout for {thread_id}: {err}");
|
||||
}
|
||||
}
|
||||
if sync_rollout_path {
|
||||
sync_materialized_rollout_path(store, thread_id, recorder.rollout_path()).await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn durable_write(recorder: &RolloutRecorder, write: RolloutWriteOp) -> ThreadStoreResult<()> {
|
||||
match write {
|
||||
RolloutWriteOp::AppendItems(items) => {
|
||||
recorder
|
||||
.record_canonical_items(items.as_slice())
|
||||
.await
|
||||
.map_err(thread_store_io_error)?;
|
||||
recorder.flush().await.map_err(thread_store_io_error)
|
||||
}
|
||||
RolloutWriteOp::Persist => recorder.persist().await.map_err(thread_store_io_error),
|
||||
RolloutWriteOp::Flush => recorder.flush().await.map_err(thread_store_io_error),
|
||||
}
|
||||
}
|
||||
2454
codex-rs/thread-store/src/local/mod.rs
Normal file
2454
codex-rs/thread-store/src/local/mod.rs
Normal file
File diff suppressed because it is too large
Load Diff
214
codex-rs/thread-store/src/local/model_context.rs
Normal file
214
codex-rs/thread-store/src/local/model_context.rs
Normal file
@@ -0,0 +1,214 @@
|
||||
//! Reconstructs model context and preserves source runtime metadata across fork cutoffs.
|
||||
|
||||
use std::io;
|
||||
use std::path::Path;
|
||||
|
||||
use codex_protocol::protocol::HistoryPosition;
|
||||
use codex_protocol::protocol::ThreadHistoryMode;
|
||||
use codex_rollout::ModelContextScan;
|
||||
use codex_rollout::ModelContextScanProgress;
|
||||
use codex_rollout::ReverseJsonlScanner;
|
||||
use codex_rollout::RolloutItem;
|
||||
use codex_rollout::ScanOutcome;
|
||||
|
||||
use super::LocalThreadStore;
|
||||
use super::read_thread;
|
||||
use super::rollout_lineage::RolloutLineage;
|
||||
use super::thread_rollout_resolver;
|
||||
use crate::LoadThreadHistoryParams;
|
||||
use crate::StoredModelContext;
|
||||
use crate::ThreadStoreError;
|
||||
use crate::ThreadStoreResult;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "model_context_tests.rs"]
|
||||
mod tests;
|
||||
|
||||
/// Loads rollout items needed to reconstruct the latest model-visible context.
|
||||
///
|
||||
/// Paginated JSONL rollouts use a reverse scan. It stops at the newest `CompactedItem` with both
|
||||
/// replacement history and a window number, and returns that compaction plus its newer suffix. If
|
||||
/// the newest compaction lacks either field, the scan continues to the beginning of the rollout.
|
||||
///
|
||||
/// Compressed segments are decoded before applying their original JSONL offsets. Legacy rollouts
|
||||
/// keep the existing full-history path.
|
||||
pub(super) async fn load_latest_model_context(
|
||||
store: &LocalThreadStore,
|
||||
params: LoadThreadHistoryParams,
|
||||
) -> ThreadStoreResult<StoredModelContext> {
|
||||
let resolved = if params.include_archived {
|
||||
thread_rollout_resolver::resolve_current_including_archived(store, params.thread_id).await?
|
||||
} else {
|
||||
thread_rollout_resolver::resolve_current(store, params.thread_id).await?
|
||||
};
|
||||
let path =
|
||||
resolved
|
||||
.map(|resolved| resolved.path)
|
||||
.ok_or_else(|| ThreadStoreError::InvalidRequest {
|
||||
message: format!("no rollout found for thread id {}", params.thread_id),
|
||||
})?;
|
||||
|
||||
load_from_rollout_path(store, params.thread_id, &path).await
|
||||
}
|
||||
|
||||
pub(super) async fn load_from_rollout_path(
|
||||
store: &LocalThreadStore,
|
||||
thread_id: codex_protocol::ThreadId,
|
||||
path: &Path,
|
||||
) -> ThreadStoreResult<StoredModelContext> {
|
||||
let before = super::history_revision::read(path).await;
|
||||
let session_meta = codex_rollout::read_session_meta_line(path)
|
||||
.await
|
||||
.map_err(|err| ThreadStoreError::Internal {
|
||||
message: format!("failed to read session metadata {}: {err}", path.display()),
|
||||
})?;
|
||||
if session_meta.meta.id != thread_id {
|
||||
return Err(ThreadStoreError::InvalidRequest {
|
||||
message: format!(
|
||||
"rollout at {} belongs to thread {}, not {}",
|
||||
path.display(),
|
||||
session_meta.meta.id,
|
||||
thread_id
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
let items = if matches!(session_meta.meta.history_mode, ThreadHistoryMode::Paginated) {
|
||||
let lineage = store
|
||||
.resolve_rollout_lineage(thread_id, Some(path.to_path_buf()))
|
||||
.await?;
|
||||
let mut items = lineage
|
||||
.read_with_fallback(store, scan_model_context_from_lineage)
|
||||
.await?;
|
||||
items.insert(0, RolloutItem::SessionMeta(Box::new(session_meta)));
|
||||
items
|
||||
} else {
|
||||
read_thread::load_history_items(path).await?
|
||||
};
|
||||
|
||||
let after = super::history_revision::read(path).await;
|
||||
Ok(StoredModelContext {
|
||||
revision: before.filter(|revision| Some(revision) == after.as_ref()),
|
||||
thread_id,
|
||||
items,
|
||||
})
|
||||
}
|
||||
|
||||
/// Loads startup context from a fork's frozen inherited prefix.
|
||||
pub(super) async fn load_for_fork(
|
||||
lineage: RolloutLineage,
|
||||
history_base: Option<HistoryPosition>,
|
||||
) -> ThreadStoreResult<Vec<RolloutItem>> {
|
||||
let source_path = lineage
|
||||
.segments()
|
||||
.last()
|
||||
.map(|segment| segment.rollout_path.as_path())
|
||||
.ok_or_else(|| ThreadStoreError::Internal {
|
||||
message: "fork lineage has no source segment".to_string(),
|
||||
})?;
|
||||
let mut session_meta = codex_rollout::read_session_meta_line(source_path)
|
||||
.await
|
||||
.map_err(|err| ThreadStoreError::Internal {
|
||||
message: format!(
|
||||
"failed to read session metadata {}: {err}",
|
||||
source_path.display()
|
||||
),
|
||||
})?;
|
||||
if session_meta.meta.multi_agent_version.is_none() {
|
||||
// Recover only the runtime version before applying the fork cutoff. Stop at the
|
||||
// newest version-bearing context instead of retaining the source's full replay.
|
||||
let source_lineage = lineage.clone();
|
||||
let (stop, keep_running) = tokio::sync::oneshot::channel::<()>();
|
||||
session_meta.meta.multi_agent_version = tokio::task::spawn_blocking(move || {
|
||||
for segment in source_lineage.segments().iter().rev() {
|
||||
let file = source_lineage
|
||||
.reads
|
||||
.open(&segment.rollout_path, || stop.is_closed())?;
|
||||
let mut scanner = match segment.end.map(|end| end.end_byte_offset) {
|
||||
Some(end_byte_offset) => ReverseJsonlScanner::new_at(file, end_byte_offset)?,
|
||||
None => ReverseJsonlScanner::new(file)?,
|
||||
};
|
||||
while let Some(outcome) = scanner.scan_next_rollout_line()? {
|
||||
let ScanOutcome::Parsed(line) = outcome else {
|
||||
continue;
|
||||
};
|
||||
if let Some(version) = codex_rollout::resume_multi_agent_version(&line.item) {
|
||||
return Ok(Some(version));
|
||||
}
|
||||
// Ancestor metadata does not describe the immediate source's runtime.
|
||||
if matches!(line.item, RolloutItem::SessionMeta(_)) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok::<_, io::Error>(None)
|
||||
})
|
||||
.await
|
||||
.map_err(|err| ThreadStoreError::Internal {
|
||||
message: format!("failed to join fork runtime version scan: {err}"),
|
||||
})?
|
||||
.map_err(|err| ThreadStoreError::Internal {
|
||||
message: format!("failed to read fork runtime version: {err}"),
|
||||
})?;
|
||||
drop(keep_running);
|
||||
}
|
||||
let mut items = match history_base {
|
||||
Some(history_base) => {
|
||||
let lineage = lineage.truncate_at(history_base).await?;
|
||||
scan_model_context_from_lineage(lineage).await?
|
||||
}
|
||||
None => Vec::new(),
|
||||
};
|
||||
items.insert(0, RolloutItem::SessionMeta(Box::new(session_meta)));
|
||||
Ok(items)
|
||||
}
|
||||
|
||||
async fn scan_model_context_from_lineage(
|
||||
lineage: RolloutLineage,
|
||||
) -> ThreadStoreResult<Vec<RolloutItem>> {
|
||||
let (stop, keep_running) = tokio::sync::oneshot::channel::<()>();
|
||||
let scan = tokio::task::spawn_blocking(move || {
|
||||
scan_model_context_from_lineage_blocking(&lineage, || stop.is_closed())
|
||||
})
|
||||
.await
|
||||
.map_err(|err| ThreadStoreError::Internal {
|
||||
message: format!("failed to join model context scan: {err}"),
|
||||
})?;
|
||||
drop(keep_running);
|
||||
match scan {
|
||||
Ok(items) => Ok(items),
|
||||
Err(err) => Err(ThreadStoreError::Internal {
|
||||
message: format!("failed to scan paginated model context lineage: {err}"),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
fn scan_model_context_from_lineage_blocking(
|
||||
lineage: &RolloutLineage,
|
||||
is_cancelled: impl Fn() -> bool,
|
||||
) -> io::Result<Vec<RolloutItem>> {
|
||||
let mut scan = ModelContextScan::default();
|
||||
'segments: for segment in lineage.segments().iter().rev() {
|
||||
let file = lineage.reads.open(&segment.rollout_path, &is_cancelled)?;
|
||||
let mut scanner = match segment.end.map(|end| end.end_byte_offset) {
|
||||
Some(end_byte_offset) => ReverseJsonlScanner::new_at(file, end_byte_offset)?,
|
||||
None => ReverseJsonlScanner::new(file)?,
|
||||
};
|
||||
while let Some(outcome) = scanner.scan_next_rollout_line()? {
|
||||
let ScanOutcome::Parsed(line) = outcome else {
|
||||
continue;
|
||||
};
|
||||
// Each rollout segment contributes only its local delta. Its session metadata is
|
||||
// replaced with the requested thread's canonical SessionMeta after replay.
|
||||
if matches!(&line.item, RolloutItem::SessionMeta(_)) {
|
||||
break;
|
||||
}
|
||||
match scan.push(line.item) {
|
||||
ModelContextScanProgress::Continue => {}
|
||||
ModelContextScanProgress::Complete => break 'segments,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(scan.finish())
|
||||
}
|
||||
778
codex-rs/thread-store/src/local/model_context_tests.rs
Normal file
778
codex-rs/thread-store/src/local/model_context_tests.rs
Normal file
@@ -0,0 +1,778 @@
|
||||
use std::fs::OpenOptions;
|
||||
use std::io::Write;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::config_types::ReasoningSummary;
|
||||
use codex_protocol::items::TurnItem;
|
||||
use codex_protocol::items::UserMessageItem;
|
||||
use codex_protocol::models::ContentItem;
|
||||
use codex_protocol::models::ResponseItem;
|
||||
use codex_protocol::protocol::AskForApproval;
|
||||
use codex_protocol::protocol::EventMsg;
|
||||
use codex_protocol::protocol::HistoryPosition;
|
||||
use codex_protocol::protocol::ItemCompletedEvent;
|
||||
use codex_protocol::protocol::MultiAgentVersion;
|
||||
use codex_protocol::protocol::ThreadHistoryMode;
|
||||
use codex_protocol::protocol::TurnCompleteEvent;
|
||||
use codex_protocol::protocol::TurnContextItem;
|
||||
use codex_protocol::protocol::TurnStartedEvent;
|
||||
use codex_protocol::protocol::WorldStateItem;
|
||||
use codex_protocol::user_input::UserInput;
|
||||
use codex_rollout::CompactedItem;
|
||||
use codex_rollout::RolloutItem;
|
||||
use codex_rollout::RolloutLine;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tempfile::TempDir;
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::*;
|
||||
use crate::ThreadStore;
|
||||
use crate::local::test_support::test_config;
|
||||
use crate::local::test_support::write_session_file_with_history_mode;
|
||||
|
||||
#[tokio::test]
|
||||
async fn model_context_revision_invalidates_after_append_or_removal() {
|
||||
let home = TempDir::new().expect("temp dir");
|
||||
let uuid = Uuid::from_u128(/*v*/ 1009);
|
||||
let thread_id = ThreadId::from_string(&uuid.to_string()).expect("thread id");
|
||||
let path = write_paginated_rollout(
|
||||
home.path(),
|
||||
"2025-01-03T13-00-08",
|
||||
uuid,
|
||||
[user_message("saved message")],
|
||||
);
|
||||
let store = LocalThreadStore::new(test_config(home.path()), /*state_db*/ None);
|
||||
let params = LoadThreadHistoryParams {
|
||||
thread_id,
|
||||
include_archived: false,
|
||||
};
|
||||
let context = store
|
||||
.load_latest_model_context(params.clone())
|
||||
.await
|
||||
.expect("load model context");
|
||||
let revision = context.revision.expect("stable history revision");
|
||||
assert!(
|
||||
store
|
||||
.is_model_context_current(params.clone(), revision.clone())
|
||||
.await
|
||||
.expect("validate unchanged context")
|
||||
);
|
||||
|
||||
let new_item = user_message("message appended during configuration loading");
|
||||
append_items(&path, [new_item.clone()]);
|
||||
assert!(
|
||||
!store
|
||||
.is_model_context_current(params.clone(), revision.clone())
|
||||
.await
|
||||
.expect("invalidate stale context")
|
||||
);
|
||||
let updated = store
|
||||
.load_latest_model_context(params.clone())
|
||||
.await
|
||||
.expect("load updated model context");
|
||||
let mut expected = context.items;
|
||||
expected.push(new_item);
|
||||
assert_eq!(
|
||||
serde_json::to_value(updated.items).expect("serialize updated context"),
|
||||
serde_json::to_value(expected).expect("serialize expected context")
|
||||
);
|
||||
|
||||
std::fs::remove_file(path).expect("remove rollout");
|
||||
assert!(
|
||||
!store
|
||||
.is_model_context_current(params, revision)
|
||||
.await
|
||||
.expect("invalidate removed context")
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn stops_at_newest_usable_compaction_and_keeps_companions() {
|
||||
let home = TempDir::new().expect("temp dir");
|
||||
let uuid = Uuid::from_u128(/*v*/ 1001);
|
||||
let thread_id = ThreadId::from_string(&uuid.to_string()).expect("thread id");
|
||||
let world_state = RolloutItem::WorldState(WorldStateItem::full(Default::default()));
|
||||
let turn_context = turn_context(home.path(), "companion");
|
||||
let path = write_paginated_rollout(
|
||||
home.path(),
|
||||
"2025-01-03T13-00-00",
|
||||
uuid,
|
||||
[
|
||||
user_message("older history"),
|
||||
compacted("older compaction", Some(Vec::new())),
|
||||
user_message("superseded suffix"),
|
||||
compacted("latest compaction", Some(Vec::new())),
|
||||
world_state.clone(),
|
||||
turn_context.clone(),
|
||||
],
|
||||
);
|
||||
let session_meta = codex_rollout::read_session_meta_line(path.as_path())
|
||||
.await
|
||||
.expect("read session metadata");
|
||||
let store = LocalThreadStore::new(test_config(home.path()), /*state_db*/ None);
|
||||
|
||||
let context = store
|
||||
.load_latest_model_context(LoadThreadHistoryParams {
|
||||
thread_id,
|
||||
include_archived: false,
|
||||
})
|
||||
.await
|
||||
.expect("load model context");
|
||||
|
||||
assert_eq!(
|
||||
serde_json::to_value(context.items).expect("serialize context"),
|
||||
serde_json::to_value(vec![
|
||||
RolloutItem::SessionMeta(Box::new(session_meta)),
|
||||
compacted("latest compaction", Some(Vec::new())),
|
||||
world_state,
|
||||
turn_context,
|
||||
])
|
||||
.expect("serialize expected context")
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn loads_recent_context_after_many_empty_wake_turns() {
|
||||
let home = TempDir::new().expect("temp dir");
|
||||
let uuid = Uuid::from_u128(/*v*/ 1008);
|
||||
let thread_id = ThreadId::from_string(&uuid.to_string()).expect("thread id");
|
||||
let path = write_paginated_rollout(
|
||||
home.path(),
|
||||
"2025-01-03T13-00-07",
|
||||
uuid,
|
||||
[
|
||||
turn_started("user-turn"),
|
||||
user_message("keep working"),
|
||||
completed_user_message("user-turn", "keep working"),
|
||||
turn_context(home.path(), "user-turn"),
|
||||
turn_complete("user-turn"),
|
||||
],
|
||||
);
|
||||
let mut expected_suffix = Vec::new();
|
||||
for index in 0..32 {
|
||||
let turn_id = format!("wake-{index}");
|
||||
let mut items = vec![turn_started(&turn_id)];
|
||||
let starts_new_window = index % 8 == 0;
|
||||
if starts_new_window {
|
||||
items.extend([
|
||||
compacted(&format!("compaction-{index}"), Some(Vec::new())),
|
||||
RolloutItem::WorldState(WorldStateItem::full(Default::default())),
|
||||
]);
|
||||
}
|
||||
items.extend([
|
||||
turn_context(home.path(), &turn_id),
|
||||
contextual_user_message(),
|
||||
turn_complete(&turn_id),
|
||||
]);
|
||||
append_items(&path, items.clone());
|
||||
if starts_new_window {
|
||||
expected_suffix = items.into_iter().skip(1).collect();
|
||||
} else {
|
||||
expected_suffix.extend(items);
|
||||
}
|
||||
}
|
||||
let session_meta = codex_rollout::read_session_meta_line(&path)
|
||||
.await
|
||||
.expect("read session metadata");
|
||||
let store = LocalThreadStore::new(test_config(home.path()), /*state_db*/ None);
|
||||
let context = store
|
||||
.load_latest_model_context(LoadThreadHistoryParams {
|
||||
thread_id,
|
||||
include_archived: false,
|
||||
})
|
||||
.await
|
||||
.expect("load model context");
|
||||
expected_suffix.insert(0, RolloutItem::SessionMeta(Box::new(session_meta)));
|
||||
|
||||
assert_eq!(
|
||||
serde_json::to_value(context.items).expect("serialize context"),
|
||||
serde_json::to_value(expected_suffix).expect("serialize expected context")
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn fork_context_excludes_items_after_frozen_cutoff() {
|
||||
let home = TempDir::new().expect("temp dir");
|
||||
let uuid = Uuid::from_u128(/*v*/ 1007);
|
||||
let thread_id = ThreadId::from_string(&uuid.to_string()).expect("thread id");
|
||||
let path = write_ordinaled_paginated_rollout(
|
||||
home.path(),
|
||||
"2025-01-03T13-00-06",
|
||||
uuid,
|
||||
[turn_started("frozen-turn"), user_message("frozen message")],
|
||||
);
|
||||
let history_base =
|
||||
history_position(path.as_path(), thread_id, /*end_ordinal_exclusive*/ 3);
|
||||
append_items(path.as_path(), [user_message("later message")]);
|
||||
let store = LocalThreadStore::new(test_config(home.path()), /*state_db*/ None);
|
||||
let lineage = store
|
||||
.resolve_rollout_lineage(thread_id, /*initial_path*/ None)
|
||||
.await
|
||||
.expect("resolve source lineage");
|
||||
let session_meta = codex_rollout::read_session_meta_line(path.as_path())
|
||||
.await
|
||||
.expect("read source metadata");
|
||||
|
||||
let context = load_for_fork(lineage, Some(history_base))
|
||||
.await
|
||||
.expect("load frozen fork context");
|
||||
|
||||
let expected = vec![
|
||||
RolloutItem::SessionMeta(Box::new(session_meta)),
|
||||
turn_started("frozen-turn"),
|
||||
user_message("frozen message"),
|
||||
];
|
||||
assert_eq!(
|
||||
serde_json::to_value(context).expect("serialize fork context"),
|
||||
serde_json::to_value(expected).expect("serialize expected fork context")
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn fork_version_stops_before_older_segments_once_resolved() {
|
||||
for stored_version in [None, Some(MultiAgentVersion::Disabled)] {
|
||||
let home = TempDir::new().expect("temp dir");
|
||||
let root_uuid = Uuid::from_u128(/*v*/ 3001);
|
||||
let root_id = ThreadId::from_string(&root_uuid.to_string()).expect("root id");
|
||||
let root_path = write_ordinaled_paginated_rollout(
|
||||
home.path(),
|
||||
"2025-01-03T13-02-00",
|
||||
root_uuid,
|
||||
[user_message("older history")],
|
||||
);
|
||||
let child_uuid = Uuid::from_u128(/*v*/ 3002);
|
||||
let child_id = ThreadId::from_string(&child_uuid.to_string()).expect("child id");
|
||||
let child_path =
|
||||
write_ordinaled_paginated_rollout(home.path(), "2025-01-03T13-02-01", child_uuid, []);
|
||||
let mut source_meta = codex_rollout::read_session_meta_line(&child_path)
|
||||
.await
|
||||
.expect("read child metadata");
|
||||
source_meta.meta.multi_agent_version = stored_version;
|
||||
source_meta.meta.history_base = Some(history_position(
|
||||
&root_path, root_id, /*end_ordinal_exclusive*/ 2,
|
||||
));
|
||||
let head = RolloutLine {
|
||||
timestamp: "2025-01-03T13:02:01Z".to_string(),
|
||||
ordinal: Some(0),
|
||||
item: RolloutItem::SessionMeta(Box::new(source_meta.clone())),
|
||||
};
|
||||
std::fs::write(
|
||||
&child_path,
|
||||
format!(
|
||||
"{}\n",
|
||||
serde_json::to_string(&head).expect("serialize head")
|
||||
),
|
||||
)
|
||||
.expect("write child metadata");
|
||||
let RolloutItem::Compacted(mut compacted) =
|
||||
compacted("version compaction", Some(Vec::new()))
|
||||
else {
|
||||
unreachable!();
|
||||
};
|
||||
compacted.resume_metadata = Some(codex_rollout::CompactionResumeMetadata {
|
||||
rejected_audio_file_ids: Default::default(),
|
||||
dynamic_tools: None,
|
||||
multi_agent_version: Some(MultiAgentVersion::V2),
|
||||
last_started_turn_id: None,
|
||||
turn_attribution: None,
|
||||
previous_turn_settings: None,
|
||||
});
|
||||
append_items(
|
||||
&child_path,
|
||||
[
|
||||
RolloutItem::Compacted(compacted),
|
||||
turn_context(home.path(), "unset-turn"),
|
||||
],
|
||||
);
|
||||
let store = LocalThreadStore::new(test_config(home.path()), /*state_db*/ None);
|
||||
let lineage = store
|
||||
.resolve_rollout_lineage(child_id, /*initial_path*/ None)
|
||||
.await
|
||||
.expect("resolve source lineage");
|
||||
// The usable compaction should stop the scan before it reaches this missing segment.
|
||||
std::fs::remove_file(root_path).expect("remove older segment after resolving lineage");
|
||||
|
||||
let context = load_for_fork(lineage, /*history_base*/ None)
|
||||
.await
|
||||
.expect("resolve version without reading older segments");
|
||||
source_meta.meta.multi_agent_version = stored_version.or(Some(MultiAgentVersion::V2));
|
||||
assert_eq!(
|
||||
serde_json::to_value(context).expect("serialize fork context"),
|
||||
serde_json::to_value(vec![RolloutItem::SessionMeta(Box::new(source_meta))])
|
||||
.expect("serialize expected context")
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn fork_version_respects_inherited_segment_cutoffs() {
|
||||
let home = TempDir::new().expect("temp dir");
|
||||
let root_uuid = Uuid::from_u128(/*v*/ 3003);
|
||||
let root_id = ThreadId::from_string(&root_uuid.to_string()).expect("root id");
|
||||
let RolloutItem::TurnContext(mut inherited) = turn_context(home.path(), "inherited") else {
|
||||
unreachable!();
|
||||
};
|
||||
inherited.multi_agent_version = Some(MultiAgentVersion::V2);
|
||||
let mut excluded = inherited.clone();
|
||||
excluded.multi_agent_version = Some(MultiAgentVersion::V1);
|
||||
let root_path = write_ordinaled_paginated_rollout(
|
||||
home.path(),
|
||||
"2025-01-03T13-02-02",
|
||||
root_uuid,
|
||||
[
|
||||
RolloutItem::TurnContext(inherited),
|
||||
RolloutItem::TurnContext(excluded),
|
||||
],
|
||||
);
|
||||
let child_uuid = Uuid::from_u128(/*v*/ 3004);
|
||||
let child_id = ThreadId::from_string(&child_uuid.to_string()).expect("child id");
|
||||
let child_path = write_ordinaled_paginated_rollout(
|
||||
home.path(),
|
||||
"2025-01-03T13-02-03",
|
||||
child_uuid,
|
||||
[turn_context(home.path(), "unset-child")],
|
||||
);
|
||||
set_history_base(
|
||||
&child_path,
|
||||
history_position(&root_path, root_id, /*end_ordinal_exclusive*/ 2),
|
||||
);
|
||||
let store = LocalThreadStore::new(test_config(home.path()), /*state_db*/ None);
|
||||
let lineage = store
|
||||
.resolve_rollout_lineage(child_id, /*initial_path*/ None)
|
||||
.await
|
||||
.expect("resolve source lineage");
|
||||
let mut source_meta = codex_rollout::read_session_meta_line(&child_path)
|
||||
.await
|
||||
.expect("read child metadata");
|
||||
|
||||
let context = load_for_fork(lineage, /*history_base*/ None)
|
||||
.await
|
||||
.expect("recover version from inherited prefix");
|
||||
source_meta.meta.multi_agent_version = Some(MultiAgentVersion::V2);
|
||||
assert_eq!(
|
||||
serde_json::to_value(context).expect("serialize fork context"),
|
||||
serde_json::to_value(vec![RolloutItem::SessionMeta(Box::new(source_meta))])
|
||||
.expect("serialize expected context")
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn returns_scanned_full_history_for_unsupported_compaction() {
|
||||
enum MissingField {
|
||||
ReplacementHistory,
|
||||
WindowNumber,
|
||||
}
|
||||
|
||||
for (index, missing_field) in [MissingField::ReplacementHistory, MissingField::WindowNumber]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
{
|
||||
let home = TempDir::new().expect("temp dir");
|
||||
let uuid = Uuid::from_u128(1002 + index as u128);
|
||||
let mut unsupported = compacted("unsupported compaction", Some(Vec::new()));
|
||||
let RolloutItem::Compacted(unsupported_compaction) = &mut unsupported else {
|
||||
unreachable!("compacted helper returns a compaction");
|
||||
};
|
||||
match missing_field {
|
||||
MissingField::ReplacementHistory => unsupported_compaction.replacement_history = None,
|
||||
MissingField::WindowNumber => unsupported_compaction.window_number = None,
|
||||
}
|
||||
let path = write_paginated_rollout(
|
||||
home.path(),
|
||||
"2025-01-03T13-00-01",
|
||||
uuid,
|
||||
[
|
||||
user_message("older history"),
|
||||
compacted("older usable compaction", Some(Vec::new())),
|
||||
unsupported,
|
||||
],
|
||||
);
|
||||
|
||||
assert_reverse_scan_matches_full_history(home.path(), path.as_path()).await;
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn returns_scanned_full_history_at_bof_without_checkpoint() {
|
||||
let home = TempDir::new().expect("temp dir");
|
||||
let uuid = Uuid::from_u128(/*v*/ 1003);
|
||||
let path = write_paginated_rollout(
|
||||
home.path(),
|
||||
"2025-01-03T13-00-02",
|
||||
uuid,
|
||||
[
|
||||
turn_started("turn-1"),
|
||||
user_message("turn"),
|
||||
completed_user_message("turn-1", "turn"),
|
||||
turn_context(home.path(), "turn-1"),
|
||||
turn_complete("turn-1"),
|
||||
],
|
||||
);
|
||||
|
||||
assert_reverse_scan_matches_full_history(home.path(), path.as_path()).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn replays_nested_archived_lineage_from_frozen_prefix() {
|
||||
let home = TempDir::new().expect("temp dir");
|
||||
let root_uuid = Uuid::from_u128(/*v*/ 2001);
|
||||
let root_id = ThreadId::from_string(&root_uuid.to_string()).expect("root id");
|
||||
let root_path = write_ordinaled_paginated_rollout(
|
||||
home.path(),
|
||||
"2025-01-03T13-01-00",
|
||||
root_uuid,
|
||||
[
|
||||
user_message("root before checkpoint"),
|
||||
compacted("root checkpoint", Some(Vec::new())),
|
||||
turn_started("root-excluded"),
|
||||
user_message("root after cutoff"),
|
||||
],
|
||||
);
|
||||
let archived_root = home
|
||||
.path()
|
||||
.join("archived_sessions")
|
||||
.join(root_path.file_name().expect("root filename"));
|
||||
std::fs::create_dir_all(archived_root.parent().expect("archive parent"))
|
||||
.expect("create archive directory");
|
||||
std::fs::rename(root_path, &archived_root).expect("archive root rollout");
|
||||
|
||||
let middle_uuid = Uuid::from_u128(/*v*/ 2002);
|
||||
let middle_id = ThreadId::from_string(&middle_uuid.to_string()).expect("middle id");
|
||||
let middle_path = write_ordinaled_paginated_rollout(
|
||||
home.path(),
|
||||
"2025-01-03T13-01-01",
|
||||
middle_uuid,
|
||||
[
|
||||
turn_started("middle-turn"),
|
||||
user_message("middle inherited"),
|
||||
completed_user_message("middle-turn", "middle inherited"),
|
||||
turn_context(home.path(), "middle-turn"),
|
||||
turn_complete("middle-turn"),
|
||||
],
|
||||
);
|
||||
set_history_base(
|
||||
middle_path.as_path(),
|
||||
history_position(
|
||||
archived_root.as_path(),
|
||||
root_id,
|
||||
/*end_ordinal_exclusive*/ 3,
|
||||
),
|
||||
);
|
||||
|
||||
let child_uuid = Uuid::from_u128(/*v*/ 2003);
|
||||
let child_id = ThreadId::from_string(&child_uuid.to_string()).expect("child id");
|
||||
let child_path = write_ordinaled_paginated_rollout(
|
||||
home.path(),
|
||||
"2025-01-03T13-01-02",
|
||||
child_uuid,
|
||||
[
|
||||
turn_started("child-turn"),
|
||||
user_message("child local"),
|
||||
completed_user_message("child-turn", "child local"),
|
||||
turn_context(home.path(), "child-turn"),
|
||||
turn_complete("child-turn"),
|
||||
],
|
||||
);
|
||||
set_history_base(
|
||||
child_path.as_path(),
|
||||
history_position(
|
||||
middle_path.as_path(),
|
||||
middle_id,
|
||||
/*end_ordinal_exclusive*/ 6,
|
||||
),
|
||||
);
|
||||
let store = LocalThreadStore::new(test_config(home.path()), /*state_db*/ None);
|
||||
|
||||
let context = store
|
||||
.load_latest_model_context(LoadThreadHistoryParams {
|
||||
thread_id: child_id,
|
||||
include_archived: false,
|
||||
})
|
||||
.await
|
||||
.expect("load lineage model context");
|
||||
|
||||
assert!(matches!(
|
||||
context.items.first(),
|
||||
Some(RolloutItem::SessionMeta(meta)) if meta.meta.id == child_id
|
||||
));
|
||||
let child_meta = codex_rollout::read_session_meta_line(child_path.as_path())
|
||||
.await
|
||||
.expect("read child metadata");
|
||||
let expected = vec![
|
||||
RolloutItem::SessionMeta(Box::new(child_meta)),
|
||||
compacted("root checkpoint", Some(Vec::new())),
|
||||
turn_started("middle-turn"),
|
||||
user_message("middle inherited"),
|
||||
completed_user_message("middle-turn", "middle inherited"),
|
||||
turn_context(home.path(), "middle-turn"),
|
||||
turn_complete("middle-turn"),
|
||||
turn_started("child-turn"),
|
||||
user_message("child local"),
|
||||
completed_user_message("child-turn", "child local"),
|
||||
turn_context(home.path(), "child-turn"),
|
||||
turn_complete("child-turn"),
|
||||
];
|
||||
assert_eq!(
|
||||
serde_json::to_value(&context.items).expect("serialize context"),
|
||||
serde_json::to_value(&expected).expect("serialize expected context")
|
||||
);
|
||||
// The same frozen lineage must replay from compressed files, without materializing or
|
||||
// accidentally including the archived root's records after the inherited cutoff.
|
||||
for path in [&archived_root, &middle_path, &child_path] {
|
||||
let input = std::fs::File::open(path).expect("open rollout");
|
||||
let output = std::fs::File::create(path.with_extension("jsonl.zst"))
|
||||
.expect("create compressed rollout");
|
||||
zstd::stream::copy_encode(input, output, /*level*/ 3).expect("compress rollout");
|
||||
std::fs::remove_file(path).expect("remove plain rollout");
|
||||
}
|
||||
let compressed_context = store
|
||||
.load_latest_model_context(LoadThreadHistoryParams {
|
||||
thread_id: child_id,
|
||||
include_archived: false,
|
||||
})
|
||||
.await
|
||||
.expect("load compressed lineage model context");
|
||||
assert_eq!(
|
||||
serde_json::to_value(compressed_context.items).expect("serialize compressed context"),
|
||||
serde_json::to_value(expected).expect("serialize expected context")
|
||||
);
|
||||
assert!(
|
||||
[archived_root, middle_path, child_path]
|
||||
.iter()
|
||||
.all(|path| !path.exists())
|
||||
);
|
||||
}
|
||||
|
||||
fn write_paginated_rollout<const N: usize>(
|
||||
home: &Path,
|
||||
timestamp: &str,
|
||||
uuid: Uuid,
|
||||
items: [RolloutItem; N],
|
||||
) -> PathBuf {
|
||||
let path =
|
||||
write_session_file_with_history_mode(home, timestamp, uuid, ThreadHistoryMode::Paginated)
|
||||
.expect("write session file");
|
||||
append_items(path.as_path(), items);
|
||||
path
|
||||
}
|
||||
|
||||
fn write_ordinaled_paginated_rollout<const N: usize>(
|
||||
home: &Path,
|
||||
timestamp: &str,
|
||||
uuid: Uuid,
|
||||
items: [RolloutItem; N],
|
||||
) -> PathBuf {
|
||||
let path =
|
||||
write_session_file_with_history_mode(home, timestamp, uuid, ThreadHistoryMode::Paginated)
|
||||
.expect("write session file");
|
||||
let mut file = OpenOptions::new()
|
||||
.append(true)
|
||||
.open(path.as_path())
|
||||
.expect("open session file");
|
||||
for (index, item) in items.into_iter().enumerate() {
|
||||
let line = RolloutLine {
|
||||
timestamp: "2025-01-03T13:00:01Z".to_string(),
|
||||
ordinal: Some(u64::try_from(index).expect("fixture index fits u64") + 1),
|
||||
item,
|
||||
};
|
||||
writeln!(
|
||||
file,
|
||||
"{}",
|
||||
serde_json::to_string(&line).expect("serialize line")
|
||||
)
|
||||
.expect("append rollout line");
|
||||
}
|
||||
path
|
||||
}
|
||||
|
||||
fn set_history_base(path: &Path, history_base: HistoryPosition) {
|
||||
let contents = std::fs::read_to_string(path).expect("read rollout");
|
||||
let mut lines = contents.lines();
|
||||
let mut head: serde_json::Value =
|
||||
serde_json::from_str(lines.next().expect("session meta line")).expect("parse head");
|
||||
head["payload"]["history_base"] =
|
||||
serde_json::to_value(history_base).expect("serialize history base");
|
||||
let mut updated = serde_json::to_string(&head).expect("serialize head");
|
||||
for line in lines {
|
||||
updated.push('\n');
|
||||
updated.push_str(line);
|
||||
}
|
||||
updated.push('\n');
|
||||
std::fs::write(path, updated).expect("write history base");
|
||||
}
|
||||
|
||||
fn history_position(
|
||||
path: &Path,
|
||||
thread_id: ThreadId,
|
||||
end_ordinal_exclusive: u64,
|
||||
) -> HistoryPosition {
|
||||
HistoryPosition {
|
||||
thread_id,
|
||||
end_ordinal_exclusive,
|
||||
end_byte_offset: rollout_end_byte_offset(path, end_ordinal_exclusive),
|
||||
}
|
||||
}
|
||||
|
||||
fn rollout_end_byte_offset(path: &Path, end_ordinal_exclusive: u64) -> u64 {
|
||||
let contents = std::fs::read(path).expect("read rollout");
|
||||
let mut byte_offset = 0_u64;
|
||||
for line in contents.split_inclusive(|byte| *byte == b'\n') {
|
||||
let parsed = codex_rollout::parse_rollout_line_bytes(line)
|
||||
.expect("parse rollout line for byte offset");
|
||||
if parsed.ordinal == Some(end_ordinal_exclusive) {
|
||||
return byte_offset;
|
||||
}
|
||||
byte_offset += u64::try_from(line.len()).expect("line length fits u64");
|
||||
}
|
||||
byte_offset
|
||||
}
|
||||
|
||||
async fn assert_reverse_scan_matches_full_history(home: &Path, path: &Path) {
|
||||
let session_meta = codex_rollout::read_session_meta_line(path)
|
||||
.await
|
||||
.expect("read session metadata");
|
||||
let store = LocalThreadStore::new(test_config(home), /*state_db*/ None);
|
||||
let items = store
|
||||
.load_latest_model_context(LoadThreadHistoryParams {
|
||||
thread_id: session_meta.meta.id,
|
||||
include_archived: false,
|
||||
})
|
||||
.await
|
||||
.expect("scan model context")
|
||||
.items;
|
||||
let full_items = read_thread::load_history_items(path)
|
||||
.await
|
||||
.expect("load full history");
|
||||
|
||||
assert_eq!(
|
||||
serde_json::to_value(items).expect("serialize scanned items"),
|
||||
serde_json::to_value(full_items).expect("serialize full items")
|
||||
);
|
||||
}
|
||||
|
||||
fn append_items(path: &Path, items: impl IntoIterator<Item = RolloutItem>) {
|
||||
let mut file = OpenOptions::new()
|
||||
.append(true)
|
||||
.open(path)
|
||||
.expect("open session file");
|
||||
for item in items {
|
||||
let line = RolloutLine {
|
||||
timestamp: "2025-01-03T13:00:01Z".to_string(),
|
||||
ordinal: None,
|
||||
item,
|
||||
};
|
||||
writeln!(
|
||||
file,
|
||||
"{}",
|
||||
serde_json::to_string(&line).expect("serialize line")
|
||||
)
|
||||
.expect("append rollout line");
|
||||
}
|
||||
}
|
||||
|
||||
fn turn_started(turn_id: &str) -> RolloutItem {
|
||||
RolloutItem::EventMsg(EventMsg::TurnStarted(TurnStartedEvent {
|
||||
turn_attribution: None,
|
||||
turn_id: turn_id.to_string(),
|
||||
root_turn_id: None,
|
||||
trace_id: None,
|
||||
started_at: None,
|
||||
model_context_window: Some(128_000),
|
||||
collaboration_mode_kind: Default::default(),
|
||||
}))
|
||||
}
|
||||
|
||||
fn turn_complete(turn_id: &str) -> RolloutItem {
|
||||
RolloutItem::EventMsg(EventMsg::TurnComplete(TurnCompleteEvent {
|
||||
root_turn_id: None,
|
||||
turn_id: turn_id.to_string(),
|
||||
last_agent_message: None,
|
||||
error: None,
|
||||
started_at: None,
|
||||
completed_at: None,
|
||||
duration_ms: None,
|
||||
time_to_first_token_ms: None,
|
||||
}))
|
||||
}
|
||||
|
||||
fn user_message(message: &str) -> RolloutItem {
|
||||
RolloutItem::ResponseItem(
|
||||
ResponseItem::Message {
|
||||
status: None,
|
||||
encrypted_content: None,
|
||||
id: None,
|
||||
role: "user".to_string(),
|
||||
content: vec![ContentItem::InputText {
|
||||
text: message.to_string(),
|
||||
}],
|
||||
phase: None,
|
||||
internal_chat_message_metadata_passthrough: None,
|
||||
}
|
||||
.into(),
|
||||
)
|
||||
}
|
||||
|
||||
fn contextual_user_message() -> RolloutItem {
|
||||
user_message("<environment_context>context only</environment_context>")
|
||||
}
|
||||
|
||||
fn completed_user_message(turn_id: &str, message: &str) -> RolloutItem {
|
||||
RolloutItem::EventMsg(EventMsg::ItemCompleted(ItemCompletedEvent {
|
||||
content_token_count: None,
|
||||
thread_id: codex_protocol::ThreadId::from_string("00000000-0000-0000-0000-000000000000")
|
||||
.expect("fixture thread id"),
|
||||
turn_id: turn_id.to_string(),
|
||||
item: TurnItem::UserMessage(UserMessageItem {
|
||||
id: format!("user-{turn_id}"),
|
||||
client_id: None,
|
||||
content: vec![UserInput::Text {
|
||||
text: message.to_string(),
|
||||
text_elements: Vec::new(),
|
||||
}],
|
||||
}),
|
||||
started_at_ms: Some(0),
|
||||
completed_at_ms: 0,
|
||||
}))
|
||||
}
|
||||
|
||||
fn turn_context(root: &Path, turn_id: &str) -> RolloutItem {
|
||||
RolloutItem::TurnContext(TurnContextItem {
|
||||
turn_id: Some(turn_id.to_string()),
|
||||
root_turn_id: None,
|
||||
direct_only_tool_namespaces: None,
|
||||
disabled_plugin_ids: None,
|
||||
cwd: serde_json::from_value(serde_json::json!(root)).expect("absolute cwd"),
|
||||
approval_policy: AskForApproval::Never,
|
||||
approvals_reviewer: None,
|
||||
permission_profile: codex_protocol::models::PermissionProfile::read_only(),
|
||||
active_permission_profile: None,
|
||||
model: "test-model".to_string(),
|
||||
comp_hash: None,
|
||||
collaboration_mode: None,
|
||||
multi_agent_version: None,
|
||||
realtime_active: None,
|
||||
cyber_access_program: None,
|
||||
effort: None,
|
||||
summary: Some(ReasoningSummary::Auto),
|
||||
})
|
||||
}
|
||||
|
||||
fn compacted(message: &str, replacement_history: Option<Vec<ResponseItem>>) -> RolloutItem {
|
||||
RolloutItem::Compacted(Box::new(CompactedItem {
|
||||
message: message.to_string(),
|
||||
replacement_history: replacement_history
|
||||
.map(|items| items.into_iter().map(Into::into).collect()),
|
||||
retained_context: None,
|
||||
guardian_history: None,
|
||||
mcp_resource_origins: None,
|
||||
window_number: Some(1),
|
||||
first_window_id: None,
|
||||
previous_window_id: None,
|
||||
window_id: None,
|
||||
compaction_response_id: None,
|
||||
latest_token_usage_record: None,
|
||||
resume_metadata: None,
|
||||
}))
|
||||
}
|
||||
58
codex-rs/thread-store/src/local/move_thread_to_section.rs
Normal file
58
codex-rs/thread-store/src/local/move_thread_to_section.rs
Normal file
@@ -0,0 +1,58 @@
|
||||
use super::LocalThreadStore;
|
||||
use crate::MoveThreadToSectionParams;
|
||||
use crate::ThreadStoreError;
|
||||
use crate::ThreadStoreResult;
|
||||
|
||||
pub(super) async fn move_thread_to_section(
|
||||
store: &LocalThreadStore,
|
||||
params: MoveThreadToSectionParams,
|
||||
) -> ThreadStoreResult<()> {
|
||||
if params
|
||||
.section
|
||||
.as_deref()
|
||||
.is_some_and(|section| section.trim().is_empty())
|
||||
{
|
||||
return Err(ThreadStoreError::InvalidRequest {
|
||||
message: "section must not be empty".to_owned(),
|
||||
});
|
||||
}
|
||||
if params.section.is_none() && params.before_thread_id.is_some() {
|
||||
return Err(ThreadStoreError::InvalidRequest {
|
||||
message: "before thread cannot be specified without a section".to_owned(),
|
||||
});
|
||||
}
|
||||
|
||||
let Some(state_db) = store.state_db().await else {
|
||||
return Err(ThreadStoreError::Unsupported {
|
||||
operation: "thread/section/move",
|
||||
});
|
||||
};
|
||||
|
||||
let updated = state_db
|
||||
.move_thread_to_section(
|
||||
params.thread_id,
|
||||
params.section.as_deref(),
|
||||
params.before_thread_id,
|
||||
)
|
||||
.await
|
||||
.map_err(|err| {
|
||||
let message = err.to_string();
|
||||
if message.starts_with("before thread ")
|
||||
|| message.starts_with("thread ")
|
||||
|| message.starts_with("section ")
|
||||
{
|
||||
ThreadStoreError::InvalidRequest { message }
|
||||
} else {
|
||||
ThreadStoreError::Internal {
|
||||
message: format!("failed to move thread {}: {message}", params.thread_id),
|
||||
}
|
||||
}
|
||||
})?;
|
||||
if !updated {
|
||||
return Err(ThreadStoreError::ThreadNotFound {
|
||||
thread_id: params.thread_id,
|
||||
});
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
150
codex-rs/thread-store/src/local/original_history.rs
Normal file
150
codex-rs/thread-store/src/local/original_history.rs
Normal file
@@ -0,0 +1,150 @@
|
||||
//! Captures a fixed tail and reads its original-record suffix through one rollout reader.
|
||||
//! Unfinished lines are excluded; suffix reads require contiguous, complete records.
|
||||
|
||||
use std::io;
|
||||
use std::io::BufRead;
|
||||
use std::io::BufReader;
|
||||
use std::io::Read;
|
||||
use std::io::Seek;
|
||||
use std::io::SeekFrom;
|
||||
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::protocol::HistoryPosition;
|
||||
use codex_protocol::protocol::ThreadHistoryMode;
|
||||
use codex_rollout::ReverseJsonlScanner;
|
||||
use codex_rollout::RolloutItem;
|
||||
use codex_rollout::ScanOutcome;
|
||||
use codex_rollout::open_rollout_seekable_reader;
|
||||
use codex_rollout::parse_rollout_line_bytes;
|
||||
|
||||
use super::LocalThreadStore;
|
||||
use super::thread_rollout_resolver;
|
||||
use crate::OriginalHistoryItem;
|
||||
use crate::OriginalHistoryRead;
|
||||
use crate::OriginalHistoryRequest;
|
||||
use crate::ThreadStoreError;
|
||||
use crate::ThreadStoreResult;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "original_history_tests.rs"]
|
||||
mod tests;
|
||||
|
||||
pub(super) async fn read(
|
||||
store: &LocalThreadStore,
|
||||
thread_id: ThreadId,
|
||||
request: OriginalHistoryRequest,
|
||||
) -> ThreadStoreResult<OriginalHistoryRead> {
|
||||
let source = thread_rollout_resolver::resolve_current(store, thread_id)
|
||||
.await?
|
||||
.ok_or(ThreadStoreError::ThreadNotFound { thread_id })?;
|
||||
if source.rollout_id != thread_id {
|
||||
return Err(ThreadStoreError::Unsupported {
|
||||
operation: "original_history_after_revert",
|
||||
});
|
||||
}
|
||||
let (stop, keep_running) = tokio::sync::oneshot::channel::<()>();
|
||||
let result = tokio::task::spawn_blocking(move || {
|
||||
let mut file = open_rollout_seekable_reader(&source.path, || stop.is_closed())?;
|
||||
let mut header = Vec::new();
|
||||
BufReader::new(&mut file).read_until(b'\n', &mut header)?;
|
||||
let line = parse_rollout_line_bytes(&header).map_err(io::Error::other)?;
|
||||
let RolloutItem::SessionMeta(meta) = line.item else {
|
||||
return Err(io::Error::other("original history has no session header"));
|
||||
};
|
||||
if meta.meta.id != thread_id
|
||||
|| meta.meta.history_mode != ThreadHistoryMode::Paginated
|
||||
|| meta.meta.history_base.is_some()
|
||||
|| meta.meta.forked_from_id.is_some()
|
||||
|| meta.meta.parent_thread_id.is_some()
|
||||
|| meta.meta.subagent_history_start_ordinal.is_some()
|
||||
{
|
||||
return Err(io::Error::other(
|
||||
"original history requires a paginated root",
|
||||
));
|
||||
}
|
||||
let end_byte_offset = complete_end(&mut file)?;
|
||||
let end_ordinal_exclusive = {
|
||||
let mut scanner = ReverseJsonlScanner::new_at(&mut file, end_byte_offset)?;
|
||||
let Some(ScanOutcome::Parsed(last)) = scanner.scan_next_rollout_line()? else {
|
||||
return Err(io::Error::other("original history has an invalid tail"));
|
||||
};
|
||||
last.ordinal
|
||||
.and_then(|ordinal| ordinal.checked_add(1))
|
||||
.ok_or_else(|| io::Error::other("original history tail has no next ordinal"))?
|
||||
};
|
||||
let end = HistoryPosition {
|
||||
thread_id,
|
||||
end_ordinal_exclusive,
|
||||
end_byte_offset,
|
||||
};
|
||||
match request {
|
||||
OriginalHistoryRequest::Tail => Ok(OriginalHistoryRead {
|
||||
items: Vec::new(),
|
||||
end,
|
||||
}),
|
||||
OriginalHistoryRequest::After(start) => {
|
||||
if start.thread_id != thread_id
|
||||
|| start.end_byte_offset > end.end_byte_offset
|
||||
|| start.end_ordinal_exclusive > end.end_ordinal_exclusive
|
||||
{
|
||||
return Err(io::Error::other("original history range no longer applies"));
|
||||
}
|
||||
file.seek(SeekFrom::Start(start.end_byte_offset))?;
|
||||
let mut reader =
|
||||
BufReader::new(file.take(end.end_byte_offset - start.end_byte_offset));
|
||||
let mut position = start;
|
||||
let mut bytes = Vec::new();
|
||||
let mut items = Vec::new();
|
||||
while reader.read_until(b'\n', &mut bytes)? != 0 {
|
||||
if !bytes.ends_with(b"\n") {
|
||||
return Err(io::Error::other("original history record is incomplete"));
|
||||
}
|
||||
let line = parse_rollout_line_bytes(&bytes).map_err(io::Error::other)?;
|
||||
if line.ordinal != Some(position.end_ordinal_exclusive) {
|
||||
return Err(io::Error::other("original history ordinal changed"));
|
||||
}
|
||||
position.end_byte_offset += bytes.len() as u64;
|
||||
position.end_ordinal_exclusive = position
|
||||
.end_ordinal_exclusive
|
||||
.checked_add(1)
|
||||
.ok_or_else(|| io::Error::other("original history ordinal overflow"))?;
|
||||
items.push(OriginalHistoryItem {
|
||||
item: line.item,
|
||||
end: position,
|
||||
});
|
||||
bytes.clear();
|
||||
}
|
||||
if position != end {
|
||||
return Err(io::Error::other("original history ended before its cutoff"));
|
||||
}
|
||||
Ok(OriginalHistoryRead { items, end })
|
||||
}
|
||||
}
|
||||
})
|
||||
.await;
|
||||
drop(keep_running);
|
||||
result
|
||||
.map_err(|error| ThreadStoreError::Internal {
|
||||
message: format!("original history reader failed: {error}"),
|
||||
})?
|
||||
.map_err(|error| ThreadStoreError::Internal {
|
||||
message: format!("cannot read original history: {error}"),
|
||||
})
|
||||
}
|
||||
|
||||
/// Find the last complete record boundary without scanning the earlier history.
|
||||
fn complete_end(file: &mut (impl Read + Seek)) -> io::Result<u64> {
|
||||
let mut end = file.seek(SeekFrom::End(0))?;
|
||||
let mut bytes = [0; 8192];
|
||||
while end > 0 {
|
||||
let count = end.min(bytes.len() as u64) as usize;
|
||||
let start = end - count as u64;
|
||||
file.seek(SeekFrom::Start(start))?;
|
||||
file.read_exact(&mut bytes[..count])?;
|
||||
if let Some(index) = bytes[..count].iter().rposition(|byte| *byte == b'\n') {
|
||||
return Ok(start + index as u64 + 1);
|
||||
}
|
||||
end = start;
|
||||
}
|
||||
Err(io::Error::other("original history has no complete record"))
|
||||
}
|
||||
194
codex-rs/thread-store/src/local/original_history_tests.rs
Normal file
194
codex-rs/thread-store/src/local/original_history_tests.rs
Normal file
@@ -0,0 +1,194 @@
|
||||
#![cfg(test)]
|
||||
//! Raw history captures retain complete originals and defer unfinished suffixes.
|
||||
|
||||
use std::fs::OpenOptions;
|
||||
use std::io::Write;
|
||||
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::protocol::HistoryPosition;
|
||||
use codex_protocol::protocol::ThreadHistoryMode;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
|
||||
use super::super::test_support::test_config;
|
||||
use super::super::test_support::write_session_file_with_history_mode;
|
||||
use crate::LocalThreadStore;
|
||||
use crate::OriginalHistoryRequest;
|
||||
use crate::ThreadStore;
|
||||
|
||||
#[tokio::test]
|
||||
async fn reads_complete_fixed_suffix_and_rejects_truncated_source()
|
||||
-> Result<(), Box<dyn std::error::Error>> {
|
||||
let dir = tempfile::tempdir()?;
|
||||
let id = uuid::Uuid::new_v4();
|
||||
let owner = ThreadId::from_string(&id.to_string())?;
|
||||
let path = write_session_file_with_history_mode(
|
||||
dir.path(),
|
||||
"2025-01-03T10-00-00",
|
||||
id,
|
||||
ThreadHistoryMode::Paginated,
|
||||
)?;
|
||||
let store = LocalThreadStore::new(test_config(dir.path()), /*state_db*/ None);
|
||||
let start = store
|
||||
.read_original_history(owner, OriginalHistoryRequest::Tail)
|
||||
.await?
|
||||
.end;
|
||||
let original = json!({"timestamp":"2025-01-03T10:00:01Z","ordinal":1,"type":"response_item",
|
||||
"payload":{"type":"message","role":"assistant","content":[{"type":"output_text","text":"Original é🙂"}]}});
|
||||
let line = format!("{original}\n");
|
||||
let mut file = OpenOptions::new().append(true).open(&path)?;
|
||||
// The tail ignores a partially appended record rather than losing it.
|
||||
file.write_all(&line.as_bytes()[..12])?;
|
||||
assert_eq!(
|
||||
store
|
||||
.read_original_history(owner, OriginalHistoryRequest::Tail)
|
||||
.await?
|
||||
.end,
|
||||
start
|
||||
);
|
||||
let partial = store
|
||||
.read_original_history(owner, OriginalHistoryRequest::After(start))
|
||||
.await?;
|
||||
assert!(partial.items.is_empty());
|
||||
assert_eq!(partial.end, start);
|
||||
file.write_all(&line.as_bytes()[12..])?;
|
||||
let read = store
|
||||
.read_original_history(owner, OriginalHistoryRequest::After(start))
|
||||
.await?;
|
||||
let end = HistoryPosition {
|
||||
end_byte_offset: start.end_byte_offset + line.len() as u64,
|
||||
end_ordinal_exclusive: start.end_ordinal_exclusive + 1,
|
||||
..start
|
||||
};
|
||||
let mut later = original.clone();
|
||||
later["ordinal"] = json!(2);
|
||||
later["payload"]["content"][0]["text"] = json!("After the cutoff");
|
||||
writeln!(file, "{later}")?;
|
||||
assert_eq!(read.end, end);
|
||||
assert_eq!(read.items.len(), 1);
|
||||
assert_eq!(read.items[0].end, end);
|
||||
assert_eq!(
|
||||
serde_json::to_value(&read.items[0].item)?,
|
||||
json!({"type":"response_item","payload":original["payload"]})
|
||||
);
|
||||
let suffix = store
|
||||
.read_original_history(owner, OriginalHistoryRequest::After(end))
|
||||
.await?;
|
||||
assert_eq!(suffix.items.len(), 1);
|
||||
assert_eq!(
|
||||
serde_json::to_value(&suffix.items[0].item)?,
|
||||
json!({"type":"response_item","payload":later["payload"]})
|
||||
);
|
||||
let other = ThreadId::new();
|
||||
let wrong = HistoryPosition {
|
||||
thread_id: other,
|
||||
..start
|
||||
};
|
||||
assert!(
|
||||
store
|
||||
.read_original_history(owner, OriginalHistoryRequest::After(wrong))
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
// Windows append-only handles cannot truncate the file.
|
||||
drop(file);
|
||||
OpenOptions::new()
|
||||
.write(true)
|
||||
.open(&path)?
|
||||
.set_len(start.end_byte_offset)?;
|
||||
assert!(
|
||||
store
|
||||
.read_original_history(owner, OriginalHistoryRequest::After(end))
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn reads_compressed_suffix_and_defers_unfinished_record()
|
||||
-> Result<(), Box<dyn std::error::Error>> {
|
||||
let dir = tempfile::tempdir()?;
|
||||
let id = uuid::Uuid::new_v4();
|
||||
let owner = ThreadId::from_string(&id.to_string())?;
|
||||
let path = write_session_file_with_history_mode(
|
||||
dir.path(),
|
||||
"2025-01-03T10-00-00",
|
||||
id,
|
||||
ThreadHistoryMode::Paginated,
|
||||
)?;
|
||||
let store = LocalThreadStore::new(test_config(dir.path()), /*state_db*/ None);
|
||||
let start = store
|
||||
.read_original_history(owner, OriginalHistoryRequest::Tail)
|
||||
.await?
|
||||
.end;
|
||||
let original = json!({"timestamp":"2025-01-03T10:00:01Z","ordinal":1,"type":"response_item",
|
||||
"payload":{"type":"message","role":"assistant","content":[{"type":"output_text","text":"Original é🙂"}]}});
|
||||
let mut later = original.clone();
|
||||
later["ordinal"] = json!(2);
|
||||
later["payload"]["content"][0]["text"] = json!("Completed in the next frame");
|
||||
let original_line = format!("{original}\n");
|
||||
let later_line = format!("{later}\n");
|
||||
let mut file = OpenOptions::new().append(true).open(&path)?;
|
||||
file.write_all(original_line.as_bytes())?;
|
||||
file.write_all(&later_line.as_bytes()[..12])?;
|
||||
drop(file);
|
||||
|
||||
let compressed_path = path.with_extension("jsonl.zst");
|
||||
let contents = std::fs::read(&path)?;
|
||||
std::fs::write(
|
||||
&compressed_path,
|
||||
zstd::stream::encode_all(contents.as_slice(), /*level*/ 3)?,
|
||||
)?;
|
||||
std::fs::remove_file(&path)?;
|
||||
let read = store
|
||||
.read_original_history(owner, OriginalHistoryRequest::After(start))
|
||||
.await?;
|
||||
let end = HistoryPosition {
|
||||
end_byte_offset: start.end_byte_offset + original_line.len() as u64,
|
||||
end_ordinal_exclusive: start.end_ordinal_exclusive + 1,
|
||||
..start
|
||||
};
|
||||
assert_eq!(read.end, end);
|
||||
assert_eq!(read.items.len(), 1);
|
||||
assert_eq!(
|
||||
(
|
||||
serde_json::to_value(&read.items[0].item)?,
|
||||
read.items[0].end
|
||||
),
|
||||
(
|
||||
json!({"type":"response_item","payload":original["payload"]}),
|
||||
end
|
||||
)
|
||||
);
|
||||
|
||||
// A complete zstd frame may still end with an unfinished logical JSONL record.
|
||||
let mut compressed = OpenOptions::new().append(true).open(&compressed_path)?;
|
||||
compressed.write_all(&zstd::stream::encode_all(
|
||||
&later_line.as_bytes()[12..],
|
||||
/*level*/ 3,
|
||||
)?)?;
|
||||
drop(compressed);
|
||||
let suffix = store
|
||||
.read_original_history(owner, OriginalHistoryRequest::After(end))
|
||||
.await?;
|
||||
let tail = HistoryPosition {
|
||||
end_byte_offset: end.end_byte_offset + later_line.len() as u64,
|
||||
end_ordinal_exclusive: end.end_ordinal_exclusive + 1,
|
||||
..end
|
||||
};
|
||||
assert_eq!(suffix.end, tail);
|
||||
assert_eq!(suffix.items.len(), 1);
|
||||
assert_eq!(
|
||||
(
|
||||
serde_json::to_value(&suffix.items[0].item)?,
|
||||
suffix.items[0].end
|
||||
),
|
||||
(
|
||||
json!({"type":"response_item","payload":later["payload"]}),
|
||||
tail
|
||||
)
|
||||
);
|
||||
assert!(!path.exists());
|
||||
Ok(())
|
||||
}
|
||||
210
codex-rs/thread-store/src/local/paginated_fork.rs
Normal file
210
codex-rs/thread-store/src/local/paginated_fork.rs
Normal file
@@ -0,0 +1,210 @@
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::protocol::HistoryPosition;
|
||||
use codex_rollout::RolloutItem;
|
||||
use std::sync::Arc;
|
||||
|
||||
use super::LocalThreadStore;
|
||||
use super::live_writer;
|
||||
use super::model_context;
|
||||
use super::rollout_lineage::RolloutLineage;
|
||||
use super::thread_history::find_source_turn;
|
||||
use super::thread_history::find_visible_turn;
|
||||
use crate::ForkBoundary;
|
||||
use crate::PrepareForkParams;
|
||||
use crate::PreparedFork;
|
||||
use crate::ThreadStoreError;
|
||||
use crate::ThreadStoreResult;
|
||||
|
||||
pub(super) async fn prepare(
|
||||
store: &LocalThreadStore,
|
||||
params: PrepareForkParams,
|
||||
) -> ThreadStoreResult<PreparedFork> {
|
||||
let PrepareForkParams {
|
||||
thread_id,
|
||||
ref boundary,
|
||||
} = params;
|
||||
let source_reservation = store.live_writer_locks.reserve_lifecycle(thread_id).await;
|
||||
// Keep the source reserved until persistence and lineage materialization finish, even if the
|
||||
// caller cancels fork preparation.
|
||||
let lineage_store = store.clone();
|
||||
let (lineage, source_reservation) = tokio::spawn(async move {
|
||||
match live_writer::persist_thread(&lineage_store, thread_id).await {
|
||||
Ok(()) | Err(ThreadStoreError::ThreadNotFound { .. }) => {}
|
||||
Err(err) => return Err(err),
|
||||
}
|
||||
let lineage = lineage_store
|
||||
.resolve_rollout_lineage_for_reference(thread_id)
|
||||
.await?;
|
||||
Ok::<_, ThreadStoreError>((lineage, source_reservation))
|
||||
})
|
||||
.await
|
||||
.map_err(|err| ThreadStoreError::Internal {
|
||||
message: format!("failed to resolve fork lineage: {err}"),
|
||||
})??;
|
||||
if store.state_db.is_none() {
|
||||
return Err(ThreadStoreError::Unsupported {
|
||||
operation: "prepare_fork",
|
||||
});
|
||||
}
|
||||
let (history_base, model_context) = lineage
|
||||
.read_with_fallback(store, |lineage| {
|
||||
read_fork_history(store, thread_id, boundary, lineage)
|
||||
})
|
||||
.await?;
|
||||
Ok(PreparedFork::with_source_reservation(
|
||||
thread_id,
|
||||
history_base,
|
||||
Arc::new(model_context),
|
||||
source_reservation,
|
||||
))
|
||||
}
|
||||
|
||||
async fn read_fork_history(
|
||||
store: &LocalThreadStore,
|
||||
thread_id: ThreadId,
|
||||
boundary: &ForkBoundary,
|
||||
lineage: RolloutLineage,
|
||||
) -> ThreadStoreResult<(Option<HistoryPosition>, Vec<RolloutItem>)> {
|
||||
let source_segment = lineage
|
||||
.segments()
|
||||
.last()
|
||||
.ok_or_else(|| ThreadStoreError::Internal {
|
||||
message: "fork lineage has no source segment".to_string(),
|
||||
})?;
|
||||
if !matches!(boundary, ForkBoundary::Latest) {
|
||||
for segment in lineage
|
||||
.segments()
|
||||
.iter()
|
||||
.take(lineage.segments().len().saturating_sub(1))
|
||||
{
|
||||
let _ancestor_writer_guard = store.live_writer_locks.lock(segment.rollout_id()).await;
|
||||
super::thread_history_materialization::materialize_to_sqlite_with_reads(
|
||||
store,
|
||||
segment.rollout_id(),
|
||||
segment.rollout_path.as_path(),
|
||||
&lineage.reads,
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
}
|
||||
let source_writer_guard = store.live_writer_locks.lock(thread_id).await;
|
||||
super::thread_history_materialization::materialize_to_sqlite(
|
||||
store,
|
||||
source_segment.rollout_id(),
|
||||
source_segment.rollout_path.as_path(),
|
||||
)
|
||||
.await?;
|
||||
|
||||
let history_base = history_base_at_boundary(store, thread_id, boundary, &lineage).await?;
|
||||
drop(source_writer_guard);
|
||||
let model_context = model_context::load_for_fork(lineage, history_base).await?;
|
||||
Ok((history_base, model_context))
|
||||
}
|
||||
|
||||
pub(super) async fn history_base_at_boundary(
|
||||
store: &LocalThreadStore,
|
||||
thread_id: ThreadId,
|
||||
boundary: &ForkBoundary,
|
||||
lineage: &RolloutLineage,
|
||||
) -> ThreadStoreResult<Option<HistoryPosition>> {
|
||||
let source_segment = lineage
|
||||
.segments()
|
||||
.last()
|
||||
.ok_or_else(|| ThreadStoreError::Internal {
|
||||
message: "fork lineage has no source segment".to_string(),
|
||||
})?;
|
||||
let latest_projection_state =
|
||||
super::thread_history::projection_state(store, source_segment.rollout_id())
|
||||
.await?
|
||||
.ok_or_else(|| ThreadStoreError::Internal {
|
||||
message: format!("missing projection state for paginated thread {thread_id}"),
|
||||
})?;
|
||||
let latest_position = HistoryPosition {
|
||||
thread_id: source_segment.rollout_id(),
|
||||
end_ordinal_exclusive: latest_projection_state.next_ordinal,
|
||||
end_byte_offset: latest_projection_state.next_byte_offset,
|
||||
};
|
||||
let pool = store.thread_history_db().await?;
|
||||
let position = match boundary {
|
||||
ForkBoundary::Latest => latest_position,
|
||||
ForkBoundary::ThroughTurn(turn_id) => {
|
||||
let visible = lineage.for_history_page().await?;
|
||||
let row = find_visible_turn(pool, &visible, turn_id.as_str()).await?;
|
||||
if row.status == "inProgress" {
|
||||
return Err(ThreadStoreError::InvalidRequest {
|
||||
message: format!("lastTurnId '{turn_id}' identifies an in-progress turn"),
|
||||
});
|
||||
}
|
||||
let rollout_end_ordinal = row
|
||||
.rollout_end_ordinal
|
||||
.ok_or_else(|| missing_turn_position(turn_id.as_str()))?;
|
||||
let rollout_end_byte_offset = row
|
||||
.rollout_end_byte_offset
|
||||
.ok_or_else(|| missing_turn_position(turn_id.as_str()))?;
|
||||
HistoryPosition {
|
||||
thread_id: row.rollout_id,
|
||||
end_ordinal_exclusive: u64::try_from(rollout_end_ordinal)
|
||||
.map_err(|_| invalid_turn_position(turn_id.as_str()))?
|
||||
.checked_add(1)
|
||||
.ok_or_else(|| invalid_turn_position(turn_id.as_str()))?,
|
||||
end_byte_offset: u64::try_from(rollout_end_byte_offset)
|
||||
.map_err(|_| invalid_turn_position(turn_id.as_str()))?,
|
||||
}
|
||||
}
|
||||
ForkBoundary::BeforeTurn(turn_id) => {
|
||||
let visible = lineage.for_history_page().await?;
|
||||
let row = find_source_turn(pool, &visible, turn_id.as_str()).await?;
|
||||
if row.rollout_end_ordinal == Some(row.rollout_ordinal) {
|
||||
return Err(ThreadStoreError::InvalidRequest {
|
||||
message: format!("turn {turn_id} does not have a persisted start boundary"),
|
||||
});
|
||||
}
|
||||
let rollout_byte_offset = row
|
||||
.rollout_byte_offset
|
||||
.ok_or_else(|| missing_turn_position(turn_id.as_str()))?;
|
||||
HistoryPosition {
|
||||
thread_id: row.rollout_id,
|
||||
end_ordinal_exclusive: u64::try_from(row.rollout_ordinal)
|
||||
.map_err(|_| invalid_turn_position(turn_id.as_str()))?,
|
||||
end_byte_offset: u64::try_from(rollout_byte_offset)
|
||||
.map_err(|_| invalid_turn_position(turn_id.as_str()))?,
|
||||
}
|
||||
}
|
||||
};
|
||||
let segment_index = lineage
|
||||
.segments()
|
||||
.iter()
|
||||
.position(|segment| segment.rollout_id() == position.thread_id)
|
||||
.ok_or_else(|| ThreadStoreError::Internal {
|
||||
message: "fork position is outside the source lineage".to_string(),
|
||||
})?;
|
||||
if lineage.segments()[segment_index].end.is_some_and(|end| {
|
||||
position.end_ordinal_exclusive > end.end_ordinal_exclusive
|
||||
|| position.end_byte_offset > end.end_byte_offset
|
||||
}) {
|
||||
return Err(ThreadStoreError::InvalidRequest {
|
||||
message: "fork boundary exceeds inherited source history".to_string(),
|
||||
});
|
||||
}
|
||||
let history_base =
|
||||
if position.end_ordinal_exclusive == lineage.segments()[segment_index].start_ordinal() {
|
||||
segment_index
|
||||
.checked_sub(1)
|
||||
.and_then(|index| lineage.segments()[index].end)
|
||||
} else {
|
||||
Some(position)
|
||||
};
|
||||
Ok(history_base)
|
||||
}
|
||||
|
||||
fn missing_turn_position(turn_id: &str) -> ThreadStoreError {
|
||||
ThreadStoreError::InvalidRequest {
|
||||
message: format!("turn {turn_id} does not have persisted rollout positions"),
|
||||
}
|
||||
}
|
||||
|
||||
fn invalid_turn_position(turn_id: &str) -> ThreadStoreError {
|
||||
ThreadStoreError::Internal {
|
||||
message: format!("invalid rollout position for turn {turn_id}"),
|
||||
}
|
||||
}
|
||||
58
codex-rs/thread-store/src/local/pending_thread_metadata.rs
Normal file
58
codex-rs/thread-store/src/local/pending_thread_metadata.rs
Normal file
@@ -0,0 +1,58 @@
|
||||
use std::collections::HashMap;
|
||||
use std::collections::hash_map::Entry;
|
||||
use std::sync::Arc;
|
||||
|
||||
use codex_protocol::ThreadId;
|
||||
use tokio::sync::Mutex;
|
||||
use tokio::sync::OwnedMutexGuard;
|
||||
|
||||
use crate::ThreadMetadataPatch;
|
||||
use crate::ThreadStoreError;
|
||||
use crate::ThreadStoreResult;
|
||||
|
||||
type PendingThreadMetadataEntry = Arc<Mutex<Option<ThreadMetadataPatch>>>;
|
||||
|
||||
/// In-memory metadata staged before a reserved thread starts.
|
||||
///
|
||||
/// The registry lock is held only while looking up or removing an entry. Never await an entry
|
||||
/// lock while holding the registry lock. Callers may hold an entry lock before the live-writer
|
||||
/// lock.
|
||||
#[derive(Clone, Default)]
|
||||
pub(super) struct PendingThreadMetadataRegistry {
|
||||
entries: Arc<Mutex<HashMap<ThreadId, PendingThreadMetadataEntry>>>,
|
||||
}
|
||||
|
||||
pub(super) type LockedPendingThreadMetadata = OwnedMutexGuard<Option<ThreadMetadataPatch>>;
|
||||
|
||||
impl PendingThreadMetadataRegistry {
|
||||
pub(super) async fn stage(
|
||||
&self,
|
||||
thread_id: ThreadId,
|
||||
patch: ThreadMetadataPatch,
|
||||
) -> ThreadStoreResult<()> {
|
||||
if patch.is_empty() {
|
||||
return Err(ThreadStoreError::InvalidRequest {
|
||||
message: "pending thread metadata cannot be empty".to_string(),
|
||||
});
|
||||
}
|
||||
let mut entries = self.entries.lock().await;
|
||||
match entries.entry(thread_id) {
|
||||
Entry::Vacant(entry) => {
|
||||
entry.insert(Arc::new(Mutex::new(Some(patch))));
|
||||
Ok(())
|
||||
}
|
||||
Entry::Occupied(_) => Err(ThreadStoreError::InvalidRequest {
|
||||
message: format!("pending thread metadata already exists: {thread_id}"),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn remove(&self, thread_id: ThreadId) {
|
||||
self.entries.lock().await.remove(&thread_id);
|
||||
}
|
||||
|
||||
pub(super) async fn lock(&self, thread_id: ThreadId) -> Option<LockedPendingThreadMetadata> {
|
||||
let entry = self.entries.lock().await.get(&thread_id).cloned()?;
|
||||
Some(entry.lock_owned().await)
|
||||
}
|
||||
}
|
||||
622
codex-rs/thread-store/src/local/pending_thread_metadata_tests.rs
Normal file
622
codex-rs/thread-store/src/local/pending_thread_metadata_tests.rs
Normal file
@@ -0,0 +1,622 @@
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::models::BaseInstructions;
|
||||
use codex_protocol::protocol::EventMsg;
|
||||
use codex_protocol::protocol::SessionSource;
|
||||
use codex_protocol::protocol::ThreadHistoryMode;
|
||||
use codex_protocol::protocol::ThreadMemoryMode;
|
||||
use codex_protocol::protocol::UserMessageEvent;
|
||||
use codex_rollout::RolloutItem;
|
||||
use codex_rollout::RolloutRecorder;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tempfile::TempDir;
|
||||
|
||||
use super::*;
|
||||
use crate::CreateThreadParams;
|
||||
use crate::LiveThread;
|
||||
use crate::PersistContext;
|
||||
use crate::ThreadPersistenceMetadata;
|
||||
use crate::UpdateThreadMetadataParams;
|
||||
use crate::local::test_support::test_config;
|
||||
|
||||
#[tokio::test]
|
||||
async fn paginated_metadata_write_failure_stays_pending_until_retry() {
|
||||
let (_home, store, runtime) = store_with_runtime().await;
|
||||
let thread_id = ThreadId::new();
|
||||
let mut params = create_thread_params(thread_id);
|
||||
params.history_mode = ThreadHistoryMode::Paginated;
|
||||
let live_thread = LiveThread::create(store.clone(), params)
|
||||
.await
|
||||
.expect("create live thread");
|
||||
let pool = store
|
||||
.config
|
||||
.sqlite
|
||||
.open_read_write_pool(&store.config.sqlite.state_db_path())
|
||||
.await
|
||||
.expect("open SQL observer");
|
||||
sqlx::query(
|
||||
"CREATE TRIGGER reject_metadata BEFORE INSERT ON threads BEGIN SELECT RAISE(ABORT, 'metadata write rejected'); END",
|
||||
)
|
||||
.execute(&pool)
|
||||
.await
|
||||
.expect("reject index writes");
|
||||
|
||||
let error = live_thread
|
||||
.persist(PersistContext::Standard)
|
||||
.await
|
||||
.expect_err("failed index writes must remain pending");
|
||||
assert!(error.to_string().contains("metadata write rejected"));
|
||||
assert_eq!(
|
||||
runtime.get_thread(thread_id).await.expect("read index"),
|
||||
None
|
||||
);
|
||||
|
||||
sqlx::query("DROP TRIGGER reject_metadata")
|
||||
.execute(&pool)
|
||||
.await
|
||||
.expect("allow index writes");
|
||||
live_thread
|
||||
.persist(PersistContext::Standard)
|
||||
.await
|
||||
.expect("retry pending metadata");
|
||||
let metadata = runtime
|
||||
.get_thread(thread_id)
|
||||
.await
|
||||
.expect("read index")
|
||||
.expect("pending metadata was indexed");
|
||||
assert_eq!(
|
||||
(metadata.id, metadata.history_mode, metadata.model_provider),
|
||||
(
|
||||
thread_id,
|
||||
ThreadHistoryMode::Paginated,
|
||||
"test-provider".to_string()
|
||||
)
|
||||
);
|
||||
live_thread
|
||||
.shutdown()
|
||||
.await
|
||||
.expect("shutdown indexed thread");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn metadata_patch_failure_does_not_partially_apply() {
|
||||
let (_home, store, runtime) = store_with_runtime().await;
|
||||
let thread_id = ThreadId::new();
|
||||
let mut params = create_thread_params(thread_id);
|
||||
params.history_mode = ThreadHistoryMode::Paginated;
|
||||
let live_thread = LiveThread::create(store.clone(), params)
|
||||
.await
|
||||
.expect("create thread");
|
||||
live_thread
|
||||
.persist(PersistContext::Standard)
|
||||
.await
|
||||
.expect("persist thread");
|
||||
let before = runtime.get_thread(thread_id).await.expect("read metadata");
|
||||
let pool = store
|
||||
.config
|
||||
.sqlite
|
||||
.open_read_write_pool(&store.config.sqlite.state_db_path())
|
||||
.await
|
||||
.expect("open SQL observer");
|
||||
sqlx::query("CREATE TRIGGER reject_memory_mode BEFORE UPDATE OF memory_mode ON threads BEGIN SELECT RAISE(ABORT, 'memory mode rejected'); END")
|
||||
.execute(&pool).await.expect("reject memory preference update");
|
||||
let patch = ThreadMetadataPatch {
|
||||
model: Some("changed-model".to_string()),
|
||||
memory_mode: Some(ThreadMemoryMode::Disabled),
|
||||
..Default::default()
|
||||
};
|
||||
live_thread
|
||||
.update_metadata(patch.clone(), /*include_archived*/ false)
|
||||
.await
|
||||
.expect_err("reject the entire patch");
|
||||
assert_eq!(
|
||||
runtime.get_thread(thread_id).await.expect("read metadata"),
|
||||
before
|
||||
);
|
||||
|
||||
sqlx::query("DROP TRIGGER reject_memory_mode")
|
||||
.execute(&pool)
|
||||
.await
|
||||
.expect("allow update");
|
||||
live_thread
|
||||
.update_metadata(patch, /*include_archived*/ false)
|
||||
.await
|
||||
.expect("retry patch");
|
||||
let metadata = runtime
|
||||
.get_thread(thread_id)
|
||||
.await
|
||||
.expect("read metadata")
|
||||
.expect("thread");
|
||||
assert_eq!(
|
||||
(
|
||||
metadata.model,
|
||||
runtime
|
||||
.get_thread_memory_mode(thread_id)
|
||||
.await
|
||||
.expect("memory mode")
|
||||
),
|
||||
(
|
||||
Some("changed-model".to_string()),
|
||||
Some("disabled".to_string())
|
||||
)
|
||||
);
|
||||
live_thread.shutdown().await.expect("shutdown thread");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn naming_empty_paginated_thread_materializes_rollout() {
|
||||
let (_home, store, runtime) = store_with_runtime().await;
|
||||
let thread_id = ThreadId::new();
|
||||
let mut params = create_thread_params(thread_id);
|
||||
params.history_mode = ThreadHistoryMode::Paginated;
|
||||
let live_thread = LiveThread::create(store.clone(), params)
|
||||
.await
|
||||
.expect("create live thread");
|
||||
let rollout_path = store
|
||||
.live_rollout_path(thread_id)
|
||||
.await
|
||||
.expect("live rollout path");
|
||||
assert!(!rollout_path.exists());
|
||||
|
||||
let named = live_thread
|
||||
.update_metadata(
|
||||
ThreadMetadataPatch {
|
||||
name: Some(Some("Scheduled task".to_string())),
|
||||
memory_mode: Some(ThreadMemoryMode::Disabled),
|
||||
..Default::default()
|
||||
},
|
||||
/*include_archived*/ false,
|
||||
)
|
||||
.await
|
||||
.expect("name empty thread");
|
||||
|
||||
assert!(rollout_path.exists());
|
||||
assert_eq!(named.name.as_deref(), Some("Scheduled task"));
|
||||
assert_eq!(named.history_mode, ThreadHistoryMode::Paginated);
|
||||
assert_eq!(
|
||||
runtime
|
||||
.get_thread_memory_mode(thread_id)
|
||||
.await
|
||||
.expect("read memory mode")
|
||||
.as_deref(),
|
||||
Some("disabled")
|
||||
);
|
||||
live_thread.shutdown().await.expect("shutdown named thread");
|
||||
let stored = store
|
||||
.read_thread(ReadThreadParams {
|
||||
thread_id,
|
||||
include_archived: false,
|
||||
include_history: false,
|
||||
})
|
||||
.await
|
||||
.expect("read durable empty thread");
|
||||
assert_eq!(stored.thread_id, thread_id);
|
||||
assert_eq!(stored.name, named.name);
|
||||
assert_eq!(stored.history_mode, ThreadHistoryMode::Paginated);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn naming_empty_paginated_thread_propagates_rollout_persistence_failure() {
|
||||
let (_home, store, runtime) = store_with_runtime().await;
|
||||
let thread_id = ThreadId::new();
|
||||
let mut params = create_thread_params(thread_id);
|
||||
params.history_mode = ThreadHistoryMode::Paginated;
|
||||
let live_thread = LiveThread::create(store.clone(), params)
|
||||
.await
|
||||
.expect("create live thread");
|
||||
let rollout_path = store
|
||||
.live_rollout_path(thread_id)
|
||||
.await
|
||||
.expect("live rollout path");
|
||||
std::fs::create_dir_all(&rollout_path).expect("block rollout file creation");
|
||||
|
||||
live_thread
|
||||
.update_metadata(
|
||||
ThreadMetadataPatch {
|
||||
name: Some(Some("Unpersistable task".to_string())),
|
||||
..Default::default()
|
||||
},
|
||||
/*include_archived*/ false,
|
||||
)
|
||||
.await
|
||||
.expect_err("naming must fail when the thread cannot be persisted");
|
||||
assert_eq!(
|
||||
runtime
|
||||
.get_thread(thread_id)
|
||||
.await
|
||||
.expect("read thread metadata")
|
||||
.and_then(|metadata| metadata.name),
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn pending_thread_metadata_is_consumed_by_first_metadata_update() {
|
||||
let (_home, store, runtime) = store_with_runtime().await;
|
||||
let thread_id = ThreadId::new();
|
||||
let pending_patch = staged_model_patch();
|
||||
|
||||
store
|
||||
.stage_pending_thread_metadata(thread_id, pending_patch.clone())
|
||||
.await
|
||||
.expect("stage pending metadata");
|
||||
let live_thread = LiveThread::create(store.clone(), create_thread_params(thread_id))
|
||||
.await
|
||||
.expect("create live thread");
|
||||
live_thread
|
||||
.append_items(&[user_message_item("materialize pending metadata")])
|
||||
.await
|
||||
.expect("append observed item");
|
||||
|
||||
let metadata = runtime
|
||||
.get_thread(thread_id)
|
||||
.await
|
||||
.expect("sqlite metadata read")
|
||||
.expect("sqlite metadata");
|
||||
assert_eq!(metadata.model.as_deref(), Some("staged-model"));
|
||||
assert_eq!(metadata.model_provider, "test-provider");
|
||||
assert_eq!(metadata.source, "exec");
|
||||
assert_eq!(
|
||||
metadata.cwd.canonicalize().expect("canonical metadata cwd"),
|
||||
std::env::current_dir()
|
||||
.expect("current directory")
|
||||
.canonicalize()
|
||||
.expect("canonical current directory")
|
||||
);
|
||||
assert_pending_metadata_consumed(&store, thread_id).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn pending_rollout_compatible_metadata_does_not_deadlock() {
|
||||
let (_home, store, runtime) = store_with_runtime().await;
|
||||
let thread_id = ThreadId::new();
|
||||
|
||||
store
|
||||
.stage_pending_thread_metadata(
|
||||
thread_id,
|
||||
ThreadMetadataPatch {
|
||||
name: Some(Some("staged-name".to_string())),
|
||||
model_provider: Some("staged-provider".to_string()),
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect("stage pending metadata");
|
||||
let live_thread = LiveThread::create(store.clone(), create_thread_params(thread_id))
|
||||
.await
|
||||
.expect("create live thread");
|
||||
tokio::time::timeout(
|
||||
Duration::from_secs(5),
|
||||
live_thread.update_metadata(
|
||||
ThreadMetadataPatch {
|
||||
model: Some("updated-model".to_string()),
|
||||
..Default::default()
|
||||
},
|
||||
/*include_archived*/ false,
|
||||
),
|
||||
)
|
||||
.await
|
||||
.expect("pending metadata update should not deadlock")
|
||||
.expect("update metadata before rollout materialization");
|
||||
|
||||
let metadata = runtime
|
||||
.get_thread(thread_id)
|
||||
.await
|
||||
.expect("sqlite metadata read")
|
||||
.expect("sqlite metadata");
|
||||
assert_eq!(metadata.title, "staged-name");
|
||||
assert_eq!(metadata.model_provider, "test-provider");
|
||||
assert_eq!(metadata.model.as_deref(), Some("updated-model"));
|
||||
assert_pending_metadata_consumed(&store, thread_id).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn pending_rollout_compatible_metadata_is_written_with_observed_update() {
|
||||
let (_home, store, _runtime) = store_with_runtime().await;
|
||||
let thread_id = ThreadId::new();
|
||||
|
||||
store
|
||||
.stage_pending_thread_metadata(
|
||||
thread_id,
|
||||
ThreadMetadataPatch {
|
||||
memory_mode: Some(ThreadMemoryMode::Disabled),
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect("stage pending metadata");
|
||||
let _live_thread = LiveThread::create(store.clone(), create_thread_params(thread_id))
|
||||
.await
|
||||
.expect("create live thread");
|
||||
store
|
||||
.update_thread_metadata(UpdateThreadMetadataParams {
|
||||
thread_id,
|
||||
patch: ThreadMetadataPatch {
|
||||
model: Some("observed-model".to_string()),
|
||||
..Default::default()
|
||||
},
|
||||
include_archived: false,
|
||||
})
|
||||
.await
|
||||
.expect("apply observed metadata");
|
||||
|
||||
let rollout_path = store
|
||||
.live_rollout_path(thread_id)
|
||||
.await
|
||||
.expect("rollout path");
|
||||
let (items, _, _) = RolloutRecorder::load_rollout_items(rollout_path.as_path())
|
||||
.await
|
||||
.expect("load durable rollout");
|
||||
let memory_mode = items.iter().rev().find_map(|item| match item {
|
||||
RolloutItem::SessionMeta(session_meta) => session_meta.meta.memory_mode.as_deref(),
|
||||
_ => None,
|
||||
});
|
||||
|
||||
assert_eq!(memory_mode, Some("disabled"));
|
||||
assert_pending_metadata_consumed(&store, thread_id).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn deferred_reads_preserve_creation_metadata_and_updates() {
|
||||
for history_mode in [ThreadHistoryMode::Legacy, ThreadHistoryMode::Paginated] {
|
||||
let (_home, store, runtime) = store_with_runtime().await;
|
||||
let thread_id = ThreadId::new();
|
||||
let mut params = create_thread_params(thread_id);
|
||||
params.history_mode = history_mode;
|
||||
params.forked_from_id = Some(ThreadId::new());
|
||||
params.parent_thread_id = Some(ThreadId::new());
|
||||
let live_thread = LiveThread::create(store.clone(), params.clone())
|
||||
.await
|
||||
.expect("create live thread");
|
||||
let rollout_path = store
|
||||
.live_rollout_path(thread_id)
|
||||
.await
|
||||
.expect("live rollout path");
|
||||
let initial = live_thread
|
||||
.read_thread(
|
||||
/*include_archived*/ false, /*include_history*/ false,
|
||||
)
|
||||
.await
|
||||
.expect_err("untouched threads still have no stored record");
|
||||
assert!(matches!(
|
||||
initial,
|
||||
ThreadStoreError::InvalidRequest { message }
|
||||
if message == format!("no rollout found for thread id {thread_id}")
|
||||
));
|
||||
assert!(!rollout_path.exists());
|
||||
assert_eq!(
|
||||
runtime.get_thread(thread_id).await.expect("read index"),
|
||||
None
|
||||
);
|
||||
|
||||
let updated = live_thread
|
||||
.update_metadata(
|
||||
ThreadMetadataPatch {
|
||||
daybreak_enabled: Some(true),
|
||||
..Default::default()
|
||||
},
|
||||
/*include_archived*/ false,
|
||||
)
|
||||
.await
|
||||
.expect("update metadata without materializing history");
|
||||
let read = live_thread
|
||||
.read_thread(
|
||||
/*include_archived*/ false, /*include_history*/ false,
|
||||
)
|
||||
.await
|
||||
.expect("read updated metadata");
|
||||
assert_eq!(
|
||||
serde_json::to_value(read).expect("serialize metadata read"),
|
||||
serde_json::to_value(&updated).expect("serialize update result")
|
||||
);
|
||||
assert_eq!(
|
||||
(
|
||||
updated.forked_from_id,
|
||||
updated.parent_thread_id,
|
||||
updated.originator.clone(),
|
||||
updated.history_mode,
|
||||
updated.daybreak_enabled,
|
||||
),
|
||||
(
|
||||
params.forked_from_id,
|
||||
params.parent_thread_id,
|
||||
Some(params.originator),
|
||||
history_mode,
|
||||
Some(true),
|
||||
)
|
||||
);
|
||||
assert!(!rollout_path.exists());
|
||||
|
||||
live_thread
|
||||
.persist(PersistContext::Standard)
|
||||
.await
|
||||
.expect("persist history");
|
||||
live_thread.shutdown().await.expect("shutdown writer");
|
||||
let durable = store
|
||||
.read_thread(ReadThreadParams {
|
||||
thread_id,
|
||||
include_archived: false,
|
||||
include_history: false,
|
||||
})
|
||||
.await
|
||||
.expect("read durable metadata");
|
||||
assert_eq!(
|
||||
serde_json::to_value(durable).expect("serialize durable metadata"),
|
||||
serde_json::to_value(updated).expect("serialize initial metadata")
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn idle_shutdown_clears_pending_thread_metadata_without_materializing() {
|
||||
let (_home, store, runtime) = store_with_runtime().await;
|
||||
let thread_id = ThreadId::new();
|
||||
|
||||
store
|
||||
.stage_pending_thread_metadata(thread_id, staged_model_patch())
|
||||
.await
|
||||
.expect("stage pending metadata");
|
||||
let live_thread = LiveThread::create(store.clone(), create_thread_params(thread_id))
|
||||
.await
|
||||
.expect("create live thread");
|
||||
let read_error = live_thread
|
||||
.read_thread(
|
||||
/*include_archived*/ false, /*include_history*/ false,
|
||||
)
|
||||
.await
|
||||
.expect_err("untouched threads still have no stored record");
|
||||
assert!(matches!(
|
||||
read_error,
|
||||
ThreadStoreError::InvalidRequest { message }
|
||||
if message == format!("no rollout found for thread id {thread_id}")
|
||||
));
|
||||
assert!(
|
||||
!store
|
||||
.live_rollout_path(thread_id)
|
||||
.await
|
||||
.expect("live rollout path")
|
||||
.exists()
|
||||
);
|
||||
live_thread.shutdown().await.expect("shutdown idle thread");
|
||||
|
||||
assert_eq!(
|
||||
runtime
|
||||
.get_thread(thread_id)
|
||||
.await
|
||||
.expect("sqlite metadata read"),
|
||||
None
|
||||
);
|
||||
assert_pending_metadata_consumed(&store, thread_id).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn discarding_live_thread_clears_pending_metadata() {
|
||||
let (_home, store, _runtime) = store_with_runtime().await;
|
||||
let thread_id = ThreadId::new();
|
||||
|
||||
store
|
||||
.stage_pending_thread_metadata(thread_id, staged_model_patch())
|
||||
.await
|
||||
.expect("stage pending metadata");
|
||||
let live_thread = LiveThread::create(store.clone(), create_thread_params(thread_id))
|
||||
.await
|
||||
.expect("create live thread");
|
||||
live_thread.discard().await.expect("discard live thread");
|
||||
|
||||
assert_pending_metadata_consumed(&store, thread_id).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn pending_thread_metadata_requires_state_db() {
|
||||
let home = TempDir::new().expect("temp dir");
|
||||
let store = LocalThreadStore::new(test_config(home.path()), /*state_db*/ None);
|
||||
|
||||
let err = store
|
||||
.stage_pending_thread_metadata(ThreadId::new(), staged_model_patch())
|
||||
.await
|
||||
.expect_err("reject pending metadata without state db");
|
||||
assert!(matches!(
|
||||
err,
|
||||
ThreadStoreError::InvalidRequest { message }
|
||||
if message == "pending thread metadata requires a state db"
|
||||
));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn pending_thread_metadata_rejects_rollout_path() {
|
||||
let (home, store, _runtime) = store_with_runtime().await;
|
||||
|
||||
let err = store
|
||||
.stage_pending_thread_metadata(
|
||||
ThreadId::new(),
|
||||
ThreadMetadataPatch {
|
||||
rollout_path: Some(home.path().join("wrong-rollout.jsonl")),
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect_err("reject host-owned rollout path");
|
||||
assert!(matches!(
|
||||
err,
|
||||
ThreadStoreError::InvalidRequest { message }
|
||||
if message == "pending thread metadata cannot set rollout_path"
|
||||
));
|
||||
}
|
||||
|
||||
async fn store_with_runtime() -> (
|
||||
TempDir,
|
||||
Arc<LocalThreadStore>,
|
||||
Arc<codex_state::StateRuntime>,
|
||||
) {
|
||||
let home = TempDir::new().expect("temp dir");
|
||||
let config = test_config(home.path());
|
||||
let runtime = codex_state::StateRuntime::init(
|
||||
config.sqlite.clone(),
|
||||
config.default_model_provider_id.clone(),
|
||||
)
|
||||
.await
|
||||
.expect("state db should initialize");
|
||||
let store = Arc::new(LocalThreadStore::new(config, Some(runtime.clone())));
|
||||
(home, store, runtime)
|
||||
}
|
||||
|
||||
async fn assert_pending_metadata_consumed(store: &LocalThreadStore, thread_id: ThreadId) {
|
||||
store
|
||||
.stage_pending_thread_metadata(thread_id, staged_model_patch())
|
||||
.await
|
||||
.expect("restage metadata after consumption");
|
||||
store
|
||||
.remove_pending_thread_metadata(thread_id)
|
||||
.await
|
||||
.expect("remove restaged metadata");
|
||||
}
|
||||
|
||||
fn staged_model_patch() -> ThreadMetadataPatch {
|
||||
ThreadMetadataPatch {
|
||||
model: Some("staged-model".to_string()),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn create_thread_params(thread_id: ThreadId) -> CreateThreadParams {
|
||||
CreateThreadParams {
|
||||
attached_thread: false,
|
||||
creator_user_id: None,
|
||||
creator_account_id: None,
|
||||
session_id: thread_id.into(),
|
||||
thread_id,
|
||||
extra_config: None,
|
||||
forked_from_id: None,
|
||||
parent_thread_id: None,
|
||||
source: SessionSource::Exec,
|
||||
thread_source: None,
|
||||
originator: "test_originator".to_string(),
|
||||
base_instructions: BaseInstructions::default(),
|
||||
dynamic_tools: Vec::new(),
|
||||
selected_capability_roots: Vec::new(),
|
||||
multi_agent_version: None,
|
||||
history_mode: ThreadHistoryMode::Legacy,
|
||||
history_base: None,
|
||||
subagent_history_start_ordinal: None,
|
||||
initial_window_id: codex_protocol::ContextWindowId::new_uuid_v7().to_string(),
|
||||
runtime_workspace_roots: None,
|
||||
metadata: ThreadPersistenceMetadata {
|
||||
cwd: Some(std::env::current_dir().expect("cwd")),
|
||||
model_provider: "test-provider".to_string(),
|
||||
memory_mode: ThreadMemoryMode::Enabled,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn user_message_item(message: &str) -> RolloutItem {
|
||||
RolloutItem::EventMsg(EventMsg::UserMessage(UserMessageEvent {
|
||||
client_id: None,
|
||||
message: message.to_string(),
|
||||
images: None,
|
||||
local_images: Vec::new(),
|
||||
text_elements: Vec::new(),
|
||||
..Default::default()
|
||||
}))
|
||||
}
|
||||
192
codex-rs/thread-store/src/local/projects.rs
Normal file
192
codex-rs/thread-store/src/local/projects.rs
Normal file
@@ -0,0 +1,192 @@
|
||||
use super::LocalThreadStore;
|
||||
use crate::CreateProjectParams;
|
||||
use crate::CreatedProject;
|
||||
use crate::DeletedProject;
|
||||
use crate::ListProjectsParams;
|
||||
use crate::MoveProjectParams;
|
||||
use crate::ProjectMoveOutcome;
|
||||
use crate::SortDirection;
|
||||
use crate::StoredProject;
|
||||
use crate::StoredProjectRoot;
|
||||
use crate::StoredProjectsPage;
|
||||
use crate::ThreadStoreError;
|
||||
use crate::ThreadStoreResult;
|
||||
use crate::UpdateProjectParams;
|
||||
use crate::UpdatedProject;
|
||||
|
||||
pub(super) async fn list_projects(
|
||||
store: &LocalThreadStore,
|
||||
params: ListProjectsParams,
|
||||
) -> ThreadStoreResult<StoredProjectsPage> {
|
||||
let state = state(store)?;
|
||||
let has_cursor = params.cursor.is_some();
|
||||
let page = state
|
||||
.list_projects(
|
||||
params.cursor.as_deref(),
|
||||
params.limit,
|
||||
params.sort_key,
|
||||
match params.sort_direction {
|
||||
SortDirection::Asc => codex_state::SortDirection::Asc,
|
||||
SortDirection::Desc => codex_state::SortDirection::Desc,
|
||||
},
|
||||
)
|
||||
.await
|
||||
.map_err(|error| {
|
||||
if has_cursor && error.to_string().starts_with("invalid project cursor:") {
|
||||
ThreadStoreError::InvalidRequest {
|
||||
message: error.to_string(),
|
||||
}
|
||||
} else {
|
||||
internal(error)
|
||||
}
|
||||
})?;
|
||||
Ok(StoredProjectsPage {
|
||||
projects: page.projects.into_iter().map(stored_project).collect(),
|
||||
next_cursor: page.next_cursor,
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) async fn read_project(
|
||||
store: &LocalThreadStore,
|
||||
project_id: String,
|
||||
) -> ThreadStoreResult<Option<StoredProject>> {
|
||||
state(store)?
|
||||
.get_project(&project_id)
|
||||
.await
|
||||
.map(|project| project.map(stored_project))
|
||||
.map_err(internal)
|
||||
}
|
||||
|
||||
pub(super) async fn create_project(
|
||||
store: &LocalThreadStore,
|
||||
params: CreateProjectParams,
|
||||
) -> ThreadStoreResult<CreatedProject> {
|
||||
state(store)?
|
||||
.create_project(
|
||||
params.name,
|
||||
params.roots.into_iter().map(state_root).collect(),
|
||||
params.metadata,
|
||||
¶ms.thread_ids,
|
||||
¶ms.idempotency_key,
|
||||
)
|
||||
.await
|
||||
.map(|created| CreatedProject {
|
||||
project: stored_project(created.project),
|
||||
created: created.created,
|
||||
})
|
||||
.map_err(project_idempotency_error)
|
||||
}
|
||||
|
||||
pub(super) async fn update_project(
|
||||
store: &LocalThreadStore,
|
||||
params: UpdateProjectParams,
|
||||
) -> ThreadStoreResult<Option<UpdatedProject>> {
|
||||
state(store)?
|
||||
.update_project(
|
||||
¶ms.project_id,
|
||||
params.name,
|
||||
params
|
||||
.roots
|
||||
.map(|roots| roots.into_iter().map(state_root).collect()),
|
||||
params.metadata,
|
||||
)
|
||||
.await
|
||||
.map(|result| {
|
||||
result.map(|(project, changed)| UpdatedProject {
|
||||
project: stored_project(project),
|
||||
changed,
|
||||
})
|
||||
})
|
||||
.map_err(internal)
|
||||
}
|
||||
|
||||
pub(super) async fn move_project(
|
||||
store: &LocalThreadStore,
|
||||
params: MoveProjectParams,
|
||||
) -> ThreadStoreResult<Option<ProjectMoveOutcome>> {
|
||||
state(store)?
|
||||
.move_project(¶ms.project_id, params.before_project_id.as_deref())
|
||||
.await
|
||||
.map(|result| {
|
||||
result.map(|changed| {
|
||||
if changed {
|
||||
ProjectMoveOutcome::Moved
|
||||
} else {
|
||||
ProjectMoveOutcome::Unchanged
|
||||
}
|
||||
})
|
||||
})
|
||||
.map_err(|error| {
|
||||
let message = error.to_string();
|
||||
if message.starts_with("before project ")
|
||||
|| message.starts_with("project ") && message.contains("cannot be moved")
|
||||
{
|
||||
ThreadStoreError::InvalidRequest { message }
|
||||
} else {
|
||||
internal(message)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) async fn delete_project(
|
||||
store: &LocalThreadStore,
|
||||
project_id: String,
|
||||
) -> ThreadStoreResult<Option<DeletedProject>> {
|
||||
state(store)?
|
||||
.delete_project(&project_id)
|
||||
.await
|
||||
.map(|result| {
|
||||
result.map(
|
||||
|(affected_active_thread_ids, affected_archived_thread_ids)| DeletedProject {
|
||||
affected_active_thread_ids,
|
||||
affected_archived_thread_ids,
|
||||
},
|
||||
)
|
||||
})
|
||||
.map_err(internal)
|
||||
}
|
||||
|
||||
fn state(store: &LocalThreadStore) -> ThreadStoreResult<&codex_rollout::StateDbHandle> {
|
||||
store
|
||||
.state_db
|
||||
.as_ref()
|
||||
.ok_or(ThreadStoreError::Unsupported {
|
||||
operation: "projects",
|
||||
})
|
||||
}
|
||||
|
||||
fn internal(error: impl std::fmt::Display) -> ThreadStoreError {
|
||||
ThreadStoreError::Internal {
|
||||
message: error.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn project_idempotency_error(error: impl std::fmt::Display) -> ThreadStoreError {
|
||||
let message = error.to_string();
|
||||
if message.starts_with("idempotency key refers to deleted project:") {
|
||||
ThreadStoreError::InvalidRequest { message }
|
||||
} else {
|
||||
internal(message)
|
||||
}
|
||||
}
|
||||
|
||||
fn state_root(root: StoredProjectRoot) -> codex_state::ProjectRoot {
|
||||
codex_state::ProjectRoot { path: root.path }
|
||||
}
|
||||
|
||||
fn stored_project(project: codex_state::Project) -> StoredProject {
|
||||
StoredProject {
|
||||
id: project.id,
|
||||
name: project.name,
|
||||
roots: project
|
||||
.roots
|
||||
.into_iter()
|
||||
.map(|root| StoredProjectRoot { path: root.path })
|
||||
.collect(),
|
||||
metadata: project.metadata,
|
||||
position: project.position,
|
||||
created_at_ms: project.created_at_ms,
|
||||
updated_at_ms: project.updated_at_ms,
|
||||
recency_at_ms: project.recency_at_ms,
|
||||
}
|
||||
}
|
||||
1711
codex-rs/thread-store/src/local/read_thread.rs
Normal file
1711
codex-rs/thread-store/src/local/read_thread.rs
Normal file
File diff suppressed because it is too large
Load Diff
89
codex-rs/thread-store/src/local/read_thread_tests.rs
Normal file
89
codex-rs/thread-store/src/local/read_thread_tests.rs
Normal file
@@ -0,0 +1,89 @@
|
||||
//! Regression coverage for metadata reads without SQLite.
|
||||
|
||||
use std::fs;
|
||||
use std::fs::FileTimes;
|
||||
|
||||
use chrono::DateTime;
|
||||
use chrono::Utc;
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::protocol::SessionMeta;
|
||||
use codex_protocol::protocol::SessionMetaLine;
|
||||
use codex_protocol::protocol::ThreadSource;
|
||||
use codex_rollout::RolloutItem;
|
||||
use codex_rollout::RolloutLine;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tempfile::TempDir;
|
||||
|
||||
use super::LocalThreadStore;
|
||||
use super::test_support::test_config;
|
||||
use crate::ReadThreadParams;
|
||||
use crate::ThreadStore;
|
||||
|
||||
#[tokio::test]
|
||||
async fn empty_archived_reads_without_sqlite_preserve_source_and_file_time()
|
||||
-> Result<(), Box<dyn std::error::Error>> {
|
||||
let home = TempDir::new()?;
|
||||
let store = LocalThreadStore::new(test_config(home.path()), /*state_db*/ None);
|
||||
let thread_id = ThreadId::new();
|
||||
let timestamp = "2026-07-09T00:00:00Z";
|
||||
let created_at = DateTime::parse_from_rfc3339(timestamp)?.with_timezone(&Utc);
|
||||
let updated_at = DateTime::parse_from_rfc3339("2026-07-10T00:00:00Z")?.with_timezone(&Utc);
|
||||
let directory = home.path().join(codex_rollout::ARCHIVED_SESSIONS_SUBDIR);
|
||||
fs::create_dir_all(&directory)?;
|
||||
let path = directory.join(format!("rollout-2026-07-09T00-00-00-{thread_id}.jsonl"));
|
||||
let line = RolloutLine {
|
||||
timestamp: timestamp.to_string(),
|
||||
ordinal: None,
|
||||
item: RolloutItem::SessionMeta(Box::new(SessionMetaLine {
|
||||
meta: SessionMeta {
|
||||
id: thread_id,
|
||||
session_id: thread_id.into(),
|
||||
timestamp: timestamp.to_string(),
|
||||
thread_source: Some(ThreadSource::User),
|
||||
..SessionMeta::default()
|
||||
},
|
||||
git: None,
|
||||
})),
|
||||
};
|
||||
fs::write(&path, format!("{}\n", serde_json::to_string(&line)?))?;
|
||||
fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.open(&path)?
|
||||
.set_times(FileTimes::new().set_modified(updated_at.into()))?;
|
||||
|
||||
let by_id = store
|
||||
.read_thread(ReadThreadParams {
|
||||
thread_id,
|
||||
include_archived: true,
|
||||
include_history: false,
|
||||
})
|
||||
.await?;
|
||||
let by_path = store
|
||||
.read_thread_by_rollout_path(
|
||||
path, /*include_archived*/ true, /*include_history*/ false,
|
||||
)
|
||||
.await?;
|
||||
for thread in [by_id, by_path] {
|
||||
assert_eq!(
|
||||
(
|
||||
thread.thread_id,
|
||||
thread.thread_source,
|
||||
thread.preview,
|
||||
thread.created_at,
|
||||
thread.updated_at,
|
||||
thread.recency_at,
|
||||
thread.archived_at
|
||||
),
|
||||
(
|
||||
thread_id,
|
||||
Some(ThreadSource::User),
|
||||
String::new(),
|
||||
created_at,
|
||||
updated_at,
|
||||
updated_at,
|
||||
Some(updated_at)
|
||||
),
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
219
codex-rs/thread-store/src/local/revert_thread.rs
Normal file
219
codex-rs/thread-store/src/local/revert_thread.rs
Normal file
@@ -0,0 +1,219 @@
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::protocol::ThreadHistoryMode;
|
||||
use codex_rollout::RolloutConfig;
|
||||
use codex_rollout::RolloutRecorder;
|
||||
use codex_rollout::RolloutRecorderParams;
|
||||
|
||||
use super::LocalThreadStore;
|
||||
use super::paginated_fork;
|
||||
use super::thread_rollout_resolver;
|
||||
use crate::ForkBoundary;
|
||||
use crate::RevertThreadParams;
|
||||
use crate::ThreadStoreError;
|
||||
use crate::ThreadStoreResult;
|
||||
|
||||
/// Revert an unloaded paginated thread by creating a new immutable rollout file.
|
||||
///
|
||||
/// Old rollouts stay intact. The new file references the retained prefix, and the only mutable
|
||||
/// cutover is the existing SQLite rollout-path pointer for the thread.
|
||||
pub(super) async fn revert(
|
||||
store: &LocalThreadStore,
|
||||
params: RevertThreadParams,
|
||||
) -> ThreadStoreResult<()> {
|
||||
let RevertThreadParams {
|
||||
thread_id,
|
||||
before_turn_id,
|
||||
multi_agent_version,
|
||||
} = params;
|
||||
let state_db = store
|
||||
.state_db()
|
||||
.await
|
||||
.ok_or(ThreadStoreError::Unsupported {
|
||||
operation: "revert_thread",
|
||||
})?;
|
||||
let _lifecycle_guard = store.live_writer_locks.lock_lifecycle(thread_id).await;
|
||||
let _live_writer_guard = store.live_writer_locks.lock(thread_id).await;
|
||||
store.ensure_live_recorder_absent(thread_id).await?;
|
||||
let writer_lock = store.acquire_writer_lock(thread_id)?;
|
||||
|
||||
// Resolution may return a compressed sibling. Keep SQLite's exact stored path for the CAS.
|
||||
let stored_metadata = state_db
|
||||
.get_thread(thread_id)
|
||||
.await
|
||||
.map_err(|err| ThreadStoreError::Internal {
|
||||
message: format!("failed to read thread metadata for {thread_id}: {err}"),
|
||||
})?
|
||||
.ok_or(ThreadStoreError::ThreadNotFound { thread_id })?;
|
||||
let expected_sqlite_path = stored_metadata.rollout_path;
|
||||
let current_rollout = thread_rollout_resolver::resolve_current(store, thread_id)
|
||||
.await?
|
||||
.ok_or(ThreadStoreError::ThreadNotFound { thread_id })?;
|
||||
let source_path = current_rollout.path;
|
||||
let mut source_meta = codex_rollout::read_session_meta_line(source_path.as_path())
|
||||
.await
|
||||
.map_err(|err| ThreadStoreError::Internal {
|
||||
message: format!(
|
||||
"failed to read current paginated rollout {}: {err}",
|
||||
source_path.display()
|
||||
),
|
||||
})?
|
||||
.meta;
|
||||
if source_meta.id != current_rollout.thread_id {
|
||||
return Err(ThreadStoreError::InvalidRequest {
|
||||
message: format!("current rollout for {thread_id} belongs to another thread"),
|
||||
});
|
||||
}
|
||||
if source_meta.history_mode != ThreadHistoryMode::Paginated {
|
||||
return Err(ThreadStoreError::InvalidRequest {
|
||||
message: format!("thread {thread_id} does not use paginated history"),
|
||||
});
|
||||
}
|
||||
|
||||
// Older binaries can omit creator fields when replacing a rollout during revert.
|
||||
source_meta.creator_user_id = source_meta
|
||||
.creator_user_id
|
||||
.or(stored_metadata.creator_user_id);
|
||||
source_meta.creator_account_id = source_meta
|
||||
.creator_account_id
|
||||
.or(stored_metadata.creator_account_id);
|
||||
|
||||
// Preserve old-reader compatibility when introducing the first reference to a standalone
|
||||
// source. Already-shared ancestors stay read-only; their offsets address decoded JSONL bytes.
|
||||
let lineage = store
|
||||
.resolve_rollout_lineage(thread_id, /*initial_path*/ None)
|
||||
.await?;
|
||||
let boundary = &ForkBoundary::BeforeTurn(before_turn_id);
|
||||
let standalone_rollout_id = source_meta
|
||||
.history_base
|
||||
.is_none()
|
||||
.then_some(current_rollout.rollout_id);
|
||||
let history_base = lineage
|
||||
.read_with_fallback(store, |mut lineage| async move {
|
||||
for segment in &mut lineage.segments {
|
||||
if Some(segment.rollout_id()) == standalone_rollout_id {
|
||||
segment.rollout_path = codex_rollout::materialize_rollout_for_reference(
|
||||
segment.rollout_path.as_path(),
|
||||
)
|
||||
.await
|
||||
.map_err(|err| ThreadStoreError::Internal {
|
||||
message: format!(
|
||||
"failed to materialize rollout {} for revert: {err}",
|
||||
segment.rollout_path.display()
|
||||
),
|
||||
})?;
|
||||
}
|
||||
super::thread_history_materialization::materialize_to_sqlite_with_reads(
|
||||
store,
|
||||
segment.rollout_id(),
|
||||
segment.rollout_path.as_path(),
|
||||
&lineage.reads,
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
paginated_fork::history_base_at_boundary(store, thread_id, boundary, &lineage).await
|
||||
})
|
||||
.await?;
|
||||
|
||||
let forked_from_ordinal_exclusive =
|
||||
codex_rollout::forked_from_ordinal_exclusive(&source_meta, Some(source_path.as_path()))
|
||||
.map(|cutoff| {
|
||||
// Reverting into inherited history can shrink, but never grow, the parent prefix.
|
||||
cutoff.min(history_base.map_or(0, |base| base.end_ordinal_exclusive))
|
||||
});
|
||||
|
||||
source_meta.multi_agent_version = multi_agent_version.or(source_meta.multi_agent_version);
|
||||
let rollout_id = ThreadId::new();
|
||||
let recorder = create_replacement_recorder(
|
||||
store,
|
||||
source_meta,
|
||||
rollout_id,
|
||||
history_base,
|
||||
forked_from_ordinal_exclusive,
|
||||
writer_lock,
|
||||
)
|
||||
.await?;
|
||||
let replacement_path = recorder.rollout_path().to_path_buf();
|
||||
recorder.persist().await.map_err(thread_store_io_error)?;
|
||||
recorder.shutdown().await.map_err(thread_store_io_error)?;
|
||||
|
||||
let replaced = state_db
|
||||
.replace_rollout_path_if_current(
|
||||
thread_id,
|
||||
expected_sqlite_path.as_path(),
|
||||
replacement_path.as_path(),
|
||||
)
|
||||
.await
|
||||
.map_err(|err| ThreadStoreError::Internal {
|
||||
message: format!("failed to switch thread {thread_id} to reverted rollout: {err}"),
|
||||
})?;
|
||||
if !replaced {
|
||||
let _ = tokio::fs::remove_file(replacement_path.as_path()).await;
|
||||
return Err(ThreadStoreError::Conflict {
|
||||
message: format!("thread {thread_id} changed while it was being reverted"),
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn create_replacement_recorder(
|
||||
store: &LocalThreadStore,
|
||||
source_meta: codex_rollout::SessionMeta,
|
||||
rollout_id: ThreadId,
|
||||
history_base: Option<codex_protocol::protocol::HistoryPosition>,
|
||||
forked_from_ordinal_exclusive: Option<u64>,
|
||||
writer_lock: super::WriterLockGuard,
|
||||
) -> ThreadStoreResult<RolloutRecorder> {
|
||||
let config = RolloutConfig {
|
||||
codex_home: store.config.codex_home.clone(),
|
||||
sqlite: store.config.sqlite.clone(),
|
||||
cwd: source_meta.cwd.clone(),
|
||||
model_provider_id: source_meta
|
||||
.model_provider
|
||||
.clone()
|
||||
.unwrap_or_else(|| store.config.default_model_provider_id.clone()),
|
||||
generate_memories: source_meta.memory_mode.as_deref() != Some("disabled"),
|
||||
};
|
||||
let mut params = RolloutRecorderParams::new(
|
||||
source_meta.id,
|
||||
source_meta.forked_from_id,
|
||||
source_meta.parent_thread_id,
|
||||
source_meta.source,
|
||||
source_meta.thread_source,
|
||||
source_meta.originator,
|
||||
source_meta.base_instructions.unwrap_or_default(),
|
||||
source_meta.dynamic_tools.unwrap_or_default(),
|
||||
)
|
||||
.with_creator(
|
||||
source_meta.creator_user_id,
|
||||
source_meta.creator_account_id,
|
||||
source_meta.account_scoped,
|
||||
)
|
||||
.with_session_id(source_meta.session_id)
|
||||
.with_attached_thread(source_meta.attached_thread)
|
||||
.with_rollout_id(rollout_id)
|
||||
.with_selected_capability_roots(source_meta.selected_capability_roots)
|
||||
.with_runtime_workspace_roots(source_meta.runtime_workspace_roots)
|
||||
.with_multi_agent_version(source_meta.multi_agent_version)
|
||||
.with_history_mode(ThreadHistoryMode::Paginated)
|
||||
.with_history_base(history_base)
|
||||
.with_forked_from_ordinal_exclusive(forked_from_ordinal_exclusive)
|
||||
.with_subagent_history_start_ordinal(source_meta.subagent_history_start_ordinal);
|
||||
if let Some(context_window) = source_meta.context_window {
|
||||
params = params.with_initial_window_id(context_window.window_id);
|
||||
}
|
||||
RolloutRecorder::new_with_writer_lock(&config, params, writer_lock)
|
||||
.await
|
||||
.map_err(|err| ThreadStoreError::Internal {
|
||||
message: format!("failed to create reverted rollout: {err}"),
|
||||
})
|
||||
}
|
||||
|
||||
fn thread_store_io_error(err: std::io::Error) -> ThreadStoreError {
|
||||
ThreadStoreError::Internal {
|
||||
message: err.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "revert_thread_tests.rs"]
|
||||
mod tests;
|
||||
431
codex-rs/thread-store/src/local/revert_thread_tests.rs
Normal file
431
codex-rs/thread-store/src/local/revert_thread_tests.rs
Normal file
@@ -0,0 +1,431 @@
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::models::BaseInstructions;
|
||||
use codex_protocol::protocol::EventMsg;
|
||||
use codex_protocol::protocol::MultiAgentVersion;
|
||||
use codex_protocol::protocol::SessionSource;
|
||||
use codex_protocol::protocol::ThreadHistoryMode;
|
||||
use codex_protocol::protocol::ThreadMemoryMode;
|
||||
use codex_protocol::protocol::TurnCompleteEvent;
|
||||
use codex_protocol::protocol::TurnStartedEvent;
|
||||
use codex_rollout::RolloutItem;
|
||||
use codex_utils_absolute_path::test_support::PathExt;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tempfile::TempDir;
|
||||
|
||||
use super::super::LocalThreadStore;
|
||||
use super::super::test_support::test_config;
|
||||
use crate::AppendThreadItemsParams;
|
||||
use crate::ArchiveThreadParams;
|
||||
use crate::CreateThreadParams;
|
||||
use crate::DeleteThreadParams;
|
||||
use crate::ListTurnsParams;
|
||||
use crate::LocalHistoryAccount;
|
||||
use crate::RevertThreadParams;
|
||||
use crate::SortDirection;
|
||||
use crate::StoredTurnItemsView;
|
||||
use crate::ThreadPersistenceMetadata;
|
||||
use crate::ThreadStore;
|
||||
|
||||
#[tokio::test]
|
||||
async fn revert_keeps_thread_id_and_hides_suffix_across_repeated_reverts() {
|
||||
let home = TempDir::new().expect("temp dir");
|
||||
let config = test_config(home.path());
|
||||
let state_db = codex_state::StateRuntime::init(
|
||||
config.sqlite.clone(),
|
||||
config.default_model_provider_id.clone(),
|
||||
)
|
||||
.await
|
||||
.expect("initialize state database");
|
||||
let store = LocalThreadStore::new(config, Some(state_db.clone()));
|
||||
let thread_id = ThreadId::new();
|
||||
create_paginated_thread(&store, thread_id).await;
|
||||
store
|
||||
.append_items(AppendThreadItemsParams {
|
||||
thread_id,
|
||||
items: vec![
|
||||
turn_started("turn-1"),
|
||||
turn_completed("turn-1"),
|
||||
turn_started("turn-2"),
|
||||
turn_completed("turn-2"),
|
||||
],
|
||||
})
|
||||
.await
|
||||
.expect("append turns");
|
||||
let original_path = store
|
||||
.live_rollout_path(thread_id)
|
||||
.await
|
||||
.expect("source rollout path");
|
||||
store
|
||||
.shutdown_thread(thread_id)
|
||||
.await
|
||||
.expect("close source writer");
|
||||
codex_rollout::state_db::reconcile_rollout(
|
||||
Some(state_db.as_ref()),
|
||||
original_path.as_path(),
|
||||
"test-provider",
|
||||
/*builder*/ None,
|
||||
&[],
|
||||
/*archived_only*/ Some(false),
|
||||
/*new_thread_memory_mode*/ None,
|
||||
)
|
||||
.await;
|
||||
compress_rollout(original_path.as_path());
|
||||
|
||||
store
|
||||
.revert_thread(RevertThreadParams {
|
||||
thread_id,
|
||||
before_turn_id: "turn-2".to_string(),
|
||||
multi_agent_version: None,
|
||||
})
|
||||
.await
|
||||
.expect("revert before second turn");
|
||||
let first_replacement_path = state_db
|
||||
.get_thread(thread_id)
|
||||
.await
|
||||
.expect("read metadata")
|
||||
.expect("thread metadata")
|
||||
.rollout_path;
|
||||
assert_ne!(first_replacement_path, original_path);
|
||||
assert_ne!(
|
||||
codex_rollout::rollout_id_from_path(first_replacement_path.as_path()),
|
||||
Some(thread_id)
|
||||
);
|
||||
let replacement_meta = codex_rollout::read_session_meta_line(first_replacement_path.as_path())
|
||||
.await
|
||||
.expect("read replacement metadata")
|
||||
.meta;
|
||||
assert_eq!(replacement_meta.id, thread_id);
|
||||
assert_eq!(
|
||||
(
|
||||
replacement_meta.account_scoped,
|
||||
replacement_meta.creator_user_id.as_deref(),
|
||||
replacement_meta.creator_account_id.as_deref()
|
||||
),
|
||||
(true, Some("creator-user"), Some("creator-account")),
|
||||
);
|
||||
assert_eq!(replacement_meta.memory_mode, None);
|
||||
assert_eq!(
|
||||
replacement_meta.runtime_workspace_roots,
|
||||
Some(vec![home.path().join("workspace")])
|
||||
);
|
||||
assert_eq!(turn_ids(&store, thread_id).await, vec!["turn-1"]);
|
||||
|
||||
// Simulate an older binary replacing the rollout without the creator fields it does not know.
|
||||
let rollout = tokio::fs::read_to_string(&first_replacement_path)
|
||||
.await
|
||||
.expect("read replacement rollout");
|
||||
let (meta_line, remaining_lines) = rollout.split_once('\n').expect("session metadata line");
|
||||
let mut meta_line: serde_json::Value = serde_json::from_str(meta_line).expect("parse metadata");
|
||||
let payload = meta_line["payload"]
|
||||
.as_object_mut()
|
||||
.expect("metadata payload");
|
||||
payload.remove("account_scoped");
|
||||
payload.remove("creator_user_id");
|
||||
payload.remove("creator_account_id");
|
||||
tokio::fs::write(
|
||||
&first_replacement_path,
|
||||
format!("{meta_line}\n{remaining_lines}"),
|
||||
)
|
||||
.await
|
||||
.expect("write legacy replacement rollout");
|
||||
|
||||
for (user, expected) in [("creator-user", true), ("other-user", false)] {
|
||||
let account = LocalHistoryAccount {
|
||||
user_id: Some(user.to_string()),
|
||||
account_id: Some("creator-account".to_string()),
|
||||
};
|
||||
assert_eq!(
|
||||
account
|
||||
.includes(
|
||||
home.path(),
|
||||
thread_id,
|
||||
Some(&first_replacement_path),
|
||||
&[thread_id],
|
||||
/*original_paths*/ &mut None,
|
||||
)
|
||||
.await,
|
||||
expected
|
||||
);
|
||||
}
|
||||
|
||||
store
|
||||
.revert_thread(RevertThreadParams {
|
||||
thread_id,
|
||||
before_turn_id: "turn-1".to_string(),
|
||||
multi_agent_version: None,
|
||||
})
|
||||
.await
|
||||
.expect("revert before first turn");
|
||||
assert_eq!(turn_ids(&store, thread_id).await, Vec::<String>::new());
|
||||
let stored = state_db
|
||||
.get_thread(thread_id)
|
||||
.await
|
||||
.expect("read metadata")
|
||||
.expect("thread metadata");
|
||||
let recovered = codex_rollout::read_session_meta_line(&stored.rollout_path)
|
||||
.await
|
||||
.expect("read recovered creator metadata")
|
||||
.meta;
|
||||
assert_eq!(
|
||||
(recovered.creator_user_id, recovered.creator_account_id),
|
||||
(
|
||||
Some("creator-user".to_string()),
|
||||
Some("creator-account".to_string())
|
||||
),
|
||||
);
|
||||
|
||||
store
|
||||
.archive_thread(ArchiveThreadParams { thread_id })
|
||||
.await
|
||||
.expect("archive reverted thread");
|
||||
assert!(
|
||||
rollout_paths_for_thread(home.path(), thread_id)
|
||||
.await
|
||||
.iter()
|
||||
.all(|path| path.starts_with(home.path().join("archived_sessions")))
|
||||
);
|
||||
store
|
||||
.unarchive_thread(ArchiveThreadParams { thread_id })
|
||||
.await
|
||||
.expect("unarchive reverted thread");
|
||||
let owned_rollout_paths = rollout_paths_for_thread(home.path(), thread_id).await;
|
||||
assert_eq!(owned_rollout_paths.len(), 3);
|
||||
assert!(
|
||||
owned_rollout_paths
|
||||
.iter()
|
||||
.all(|path| path.starts_with(home.path().join("sessions")))
|
||||
);
|
||||
|
||||
store
|
||||
.delete_thread(DeleteThreadParams { thread_id })
|
||||
.await
|
||||
.expect("delete reverted thread");
|
||||
for rollout_path in owned_rollout_paths {
|
||||
assert!(!rollout_path.exists());
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn revert_preserves_legacy_scope_and_resolved_multi_agent_version() {
|
||||
let home = TempDir::new().expect("temp dir");
|
||||
let config = test_config(home.path());
|
||||
let state_db = codex_state::StateRuntime::init(
|
||||
config.sqlite.clone(),
|
||||
config.default_model_provider_id.clone(),
|
||||
)
|
||||
.await
|
||||
.expect("initialize state database");
|
||||
let store = LocalThreadStore::new(config, Some(state_db.clone()));
|
||||
let other_account = LocalHistoryAccount {
|
||||
user_id: Some("other-user".to_string()),
|
||||
account_id: Some("other-account".to_string()),
|
||||
};
|
||||
let mut archived_threads = Vec::new();
|
||||
|
||||
for version in [
|
||||
MultiAgentVersion::V1,
|
||||
MultiAgentVersion::V2,
|
||||
MultiAgentVersion::Disabled,
|
||||
] {
|
||||
let thread_id = ThreadId::new();
|
||||
create_paginated_thread(&store, thread_id).await;
|
||||
store
|
||||
.append_items(AppendThreadItemsParams {
|
||||
thread_id,
|
||||
items: vec![
|
||||
turn_started("turn-1"),
|
||||
turn_completed("turn-1"),
|
||||
turn_started("turn-2"),
|
||||
turn_completed("turn-2"),
|
||||
],
|
||||
})
|
||||
.await
|
||||
.expect("append turns");
|
||||
let path = store
|
||||
.live_rollout_path(thread_id)
|
||||
.await
|
||||
.expect("source rollout path");
|
||||
store
|
||||
.shutdown_thread(thread_id)
|
||||
.await
|
||||
.expect("close source writer");
|
||||
let contents = tokio::fs::read_to_string(&path)
|
||||
.await
|
||||
.expect("read rollout");
|
||||
// Preserve indexed offsets while turning the fixture into pre-enforcement history.
|
||||
let marker = "\"account_scoped\":true,";
|
||||
tokio::fs::write(
|
||||
&path,
|
||||
contents.replacen(marker, &" ".repeat(marker.len()), 1),
|
||||
)
|
||||
.await
|
||||
.expect("write legacy rollout");
|
||||
codex_rollout::state_db::reconcile_rollout(
|
||||
Some(state_db.as_ref()),
|
||||
path.as_path(),
|
||||
"test-provider",
|
||||
/*builder*/ None,
|
||||
&[],
|
||||
/*archived_only*/ Some(false),
|
||||
/*new_thread_memory_mode*/ None,
|
||||
)
|
||||
.await;
|
||||
|
||||
// The second revert has no live version to supply and must keep the persisted one.
|
||||
for (before_turn_id, multi_agent_version) in [("turn-2", Some(version)), ("turn-1", None)] {
|
||||
store
|
||||
.revert_thread(RevertThreadParams {
|
||||
thread_id,
|
||||
before_turn_id: before_turn_id.to_string(),
|
||||
multi_agent_version,
|
||||
})
|
||||
.await
|
||||
.expect("revert thread");
|
||||
let path = state_db
|
||||
.get_thread(thread_id)
|
||||
.await
|
||||
.expect("read metadata")
|
||||
.expect("thread metadata")
|
||||
.rollout_path;
|
||||
let meta = codex_rollout::read_session_meta_line(&path)
|
||||
.await
|
||||
.expect("read replacement metadata");
|
||||
assert_eq!(
|
||||
(meta.meta.multi_agent_version, meta.meta.account_scoped),
|
||||
(Some(version), false)
|
||||
);
|
||||
assert!(
|
||||
other_account
|
||||
.includes(
|
||||
home.path(),
|
||||
thread_id,
|
||||
Some(&path),
|
||||
&[thread_id],
|
||||
/*original_paths*/ &mut None,
|
||||
)
|
||||
.await
|
||||
);
|
||||
}
|
||||
store
|
||||
.archive_thread(ArchiveThreadParams { thread_id })
|
||||
.await
|
||||
.expect("archive reverted legacy thread");
|
||||
let path = state_db
|
||||
.get_thread(thread_id)
|
||||
.await
|
||||
.expect("read archived metadata")
|
||||
.expect("archived thread")
|
||||
.rollout_path;
|
||||
archived_threads.push((thread_id, path));
|
||||
}
|
||||
let page_thread_ids: Vec<_> = archived_threads.iter().map(|(id, _)| *id).collect();
|
||||
let mut original_paths = None;
|
||||
for (thread_id, path) in archived_threads {
|
||||
assert!(
|
||||
other_account
|
||||
.includes(
|
||||
home.path(),
|
||||
thread_id,
|
||||
Some(&path),
|
||||
&page_thread_ids,
|
||||
&mut original_paths,
|
||||
)
|
||||
.await
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async fn rollout_paths_for_thread(
|
||||
home: &std::path::Path,
|
||||
thread_id: ThreadId,
|
||||
) -> Vec<std::path::PathBuf> {
|
||||
codex_rollout::RolloutReferenceIndex::scan(home)
|
||||
.await
|
||||
.expect("scan rollout references")
|
||||
.rollouts_for_thread(thread_id)
|
||||
.map(|(_, path)| path.to_path_buf())
|
||||
.collect()
|
||||
}
|
||||
|
||||
async fn create_paginated_thread(store: &LocalThreadStore, thread_id: ThreadId) {
|
||||
store
|
||||
.create_thread(CreateThreadParams {
|
||||
attached_thread: false,
|
||||
creator_user_id: Some("creator-user".to_string()),
|
||||
creator_account_id: Some("creator-account".to_string()),
|
||||
session_id: thread_id.into(),
|
||||
thread_id,
|
||||
extra_config: None,
|
||||
forked_from_id: None,
|
||||
parent_thread_id: None,
|
||||
source: SessionSource::Exec,
|
||||
thread_source: None,
|
||||
originator: "test_originator".to_string(),
|
||||
base_instructions: BaseInstructions::default(),
|
||||
dynamic_tools: Vec::new(),
|
||||
selected_capability_roots: Vec::new(),
|
||||
multi_agent_version: None,
|
||||
history_mode: ThreadHistoryMode::Paginated,
|
||||
history_base: None,
|
||||
subagent_history_start_ordinal: None,
|
||||
initial_window_id: "window-1".to_string(),
|
||||
runtime_workspace_roots: Some(vec![store.config.codex_home.join("workspace").abs()]),
|
||||
metadata: ThreadPersistenceMetadata {
|
||||
cwd: Some(std::env::current_dir().expect("cwd")),
|
||||
model_provider: "test-provider".to_string(),
|
||||
memory_mode: ThreadMemoryMode::Enabled,
|
||||
},
|
||||
})
|
||||
.await
|
||||
.expect("create paginated thread");
|
||||
}
|
||||
|
||||
async fn turn_ids(store: &LocalThreadStore, thread_id: ThreadId) -> Vec<String> {
|
||||
store
|
||||
.list_turns(ListTurnsParams {
|
||||
thread_id,
|
||||
include_archived: false,
|
||||
cursor: None,
|
||||
page_size: 10,
|
||||
sort_direction: SortDirection::Asc,
|
||||
items_view: StoredTurnItemsView::NotLoaded,
|
||||
})
|
||||
.await
|
||||
.expect("list turns")
|
||||
.turns
|
||||
.into_iter()
|
||||
.map(|turn| turn.turn_id)
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn turn_started(turn_id: &str) -> RolloutItem {
|
||||
RolloutItem::EventMsg(EventMsg::TurnStarted(TurnStartedEvent {
|
||||
turn_attribution: None,
|
||||
turn_id: turn_id.to_string(),
|
||||
root_turn_id: None,
|
||||
trace_id: None,
|
||||
started_at: Some(10),
|
||||
model_context_window: None,
|
||||
collaboration_mode_kind: Default::default(),
|
||||
}))
|
||||
}
|
||||
|
||||
fn turn_completed(turn_id: &str) -> RolloutItem {
|
||||
RolloutItem::EventMsg(EventMsg::TurnComplete(TurnCompleteEvent {
|
||||
root_turn_id: None,
|
||||
turn_id: turn_id.to_string(),
|
||||
last_agent_message: None,
|
||||
error: None,
|
||||
started_at: Some(10),
|
||||
completed_at: Some(20),
|
||||
duration_ms: Some(10_000),
|
||||
time_to_first_token_ms: None,
|
||||
}))
|
||||
}
|
||||
|
||||
fn compress_rollout(path: &std::path::Path) {
|
||||
let contents = std::fs::read(path).expect("read rollout");
|
||||
let compressed = zstd::stream::encode_all(contents.as_slice(), 3).expect("compress rollout");
|
||||
std::fs::write(path.with_extension("jsonl.zst"), compressed).expect("write compressed rollout");
|
||||
std::fs::remove_file(path).expect("remove plain rollout");
|
||||
}
|
||||
640
codex-rs/thread-store/src/local/rollout_lineage.rs
Normal file
640
codex-rs/thread-store/src/local/rollout_lineage.rs
Normal file
@@ -0,0 +1,640 @@
|
||||
use std::borrow::Cow;
|
||||
use std::collections::HashMap;
|
||||
use std::collections::HashSet;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::protocol::EventMsg;
|
||||
use codex_protocol::protocol::HistoryPosition;
|
||||
use codex_protocol::protocol::ThreadHistoryMode;
|
||||
|
||||
use codex_rollout::RolloutItem;
|
||||
|
||||
mod ancestor_reads;
|
||||
pub(super) use ancestor_reads::AncestorReads;
|
||||
use ancestor_reads::FailedAncestor;
|
||||
|
||||
use super::LocalThreadStore;
|
||||
use super::thread_rollout_resolver;
|
||||
use crate::ThreadStoreError;
|
||||
use crate::ThreadStoreResult;
|
||||
|
||||
/// One immutable rollout range contributing to a paginated thread's history.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub(super) struct RolloutLineageSegment {
|
||||
pub(super) rollout_id: ThreadId,
|
||||
pub(super) rollout_path: PathBuf,
|
||||
pub(super) start_ordinal: u64,
|
||||
pub(super) end: Option<HistoryPosition>,
|
||||
hides_parent: bool,
|
||||
}
|
||||
|
||||
/// Ordered rollout ranges contributing to one forked history.
|
||||
///
|
||||
/// This is the only local abstraction that follows SessionMeta.history_base pointers. Readers
|
||||
/// consume its bounded rollout segments without resolving or mutating fork pointers themselves.
|
||||
#[derive(Clone, Debug)]
|
||||
pub(super) struct RolloutLineage {
|
||||
pub(super) segments: Vec<RolloutLineageSegment>,
|
||||
pub(super) reads: AncestorReads,
|
||||
requested_thread_id: ThreadId,
|
||||
mode: LineageResolutionMode,
|
||||
}
|
||||
|
||||
impl LocalThreadStore {
|
||||
pub(super) async fn resolve_rollout_lineage(
|
||||
&self,
|
||||
requested_thread_id: ThreadId,
|
||||
initial_path: Option<PathBuf>,
|
||||
) -> ThreadStoreResult<RolloutLineage> {
|
||||
self.resolve_rollout_lineage_with_mode(
|
||||
requested_thread_id,
|
||||
LineageResolutionMode::Existing,
|
||||
initial_path,
|
||||
&HashMap::new(),
|
||||
)
|
||||
.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,
|
||||
&HashMap::new(),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
pub(super) async fn resolve_rollout_lineage_for_reference(
|
||||
&self,
|
||||
requested_thread_id: ThreadId,
|
||||
) -> ThreadStoreResult<RolloutLineage> {
|
||||
self.resolve_rollout_lineage_with_mode(
|
||||
requested_thread_id,
|
||||
LineageResolutionMode::PlainForReference,
|
||||
/*initial_path*/ None,
|
||||
&HashMap::new(),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn resolve_rollout_lineage_with_mode(
|
||||
&self,
|
||||
requested_thread_id: ThreadId,
|
||||
mode: LineageResolutionMode,
|
||||
mut initial_path: Option<PathBuf>,
|
||||
excluded: &HashMap<ThreadId, FailedAncestor>,
|
||||
) -> ThreadStoreResult<RolloutLineage> {
|
||||
let mut segments = Vec::new();
|
||||
let mut seen = HashSet::new();
|
||||
let mut end: Option<HistoryPosition> = None;
|
||||
let mut prefetched_paths = HashMap::new();
|
||||
let mut ancestor_paths = HashMap::new();
|
||||
|
||||
loop {
|
||||
let coordination_id = end.map_or(requested_thread_id, |end| end.thread_id);
|
||||
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, bounds)) = if let Some(end) = end {
|
||||
let ancestor = resolve_ancestor_rollout(
|
||||
self,
|
||||
requested_thread_id,
|
||||
end,
|
||||
mode,
|
||||
prefetched_paths.remove(&end.thread_id),
|
||||
excluded.get(&end.thread_id),
|
||||
)
|
||||
.await?;
|
||||
(end.thread_id, ancestor)
|
||||
} else {
|
||||
let (rollout_id, path) = match initial_path.take() {
|
||||
Some(path) => {
|
||||
let id = thread_rollout_resolver::rollout_id_from_path_or_legacy_thread_id(
|
||||
&path,
|
||||
requested_thread_id,
|
||||
ThreadHistoryMode::Paginated,
|
||||
)?;
|
||||
(id, path)
|
||||
}
|
||||
None => {
|
||||
let resolved = thread_rollout_resolver::resolve_current_including_archived(
|
||||
self,
|
||||
requested_thread_id,
|
||||
)
|
||||
.await?
|
||||
.ok_or_else(|| {
|
||||
malformed_lineage(requested_thread_id, "missing source rollout")
|
||||
})?;
|
||||
(resolved.rollout_id, resolved.path)
|
||||
}
|
||||
};
|
||||
let (path, mut bounds) = mode
|
||||
.read_rollout(self, path, requested_thread_id, Some(requested_thread_id))
|
||||
.await?;
|
||||
if matches!(mode, LineageResolutionMode::HistoryPage) {
|
||||
bounds
|
||||
.read_history_page_bounds(&path, requested_thread_id)
|
||||
.await?;
|
||||
}
|
||||
(rollout_id, (path, bounds))
|
||||
};
|
||||
if !seen.insert(rollout_id) {
|
||||
return Err(malformed_lineage(requested_thread_id, "cycle detected"));
|
||||
}
|
||||
let rollout_path = match mode {
|
||||
LineageResolutionMode::Existing | LineageResolutionMode::HistoryPage => {
|
||||
rollout_path
|
||||
}
|
||||
LineageResolutionMode::PlainForReference
|
||||
if end.is_none() && bounds.parent.is_none() =>
|
||||
{
|
||||
// A newly shared standalone source must remain readable by older binaries.
|
||||
codex_rollout::materialize_rollout_for_reference(rollout_path.as_path())
|
||||
.await
|
||||
.map_err(|err| ThreadStoreError::Internal {
|
||||
message: format!(
|
||||
"failed to materialize referenced rollout {}: {err}",
|
||||
rollout_path.display()
|
||||
),
|
||||
})?
|
||||
}
|
||||
// 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.
|
||||
LineageResolutionMode::PlainForReference => rollout_path,
|
||||
};
|
||||
if let Some(end) = end
|
||||
&& !matches!(mode, LineageResolutionMode::HistoryPage)
|
||||
{
|
||||
ancestor_paths.insert(rollout_path.clone(), (end, bounds.owner));
|
||||
}
|
||||
segments.push(RolloutLineageSegment {
|
||||
rollout_id,
|
||||
rollout_path,
|
||||
start_ordinal: bounds.start_ordinal,
|
||||
end,
|
||||
hides_parent: bounds.hides_parent,
|
||||
});
|
||||
|
||||
let Some(base) = bounds.parent 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();
|
||||
}
|
||||
end = Some(base);
|
||||
}
|
||||
|
||||
segments.reverse();
|
||||
Ok(RolloutLineage {
|
||||
segments,
|
||||
reads: AncestorReads::new(ancestor_paths),
|
||||
requested_thread_id,
|
||||
mode,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// A mid-turn fork starts with its header, settings, optional model guidance, and parent abort.
|
||||
/// Stop before the first child event; a real child interruption follows its own turn start.
|
||||
async fn attached_history_start(path: &Path, start: u64) -> std::io::Result<u64> {
|
||||
let mut reader = codex_rollout::open_rollout_line_reader(path).await?;
|
||||
for _ in 0..4 {
|
||||
let Some(line) = reader.next_line().await? else {
|
||||
break;
|
||||
};
|
||||
let Ok(line) = codex_rollout::parse_rollout_line(&line) else {
|
||||
break;
|
||||
};
|
||||
match line.item {
|
||||
RolloutItem::SessionMeta(_)
|
||||
| RolloutItem::EventMsg(EventMsg::ThreadSettingsApplied(_))
|
||||
| RolloutItem::ResponseItem(_) => {}
|
||||
RolloutItem::EventMsg(EventMsg::TurnAborted(_)) => {
|
||||
return Ok(line.ordinal.map_or(start, |n| n.saturating_add(1)));
|
||||
}
|
||||
_ => break,
|
||||
}
|
||||
}
|
||||
Ok(start)
|
||||
}
|
||||
|
||||
// Resume can retain either a logical or canonical path. Validate both against the same
|
||||
// canonical managed roots so a nested symlink cannot escape this home.
|
||||
async fn managed_rollout_path(store: &LocalThreadStore, rollout_path: &Path) -> Option<PathBuf> {
|
||||
let path = tokio::fs::canonicalize(rollout_path).await.ok()?;
|
||||
for subdir in [
|
||||
codex_rollout::SESSIONS_SUBDIR,
|
||||
codex_rollout::ARCHIVED_SESSIONS_SUBDIR,
|
||||
] {
|
||||
if tokio::fs::canonicalize(store.config.codex_home.join(subdir))
|
||||
.await
|
||||
.is_ok_and(|root| path.starts_with(root))
|
||||
{
|
||||
return Some(path);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
// The filename scan skips file symlinks. Following one here could change which plain
|
||||
// sibling the reader prefers after canonicalizing a compressed rollout.
|
||||
async fn existing_regular_rollout_path(path: &Path) -> Option<PathBuf> {
|
||||
let path = codex_rollout::existing_rollout_path(path).await?;
|
||||
let metadata = tokio::fs::symlink_metadata(&path).await.ok()?;
|
||||
metadata.is_file().then_some(path)
|
||||
}
|
||||
|
||||
/// Resolve the representation the reader will open and check its immutable ID inside managed storage.
|
||||
async fn managed_ancestor_path(
|
||||
store: &LocalThreadStore,
|
||||
path: &Path,
|
||||
rollout_id: ThreadId,
|
||||
) -> Option<PathBuf> {
|
||||
if codex_rollout::rollout_id_from_path(path) != Some(rollout_id) {
|
||||
return None;
|
||||
}
|
||||
let path = existing_regular_rollout_path(path).await?;
|
||||
let path = managed_rollout_path(store, &path).await?;
|
||||
(codex_rollout::rollout_id_from_path(&path) == Some(rollout_id)).then_some(path)
|
||||
}
|
||||
|
||||
struct RolloutBounds {
|
||||
owner: ThreadId,
|
||||
start_ordinal: u64,
|
||||
parent: Option<HistoryPosition>,
|
||||
hides_parent: bool,
|
||||
}
|
||||
|
||||
async fn resolve_ancestor_rollout(
|
||||
store: &LocalThreadStore,
|
||||
requested_thread_id: ThreadId,
|
||||
end: HistoryPosition,
|
||||
mode: LineageResolutionMode,
|
||||
prefetched_path: Option<PathBuf>,
|
||||
excluded: Option<&FailedAncestor>,
|
||||
) -> ThreadStoreResult<(PathBuf, RolloutBounds)> {
|
||||
if end.end_ordinal_exclusive == 0 {
|
||||
return Err(malformed_lineage(
|
||||
requested_thread_id,
|
||||
"cutoff cannot include source session metadata",
|
||||
));
|
||||
}
|
||||
let (path, mut bounds) = resolve_ancestor_candidate(
|
||||
store,
|
||||
requested_thread_id,
|
||||
end.thread_id,
|
||||
mode,
|
||||
prefetched_path,
|
||||
excluded,
|
||||
)
|
||||
.await?;
|
||||
if matches!(mode, LineageResolutionMode::HistoryPage)
|
||||
&& let Err(error) = bounds
|
||||
.read_history_page_bounds(&path, requested_thread_id)
|
||||
.await
|
||||
{
|
||||
let failed = FailedAncestor {
|
||||
path: tokio::fs::canonicalize(&path).await.unwrap_or(path),
|
||||
owner: bounds.owner,
|
||||
error,
|
||||
};
|
||||
let (path, mut bounds) = resolve_ancestor_candidate(
|
||||
store,
|
||||
requested_thread_id,
|
||||
end.thread_id,
|
||||
mode,
|
||||
/*prefetched_path*/ None,
|
||||
Some(&failed),
|
||||
)
|
||||
.await
|
||||
.map_err(|_| failed.error.clone())?;
|
||||
bounds
|
||||
.read_history_page_bounds(&path, requested_thread_id)
|
||||
.await
|
||||
.map_err(|_| failed.error)?;
|
||||
return Ok((path, bounds));
|
||||
}
|
||||
Ok((path, bounds))
|
||||
}
|
||||
|
||||
async fn resolve_ancestor_candidate(
|
||||
store: &LocalThreadStore,
|
||||
requested_thread_id: ThreadId,
|
||||
rollout_id: ThreadId,
|
||||
mode: LineageResolutionMode,
|
||||
prefetched_path: Option<PathBuf>,
|
||||
excluded: Option<&FailedAncestor>,
|
||||
) -> ThreadStoreResult<(PathBuf, RolloutBounds)> {
|
||||
let mut rejected = None;
|
||||
let path = if excluded.is_none()
|
||||
&& let Some(path) = prefetched_path
|
||||
&& let Some(path) = existing_regular_rollout_path(&path).await
|
||||
{
|
||||
path
|
||||
} else {
|
||||
// SQLite records the current path by thread ID. An original rollout shares its owner's
|
||||
// ID, but the current path can also name a later rollout created by a revert.
|
||||
if excluded.is_none()
|
||||
&& let Some(state_db) = store.state_db().await
|
||||
&& let Ok(Some(path)) = state_db
|
||||
.find_rollout_path_by_id(rollout_id, /*archived_only*/ None)
|
||||
.await
|
||||
&& let Some(path) = managed_ancestor_path(store, &path, rollout_id).await
|
||||
{
|
||||
match RolloutBounds::read(&path, requested_thread_id, Some(rollout_id)).await {
|
||||
Ok(bounds) => return Ok((path, bounds)),
|
||||
Err(error) => rejected = Some((path, error)),
|
||||
}
|
||||
}
|
||||
let excluded_path = excluded
|
||||
.map(|failed| failed.path.as_path())
|
||||
.or_else(|| rejected.as_ref().map(|(path, _)| path.as_path()));
|
||||
codex_rollout::find_rollout_path_by_rollout_id_excluding(
|
||||
&store.config.codex_home,
|
||||
rollout_id,
|
||||
excluded_path,
|
||||
)
|
||||
.await
|
||||
.map_err(|err| ThreadStoreError::Internal {
|
||||
message: format!("failed to locate rollout {rollout_id}: {err}"),
|
||||
})
|
||||
.and_then(|path| {
|
||||
path.ok_or_else(|| malformed_lineage(rollout_id, "missing source rollout"))
|
||||
})
|
||||
.map_err(|scan_error| rejected.take().map_or(scan_error, |(_, error)| error))?
|
||||
};
|
||||
if let Some(failed) = excluded {
|
||||
let path = managed_ancestor_path(store, &path, rollout_id)
|
||||
.await
|
||||
.ok_or_else(|| malformed_lineage(rollout_id, "invalid replacement rollout path"))?;
|
||||
// A revert can give a rollout a new ID without changing the thread that owns its history.
|
||||
let bounds = RolloutBounds::read(&path, requested_thread_id, Some(failed.owner)).await?;
|
||||
return Ok((path, bounds));
|
||||
}
|
||||
mode.read_rollout(
|
||||
store,
|
||||
path,
|
||||
requested_thread_id,
|
||||
rejected.is_some().then_some(rollout_id),
|
||||
)
|
||||
.await
|
||||
.map_err(|scan_error| rejected.map_or(scan_error, |(_, error)| error))
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
enum LineageResolutionMode {
|
||||
Existing,
|
||||
HistoryPage,
|
||||
PlainForReference,
|
||||
}
|
||||
|
||||
impl LineageResolutionMode {
|
||||
async fn read_rollout(
|
||||
self,
|
||||
store: &LocalThreadStore,
|
||||
path: PathBuf,
|
||||
requested_thread_id: ThreadId,
|
||||
expected_owner: Option<ThreadId>,
|
||||
) -> ThreadStoreResult<(PathBuf, RolloutBounds)> {
|
||||
let path = match self {
|
||||
Self::Existing | Self::HistoryPage => path,
|
||||
Self::PlainForReference => {
|
||||
managed_rollout_path(store, &path).await.ok_or_else(|| {
|
||||
ThreadStoreError::InvalidRequest {
|
||||
message: format!(
|
||||
"rollout path `{}` must be in Codex home directory",
|
||||
path.display()
|
||||
),
|
||||
}
|
||||
})?
|
||||
}
|
||||
};
|
||||
let bounds = RolloutBounds::read(&path, requested_thread_id, expected_owner).await?;
|
||||
Ok((path, bounds))
|
||||
}
|
||||
}
|
||||
|
||||
impl RolloutBounds {
|
||||
async fn read(
|
||||
path: &Path,
|
||||
requested_thread_id: ThreadId,
|
||||
expected_owner: Option<ThreadId>,
|
||||
) -> ThreadStoreResult<Self> {
|
||||
let meta = codex_rollout::read_session_meta_line(path)
|
||||
.await
|
||||
.map_err(|err| ThreadStoreError::Internal {
|
||||
message: format!("failed to read lineage metadata {}: {err}", path.display()),
|
||||
})?;
|
||||
if expected_owner.is_some_and(|owner| owner != meta.meta.id) {
|
||||
return Err(malformed_lineage(
|
||||
requested_thread_id,
|
||||
"source rollout belongs to another thread",
|
||||
));
|
||||
}
|
||||
if meta.meta.history_mode != ThreadHistoryMode::Paginated {
|
||||
return Err(malformed_lineage(
|
||||
requested_thread_id,
|
||||
"source rollout is not paginated",
|
||||
));
|
||||
}
|
||||
let Some(base) = meta.meta.history_base else {
|
||||
return Ok(RolloutBounds {
|
||||
owner: meta.meta.id,
|
||||
start_ordinal: 1,
|
||||
parent: None,
|
||||
hides_parent: false,
|
||||
});
|
||||
};
|
||||
let start_ordinal = base
|
||||
.end_ordinal_exclusive
|
||||
.checked_add(1)
|
||||
.ok_or_else(|| malformed_lineage(requested_thread_id, "source ordinal overflow"))?;
|
||||
// Reverts can point to earlier records of the same child. Stop at the original parent bookmark.
|
||||
let hides_parent = meta.meta.attached_thread
|
||||
&& codex_rollout::forked_from_ordinal_exclusive(&meta.meta, Some(path))
|
||||
.is_some_and(|end| base.end_ordinal_exclusive <= end);
|
||||
Ok(RolloutBounds {
|
||||
owner: meta.meta.id,
|
||||
start_ordinal,
|
||||
parent: Some(base),
|
||||
hides_parent,
|
||||
})
|
||||
}
|
||||
|
||||
async fn read_history_page_bounds(
|
||||
&mut self,
|
||||
path: &Path,
|
||||
requested_thread_id: ThreadId,
|
||||
) -> ThreadStoreResult<()> {
|
||||
if self.hides_parent {
|
||||
self.start_ordinal = attached_history_start(path, self.start_ordinal)
|
||||
.await
|
||||
.map_err(|err| malformed_lineage(requested_thread_id, &err.to_string()))?;
|
||||
self.parent = None;
|
||||
self.hides_parent = false;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl RolloutLineage {
|
||||
/// Use the projected paths for named turn lookup, hiding history inherited by an attached child.
|
||||
pub(super) async fn for_history_page(&self) -> ThreadStoreResult<Cow<'_, Self>> {
|
||||
let Some(first) = self
|
||||
.segments
|
||||
.iter()
|
||||
.rposition(|segment| segment.hides_parent)
|
||||
else {
|
||||
return Ok(Cow::Borrowed(self));
|
||||
};
|
||||
let mut segments = self.segments[first..].to_vec();
|
||||
let child = &mut segments[0];
|
||||
child.start_ordinal = attached_history_start(&child.rollout_path, child.start_ordinal)
|
||||
.await
|
||||
.map_err(|err| {
|
||||
self.reads.record_failure(&child.rollout_path);
|
||||
malformed_lineage(
|
||||
self.requested_thread_id,
|
||||
&format!(
|
||||
"failed to read attached history {}: {err}",
|
||||
child.rollout_path.display()
|
||||
),
|
||||
)
|
||||
})?;
|
||||
child.hides_parent = false;
|
||||
Ok(Cow::Owned(Self {
|
||||
segments,
|
||||
reads: self.reads.clone(),
|
||||
requested_thread_id: self.requested_thread_id,
|
||||
mode: LineageResolutionMode::HistoryPage,
|
||||
}))
|
||||
}
|
||||
|
||||
pub(super) fn segments(&self) -> &[RolloutLineageSegment] {
|
||||
self.segments.as_slice()
|
||||
}
|
||||
|
||||
pub(super) fn segment_index_for_ordinal(&self, ordinal: u64) -> Option<usize> {
|
||||
self.segments.iter().position(|segment| {
|
||||
ordinal >= segment.start_ordinal()
|
||||
&& segment
|
||||
.end_ordinal()
|
||||
.is_none_or(|end_ordinal| ordinal < end_ordinal)
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) async fn truncate_at(
|
||||
mut self,
|
||||
end: HistoryPosition,
|
||||
) -> ThreadStoreResult<RolloutLineage> {
|
||||
let segment_index = self
|
||||
.segments
|
||||
.iter()
|
||||
.position(|segment| segment.rollout_id == end.thread_id)
|
||||
.ok_or_else(|| ThreadStoreError::Internal {
|
||||
message: "fork position is outside the source lineage".to_string(),
|
||||
})?;
|
||||
self.segments.truncate(segment_index + 1);
|
||||
let segment = self
|
||||
.segments
|
||||
.last_mut()
|
||||
.ok_or_else(|| ThreadStoreError::Internal {
|
||||
message: "rollout lineage has no segments".to_string(),
|
||||
})?;
|
||||
if end.end_ordinal_exclusive < segment.start_ordinal {
|
||||
return Err(malformed_lineage(
|
||||
end.thread_id,
|
||||
"fork boundary is outside inherited source history",
|
||||
));
|
||||
}
|
||||
if self.reads.tracks(&segment.rollout_path)
|
||||
&& let Some(inherited) = segment.end
|
||||
{
|
||||
if end.end_byte_offset > inherited.end_byte_offset
|
||||
|| end.end_ordinal_exclusive > inherited.end_ordinal_exclusive
|
||||
{
|
||||
return Err(malformed_lineage(
|
||||
end.thread_id,
|
||||
"fork boundary exceeds inherited source history",
|
||||
));
|
||||
}
|
||||
} else {
|
||||
validate_cutoff_byte_offset(end.thread_id, &segment.rollout_path, &end).await?;
|
||||
}
|
||||
segment.end = Some(end);
|
||||
Ok(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl RolloutLineageSegment {
|
||||
pub(super) fn rollout_id(&self) -> ThreadId {
|
||||
self.rollout_id
|
||||
}
|
||||
|
||||
pub(super) fn start_ordinal(&self) -> u64 {
|
||||
self.start_ordinal
|
||||
}
|
||||
|
||||
pub(super) fn end_ordinal(&self) -> Option<u64> {
|
||||
self.end.map(|end| end.end_ordinal_exclusive)
|
||||
}
|
||||
}
|
||||
|
||||
async fn validate_cutoff_byte_offset(
|
||||
requested_thread_id: ThreadId,
|
||||
rollout_path: &Path,
|
||||
end: &HistoryPosition,
|
||||
) -> ThreadStoreResult<()> {
|
||||
let path = rollout_path.to_path_buf();
|
||||
let end_byte_offset = end.end_byte_offset;
|
||||
let (stop, keep_running) = tokio::sync::oneshot::channel::<()>();
|
||||
let contains_prefix = tokio::task::spawn_blocking(move || {
|
||||
codex_rollout::rollout_contains_prefix(&path, end_byte_offset, || stop.is_closed())
|
||||
})
|
||||
.await
|
||||
.map_err(|err| ThreadStoreError::Internal {
|
||||
message: format!("failed to join rollout prefix validation: {err}"),
|
||||
})?
|
||||
.map_err(|err| ThreadStoreError::Internal {
|
||||
message: format!(
|
||||
"failed to read lineage metadata {}: {err}",
|
||||
rollout_path.display()
|
||||
),
|
||||
})?;
|
||||
drop(keep_running);
|
||||
if !contains_prefix {
|
||||
return Err(malformed_lineage(
|
||||
requested_thread_id,
|
||||
"cutoff byte offset is past the source rollout",
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn malformed_lineage(thread_id: ThreadId, detail: &str) -> ThreadStoreError {
|
||||
ThreadStoreError::InvalidRequest {
|
||||
message: format!("invalid paginated history lineage for {thread_id}: {detail}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "rollout_lineage_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,147 @@
|
||||
//! Retries reads from the same leaf when an ancestor cannot supply its frozen history.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::future::Future;
|
||||
use std::io;
|
||||
use std::io::Read;
|
||||
use std::io::Seek;
|
||||
use std::io::SeekFrom;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::sync::OnceLock;
|
||||
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::protocol::HistoryPosition;
|
||||
|
||||
use super::LocalThreadStore;
|
||||
use super::RolloutLineage;
|
||||
use crate::ThreadStoreError;
|
||||
use crate::ThreadStoreResult;
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub(in crate::local) struct AncestorReads(Option<Arc<TrackedAncestors>>);
|
||||
|
||||
#[derive(Debug)]
|
||||
struct TrackedAncestors {
|
||||
cutoffs: HashMap<PathBuf, (HistoryPosition, ThreadId)>,
|
||||
failed_path: OnceLock<PathBuf>,
|
||||
}
|
||||
|
||||
pub(super) struct FailedAncestor {
|
||||
pub(super) path: PathBuf,
|
||||
pub(super) owner: ThreadId,
|
||||
pub(super) error: ThreadStoreError,
|
||||
}
|
||||
|
||||
impl AncestorReads {
|
||||
pub(super) fn new(cutoffs: HashMap<PathBuf, (HistoryPosition, ThreadId)>) -> Self {
|
||||
Self((!cutoffs.is_empty()).then(|| {
|
||||
Arc::new(TrackedAncestors {
|
||||
cutoffs,
|
||||
failed_path: OnceLock::new(),
|
||||
})
|
||||
}))
|
||||
}
|
||||
|
||||
pub(in crate::local) fn cutoff(&self, path: &Path) -> Option<HistoryPosition> {
|
||||
self.0.as_ref()?.cutoffs.get(path).map(|(end, _)| *end)
|
||||
}
|
||||
|
||||
pub(in crate::local) fn tracks(&self, path: &Path) -> bool {
|
||||
self.cutoff(path).is_some()
|
||||
}
|
||||
|
||||
pub(in crate::local) fn record_failure(&self, path: &Path) {
|
||||
if let Some(ancestors) = &self.0
|
||||
&& ancestors.cutoffs.contains_key(path)
|
||||
{
|
||||
ancestors.failed_path.get_or_init(|| path.to_owned());
|
||||
}
|
||||
}
|
||||
|
||||
/// Validate the inherited offset on the reader that will actually consume the file.
|
||||
pub(in crate::local) fn open<F: Fn() -> bool>(
|
||||
&self,
|
||||
path: &Path,
|
||||
is_cancelled: F,
|
||||
) -> io::Result<impl Read + Seek> {
|
||||
let file = codex_rollout::open_rollout_seekable_reader(path, is_cancelled);
|
||||
let Some(end) = self.cutoff(path) else {
|
||||
return file;
|
||||
};
|
||||
file.and_then(|mut file| {
|
||||
if file.seek(SeekFrom::End(0))? < end.end_byte_offset {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::UnexpectedEof,
|
||||
"cutoff byte offset is past the source rollout",
|
||||
));
|
||||
}
|
||||
file.rewind()?;
|
||||
Ok(file)
|
||||
})
|
||||
.map_err(|err| {
|
||||
self.record_failure(path);
|
||||
io::Error::new(err.kind(), format!("{}: {err}", path.display()))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl RolloutLineage {
|
||||
/// A failed ancestor read can select another copy. An alternate may name a different
|
||||
/// parent, so resolve its lineage before retrying the read.
|
||||
pub(in crate::local) async fn read_with_fallback<T, F>(
|
||||
self,
|
||||
store: &LocalThreadStore,
|
||||
read: impl Fn(Self) -> F,
|
||||
) -> ThreadStoreResult<T>
|
||||
where
|
||||
F: Future<Output = ThreadStoreResult<T>> + Send,
|
||||
{
|
||||
let requested_thread_id = self.requested_thread_id;
|
||||
let mode = self.mode;
|
||||
let leaf = self
|
||||
.segments
|
||||
.last()
|
||||
.map(|segment| segment.rollout_path.clone());
|
||||
let mut excluded = HashMap::<ThreadId, FailedAncestor>::new();
|
||||
let mut lineage = self;
|
||||
loop {
|
||||
let reads = lineage.reads.clone();
|
||||
let error = match read(lineage).await {
|
||||
Ok(value) => return Ok(value),
|
||||
Err(error) => error,
|
||||
};
|
||||
let Some((path, (end, owner))) = reads.0.as_ref().and_then(|ancestors| {
|
||||
ancestors
|
||||
.cutoffs
|
||||
.get_key_value(ancestors.failed_path.get()?)
|
||||
}) else {
|
||||
return Err(error);
|
||||
};
|
||||
if let Some(original) = excluded.remove(&end.thread_id) {
|
||||
return Err(original.error);
|
||||
}
|
||||
let path = tokio::fs::canonicalize(path)
|
||||
.await
|
||||
.unwrap_or_else(|_| path.clone());
|
||||
excluded.insert(
|
||||
end.thread_id,
|
||||
FailedAncestor {
|
||||
path,
|
||||
owner: *owner,
|
||||
error: error.clone(),
|
||||
},
|
||||
);
|
||||
lineage = store
|
||||
.resolve_rollout_lineage_with_mode(
|
||||
requested_thread_id,
|
||||
mode,
|
||||
leaf.clone(),
|
||||
&excluded,
|
||||
)
|
||||
.await
|
||||
.map_err(|_| error)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
645
codex-rs/thread-store/src/local/rollout_lineage_tests.rs
Normal file
645
codex-rs/thread-store/src/local/rollout_lineage_tests.rs
Normal file
@@ -0,0 +1,645 @@
|
||||
use std::fs;
|
||||
use std::io::Write;
|
||||
use std::path::Path;
|
||||
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::protocol::HistoryPosition;
|
||||
use codex_protocol::protocol::SessionMeta;
|
||||
use codex_protocol::protocol::SessionMetaLine;
|
||||
use codex_protocol::protocol::ThreadHistoryMode;
|
||||
use codex_rollout::RolloutItem;
|
||||
use codex_rollout::RolloutLine;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tempfile::TempDir;
|
||||
|
||||
use super::super::LocalThreadStore;
|
||||
use super::super::test_support::test_config;
|
||||
use super::RolloutLineageSegment;
|
||||
use crate::ForkBoundary;
|
||||
use crate::LoadThreadHistoryParams;
|
||||
use crate::PrepareForkParams;
|
||||
use crate::ThreadStore;
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn rejects_reference_lineage_escaping_symlinked_sessions_root() {
|
||||
let home = TempDir::new().expect("temp dir");
|
||||
let external = TempDir::new().expect("external temp dir");
|
||||
let external_sessions = external.path().join("sessions");
|
||||
fs::create_dir_all(external_sessions.as_path()).expect("create external sessions");
|
||||
std::os::unix::fs::symlink(external_sessions.as_path(), home.path().join("sessions"))
|
||||
.expect("symlink sessions");
|
||||
let escaped = TempDir::new().expect("escaped temp dir");
|
||||
let escaped_rollouts = escaped.path().join("rollouts");
|
||||
fs::create_dir_all(escaped_rollouts.as_path()).expect("create escaped rollouts");
|
||||
std::os::unix::fs::symlink(escaped_rollouts.as_path(), external_sessions.join("2026"))
|
||||
.expect("symlink nested sessions directory");
|
||||
let store = LocalThreadStore::new(test_config(home.path()), /*state_db*/ None);
|
||||
let thread_id = ThreadId::default();
|
||||
write_rollout(
|
||||
home.path(),
|
||||
thread_id,
|
||||
/*history_base*/ None,
|
||||
/*next_ordinal*/ 3,
|
||||
);
|
||||
|
||||
let error = store
|
||||
.resolve_rollout_lineage_for_reference(thread_id)
|
||||
.await
|
||||
.expect_err("escaping reference lineage should be rejected");
|
||||
|
||||
assert!(error.to_string().contains("must be in Codex home"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn resolves_nested_lineage_with_empty_intermediate_segments() {
|
||||
let home = TempDir::new().expect("temp dir");
|
||||
let store = LocalThreadStore::new(test_config(home.path()), /*state_db*/ None);
|
||||
let root = ThreadId::default();
|
||||
let middle = ThreadId::default();
|
||||
let child = ThreadId::default();
|
||||
let root_path = write_rollout(
|
||||
home.path(),
|
||||
root,
|
||||
/*history_base*/ None,
|
||||
/*next_ordinal*/ 6,
|
||||
);
|
||||
let root_end = history_position(root_path.as_path(), root, /*end_ordinal_exclusive*/ 4);
|
||||
let middle_path = write_rollout(home.path(), middle, Some(root_end), /*next_ordinal*/ 1);
|
||||
let middle_end = history_position(
|
||||
middle_path.as_path(),
|
||||
middle,
|
||||
/*end_ordinal_exclusive*/ 5,
|
||||
);
|
||||
let child_path = write_rollout(
|
||||
home.path(),
|
||||
child,
|
||||
Some(middle_end),
|
||||
/*next_ordinal*/ 3,
|
||||
);
|
||||
|
||||
let lineage = store
|
||||
.resolve_rollout_lineage(child, /*initial_path*/ None)
|
||||
.await
|
||||
.expect("resolve nested lineage");
|
||||
|
||||
assert_eq!(
|
||||
lineage.segments,
|
||||
vec![
|
||||
RolloutLineageSegment {
|
||||
rollout_id: root,
|
||||
rollout_path: root_path.clone(),
|
||||
start_ordinal: 1,
|
||||
end: Some(root_end),
|
||||
hides_parent: false,
|
||||
},
|
||||
RolloutLineageSegment {
|
||||
rollout_id: middle,
|
||||
rollout_path: middle_path.clone(),
|
||||
start_ordinal: 5,
|
||||
end: Some(middle_end),
|
||||
hides_parent: false,
|
||||
},
|
||||
RolloutLineageSegment {
|
||||
rollout_id: child,
|
||||
rollout_path: child_path,
|
||||
start_ordinal: 6,
|
||||
end: None,
|
||||
hides_parent: false,
|
||||
},
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn resolves_archived_ancestors() {
|
||||
let home = TempDir::new().expect("temp dir");
|
||||
let store = LocalThreadStore::new(test_config(home.path()), /*state_db*/ None);
|
||||
let root = ThreadId::default();
|
||||
let child = ThreadId::default();
|
||||
let root_path = write_rollout_under(
|
||||
home.path().join("archived_sessions"),
|
||||
root,
|
||||
/*history_base*/ None,
|
||||
/*next_ordinal*/ 3,
|
||||
);
|
||||
write_rollout(
|
||||
home.path(),
|
||||
child,
|
||||
Some(history_position(
|
||||
root_path.as_path(),
|
||||
root,
|
||||
/*end_ordinal_exclusive*/ 3,
|
||||
)),
|
||||
/*next_ordinal*/ 2,
|
||||
);
|
||||
|
||||
let lineage = store
|
||||
.resolve_rollout_lineage(child, /*initial_path*/ None)
|
||||
.await
|
||||
.expect("resolve archived ancestor");
|
||||
|
||||
assert_eq!(lineage.segments[0].rollout_path, root_path);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn unreadable_ancestor_recovers_from_another_copy_of_the_same_rollout() {
|
||||
let temp = TempDir::new().expect("temp dir");
|
||||
let home = temp.path().canonicalize().expect("canonical home");
|
||||
let store = store_with_state(&home).await;
|
||||
let owner = ThreadId::new();
|
||||
let root = ThreadId::new();
|
||||
let child = ThreadId::new();
|
||||
let original = write_rollout(
|
||||
&home, owner, /*history_base*/ None, /*next_ordinal*/ 5,
|
||||
);
|
||||
// Reverted rollout filenames contain the owner's stable thread ID and a distinct rollout ID.
|
||||
let name = format!("rollout-2026-07-16T00-00-00-{owner}_{root}.jsonl");
|
||||
let active = original.with_file_name(&name);
|
||||
fs::rename(original, &active).expect("name reverted rollout");
|
||||
let end = history_position(&active, root, /*end_ordinal_exclusive*/ 3);
|
||||
let child_path = write_rollout(&home, child, Some(end), /*next_ordinal*/ 2);
|
||||
let archived_dir = home.join("archived_sessions");
|
||||
fs::create_dir_all(&archived_dir).expect("create archive");
|
||||
let archived = archived_dir.join(name);
|
||||
let contents = fs::read_to_string(&active).expect("read active rollout");
|
||||
let load_context = || {
|
||||
store.load_latest_model_context(LoadThreadHistoryParams {
|
||||
thread_id: child,
|
||||
include_archived: false,
|
||||
})
|
||||
};
|
||||
let expected = load_context().await.expect("load intact context").items;
|
||||
let expected = serde_json::to_value(expected).expect("serialize context");
|
||||
let compressed = active.with_extension("jsonl.zst");
|
||||
let header = contents
|
||||
.split_inclusive('\n')
|
||||
.next()
|
||||
.expect("session header");
|
||||
write_unfinished_frame(&compressed, header);
|
||||
fs::remove_file(&active).expect("remove plain rollout");
|
||||
|
||||
let assert_original_error = async || {
|
||||
let err = load_context().await.expect_err("no usable copy");
|
||||
assert!(
|
||||
err.to_string()
|
||||
.ends_with(&format!("{}: incomplete frame", compressed.display())),
|
||||
"{err}"
|
||||
);
|
||||
};
|
||||
assert_original_error().await;
|
||||
// History pages read projected rows and only need the ancestor header for its bounds.
|
||||
let page = store
|
||||
.resolve_rollout_lineage_for_history_page(child)
|
||||
.await
|
||||
.expect("page with only the short active copy");
|
||||
assert_eq!(page.segments[0].rollout_path, compressed);
|
||||
let child_contents = fs::read_to_string(&child_path).expect("read child");
|
||||
let checkpoint = serde_json::json!({
|
||||
"timestamp": "2026-07-16T00:00:00.000Z", "ordinal": 5, "type": "compacted",
|
||||
"payload": {"message": "child checkpoint", "replacement_history": [], "window_number": 1}
|
||||
});
|
||||
fs::write(&child_path, format!("{child_contents}{checkpoint}\n")).expect("append checkpoint");
|
||||
let context = load_context()
|
||||
.await
|
||||
.expect("resume at the newer checkpoint");
|
||||
assert!(matches!(
|
||||
context.items.as_slice(),
|
||||
[RolloutItem::SessionMeta(_), RolloutItem::Compacted(item)] if item.message == "child checkpoint"
|
||||
));
|
||||
fs::write(&child_path, child_contents).expect("restore child");
|
||||
fs::write(
|
||||
&archived,
|
||||
contents.replace(&owner.to_string(), &root.to_string()),
|
||||
)
|
||||
.expect("stage another owner's history");
|
||||
assert_original_error().await;
|
||||
|
||||
let archive = contents.split_inclusive('\n').take(4).collect::<String>();
|
||||
fs::write(&archived, archive).expect("restore matching archived copy");
|
||||
let context = load_context().await.expect("resume from archive").items;
|
||||
assert_eq!(
|
||||
serde_json::to_value(context).expect("serialize resumed context"),
|
||||
expected
|
||||
);
|
||||
let fork = store
|
||||
.prepare_fork(PrepareForkParams {
|
||||
thread_id: child,
|
||||
boundary: ForkBoundary::Latest,
|
||||
})
|
||||
.await
|
||||
.expect("fork from archive");
|
||||
assert_eq!(
|
||||
serde_json::to_value(fork.model_context.as_ref()).expect("serialize fork context"),
|
||||
expected
|
||||
);
|
||||
|
||||
let assert_archive_projected = async |expected_offset| {
|
||||
let err = store
|
||||
.prepare_fork(PrepareForkParams {
|
||||
thread_id: child,
|
||||
boundary: ForkBoundary::ThroughTurn("missing".to_string()),
|
||||
})
|
||||
.await
|
||||
.expect_err("turn is missing after projection");
|
||||
assert!(
|
||||
matches!(&err, crate::ThreadStoreError::InvalidRequest { message } if message == "turn not found: missing"),
|
||||
"{err}"
|
||||
);
|
||||
let projection = super::super::thread_history::projection_state(&store, root)
|
||||
.await
|
||||
.expect("read checkpoint")
|
||||
.expect("ancestor projected");
|
||||
assert_eq!(projection.next_byte_offset, expected_offset);
|
||||
};
|
||||
assert_archive_projected(end.end_byte_offset).await;
|
||||
|
||||
// The ancestor's own projection can advance beyond the child's inherited prefix.
|
||||
super::super::thread_history_materialization::materialize_to_sqlite(&store, root, &archived)
|
||||
.await
|
||||
.expect("project the rest of the archive");
|
||||
let projected = fs::metadata(&archived).expect("archive size").len();
|
||||
let prefix = &contents.as_bytes()[..end.end_byte_offset as usize];
|
||||
let compressed_prefix = zstd::encode_all(prefix, /*level*/ 0).expect("compress prefix");
|
||||
fs::write(&compressed, compressed_prefix).expect("replace active copy with a shorter stream");
|
||||
fs::write(&archived, prefix).expect("shorten archive to the inherited prefix");
|
||||
assert_archive_projected(projected).await;
|
||||
}
|
||||
|
||||
async fn store_with_state(home: &Path) -> LocalThreadStore {
|
||||
let config = test_config(home);
|
||||
let state = codex_state::StateRuntime::init(
|
||||
config.sqlite.clone(),
|
||||
config.default_model_provider_id.clone(),
|
||||
)
|
||||
.await
|
||||
.expect("initialize sqlite");
|
||||
LocalThreadStore::new(config, Some(state))
|
||||
}
|
||||
|
||||
fn write_unfinished_frame(path: &Path, prefix: &str) {
|
||||
let mut encoder = zstd::Encoder::new(Vec::new(), /*level*/ 0).expect("create encoder");
|
||||
encoder
|
||||
.set_pledged_src_size(Some(prefix.len() as u64))
|
||||
.expect("set frame size");
|
||||
encoder.write_all(prefix.as_bytes()).expect("write prefix");
|
||||
encoder.flush().expect("flush unfinished frame");
|
||||
fs::write(path, encoder.get_ref()).expect("write unfinished frame");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn indexed_ancestor_must_be_managed_and_owned_by_the_indexed_thread() {
|
||||
let temp = TempDir::new().expect("temp dir");
|
||||
let home = temp.path().canonicalize().expect("canonical home");
|
||||
let external_home = TempDir::new().expect("external home");
|
||||
let store = store_with_state(&home).await;
|
||||
let state = store.state_db().await.expect("SQLite store");
|
||||
let root = ThreadId::new();
|
||||
let child = ThreadId::new();
|
||||
let active = write_rollout(
|
||||
&home, root, /*history_base*/ None, /*next_ordinal*/ 3,
|
||||
);
|
||||
let archived = write_rollout_under(
|
||||
home.join("archived_sessions"),
|
||||
root,
|
||||
/*history_base*/ None,
|
||||
/*next_ordinal*/ 4,
|
||||
);
|
||||
let external = write_rollout(
|
||||
external_home.path(),
|
||||
root,
|
||||
/*history_base*/ None,
|
||||
/*next_ordinal*/ 3,
|
||||
);
|
||||
let end = history_position(&active, root, /*end_ordinal_exclusive*/ 3);
|
||||
write_rollout(&home, child, Some(end), /*next_ordinal*/ 2);
|
||||
let assert_lookup = async |indexed: &Path, expected: &Path| {
|
||||
let mut metadata = codex_state::ThreadMetadataBuilder::new(
|
||||
root,
|
||||
indexed.to_owned(),
|
||||
chrono::Utc::now(),
|
||||
codex_protocol::protocol::SessionSource::Cli,
|
||||
);
|
||||
metadata.history_mode = ThreadHistoryMode::Paginated;
|
||||
state
|
||||
.upsert_thread(&metadata.build("test-provider"))
|
||||
.await
|
||||
.expect("index ancestor");
|
||||
let existing = store
|
||||
.resolve_rollout_lineage(child, /*initial_path*/ None)
|
||||
.await
|
||||
.expect("resolve ancestor");
|
||||
let reference = store
|
||||
.resolve_rollout_lineage_for_reference(child)
|
||||
.await
|
||||
.expect("resolve reference");
|
||||
for lineage in [existing, reference] {
|
||||
assert_eq!(lineage.segments[0].rollout_path, expected);
|
||||
}
|
||||
};
|
||||
assert_lookup(&archived, &archived).await;
|
||||
assert_lookup(&external, &active).await;
|
||||
let contents = fs::read_to_string(&archived).expect("read archive");
|
||||
let (header, events) = contents.split_once('\n').expect("header and events");
|
||||
let legacy = header.replace("\"paginated\"", "\"legacy\"");
|
||||
fs::write(&archived, header).expect("shorten indexed archive");
|
||||
assert_lookup(&archived, &archived).await;
|
||||
fs::write(&archived, format!("{legacy}\n{events}")).expect("write legacy archive");
|
||||
assert_lookup(&archived, &active).await;
|
||||
let compressed = archived.with_extension("jsonl.zst");
|
||||
fs::write(
|
||||
&compressed,
|
||||
zstd::encode_all(contents.as_bytes(), /*level*/ 0).expect("compress archive"),
|
||||
)
|
||||
.expect("write complete compressed copy");
|
||||
fs::remove_file(&archived).expect("remove plain archive");
|
||||
assert_lookup(&compressed, &compressed).await;
|
||||
let load_context = || {
|
||||
store.load_latest_model_context(LoadThreadHistoryParams {
|
||||
thread_id: child,
|
||||
include_archived: false,
|
||||
})
|
||||
};
|
||||
let items = async || {
|
||||
serde_json::to_value(load_context().await.expect("load context").items)
|
||||
.expect("serialize context")
|
||||
};
|
||||
let expected = items().await;
|
||||
for prefix in [contents.as_str(), &contents[..header.len() + 1]] {
|
||||
write_unfinished_frame(&compressed, prefix);
|
||||
assert_lookup(&compressed, &compressed).await;
|
||||
assert_eq!(items().await, expected);
|
||||
let fork = store
|
||||
.prepare_fork(PrepareForkParams {
|
||||
thread_id: child,
|
||||
boundary: ForkBoundary::Latest,
|
||||
})
|
||||
.await
|
||||
.expect("fork using the intact active copy");
|
||||
assert_eq!(
|
||||
serde_json::to_value(fork.model_context.as_ref()).expect("serialize fork"),
|
||||
expected
|
||||
);
|
||||
let page = store
|
||||
.resolve_rollout_lineage_for_history_page(child)
|
||||
.await
|
||||
.expect("resolve page");
|
||||
assert_eq!(page.segments[0].rollout_path, compressed);
|
||||
}
|
||||
let wrong_owner = contents.replace(&root.to_string(), &ThreadId::new().to_string());
|
||||
fs::write(&active, &wrong_owner).expect("substitute another thread's history");
|
||||
let error = load_context()
|
||||
.await
|
||||
.expect_err("reject wrong owner on retry");
|
||||
assert!(
|
||||
error
|
||||
.to_string()
|
||||
.ends_with(&format!("{}: incomplete frame", compressed.display())),
|
||||
"{error}"
|
||||
);
|
||||
fs::remove_file(&compressed).expect("remove truncated archive");
|
||||
fs::write(&archived, &contents).expect("restore archive");
|
||||
assert_lookup(&active, &archived).await;
|
||||
fs::write(&active, []).expect("empty indexed rollout");
|
||||
assert_lookup(&active, &archived).await;
|
||||
fs::remove_file(&archived).expect("remove fallback");
|
||||
assert_invalid_lineage(
|
||||
&store,
|
||||
child,
|
||||
&format!("rollout at {} is empty", active.display()),
|
||||
)
|
||||
.await;
|
||||
|
||||
#[cfg(unix)]
|
||||
{
|
||||
fs::copy(&external, &active).expect("restore active rollout");
|
||||
fs::write(
|
||||
&compressed,
|
||||
zstd::encode_all(contents.as_bytes(), /*level*/ 0).expect("compress archive"),
|
||||
)
|
||||
.expect("restore compressed archive");
|
||||
std::os::unix::fs::symlink(&external, &archived).expect("link plain sibling outside home");
|
||||
let alias = home
|
||||
.join("sessions")
|
||||
.join(compressed.file_name().expect("filename"));
|
||||
std::os::unix::fs::symlink(&compressed, &alias).expect("link indexed compressed rollout");
|
||||
assert_lookup(&alias, &active).await;
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn resolves_lineage_at_explicit_history_position() {
|
||||
let home = TempDir::new().expect("temp dir");
|
||||
let store = LocalThreadStore::new(test_config(home.path()), /*state_db*/ None);
|
||||
let root = ThreadId::default();
|
||||
let child = ThreadId::default();
|
||||
let root_path = write_rollout(
|
||||
home.path(),
|
||||
root,
|
||||
/*history_base*/ None,
|
||||
/*next_ordinal*/ 6,
|
||||
);
|
||||
let root_end = history_position(root_path.as_path(), root, /*end_ordinal_exclusive*/ 4);
|
||||
let child_path = write_rollout(home.path(), child, Some(root_end), /*next_ordinal*/ 4);
|
||||
let end = history_position(
|
||||
child_path.as_path(),
|
||||
child,
|
||||
/*end_ordinal_exclusive*/ 6,
|
||||
);
|
||||
|
||||
let lineage = store
|
||||
.resolve_rollout_lineage(child, /*initial_path*/ None)
|
||||
.await
|
||||
.expect("resolve child lineage")
|
||||
.truncate_at(end)
|
||||
.await
|
||||
.expect("resolve explicit position");
|
||||
|
||||
assert_eq!(
|
||||
lineage.segments,
|
||||
vec![
|
||||
RolloutLineageSegment {
|
||||
rollout_id: root,
|
||||
rollout_path: root_path.clone(),
|
||||
start_ordinal: 1,
|
||||
end: Some(root_end),
|
||||
hides_parent: false,
|
||||
},
|
||||
RolloutLineageSegment {
|
||||
rollout_id: child,
|
||||
rollout_path: child_path.clone(),
|
||||
start_ordinal: 5,
|
||||
end: Some(end),
|
||||
hides_parent: false,
|
||||
},
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rejects_missing_cycles_and_out_of_bounds_offsets() {
|
||||
let home = TempDir::new().expect("temp dir");
|
||||
let store = LocalThreadStore::new(test_config(home.path()), /*state_db*/ None);
|
||||
let missing_parent = ThreadId::default();
|
||||
let missing_child = ThreadId::default();
|
||||
write_rollout(
|
||||
home.path(),
|
||||
missing_child,
|
||||
Some(unchecked_history_position(
|
||||
missing_parent,
|
||||
/*end_ordinal_exclusive*/ 1,
|
||||
)),
|
||||
/*next_ordinal*/ 2,
|
||||
);
|
||||
assert_invalid_lineage(&store, missing_child, "missing source rollout").await;
|
||||
|
||||
let cycle_a = ThreadId::default();
|
||||
let cycle_b = ThreadId::default();
|
||||
write_rollout(
|
||||
home.path(),
|
||||
cycle_a,
|
||||
Some(unchecked_history_position(
|
||||
cycle_b, /*end_ordinal_exclusive*/ 1,
|
||||
)),
|
||||
/*next_ordinal*/ 2,
|
||||
);
|
||||
write_rollout(
|
||||
home.path(),
|
||||
cycle_b,
|
||||
Some(unchecked_history_position(
|
||||
cycle_a, /*end_ordinal_exclusive*/ 1,
|
||||
)),
|
||||
/*next_ordinal*/ 2,
|
||||
);
|
||||
assert_invalid_lineage(&store, cycle_a, "cycle detected").await;
|
||||
|
||||
let root = ThreadId::default();
|
||||
let invalid_child = ThreadId::default();
|
||||
let root_path = write_rollout(
|
||||
home.path(),
|
||||
root,
|
||||
/*history_base*/ None,
|
||||
/*next_ordinal*/ 2,
|
||||
);
|
||||
write_rollout(
|
||||
home.path(),
|
||||
invalid_child,
|
||||
Some(HistoryPosition {
|
||||
thread_id: root,
|
||||
end_ordinal_exclusive: 2,
|
||||
end_byte_offset: fs::metadata(root_path).expect("root metadata").len() + 1,
|
||||
}),
|
||||
/*next_ordinal*/ 2,
|
||||
);
|
||||
assert_invalid_lineage(
|
||||
&store,
|
||||
invalid_child,
|
||||
"cutoff byte offset is past the source rollout",
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
async fn assert_invalid_lineage(store: &LocalThreadStore, thread_id: ThreadId, detail: &str) {
|
||||
let err = store
|
||||
.load_latest_model_context(LoadThreadHistoryParams {
|
||||
thread_id,
|
||||
include_archived: false,
|
||||
})
|
||||
.await
|
||||
.expect_err("lineage should be invalid");
|
||||
assert!(err.to_string().contains(detail), "{err}");
|
||||
}
|
||||
|
||||
fn write_rollout(
|
||||
home: &Path,
|
||||
thread_id: ThreadId,
|
||||
history_base: Option<HistoryPosition>,
|
||||
next_ordinal: u64,
|
||||
) -> std::path::PathBuf {
|
||||
write_rollout_under(
|
||||
home.join("sessions/2026/07/16"),
|
||||
thread_id,
|
||||
history_base,
|
||||
next_ordinal,
|
||||
)
|
||||
}
|
||||
|
||||
fn write_rollout_under(
|
||||
directory: std::path::PathBuf,
|
||||
thread_id: ThreadId,
|
||||
history_base: Option<HistoryPosition>,
|
||||
next_ordinal: u64,
|
||||
) -> std::path::PathBuf {
|
||||
fs::create_dir_all(directory.as_path()).expect("create rollout directory");
|
||||
let path = directory.join(format!("rollout-2026-07-16T00-00-00-{thread_id}.jsonl"));
|
||||
let initial_ordinal = history_base.map_or(0, |base| base.end_ordinal_exclusive);
|
||||
let mut lines = vec![rollout_line(
|
||||
initial_ordinal,
|
||||
RolloutItem::SessionMeta(Box::new(SessionMetaLine {
|
||||
meta: SessionMeta {
|
||||
session_id: thread_id.into(),
|
||||
id: thread_id,
|
||||
history_mode: ThreadHistoryMode::Paginated,
|
||||
history_base,
|
||||
..SessionMeta::default()
|
||||
},
|
||||
git: None,
|
||||
})),
|
||||
)];
|
||||
for offset in 1..next_ordinal {
|
||||
let ordinal = initial_ordinal
|
||||
.checked_add(offset)
|
||||
.expect("fixture ordinal");
|
||||
lines.push(rollout_line(
|
||||
ordinal,
|
||||
RolloutItem::EventMsg(codex_protocol::protocol::EventMsg::ShutdownComplete),
|
||||
));
|
||||
}
|
||||
fs::write(path.as_path(), format!("{}\n", lines.join("\n"))).expect("write rollout");
|
||||
path
|
||||
}
|
||||
|
||||
fn rollout_line(ordinal: u64, item: RolloutItem) -> String {
|
||||
serde_json::to_string(&RolloutLine {
|
||||
timestamp: "2026-07-16T00:00:00.000Z".to_string(),
|
||||
ordinal: Some(ordinal),
|
||||
item,
|
||||
})
|
||||
.expect("serialize rollout line")
|
||||
}
|
||||
|
||||
fn history_position(
|
||||
path: &Path,
|
||||
thread_id: ThreadId,
|
||||
end_ordinal_exclusive: u64,
|
||||
) -> HistoryPosition {
|
||||
HistoryPosition {
|
||||
thread_id,
|
||||
end_ordinal_exclusive,
|
||||
end_byte_offset: rollout_end_byte_offset(path, end_ordinal_exclusive),
|
||||
}
|
||||
}
|
||||
|
||||
fn rollout_end_byte_offset(path: &Path, end_ordinal_exclusive: u64) -> u64 {
|
||||
let bytes = fs::read(path).expect("read rollout");
|
||||
let end_byte_offset = bytes
|
||||
.split_inclusive(|byte| *byte == b'\n')
|
||||
.take_while(|line| {
|
||||
codex_rollout::parse_rollout_line_bytes(line)
|
||||
.expect("parse rollout fixture")
|
||||
.ordinal
|
||||
.expect("paginated rollout ordinal")
|
||||
< end_ordinal_exclusive
|
||||
})
|
||||
.map(<[u8]>::len)
|
||||
.sum::<usize>();
|
||||
u64::try_from(end_byte_offset).expect("rollout byte offset fits u64")
|
||||
}
|
||||
|
||||
fn unchecked_history_position(thread_id: ThreadId, end_ordinal_exclusive: u64) -> HistoryPosition {
|
||||
HistoryPosition {
|
||||
thread_id,
|
||||
end_ordinal_exclusive,
|
||||
end_byte_offset: 0,
|
||||
}
|
||||
}
|
||||
1442
codex-rs/thread-store/src/local/rollout_migration.rs
Normal file
1442
codex-rs/thread-store/src/local/rollout_migration.rs
Normal file
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,510 @@
|
||||
//! Replays normalized legacy rollout records into canonical paginated JSONL.
|
||||
//!
|
||||
//! `line_parser` makes old JSON shapes parseable, `legacy_event` converts obsolete completion
|
||||
//! events into modern turn items. Rollback planning happens before this writer sees a record, so
|
||||
//! this module only assigns stable ordinals, keeps `SessionMeta` at ordinal zero, and emits the
|
||||
//! already-selected surviving history.
|
||||
//!
|
||||
//! The goal is to preserve the model-visible conversation, not to preserve every legacy record
|
||||
//! byte-for-byte. Filesystem publishing and SQLite projection intentionally live outside this
|
||||
//! module.
|
||||
|
||||
use chrono::DateTime;
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::items::ReasoningItem;
|
||||
use codex_protocol::items::TurnItem;
|
||||
use codex_protocol::items::parse_hook_prompt_message;
|
||||
use codex_protocol::models::ResponseItem;
|
||||
use codex_protocol::protocol::EventMsg;
|
||||
use codex_protocol::protocol::ItemCompletedEvent;
|
||||
use codex_protocol::protocol::ThreadHistoryMode;
|
||||
use codex_protocol::protocol::TurnCompleteEvent;
|
||||
use codex_protocol::protocol::TurnStartedEvent;
|
||||
use codex_rollout::RolloutItem;
|
||||
use codex_rollout::RolloutLine;
|
||||
use std::borrow::Cow;
|
||||
use std::collections::HashSet;
|
||||
use tokio::fs::File;
|
||||
use tokio::io::AsyncWriteExt;
|
||||
use tokio::io::BufWriter;
|
||||
|
||||
use super::legacy_event;
|
||||
use super::migration_error;
|
||||
use crate::ThreadStoreResult;
|
||||
|
||||
#[derive(Clone)]
|
||||
struct ActiveTurn {
|
||||
id: String,
|
||||
explicit: bool,
|
||||
saw_user: bool,
|
||||
}
|
||||
|
||||
enum ReasoningTextKind {
|
||||
Summary,
|
||||
Raw,
|
||||
}
|
||||
|
||||
pub(super) struct LegacyRolloutCanonicalizer {
|
||||
thread_id: ThreadId,
|
||||
next_ordinal: u64,
|
||||
next_item_index: u64,
|
||||
output_byte_offset: u64,
|
||||
bytes_written: u64,
|
||||
source_line_index: u64,
|
||||
active_turn: Option<ActiveTurn>,
|
||||
known_turn_ids: HashSet<String>,
|
||||
reasoning: Option<ReasoningItem>,
|
||||
}
|
||||
|
||||
impl LegacyRolloutCanonicalizer {
|
||||
pub(super) fn new(thread_id: ThreadId) -> Self {
|
||||
Self {
|
||||
thread_id,
|
||||
next_ordinal: 0,
|
||||
next_item_index: 1,
|
||||
output_byte_offset: 0,
|
||||
bytes_written: 0,
|
||||
source_line_index: 0,
|
||||
active_turn: None,
|
||||
known_turn_ids: HashSet::new(),
|
||||
reasoning: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn next_ordinal(&self) -> u64 {
|
||||
self.next_ordinal
|
||||
}
|
||||
|
||||
pub(super) fn output_byte_offset(&self) -> u64 {
|
||||
self.output_byte_offset
|
||||
}
|
||||
|
||||
pub(super) async fn write_head_session_meta(
|
||||
&mut self,
|
||||
line: RolloutLine,
|
||||
writer: &mut BufWriter<File>,
|
||||
) -> ThreadStoreResult<u64> {
|
||||
let timestamp = line.timestamp;
|
||||
let RolloutItem::SessionMeta(mut metadata) = line.item else {
|
||||
return Err(migration_error("canonical session metadata is missing"));
|
||||
};
|
||||
if metadata.meta.id != self.thread_id {
|
||||
return Err(migration_error("rollout metadata thread id changed"));
|
||||
}
|
||||
metadata.meta.history_mode = ThreadHistoryMode::Paginated;
|
||||
metadata.meta.history_base = None;
|
||||
metadata.meta.subagent_history_start_ordinal = None;
|
||||
|
||||
let bytes_before = self.bytes_written;
|
||||
self.write_item(writer, ×tamp, RolloutItem::SessionMeta(metadata))
|
||||
.await?;
|
||||
Ok(self.bytes_written - bytes_before)
|
||||
}
|
||||
|
||||
pub(super) async fn process_line(
|
||||
&mut self,
|
||||
line: RolloutLine,
|
||||
writer: &mut BufWriter<File>,
|
||||
) -> ThreadStoreResult<u64> {
|
||||
let source_index = self.source_line_index;
|
||||
self.source_line_index = self
|
||||
.source_line_index
|
||||
.checked_add(1)
|
||||
.ok_or_else(|| migration_error("legacy rollout line index overflow"))?;
|
||||
let timestamp = line.timestamp;
|
||||
let bytes_before = self.bytes_written;
|
||||
match line.item {
|
||||
RolloutItem::SessionMeta(_) => return Ok(0),
|
||||
RolloutItem::ResponseItem(response) => {
|
||||
if matches!(&response.item, ResponseItem::Other) {
|
||||
return Err(migration_error(
|
||||
"legacy rollout contains an unsupported response item",
|
||||
));
|
||||
}
|
||||
let hook = match &response.item {
|
||||
ResponseItem::Message {
|
||||
role, content, id, ..
|
||||
} if role == "user" => parse_hook_prompt_message(id.as_deref(), content),
|
||||
_ => None,
|
||||
};
|
||||
self.write_item(writer, ×tamp, RolloutItem::ResponseItem(response))
|
||||
.await?;
|
||||
if let Some(hook) = hook {
|
||||
self.ensure_turn(writer, ×tamp, source_index).await?;
|
||||
self.reasoning = None;
|
||||
self.write_completed_item(writer, ×tamp, TurnItem::HookPrompt(hook))
|
||||
.await?;
|
||||
}
|
||||
}
|
||||
RolloutItem::EventMsg(EventMsg::ThreadRolledBack(_)) => {
|
||||
return Err(migration_error(
|
||||
"rollback marker reached canonical writer without a rollback plan",
|
||||
));
|
||||
}
|
||||
RolloutItem::EventMsg(EventMsg::TurnStarted(event)) => {
|
||||
self.finish_implicit_turn(writer, ×tamp).await?;
|
||||
self.known_turn_ids.insert(event.turn_id.clone());
|
||||
self.active_turn = Some(ActiveTurn {
|
||||
id: event.turn_id.clone(),
|
||||
explicit: true,
|
||||
saw_user: false,
|
||||
});
|
||||
self.reasoning = None;
|
||||
self.write_item(
|
||||
writer,
|
||||
×tamp,
|
||||
RolloutItem::EventMsg(EventMsg::TurnStarted(event)),
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
RolloutItem::EventMsg(EventMsg::TurnComplete(event)) => {
|
||||
self.reasoning = None;
|
||||
if self
|
||||
.active_turn
|
||||
.as_ref()
|
||||
.is_some_and(|turn| turn.id == event.turn_id)
|
||||
{
|
||||
self.active_turn = None;
|
||||
}
|
||||
self.write_item(
|
||||
writer,
|
||||
×tamp,
|
||||
RolloutItem::EventMsg(EventMsg::TurnComplete(event)),
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
RolloutItem::EventMsg(EventMsg::TurnAborted(mut event)) => {
|
||||
if event.turn_id.is_none() {
|
||||
event.turn_id = self.active_turn.as_ref().map(|turn| turn.id.clone());
|
||||
}
|
||||
if self
|
||||
.active_turn
|
||||
.as_ref()
|
||||
.is_some_and(|turn| event.turn_id.as_deref() == Some(turn.id.as_str()))
|
||||
{
|
||||
self.active_turn = None;
|
||||
}
|
||||
self.reasoning = None;
|
||||
self.write_item(
|
||||
writer,
|
||||
×tamp,
|
||||
RolloutItem::EventMsg(EventMsg::TurnAborted(event)),
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
RolloutItem::EventMsg(EventMsg::UserMessage(event)) => {
|
||||
if self
|
||||
.active_turn
|
||||
.as_ref()
|
||||
.is_some_and(|turn| !turn.explicit && turn.saw_user)
|
||||
{
|
||||
self.finish_implicit_turn(writer, ×tamp).await?;
|
||||
}
|
||||
self.ensure_turn(writer, ×tamp, source_index).await?;
|
||||
let item = legacy_event::user_message_item(event, &mut || self.next_item_id())?;
|
||||
if let Some(turn) = self.active_turn.as_mut() {
|
||||
turn.saw_user = true;
|
||||
}
|
||||
self.reasoning = None;
|
||||
self.write_completed_item(writer, ×tamp, item).await?;
|
||||
}
|
||||
RolloutItem::EventMsg(EventMsg::AgentReasoning(event)) => {
|
||||
self.write_reasoning(
|
||||
writer,
|
||||
×tamp,
|
||||
source_index,
|
||||
event.text,
|
||||
ReasoningTextKind::Summary,
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
RolloutItem::EventMsg(EventMsg::AgentReasoningRawContent(event)) => {
|
||||
self.write_reasoning(
|
||||
writer,
|
||||
×tamp,
|
||||
source_index,
|
||||
event.text,
|
||||
ReasoningTextKind::Raw,
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
RolloutItem::EventMsg(EventMsg::ItemCompleted(mut event)) => {
|
||||
event.thread_id = self.thread_id;
|
||||
self.reasoning = None;
|
||||
self.write_item(
|
||||
writer,
|
||||
×tamp,
|
||||
RolloutItem::EventMsg(EventMsg::ItemCompleted(event)),
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
RolloutItem::EventMsg(event) => {
|
||||
if let Some((item, turn_id)) =
|
||||
legacy_event::completed_item(&event, &mut || self.next_item_id())?
|
||||
{
|
||||
match turn_id {
|
||||
Some(turn_id)
|
||||
if self
|
||||
.active_turn
|
||||
.as_ref()
|
||||
.is_some_and(|turn| turn.id.as_str() != turn_id.as_str()) =>
|
||||
{
|
||||
self.write_completed_item_to_turn(writer, ×tamp, turn_id, item)
|
||||
.await?;
|
||||
}
|
||||
Some(turn_id) => {
|
||||
if self.active_turn.is_none()
|
||||
&& self.known_turn_ids.contains(turn_id.as_str())
|
||||
{
|
||||
self.reasoning = None;
|
||||
self.write_completed_item_to_turn(
|
||||
writer, ×tamp, turn_id, item,
|
||||
)
|
||||
.await?;
|
||||
} else if self.active_turn.is_none() {
|
||||
self.start_implicit_turn(writer, ×tamp, turn_id)
|
||||
.await?;
|
||||
self.reasoning = None;
|
||||
self.write_completed_item(writer, ×tamp, item).await?;
|
||||
} else {
|
||||
self.reasoning = None;
|
||||
self.write_completed_item(writer, ×tamp, item).await?;
|
||||
}
|
||||
}
|
||||
None => {
|
||||
self.ensure_turn(writer, ×tamp, source_index).await?;
|
||||
self.reasoning = None;
|
||||
self.write_completed_item(writer, ×tamp, item).await?;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
let item = RolloutItem::EventMsg(event);
|
||||
self.write_item(writer, ×tamp, item).await?;
|
||||
}
|
||||
}
|
||||
item @ RolloutItem::InterAgentCommunication(_) => {
|
||||
self.write_item(writer, ×tamp, item).await?;
|
||||
}
|
||||
item @ RolloutItem::Compacted(_) => {
|
||||
self.write_item(writer, ×tamp, item).await?;
|
||||
}
|
||||
item @ (RolloutItem::InterAgentCommunicationMetadata { .. }
|
||||
| RolloutItem::TurnContext(_)
|
||||
| RolloutItem::DynamicToolsUpdated { .. }
|
||||
| RolloutItem::TokenUsageRecord(_)
|
||||
| RolloutItem::RealtimeItem(_)
|
||||
| RolloutItem::RetainedContext(_)
|
||||
| RolloutItem::SecurityRiskScore(_)
|
||||
| RolloutItem::WorldState(_)) => {
|
||||
self.write_item(writer, ×tamp, item).await?;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(self.bytes_written - bytes_before)
|
||||
}
|
||||
|
||||
pub(super) async fn finish(
|
||||
&mut self,
|
||||
writer: &mut BufWriter<File>,
|
||||
timestamp: &str,
|
||||
) -> ThreadStoreResult<u64> {
|
||||
let bytes_before = self.bytes_written;
|
||||
self.finish_implicit_turn(writer, timestamp).await?;
|
||||
Ok(self.bytes_written - bytes_before)
|
||||
}
|
||||
|
||||
async fn ensure_turn(
|
||||
&mut self,
|
||||
writer: &mut BufWriter<File>,
|
||||
timestamp: &str,
|
||||
source_index: u64,
|
||||
) -> ThreadStoreResult<()> {
|
||||
if self.active_turn.is_some() {
|
||||
return Ok(());
|
||||
}
|
||||
let turn_id = format!("rollout-{source_index}");
|
||||
self.start_implicit_turn(writer, timestamp, turn_id).await
|
||||
}
|
||||
|
||||
async fn start_implicit_turn(
|
||||
&mut self,
|
||||
writer: &mut BufWriter<File>,
|
||||
timestamp: &str,
|
||||
turn_id: String,
|
||||
) -> ThreadStoreResult<()> {
|
||||
self.active_turn = Some(ActiveTurn {
|
||||
id: turn_id.clone(),
|
||||
explicit: false,
|
||||
saw_user: false,
|
||||
});
|
||||
self.known_turn_ids.insert(turn_id.clone());
|
||||
self.reasoning = None;
|
||||
let started_at = DateTime::parse_from_rfc3339(timestamp)
|
||||
.map_err(migration_error)?
|
||||
.timestamp();
|
||||
self.write_item(
|
||||
writer,
|
||||
timestamp,
|
||||
RolloutItem::EventMsg(EventMsg::TurnStarted(TurnStartedEvent {
|
||||
turn_attribution: None,
|
||||
turn_id,
|
||||
root_turn_id: None,
|
||||
trace_id: None,
|
||||
started_at: Some(started_at),
|
||||
model_context_window: None,
|
||||
collaboration_mode_kind: Default::default(),
|
||||
})),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn finish_implicit_turn(
|
||||
&mut self,
|
||||
writer: &mut BufWriter<File>,
|
||||
timestamp: &str,
|
||||
) -> ThreadStoreResult<()> {
|
||||
let Some(turn) = self.active_turn.as_ref() else {
|
||||
return Ok(());
|
||||
};
|
||||
if turn.explicit {
|
||||
return Ok(());
|
||||
}
|
||||
let turn_id = turn.id.clone();
|
||||
self.active_turn = None;
|
||||
self.reasoning = None;
|
||||
self.write_item(
|
||||
writer,
|
||||
timestamp,
|
||||
RolloutItem::EventMsg(EventMsg::TurnComplete(TurnCompleteEvent {
|
||||
root_turn_id: None,
|
||||
turn_id,
|
||||
last_agent_message: None,
|
||||
error: None,
|
||||
started_at: None,
|
||||
completed_at: Some(
|
||||
DateTime::parse_from_rfc3339(timestamp)
|
||||
.map_err(migration_error)?
|
||||
.timestamp(),
|
||||
),
|
||||
duration_ms: None,
|
||||
time_to_first_token_ms: None,
|
||||
})),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn write_completed_item(
|
||||
&mut self,
|
||||
writer: &mut BufWriter<File>,
|
||||
timestamp: &str,
|
||||
item: TurnItem,
|
||||
) -> ThreadStoreResult<()> {
|
||||
let turn_id = self
|
||||
.active_turn
|
||||
.as_ref()
|
||||
.map(|turn| turn.id.clone())
|
||||
.ok_or_else(|| migration_error("completed rollout item has no active turn"))?;
|
||||
self.write_completed_item_to_turn(writer, timestamp, turn_id, item)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn write_completed_item_to_turn(
|
||||
&mut self,
|
||||
writer: &mut BufWriter<File>,
|
||||
timestamp: &str,
|
||||
turn_id: String,
|
||||
item: TurnItem,
|
||||
) -> ThreadStoreResult<()> {
|
||||
let completed_at_ms = DateTime::parse_from_rfc3339(timestamp)
|
||||
.map_err(migration_error)?
|
||||
.timestamp_millis();
|
||||
self.write_item(
|
||||
writer,
|
||||
timestamp,
|
||||
RolloutItem::EventMsg(EventMsg::ItemCompleted(ItemCompletedEvent {
|
||||
content_token_count: None,
|
||||
thread_id: self.thread_id,
|
||||
turn_id,
|
||||
item,
|
||||
started_at_ms: None,
|
||||
completed_at_ms,
|
||||
})),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn write_reasoning(
|
||||
&mut self,
|
||||
writer: &mut BufWriter<File>,
|
||||
timestamp: &str,
|
||||
source_index: u64,
|
||||
text: String,
|
||||
kind: ReasoningTextKind,
|
||||
) -> ThreadStoreResult<()> {
|
||||
if text.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
self.ensure_turn(writer, timestamp, source_index).await?;
|
||||
let mut item = match self.reasoning.take() {
|
||||
Some(item) => item,
|
||||
None => ReasoningItem {
|
||||
id: self.next_item_id()?,
|
||||
summary_text: Vec::new(),
|
||||
raw_content: Vec::new(),
|
||||
},
|
||||
};
|
||||
match kind {
|
||||
ReasoningTextKind::Summary => item.summary_text.push(text),
|
||||
ReasoningTextKind::Raw => item.raw_content.push(text),
|
||||
}
|
||||
self.reasoning = Some(item.clone());
|
||||
self.write_completed_item(writer, timestamp, TurnItem::Reasoning(item))
|
||||
.await
|
||||
}
|
||||
|
||||
async fn write_item(
|
||||
&mut self,
|
||||
writer: &mut BufWriter<File>,
|
||||
timestamp: &str,
|
||||
item: RolloutItem,
|
||||
) -> ThreadStoreResult<()> {
|
||||
let item = match codex_rollout::persisted_rollout_item(&item, ThreadHistoryMode::Paginated)
|
||||
{
|
||||
Some(Cow::Borrowed(_)) => item,
|
||||
Some(Cow::Owned(item)) => item,
|
||||
None => return Ok(()),
|
||||
};
|
||||
let mut bytes = serde_json::to_vec(&RolloutLine {
|
||||
timestamp: timestamp.to_string(),
|
||||
ordinal: Some(self.next_ordinal),
|
||||
item,
|
||||
})
|
||||
.map_err(migration_error)?;
|
||||
bytes.push(b'\n');
|
||||
writer.write_all(&bytes).await.map_err(migration_error)?;
|
||||
let byte_count = u64::try_from(bytes.len())
|
||||
.map_err(|_| migration_error("rollout record exceeds addressable size"))?;
|
||||
self.output_byte_offset = self
|
||||
.output_byte_offset
|
||||
.checked_add(byte_count)
|
||||
.ok_or_else(|| migration_error("paginated rollout byte offset overflow"))?;
|
||||
self.bytes_written = self
|
||||
.bytes_written
|
||||
.checked_add(byte_count)
|
||||
.ok_or_else(|| migration_error("paginated rollout byte count overflow"))?;
|
||||
self.next_ordinal = self
|
||||
.next_ordinal
|
||||
.checked_add(1)
|
||||
.ok_or_else(|| migration_error("paginated rollout ordinal overflow"))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn next_item_id(&mut self) -> ThreadStoreResult<String> {
|
||||
let item_id = format!("item-{}", self.next_item_index);
|
||||
self.next_item_index = self
|
||||
.next_item_index
|
||||
.checked_add(1)
|
||||
.ok_or_else(|| migration_error("legacy rollout item id overflow"))?;
|
||||
Ok(item_id)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,339 @@
|
||||
//! Converts legacy persisted events into modern paginated turn items.
|
||||
//!
|
||||
//! Legacy rollouts persisted events like `ExecCommandEnd`, `PatchApplyEnd`, and
|
||||
//! `McpToolCallEnd`. Paginated history instead persists `ItemCompleted(item)` records containing
|
||||
//! canonical `TurnItem`s.
|
||||
//!
|
||||
//! This module owns that old-event -> new-item mapping, including stable synthesized item IDs.
|
||||
//! It intentionally stays separate from live thread-history reduction because migration needs a
|
||||
//! frozen adapter for historical rollout payloads.
|
||||
|
||||
use codex_extension_items::ExtensionItem;
|
||||
use codex_extension_items::image_generation::ImageGenerationItem;
|
||||
use codex_protocol::items::AgentMessageContent;
|
||||
use codex_protocol::items::AgentMessageItem;
|
||||
use codex_protocol::items::CommandExecutionItem;
|
||||
use codex_protocol::items::ContextCompactionItem;
|
||||
use codex_protocol::items::DynamicToolCallItem;
|
||||
use codex_protocol::items::DynamicToolCallStatus;
|
||||
use codex_protocol::items::EnteredReviewModeItem;
|
||||
use codex_protocol::items::ExitedReviewModeItem;
|
||||
use codex_protocol::items::FileChangeItem;
|
||||
use codex_protocol::items::McpToolCallError;
|
||||
use codex_protocol::items::McpToolCallItem;
|
||||
use codex_protocol::items::McpToolCallStatus;
|
||||
use codex_protocol::items::SubAgentActivityItem;
|
||||
use codex_protocol::items::TurnItem;
|
||||
use codex_protocol::items::UserMessageItem;
|
||||
use codex_protocol::items::WebSearchItem;
|
||||
use codex_protocol::models::AudioReference;
|
||||
use codex_protocol::models::ImageReference;
|
||||
use codex_protocol::protocol::EventMsg;
|
||||
use codex_protocol::protocol::UserMessageAudioKind;
|
||||
use codex_protocol::protocol::UserMessageEvent;
|
||||
use codex_protocol::protocol::UserMessageImageKind;
|
||||
use codex_protocol::user_input::UserInput;
|
||||
|
||||
use crate::ThreadStoreResult;
|
||||
|
||||
pub(super) fn user_message_item(
|
||||
event: UserMessageEvent,
|
||||
next_item_id: &mut impl FnMut() -> ThreadStoreResult<String>,
|
||||
) -> ThreadStoreResult<TurnItem> {
|
||||
let mut content = Vec::new();
|
||||
let has_image_order = event.has_complete_image_order();
|
||||
let has_audio_order = event.has_complete_audio_order();
|
||||
if !event.message.trim().is_empty() {
|
||||
content.push(UserInput::Text {
|
||||
text: event.message,
|
||||
text_elements: event.text_elements,
|
||||
});
|
||||
}
|
||||
if has_image_order {
|
||||
let mut inline_index = 0;
|
||||
let mut file_index = 0;
|
||||
for image_kind in event.image_order {
|
||||
let (image, detail) = match image_kind {
|
||||
UserMessageImageKind::Inline => {
|
||||
let Some(image_url) = event
|
||||
.images
|
||||
.as_deref()
|
||||
.and_then(|images| images.get(inline_index))
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let detail = event.image_details.get(inline_index).copied().flatten();
|
||||
inline_index += 1;
|
||||
(
|
||||
ImageReference::Inline {
|
||||
image_url: image_url.clone(),
|
||||
},
|
||||
detail,
|
||||
)
|
||||
}
|
||||
UserMessageImageKind::File => {
|
||||
let Some(file_id) = event
|
||||
.file_ids
|
||||
.as_deref()
|
||||
.and_then(|file_ids| file_ids.get(file_index))
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let detail = event.file_id_details.get(file_index).copied().flatten();
|
||||
file_index += 1;
|
||||
(
|
||||
ImageReference::File {
|
||||
file_id: file_id.clone(),
|
||||
},
|
||||
detail,
|
||||
)
|
||||
}
|
||||
};
|
||||
content.push(UserInput::Image { image, detail });
|
||||
}
|
||||
} else if let Some(images) = event.images {
|
||||
for (index, image_url) in images.into_iter().enumerate() {
|
||||
content.push(UserInput::Image {
|
||||
image: ImageReference::Inline { image_url },
|
||||
detail: event.image_details.get(index).copied().flatten(),
|
||||
});
|
||||
}
|
||||
}
|
||||
if !has_image_order && let Some(file_ids) = event.file_ids {
|
||||
for (index, file_id) in file_ids.into_iter().enumerate() {
|
||||
content.push(UserInput::Image {
|
||||
image: ImageReference::File { file_id },
|
||||
detail: event.file_id_details.get(index).copied().flatten(),
|
||||
});
|
||||
}
|
||||
}
|
||||
for (index, path) in event.local_images.into_iter().enumerate() {
|
||||
content.push(UserInput::LocalImage {
|
||||
path,
|
||||
detail: event.local_image_details.get(index).copied().flatten(),
|
||||
});
|
||||
}
|
||||
if has_audio_order {
|
||||
let mut inline_audio = event.audio.unwrap_or_default().into_iter();
|
||||
let mut file_audio = event.audio_references.unwrap_or_default().into_iter();
|
||||
for audio_kind in event.audio_order {
|
||||
let audio = match audio_kind {
|
||||
UserMessageAudioKind::Inline => inline_audio
|
||||
.next()
|
||||
.map(|audio_url| AudioReference::Inline { audio_url }),
|
||||
UserMessageAudioKind::File => file_audio.next(),
|
||||
};
|
||||
if let Some(audio) = audio {
|
||||
content.push(UserInput::Audio { audio });
|
||||
}
|
||||
}
|
||||
} else if let Some(audio) = event.audio_references {
|
||||
content.extend(audio.into_iter().map(|audio| UserInput::Audio { audio }));
|
||||
} else if let Some(audio) = event.audio {
|
||||
content.extend(audio.into_iter().map(|audio_url| UserInput::Audio {
|
||||
audio: AudioReference::Inline { audio_url },
|
||||
}));
|
||||
}
|
||||
content.extend(
|
||||
event
|
||||
.local_audio
|
||||
.into_iter()
|
||||
.map(|path| UserInput::LocalAudio { path }),
|
||||
);
|
||||
Ok(TurnItem::UserMessage(UserMessageItem {
|
||||
id: next_item_id()?,
|
||||
client_id: event.client_id,
|
||||
content,
|
||||
}))
|
||||
}
|
||||
|
||||
/// Convert historical completion events into the canonical completed-item payloads
|
||||
/// that paginated rollouts persist. This deliberately remains a frozen migration
|
||||
/// adapter rather than sharing the live thread-history reducer: migration must
|
||||
/// preserve historical payloads while synthesizing stable item and turn IDs.
|
||||
pub(super) fn completed_item(
|
||||
event: &EventMsg,
|
||||
next_item_id: &mut impl FnMut() -> ThreadStoreResult<String>,
|
||||
) -> ThreadStoreResult<Option<(TurnItem, Option<String>)>> {
|
||||
let result = match event {
|
||||
EventMsg::AgentMessage(event) if !event.message.is_empty() => Some((
|
||||
TurnItem::AgentMessage(AgentMessageItem {
|
||||
moderation: event.moderation.as_ref().map(|decision| {
|
||||
codex_protocol::items::AgentMessageModeration {
|
||||
moderated: decision.moderated,
|
||||
display: decision.display.clone(),
|
||||
}
|
||||
}),
|
||||
id: event
|
||||
.moderation
|
||||
.as_ref()
|
||||
.map_or(next_item_id()?, |decision| decision.item_id.clone()),
|
||||
content: vec![AgentMessageContent::Text {
|
||||
text: event.message.clone(),
|
||||
}],
|
||||
phase: event.phase.clone(),
|
||||
memory_citation: event.memory_citation.clone(),
|
||||
delivery: event.delivery,
|
||||
questions: event.questions.clone(),
|
||||
}),
|
||||
None,
|
||||
)),
|
||||
EventMsg::PatchApplyEnd(event) => Some((
|
||||
TurnItem::FileChange(FileChangeItem {
|
||||
id: event.call_id.clone(),
|
||||
changes: event.changes.clone(),
|
||||
status: Some(event.status.clone()),
|
||||
auto_approved: None,
|
||||
stdout: (!event.stdout.is_empty()).then(|| event.stdout.clone()),
|
||||
stderr: (!event.stderr.is_empty()).then(|| event.stderr.clone()),
|
||||
}),
|
||||
(!event.turn_id.is_empty()).then(|| event.turn_id.clone()),
|
||||
)),
|
||||
EventMsg::McpToolCallEnd(event) => {
|
||||
let (result, error) = match &event.result {
|
||||
Ok(result) => (Some(result.clone()), None),
|
||||
Err(message) => (
|
||||
None,
|
||||
Some(McpToolCallError {
|
||||
message: message.clone(),
|
||||
}),
|
||||
),
|
||||
};
|
||||
Some((
|
||||
TurnItem::McpToolCall(McpToolCallItem {
|
||||
id: event.call_id.clone(),
|
||||
server: event.invocation.server.clone(),
|
||||
tool: event.invocation.tool.clone(),
|
||||
arguments: event
|
||||
.invocation
|
||||
.arguments
|
||||
.clone()
|
||||
.unwrap_or(serde_json::Value::Null),
|
||||
connector_id: event.connector_id.clone(),
|
||||
mcp_app_resource_uri: event.mcp_app_resource_uri.clone(),
|
||||
mcp_app_ui: event.mcp_app_ui.clone(),
|
||||
link_id: event.link_id.clone(),
|
||||
app_name: event.app_name.clone(),
|
||||
action_name: event.action_name.clone(),
|
||||
plugin_id: event.plugin_id.clone(),
|
||||
read_only_hint: event.read_only_hint,
|
||||
status: if event.is_success() {
|
||||
McpToolCallStatus::Completed
|
||||
} else {
|
||||
McpToolCallStatus::Failed
|
||||
},
|
||||
result,
|
||||
error,
|
||||
duration: Some(event.duration),
|
||||
}),
|
||||
(!event.turn_id.is_empty()).then(|| event.turn_id.clone()),
|
||||
))
|
||||
}
|
||||
EventMsg::WebSearchEnd(event) => Some((
|
||||
TurnItem::WebSearch(WebSearchItem {
|
||||
id: event.call_id.clone(),
|
||||
query: event.query.clone(),
|
||||
action: event.action.clone(),
|
||||
results: event.results.clone(),
|
||||
}),
|
||||
None,
|
||||
)),
|
||||
EventMsg::ImageGenerationEnd(event) => Some((
|
||||
TurnItem::Extension(ExtensionItem::ImageGeneration(ImageGenerationItem {
|
||||
id: event.call_id.clone(),
|
||||
status: event.status.clone(),
|
||||
revised_prompt: event.revised_prompt.clone(),
|
||||
image: event.image.clone(),
|
||||
transparent_background: event.transparent_background,
|
||||
failure: event.failure.clone(),
|
||||
saved_path: event.saved_path.clone(),
|
||||
input_images: event.input_images.clone(),
|
||||
imagegen_request_id: None,
|
||||
generation_id: event.generation_id.clone(),
|
||||
})),
|
||||
None,
|
||||
)),
|
||||
EventMsg::ContextCompacted(_) => Some((
|
||||
TurnItem::ContextCompaction(ContextCompactionItem {
|
||||
id: next_item_id()?,
|
||||
}),
|
||||
None,
|
||||
)),
|
||||
EventMsg::EnteredReviewMode(event) => Some((
|
||||
TurnItem::EnteredReviewMode(EnteredReviewModeItem {
|
||||
id: match event.item_id.clone() {
|
||||
Some(id) => id,
|
||||
None => next_item_id()?,
|
||||
},
|
||||
target: event.target.clone(),
|
||||
user_facing_hint: event
|
||||
.user_facing_hint
|
||||
.clone()
|
||||
.unwrap_or_else(|| "Review requested.".to_string()),
|
||||
}),
|
||||
event.turn_id.clone(),
|
||||
)),
|
||||
EventMsg::ExitedReviewMode(event) => Some((
|
||||
TurnItem::ExitedReviewMode(ExitedReviewModeItem {
|
||||
id: match event.item_id.clone() {
|
||||
Some(id) => id,
|
||||
None => next_item_id()?,
|
||||
},
|
||||
review_output: event.review_output.clone(),
|
||||
}),
|
||||
event.turn_id.clone(),
|
||||
)),
|
||||
EventMsg::SubAgentActivity(event) => Some((
|
||||
TurnItem::SubAgentActivity(SubAgentActivityItem {
|
||||
model: event.model.clone(),
|
||||
reasoning_effort: event.reasoning_effort.clone(),
|
||||
id: event.event_id.clone(),
|
||||
kind: event.kind,
|
||||
agent_thread_id: event.agent_thread_id,
|
||||
agent_path: event.agent_path.clone(),
|
||||
}),
|
||||
None,
|
||||
)),
|
||||
EventMsg::ExecCommandEnd(event) => Some((
|
||||
TurnItem::CommandExecution(CommandExecutionItem {
|
||||
model_context: None,
|
||||
sandbox_type: None,
|
||||
id: event.call_id.clone(),
|
||||
plugin_id: event.plugin_id.clone(),
|
||||
script_path: event.script_path.clone(),
|
||||
process_id: event.process_id.clone(),
|
||||
command: event.command.clone(),
|
||||
cwd: event.cwd.clone(),
|
||||
parsed_cmd: event.parsed_cmd.clone(),
|
||||
source: event.source,
|
||||
interaction_input: None,
|
||||
status: event.status.clone().into(),
|
||||
aggregated_output: (!event.aggregated_output.is_empty())
|
||||
.then(|| event.aggregated_output.clone()),
|
||||
exit_code: Some(event.exit_code),
|
||||
duration: Some(event.duration),
|
||||
}),
|
||||
Some(event.turn_id.clone()),
|
||||
)),
|
||||
EventMsg::DynamicToolCallResponse(event) => Some((
|
||||
TurnItem::DynamicToolCall(DynamicToolCallItem {
|
||||
id: event.call_id.clone(),
|
||||
namespace: event.namespace.clone(),
|
||||
tool: event.tool.clone(),
|
||||
arguments: event.arguments.clone(),
|
||||
status: if event.success {
|
||||
DynamicToolCallStatus::Completed
|
||||
} else {
|
||||
DynamicToolCallStatus::Failed
|
||||
},
|
||||
content_items: Some(event.content_items.clone()),
|
||||
success: Some(event.success),
|
||||
error: event.error.clone(),
|
||||
duration: Some(event.duration),
|
||||
}),
|
||||
Some(event.turn_id.clone()),
|
||||
)),
|
||||
_ => None,
|
||||
};
|
||||
Ok(result)
|
||||
}
|
||||
201
codex-rs/thread-store/src/local/rollout_migration/line_parser.rs
Normal file
201
codex-rs/thread-store/src/local/rollout_migration/line_parser.rs
Normal file
@@ -0,0 +1,201 @@
|
||||
//! Makes historical rollout JSON parse like today's protocol types.
|
||||
//!
|
||||
//! Legacy rollouts span a bunch of old wire shapes: renamed fields, old sandbox policy layouts,
|
||||
//! string timestamps, legacy command cwd paths, retired events, and payloads that only deserialize
|
||||
//! correctly after going through `serde_json::Value`.
|
||||
//!
|
||||
//! This module only applies narrowly scoped compatibility rewrites for shapes we know existed in
|
||||
//! persisted rollouts. It does not decide turn boundaries, rollback behavior, or what gets written
|
||||
//! into paginated history.
|
||||
|
||||
use chrono::DateTime;
|
||||
use codex_rollout::RolloutLine;
|
||||
use codex_utils_path_uri::LegacyAppPathString;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
use serde_json::Map;
|
||||
use serde_json::Value;
|
||||
|
||||
/// Parse one legacy rollout line after applying narrowly scoped compatibility
|
||||
/// rewrites for historical wire shapes that current protocol types no longer
|
||||
/// accept.
|
||||
pub(super) fn parse_legacy_rollout_line(bytes: &[u8]) -> Result<Option<RolloutLine>, String> {
|
||||
if bytes.iter().all(u8::is_ascii_whitespace) {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
// Deserializing through Value is intentional. Some historical numeric
|
||||
// payloads fail serde_json's streaming enum path but deserialize correctly
|
||||
// once their tagged object shape has been materialized.
|
||||
let value = serde_json::from_slice::<Value>(bytes).map_err(|error| error.to_string())?;
|
||||
parse_legacy_rollout_value(value)
|
||||
}
|
||||
|
||||
pub(super) fn parse_legacy_rollout_value(mut value: Value) -> Result<Option<RolloutLine>, String> {
|
||||
if should_skip_retired_record(&value) {
|
||||
return Ok(None);
|
||||
}
|
||||
normalize_legacy_turn_context(&mut value);
|
||||
normalize_legacy_sandbox_policy(&mut value);
|
||||
normalize_legacy_rate_limit_resets(&mut value);
|
||||
normalize_legacy_review_entry(&mut value);
|
||||
normalize_legacy_command_cwd(&mut value)?;
|
||||
codex_rollout::decode_rollout_line(value)
|
||||
.map(Some)
|
||||
.map_err(|error| error.to_string())
|
||||
}
|
||||
|
||||
fn should_skip_retired_record(value: &Value) -> bool {
|
||||
matches!(
|
||||
event_type(value),
|
||||
Some("guardian_assessment" | "thread_name_updated" | "undo_completed")
|
||||
) || (rollout_type(value) == Some("response_item")
|
||||
&& value
|
||||
.get("payload")
|
||||
.and_then(Value::as_object)
|
||||
.and_then(|payload| payload.get("type"))
|
||||
.and_then(Value::as_str)
|
||||
== Some("ghost_snapshot"))
|
||||
}
|
||||
|
||||
fn normalize_legacy_turn_context(value: &mut Value) {
|
||||
if rollout_type(value) != Some("turn_context") {
|
||||
return;
|
||||
}
|
||||
let Some(payload) = payload_object_mut(value) else {
|
||||
return;
|
||||
};
|
||||
let Some(collaboration_mode) = payload
|
||||
.get_mut("collaboration_mode")
|
||||
.and_then(Value::as_object_mut)
|
||||
else {
|
||||
return;
|
||||
};
|
||||
if collaboration_mode.contains_key("settings") {
|
||||
return;
|
||||
}
|
||||
|
||||
let mut settings = Map::new();
|
||||
for key in ["model", "reasoning_effort", "developer_instructions"] {
|
||||
if let Some(value) = collaboration_mode.get(key) {
|
||||
settings.insert(key.to_string(), value.clone());
|
||||
}
|
||||
}
|
||||
if !settings.is_empty() {
|
||||
collaboration_mode.insert("settings".to_string(), Value::Object(settings));
|
||||
}
|
||||
}
|
||||
|
||||
fn normalize_legacy_review_entry(value: &mut Value) {
|
||||
if event_type(value) != Some("entered_review_mode") {
|
||||
return;
|
||||
}
|
||||
let Some(payload) = payload_object_mut(value) else {
|
||||
return;
|
||||
};
|
||||
if payload.contains_key("target") {
|
||||
return;
|
||||
}
|
||||
let Some(prompt) = payload.get("prompt").and_then(Value::as_str) else {
|
||||
return;
|
||||
};
|
||||
payload.insert(
|
||||
"target".to_string(),
|
||||
serde_json::json!({
|
||||
"type": "custom",
|
||||
"instructions": prompt,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
fn normalize_legacy_rate_limit_resets(value: &mut Value) {
|
||||
if event_type(value) != Some("token_count") {
|
||||
return;
|
||||
}
|
||||
let Some(rate_limits) = payload_object_mut(value)
|
||||
.and_then(|payload| payload.get_mut("rate_limits"))
|
||||
.and_then(Value::as_object_mut)
|
||||
else {
|
||||
return;
|
||||
};
|
||||
for window_name in ["primary", "secondary"] {
|
||||
let Some(window) = rate_limits
|
||||
.get_mut(window_name)
|
||||
.and_then(Value::as_object_mut)
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let Some(resets_at) = window.get("resets_at").and_then(Value::as_str) else {
|
||||
continue;
|
||||
};
|
||||
let Ok(resets_at) = DateTime::parse_from_rfc3339(resets_at) else {
|
||||
continue;
|
||||
};
|
||||
window.insert("resets_at".to_string(), Value::from(resets_at.timestamp()));
|
||||
}
|
||||
}
|
||||
|
||||
fn normalize_legacy_sandbox_policy(value: &mut Value) {
|
||||
if rollout_type(value) != Some("turn_context") {
|
||||
return;
|
||||
}
|
||||
let Some(sandbox_policy) = payload_object_mut(value)
|
||||
.and_then(|payload| payload.get_mut("sandbox_policy"))
|
||||
.and_then(Value::as_object_mut)
|
||||
else {
|
||||
return;
|
||||
};
|
||||
if sandbox_policy.contains_key("type") {
|
||||
return;
|
||||
}
|
||||
if let Some(mode) = sandbox_policy.get("mode").cloned() {
|
||||
sandbox_policy.insert("type".to_string(), mode);
|
||||
}
|
||||
}
|
||||
|
||||
fn normalize_legacy_command_cwd(value: &mut Value) -> Result<(), String> {
|
||||
if !matches!(
|
||||
event_type(value),
|
||||
Some("exec_command_begin" | "exec_command_end")
|
||||
) {
|
||||
return Ok(());
|
||||
}
|
||||
let Some(payload) = payload_object_mut(value) else {
|
||||
return Ok(());
|
||||
};
|
||||
let Some(cwd) = payload.get("cwd").and_then(Value::as_str) else {
|
||||
return Ok(());
|
||||
};
|
||||
if cwd.starts_with("file:") {
|
||||
return Ok(());
|
||||
}
|
||||
let cwd = PathUri::try_from(LegacyAppPathString::from_string(cwd))
|
||||
.map_err(|error| format!("invalid legacy command cwd: {error}"))?;
|
||||
payload.insert(
|
||||
"cwd".to_string(),
|
||||
serde_json::to_value(cwd).map_err(|error| error.to_string())?,
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn rollout_type(value: &Value) -> Option<&str> {
|
||||
value.get("type").and_then(Value::as_str)
|
||||
}
|
||||
|
||||
fn event_type(value: &Value) -> Option<&str> {
|
||||
if rollout_type(value) != Some("event_msg") {
|
||||
return None;
|
||||
}
|
||||
value
|
||||
.get("payload")
|
||||
.and_then(Value::as_object)
|
||||
.and_then(|payload| payload.get("type"))
|
||||
.and_then(Value::as_str)
|
||||
}
|
||||
|
||||
fn payload_object_mut(value: &mut Value) -> Option<&mut Map<String, Value>> {
|
||||
value.get_mut("payload").and_then(Value::as_object_mut)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "line_parser_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,228 @@
|
||||
use codex_protocol::protocol::EventMsg;
|
||||
use codex_rollout::RolloutItem;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
|
||||
use super::parse_legacy_rollout_line;
|
||||
|
||||
fn line(payload_type: &str, payload: serde_json::Value) -> Vec<u8> {
|
||||
serde_json::to_vec(&json!({
|
||||
"timestamp": "2025-01-03T12:00:00Z",
|
||||
"type": payload_type,
|
||||
"payload": payload,
|
||||
}))
|
||||
.expect("serialize fixture")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_legacy_numeric_event_payloads_through_value() {
|
||||
let bytes = line(
|
||||
"event_msg",
|
||||
json!({
|
||||
"type": "token_count",
|
||||
"info": null,
|
||||
"rate_limits": {
|
||||
"primary": {
|
||||
"used_percent": 0.0,
|
||||
"window_minutes": 300,
|
||||
"resets_at": 1_770_414_841,
|
||||
},
|
||||
"secondary": {
|
||||
"used_percent": 12.5,
|
||||
"window_minutes": 10_080,
|
||||
"resets_at": 1_770_698_702,
|
||||
},
|
||||
"credits": {
|
||||
"has_credits": false,
|
||||
"unlimited": false,
|
||||
"balance": null,
|
||||
},
|
||||
"plan_type": null,
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
let parsed = parse_legacy_rollout_line(&bytes)
|
||||
.expect("parse legacy token count")
|
||||
.expect("keep legacy token count");
|
||||
assert!(matches!(
|
||||
parsed.item,
|
||||
RolloutItem::EventMsg(EventMsg::TokenCount(_))
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normalizes_legacy_rate_limit_reset_timestamps() {
|
||||
let bytes = line(
|
||||
"event_msg",
|
||||
json!({
|
||||
"type": "token_count",
|
||||
"info": null,
|
||||
"rate_limits": {
|
||||
"primary": {
|
||||
"used_percent": 2,
|
||||
"window_minutes": 300,
|
||||
"resets_at": "2025-10-19T08:51:37.876641+00:00",
|
||||
},
|
||||
"secondary": null,
|
||||
"credits": null,
|
||||
"plan_type": null,
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
let parsed = parse_legacy_rollout_line(&bytes)
|
||||
.expect("parse legacy reset timestamp")
|
||||
.expect("keep legacy token count");
|
||||
assert!(matches!(
|
||||
parsed.item,
|
||||
RolloutItem::EventMsg(EventMsg::TokenCount(_))
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normalizes_legacy_turn_context_collaboration_mode() {
|
||||
let cwd = std::env::temp_dir().to_string_lossy().into_owned();
|
||||
let bytes = line(
|
||||
"turn_context",
|
||||
json!({
|
||||
"cwd": cwd,
|
||||
"approval_policy": "never",
|
||||
"sandbox_policy": {"type": "danger-full-access"},
|
||||
"model": "gpt-test",
|
||||
"personality": null,
|
||||
"collaboration_mode": {
|
||||
"mode": "plan",
|
||||
"model": "gpt-test",
|
||||
"reasoning_effort": null,
|
||||
"developer_instructions": null,
|
||||
},
|
||||
"effort": null,
|
||||
"summary": "auto",
|
||||
}),
|
||||
);
|
||||
|
||||
let parsed = parse_legacy_rollout_line(&bytes)
|
||||
.expect("parse legacy turn context")
|
||||
.expect("keep legacy turn context");
|
||||
let RolloutItem::TurnContext(context) = parsed.item else {
|
||||
panic!("expected turn context");
|
||||
};
|
||||
assert_eq!(
|
||||
context
|
||||
.collaboration_mode
|
||||
.expect("collaboration mode")
|
||||
.model(),
|
||||
"gpt-test"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normalizes_legacy_turn_context_sandbox_policy() {
|
||||
let cwd = std::env::temp_dir().to_string_lossy().into_owned();
|
||||
let bytes = line(
|
||||
"turn_context",
|
||||
json!({
|
||||
"cwd": cwd,
|
||||
"approval_policy": "never",
|
||||
"sandbox_policy": {"mode": "danger-full-access"},
|
||||
"model": "gpt-test",
|
||||
"personality": null,
|
||||
"effort": null,
|
||||
"summary": "auto",
|
||||
}),
|
||||
);
|
||||
|
||||
let parsed = parse_legacy_rollout_line(&bytes)
|
||||
.expect("parse legacy sandbox policy")
|
||||
.expect("keep legacy turn context");
|
||||
assert!(matches!(parsed.item, RolloutItem::TurnContext(_)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normalizes_legacy_review_entry_prompt() {
|
||||
let bytes = line(
|
||||
"event_msg",
|
||||
json!({
|
||||
"type": "entered_review_mode",
|
||||
"prompt": "review these changes",
|
||||
"user_facing_hint": "Review requested.",
|
||||
}),
|
||||
);
|
||||
|
||||
let parsed = parse_legacy_rollout_line(&bytes)
|
||||
.expect("parse legacy review entry")
|
||||
.expect("keep legacy review entry");
|
||||
assert!(matches!(
|
||||
parsed.item,
|
||||
RolloutItem::EventMsg(EventMsg::EnteredReviewMode(_))
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normalizes_legacy_plain_command_cwd() {
|
||||
let cwd = std::env::temp_dir().to_string_lossy().into_owned();
|
||||
let bytes = line(
|
||||
"event_msg",
|
||||
json!({
|
||||
"type": "exec_command_end",
|
||||
"call_id": "call-1",
|
||||
"turn_id": "turn-1",
|
||||
"command": ["echo", "ok"],
|
||||
"cwd": cwd,
|
||||
"parsed_cmd": [],
|
||||
"source": "agent",
|
||||
"stdout": "",
|
||||
"stderr": "",
|
||||
"aggregated_output": "",
|
||||
"exit_code": 0,
|
||||
"duration": {"secs": 0, "nanos": 0},
|
||||
"formatted_output": "",
|
||||
"status": "completed",
|
||||
}),
|
||||
);
|
||||
|
||||
let parsed = parse_legacy_rollout_line(&bytes)
|
||||
.expect("parse legacy command")
|
||||
.expect("keep legacy command");
|
||||
assert!(matches!(
|
||||
parsed.item,
|
||||
RolloutItem::EventMsg(EventMsg::ExecCommandEnd(_))
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn skips_only_known_retired_events() {
|
||||
for event_type in [
|
||||
"guardian_assessment",
|
||||
"thread_name_updated",
|
||||
"undo_completed",
|
||||
] {
|
||||
let bytes = line("event_msg", json!({"type": event_type}));
|
||||
assert!(
|
||||
parse_legacy_rollout_line(&bytes)
|
||||
.expect("inspect retired event")
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
|
||||
let unknown = line("event_msg", json!({"type": "unknown_legacy_event"}));
|
||||
assert!(parse_legacy_rollout_line(&unknown).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn skips_legacy_ghost_snapshots() {
|
||||
let ghost_snapshot = line(
|
||||
"response_item",
|
||||
json!({
|
||||
"type": "ghost_snapshot",
|
||||
"ghost_commit": {"id": "legacy"},
|
||||
}),
|
||||
);
|
||||
|
||||
assert!(
|
||||
parse_legacy_rollout_line(&ghost_snapshot)
|
||||
.expect("inspect ghost snapshot")
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
275
codex-rs/thread-store/src/local/rollout_migration/publish.rs
Normal file
275
codex-rs/thread-store/src/local/rollout_migration/publish.rs
Normal file
@@ -0,0 +1,275 @@
|
||||
//! Filesystem helpers for safely publishing migrated rollouts.
|
||||
//!
|
||||
//! This module owns temporary rollout paths, durable `.pending` journals, compressed rollout
|
||||
//! staging, cleanup, and parent-directory syncs. The migration orchestrator decides when to call
|
||||
//! these helpers; this module keeps the low-level file operations in one place.
|
||||
//!
|
||||
//! A migration can crash between publishing JSONL and finishing SQLite metadata. The journal is
|
||||
//! the durable handoff between those steps, so cleanup must only remove it once the paginated
|
||||
//! rollout and SQLite state are both complete.
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::fs::Permissions;
|
||||
use std::io;
|
||||
use std::io::Write;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::time::SystemTime;
|
||||
|
||||
#[cfg(unix)]
|
||||
use std::os::unix::fs::OpenOptionsExt;
|
||||
#[cfg(unix)]
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_rollout::RolloutItem;
|
||||
use tokio::fs::File;
|
||||
use tokio::io::AsyncBufReadExt;
|
||||
use tokio::io::AsyncWriteExt;
|
||||
use tokio::io::BufReader;
|
||||
use tokio::io::BufWriter;
|
||||
|
||||
use super::MigrationLocks;
|
||||
use super::migration_error;
|
||||
use crate::ThreadStoreResult;
|
||||
|
||||
const MIGRATION_JOURNAL_DIRECTORY: &str = "rollout-migrations";
|
||||
|
||||
pub(super) fn migration_journal_path(codex_home: &Path, thread_id: ThreadId) -> PathBuf {
|
||||
codex_home
|
||||
.join(MIGRATION_JOURNAL_DIRECTORY)
|
||||
.join(format!("{thread_id}.pending"))
|
||||
}
|
||||
|
||||
pub(super) async fn pending_migration_thread_ids(
|
||||
codex_home: &Path,
|
||||
) -> ThreadStoreResult<HashSet<ThreadId>> {
|
||||
let mut entries = match tokio::fs::read_dir(codex_home.join(MIGRATION_JOURNAL_DIRECTORY)).await
|
||||
{
|
||||
Ok(entries) => entries,
|
||||
Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(HashSet::new()),
|
||||
Err(error) => return Err(migration_error(error)),
|
||||
};
|
||||
let mut thread_ids = HashSet::new();
|
||||
while let Some(entry) = entries.next_entry().await.map_err(migration_error)? {
|
||||
if !entry.file_type().await.map_err(migration_error)?.is_file() {
|
||||
continue;
|
||||
}
|
||||
let filename = entry.file_name();
|
||||
let Some(thread_id) = filename
|
||||
.to_str()
|
||||
.and_then(|filename| filename.strip_suffix(".pending"))
|
||||
.and_then(|thread_id| ThreadId::from_string(thread_id).ok())
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
thread_ids.insert(thread_id);
|
||||
}
|
||||
Ok(thread_ids)
|
||||
}
|
||||
|
||||
pub(super) fn staged_rollout_path(rollout_path: &Path) -> ThreadStoreResult<PathBuf> {
|
||||
staged_path(rollout_path, "paginated")
|
||||
}
|
||||
|
||||
pub(super) fn decompressed_staged_rollout_path(rollout_path: &Path) -> ThreadStoreResult<PathBuf> {
|
||||
staged_path(rollout_path, "decompressed")
|
||||
}
|
||||
|
||||
pub(super) fn compressed_staged_rollout_path(rollout_path: &Path) -> ThreadStoreResult<PathBuf> {
|
||||
staged_path(rollout_path, "paginated.zst")
|
||||
}
|
||||
|
||||
fn staged_path(rollout_path: &Path, suffix: &str) -> ThreadStoreResult<PathBuf> {
|
||||
let filename = rollout_path
|
||||
.file_name()
|
||||
.and_then(|filename| filename.to_str())
|
||||
.ok_or_else(|| migration_error("rollout path has no valid filename"))?;
|
||||
Ok(rollout_path.with_file_name(format!(".{filename}.{suffix}.tmp")))
|
||||
}
|
||||
|
||||
pub(super) async fn decompress_rollout_to_path(
|
||||
compressed_path: &Path,
|
||||
plain_path: &Path,
|
||||
locks: &Arc<MigrationLocks>,
|
||||
) -> ThreadStoreResult<()> {
|
||||
let compressed_path = compressed_path.to_path_buf();
|
||||
let plain_path = plain_path.to_path_buf();
|
||||
let locks = Arc::clone(locks);
|
||||
tokio::task::spawn_blocking(move || -> io::Result<()> {
|
||||
let _locks = locks;
|
||||
let input = std::fs::File::open(compressed_path)?;
|
||||
let mut decoder = zstd::stream::read::Decoder::new(input)?;
|
||||
let mut options = std::fs::OpenOptions::new();
|
||||
options.create(true).truncate(true).write(true);
|
||||
#[cfg(unix)]
|
||||
options.mode(0o600);
|
||||
let mut output = options.open(plain_path)?;
|
||||
#[cfg(unix)]
|
||||
output.set_permissions(Permissions::from_mode(0o600))?;
|
||||
io::copy(&mut decoder, &mut output)?;
|
||||
output.flush()
|
||||
})
|
||||
.await
|
||||
.map_err(migration_error)?
|
||||
.map_err(migration_error)
|
||||
}
|
||||
|
||||
pub(super) async fn compress_rollout_to_path(
|
||||
plain_path: &Path,
|
||||
compressed_path: &Path,
|
||||
permissions: Permissions,
|
||||
modified_at: Option<SystemTime>,
|
||||
locks: &Arc<MigrationLocks>,
|
||||
) -> ThreadStoreResult<()> {
|
||||
let plain_path = plain_path.to_path_buf();
|
||||
let compressed_path = compressed_path.to_path_buf();
|
||||
let locks = Arc::clone(locks);
|
||||
tokio::task::spawn_blocking(move || -> io::Result<()> {
|
||||
let _locks = locks;
|
||||
let mut input = std::fs::File::open(plain_path)?;
|
||||
let output = std::fs::OpenOptions::new()
|
||||
.create(true)
|
||||
.truncate(true)
|
||||
.write(true)
|
||||
.open(&compressed_path)?;
|
||||
let mut encoder = zstd::stream::write::Encoder::new(output, 3)?;
|
||||
io::copy(&mut input, &mut encoder)?;
|
||||
let output = encoder.finish()?;
|
||||
output.set_permissions(permissions)?;
|
||||
if let Some(modified_at) = modified_at {
|
||||
output.set_times(std::fs::FileTimes::new().set_modified(modified_at))?;
|
||||
}
|
||||
output.sync_all()?;
|
||||
|
||||
let input = std::fs::File::open(compressed_path)?;
|
||||
let mut decoder = zstd::stream::read::Decoder::new(input)?;
|
||||
io::copy(&mut decoder, &mut io::sink())?;
|
||||
Ok(())
|
||||
})
|
||||
.await
|
||||
.map_err(migration_error)?
|
||||
.map_err(migration_error)
|
||||
}
|
||||
|
||||
pub(super) fn rewritten_staged_rollout_path(staged_path: &Path) -> ThreadStoreResult<PathBuf> {
|
||||
let filename = staged_path
|
||||
.file_name()
|
||||
.and_then(|filename| filename.to_str())
|
||||
.ok_or_else(|| migration_error("staged rollout path has no valid filename"))?;
|
||||
Ok(staged_path.with_file_name(format!("{filename}.head.tmp")))
|
||||
}
|
||||
|
||||
pub(super) async fn rewrite_subagent_history_boundary(
|
||||
staged_path: &Path,
|
||||
boundary: u64,
|
||||
) -> ThreadStoreResult<()> {
|
||||
let rewritten_path = rewritten_staged_rollout_path(staged_path)?;
|
||||
let permissions = tokio::fs::metadata(staged_path)
|
||||
.await
|
||||
.map_err(migration_error)?
|
||||
.permissions();
|
||||
let source = File::open(staged_path).await.map_err(migration_error)?;
|
||||
let mut source = BufReader::new(source);
|
||||
let mut head_bytes = Vec::new();
|
||||
source
|
||||
.read_until(b'\n', &mut head_bytes)
|
||||
.await
|
||||
.map_err(migration_error)?;
|
||||
let mut head = codex_rollout::parse_rollout_line_bytes(&head_bytes).map_err(migration_error)?;
|
||||
let RolloutItem::SessionMeta(session_meta) = &mut head.item else {
|
||||
return Err(migration_error(
|
||||
"staged rollout head is not session metadata",
|
||||
));
|
||||
};
|
||||
session_meta.meta.subagent_history_start_ordinal = Some(boundary);
|
||||
|
||||
let rewritten = tokio::fs::OpenOptions::new()
|
||||
.create(true)
|
||||
.truncate(true)
|
||||
.write(true)
|
||||
.open(&rewritten_path)
|
||||
.await
|
||||
.map_err(migration_error)?;
|
||||
rewritten
|
||||
.set_permissions(permissions)
|
||||
.await
|
||||
.map_err(migration_error)?;
|
||||
let mut rewritten = BufWriter::new(rewritten);
|
||||
rewritten
|
||||
.write_all(
|
||||
serde_json::to_string(&head)
|
||||
.map_err(migration_error)?
|
||||
.as_bytes(),
|
||||
)
|
||||
.await
|
||||
.map_err(migration_error)?;
|
||||
rewritten.write_all(b"\n").await.map_err(migration_error)?;
|
||||
tokio::io::copy(&mut source, &mut rewritten)
|
||||
.await
|
||||
.map_err(migration_error)?;
|
||||
rewritten.flush().await.map_err(migration_error)?;
|
||||
rewritten
|
||||
.get_ref()
|
||||
.sync_all()
|
||||
.await
|
||||
.map_err(migration_error)?;
|
||||
drop(rewritten);
|
||||
tokio::fs::rename(rewritten_path, staged_path)
|
||||
.await
|
||||
.map_err(migration_error)
|
||||
}
|
||||
|
||||
pub(super) async fn remove_file_if_present(path: &Path) -> ThreadStoreResult<()> {
|
||||
if tokio::fs::try_exists(path).await.map_err(migration_error)? {
|
||||
tokio::fs::remove_file(path)
|
||||
.await
|
||||
.map_err(migration_error)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) async fn write_migration_journal(path: &Path) -> ThreadStoreResult<()> {
|
||||
let parent = path
|
||||
.parent()
|
||||
.ok_or_else(|| migration_error("rollout migration journal has no parent directory"))?;
|
||||
let parent_already_exists = tokio::fs::try_exists(parent)
|
||||
.await
|
||||
.map_err(migration_error)?;
|
||||
tokio::fs::create_dir_all(parent)
|
||||
.await
|
||||
.map_err(migration_error)?;
|
||||
if !parent_already_exists {
|
||||
sync_parent_directory(parent).await?;
|
||||
}
|
||||
let file = tokio::fs::OpenOptions::new()
|
||||
.create(true)
|
||||
.truncate(true)
|
||||
.write(true)
|
||||
.open(path)
|
||||
.await
|
||||
.map_err(migration_error)?;
|
||||
file.sync_all().await.map_err(migration_error)?;
|
||||
drop(file);
|
||||
sync_parent_directory(path).await
|
||||
}
|
||||
|
||||
pub(super) async fn sync_parent_directory(path: &Path) -> ThreadStoreResult<()> {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
let parent = path
|
||||
.parent()
|
||||
.ok_or_else(|| migration_error("rollout path has no parent directory"))?
|
||||
.to_path_buf();
|
||||
tokio::task::spawn_blocking(move || std::fs::File::open(parent)?.sync_all())
|
||||
.await
|
||||
.map_err(migration_error)?
|
||||
.map_err(migration_error)?;
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
{
|
||||
let _ = path;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
147
codex-rs/thread-store/src/local/rollout_migration/rollback.rs
Normal file
147
codex-rs/thread-store/src/local/rollout_migration/rollback.rs
Normal file
@@ -0,0 +1,147 @@
|
||||
//! Defines which persisted history entries count as rollbackable user turns.
|
||||
//!
|
||||
//! Legacy `ThreadRolledBack { num_turns }` does not mean “drop the last N JSONL records.” A turn
|
||||
//! can include contextual user/developer messages, paired `ResponseItem` + `UserMessage` records,
|
||||
//! inter-agent communication, or compaction replacement history.
|
||||
//!
|
||||
//! This module mirrors the legacy cold-resume rollback boundary rules for persisted rollout shapes.
|
||||
//! It stays local to migration because core's live predicate also knows about dynamically
|
||||
//! registered contextual fragments that thread-store should not depend on.
|
||||
|
||||
use codex_protocol::items::parse_hook_prompt_fragment;
|
||||
use codex_protocol::models::ContentItem;
|
||||
use codex_protocol::models::ResponseItem;
|
||||
use codex_protocol::protocol::InterAgentCommunication;
|
||||
use std::borrow::Borrow;
|
||||
|
||||
/// Match the rollback boundaries used by legacy history reconstruction without
|
||||
/// treating every persisted lifecycle as a user turn. This intentionally stays
|
||||
/// local to the frozen migration adapter: the full core predicate also knows
|
||||
/// about dynamically registered contextual fragments that thread-store cannot
|
||||
/// depend on.
|
||||
pub(super) fn counts_as_boundary(response: &ResponseItem) -> bool {
|
||||
if matches!(response, ResponseItem::AgentMessage { .. }) {
|
||||
return true;
|
||||
}
|
||||
let ResponseItem::Message { role, content, .. } = response else {
|
||||
return false;
|
||||
};
|
||||
(role == "user" && !is_known_contextual_user_message_content(content))
|
||||
|| (role == "assistant" && InterAgentCommunication::is_message_content(content))
|
||||
}
|
||||
|
||||
pub(super) fn is_pre_turn_context_update(response: &ResponseItem) -> bool {
|
||||
let ResponseItem::Message { role, content, .. } = response else {
|
||||
return false;
|
||||
};
|
||||
(role == "user" && is_known_contextual_user_message_content(content))
|
||||
|| (role == "developer" && is_known_contextual_developer_message_content(content))
|
||||
}
|
||||
|
||||
/// Apply the same response-history cut used by legacy cold resume to a persisted
|
||||
/// compaction checkpoint. The migration adapter uses a frozen contextual-fragment
|
||||
/// matcher because thread-store cannot depend on core's runtime fragment registry.
|
||||
pub(super) fn drop_last_n_user_turns<T>(history: &mut Vec<T>, num_turns: u32)
|
||||
where
|
||||
T: Borrow<ResponseItem>,
|
||||
{
|
||||
if num_turns == 0 {
|
||||
return;
|
||||
}
|
||||
let user_positions = history
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(index, item)| counts_as_boundary(item.borrow()).then_some(index))
|
||||
.collect::<Vec<_>>();
|
||||
let Some(&first_turn_index) = user_positions.first() else {
|
||||
return;
|
||||
};
|
||||
let count = usize::try_from(num_turns).unwrap_or(usize::MAX);
|
||||
let mut cut_index = if count >= user_positions.len() {
|
||||
first_turn_index
|
||||
} else {
|
||||
user_positions[user_positions.len() - count]
|
||||
};
|
||||
while cut_index > first_turn_index
|
||||
&& is_pre_turn_context_update(history[cut_index - 1].borrow())
|
||||
{
|
||||
cut_index -= 1;
|
||||
}
|
||||
history.truncate(cut_index);
|
||||
}
|
||||
|
||||
fn is_known_contextual_user_message_content(content: &[ContentItem]) -> bool {
|
||||
content.iter().any(|item| {
|
||||
let ContentItem::InputText { text } = item else {
|
||||
return false;
|
||||
};
|
||||
is_known_contextual_user_text(text)
|
||||
})
|
||||
}
|
||||
|
||||
fn is_known_contextual_developer_message_content(content: &[ContentItem]) -> bool {
|
||||
content.iter().any(|item| {
|
||||
let ContentItem::InputText { text } = item else {
|
||||
return false;
|
||||
};
|
||||
let text = text.trim_start();
|
||||
[
|
||||
"<permissions instructions>",
|
||||
"<model_switch>",
|
||||
"<managed_developer_instructions>",
|
||||
"<apps_instructions>",
|
||||
"<collaboration_mode>",
|
||||
"<multi_agent_mode>",
|
||||
"<environments_instructions>",
|
||||
"<git_attribution>",
|
||||
"<plugins_instructions>",
|
||||
"<realtime_conversation>",
|
||||
"<skills_instructions>",
|
||||
"<tools>",
|
||||
"<personality_spec>",
|
||||
"<token_budget>",
|
||||
"<context_window>",
|
||||
"<context_window_guidance>",
|
||||
"<rollout_budget>",
|
||||
]
|
||||
.iter()
|
||||
.any(|prefix| {
|
||||
text.get(..prefix.len())
|
||||
.is_some_and(|candidate| candidate.eq_ignore_ascii_case(prefix))
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
// Keep this frozen alongside the legacy migration adapter. Core's live predicate also knows
|
||||
// about dynamically registered fragments, but legacy rollouts only need these persisted shapes.
|
||||
fn is_known_contextual_user_text(text: &str) -> bool {
|
||||
let text = text.trim();
|
||||
parse_hook_prompt_fragment(text).is_some()
|
||||
|| [
|
||||
("# AGENTS.md instructions", "</INSTRUCTIONS>"),
|
||||
("<environment_context>", "</environment_context>"),
|
||||
("<skill>", "</skill>"),
|
||||
("<user_shell_command>", "</user_shell_command>"),
|
||||
("<turn_aborted>", "</turn_aborted>"),
|
||||
("<subagent_notification>", "</subagent_notification>"),
|
||||
("<recommended_plugins>", "</recommended_plugins>"),
|
||||
("<goal_context>", "</goal_context>"),
|
||||
]
|
||||
.iter()
|
||||
.any(|(start, end)| text.starts_with(start) && text.ends_with(end))
|
||||
|| (text.starts_with("<external_")
|
||||
&& text
|
||||
.split_once('>')
|
||||
.and_then(|(start, _)| start.strip_prefix("<external_"))
|
||||
.is_some_and(|key| text.ends_with(&format!("</external_{key}>"))))
|
||||
|| (text.starts_with("<codex_internal_context")
|
||||
&& text.ends_with("</codex_internal_context>"))
|
||||
|| text.starts_with(
|
||||
"Warning: The maximum number of unified exec processes you can keep open is",
|
||||
)
|
||||
|| (text.starts_with("Warning: apply_patch was requested via ")
|
||||
&& text.ends_with("Use the apply_patch tool instead of exec_command."))
|
||||
|| text.starts_with(
|
||||
"Warning: Your account was flagged for potentially high-risk cyber activity",
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,656 @@
|
||||
//! Decides which legacy records remain visible after historical rollback.
|
||||
//!
|
||||
//! Legacy rollback removes logical instruction turns, not a physical suffix of the rollout file.
|
||||
//! Most records happen to be ordered that way, but late completion events can target an older
|
||||
//! surviving turn after a newer turn has started. This planner keeps compact per-record ownership
|
||||
//! metadata for SQLite visibility, then combines it with `rollback_replay`'s cold-resume answer
|
||||
//! before the writer makes its second streaming pass. Retained checkpoints are reduced when
|
||||
//! rollback is encountered, never by reapplying old rollbacks to later checkpoints.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::collections::HashSet;
|
||||
|
||||
use codex_protocol::ResponseItemId;
|
||||
use codex_protocol::models::AudioReference;
|
||||
use codex_protocol::models::ContentItem;
|
||||
use codex_protocol::models::ImageReference;
|
||||
use codex_protocol::models::ResponseItem;
|
||||
use codex_protocol::protocol::EventMsg;
|
||||
use codex_protocol::protocol::UserMessageAudioKind;
|
||||
use codex_protocol::protocol::UserMessageEvent;
|
||||
use codex_protocol::protocol::UserMessageImageKind;
|
||||
use codex_rollout::CompactedItem;
|
||||
use codex_rollout::RetainedContextEntry;
|
||||
use codex_rollout::RetainedInputSource;
|
||||
use codex_rollout::RolloutItem;
|
||||
use codex_rollout::RolloutLine;
|
||||
|
||||
use super::migration_error;
|
||||
use super::rollback;
|
||||
use super::rollback_replay::ModelReplayPlanner;
|
||||
use crate::ThreadStoreResult;
|
||||
|
||||
#[derive(Clone)]
|
||||
struct CompactionFrame {
|
||||
record_index: usize,
|
||||
boundary_depth: usize,
|
||||
owner: Option<usize>,
|
||||
item: CompactedItem,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct PendingUserResponse {
|
||||
boundary: usize,
|
||||
content: Vec<ContentItem>,
|
||||
}
|
||||
|
||||
struct InstructionBoundary {
|
||||
record_index: usize,
|
||||
message_id: Option<ResponseItemId>,
|
||||
input_source: RetainedInputSource,
|
||||
is_communication: bool,
|
||||
alive: bool,
|
||||
}
|
||||
|
||||
struct RetainedFactSource {
|
||||
record_index: usize,
|
||||
turn_id: String,
|
||||
acceptance_order: Option<u64>,
|
||||
}
|
||||
|
||||
/// Compact plan keyed by parsed source-record index.
|
||||
pub(super) struct RollbackPlan {
|
||||
record_boundaries: Vec<Option<usize>>,
|
||||
boundary_alive: Vec<bool>,
|
||||
compacted_items: HashMap<usize, CompactedItem>,
|
||||
}
|
||||
|
||||
impl RollbackPlan {
|
||||
pub(super) fn record_count(&self) -> usize {
|
||||
self.record_boundaries.len()
|
||||
}
|
||||
|
||||
pub(super) fn apply(
|
||||
&self,
|
||||
record_index: usize,
|
||||
mut line: RolloutLine,
|
||||
) -> ThreadStoreResult<Option<RolloutLine>> {
|
||||
let boundary = self
|
||||
.record_boundaries
|
||||
.get(record_index)
|
||||
.ok_or_else(|| migration_error("rollback plan is shorter than source replay"))?;
|
||||
if matches!(
|
||||
&line.item,
|
||||
RolloutItem::EventMsg(EventMsg::ThreadRolledBack(_))
|
||||
) {
|
||||
return Ok(None);
|
||||
}
|
||||
// A rolled-back turn can still own the empty checkpoint that keeps cold resume from
|
||||
// replaying older history.
|
||||
if let Some(compacted) = self.compacted_items.get(&record_index) {
|
||||
line.item = RolloutItem::Compacted(Box::new(compacted.clone()));
|
||||
return Ok(Some(line));
|
||||
}
|
||||
if boundary.is_some_and(|boundary| !self.boundary_alive[boundary]) {
|
||||
return Ok(None);
|
||||
}
|
||||
Ok(Some(line))
|
||||
}
|
||||
}
|
||||
|
||||
/// Streaming builder for RollbackPlan.
|
||||
pub(super) struct RollbackPlanner {
|
||||
record_boundaries: Vec<Option<usize>>,
|
||||
boundaries: Vec<InstructionBoundary>,
|
||||
boundary_stack: Vec<usize>,
|
||||
active_turn_id: Option<String>,
|
||||
pending_turn_records: Vec<usize>,
|
||||
pending_context_records: Vec<usize>,
|
||||
pending_user_response: Option<PendingUserResponse>,
|
||||
pending_delivery_boundary: Option<usize>,
|
||||
turn_boundaries: HashMap<String, usize>,
|
||||
turn_initial_boundaries: HashMap<String, usize>,
|
||||
call_boundaries: HashMap<(String, String), Option<usize>>,
|
||||
retained_fact_sources: Vec<RetainedFactSource>,
|
||||
compactions: Vec<CompactionFrame>,
|
||||
model_replay: ModelReplayPlanner,
|
||||
}
|
||||
|
||||
impl RollbackPlanner {
|
||||
pub(super) fn new() -> Self {
|
||||
Self {
|
||||
record_boundaries: Vec::new(),
|
||||
boundaries: Vec::new(),
|
||||
boundary_stack: Vec::new(),
|
||||
active_turn_id: None,
|
||||
pending_turn_records: Vec::new(),
|
||||
pending_context_records: Vec::new(),
|
||||
pending_user_response: None,
|
||||
pending_delivery_boundary: None,
|
||||
turn_boundaries: HashMap::new(),
|
||||
turn_initial_boundaries: HashMap::new(),
|
||||
call_boundaries: HashMap::new(),
|
||||
retained_fact_sources: Vec::new(),
|
||||
compactions: Vec::new(),
|
||||
model_replay: ModelReplayPlanner::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn observe(&mut self, line: &RolloutLine) -> ThreadStoreResult<()> {
|
||||
let index = self.record_boundaries.len();
|
||||
self.model_replay.observe(index, &line.item);
|
||||
self.record_boundaries
|
||||
.push(self.boundary_stack.last().copied());
|
||||
let paired_user_boundary = match (&self.pending_user_response, &line.item) {
|
||||
(Some(pending), RolloutItem::EventMsg(EventMsg::UserMessage(event)))
|
||||
if user_response_matches_event(&pending.content, event) =>
|
||||
{
|
||||
Some(pending.boundary)
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
let paired_delivery_boundary = match (&self.pending_delivery_boundary, &line.item) {
|
||||
(Some(boundary), RolloutItem::ResponseItem(response))
|
||||
if matches!(&response.item, ResponseItem::AgentMessage { .. }) =>
|
||||
{
|
||||
Some(*boundary)
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
self.pending_user_response = None;
|
||||
self.pending_delivery_boundary = None;
|
||||
|
||||
match &line.item {
|
||||
RolloutItem::DynamicToolsUpdated { .. } | RolloutItem::SessionMeta(_) => {
|
||||
self.record_boundaries[index] = None
|
||||
}
|
||||
RolloutItem::ResponseItem(response) => {
|
||||
if matches!(&response.item, ResponseItem::Message { role, .. } if role == "assistant")
|
||||
|| matches!(&response.item, ResponseItem::FunctionCall { .. })
|
||||
{
|
||||
self.retained_fact_sources.push(RetainedFactSource {
|
||||
record_index: index,
|
||||
turn_id: response.turn_id().unwrap_or_default().to_owned(),
|
||||
acceptance_order: response
|
||||
.metadata
|
||||
.as_ref()
|
||||
.filter(|metadata| !metadata.inherited_user_message)
|
||||
.and_then(|metadata| metadata.user_input_order),
|
||||
});
|
||||
}
|
||||
if let Some(boundary) = paired_delivery_boundary {
|
||||
self.record_boundaries[index] = Some(boundary);
|
||||
self.boundaries[boundary].message_id = response.id().cloned();
|
||||
self.boundaries[boundary].input_source = response.metadata.as_ref().into();
|
||||
} else if rollback::counts_as_boundary(&response.item) {
|
||||
let boundary = self.start_boundary(index);
|
||||
self.boundaries[boundary].message_id = response.id().cloned();
|
||||
self.boundaries[boundary].input_source = response.metadata.as_ref().into();
|
||||
self.boundaries[boundary].is_communication =
|
||||
matches!(response.item, ResponseItem::AgentMessage { .. });
|
||||
if let ResponseItem::Message { role, content, .. } = &response.item
|
||||
&& role == "user"
|
||||
{
|
||||
self.pending_user_response = Some(PendingUserResponse {
|
||||
boundary,
|
||||
content: content.clone(),
|
||||
});
|
||||
}
|
||||
} else if rollback::is_pre_turn_context_update(&response.item) {
|
||||
// Until another user boundary arrives, this is trailing context for the
|
||||
// previous turn. Keep that fallback owner so rollback drops it when there is
|
||||
// no later turn to attach it to.
|
||||
self.pending_context_records.push(index);
|
||||
}
|
||||
if let ResponseItem::FunctionCall { call_id, .. } = &response.item
|
||||
&& let Some(turn_id) = response.turn_id().or(self.active_turn_id.as_deref())
|
||||
{
|
||||
self.call_boundaries.insert(
|
||||
(turn_id.to_owned(), call_id.clone()),
|
||||
self.record_boundaries[index],
|
||||
);
|
||||
}
|
||||
}
|
||||
RolloutItem::EventMsg(EventMsg::ThreadRolledBack(rollback)) => {
|
||||
self.apply_rollback(rollback.num_turns)?;
|
||||
}
|
||||
RolloutItem::EventMsg(EventMsg::TurnStarted(event)) => {
|
||||
self.active_turn_id = Some(event.turn_id.clone());
|
||||
self.pending_turn_records.clear();
|
||||
self.pending_turn_records.push(index);
|
||||
}
|
||||
RolloutItem::EventMsg(EventMsg::TurnComplete(event)) => {
|
||||
self.assign_targeted_record(index, Some(event.turn_id.as_str()));
|
||||
if self.active_turn_id.as_deref() == Some(event.turn_id.as_str()) {
|
||||
self.active_turn_id = None;
|
||||
self.pending_turn_records.clear();
|
||||
}
|
||||
}
|
||||
RolloutItem::EventMsg(EventMsg::TurnAborted(event)) => {
|
||||
self.assign_targeted_record(index, event.turn_id.as_deref());
|
||||
if event
|
||||
.turn_id
|
||||
.as_deref()
|
||||
.is_some_and(|turn_id| self.active_turn_id.as_deref() == Some(turn_id))
|
||||
{
|
||||
self.active_turn_id = None;
|
||||
self.pending_turn_records.clear();
|
||||
}
|
||||
}
|
||||
RolloutItem::EventMsg(EventMsg::UserMessage(_)) => {
|
||||
let boundary = paired_user_boundary.unwrap_or_else(|| self.start_boundary(index));
|
||||
self.record_boundaries[index] = Some(boundary);
|
||||
}
|
||||
RolloutItem::EventMsg(EventMsg::ItemCompleted(event)) => {
|
||||
self.assign_targeted_record(index, Some(event.turn_id.as_str()));
|
||||
}
|
||||
RolloutItem::EventMsg(event) => {
|
||||
self.assign_targeted_record(index, explicit_event_turn_id(event));
|
||||
}
|
||||
RolloutItem::InterAgentCommunication(_) => {
|
||||
let boundary = self.start_boundary(index);
|
||||
self.boundaries[boundary].is_communication = true;
|
||||
}
|
||||
RolloutItem::InterAgentCommunicationMetadata { .. } => {
|
||||
let boundary = self.start_boundary(index);
|
||||
self.boundaries[boundary].is_communication = true;
|
||||
self.pending_delivery_boundary = Some(boundary);
|
||||
}
|
||||
RolloutItem::Compacted(item) => {
|
||||
let owner = self
|
||||
.active_turn_id
|
||||
.as_deref()
|
||||
.and_then(|turn_id| self.turn_boundaries.get(turn_id).copied());
|
||||
self.record_boundaries[index] = owner;
|
||||
self.compactions.push(CompactionFrame {
|
||||
record_index: index,
|
||||
boundary_depth: self.boundary_stack.len(),
|
||||
owner,
|
||||
item: item.as_ref().clone(),
|
||||
});
|
||||
}
|
||||
RolloutItem::TurnContext(_) => {
|
||||
if self.active_turn_id.is_some()
|
||||
&& self
|
||||
.active_turn_id
|
||||
.as_deref()
|
||||
.is_none_or(|turn_id| !self.turn_boundaries.contains_key(turn_id))
|
||||
{
|
||||
self.pending_turn_records.push(index);
|
||||
}
|
||||
}
|
||||
RolloutItem::RetainedContext(
|
||||
codex_rollout::RetainedContextEvent::AcceptedFileAudio { evidence },
|
||||
) => {
|
||||
self.assign_targeted_record(index, Some(&evidence.turn_id));
|
||||
}
|
||||
RolloutItem::TokenUsageRecord(record) => {
|
||||
self.assign_targeted_record(index, Some(record.turn_id.as_str()));
|
||||
}
|
||||
RolloutItem::WorldState(_) | RolloutItem::RealtimeItem(_) => {}
|
||||
RolloutItem::RetainedContext(codex_rollout::RetainedContextEvent::VerifiedAnswer {
|
||||
answer,
|
||||
acceptance_order,
|
||||
}) => {
|
||||
let source = (answer.turn_id.clone(), answer.call_id.clone());
|
||||
// A late answer still belongs to its call's instruction boundary, even
|
||||
// if the same running turn has since received another user steer.
|
||||
if let Some(boundary) = self.call_boundaries.get(&source) {
|
||||
self.record_boundaries[index] = *boundary;
|
||||
} else {
|
||||
self.assign_targeted_record(index, Some(&answer.turn_id));
|
||||
}
|
||||
self.call_boundaries
|
||||
.insert(source, self.record_boundaries[index]);
|
||||
self.retained_fact_sources.push(RetainedFactSource {
|
||||
record_index: index,
|
||||
turn_id: answer.turn_id.clone(),
|
||||
acceptance_order: *acceptance_order,
|
||||
});
|
||||
}
|
||||
RolloutItem::RetainedContext(
|
||||
codex_rollout::RetainedContextEvent::DeliveredAssistantMessage {
|
||||
message,
|
||||
acceptance_order,
|
||||
},
|
||||
) => {
|
||||
// Nested calls have no response item; match them to instructions by acceptance order.
|
||||
let ordered = self
|
||||
.boundary_stack
|
||||
.iter()
|
||||
.rev()
|
||||
.copied()
|
||||
.find(|boundary| {
|
||||
self.boundaries[*boundary]
|
||||
.input_source
|
||||
.acceptance_order()
|
||||
.is_some_and(|order| order <= *acceptance_order)
|
||||
})
|
||||
.or_else(|| {
|
||||
// An unsequenced legacy instruction is safe only when it is the
|
||||
// sole boundary. A later unsequenced steer has ambiguous order.
|
||||
(self.boundary_stack.len() == 1)
|
||||
.then(|| self.boundary_stack[0])
|
||||
.filter(|boundary| {
|
||||
self.boundaries[*boundary]
|
||||
.input_source
|
||||
.acceptance_order()
|
||||
.is_none()
|
||||
})
|
||||
});
|
||||
// Older communication records have no order, but can still own the turn they started.
|
||||
let communication = self
|
||||
.turn_initial_boundaries
|
||||
.get(&message.turn_id)
|
||||
.copied()
|
||||
.filter(|boundary| {
|
||||
let boundary = &self.boundaries[*boundary];
|
||||
boundary.is_communication
|
||||
&& boundary.input_source.acceptance_order().is_none()
|
||||
});
|
||||
self.record_boundaries[index] = ordered.max(communication);
|
||||
self.retained_fact_sources.push(RetainedFactSource {
|
||||
record_index: index,
|
||||
turn_id: message.turn_id.clone(),
|
||||
acceptance_order: Some(*acceptance_order),
|
||||
});
|
||||
}
|
||||
RolloutItem::SecurityRiskScore(_) => self.record_boundaries[index] = None,
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn finish(self) -> RollbackPlan {
|
||||
let RollbackPlanner {
|
||||
record_boundaries,
|
||||
boundaries,
|
||||
compactions,
|
||||
model_replay,
|
||||
..
|
||||
} = self;
|
||||
let replay_anchor = model_replay.finish().empty_replacement_history_compaction;
|
||||
let boundary_alive = boundaries
|
||||
.into_iter()
|
||||
.map(|boundary| boundary.alive)
|
||||
.collect::<Vec<_>>();
|
||||
let compacted_items = compactions
|
||||
.into_iter()
|
||||
.filter_map(|mut frame| {
|
||||
if Some(frame.record_index) == replay_anchor {
|
||||
frame.item.replacement_history = Some(Vec::new());
|
||||
frame.item.mcp_resource_origins = None;
|
||||
return Some((frame.record_index, frame.item));
|
||||
}
|
||||
frame
|
||||
.owner
|
||||
.is_none_or(|boundary| boundary_alive[boundary])
|
||||
.then_some((frame.record_index, frame.item))
|
||||
})
|
||||
.collect::<HashMap<_, _>>();
|
||||
RollbackPlan {
|
||||
record_boundaries,
|
||||
boundary_alive,
|
||||
compacted_items,
|
||||
}
|
||||
}
|
||||
|
||||
fn start_boundary(&mut self, index: usize) -> usize {
|
||||
let boundary = self.boundaries.len();
|
||||
self.boundaries.push(InstructionBoundary {
|
||||
record_index: index,
|
||||
message_id: None,
|
||||
input_source: RetainedInputSource::Local(None),
|
||||
is_communication: false,
|
||||
alive: true,
|
||||
});
|
||||
let had_prior_boundary = !self.boundary_stack.is_empty();
|
||||
if had_prior_boundary {
|
||||
for pending_index in self.pending_context_records.drain(..) {
|
||||
self.record_boundaries[pending_index] = Some(boundary);
|
||||
}
|
||||
} else {
|
||||
self.pending_context_records.clear();
|
||||
}
|
||||
for pending_index in self.pending_turn_records.drain(..) {
|
||||
self.record_boundaries[pending_index] = Some(boundary);
|
||||
}
|
||||
self.record_boundaries[index] = Some(boundary);
|
||||
self.boundary_stack.push(boundary);
|
||||
self.bind_active_turn(boundary);
|
||||
boundary
|
||||
}
|
||||
|
||||
fn bind_active_turn(&mut self, boundary: usize) {
|
||||
if let Some(turn_id) = self.active_turn_id.as_ref() {
|
||||
self.turn_boundaries.insert(turn_id.clone(), boundary);
|
||||
self.turn_initial_boundaries
|
||||
.entry(turn_id.clone())
|
||||
.or_insert(boundary);
|
||||
}
|
||||
}
|
||||
|
||||
fn assign_targeted_record(&mut self, index: usize, turn_id: Option<&str>) {
|
||||
if let Some(boundary) = turn_id.and_then(|turn_id| self.turn_boundaries.get(turn_id)) {
|
||||
self.record_boundaries[index] = Some(*boundary);
|
||||
} else if self.active_turn_id.is_some()
|
||||
&& self
|
||||
.active_turn_id
|
||||
.as_deref()
|
||||
.is_none_or(|turn_id| !self.turn_boundaries.contains_key(turn_id))
|
||||
{
|
||||
self.pending_turn_records.push(index);
|
||||
}
|
||||
}
|
||||
|
||||
fn apply_rollback(&mut self, num_turns: u32) -> ThreadStoreResult<()> {
|
||||
let count = usize::try_from(num_turns).unwrap_or(usize::MAX);
|
||||
if count == 0 {
|
||||
return Ok(());
|
||||
}
|
||||
let depth_before = self.boundary_stack.len();
|
||||
let mut removed_boundaries = HashSet::new();
|
||||
let mut first_removed_boundary = None;
|
||||
for _ in 0..count {
|
||||
let Some(boundary) = self.boundary_stack.pop() else {
|
||||
break;
|
||||
};
|
||||
self.boundaries[boundary].alive = false;
|
||||
removed_boundaries.insert(boundary);
|
||||
first_removed_boundary = Some(boundary);
|
||||
}
|
||||
if let Some(boundary) = first_removed_boundary {
|
||||
let source = &self.boundaries[boundary];
|
||||
let acceptance_order = source.input_source.acceptance_order();
|
||||
if let Some(order) = acceptance_order {
|
||||
// An answer may have been persisted before the queued instruction
|
||||
// accepted ahead of it. Both are removed at that acceptance boundary.
|
||||
for fact in &self.retained_fact_sources {
|
||||
if fact
|
||||
.acceptance_order
|
||||
.is_some_and(|accepted| accepted >= order)
|
||||
{
|
||||
self.record_boundaries[fact.record_index] = Some(boundary);
|
||||
}
|
||||
}
|
||||
}
|
||||
let removed_turns = self
|
||||
.turn_boundaries
|
||||
.iter()
|
||||
.filter(|(_, boundary)| removed_boundaries.contains(*boundary))
|
||||
.map(|(turn_id, _)| turn_id.as_str())
|
||||
.chain(
|
||||
self.retained_fact_sources
|
||||
.iter()
|
||||
.filter(|fact| {
|
||||
self.record_boundaries[fact.record_index]
|
||||
.is_some_and(|boundary| removed_boundaries.contains(&boundary))
|
||||
})
|
||||
.map(|fact| fact.turn_id.as_str()),
|
||||
)
|
||||
.collect::<Vec<_>>();
|
||||
// Accepted answers can precede a queued instruction in the rollout,
|
||||
// including in checkpoints. Legacy evidence uses the recorded boundary.
|
||||
// Later checkpoints have not been observed yet and already reflect this rollback.
|
||||
for frame in self.compactions.iter_mut().rev().take_while(|frame| {
|
||||
acceptance_order.is_some() || frame.record_index >= source.record_index
|
||||
}) {
|
||||
if let Some(context) = &mut frame.item.retained_context {
|
||||
if acceptance_order.is_some()
|
||||
|| context
|
||||
.ordered_entries()
|
||||
.any(|(_, entry)| matches!(entry, RetainedContextEntry::UserMessage(_)))
|
||||
{
|
||||
context.rollback(
|
||||
&removed_turns,
|
||||
source.message_id.as_ref().map(ResponseItemId::as_str),
|
||||
source.input_source,
|
||||
);
|
||||
} else {
|
||||
// Checkpoints written without instruction retention keep the legacy
|
||||
// source-call boundary, including answers before a same-turn steer.
|
||||
context.retain_answers(|answer| {
|
||||
self.call_boundaries
|
||||
.get(&(answer.turn_id.clone(), answer.call_id.clone()))
|
||||
.map_or_else(
|
||||
|| !removed_turns.contains(&answer.turn_id.as_str()),
|
||||
|boundary| {
|
||||
boundary
|
||||
.is_none_or(|boundary| self.boundaries[boundary].alive)
|
||||
},
|
||||
)
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let compaction_index = self.compactions.iter().rposition(|frame| {
|
||||
frame
|
||||
.owner
|
||||
.is_none_or(|boundary| self.boundaries[boundary].alive)
|
||||
});
|
||||
if let Some(compaction_index) = compaction_index {
|
||||
let frame = &mut self.compactions[compaction_index];
|
||||
let post_compaction_turns = depth_before.saturating_sub(frame.boundary_depth);
|
||||
let remaining = count.saturating_sub(post_compaction_turns);
|
||||
if remaining > 0 {
|
||||
frame.item.mcp_resource_origins = None;
|
||||
let replacement_history =
|
||||
frame.item.replacement_history.as_mut().ok_or_else(|| {
|
||||
migration_error(
|
||||
"legacy rollback crosses a compaction without replacement history",
|
||||
)
|
||||
})?;
|
||||
rollback::drop_last_n_user_turns(
|
||||
replacement_history,
|
||||
u32::try_from(remaining).unwrap_or(u32::MAX),
|
||||
);
|
||||
}
|
||||
}
|
||||
self.active_turn_id = None;
|
||||
self.pending_turn_records.clear();
|
||||
self.pending_context_records.clear();
|
||||
self.pending_user_response = None;
|
||||
self.pending_delivery_boundary = None;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn explicit_event_turn_id(event: &EventMsg) -> Option<&str> {
|
||||
match event {
|
||||
EventMsg::ExecCommandEnd(event) => Some(event.turn_id.as_str()),
|
||||
EventMsg::PatchApplyEnd(event) => Some(event.turn_id.as_str()),
|
||||
EventMsg::DynamicToolCallResponse(event) => Some(event.turn_id.as_str()),
|
||||
EventMsg::EnteredReviewMode(event) => event.turn_id.as_deref(),
|
||||
EventMsg::ExitedReviewMode(event) => event.turn_id.as_deref(),
|
||||
_ => None,
|
||||
}
|
||||
.filter(|turn_id| !turn_id.is_empty())
|
||||
}
|
||||
|
||||
fn user_response_matches_event(content: &[ContentItem], event: &UserMessageEvent) -> bool {
|
||||
let mut text = String::new();
|
||||
let mut images = Vec::new();
|
||||
let mut file_ids = Vec::new();
|
||||
let mut image_order = Vec::new();
|
||||
let mut audio = Vec::new();
|
||||
for item in content {
|
||||
match item {
|
||||
ContentItem::InputText { text: item_text } => text.push_str(item_text),
|
||||
ContentItem::InputImage { image, .. } => match image {
|
||||
ImageReference::Inline { image_url } => {
|
||||
image_order.push(UserMessageImageKind::Inline);
|
||||
images.push(image_url.as_str());
|
||||
}
|
||||
ImageReference::File { file_id } => {
|
||||
image_order.push(UserMessageImageKind::File);
|
||||
file_ids.push(file_id.as_str());
|
||||
}
|
||||
},
|
||||
ContentItem::InputAudio { audio: reference } => audio.push(reference),
|
||||
ContentItem::OutputText { .. } => return false,
|
||||
}
|
||||
}
|
||||
text == event.message
|
||||
&& (!event.has_complete_image_order() || image_order == event.image_order)
|
||||
&& images
|
||||
== event
|
||||
.images
|
||||
.as_deref()
|
||||
.unwrap_or_default()
|
||||
.iter()
|
||||
.map(String::as_str)
|
||||
.collect::<Vec<_>>()
|
||||
&& file_ids
|
||||
== event
|
||||
.file_ids
|
||||
.as_deref()
|
||||
.unwrap_or_default()
|
||||
.iter()
|
||||
.map(String::as_str)
|
||||
.collect::<Vec<_>>()
|
||||
&& {
|
||||
if event.has_complete_audio_order() {
|
||||
let mut actual = audio.into_iter();
|
||||
let mut inline = event.audio.as_deref().unwrap_or_default().iter();
|
||||
let mut file = event.audio_references.as_deref().unwrap_or_default().iter();
|
||||
event.audio_order.iter().all(|kind| {
|
||||
let Some(actual) = actual.next() else {
|
||||
return false;
|
||||
};
|
||||
match kind {
|
||||
UserMessageAudioKind::Inline => matches!(
|
||||
(actual, inline.next()),
|
||||
(
|
||||
AudioReference::Inline { audio_url },
|
||||
Some(expected),
|
||||
) if audio_url == expected
|
||||
),
|
||||
UserMessageAudioKind::File => {
|
||||
file.next().is_some_and(|expected| actual == expected)
|
||||
}
|
||||
}
|
||||
}) && actual.next().is_none()
|
||||
&& inline.next().is_none()
|
||||
&& file.next().is_none()
|
||||
} else {
|
||||
match &event.audio_references {
|
||||
Some(references) => audio.into_iter().eq(references),
|
||||
None => audio
|
||||
.into_iter()
|
||||
.map(|reference| match reference {
|
||||
AudioReference::Inline { audio_url } => Some(audio_url.as_str()),
|
||||
AudioReference::File { .. } => None,
|
||||
})
|
||||
.eq(event
|
||||
.audio
|
||||
.as_deref()
|
||||
.unwrap_or_default()
|
||||
.iter()
|
||||
.map(|url| Some(url.as_str()))),
|
||||
}
|
||||
}
|
||||
}
|
||||
&& event.local_images.is_empty()
|
||||
&& event.local_audio.is_empty()
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
//! Mirrors the part of legacy cold resume that chooses the model-history checkpoint.
|
||||
//!
|
||||
//! Legacy rollback has two jobs. The forward history reducer decides which turns remain visible,
|
||||
//! while cold resume scans backward to find the newest surviving compaction base. Migration needs
|
||||
//! both answers because removing rollback markers must not change what the next resume sends to
|
||||
//! the model.
|
||||
|
||||
use codex_protocol::protocol::EventMsg;
|
||||
use codex_rollout::RolloutItem;
|
||||
|
||||
use super::rollback;
|
||||
|
||||
enum ReplayRecord {
|
||||
Compacted {
|
||||
record_index: usize,
|
||||
has_replacement_history: bool,
|
||||
},
|
||||
Rollback(u32),
|
||||
TurnStarted(String),
|
||||
TurnComplete(String),
|
||||
TurnAborted(Option<String>),
|
||||
TurnContext(Option<String>),
|
||||
UserBoundary,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct ReverseSegment {
|
||||
turn_id: Option<String>,
|
||||
counts_as_user_turn: bool,
|
||||
compaction_index: Option<usize>,
|
||||
}
|
||||
|
||||
/// Rewrite needed when legacy reverse replay skips a compaction segment but still resumes from
|
||||
/// the suffix after that checkpoint.
|
||||
pub(super) struct ModelReplayPlan {
|
||||
pub(super) empty_replacement_history_compaction: Option<usize>,
|
||||
}
|
||||
|
||||
pub(super) struct ModelReplayPlanner {
|
||||
records: Vec<ReplayRecord>,
|
||||
}
|
||||
|
||||
impl ModelReplayPlanner {
|
||||
pub(super) fn new() -> Self {
|
||||
Self {
|
||||
records: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn observe(&mut self, record_index: usize, item: &RolloutItem) {
|
||||
let record = match item {
|
||||
RolloutItem::Compacted(compacted) => ReplayRecord::Compacted {
|
||||
record_index,
|
||||
has_replacement_history: compacted.replacement_history.is_some(),
|
||||
},
|
||||
RolloutItem::EventMsg(EventMsg::ThreadRolledBack(rollback)) => {
|
||||
ReplayRecord::Rollback(rollback.num_turns)
|
||||
}
|
||||
RolloutItem::EventMsg(EventMsg::TurnStarted(event)) => {
|
||||
ReplayRecord::TurnStarted(event.turn_id.clone())
|
||||
}
|
||||
RolloutItem::EventMsg(EventMsg::TurnComplete(event)) => {
|
||||
ReplayRecord::TurnComplete(event.turn_id.clone())
|
||||
}
|
||||
RolloutItem::EventMsg(EventMsg::TurnAborted(event)) => {
|
||||
ReplayRecord::TurnAborted(event.turn_id.clone())
|
||||
}
|
||||
RolloutItem::TurnContext(context) => ReplayRecord::TurnContext(context.turn_id.clone()),
|
||||
RolloutItem::EventMsg(EventMsg::UserMessage(_))
|
||||
| RolloutItem::InterAgentCommunication(_) => ReplayRecord::UserBoundary,
|
||||
RolloutItem::ResponseItem(response) if rollback::counts_as_boundary(&response.item) => {
|
||||
ReplayRecord::UserBoundary
|
||||
}
|
||||
RolloutItem::DynamicToolsUpdated { .. }
|
||||
| RolloutItem::SessionMeta(_)
|
||||
| RolloutItem::ResponseItem(_)
|
||||
| RolloutItem::EventMsg(_)
|
||||
| RolloutItem::InterAgentCommunicationMetadata { .. }
|
||||
| RolloutItem::RealtimeItem(_)
|
||||
| RolloutItem::TokenUsageRecord(_)
|
||||
| RolloutItem::RetainedContext(_)
|
||||
| RolloutItem::SecurityRiskScore(_)
|
||||
| RolloutItem::WorldState(_) => return,
|
||||
};
|
||||
self.records.push(record);
|
||||
}
|
||||
|
||||
pub(super) fn finish(self) -> ModelReplayPlan {
|
||||
let mut selected_compaction = None;
|
||||
let mut suffix_start = None;
|
||||
let mut pending_rollback_turns = 0usize;
|
||||
let mut active_segment: Option<ReverseSegment> = None;
|
||||
|
||||
for record in self.records.iter().rev() {
|
||||
match record {
|
||||
ReplayRecord::Compacted {
|
||||
record_index,
|
||||
has_replacement_history,
|
||||
} => {
|
||||
let segment = active_segment.get_or_insert_with(ReverseSegment::default);
|
||||
if segment.compaction_index.is_none() && *has_replacement_history {
|
||||
segment.compaction_index = Some(*record_index);
|
||||
suffix_start = record_index.checked_add(1);
|
||||
}
|
||||
}
|
||||
ReplayRecord::Rollback(num_turns) => {
|
||||
pending_rollback_turns = pending_rollback_turns
|
||||
.saturating_add(usize::try_from(*num_turns).unwrap_or(usize::MAX));
|
||||
}
|
||||
ReplayRecord::TurnComplete(turn_id) => {
|
||||
let segment = active_segment.get_or_insert_with(ReverseSegment::default);
|
||||
if segment.turn_id.is_none() {
|
||||
segment.turn_id = Some(turn_id.clone());
|
||||
}
|
||||
}
|
||||
ReplayRecord::TurnAborted(turn_id) => {
|
||||
if let Some(segment) = active_segment.as_mut() {
|
||||
if segment.turn_id.is_none() {
|
||||
segment.turn_id = turn_id.clone();
|
||||
}
|
||||
} else if turn_id.is_some() {
|
||||
active_segment = Some(ReverseSegment {
|
||||
turn_id: turn_id.clone(),
|
||||
..Default::default()
|
||||
});
|
||||
}
|
||||
}
|
||||
ReplayRecord::TurnContext(turn_id) => {
|
||||
let segment = active_segment.get_or_insert_with(ReverseSegment::default);
|
||||
if segment.turn_id.is_none() {
|
||||
segment.turn_id = turn_id.clone();
|
||||
}
|
||||
}
|
||||
ReplayRecord::UserBoundary => {
|
||||
active_segment
|
||||
.get_or_insert_with(ReverseSegment::default)
|
||||
.counts_as_user_turn = true;
|
||||
}
|
||||
ReplayRecord::TurnStarted(turn_id) => {
|
||||
if active_segment.as_ref().is_some_and(|segment| {
|
||||
turn_ids_are_compatible(segment.turn_id.as_deref(), Some(turn_id.as_str()))
|
||||
}) && let Some(segment) = active_segment.take()
|
||||
{
|
||||
finalize_segment(
|
||||
segment,
|
||||
&mut selected_compaction,
|
||||
&mut pending_rollback_turns,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(segment) = active_segment {
|
||||
finalize_segment(
|
||||
segment,
|
||||
&mut selected_compaction,
|
||||
&mut pending_rollback_turns,
|
||||
);
|
||||
}
|
||||
|
||||
// If reverse replay saw a replacement-history checkpoint but rolled back its segment,
|
||||
// it resumes from that checkpoint's suffix without using the checkpoint history. Keep an
|
||||
// empty checkpoint in the paginated file so older SQLite-visible records do not leak back
|
||||
// into model context after the rollback markers are gone.
|
||||
let empty_replacement_history_compaction = selected_compaction
|
||||
.is_none()
|
||||
.then_some(suffix_start)
|
||||
.flatten()
|
||||
.and_then(|start| start.checked_sub(1));
|
||||
ModelReplayPlan {
|
||||
empty_replacement_history_compaction,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn finalize_segment(
|
||||
segment: ReverseSegment,
|
||||
selected_compaction: &mut Option<usize>,
|
||||
pending_rollback_turns: &mut usize,
|
||||
) {
|
||||
if *pending_rollback_turns > 0 {
|
||||
if segment.counts_as_user_turn {
|
||||
*pending_rollback_turns -= 1;
|
||||
}
|
||||
return;
|
||||
}
|
||||
if selected_compaction.is_none() {
|
||||
*selected_compaction = segment.compaction_index;
|
||||
}
|
||||
}
|
||||
|
||||
fn turn_ids_are_compatible(active_turn_id: Option<&str>, item_turn_id: Option<&str>) -> bool {
|
||||
active_turn_id
|
||||
.is_none_or(|turn_id| item_turn_id.is_none_or(|item_turn_id| item_turn_id == turn_id))
|
||||
}
|
||||
418
codex-rs/thread-store/src/local/rollout_migration/startup.rs
Normal file
418
codex-rs/thread-store/src/local/rollout_migration/startup.rs
Normal file
@@ -0,0 +1,418 @@
|
||||
//! Decides whether startup needs to invoke legacy -> paginated rollout migration.
|
||||
//!
|
||||
//! It keeps startup cheap by storing a creation-ordered cursor in SQLite and checking only newer
|
||||
//! rollout files on later launches. When it finds legacy history or a pending recovery marker, it
|
||||
//! invokes the existing full migration path.
|
||||
//!
|
||||
//! Rollouts that background migration cannot finish are remembered so they do not hold the cursor
|
||||
//! back forever. Ordinary failures stay skipped until a manual migration retries them; busy
|
||||
//! rollouts are retried on later startups because the writer may have gone away.
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::ffi::OsString;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use std::time::Duration;
|
||||
use std::time::SystemTime;
|
||||
|
||||
use chrono::NaiveDateTime;
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::protocol::ThreadHistoryMode;
|
||||
use codex_rollout::StateDbHandle;
|
||||
use codex_state::RolloutMigrationCursor;
|
||||
use codex_state::RolloutMigrationSkippedRollout;
|
||||
|
||||
use super::LocalThreadStore;
|
||||
use super::RolloutMigrationMode;
|
||||
use super::RolloutMigrationOptions;
|
||||
use super::RolloutMigrationReport;
|
||||
use super::RolloutMigrationStatus;
|
||||
use super::find_all_rollout_paths;
|
||||
use super::migration_error;
|
||||
use super::publish::migration_journal_path;
|
||||
use super::publish::pending_migration_thread_ids;
|
||||
use super::telemetry::RolloutMigrationTrigger;
|
||||
use super::thread_id_from_rollout_filename;
|
||||
use crate::ThreadStoreError;
|
||||
use crate::ThreadStoreResult;
|
||||
|
||||
const LEGACY_TO_PAGINATED_MIGRATION_ID: &str = "legacy_to_paginated_v1";
|
||||
const EMPTY_SKIP_REASON: &str = "empty";
|
||||
const FAILED_SKIP_REASON: &str = "failed";
|
||||
const MALFORMED_SESSION_META_SKIP_REASON: &str = "malformed_session_meta";
|
||||
const BUSY_SKIP_REASON: &str = "busy";
|
||||
const CURSOR_LOOKBACK_SECONDS: i64 = 48 * 60 * 60;
|
||||
const MAINTENANCE_RETRY_DELAY: Duration = Duration::from_secs(1);
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
|
||||
struct RolloutFingerprint {
|
||||
size_bytes: i64,
|
||||
modified_at_ns: i64,
|
||||
}
|
||||
|
||||
enum StartupInspection {
|
||||
Paginated,
|
||||
Legacy,
|
||||
NeedsMigration,
|
||||
Skipped,
|
||||
Unresolved,
|
||||
}
|
||||
|
||||
pub(super) async fn migrate_rollouts_on_startup(store: &LocalThreadStore) -> ThreadStoreResult<()> {
|
||||
let Some(state_db) = store.state_db.as_ref() else {
|
||||
return Ok(());
|
||||
};
|
||||
let paths = find_all_rollout_paths(&store.config.codex_home).await?;
|
||||
let mut skipped_rollouts = state_db
|
||||
.list_rollout_migration_skipped_rollouts(LEGACY_TO_PAGINATED_MIGRATION_ID)
|
||||
.await
|
||||
.map_err(migration_error)?;
|
||||
retry_busy_rollouts(store, skipped_rollouts.as_slice(), paths.as_slice()).await?;
|
||||
skipped_rollouts = state_db
|
||||
.list_rollout_migration_skipped_rollouts(LEGACY_TO_PAGINATED_MIGRATION_ID)
|
||||
.await
|
||||
.map_err(migration_error)?;
|
||||
if !pending_migration_thread_ids(&store.config.codex_home)
|
||||
.await?
|
||||
.is_empty()
|
||||
{
|
||||
return migrate_all_rollouts(store, paths, skipped_rollouts.as_slice()).await;
|
||||
}
|
||||
let skipped_file_names = skipped_rollout_file_names(store, skipped_rollouts.as_slice());
|
||||
let state = state_db
|
||||
.get_rollout_migration_state(LEGACY_TO_PAGINATED_MIGRATION_ID)
|
||||
.await
|
||||
.map_err(migration_error)?;
|
||||
|
||||
if state.is_none() {
|
||||
return migrate_all_rollouts(store, paths, skipped_rollouts.as_slice()).await;
|
||||
}
|
||||
|
||||
let last_checked_thread = state.and_then(|state| state.last_checked_thread);
|
||||
let lookback_created_at = last_checked_thread.as_ref().map(|cursor| {
|
||||
cursor
|
||||
.thread_created_at
|
||||
.saturating_sub(CURSOR_LOOKBACK_SECONDS)
|
||||
});
|
||||
let candidates = paths
|
||||
.iter()
|
||||
.filter(|path| {
|
||||
!plain_rollout_file_name(path)
|
||||
.is_some_and(|file_name| skipped_file_names.contains(&file_name))
|
||||
&& thread_creation_cursor(path).is_none_or(|cursor| {
|
||||
lookback_created_at.is_none_or(|lookback_created_at| {
|
||||
cursor.thread_created_at >= lookback_created_at
|
||||
})
|
||||
})
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
if candidates.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let mut unresolved = false;
|
||||
for path in candidates {
|
||||
match inspect_rollout_path(store, path).await? {
|
||||
StartupInspection::Paginated | StartupInspection::Skipped => {}
|
||||
StartupInspection::Legacy | StartupInspection::NeedsMigration => {
|
||||
return migrate_all_rollouts(store, paths, skipped_rollouts.as_slice()).await;
|
||||
}
|
||||
StartupInspection::Unresolved => unresolved = true,
|
||||
}
|
||||
}
|
||||
if unresolved {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
advance_last_checked_thread(store, paths.as_slice()).await
|
||||
}
|
||||
|
||||
async fn migrate_all_rollouts(
|
||||
store: &LocalThreadStore,
|
||||
paths_before_migration: Vec<PathBuf>,
|
||||
existing_skips: &[RolloutMigrationSkippedRollout],
|
||||
) -> ThreadStoreResult<()> {
|
||||
let skipped_file_names = skipped_rollout_file_names(store, existing_skips);
|
||||
let pending_thread_ids = pending_migration_thread_ids(&store.config.codex_home).await?;
|
||||
let paths_to_migrate = paths_before_migration
|
||||
.iter()
|
||||
.filter(|path| {
|
||||
!plain_rollout_file_name(path)
|
||||
.is_some_and(|file_name| skipped_file_names.contains(&file_name))
|
||||
|| thread_id_from_rollout_filename(path)
|
||||
.is_some_and(|thread_id| pending_thread_ids.contains(&thread_id))
|
||||
})
|
||||
.cloned()
|
||||
.collect();
|
||||
let report = run_startup_migration(store, paths_to_migrate).await?;
|
||||
for outcome in &report.outcomes {
|
||||
update_skip_after_outcome(store, outcome).await?;
|
||||
}
|
||||
// Only mark the pre-migration snapshot; newer rollouts wait for the next startup check.
|
||||
advance_last_checked_thread(store, paths_before_migration.as_slice()).await
|
||||
}
|
||||
|
||||
async fn retry_busy_rollouts(
|
||||
store: &LocalThreadStore,
|
||||
skipped_rollouts: &[RolloutMigrationSkippedRollout],
|
||||
discovered_paths: &[PathBuf],
|
||||
) -> ThreadStoreResult<()> {
|
||||
let mut paths = Vec::new();
|
||||
let mut moved_skip_paths = Vec::new();
|
||||
for skipped_rollout in skipped_rollouts
|
||||
.iter()
|
||||
.filter(|skipped_rollout| skipped_rollout.skip_reason == BUSY_SKIP_REASON)
|
||||
{
|
||||
let stored_path = store.config.codex_home.join(&skipped_rollout.rollout_path);
|
||||
let path = if tokio::fs::try_exists(&stored_path)
|
||||
.await
|
||||
.map_err(migration_error)?
|
||||
{
|
||||
Some(stored_path.clone())
|
||||
} else {
|
||||
// Archive/unarchive moves one rollout between roots, while compression swaps between
|
||||
// its plain and compressed filenames. Match the plain basename across both.
|
||||
let file_name = plain_rollout_file_name(&stored_path);
|
||||
discovered_paths
|
||||
.iter()
|
||||
.find(|path| plain_rollout_file_name(path) == file_name)
|
||||
.cloned()
|
||||
};
|
||||
let Some(path) = path else {
|
||||
continue;
|
||||
};
|
||||
if path != stored_path {
|
||||
moved_skip_paths.push(skipped_rollout.rollout_path.as_str());
|
||||
}
|
||||
paths.push(path);
|
||||
}
|
||||
if paths.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let report = run_startup_migration(store, paths).await?;
|
||||
for moved_skip_path in moved_skip_paths {
|
||||
remove_skip(store, moved_skip_path).await?;
|
||||
}
|
||||
for outcome in &report.outcomes {
|
||||
update_skip_after_outcome(store, outcome).await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn run_startup_migration(
|
||||
store: &LocalThreadStore,
|
||||
paths: Vec<PathBuf>,
|
||||
) -> ThreadStoreResult<RolloutMigrationReport> {
|
||||
loop {
|
||||
let Some(maintenance_guard) =
|
||||
codex_rollout::try_acquire_rollout_maintenance_lock(&store.config.codex_home)
|
||||
.map_err(migration_error)?
|
||||
else {
|
||||
#[cfg(test)]
|
||||
if let Some(gate) = &store.startup_migration_retry_gate {
|
||||
gate.retry_started.notify_one();
|
||||
gate.retry_allowed.notified().await;
|
||||
continue;
|
||||
}
|
||||
tokio::time::sleep(MAINTENANCE_RETRY_DELAY).await;
|
||||
continue;
|
||||
};
|
||||
// Avoid counting expected compression contention as a failed migration run. The migration
|
||||
// path takes the real lock below, so retry if another maintainer wins this small gap.
|
||||
drop(maintenance_guard);
|
||||
match store
|
||||
.migrate_rollouts_with_progress_for_trigger(
|
||||
RolloutMigrationOptions {
|
||||
mode: RolloutMigrationMode::Apply,
|
||||
thread_ids: Vec::new(),
|
||||
max_mib_per_second: None,
|
||||
},
|
||||
|_| {},
|
||||
RolloutMigrationTrigger::Startup,
|
||||
super::RolloutMigrationPaths::Known(paths.clone()),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Err(ThreadStoreError::Conflict { .. }) => continue,
|
||||
result => return result,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn update_skip_after_outcome(
|
||||
store: &LocalThreadStore,
|
||||
outcome: &super::RolloutMigrationOutcome,
|
||||
) -> ThreadStoreResult<()> {
|
||||
let relative_path = relative_rollout_path(store, &outcome.rollout_path);
|
||||
match outcome.status {
|
||||
RolloutMigrationStatus::Migrated | RolloutMigrationStatus::AlreadyPaginated => {
|
||||
remove_skip(store, relative_path.as_str()).await
|
||||
}
|
||||
RolloutMigrationStatus::SkippedEmpty => {
|
||||
record_current_skip(store, &outcome.rollout_path, EMPTY_SKIP_REASON).await
|
||||
}
|
||||
RolloutMigrationStatus::SkippedBusy => {
|
||||
record_current_skip(store, &outcome.rollout_path, BUSY_SKIP_REASON).await
|
||||
}
|
||||
RolloutMigrationStatus::Failed => {
|
||||
if outcome.thread_id.is_some_and(|thread_id| {
|
||||
migration_journal_path(&store.config.codex_home, thread_id).exists()
|
||||
}) {
|
||||
return Ok(());
|
||||
}
|
||||
record_current_skip(store, &outcome.rollout_path, FAILED_SKIP_REASON).await
|
||||
}
|
||||
RolloutMigrationStatus::Eligible => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
async fn inspect_rollout_path(
|
||||
store: &LocalThreadStore,
|
||||
path: &Path,
|
||||
) -> ThreadStoreResult<StartupInspection> {
|
||||
let before = rollout_fingerprint(path).await?;
|
||||
match codex_rollout::read_session_meta_line(path).await {
|
||||
Ok(metadata) if metadata.meta.history_mode == ThreadHistoryMode::Legacy => {
|
||||
Ok(StartupInspection::Legacy)
|
||||
}
|
||||
Ok(_) => Ok(StartupInspection::Paginated),
|
||||
Err(_) => {
|
||||
let after = rollout_fingerprint(path).await?;
|
||||
if before != after {
|
||||
return Ok(StartupInspection::Unresolved);
|
||||
}
|
||||
// The migration path re-reads empty files under the writer lock before deciding
|
||||
// whether they are terminally empty or just waiting for SessionMeta.
|
||||
if before.size_bytes == 0 {
|
||||
return Ok(StartupInspection::NeedsMigration);
|
||||
}
|
||||
record_skip(store, path, before, MALFORMED_SESSION_META_SKIP_REASON).await?;
|
||||
Ok(StartupInspection::Skipped)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn record_current_skip(
|
||||
store: &LocalThreadStore,
|
||||
path: &Path,
|
||||
skip_reason: &str,
|
||||
) -> ThreadStoreResult<()> {
|
||||
// These fields remain in the generic schema, but background skips are permanent now. Keep
|
||||
// recording the best available fingerprint for humans inspecting SQLite.
|
||||
let fingerprint = rollout_fingerprint(path).await.unwrap_or_default();
|
||||
record_skip(store, path, fingerprint, skip_reason).await
|
||||
}
|
||||
|
||||
async fn record_skip(
|
||||
store: &LocalThreadStore,
|
||||
path: &Path,
|
||||
fingerprint: RolloutFingerprint,
|
||||
skip_reason: &str,
|
||||
) -> ThreadStoreResult<()> {
|
||||
let state_db = startup_state_db(store)?;
|
||||
let skipped_rollout = RolloutMigrationSkippedRollout {
|
||||
rollout_path: relative_rollout_path(store, path),
|
||||
rollout_size_bytes: fingerprint.size_bytes,
|
||||
rollout_modified_at_ns: fingerprint.modified_at_ns,
|
||||
skip_reason: skip_reason.to_string(),
|
||||
};
|
||||
state_db
|
||||
.record_rollout_migration_skip(LEGACY_TO_PAGINATED_MIGRATION_ID, &skipped_rollout)
|
||||
.await
|
||||
.map_err(migration_error)
|
||||
}
|
||||
|
||||
async fn remove_skip(store: &LocalThreadStore, rollout_path: &str) -> ThreadStoreResult<()> {
|
||||
startup_state_db(store)?
|
||||
.remove_rollout_migration_skip(LEGACY_TO_PAGINATED_MIGRATION_ID, rollout_path)
|
||||
.await
|
||||
.map_err(migration_error)
|
||||
}
|
||||
|
||||
async fn advance_last_checked_thread(
|
||||
store: &LocalThreadStore,
|
||||
paths: &[PathBuf],
|
||||
) -> ThreadStoreResult<()> {
|
||||
let last_checked_thread = paths
|
||||
.iter()
|
||||
.filter_map(|path| thread_creation_cursor(path))
|
||||
.max();
|
||||
startup_state_db(store)?
|
||||
.advance_rollout_migration_state(
|
||||
LEGACY_TO_PAGINATED_MIGRATION_ID,
|
||||
last_checked_thread.as_ref(),
|
||||
)
|
||||
.await
|
||||
.map_err(migration_error)
|
||||
}
|
||||
|
||||
fn startup_state_db(store: &LocalThreadStore) -> ThreadStoreResult<&StateDbHandle> {
|
||||
store
|
||||
.state_db
|
||||
.as_ref()
|
||||
.ok_or_else(|| migration_error("startup migration requires state db"))
|
||||
}
|
||||
|
||||
fn thread_creation_cursor(path: &Path) -> Option<RolloutMigrationCursor> {
|
||||
let name = path.file_name()?.to_str()?;
|
||||
let stem = name
|
||||
.strip_suffix(".jsonl.zst")
|
||||
.or_else(|| name.strip_suffix(".jsonl"))?
|
||||
.strip_prefix("rollout-")?;
|
||||
let separator = stem.len().checked_sub(37)?;
|
||||
let thread_id = stem.get(separator + 1..)?;
|
||||
ThreadId::from_string(thread_id).ok()?;
|
||||
let timestamp = NaiveDateTime::parse_from_str(stem.get(..separator)?, "%Y-%m-%dT%H-%M-%S")
|
||||
.ok()?
|
||||
.and_utc()
|
||||
.timestamp();
|
||||
Some(RolloutMigrationCursor {
|
||||
thread_created_at: timestamp,
|
||||
thread_id: thread_id.to_string(),
|
||||
})
|
||||
}
|
||||
|
||||
fn relative_rollout_path(store: &LocalThreadStore, path: &Path) -> String {
|
||||
path.strip_prefix(&store.config.codex_home)
|
||||
.unwrap_or(path)
|
||||
.to_string_lossy()
|
||||
.replace('\\', "/")
|
||||
}
|
||||
|
||||
fn skipped_rollout_file_names(
|
||||
store: &LocalThreadStore,
|
||||
skipped_rollouts: &[RolloutMigrationSkippedRollout],
|
||||
) -> HashSet<OsString> {
|
||||
skipped_rollouts
|
||||
.iter()
|
||||
.filter_map(|skipped_rollout| {
|
||||
plain_rollout_file_name(&store.config.codex_home.join(&skipped_rollout.rollout_path))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn plain_rollout_file_name(path: &Path) -> Option<OsString> {
|
||||
codex_rollout::plain_rollout_path(path)
|
||||
.file_name()
|
||||
.map(std::ffi::OsStr::to_os_string)
|
||||
}
|
||||
|
||||
async fn rollout_fingerprint(path: &Path) -> ThreadStoreResult<RolloutFingerprint> {
|
||||
let metadata = tokio::fs::metadata(path).await.map_err(migration_error)?;
|
||||
let size_bytes = i64::try_from(metadata.len()).map_err(migration_error)?;
|
||||
let modified_at_ns = metadata
|
||||
.modified()
|
||||
.map_err(migration_error)?
|
||||
.duration_since(SystemTime::UNIX_EPOCH)
|
||||
.map_err(migration_error)?
|
||||
.as_nanos();
|
||||
let modified_at_ns = i64::try_from(modified_at_ns).map_err(migration_error)?;
|
||||
Ok(RolloutFingerprint {
|
||||
size_bytes,
|
||||
modified_at_ns,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "startup_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,566 @@
|
||||
use std::fs;
|
||||
use std::io::Write;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::protocol::EventMsg;
|
||||
use codex_protocol::protocol::SessionMeta;
|
||||
use codex_protocol::protocol::SessionMetaLine;
|
||||
use codex_protocol::protocol::SessionSource;
|
||||
use codex_protocol::protocol::ThreadHistoryMode;
|
||||
use codex_protocol::protocol::UserMessageEvent;
|
||||
use codex_rollout::RolloutConfig;
|
||||
use codex_rollout::RolloutItem;
|
||||
use codex_rollout::RolloutLine;
|
||||
use codex_rollout::RolloutRecorder;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tempfile::TempDir;
|
||||
|
||||
use super::super::publish::migration_journal_path;
|
||||
use super::super::publish::write_migration_journal;
|
||||
use super::super::thread_history;
|
||||
use super::LocalThreadStore;
|
||||
use crate::local::StartupMigrationRetryGate;
|
||||
use crate::local::test_support::test_config;
|
||||
|
||||
const TIMESTAMP: &str = "2025-01-03T12:00:00Z";
|
||||
|
||||
fn write_rollout(home: &Path, thread_id: ThreadId, history_mode: ThreadHistoryMode) -> PathBuf {
|
||||
let directory = home.join("sessions/2025/01/03");
|
||||
fs::create_dir_all(&directory).expect("create rollout directory");
|
||||
let path = directory.join(format!("rollout-2025-01-03T12-00-00-{thread_id}.jsonl"));
|
||||
let mut file = fs::File::create(&path).expect("create legacy rollout");
|
||||
let paginated = history_mode == ThreadHistoryMode::Paginated;
|
||||
let metadata = SessionMeta {
|
||||
session_id: thread_id.into(),
|
||||
id: thread_id,
|
||||
timestamp: TIMESTAMP.to_string(),
|
||||
cwd: home.to_path_buf(),
|
||||
originator: "test-originator".to_string(),
|
||||
cli_version: "0.0.0".to_string(),
|
||||
source: SessionSource::Cli,
|
||||
model_provider: Some("test-provider".to_string()),
|
||||
history_mode,
|
||||
..SessionMeta::default()
|
||||
};
|
||||
for (ordinal, item) in [
|
||||
RolloutItem::SessionMeta(Box::new(SessionMetaLine {
|
||||
meta: metadata,
|
||||
git: None,
|
||||
})),
|
||||
RolloutItem::EventMsg(EventMsg::UserMessage(UserMessageEvent {
|
||||
message: "question".to_string(),
|
||||
..UserMessageEvent::default()
|
||||
})),
|
||||
]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
{
|
||||
let line = RolloutLine {
|
||||
timestamp: TIMESTAMP.to_string(),
|
||||
ordinal: paginated.then_some(ordinal as u64),
|
||||
item,
|
||||
};
|
||||
writeln!(
|
||||
file,
|
||||
"{}",
|
||||
serde_json::to_string(&line).expect("serialize legacy record")
|
||||
)
|
||||
.expect("write legacy record");
|
||||
}
|
||||
path
|
||||
}
|
||||
|
||||
fn move_to_timestamp(
|
||||
home: &Path,
|
||||
path: PathBuf,
|
||||
session_day: &str,
|
||||
filename_timestamp: &str,
|
||||
) -> PathBuf {
|
||||
let directory = home.join(format!("sessions/{session_day}"));
|
||||
fs::create_dir_all(&directory).expect("create rollout directory");
|
||||
let stem = path
|
||||
.file_name()
|
||||
.and_then(|name| name.to_str())
|
||||
.and_then(|name| name.strip_suffix(".jsonl"))
|
||||
.expect("rollout filename");
|
||||
let thread_id = stem
|
||||
.get(stem.len().checked_sub(36).expect("thread id offset")..)
|
||||
.expect("thread id in rollout filename");
|
||||
let moved_path = directory.join(format!("rollout-{filename_timestamp}-{thread_id}.jsonl"));
|
||||
fs::rename(path, &moved_path).expect("move rollout timestamp");
|
||||
moved_path
|
||||
}
|
||||
|
||||
async fn indexed_store(home: &Path) -> LocalThreadStore {
|
||||
let config = test_config(home);
|
||||
let rollout_config = RolloutConfig {
|
||||
codex_home: config.codex_home.clone(),
|
||||
sqlite: config.sqlite.clone(),
|
||||
cwd: home.to_path_buf(),
|
||||
model_provider_id: config.default_model_provider_id.clone(),
|
||||
generate_memories: false,
|
||||
};
|
||||
let state_db = codex_rollout::state_db::try_init(&rollout_config)
|
||||
.await
|
||||
.expect("backfill legacy thread metadata");
|
||||
LocalThreadStore::new(config, Some(state_db))
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn records_and_advances_checked_thread() {
|
||||
let home = TempDir::new().expect("create Codex home");
|
||||
let legacy_thread_id = ThreadId::new();
|
||||
let legacy_path = write_rollout(home.path(), legacy_thread_id, ThreadHistoryMode::Legacy);
|
||||
let store = indexed_store(home.path()).await;
|
||||
|
||||
store
|
||||
.migrate_rollouts_on_startup()
|
||||
.await
|
||||
.expect("migrate startup rollouts");
|
||||
assert_eq!(
|
||||
codex_rollout::read_session_meta_line(&legacy_path)
|
||||
.await
|
||||
.expect("read migrated metadata")
|
||||
.meta
|
||||
.history_mode,
|
||||
ThreadHistoryMode::Paginated
|
||||
);
|
||||
|
||||
let newer_thread_id = ThreadId::new();
|
||||
move_to_timestamp(
|
||||
home.path(),
|
||||
write_rollout(home.path(), newer_thread_id, ThreadHistoryMode::Paginated),
|
||||
"2025/01/04",
|
||||
"2025-01-04T12-00-00",
|
||||
);
|
||||
store
|
||||
.migrate_rollouts_on_startup()
|
||||
.await
|
||||
.expect("check newer paginated rollout");
|
||||
|
||||
let state = store
|
||||
.state_db()
|
||||
.await
|
||||
.expect("state db")
|
||||
.get_rollout_migration_state(super::LEGACY_TO_PAGINATED_MIGRATION_ID)
|
||||
.await
|
||||
.expect("read migration state")
|
||||
.expect("migration state");
|
||||
assert_eq!(
|
||||
state
|
||||
.last_checked_thread
|
||||
.expect("last checked thread")
|
||||
.thread_id,
|
||||
newer_thread_id.to_string()
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn checks_rollouts_within_the_cursor_lookback() {
|
||||
let home = TempDir::new().expect("create Codex home");
|
||||
let older_thread_id = ThreadId::new();
|
||||
let older_path = move_to_timestamp(
|
||||
home.path(),
|
||||
write_rollout(home.path(), older_thread_id, ThreadHistoryMode::Legacy),
|
||||
"2025/01/02",
|
||||
"2025-01-02T12-00-00",
|
||||
);
|
||||
let newer_path = move_to_timestamp(
|
||||
home.path(),
|
||||
write_rollout(home.path(), ThreadId::new(), ThreadHistoryMode::Paginated),
|
||||
"2025/01/03",
|
||||
"2025-01-03T12-00-00",
|
||||
);
|
||||
let store = indexed_store(home.path()).await;
|
||||
let cursor = super::thread_creation_cursor(&newer_path).expect("newer rollout cursor");
|
||||
store
|
||||
.state_db()
|
||||
.await
|
||||
.expect("state db")
|
||||
.advance_rollout_migration_state(super::LEGACY_TO_PAGINATED_MIGRATION_ID, Some(&cursor))
|
||||
.await
|
||||
.expect("seed migration cursor");
|
||||
|
||||
store
|
||||
.migrate_rollouts_on_startup()
|
||||
.await
|
||||
.expect("check rollout behind cursor");
|
||||
|
||||
assert_eq!(
|
||||
codex_rollout::read_session_meta_line(&older_path)
|
||||
.await
|
||||
.expect("read migrated metadata")
|
||||
.meta
|
||||
.history_mode,
|
||||
ThreadHistoryMode::Paginated
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn recovers_pending_migrations_after_retrying_busy_rollouts() {
|
||||
let home = TempDir::new().expect("create Codex home");
|
||||
let pending_thread_id = ThreadId::new();
|
||||
write_rollout(home.path(), pending_thread_id, ThreadHistoryMode::Legacy);
|
||||
let busy_thread_id = ThreadId::new();
|
||||
let busy_path = move_to_timestamp(
|
||||
home.path(),
|
||||
write_rollout(home.path(), busy_thread_id, ThreadHistoryMode::Legacy),
|
||||
"2025/01/04",
|
||||
"2025-01-04T12-00-00",
|
||||
);
|
||||
let store = indexed_store(home.path()).await;
|
||||
let state_db = store.state_db().await.expect("state db");
|
||||
let writer_guard = store
|
||||
.acquire_writer_lock(busy_thread_id)
|
||||
.expect("hold cross-process writer lock");
|
||||
|
||||
store
|
||||
.migrate_rollouts_on_startup()
|
||||
.await
|
||||
.expect("migrate and record busy rollout");
|
||||
drop(writer_guard);
|
||||
thread_history::delete_thread(&store, pending_thread_id)
|
||||
.await
|
||||
.expect("simulate missing projection");
|
||||
let journal_path = migration_journal_path(home.path(), pending_thread_id);
|
||||
write_migration_journal(&journal_path)
|
||||
.await
|
||||
.expect("simulate pending migration marker");
|
||||
|
||||
store
|
||||
.migrate_rollouts_on_startup()
|
||||
.await
|
||||
.expect("retry busy rollout before recovery");
|
||||
|
||||
assert_eq!(
|
||||
codex_rollout::read_session_meta_line(&busy_path)
|
||||
.await
|
||||
.expect("read migrated metadata")
|
||||
.meta
|
||||
.history_mode,
|
||||
ThreadHistoryMode::Paginated
|
||||
);
|
||||
assert!(!journal_path.exists());
|
||||
assert!(
|
||||
thread_history::projection_state(&store, pending_thread_id)
|
||||
.await
|
||||
.expect("read repaired projection")
|
||||
.is_some()
|
||||
);
|
||||
assert!(
|
||||
state_db
|
||||
.list_rollout_migration_skipped_rollouts(super::LEGACY_TO_PAGINATED_MIGRATION_ID)
|
||||
.await
|
||||
.expect("read skipped rollouts")
|
||||
.is_empty()
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn waits_for_a_live_writer_before_migrating() {
|
||||
let home = TempDir::new().expect("create Codex home");
|
||||
let thread_id = ThreadId::new();
|
||||
let path = write_rollout(home.path(), thread_id, ThreadHistoryMode::Legacy);
|
||||
let store = indexed_store(home.path()).await;
|
||||
let live_writer_guard = store.live_writer_locks.lock(thread_id).await;
|
||||
let migration_store = store.clone();
|
||||
let mut migration = tokio::spawn(async move {
|
||||
migration_store
|
||||
.migrate_rollouts_on_startup()
|
||||
.await
|
||||
.expect("migrate startup rollouts");
|
||||
});
|
||||
|
||||
assert!(
|
||||
tokio::time::timeout(Duration::from_millis(50), &mut migration)
|
||||
.await
|
||||
.is_err(),
|
||||
"migration should wait for the live writer"
|
||||
);
|
||||
drop(live_writer_guard);
|
||||
migration.await.expect("join startup migration");
|
||||
|
||||
assert_eq!(
|
||||
codex_rollout::read_session_meta_line(&path)
|
||||
.await
|
||||
.expect("read migrated metadata")
|
||||
.meta
|
||||
.history_mode,
|
||||
ThreadHistoryMode::Paginated
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn waits_for_rollout_maintenance_before_migrating() {
|
||||
let home = TempDir::new().expect("create Codex home");
|
||||
let thread_id = ThreadId::new();
|
||||
let path = write_rollout(home.path(), thread_id, ThreadHistoryMode::Legacy);
|
||||
let mut store = indexed_store(home.path()).await;
|
||||
let gate = Arc::new(StartupMigrationRetryGate::default());
|
||||
store.startup_migration_retry_gate = Some(Arc::clone(&gate));
|
||||
let maintenance_guard = codex_rollout::try_acquire_rollout_maintenance_lock(home.path())
|
||||
.expect("acquire rollout maintenance lock")
|
||||
.expect("claim rollout maintenance lock");
|
||||
let migration_store = store.clone();
|
||||
let mut migration = tokio::spawn(async move {
|
||||
migration_store
|
||||
.migrate_rollouts_on_startup()
|
||||
.await
|
||||
.expect("migrate startup rollouts");
|
||||
});
|
||||
|
||||
// Observe real lock contention instead of assuming the task reached it after 50 ms.
|
||||
tokio::time::timeout(Duration::from_secs(2), async {
|
||||
tokio::select! {
|
||||
result = &mut migration => panic!("migration should wait for rollout maintenance: {result:?}"),
|
||||
_ = gate.retry_started.notified() => {}
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("migration should encounter rollout maintenance");
|
||||
assert_eq!(
|
||||
codex_rollout::read_session_meta_line(&path)
|
||||
.await
|
||||
.expect("read metadata while maintenance is held")
|
||||
.meta
|
||||
.history_mode,
|
||||
ThreadHistoryMode::Legacy
|
||||
);
|
||||
|
||||
drop(maintenance_guard);
|
||||
// Drive the retry explicitly so the completion budget does not include the production backoff.
|
||||
gate.retry_allowed.notify_one();
|
||||
tokio::time::timeout(Duration::from_secs(2), migration)
|
||||
.await
|
||||
.expect("migration should retry rollout maintenance")
|
||||
.expect("join startup migration");
|
||||
|
||||
assert_eq!(
|
||||
codex_rollout::read_session_meta_line(&path)
|
||||
.await
|
||||
.expect("read migrated metadata")
|
||||
.meta
|
||||
.history_mode,
|
||||
ThreadHistoryMode::Paginated
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn permanently_skips_failed_rollouts_without_blocking_the_cursor() {
|
||||
let home = TempDir::new().expect("create Codex home");
|
||||
let failed_thread_id = ThreadId::new();
|
||||
let failed_path = write_rollout(home.path(), failed_thread_id, ThreadHistoryMode::Legacy);
|
||||
let store = indexed_store(home.path()).await;
|
||||
let state_db = store.state_db().await.expect("state db");
|
||||
let metadata = state_db
|
||||
.get_thread(failed_thread_id)
|
||||
.await
|
||||
.expect("read thread metadata")
|
||||
.expect("thread metadata");
|
||||
state_db
|
||||
.delete_thread(failed_thread_id)
|
||||
.await
|
||||
.expect("remove thread metadata");
|
||||
|
||||
store
|
||||
.migrate_rollouts_on_startup()
|
||||
.await
|
||||
.expect("record failed rollout");
|
||||
assert_eq!(
|
||||
state_db
|
||||
.get_rollout_migration_state(super::LEGACY_TO_PAGINATED_MIGRATION_ID)
|
||||
.await
|
||||
.expect("read migration state")
|
||||
.expect("migration state")
|
||||
.last_checked_thread
|
||||
.expect("checked thread")
|
||||
.thread_id,
|
||||
failed_thread_id.to_string()
|
||||
);
|
||||
assert_eq!(
|
||||
state_db
|
||||
.list_rollout_migration_skipped_rollouts(super::LEGACY_TO_PAGINATED_MIGRATION_ID)
|
||||
.await
|
||||
.expect("read skipped rollouts")
|
||||
.into_iter()
|
||||
.map(|skipped_rollout| skipped_rollout.skip_reason)
|
||||
.collect::<Vec<_>>(),
|
||||
vec![super::FAILED_SKIP_REASON.to_string()]
|
||||
);
|
||||
|
||||
state_db
|
||||
.insert_thread_if_absent(&metadata)
|
||||
.await
|
||||
.expect("restore thread metadata");
|
||||
let archived_directory = home.path().join(codex_rollout::ARCHIVED_SESSIONS_SUBDIR);
|
||||
fs::create_dir_all(&archived_directory).expect("create archived directory");
|
||||
let archived_path = archived_directory.join(failed_path.file_name().expect("rollout filename"));
|
||||
fs::rename(&failed_path, &archived_path).expect("archive failed rollout");
|
||||
|
||||
store
|
||||
.migrate_rollouts_on_startup()
|
||||
.await
|
||||
.expect("skip failed rollout again");
|
||||
|
||||
assert_eq!(
|
||||
codex_rollout::read_session_meta_line(&archived_path)
|
||||
.await
|
||||
.expect("read failed rollout metadata")
|
||||
.meta
|
||||
.history_mode,
|
||||
ThreadHistoryMode::Legacy
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn retries_busy_rollouts_after_archive_and_compression_move() {
|
||||
let home = TempDir::new().expect("create Codex home");
|
||||
let thread_id = ThreadId::new();
|
||||
let path = move_to_timestamp(
|
||||
home.path(),
|
||||
write_rollout(home.path(), thread_id, ThreadHistoryMode::Legacy),
|
||||
"2025/01/01",
|
||||
"2025-01-01T12-00-00",
|
||||
);
|
||||
let newest_thread_id = ThreadId::new();
|
||||
move_to_timestamp(
|
||||
home.path(),
|
||||
write_rollout(home.path(), newest_thread_id, ThreadHistoryMode::Paginated),
|
||||
"2025/01/04",
|
||||
"2025-01-04T12-00-00",
|
||||
);
|
||||
let store = indexed_store(home.path()).await;
|
||||
let state_db = store.state_db().await.expect("state db");
|
||||
let writer_guard = store
|
||||
.acquire_writer_lock(thread_id)
|
||||
.expect("hold cross-process writer lock");
|
||||
|
||||
store
|
||||
.migrate_rollouts_on_startup()
|
||||
.await
|
||||
.expect("record busy rollout");
|
||||
assert_eq!(
|
||||
state_db
|
||||
.get_rollout_migration_state(super::LEGACY_TO_PAGINATED_MIGRATION_ID)
|
||||
.await
|
||||
.expect("read migration state")
|
||||
.expect("migration state")
|
||||
.last_checked_thread
|
||||
.expect("checked thread")
|
||||
.thread_id,
|
||||
newest_thread_id.to_string()
|
||||
);
|
||||
assert_eq!(
|
||||
state_db
|
||||
.list_rollout_migration_skipped_rollouts(super::LEGACY_TO_PAGINATED_MIGRATION_ID)
|
||||
.await
|
||||
.expect("read skipped rollouts")
|
||||
.into_iter()
|
||||
.map(|skipped_rollout| skipped_rollout.skip_reason)
|
||||
.collect::<Vec<_>>(),
|
||||
vec![super::BUSY_SKIP_REASON.to_string()]
|
||||
);
|
||||
|
||||
drop(writer_guard);
|
||||
let archived_directory = home.path().join(codex_rollout::ARCHIVED_SESSIONS_SUBDIR);
|
||||
fs::create_dir_all(&archived_directory).expect("create archived directory");
|
||||
let archived_path = archived_directory.join(path.file_name().expect("rollout filename"));
|
||||
fs::rename(&path, &archived_path).expect("archive busy rollout");
|
||||
let compressed_path = archived_path.with_extension("jsonl.zst");
|
||||
let mut input = fs::File::open(&archived_path).expect("open archived rollout");
|
||||
let output = fs::File::create(&compressed_path).expect("create compressed rollout");
|
||||
let mut encoder = zstd::stream::write::Encoder::new(output, 0).expect("create encoder");
|
||||
std::io::copy(&mut input, &mut encoder).expect("compress archived rollout");
|
||||
encoder.finish().expect("finish compressed rollout");
|
||||
fs::remove_file(&archived_path).expect("remove plain archived rollout");
|
||||
store
|
||||
.migrate_rollouts_on_startup()
|
||||
.await
|
||||
.expect("retry no-longer-busy rollout");
|
||||
|
||||
assert_eq!(
|
||||
codex_rollout::read_session_meta_line(&compressed_path)
|
||||
.await
|
||||
.expect("read migrated metadata")
|
||||
.meta
|
||||
.history_mode,
|
||||
ThreadHistoryMode::Paginated
|
||||
);
|
||||
assert!(
|
||||
state_db
|
||||
.list_rollout_migration_skipped_rollouts(super::LEGACY_TO_PAGINATED_MIGRATION_ID)
|
||||
.await
|
||||
.expect("read skipped rollouts")
|
||||
.is_empty()
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn treats_writer_owned_empty_rollouts_as_busy() {
|
||||
let home = TempDir::new().expect("create Codex home");
|
||||
write_rollout(home.path(), ThreadId::new(), ThreadHistoryMode::Paginated);
|
||||
let store = indexed_store(home.path()).await;
|
||||
store
|
||||
.migrate_rollouts_on_startup()
|
||||
.await
|
||||
.expect("seed startup cursor");
|
||||
|
||||
let thread_id = ThreadId::new();
|
||||
let path = move_to_timestamp(
|
||||
home.path(),
|
||||
write_rollout(home.path(), thread_id, ThreadHistoryMode::Legacy),
|
||||
"2025/01/04",
|
||||
"2025-01-04T12-00-00",
|
||||
);
|
||||
let (items, _, _) = RolloutRecorder::load_rollout_items(&path)
|
||||
.await
|
||||
.expect("load rollout items");
|
||||
let metadata = codex_rollout::builder_from_items(items.as_slice(), &path)
|
||||
.expect("build thread metadata")
|
||||
.build("test-provider");
|
||||
let contents = fs::read(&path).expect("read rollout before emptying");
|
||||
fs::write(&path, []).expect("empty rollout");
|
||||
let state_db = store.state_db().await.expect("state db");
|
||||
state_db
|
||||
.upsert_thread(&metadata)
|
||||
.await
|
||||
.expect("seed thread metadata");
|
||||
let writer_guard = store
|
||||
.acquire_writer_lock(thread_id)
|
||||
.expect("hold cross-process writer lock");
|
||||
|
||||
store
|
||||
.migrate_rollouts_on_startup()
|
||||
.await
|
||||
.expect("record empty rollout as busy");
|
||||
assert_eq!(
|
||||
state_db
|
||||
.list_rollout_migration_skipped_rollouts(super::LEGACY_TO_PAGINATED_MIGRATION_ID)
|
||||
.await
|
||||
.expect("read skipped rollouts")
|
||||
.into_iter()
|
||||
.map(|skipped_rollout| skipped_rollout.skip_reason)
|
||||
.collect::<Vec<_>>(),
|
||||
vec![super::BUSY_SKIP_REASON.to_string()]
|
||||
);
|
||||
|
||||
fs::write(&path, contents).expect("restore rollout");
|
||||
drop(writer_guard);
|
||||
store
|
||||
.migrate_rollouts_on_startup()
|
||||
.await
|
||||
.expect("retry no-longer-empty rollout");
|
||||
|
||||
assert_eq!(
|
||||
codex_rollout::read_session_meta_line(&path)
|
||||
.await
|
||||
.expect("read migrated metadata")
|
||||
.meta
|
||||
.history_mode,
|
||||
ThreadHistoryMode::Paginated
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
//! Selects a smaller resume context for legacy subagent rollouts.
|
||||
//!
|
||||
//! Legacy subagents copied the parent's full rollout into every child rollout. Migrating those
|
||||
//! files verbatim can preserve gigabytes of duplicated history even though a resumed subagent only
|
||||
//! needs its latest bounded model context.
|
||||
//!
|
||||
//! This module reverse-scans the legacy rollout for the newest compaction with replacement history
|
||||
//! and a window number. Malformed records are skipped. If no such compaction exists, the caller
|
||||
//! falls back to full tolerant replay.
|
||||
|
||||
use std::fs::File;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use codex_rollout::ModelContextScan;
|
||||
use codex_rollout::ModelContextScanProgress;
|
||||
use codex_rollout::ReverseJsonlScanner;
|
||||
use codex_rollout::RolloutItem;
|
||||
use codex_rollout::ScanOutcome;
|
||||
use serde_json::Value;
|
||||
|
||||
use super::line_parser;
|
||||
use super::migration_error;
|
||||
use crate::ThreadStoreResult;
|
||||
|
||||
/// Returns the suffix starting at the newest usable compaction, if one exists.
|
||||
pub(super) async fn select_bounded_context(
|
||||
rollout_path: PathBuf,
|
||||
) -> ThreadStoreResult<Option<Vec<RolloutItem>>> {
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let file = File::open(rollout_path).map_err(migration_error)?;
|
||||
let mut scanner = ReverseJsonlScanner::new(file)
|
||||
.map_err(migration_error)?
|
||||
.with_max_record_bytes(super::MAX_ROLLOUT_LINE_BYTES);
|
||||
let mut scan = ModelContextScan::default();
|
||||
|
||||
while let Some(outcome) = scanner.scan_next::<Value>().map_err(migration_error)? {
|
||||
let value = match outcome {
|
||||
ScanOutcome::Parsed(value) => value,
|
||||
ScanOutcome::Rejected(_) => continue,
|
||||
};
|
||||
let Ok(Some(line)) = line_parser::parse_legacy_rollout_value(value) else {
|
||||
continue;
|
||||
};
|
||||
if scan.push(line.item) == ModelContextScanProgress::Complete {
|
||||
let mut items = scan.finish();
|
||||
items.retain(|item| !matches!(item, RolloutItem::SessionMeta(_)));
|
||||
return Ok(Some(items));
|
||||
}
|
||||
}
|
||||
|
||||
Ok(None)
|
||||
})
|
||||
.await
|
||||
.map_err(migration_error)?
|
||||
}
|
||||
152
codex-rs/thread-store/src/local/rollout_migration/telemetry.rs
Normal file
152
codex-rs/thread-store/src/local/rollout_migration/telemetry.rs
Normal file
@@ -0,0 +1,152 @@
|
||||
//! Records low-cardinality migration metrics shared by manual and startup runs.
|
||||
//!
|
||||
//! Migration owns the outcome stream, so it is the one place that can count successful,
|
||||
//! skipped, and failed rollouts consistently. Callers only tell it why the run started.
|
||||
|
||||
use std::time::Instant;
|
||||
|
||||
use super::RolloutMigrationFailureReason;
|
||||
use super::RolloutMigrationMode;
|
||||
use super::RolloutMigrationOptions;
|
||||
use super::RolloutMigrationReport;
|
||||
use super::RolloutMigrationStatus;
|
||||
use crate::ThreadStoreResult;
|
||||
|
||||
const RUN_METRIC: &str = "codex.rollout_migration.run";
|
||||
const RUN_DURATION_METRIC: &str = "codex.rollout_migration.run.duration_ms";
|
||||
const RUN_IO_BYTES_METRIC: &str = "codex.rollout_migration.run.io_bytes";
|
||||
const THREAD_METRIC: &str = "codex.rollout_migration.thread";
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub(super) enum RolloutMigrationTrigger {
|
||||
Manual,
|
||||
Startup,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum RolloutMigrationScope {
|
||||
All,
|
||||
Selected,
|
||||
}
|
||||
|
||||
pub(super) struct RolloutMigrationTelemetry {
|
||||
trigger: RolloutMigrationTrigger,
|
||||
mode: RolloutMigrationMode,
|
||||
scope: RolloutMigrationScope,
|
||||
started_at: Instant,
|
||||
}
|
||||
|
||||
impl RolloutMigrationTelemetry {
|
||||
pub(super) fn new(trigger: RolloutMigrationTrigger, options: &RolloutMigrationOptions) -> Self {
|
||||
Self {
|
||||
trigger,
|
||||
mode: options.mode,
|
||||
scope: if options.thread_ids.is_empty() {
|
||||
RolloutMigrationScope::All
|
||||
} else {
|
||||
RolloutMigrationScope::Selected
|
||||
},
|
||||
started_at: Instant::now(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn finish(&self, result: &ThreadStoreResult<RolloutMigrationReport>) {
|
||||
let Some(metrics) = codex_otel::global() else {
|
||||
return;
|
||||
};
|
||||
let mut io_bytes = 0_u64;
|
||||
if let Ok(report) = result {
|
||||
for outcome in &report.outcomes {
|
||||
let mut tags = vec![
|
||||
("trigger", self.trigger.tag()),
|
||||
("mode", self.mode.tag()),
|
||||
("scope", self.scope.tag()),
|
||||
("status", outcome.status.tag()),
|
||||
];
|
||||
if let Some(failure_reason) = outcome.failure_reason {
|
||||
tags.push(("failure_reason", failure_reason.tag()));
|
||||
}
|
||||
let _ = metrics.counter(THREAD_METRIC, /*inc*/ 1, &tags);
|
||||
io_bytes = io_bytes.saturating_add(outcome.bytes_processed);
|
||||
}
|
||||
}
|
||||
let result = match result {
|
||||
Err(_) => "error",
|
||||
Ok(report)
|
||||
if report
|
||||
.outcomes
|
||||
.iter()
|
||||
.any(|outcome| outcome.status == RolloutMigrationStatus::Failed) =>
|
||||
{
|
||||
"partial_failure"
|
||||
}
|
||||
Ok(_) => "success",
|
||||
};
|
||||
let tags = [
|
||||
("trigger", self.trigger.tag()),
|
||||
("mode", self.mode.tag()),
|
||||
("scope", self.scope.tag()),
|
||||
("result", result),
|
||||
];
|
||||
let duration_ms = i64::try_from(self.started_at.elapsed().as_millis()).unwrap_or(i64::MAX);
|
||||
let io_bytes = i64::try_from(io_bytes).unwrap_or(i64::MAX);
|
||||
let _ = metrics.counter(RUN_METRIC, /*inc*/ 1, &tags);
|
||||
let _ = metrics.histogram(RUN_DURATION_METRIC, duration_ms, &tags);
|
||||
let _ = metrics.histogram(RUN_IO_BYTES_METRIC, io_bytes, &tags);
|
||||
}
|
||||
}
|
||||
|
||||
impl RolloutMigrationTrigger {
|
||||
fn tag(self) -> &'static str {
|
||||
match self {
|
||||
Self::Manual => "manual",
|
||||
Self::Startup => "startup",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl RolloutMigrationMode {
|
||||
fn tag(self) -> &'static str {
|
||||
match self {
|
||||
Self::DryRun => "dry_run",
|
||||
Self::Apply => "apply",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl RolloutMigrationScope {
|
||||
fn tag(self) -> &'static str {
|
||||
match self {
|
||||
Self::All => "all",
|
||||
Self::Selected => "selected",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl RolloutMigrationStatus {
|
||||
fn tag(self) -> &'static str {
|
||||
match self {
|
||||
Self::Eligible => "eligible",
|
||||
Self::Migrated => "migrated",
|
||||
Self::AlreadyPaginated => "already_paginated",
|
||||
Self::SkippedEmpty => "skipped_empty",
|
||||
Self::SkippedBusy => "skipped_busy",
|
||||
Self::Failed => "failed",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl RolloutMigrationFailureReason {
|
||||
fn tag(self) -> &'static str {
|
||||
match self {
|
||||
Self::MissingSqliteMetadata => "missing_sqlite_metadata",
|
||||
Self::InvalidSessionMetadata => "invalid_session_metadata",
|
||||
Self::RolloutReadFailed => "rollout_read_failed",
|
||||
Self::LegacyRolloutConversionFailed => "legacy_rollout_conversion_failed",
|
||||
Self::SqliteMaterializationFailed => "sqlite_materialization_failed",
|
||||
Self::RolloutPublishFailed => "rollout_publish_failed",
|
||||
Self::InterruptedMigrationRecoveryFailed => "interrupted_migration_recovery_failed",
|
||||
Self::Unknown => "unknown",
|
||||
}
|
||||
}
|
||||
}
|
||||
3370
codex-rs/thread-store/src/local/rollout_migration_tests.rs
Normal file
3370
codex-rs/thread-store/src/local/rollout_migration_tests.rs
Normal file
File diff suppressed because it is too large
Load Diff
286
codex-rs/thread-store/src/local/search_threads.rs
Normal file
286
codex-rs/thread-store/src/local/search_threads.rs
Normal file
@@ -0,0 +1,286 @@
|
||||
use std::collections::HashMap;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use codex_install_context::InstallContext;
|
||||
use codex_rollout::RolloutConfig;
|
||||
use codex_rollout::first_rollout_content_match_snippet;
|
||||
use codex_rollout::parse_cursor;
|
||||
use codex_rollout::search_rollout_matches;
|
||||
use codex_utils_absolute_path::normalize_windows_device_path;
|
||||
|
||||
use super::LocalThreadStore;
|
||||
use super::helpers::resolve_thread_names;
|
||||
use super::helpers::resolve_thread_section_metadata;
|
||||
use super::helpers::set_thread_name;
|
||||
use super::helpers::stored_thread_from_rollout_item;
|
||||
use super::list_threads::list_rollout_threads;
|
||||
use crate::ListThreadsParams;
|
||||
use crate::SearchThreadsParams;
|
||||
use crate::SortDirection;
|
||||
use crate::StoredThreadSearchResult;
|
||||
use crate::ThreadSearchPage;
|
||||
use crate::ThreadSortKey;
|
||||
use crate::ThreadStoreError;
|
||||
use crate::ThreadStoreResult;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "search_threads_tests.rs"]
|
||||
mod tests;
|
||||
|
||||
struct ThreadSearchItem {
|
||||
item: codex_rollout::ThreadItem,
|
||||
snippet: String,
|
||||
}
|
||||
|
||||
pub(super) async fn search_threads(
|
||||
store: &LocalThreadStore,
|
||||
params: SearchThreadsParams,
|
||||
) -> ThreadStoreResult<ThreadSearchPage> {
|
||||
let search_term = params.search_term.as_str();
|
||||
if search_term.is_empty() {
|
||||
return Err(ThreadStoreError::InvalidRequest {
|
||||
message: "thread/search requires search_term".to_string(),
|
||||
});
|
||||
}
|
||||
let cursor = params
|
||||
.cursor
|
||||
.as_deref()
|
||||
.map(|cursor| {
|
||||
parse_cursor(cursor).ok_or_else(|| ThreadStoreError::InvalidRequest {
|
||||
message: format!("invalid cursor: {cursor}"),
|
||||
})
|
||||
})
|
||||
.transpose()?;
|
||||
let sort_key = match params.sort_key {
|
||||
ThreadSortKey::CreatedAt => codex_rollout::ThreadSortKey::CreatedAt,
|
||||
ThreadSortKey::UpdatedAt => codex_rollout::ThreadSortKey::UpdatedAt,
|
||||
ThreadSortKey::RecencyAt => codex_rollout::ThreadSortKey::RecencyAt,
|
||||
ThreadSortKey::SectionPosition => {
|
||||
return Err(ThreadStoreError::InvalidRequest {
|
||||
message: "section-position sorting requires a section filter".to_owned(),
|
||||
});
|
||||
}
|
||||
};
|
||||
let sort_direction = match params.sort_direction {
|
||||
SortDirection::Asc => codex_rollout::SortDirection::Asc,
|
||||
SortDirection::Desc => codex_rollout::SortDirection::Desc,
|
||||
};
|
||||
let state_db = store.state_db().await;
|
||||
let rollout_config = RolloutConfig {
|
||||
codex_home: store.config.codex_home.clone(),
|
||||
sqlite: store.config.sqlite.clone(),
|
||||
cwd: store.config.codex_home.clone(),
|
||||
model_provider_id: store.config.default_model_provider_id.clone(),
|
||||
generate_memories: false,
|
||||
};
|
||||
let rg_command = InstallContext::current().rg_command();
|
||||
let matching_rollouts = search_rollout_matches(
|
||||
rg_command.as_path(),
|
||||
store.config.codex_home.as_path(),
|
||||
params.archived,
|
||||
search_term,
|
||||
)
|
||||
.await
|
||||
.map_err(|err| ThreadStoreError::Internal {
|
||||
message: format!("failed to search rollout contents: {err}"),
|
||||
})?;
|
||||
if matching_rollouts.is_empty() {
|
||||
return Ok(ThreadSearchPage {
|
||||
items: Vec::new(),
|
||||
next_cursor: None,
|
||||
});
|
||||
}
|
||||
let mut matching_items = Vec::new();
|
||||
let mut page_cursor = cursor;
|
||||
let scan_page_size = params.page_size.saturating_mul(8).clamp(256, 2048);
|
||||
let scan_params = ListThreadsParams {
|
||||
page_size: scan_page_size,
|
||||
cursor: None,
|
||||
sort_key: params.sort_key,
|
||||
sort_direction: params.sort_direction,
|
||||
allowed_sources: params.allowed_sources.clone(),
|
||||
model_providers: None,
|
||||
cwd_filters: None,
|
||||
section: None,
|
||||
project_id: None,
|
||||
archived: params.archived,
|
||||
search_term: None,
|
||||
relation_filter: None,
|
||||
use_state_db_only: state_db.is_some(),
|
||||
};
|
||||
let mut remaining_rollouts = matching_rollouts
|
||||
.into_iter()
|
||||
.map(|(path, snippet)| (rollout_search_path(&path), snippet))
|
||||
.collect::<HashMap<_, _>>();
|
||||
|
||||
loop {
|
||||
let page = list_rollout_threads(
|
||||
state_db.clone(),
|
||||
&rollout_config,
|
||||
store.config.default_model_provider_id.as_str(),
|
||||
&scan_params,
|
||||
page_cursor.as_ref(),
|
||||
sort_key,
|
||||
sort_direction,
|
||||
)
|
||||
.await?;
|
||||
let page_thread_ids: Vec<_> = page
|
||||
.items
|
||||
.iter()
|
||||
.filter_map(|item| item.thread_id)
|
||||
.collect();
|
||||
let mut original_paths = None;
|
||||
for item in page.items {
|
||||
let logical_path = rollout_search_path(item.path.as_path());
|
||||
let Some(mut snippet) = remaining_rollouts.remove(logical_path.as_path()) else {
|
||||
continue;
|
||||
};
|
||||
if let Some(account) = ¶ms.account {
|
||||
let Some(thread_id) = item.thread_id else {
|
||||
continue;
|
||||
};
|
||||
if !account
|
||||
.includes(
|
||||
&store.config.codex_home,
|
||||
thread_id,
|
||||
Some(&item.path),
|
||||
&page_thread_ids,
|
||||
&mut original_paths,
|
||||
)
|
||||
.await
|
||||
{
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if snippet.is_none() {
|
||||
snippet = first_rollout_content_match_snippet(item.path.as_path(), search_term)
|
||||
.await
|
||||
.map_err(|err| ThreadStoreError::Internal {
|
||||
message: format!("failed to read rollout search match: {err}"),
|
||||
})?;
|
||||
}
|
||||
let Some(snippet) = snippet else { continue };
|
||||
matching_items.push(ThreadSearchItem { item, snippet });
|
||||
if matching_items.len() > params.page_size {
|
||||
break;
|
||||
}
|
||||
}
|
||||
page_cursor = page.next_cursor;
|
||||
if matching_items.len() > params.page_size
|
||||
|| remaining_rollouts.is_empty()
|
||||
|| page_cursor.is_none()
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
let more_matches_available = matching_items.len() > params.page_size;
|
||||
matching_items.truncate(params.page_size);
|
||||
let next_cursor = if more_matches_available {
|
||||
matching_items.last().and_then(|item| {
|
||||
if scan_params.use_state_db_only {
|
||||
cursor_from_thread_search_item(item, params.sort_key)
|
||||
} else {
|
||||
item.item.filesystem_cursor(sort_key)
|
||||
}
|
||||
})
|
||||
} else {
|
||||
None
|
||||
}
|
||||
.as_ref()
|
||||
.and_then(|cursor| serde_json::to_value(cursor).ok())
|
||||
.and_then(|value| value.as_str().map(str::to_owned));
|
||||
|
||||
let mut items = matching_items
|
||||
.into_iter()
|
||||
.filter_map(|item| {
|
||||
stored_thread_from_rollout_item(
|
||||
item.item,
|
||||
params.archived,
|
||||
store.config.default_model_provider_id.as_str(),
|
||||
)
|
||||
.map(|thread| StoredThreadSearchResult {
|
||||
thread,
|
||||
snippet: item.snippet,
|
||||
})
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
if let Some(state_db) = state_db {
|
||||
let sectioned_thread_ids = items
|
||||
.iter()
|
||||
.filter(|item| item.thread.section.is_some())
|
||||
.map(|item| item.thread.thread_id)
|
||||
.collect::<Vec<_>>();
|
||||
let mut section_metadata =
|
||||
resolve_thread_section_metadata(state_db.as_ref(), §ioned_thread_ids).await;
|
||||
for item in &mut items {
|
||||
if let Some((section_position, section_entered_at)) =
|
||||
section_metadata.remove(&item.thread.thread_id)
|
||||
{
|
||||
item.thread.section_position = section_position;
|
||||
item.thread.section_entered_at = section_entered_at;
|
||||
}
|
||||
}
|
||||
}
|
||||
set_thread_search_result_names(store, &mut items).await;
|
||||
|
||||
Ok(ThreadSearchPage { items, next_cursor })
|
||||
}
|
||||
|
||||
fn rollout_search_path(path: &Path) -> PathBuf {
|
||||
let path = codex_rollout::plain_rollout_path(path);
|
||||
// Resume can persist a Windows namespace prefix while filesystem search returns the
|
||||
// ordinary spelling. Normalize both join keys without requiring the uncompressed file
|
||||
// to exist, and retain the filename identifying the selected rollout after a revert.
|
||||
if cfg!(windows)
|
||||
&& let Some(normalized) = path.to_str().and_then(normalize_windows_device_path)
|
||||
{
|
||||
return PathBuf::from(normalized);
|
||||
}
|
||||
path
|
||||
}
|
||||
|
||||
fn cursor_from_thread_search_item(
|
||||
item: &ThreadSearchItem,
|
||||
sort_key: ThreadSortKey,
|
||||
) -> Option<codex_rollout::Cursor> {
|
||||
let timestamp = match sort_key {
|
||||
ThreadSortKey::CreatedAt => item.item.created_at.as_deref()?,
|
||||
ThreadSortKey::UpdatedAt => item
|
||||
.item
|
||||
.updated_at
|
||||
.as_deref()
|
||||
.or(item.item.created_at.as_deref())?,
|
||||
ThreadSortKey::RecencyAt => item
|
||||
.item
|
||||
.recency_at
|
||||
.as_deref()
|
||||
.or(item.item.updated_at.as_deref())
|
||||
.or(item.item.created_at.as_deref())?,
|
||||
ThreadSortKey::SectionPosition => return None,
|
||||
};
|
||||
parse_cursor(&format!("{timestamp}|{}", item.item.thread_id?))
|
||||
}
|
||||
|
||||
async fn set_thread_search_result_names(
|
||||
store: &LocalThreadStore,
|
||||
items: &mut [StoredThreadSearchResult],
|
||||
) {
|
||||
let thread_history_modes = items
|
||||
.iter()
|
||||
.map(|item| (item.thread.thread_id, item.thread.history_mode))
|
||||
.collect::<HashMap<_, _>>();
|
||||
let names = resolve_thread_names(
|
||||
store,
|
||||
&thread_history_modes,
|
||||
/*use_state_db_only*/ false,
|
||||
)
|
||||
.await
|
||||
.unwrap_or_default();
|
||||
for item in items {
|
||||
if let Some(name) = names.get(&item.thread.thread_id).cloned() {
|
||||
set_thread_name(&mut item.thread, name);
|
||||
}
|
||||
}
|
||||
}
|
||||
170
codex-rs/thread-store/src/local/search_threads_tests.rs
Normal file
170
codex-rs/thread-store/src/local/search_threads_tests.rs
Normal file
@@ -0,0 +1,170 @@
|
||||
use chrono::Utc;
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::protocol::SessionSource;
|
||||
use codex_protocol::protocol::ThreadHistoryMode;
|
||||
use codex_rollout::ThreadItem;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tempfile::TempDir;
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::super::LocalThreadStore;
|
||||
use super::super::test_support::test_config;
|
||||
use super::super::test_support::write_session_file_with;
|
||||
use super::ThreadSearchItem;
|
||||
use super::cursor_from_thread_search_item;
|
||||
use crate::SearchThreadsParams;
|
||||
use crate::SortDirection;
|
||||
use crate::ThreadSortKey;
|
||||
use crate::ThreadStore;
|
||||
|
||||
#[test]
|
||||
fn time_sort_cursors_include_thread_id_tie_breaker() {
|
||||
let thread_id = ThreadId::from_string("00000000-0000-0000-0000-000000000123")
|
||||
.expect("thread ID should parse");
|
||||
let item = ThreadSearchItem {
|
||||
item: ThreadItem {
|
||||
thread_id: Some(thread_id),
|
||||
created_at: Some("2026-01-27T12:34:56Z".to_string()),
|
||||
updated_at: Some("2026-01-27T12:34:56Z".to_string()),
|
||||
recency_at: Some("2026-01-27T12:34:56Z".to_string()),
|
||||
..Default::default()
|
||||
},
|
||||
snippet: String::new(),
|
||||
};
|
||||
|
||||
for sort_key in [
|
||||
ThreadSortKey::CreatedAt,
|
||||
ThreadSortKey::UpdatedAt,
|
||||
ThreadSortKey::RecencyAt,
|
||||
] {
|
||||
let cursor = cursor_from_thread_search_item(&item, sort_key).expect("cursor should build");
|
||||
assert_eq!(
|
||||
serde_json::to_string(&cursor).expect("cursor should serialize"),
|
||||
format!("\"2026-01-27T12:34:56Z|{thread_id}\"")
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn search_matches_selected_rollout_across_path_spellings_and_compression() {
|
||||
for compressed in [false, true] {
|
||||
let home = TempDir::new().expect("temp dir");
|
||||
let config = test_config(home.path());
|
||||
let state_db = codex_state::StateRuntime::init(
|
||||
config.sqlite.clone(),
|
||||
config.default_model_provider_id.clone(),
|
||||
)
|
||||
.await
|
||||
.expect("initialize state database");
|
||||
let uuid = Uuid::new_v4();
|
||||
let thread_id = ThreadId::from_string(&uuid.to_string()).expect("thread ID should parse");
|
||||
let selected_path = write_session_file_with(
|
||||
home.path(),
|
||||
home.path().join("sessions/2025/01/03"),
|
||||
"2025-01-03T12-00-00",
|
||||
uuid,
|
||||
"needle in selected rollout",
|
||||
Some("test-provider"),
|
||||
ThreadHistoryMode::Legacy,
|
||||
)
|
||||
.expect("write selected rollout");
|
||||
// Reverting a thread leaves its previous rollout on disk with the same thread ID.
|
||||
write_session_file_with(
|
||||
home.path(),
|
||||
home.path().join("sessions/2025/01/03"),
|
||||
"2025-01-03T11-00-00",
|
||||
uuid,
|
||||
"obsolete needle in previous rollout",
|
||||
Some("test-provider"),
|
||||
ThreadHistoryMode::Legacy,
|
||||
)
|
||||
.expect("write unselected rollout");
|
||||
|
||||
let home_paths = [home.path().to_path_buf()];
|
||||
#[cfg(windows)]
|
||||
let home_paths = {
|
||||
let verbatim = std::fs::canonicalize(&home_paths[0]).expect("canonicalize home");
|
||||
let ordinary =
|
||||
codex_utils_absolute_path::AbsolutePathBuf::from_absolute_path(&verbatim)
|
||||
.expect("normalize home")
|
||||
.into_path_buf();
|
||||
[ordinary, verbatim]
|
||||
};
|
||||
let relative_path = selected_path
|
||||
.strip_prefix(home.path())
|
||||
.expect("relative rollout path");
|
||||
let selected_paths = home_paths.each_ref().map(|home| home.join(relative_path));
|
||||
#[cfg(windows)]
|
||||
assert_ne!(selected_paths[0], selected_paths[1]);
|
||||
|
||||
if compressed {
|
||||
let contents = std::fs::read(&selected_path).expect("read selected rollout");
|
||||
let contents = zstd::stream::encode_all(contents.as_slice(), /*level*/ 3)
|
||||
.expect("compress selected rollout");
|
||||
std::fs::write(selected_path.with_extension("jsonl.zst"), contents)
|
||||
.expect("write compressed rollout");
|
||||
std::fs::remove_file(&selected_path).expect("remove plain rollout");
|
||||
}
|
||||
let selected_paths = selected_paths
|
||||
.into_iter()
|
||||
.flat_map(|path| {
|
||||
let compressed_path = compressed.then(|| path.with_extension("jsonl.zst"));
|
||||
std::iter::once(path).chain(compressed_path)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
for codex_home in home_paths {
|
||||
let store = LocalThreadStore::new(
|
||||
super::super::LocalThreadStoreConfig {
|
||||
codex_home,
|
||||
..config.clone()
|
||||
},
|
||||
Some(state_db.clone()),
|
||||
);
|
||||
for selected_path in &selected_paths {
|
||||
let mut metadata = codex_state::ThreadMetadataBuilder::new(
|
||||
thread_id,
|
||||
selected_path.clone(),
|
||||
Utc::now(),
|
||||
SessionSource::Cli,
|
||||
)
|
||||
.build("test-provider");
|
||||
metadata.first_user_message = Some("needle in selected rollout".to_string());
|
||||
state_db
|
||||
.upsert_thread(&metadata)
|
||||
.await
|
||||
.expect("select rollout in database");
|
||||
|
||||
for (search_term, expected) in [
|
||||
("needle", vec![(thread_id, "needle in selected rollout")]),
|
||||
("obsolete", Vec::new()),
|
||||
] {
|
||||
let page = store
|
||||
.search_threads(SearchThreadsParams {
|
||||
account: None,
|
||||
page_size: 10,
|
||||
cursor: None,
|
||||
sort_key: ThreadSortKey::CreatedAt,
|
||||
sort_direction: SortDirection::Desc,
|
||||
allowed_sources: vec![SessionSource::Cli],
|
||||
archived: false,
|
||||
search_term: search_term.to_string(),
|
||||
})
|
||||
.await
|
||||
.expect("search selected rollout");
|
||||
assert_eq!(
|
||||
(
|
||||
page.items
|
||||
.iter()
|
||||
.map(|item| (item.thread.thread_id, item.snippet.as_str()))
|
||||
.collect::<Vec<_>>(),
|
||||
page.next_cursor,
|
||||
),
|
||||
(expected, None),
|
||||
"compressed={compressed}, selected_path={selected_path:?}",
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
131
codex-rs/thread-store/src/local/test_support.rs
Normal file
131
codex-rs/thread-store/src/local/test_support.rs
Normal file
@@ -0,0 +1,131 @@
|
||||
use std::fs;
|
||||
use std::io::Write;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use codex_protocol::protocol::ThreadHistoryMode;
|
||||
use codex_rollout::ARCHIVED_SESSIONS_SUBDIR;
|
||||
use codex_utils_absolute_path::test_support::PathExt;
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::LocalThreadStoreConfig;
|
||||
|
||||
pub(super) fn test_config(codex_home: &Path) -> LocalThreadStoreConfig {
|
||||
LocalThreadStoreConfig {
|
||||
codex_home: codex_home.to_path_buf(),
|
||||
sqlite: codex_state::SqliteConfig::new_for_testing(codex_home.abs()),
|
||||
default_model_provider_id: "test-provider".to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn write_session_file(root: &Path, ts: &str, uuid: Uuid) -> std::io::Result<PathBuf> {
|
||||
write_session_file_with_history_mode(root, ts, uuid, ThreadHistoryMode::Legacy)
|
||||
}
|
||||
|
||||
pub(super) fn write_session_file_with_history_mode(
|
||||
root: &Path,
|
||||
ts: &str,
|
||||
uuid: Uuid,
|
||||
history_mode: ThreadHistoryMode,
|
||||
) -> std::io::Result<PathBuf> {
|
||||
write_session_file_with(
|
||||
root,
|
||||
root.join("sessions/2025/01/03"),
|
||||
ts,
|
||||
uuid,
|
||||
"Hello from user",
|
||||
Some("test-provider"),
|
||||
history_mode,
|
||||
)
|
||||
}
|
||||
|
||||
pub(super) fn write_archived_session_file(
|
||||
root: &Path,
|
||||
ts: &str,
|
||||
uuid: Uuid,
|
||||
) -> std::io::Result<PathBuf> {
|
||||
write_session_file_with(
|
||||
root,
|
||||
root.join(ARCHIVED_SESSIONS_SUBDIR),
|
||||
ts,
|
||||
uuid,
|
||||
"Archived user message",
|
||||
Some("test-provider"),
|
||||
ThreadHistoryMode::Legacy,
|
||||
)
|
||||
}
|
||||
|
||||
pub(super) fn write_session_file_with(
|
||||
root: &Path,
|
||||
day_dir: PathBuf,
|
||||
ts: &str,
|
||||
uuid: Uuid,
|
||||
first_user_message: &str,
|
||||
model_provider: Option<&str>,
|
||||
history_mode: ThreadHistoryMode,
|
||||
) -> std::io::Result<PathBuf> {
|
||||
write_session_file_with_fork(
|
||||
root,
|
||||
day_dir,
|
||||
ts,
|
||||
uuid,
|
||||
first_user_message,
|
||||
model_provider,
|
||||
/*forked_from_id*/ None,
|
||||
history_mode,
|
||||
)
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(super) fn write_session_file_with_fork(
|
||||
root: &Path,
|
||||
day_dir: PathBuf,
|
||||
ts: &str,
|
||||
uuid: Uuid,
|
||||
first_user_message: &str,
|
||||
model_provider: Option<&str>,
|
||||
forked_from_id: Option<Uuid>,
|
||||
history_mode: ThreadHistoryMode,
|
||||
) -> std::io::Result<PathBuf> {
|
||||
fs::create_dir_all(&day_dir)?;
|
||||
let path = day_dir.join(format!("rollout-{ts}-{uuid}.jsonl"));
|
||||
let mut file = fs::File::create(&path)?;
|
||||
let mut meta = serde_json::json!({
|
||||
"timestamp": ts,
|
||||
"type": "session_meta",
|
||||
"payload": {
|
||||
"session_id": uuid,
|
||||
"id": uuid,
|
||||
"forked_from_id": forked_from_id,
|
||||
"timestamp": ts,
|
||||
"cwd": root,
|
||||
"originator": "test_originator",
|
||||
"cli_version": "test_version",
|
||||
"source": "cli",
|
||||
"model_provider": model_provider,
|
||||
"history_mode": history_mode,
|
||||
"git": {
|
||||
"commit_hash": "abcdef",
|
||||
"branch": "main",
|
||||
"repository_url": "https://example.com/repo.git"
|
||||
}
|
||||
},
|
||||
});
|
||||
if matches!(history_mode, ThreadHistoryMode::Paginated) {
|
||||
meta["ordinal"] = serde_json::json!(0);
|
||||
}
|
||||
writeln!(file, "{meta}")?;
|
||||
if matches!(history_mode, ThreadHistoryMode::Legacy) {
|
||||
let user_event = serde_json::json!({
|
||||
"timestamp": ts,
|
||||
"type": "event_msg",
|
||||
"payload": {
|
||||
"type": "user_message",
|
||||
"message": first_user_message,
|
||||
"kind": "plain",
|
||||
},
|
||||
});
|
||||
writeln!(file, "{user_event}")?;
|
||||
}
|
||||
Ok(path)
|
||||
}
|
||||
51
codex-rs/thread-store/src/local/tests/acquisition_tests.rs
Normal file
51
codex-rs/thread-store/src/local/tests/acquisition_tests.rs
Normal file
@@ -0,0 +1,51 @@
|
||||
//! Persistence acquisition stays owned when its caller is cancelled after writer installation.
|
||||
|
||||
use super::*;
|
||||
use crate::LiveThreadInitGuard;
|
||||
use futures::poll;
|
||||
use tokio::sync::oneshot;
|
||||
|
||||
#[tokio::test]
|
||||
async fn cancelled_acquisition_waits_for_writer_handoff_before_discarding() {
|
||||
let home = TempDir::new().expect("temp dir");
|
||||
let store = Arc::new(LocalThreadStore::new(
|
||||
test_config(home.path()),
|
||||
/*state_db*/ None,
|
||||
));
|
||||
let thread_id = ThreadId::default();
|
||||
let params = create_thread_params(thread_id);
|
||||
let (installed, installation) = oneshot::channel();
|
||||
let (release, released) = oneshot::channel();
|
||||
let creating_store = Arc::clone(&store);
|
||||
// Model the cloud wrapper: creation runs independently, installs its writer, then awaits
|
||||
// initial metadata before returning. Dropping the JoinHandle would detach that work.
|
||||
let creating = tokio::spawn(async move {
|
||||
let live_thread = LiveThread::create(creating_store, params).await?;
|
||||
installed.send(()).expect("installation observed");
|
||||
released.await.expect("release acquisition");
|
||||
Ok(live_thread)
|
||||
});
|
||||
let mut guard = LiveThreadInitGuard::default();
|
||||
let mut start = Box::pin(guard.acquire(async move { creating.await.expect("creation task") }));
|
||||
assert!(poll!(&mut start).is_pending());
|
||||
installation
|
||||
.await
|
||||
.expect("writer installed before cancellation");
|
||||
drop(start);
|
||||
store
|
||||
.flush_thread(thread_id)
|
||||
.await
|
||||
.expect("writer installed");
|
||||
|
||||
let mut cleanup = Box::pin(guard.discard());
|
||||
assert!(
|
||||
poll!(&mut cleanup).is_pending(),
|
||||
"cleanup must retain the unfinished acquisition"
|
||||
);
|
||||
release.send(()).expect("creation still owned");
|
||||
cleanup.await.expect("discard acquired writer");
|
||||
assert!(matches!(
|
||||
store.flush_thread(thread_id).await,
|
||||
Err(ThreadStoreError::ThreadNotFound { .. })
|
||||
));
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
//! Delegated tasks are discoverable through database listing before any user message.
|
||||
|
||||
use super::*;
|
||||
use crate::SortDirection;
|
||||
use crate::ThreadSortKey;
|
||||
use codex_protocol::items::FunctionCallOutputItem;
|
||||
use codex_protocol::models::FunctionCallOutputBody;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[tokio::test]
|
||||
async fn delegated_thread_is_listed_before_user_followup() {
|
||||
for history_mode in [ThreadHistoryMode::Legacy, ThreadHistoryMode::Paginated] {
|
||||
let home = TempDir::new().expect("temp dir");
|
||||
let config = test_config(home.path());
|
||||
let runtime = codex_state::StateRuntime::init(
|
||||
config.sqlite.clone(),
|
||||
config.default_model_provider_id.clone(),
|
||||
)
|
||||
.await
|
||||
.expect("initialize state database");
|
||||
let store = Arc::new(LocalThreadStore::new(config, Some(runtime)));
|
||||
let thread_id = ThreadId::new();
|
||||
let mut params = create_thread_params(thread_id);
|
||||
params.history_mode = history_mode;
|
||||
let live_thread = LiveThread::create(store.clone(), params)
|
||||
.await
|
||||
.expect("create live thread");
|
||||
let preview = "Inspect <main> & report findings.";
|
||||
live_thread
|
||||
.append_items(&[RolloutItem::EventMsg(EventMsg::ItemCompleted(
|
||||
ItemCompletedEvent {
|
||||
content_token_count: None,
|
||||
thread_id,
|
||||
turn_id: "delegated-turn".to_string(),
|
||||
item: TurnItem::FunctionCallOutput(FunctionCallOutputItem {
|
||||
id: "delegated-output".to_string(),
|
||||
name: "create_thread".to_string(),
|
||||
namespace: Some("codex_app".to_string()),
|
||||
output: FunctionCallOutputBody::Text(
|
||||
"<codex_delegation>\n <source_thread_id>source</source_thread_id>\n <input>Inspect <main> & report findings.</input>\n</codex_delegation>".to_string(),
|
||||
),
|
||||
}),
|
||||
started_at_ms: Some(0),
|
||||
completed_at_ms: 0,
|
||||
},
|
||||
))])
|
||||
.await
|
||||
.expect("append delegated input");
|
||||
live_thread.flush().await.expect("persist delegated input");
|
||||
|
||||
let listed = store
|
||||
.list_threads(ListThreadsParams {
|
||||
page_size: 10,
|
||||
cursor: None,
|
||||
sort_key: ThreadSortKey::CreatedAt,
|
||||
sort_direction: SortDirection::Desc,
|
||||
allowed_sources: Vec::new(),
|
||||
model_providers: None,
|
||||
cwd_filters: None,
|
||||
section: None,
|
||||
project_id: None,
|
||||
archived: false,
|
||||
search_term: None,
|
||||
relation_filter: None,
|
||||
use_state_db_only: true,
|
||||
})
|
||||
.await
|
||||
.expect("list database threads");
|
||||
assert_eq!(
|
||||
listed
|
||||
.items
|
||||
.iter()
|
||||
.map(|thread| (
|
||||
thread.thread_id,
|
||||
thread.preview.as_str(),
|
||||
thread.first_user_message.as_deref(),
|
||||
))
|
||||
.collect::<Vec<_>>(),
|
||||
vec![(thread_id, preview, None)],
|
||||
"history mode: {history_mode:?}",
|
||||
);
|
||||
live_thread.shutdown().await.expect("shutdown live thread");
|
||||
}
|
||||
}
|
||||
135
codex-rs/thread-store/src/local/thread_attachments.rs
Normal file
135
codex-rs/thread-store/src/local/thread_attachments.rs
Normal file
@@ -0,0 +1,135 @@
|
||||
//! Local attachment adapter sharing lifecycle exclusion with thread deletion.
|
||||
|
||||
use super::LocalThreadStore;
|
||||
use crate::AddThreadAttachmentOutcome;
|
||||
use crate::AddThreadAttachmentParams;
|
||||
use crate::ListThreadAttachmentThreadsParams;
|
||||
use crate::ListThreadAttachmentsParams;
|
||||
use crate::RemoveThreadAttachmentOutcome;
|
||||
use crate::RemoveThreadAttachmentParams;
|
||||
use crate::ThreadAttachmentOwnerPage;
|
||||
use crate::ThreadAttachmentPage;
|
||||
use crate::ThreadStoreError;
|
||||
use crate::ThreadStoreResult;
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_rollout::StateDbHandle;
|
||||
|
||||
pub(super) async fn copy_thread_attachments(
|
||||
store: &LocalThreadStore,
|
||||
source_thread_id: ThreadId,
|
||||
destination_thread_id: ThreadId,
|
||||
) -> ThreadStoreResult<()> {
|
||||
let state_db = state_db(store, "copy_thread_attachments")?;
|
||||
let _lifecycle_reservation = store
|
||||
.live_writer_locks
|
||||
.reserve_lifecycle(destination_thread_id)
|
||||
.await;
|
||||
// Reference-backed forks already reserve their source. Do not recursively acquire that
|
||||
// reservation: a queued deletion could deadlock it. SQLite serializes the source snapshot.
|
||||
state_db
|
||||
.copy_thread_attachments(source_thread_id, destination_thread_id)
|
||||
.await
|
||||
.map_err(|error| attachment_error("copy", Some(destination_thread_id), error))
|
||||
}
|
||||
|
||||
pub(super) async fn add_thread_attachment(
|
||||
store: &LocalThreadStore,
|
||||
params: AddThreadAttachmentParams,
|
||||
) -> ThreadStoreResult<AddThreadAttachmentOutcome> {
|
||||
let state_db = state_db(store, "thread/attachment/add")?;
|
||||
let _lifecycle_reservation = store
|
||||
.live_writer_locks
|
||||
.reserve_lifecycle(params.thread_id)
|
||||
.await;
|
||||
state_db
|
||||
.add_thread_attachment(
|
||||
params.thread_id,
|
||||
¶ms.attachment_type,
|
||||
¶ms.identity_key,
|
||||
¶ms.payload,
|
||||
)
|
||||
.await
|
||||
.map_err(|error| attachment_error("add", Some(params.thread_id), error))
|
||||
}
|
||||
|
||||
pub(super) async fn list_thread_attachments(
|
||||
store: &LocalThreadStore,
|
||||
params: ListThreadAttachmentsParams,
|
||||
) -> ThreadStoreResult<ThreadAttachmentPage> {
|
||||
let state_db = state_db(store, "thread/attachment/list")?;
|
||||
state_db
|
||||
.list_thread_attachments(params.thread_id, params.cursor.as_deref(), params.limit)
|
||||
.await
|
||||
.map_err(|error| attachment_error("list", /*thread_id*/ None, error))
|
||||
}
|
||||
|
||||
pub(super) async fn list_thread_attachment_threads(
|
||||
store: &LocalThreadStore,
|
||||
params: ListThreadAttachmentThreadsParams,
|
||||
) -> ThreadStoreResult<ThreadAttachmentOwnerPage> {
|
||||
let state_db = state_db(store, "thread/attachmentOwner/list")?;
|
||||
state_db
|
||||
.list_thread_attachment_threads(
|
||||
¶ms.attachment_type,
|
||||
¶ms.identity_key,
|
||||
params.archive_filter,
|
||||
params.cursor.as_deref(),
|
||||
params.limit,
|
||||
)
|
||||
.await
|
||||
.map_err(|error| attachment_error("list owners of", /*thread_id*/ None, error))
|
||||
}
|
||||
|
||||
pub(super) async fn remove_thread_attachment(
|
||||
store: &LocalThreadStore,
|
||||
params: RemoveThreadAttachmentParams,
|
||||
) -> ThreadStoreResult<RemoveThreadAttachmentOutcome> {
|
||||
let state_db = state_db(store, "thread/attachment/remove")?;
|
||||
let _lifecycle_reservation = store
|
||||
.live_writer_locks
|
||||
.reserve_lifecycle(params.thread_id)
|
||||
.await;
|
||||
state_db
|
||||
.remove_thread_attachment(
|
||||
params.thread_id,
|
||||
¶ms.attachment_type,
|
||||
¶ms.identity_key,
|
||||
)
|
||||
.await
|
||||
.map_err(|error| attachment_error("remove", Some(params.thread_id), error))
|
||||
}
|
||||
|
||||
fn state_db<'store>(
|
||||
store: &'store LocalThreadStore,
|
||||
operation: &'static str,
|
||||
) -> ThreadStoreResult<&'store StateDbHandle> {
|
||||
store
|
||||
.state_db
|
||||
.as_ref()
|
||||
.ok_or(ThreadStoreError::Unsupported { operation })
|
||||
}
|
||||
|
||||
fn attachment_error(
|
||||
operation: &str,
|
||||
thread_id: Option<ThreadId>,
|
||||
error: impl std::fmt::Display,
|
||||
) -> ThreadStoreError {
|
||||
let message = error.to_string();
|
||||
if let Some(message) = message.strip_prefix("invalid thread attachment request: ") {
|
||||
return ThreadStoreError::InvalidRequest {
|
||||
message: message.to_string(),
|
||||
};
|
||||
}
|
||||
if message.starts_with("thread not found: ")
|
||||
&& let Some(thread_id) = thread_id
|
||||
{
|
||||
return ThreadStoreError::ThreadNotFound { thread_id };
|
||||
}
|
||||
ThreadStoreError::Internal {
|
||||
message: format!("failed to {operation} thread attachment: {message}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "thread_attachments_tests.rs"]
|
||||
mod tests;
|
||||
509
codex-rs/thread-store/src/local/thread_attachments_tests.rs
Normal file
509
codex-rs/thread-store/src/local/thread_attachments_tests.rs
Normal file
@@ -0,0 +1,509 @@
|
||||
//! Coverage for unloaded attachment operations and thread deletion exclusion.
|
||||
|
||||
use super::LocalThreadStore;
|
||||
use crate::AddThreadAttachmentOutcome;
|
||||
use crate::AddThreadAttachmentParams;
|
||||
use crate::DeleteThreadParams;
|
||||
use crate::DeleteThreadsParams;
|
||||
use crate::InMemoryThreadStore;
|
||||
use crate::ListThreadAttachmentsParams;
|
||||
use crate::RemoveThreadAttachmentOutcome;
|
||||
use crate::RemoveThreadAttachmentParams;
|
||||
use crate::ThreadAttachmentPage;
|
||||
use crate::ThreadStore;
|
||||
use crate::ThreadStoreError;
|
||||
use crate::local::test_support::test_config;
|
||||
use crate::local::test_support::write_session_file;
|
||||
use chrono::Utc;
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::protocol::SessionSource;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use uuid::Uuid;
|
||||
|
||||
#[tokio::test]
|
||||
async fn thread_attachments_require_a_supported_sqlite_store() {
|
||||
let thread_id = ThreadId::new();
|
||||
let default_store = InMemoryThreadStore::default();
|
||||
assert!(!default_store.supports_thread_attachments());
|
||||
assert!(matches!(
|
||||
default_store
|
||||
.add_thread_attachment(AddThreadAttachmentParams {
|
||||
thread_id,
|
||||
attachment_type: "pull_request".to_string(),
|
||||
identity_key: "openai/codex#1".to_string(),
|
||||
payload: json!({"url": "https://github.com/openai/codex/pull/1"}),
|
||||
})
|
||||
.await,
|
||||
Err(ThreadStoreError::Unsupported {
|
||||
operation: "thread/attachment/add"
|
||||
})
|
||||
));
|
||||
|
||||
let home = tempfile::TempDir::new().expect("temp dir");
|
||||
let store = LocalThreadStore::new(test_config(home.path()), /*state_db*/ None);
|
||||
assert!(!store.supports_thread_attachments());
|
||||
assert!(matches!(
|
||||
store
|
||||
.list_thread_attachments(ListThreadAttachmentsParams {
|
||||
thread_id,
|
||||
cursor: None,
|
||||
limit: 10,
|
||||
})
|
||||
.await,
|
||||
Err(ThreadStoreError::Unsupported {
|
||||
operation: "thread/attachment/list"
|
||||
})
|
||||
));
|
||||
assert!(matches!(
|
||||
store
|
||||
.remove_thread_attachment(RemoveThreadAttachmentParams {
|
||||
thread_id,
|
||||
attachment_type: "pull_request".to_string(),
|
||||
identity_key: "openai/codex#1".to_string(),
|
||||
})
|
||||
.await,
|
||||
Err(ThreadStoreError::Unsupported {
|
||||
operation: "thread/attachment/remove"
|
||||
})
|
||||
));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn unloaded_thread_attachments_support_listing_and_removal() {
|
||||
let home = tempfile::TempDir::new().expect("temp dir");
|
||||
let config = test_config(home.path());
|
||||
let runtime = codex_state::StateRuntime::init(
|
||||
config.sqlite.clone(),
|
||||
config.default_model_provider_id.clone(),
|
||||
)
|
||||
.await
|
||||
.expect("state db should initialize");
|
||||
let store = LocalThreadStore::new(config.clone(), Some(runtime.clone()));
|
||||
assert!(store.supports_thread_attachments());
|
||||
|
||||
let first_thread_id = ThreadId::new();
|
||||
let second_thread_id = ThreadId::new();
|
||||
for thread_id in [first_thread_id, second_thread_id] {
|
||||
let metadata = codex_state::ThreadMetadataBuilder::new(
|
||||
thread_id,
|
||||
home.path().join(format!("{thread_id}.jsonl")),
|
||||
Utc::now(),
|
||||
SessionSource::Cli,
|
||||
)
|
||||
.build(&config.default_model_provider_id);
|
||||
runtime
|
||||
.upsert_thread(&metadata)
|
||||
.await
|
||||
.expect("persist unloaded thread metadata");
|
||||
}
|
||||
|
||||
let params = AddThreadAttachmentParams {
|
||||
thread_id: first_thread_id,
|
||||
attachment_type: "pull_request".to_string(),
|
||||
identity_key: "openai/codex#1".to_string(),
|
||||
payload: json!({"url": "https://github.com/openai/codex/pull/1"}),
|
||||
};
|
||||
let AddThreadAttachmentOutcome::Created(first_attachment) = store
|
||||
.add_thread_attachment(params.clone())
|
||||
.await
|
||||
.expect("attach attachment to unloaded persisted thread")
|
||||
else {
|
||||
panic!("first explicit attachment should create an attachment");
|
||||
};
|
||||
assert_eq!(
|
||||
store
|
||||
.add_thread_attachment(params.clone())
|
||||
.await
|
||||
.expect("repeat attachment attachment"),
|
||||
AddThreadAttachmentOutcome::Existing(first_attachment.clone())
|
||||
);
|
||||
|
||||
let second_params = AddThreadAttachmentParams {
|
||||
thread_id: first_thread_id,
|
||||
identity_key: "openai/codex#2".to_string(),
|
||||
payload: json!({"url": "https://github.com/openai/codex/pull/2"}),
|
||||
..params.clone()
|
||||
};
|
||||
let AddThreadAttachmentOutcome::Created(second_attachment) = store
|
||||
.add_thread_attachment(second_params)
|
||||
.await
|
||||
.expect("attach second thread attachment")
|
||||
else {
|
||||
panic!("second thread attachment should create an attachment");
|
||||
};
|
||||
|
||||
let first_page = store
|
||||
.list_thread_attachments(ListThreadAttachmentsParams {
|
||||
thread_id: first_thread_id,
|
||||
cursor: None,
|
||||
limit: 1,
|
||||
})
|
||||
.await
|
||||
.expect("list first page");
|
||||
assert_eq!(first_page.attachments.len(), 1);
|
||||
let second_page = store
|
||||
.list_thread_attachments(ListThreadAttachmentsParams {
|
||||
thread_id: first_thread_id,
|
||||
cursor: first_page.next_cursor,
|
||||
limit: 1,
|
||||
})
|
||||
.await
|
||||
.expect("list second page");
|
||||
assert_eq!(second_page.attachments.len(), 1);
|
||||
assert_eq!(second_page.next_cursor, None);
|
||||
let listed_ids = [
|
||||
first_page.attachments[0].id.clone(),
|
||||
second_page.attachments[0].id.clone(),
|
||||
];
|
||||
assert!(listed_ids.contains(&first_attachment.id));
|
||||
assert!(listed_ids.contains(&second_attachment.id));
|
||||
|
||||
let removal_params = RemoveThreadAttachmentParams {
|
||||
thread_id: first_thread_id,
|
||||
attachment_type: params.attachment_type.clone(),
|
||||
identity_key: params.identity_key.clone(),
|
||||
};
|
||||
assert_eq!(
|
||||
store
|
||||
.remove_thread_attachment(removal_params.clone())
|
||||
.await
|
||||
.expect("remove existing attachment"),
|
||||
RemoveThreadAttachmentOutcome::Removed(first_attachment)
|
||||
);
|
||||
assert_eq!(
|
||||
store
|
||||
.remove_thread_attachment(removal_params)
|
||||
.await
|
||||
.expect("repeat attachment removal"),
|
||||
RemoveThreadAttachmentOutcome::NotFound
|
||||
);
|
||||
assert!(matches!(
|
||||
store
|
||||
.add_thread_attachment(params)
|
||||
.await
|
||||
.expect("reattach removed attachment"),
|
||||
AddThreadAttachmentOutcome::Created(_)
|
||||
));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn attachment_state_errors_preserve_missing_thread_and_invalid_request_categories() {
|
||||
let home = tempfile::TempDir::new().expect("temp dir");
|
||||
let config = test_config(home.path());
|
||||
let runtime = codex_state::StateRuntime::init(
|
||||
config.sqlite.clone(),
|
||||
config.default_model_provider_id.clone(),
|
||||
)
|
||||
.await
|
||||
.expect("state db should initialize");
|
||||
let store = LocalThreadStore::new(config, Some(runtime));
|
||||
let thread_id = ThreadId::new();
|
||||
|
||||
assert!(matches!(
|
||||
store
|
||||
.add_thread_attachment(AddThreadAttachmentParams {
|
||||
thread_id,
|
||||
attachment_type: "pull_request".to_string(),
|
||||
identity_key: "openai/codex#1".to_string(),
|
||||
payload: json!({}),
|
||||
})
|
||||
.await,
|
||||
Err(ThreadStoreError::ThreadNotFound { thread_id: missing }) if missing == thread_id
|
||||
));
|
||||
assert!(matches!(
|
||||
store
|
||||
.add_thread_attachment(AddThreadAttachmentParams {
|
||||
thread_id,
|
||||
attachment_type: " ".to_string(),
|
||||
identity_key: "openai/codex#1".to_string(),
|
||||
payload: json!({}),
|
||||
})
|
||||
.await,
|
||||
Err(ThreadStoreError::InvalidRequest { message })
|
||||
if message == "attachment type must not be empty"
|
||||
));
|
||||
assert!(matches!(
|
||||
store
|
||||
.list_thread_attachments(ListThreadAttachmentsParams {
|
||||
thread_id,
|
||||
cursor: None,
|
||||
limit: 0,
|
||||
})
|
||||
.await,
|
||||
Err(ThreadStoreError::InvalidRequest { message })
|
||||
if message == "page limit must be between 1 and 100"
|
||||
));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn attachment_mutations_wait_for_exclusive_thread_lifecycle_operations() {
|
||||
let home = tempfile::TempDir::new().expect("temp dir");
|
||||
let config = test_config(home.path());
|
||||
let runtime = codex_state::StateRuntime::init(
|
||||
config.sqlite.clone(),
|
||||
config.default_model_provider_id.clone(),
|
||||
)
|
||||
.await
|
||||
.expect("state db should initialize");
|
||||
let store = LocalThreadStore::new(config.clone(), Some(runtime.clone()));
|
||||
let thread_id = ThreadId::new();
|
||||
let metadata = codex_state::ThreadMetadataBuilder::new(
|
||||
thread_id,
|
||||
home.path().join(format!("{thread_id}.jsonl")),
|
||||
Utc::now(),
|
||||
SessionSource::Cli,
|
||||
)
|
||||
.build(&config.default_model_provider_id);
|
||||
runtime
|
||||
.upsert_thread(&metadata)
|
||||
.await
|
||||
.expect("persist attachment owner");
|
||||
|
||||
let lifecycle_guard = store.live_writer_locks.lock_lifecycle(thread_id).await;
|
||||
let mut attachment = Box::pin(store.add_thread_attachment(AddThreadAttachmentParams {
|
||||
thread_id,
|
||||
attachment_type: "pull_request".to_string(),
|
||||
identity_key: "openai/codex#1".to_string(),
|
||||
payload: json!({"url": "https://github.com/openai/codex/pull/1"}),
|
||||
}));
|
||||
tokio::select! {
|
||||
biased;
|
||||
result = &mut attachment => panic!("attachment attached during lifecycle mutation: {result:?}"),
|
||||
_ = tokio::task::yield_now() => {}
|
||||
}
|
||||
drop(lifecycle_guard);
|
||||
assert!(matches!(
|
||||
attachment.await,
|
||||
Ok(AddThreadAttachmentOutcome::Created(_))
|
||||
));
|
||||
|
||||
let lifecycle_guard = store.live_writer_locks.lock_lifecycle(thread_id).await;
|
||||
let mut removal = Box::pin(
|
||||
store.remove_thread_attachment(RemoveThreadAttachmentParams {
|
||||
thread_id,
|
||||
attachment_type: "pull_request".to_string(),
|
||||
identity_key: "openai/codex#1".to_string(),
|
||||
}),
|
||||
);
|
||||
tokio::select! {
|
||||
biased;
|
||||
result = &mut removal => panic!("attachment removed during lifecycle mutation: {result:?}"),
|
||||
_ = tokio::task::yield_now() => {}
|
||||
}
|
||||
drop(lifecycle_guard);
|
||||
assert!(matches!(
|
||||
removal.await,
|
||||
Ok(RemoveThreadAttachmentOutcome::Removed(_))
|
||||
));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn attachment_mutations_queued_behind_deletion_reject_deleted_threads() {
|
||||
enum DeleteMode {
|
||||
Single,
|
||||
Batch,
|
||||
}
|
||||
|
||||
for mode in [DeleteMode::Single, DeleteMode::Batch] {
|
||||
let home = tempfile::TempDir::new().expect("temp dir");
|
||||
let thread_id = ThreadId::new();
|
||||
let thread_ids = match mode {
|
||||
DeleteMode::Single => vec![thread_id],
|
||||
DeleteMode::Batch => vec![thread_id, ThreadId::new()],
|
||||
};
|
||||
let (store, _) = store_with_attachment_owners(home.path(), &thread_ids).await;
|
||||
let runtime = store.state_db().await.expect("state db");
|
||||
|
||||
let reservation = store.live_writer_locks.reserve_lifecycle(thread_id).await;
|
||||
let mut deletion = match mode {
|
||||
DeleteMode::Single => store.delete_thread(DeleteThreadParams { thread_id }),
|
||||
DeleteMode::Batch => store.delete_threads(DeleteThreadsParams {
|
||||
thread_ids: thread_ids.clone(),
|
||||
}),
|
||||
};
|
||||
assert!(futures::poll!(&mut deletion).is_pending());
|
||||
|
||||
// The queued exclusive delete must precede subsequent shared attachment reservations.
|
||||
let mut attachment = store.add_thread_attachment(AddThreadAttachmentParams {
|
||||
thread_id,
|
||||
attachment_type: "pull_request".to_string(),
|
||||
identity_key: "openai/codex#2".to_string(),
|
||||
payload: json!({"url": "https://github.com/openai/codex/pull/2"}),
|
||||
});
|
||||
let mut removal = store.remove_thread_attachment(RemoveThreadAttachmentParams {
|
||||
thread_id,
|
||||
attachment_type: "pull_request".to_string(),
|
||||
identity_key: "openai/codex#1".to_string(),
|
||||
});
|
||||
assert!(futures::poll!(&mut attachment).is_pending());
|
||||
assert!(futures::poll!(&mut removal).is_pending());
|
||||
drop(reservation);
|
||||
|
||||
let (deletion, attachment, removal) = tokio::join!(deletion, attachment, removal);
|
||||
deletion.expect("delete attachment owners");
|
||||
assert!(
|
||||
matches!(attachment, Err(ThreadStoreError::ThreadNotFound { thread_id: missing }) if missing == thread_id),
|
||||
"attachment resumed after deletion: {attachment:?}"
|
||||
);
|
||||
assert!(
|
||||
matches!(removal, Err(ThreadStoreError::ThreadNotFound { thread_id: missing }) if missing == thread_id),
|
||||
"removal resumed after deletion: {removal:?}"
|
||||
);
|
||||
for &owner_id in &thread_ids {
|
||||
assert_eq!(
|
||||
runtime
|
||||
.get_thread(owner_id)
|
||||
.await
|
||||
.expect("read deleted owner"),
|
||||
None
|
||||
);
|
||||
}
|
||||
for &owner_id in &thread_ids {
|
||||
assert_eq!(
|
||||
store
|
||||
.list_thread_attachments(ListThreadAttachmentsParams {
|
||||
thread_id: owner_id,
|
||||
cursor: None,
|
||||
limit: 10,
|
||||
})
|
||||
.await
|
||||
.expect("list attachments after deletion"),
|
||||
ThreadAttachmentPage {
|
||||
attachments: Vec::new(),
|
||||
next_cursor: None,
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn attachment_owner_deletion_can_retry_after_state_cleanup_fails() {
|
||||
let home = tempfile::TempDir::new().expect("temp dir");
|
||||
let parent_id = ThreadId::new();
|
||||
let child_id = ThreadId::new();
|
||||
let (store, rollout_paths) =
|
||||
store_with_attachment_owners(home.path(), &[parent_id, child_id]).await;
|
||||
let runtime = store.state_db().await.expect("state db");
|
||||
runtime
|
||||
.upsert_thread_spawn_edge(
|
||||
parent_id,
|
||||
child_id,
|
||||
codex_state::DirectionalThreadSpawnEdgeStatus::Closed,
|
||||
)
|
||||
.await
|
||||
.expect("persist child relation for deletion retry");
|
||||
let pool = runtime
|
||||
.sqlite()
|
||||
.open_read_write_pool(&runtime.sqlite().state_db_path())
|
||||
.await
|
||||
.expect("open state db for failure injection");
|
||||
sqlx::query(
|
||||
"CREATE TRIGGER fail_thread_delete BEFORE DELETE ON threads BEGIN SELECT RAISE(ABORT, 'state cleanup failed'); END",
|
||||
)
|
||||
.execute(&pool)
|
||||
.await
|
||||
.expect("inject state cleanup failure");
|
||||
let params = DeleteThreadsParams {
|
||||
thread_ids: vec![child_id, parent_id],
|
||||
};
|
||||
let error = store
|
||||
.delete_threads(params.clone())
|
||||
.await
|
||||
.expect_err("state cleanup failure must fail the delete");
|
||||
assert!(matches!(error, ThreadStoreError::Internal { .. }));
|
||||
assert!(rollout_paths.iter().all(|path| !path.exists()));
|
||||
assert_eq!(
|
||||
runtime
|
||||
.list_thread_spawn_descendants(parent_id)
|
||||
.await
|
||||
.expect("read child relation after failed deletion"),
|
||||
vec![child_id]
|
||||
);
|
||||
|
||||
sqlx::query("DROP TRIGGER fail_thread_delete")
|
||||
.execute(&pool)
|
||||
.await
|
||||
.expect("restore state cleanup");
|
||||
store
|
||||
.delete_thread(DeleteThreadParams {
|
||||
thread_id: child_id,
|
||||
})
|
||||
.await
|
||||
.expect("single-thread retry must remove the owner even without a rollout");
|
||||
store
|
||||
.delete_threads(params.clone())
|
||||
.await
|
||||
.expect("batch retry must tolerate missing rollouts and already-deleted members");
|
||||
for &owner_id in ¶ms.thread_ids {
|
||||
assert_eq!(
|
||||
store
|
||||
.list_thread_attachments(ListThreadAttachmentsParams {
|
||||
thread_id: owner_id,
|
||||
cursor: None,
|
||||
limit: 10,
|
||||
})
|
||||
.await
|
||||
.expect("list attachments after deletion retry"),
|
||||
ThreadAttachmentPage {
|
||||
attachments: Vec::new(),
|
||||
next_cursor: None,
|
||||
}
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
runtime
|
||||
.delete_threads_strict(¶ms.thread_ids)
|
||||
.await
|
||||
.expect("repeated app-server state cleanup is idempotent"),
|
||||
0
|
||||
);
|
||||
}
|
||||
|
||||
async fn store_with_attachment_owners(
|
||||
home: &Path,
|
||||
thread_ids: &[ThreadId],
|
||||
) -> (LocalThreadStore, Vec<PathBuf>) {
|
||||
let config = test_config(home);
|
||||
let runtime = codex_state::StateRuntime::init(
|
||||
config.sqlite.clone(),
|
||||
config.default_model_provider_id.clone(),
|
||||
)
|
||||
.await
|
||||
.expect("state db should initialize");
|
||||
let store = LocalThreadStore::new(config.clone(), Some(runtime.clone()));
|
||||
let mut rollout_paths = Vec::new();
|
||||
for &thread_id in thread_ids {
|
||||
let rollout_path = write_session_file(
|
||||
home,
|
||||
"2025-01-03T12-00-00",
|
||||
Uuid::parse_str(&thread_id.to_string()).expect("thread UUID"),
|
||||
)
|
||||
.expect("session file");
|
||||
let metadata = codex_state::ThreadMetadataBuilder::new(
|
||||
thread_id,
|
||||
rollout_path.clone(),
|
||||
Utc::now(),
|
||||
SessionSource::Cli,
|
||||
)
|
||||
.build(&config.default_model_provider_id);
|
||||
runtime
|
||||
.upsert_thread(&metadata)
|
||||
.await
|
||||
.expect("persist attachment owner");
|
||||
store
|
||||
.add_thread_attachment(AddThreadAttachmentParams {
|
||||
thread_id,
|
||||
attachment_type: "pull_request".to_string(),
|
||||
identity_key: "openai/codex#1".to_string(),
|
||||
payload: json!({"url": "https://github.com/openai/codex/pull/1"}),
|
||||
})
|
||||
.await
|
||||
.expect("attach attachment before deleting its owner");
|
||||
rollout_paths.push(rollout_path);
|
||||
}
|
||||
(store, rollout_paths)
|
||||
}
|
||||
591
codex-rs/thread-store/src/local/thread_history.rs
Normal file
591
codex-rs/thread-store/src/local/thread_history.rs
Normal file
@@ -0,0 +1,591 @@
|
||||
use codex_app_server_protocol::ThreadHistoryChangeSet;
|
||||
use codex_app_server_protocol::ThreadItemPayload;
|
||||
use codex_app_server_protocol::TurnStatus;
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::models::MessagePhase;
|
||||
use codex_protocol::realtime::RealtimeItem;
|
||||
use codex_state::SqlitePoolWriteExt;
|
||||
|
||||
use super::LocalThreadStore;
|
||||
use crate::ThreadStoreError;
|
||||
use crate::ThreadStoreResult;
|
||||
|
||||
mod read;
|
||||
mod realtime;
|
||||
mod search;
|
||||
mod segment_paging;
|
||||
mod turn_lookup;
|
||||
|
||||
pub(super) use read::list_items;
|
||||
pub(super) use read::list_turns;
|
||||
pub(super) use realtime::list_timeline;
|
||||
pub(super) use search::search_thread_occurrences;
|
||||
pub(super) use turn_lookup::find_source_turn;
|
||||
pub(super) use turn_lookup::find_visible_turn;
|
||||
|
||||
/// A valid complete rollout line with its absolute byte span in durable JSONL.
|
||||
///
|
||||
/// `start_byte_offset..end_byte_offset` includes the terminating newline.
|
||||
pub(super) struct ProjectedRolloutLine {
|
||||
pub ordinal: u64,
|
||||
pub start_byte_offset: u64,
|
||||
pub end_byte_offset: u64,
|
||||
pub fallback_created_at_ms: Option<i64>,
|
||||
pub changes: ThreadHistoryChangeSet,
|
||||
pub realtime_item: Option<RealtimeItem>,
|
||||
}
|
||||
|
||||
/// One ordered update to apply while advancing a rollout projection checkpoint.
|
||||
///
|
||||
/// Skipped ordinal ranges keep the byte and ordinal checkpoints describing the same durable
|
||||
/// prefix even when a complete rollout line cannot be projected.
|
||||
pub(super) enum RolloutProjectionStep {
|
||||
Line(Box<ProjectedRolloutLine>),
|
||||
SkippedOrdinalRange {
|
||||
start_ordinal: u64,
|
||||
end_ordinal_exclusive: u64,
|
||||
},
|
||||
}
|
||||
|
||||
pub(super) struct RolloutProjectionState {
|
||||
pub next_byte_offset: u64,
|
||||
pub next_ordinal: u64,
|
||||
}
|
||||
|
||||
pub(super) async fn projection_state(
|
||||
store: &LocalThreadStore,
|
||||
thread_id: ThreadId,
|
||||
) -> ThreadStoreResult<Option<RolloutProjectionState>> {
|
||||
if store.state_db.is_none() {
|
||||
return Ok(None);
|
||||
}
|
||||
let db_path = store.config.sqlite.thread_history_db_path();
|
||||
if !tokio::fs::try_exists(db_path.as_path())
|
||||
.await
|
||||
.map_err(thread_history_error)?
|
||||
{
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let pool = store.thread_history_db().await?;
|
||||
let state = sqlx::query_as::<_, (i64, i64)>(
|
||||
r#"
|
||||
SELECT next_rollout_byte_offset, next_rollout_ordinal
|
||||
FROM thread_history_projection_state
|
||||
WHERE thread_id = ?
|
||||
"#,
|
||||
)
|
||||
.bind(thread_id.to_string())
|
||||
.fetch_optional(pool)
|
||||
.await
|
||||
.map_err(thread_history_error)?;
|
||||
state
|
||||
.map(|(next_byte_offset, next_ordinal)| {
|
||||
Ok(RolloutProjectionState {
|
||||
next_byte_offset: u64::try_from(next_byte_offset).map_err(|_| {
|
||||
ThreadStoreError::Internal {
|
||||
message: format!(
|
||||
"thread history projection for {thread_id} has a negative byte offset"
|
||||
),
|
||||
}
|
||||
})?,
|
||||
next_ordinal: u64::try_from(next_ordinal).map_err(|_| {
|
||||
ThreadStoreError::Internal {
|
||||
message: format!(
|
||||
"thread history projection for {thread_id} has a negative ordinal"
|
||||
),
|
||||
}
|
||||
})?,
|
||||
})
|
||||
})
|
||||
.transpose()
|
||||
}
|
||||
|
||||
pub(super) async fn apply_projection(
|
||||
store: &LocalThreadStore,
|
||||
thread_id: ThreadId,
|
||||
start_offset: u64,
|
||||
next_offset: u64,
|
||||
initial_ordinal: u64,
|
||||
projections: Vec<RolloutProjectionStep>,
|
||||
) -> ThreadStoreResult<()> {
|
||||
let pool = store.thread_history_db().await?;
|
||||
// Write the projected rows and advance the JSONL offset and ordinal in one transaction. If
|
||||
// SQLite fails, it stays behind the durable rollout instead of claiming data it did not
|
||||
// materialize.
|
||||
let _writer = store
|
||||
.thread_history_writer
|
||||
.acquire()
|
||||
.await
|
||||
.map_err(thread_history_error)?;
|
||||
let mut transaction = pool.begin_immediate().await.map_err(thread_history_error)?;
|
||||
let thread_id = thread_id.to_string();
|
||||
let projection_state = sqlx::query_as::<_, (i64, i64)>(
|
||||
r#"
|
||||
SELECT next_rollout_byte_offset, next_rollout_ordinal
|
||||
FROM thread_history_projection_state
|
||||
WHERE thread_id = ?
|
||||
"#,
|
||||
)
|
||||
.bind(thread_id.as_str())
|
||||
.fetch_optional(&mut *transaction)
|
||||
.await
|
||||
.map_err(thread_history_error)?;
|
||||
let (expected_offset, mut next_ordinal) =
|
||||
projection_state.unwrap_or((0, sqlite_integer(initial_ordinal, "rollout ordinal")?));
|
||||
let start_offset = sqlite_integer(start_offset, "rollout byte offset")?;
|
||||
if expected_offset != start_offset {
|
||||
return Err(ThreadStoreError::Internal {
|
||||
message: format!("thread history projection for {thread_id} is behind durable rollout"),
|
||||
});
|
||||
}
|
||||
|
||||
for projection in projections {
|
||||
match projection {
|
||||
RolloutProjectionStep::Line(projection) => {
|
||||
let ordinal = sqlite_integer(projection.ordinal, "rollout ordinal")?;
|
||||
if ordinal != next_ordinal {
|
||||
return Err(ThreadStoreError::Internal {
|
||||
message: format!(
|
||||
"thread history projection for {thread_id} expected ordinal {next_ordinal}, got {ordinal}"
|
||||
),
|
||||
});
|
||||
}
|
||||
apply_change_set(
|
||||
&mut transaction,
|
||||
thread_id.as_str(),
|
||||
ordinal,
|
||||
sqlite_integer(projection.start_byte_offset, "rollout byte offset")?,
|
||||
sqlite_integer(projection.end_byte_offset, "rollout byte offset")?,
|
||||
projection.fallback_created_at_ms,
|
||||
projection.changes,
|
||||
)
|
||||
.await?;
|
||||
if let Some(item) = projection.realtime_item {
|
||||
let item_json = serde_json::to_string(&item).map_err(thread_history_error)?;
|
||||
sqlx::query(
|
||||
r#"
|
||||
INSERT INTO thread_realtime_items (
|
||||
thread_id,
|
||||
item_id,
|
||||
rollout_ordinal,
|
||||
created_at_ms,
|
||||
item_type,
|
||||
item_json
|
||||
) VALUES (?, ?, ?, ?, json_extract(?, '$.type'), ?)
|
||||
ON CONFLICT(thread_id, item_id) DO NOTHING
|
||||
"#,
|
||||
)
|
||||
.bind(thread_id.as_str())
|
||||
.bind(item.id.as_str())
|
||||
.bind(ordinal)
|
||||
.bind(projection.fallback_created_at_ms.ok_or_else(|| {
|
||||
ThreadStoreError::Internal {
|
||||
message: "realtime rollout item is missing its timestamp".to_string(),
|
||||
}
|
||||
})?)
|
||||
.bind(item_json.as_str())
|
||||
.bind(item_json.as_str())
|
||||
.execute(&mut *transaction)
|
||||
.await
|
||||
.map_err(thread_history_error)?;
|
||||
}
|
||||
next_ordinal =
|
||||
next_ordinal
|
||||
.checked_add(1)
|
||||
.ok_or_else(|| ThreadStoreError::Internal {
|
||||
message: "rollout ordinal exceeds SQLite integer range".to_string(),
|
||||
})?;
|
||||
}
|
||||
RolloutProjectionStep::SkippedOrdinalRange {
|
||||
start_ordinal,
|
||||
end_ordinal_exclusive,
|
||||
} => {
|
||||
let start_ordinal = sqlite_integer(start_ordinal, "rollout ordinal")?;
|
||||
if start_ordinal != next_ordinal {
|
||||
return Err(ThreadStoreError::Internal {
|
||||
message: format!(
|
||||
"thread history projection for {thread_id} expected ordinal {next_ordinal}, got {start_ordinal}"
|
||||
),
|
||||
});
|
||||
}
|
||||
let end_ordinal_exclusive =
|
||||
sqlite_integer(end_ordinal_exclusive, "rollout ordinal")?;
|
||||
if end_ordinal_exclusive <= start_ordinal {
|
||||
return Err(ThreadStoreError::Internal {
|
||||
message: format!(
|
||||
"thread history projection for {thread_id} has an empty skipped ordinal range"
|
||||
),
|
||||
});
|
||||
}
|
||||
next_ordinal = end_ordinal_exclusive;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
sqlx::query(
|
||||
r#"
|
||||
INSERT INTO thread_history_projection_state (
|
||||
thread_id,
|
||||
next_rollout_byte_offset,
|
||||
next_rollout_ordinal
|
||||
) VALUES (?, ?, ?)
|
||||
ON CONFLICT(thread_id) DO UPDATE SET
|
||||
next_rollout_byte_offset = excluded.next_rollout_byte_offset,
|
||||
next_rollout_ordinal = excluded.next_rollout_ordinal
|
||||
"#,
|
||||
)
|
||||
.bind(thread_id.as_str())
|
||||
.bind(sqlite_integer(next_offset, "rollout byte offset")?)
|
||||
.bind(next_ordinal)
|
||||
.execute(&mut *transaction)
|
||||
.await
|
||||
.map_err(thread_history_error)?;
|
||||
transaction.commit().await.map_err(thread_history_error)
|
||||
}
|
||||
|
||||
pub(super) async fn delete_thread(
|
||||
store: &LocalThreadStore,
|
||||
thread_id: ThreadId,
|
||||
) -> ThreadStoreResult<()> {
|
||||
let db_path = store.config.sqlite.thread_history_db_path();
|
||||
if !tokio::fs::try_exists(db_path.as_path())
|
||||
.await
|
||||
.map_err(thread_history_delete_error)?
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let pool = store.thread_history_db().await?;
|
||||
let _writer = store
|
||||
.thread_history_writer
|
||||
.acquire()
|
||||
.await
|
||||
.map_err(thread_history_delete_error)?;
|
||||
let mut transaction = pool
|
||||
.begin_immediate()
|
||||
.await
|
||||
.map_err(thread_history_delete_error)?;
|
||||
let thread_id = thread_id.to_string();
|
||||
sqlx::query("DELETE FROM thread_items WHERE thread_id = ?")
|
||||
.bind(thread_id.as_str())
|
||||
.execute(&mut *transaction)
|
||||
.await
|
||||
.map_err(thread_history_delete_error)?;
|
||||
sqlx::query("DELETE FROM thread_realtime_items WHERE thread_id = ?")
|
||||
.bind(thread_id.as_str())
|
||||
.execute(&mut *transaction)
|
||||
.await
|
||||
.map_err(thread_history_delete_error)?;
|
||||
sqlx::query("DELETE FROM thread_turns WHERE thread_id = ?")
|
||||
.bind(thread_id.as_str())
|
||||
.execute(&mut *transaction)
|
||||
.await
|
||||
.map_err(thread_history_delete_error)?;
|
||||
sqlx::query("DELETE FROM thread_history_projection_state WHERE thread_id = ?")
|
||||
.bind(thread_id.as_str())
|
||||
.execute(&mut *transaction)
|
||||
.await
|
||||
.map_err(thread_history_delete_error)?;
|
||||
transaction
|
||||
.commit()
|
||||
.await
|
||||
.map_err(thread_history_delete_error)
|
||||
}
|
||||
|
||||
async fn apply_change_set(
|
||||
transaction: &mut sqlx::Transaction<'_, sqlx::Sqlite>,
|
||||
thread_id: &str,
|
||||
rollout_ordinal: i64,
|
||||
rollout_byte_offset: i64,
|
||||
rollout_end_byte_offset: i64,
|
||||
fallback_created_at_ms: Option<i64>,
|
||||
changes: ThreadHistoryChangeSet,
|
||||
) -> ThreadStoreResult<()> {
|
||||
for turn in changes.changed_turns {
|
||||
let turn_id = turn.turn_id;
|
||||
let error_json = turn
|
||||
.error
|
||||
.as_ref()
|
||||
.map(serde_json::to_string)
|
||||
.transpose()
|
||||
.map_err(thread_history_error)?;
|
||||
let (terminal_ordinal, terminal_byte_offset) = match &turn.status {
|
||||
TurnStatus::Completed | TurnStatus::Interrupted | TurnStatus::Failed => {
|
||||
(Some(rollout_ordinal), Some(rollout_end_byte_offset))
|
||||
}
|
||||
TurnStatus::InProgress => (None, None),
|
||||
};
|
||||
// The same turn can appear again as it moves from started to completed. Update its latest
|
||||
// status, error, and timestamps, but keep the rollout ordinal from the first record that
|
||||
// created it.
|
||||
sqlx::query(
|
||||
r#"
|
||||
INSERT INTO thread_turns (
|
||||
thread_id,
|
||||
turn_id,
|
||||
root_turn_id,
|
||||
rollout_ordinal,
|
||||
rollout_byte_offset,
|
||||
rollout_end_ordinal,
|
||||
rollout_end_byte_offset,
|
||||
status,
|
||||
error_json,
|
||||
started_at,
|
||||
completed_at,
|
||||
duration_ms
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(thread_id, turn_id) DO UPDATE SET
|
||||
root_turn_id = COALESCE(thread_turns.root_turn_id, excluded.root_turn_id),
|
||||
rollout_end_ordinal = excluded.rollout_end_ordinal,
|
||||
rollout_end_byte_offset = excluded.rollout_end_byte_offset,
|
||||
status = excluded.status,
|
||||
error_json = excluded.error_json,
|
||||
started_at = excluded.started_at,
|
||||
completed_at = excluded.completed_at,
|
||||
duration_ms = excluded.duration_ms
|
||||
WHERE thread_turns.rollout_end_ordinal IS NULL
|
||||
AND thread_turns.status = 'inProgress'
|
||||
"#,
|
||||
)
|
||||
.bind(thread_id)
|
||||
.bind(turn_id.as_str())
|
||||
.bind(turn.root_turn_id)
|
||||
.bind(rollout_ordinal)
|
||||
.bind(rollout_byte_offset)
|
||||
.bind(terminal_ordinal)
|
||||
.bind(terminal_byte_offset)
|
||||
.bind(turn_status(&turn.status))
|
||||
.bind(error_json)
|
||||
.bind(turn.started_at)
|
||||
.bind(turn.completed_at)
|
||||
.bind(turn.duration_ms)
|
||||
.execute(&mut **transaction)
|
||||
.await
|
||||
.map_err(thread_history_error)?;
|
||||
|
||||
// Review turns can persist completed items before their turn lifecycle record. Fill the
|
||||
// summary IDs from those older item rows when the turn row finally arrives.
|
||||
sqlx::query(
|
||||
r#"
|
||||
UPDATE thread_turns
|
||||
SET
|
||||
first_user_item_id = COALESCE(
|
||||
first_user_item_id,
|
||||
(
|
||||
SELECT item_id
|
||||
FROM thread_items
|
||||
WHERE thread_id = ?
|
||||
AND turn_id = ?
|
||||
AND (
|
||||
item_type = 'userMessage'
|
||||
OR (item_type = '' AND json_extract(item_json, '$.type') = 'userMessage')
|
||||
)
|
||||
ORDER BY rollout_ordinal
|
||||
LIMIT 1
|
||||
)
|
||||
),
|
||||
final_agent_item_id = COALESCE(
|
||||
(
|
||||
SELECT item_id
|
||||
FROM thread_items
|
||||
WHERE thread_id = ?
|
||||
AND turn_id = ?
|
||||
AND (
|
||||
item_type = 'agentMessage'
|
||||
OR (item_type = '' AND json_extract(item_json, '$.type') = 'agentMessage')
|
||||
)
|
||||
AND json_extract(item_json, '$.phase') = 'final_answer'
|
||||
ORDER BY rollout_ordinal DESC
|
||||
LIMIT 1
|
||||
),
|
||||
CASE
|
||||
WHEN status IN ('completed', 'interrupted', 'failed') THEN (
|
||||
SELECT item_id
|
||||
FROM thread_items
|
||||
WHERE thread_id = ?
|
||||
AND turn_id = ?
|
||||
AND (
|
||||
item_type = 'agentMessage'
|
||||
OR (item_type = '' AND json_extract(item_json, '$.type') = 'agentMessage')
|
||||
)
|
||||
AND json_extract(item_json, '$.phase') IS NULL
|
||||
ORDER BY rollout_ordinal DESC
|
||||
LIMIT 1
|
||||
)
|
||||
END,
|
||||
final_agent_item_id
|
||||
)
|
||||
WHERE thread_id = ?
|
||||
AND turn_id = ?
|
||||
AND (
|
||||
rollout_end_ordinal = ?
|
||||
OR status = 'inProgress'
|
||||
)
|
||||
"#,
|
||||
)
|
||||
.bind(thread_id)
|
||||
.bind(turn_id.as_str())
|
||||
.bind(thread_id)
|
||||
.bind(turn_id.as_str())
|
||||
.bind(thread_id)
|
||||
.bind(turn_id.as_str())
|
||||
.bind(thread_id)
|
||||
.bind(turn_id.as_str())
|
||||
.bind(rollout_ordinal)
|
||||
.execute(&mut **transaction)
|
||||
.await
|
||||
.map_err(thread_history_error)?;
|
||||
}
|
||||
|
||||
for change in changes.changed_items {
|
||||
let item = change.item;
|
||||
let created_at_ms =
|
||||
item.started_at_ms
|
||||
.or(fallback_created_at_ms)
|
||||
.ok_or_else(|| ThreadStoreError::Internal {
|
||||
message: format!(
|
||||
"thread history projection for {thread_id} is missing an item creation timestamp"
|
||||
),
|
||||
})?;
|
||||
let item_id = item.id().to_string();
|
||||
let item_json = serde_json::to_string(&item.payload).map_err(thread_history_error)?;
|
||||
// Completed items are immutable: local producers emit ItemCompleted exactly once per
|
||||
// item. Tolerate an unexpected duplicate defensively so it cannot poison materialization,
|
||||
// preserving the original creation ordinal and timestamp while updating its snapshot.
|
||||
sqlx::query(
|
||||
r#"
|
||||
INSERT INTO thread_items (
|
||||
thread_id,
|
||||
turn_id,
|
||||
item_id,
|
||||
rollout_ordinal,
|
||||
updated_at_ordinal,
|
||||
created_at_ms,
|
||||
started_at_ms,
|
||||
completed_at_ms,
|
||||
item_type,
|
||||
item_json
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, json_extract(?, '$.type'), ?)
|
||||
ON CONFLICT(thread_id, turn_id, item_id) DO UPDATE SET
|
||||
updated_at_ordinal = excluded.updated_at_ordinal,
|
||||
started_at_ms = COALESCE(thread_items.started_at_ms, excluded.started_at_ms),
|
||||
completed_at_ms = COALESCE(thread_items.completed_at_ms, excluded.completed_at_ms),
|
||||
item_type = excluded.item_type,
|
||||
item_json = excluded.item_json
|
||||
"#,
|
||||
)
|
||||
.bind(thread_id)
|
||||
.bind(change.turn_id.as_str())
|
||||
.bind(item_id.as_str())
|
||||
.bind(rollout_ordinal)
|
||||
.bind(rollout_ordinal)
|
||||
.bind(created_at_ms)
|
||||
.bind(item.started_at_ms)
|
||||
.bind(item.completed_at_ms)
|
||||
.bind(item_json.as_str())
|
||||
.bind(item_json)
|
||||
.execute(&mut **transaction)
|
||||
.await
|
||||
.map_err(thread_history_error)?;
|
||||
|
||||
// Keep summary item IDs on the turn row so reads do not need to scan every item in the
|
||||
// turn.
|
||||
match item.payload {
|
||||
ThreadItemPayload::UserMessage { .. } => {
|
||||
sqlx::query(
|
||||
r#"
|
||||
UPDATE thread_turns
|
||||
SET first_user_item_id = COALESCE(first_user_item_id, ?)
|
||||
WHERE thread_id = ?
|
||||
AND turn_id = ?
|
||||
AND rollout_end_ordinal IS NULL
|
||||
AND status = 'inProgress'
|
||||
"#,
|
||||
)
|
||||
.bind(item_id.as_str())
|
||||
.bind(thread_id)
|
||||
.bind(change.turn_id.as_str())
|
||||
.execute(&mut **transaction)
|
||||
.await
|
||||
.map_err(thread_history_error)?;
|
||||
}
|
||||
ThreadItemPayload::AgentMessage {
|
||||
phase: Some(MessagePhase::FinalAnswer),
|
||||
..
|
||||
} => {
|
||||
sqlx::query(
|
||||
r#"
|
||||
UPDATE thread_turns
|
||||
SET final_agent_item_id = ?
|
||||
WHERE thread_id = ?
|
||||
AND turn_id = ?
|
||||
AND rollout_end_ordinal IS NULL
|
||||
AND status = 'inProgress'
|
||||
"#,
|
||||
)
|
||||
.bind(item_id.as_str())
|
||||
.bind(thread_id)
|
||||
.bind(change.turn_id.as_str())
|
||||
.execute(&mut **transaction)
|
||||
.await
|
||||
.map_err(thread_history_error)?;
|
||||
}
|
||||
ThreadItemPayload::AgentMessage {
|
||||
phase: Some(MessagePhase::Commentary | MessagePhase::PartialAnswer) | None,
|
||||
..
|
||||
}
|
||||
| ThreadItemPayload::HookPrompt { .. }
|
||||
| ThreadItemPayload::FunctionCallOutput { .. }
|
||||
| ThreadItemPayload::Plan { .. }
|
||||
| ThreadItemPayload::Reasoning { .. }
|
||||
| ThreadItemPayload::CommandExecution { .. }
|
||||
| ThreadItemPayload::FileChange { .. }
|
||||
| ThreadItemPayload::McpToolCall { .. }
|
||||
| ThreadItemPayload::DynamicToolCall { .. }
|
||||
| ThreadItemPayload::CollabAgentToolCall { .. }
|
||||
| ThreadItemPayload::SubAgentActivity { .. }
|
||||
| ThreadItemPayload::WebSearch(_)
|
||||
| ThreadItemPayload::ImageView { .. }
|
||||
| ThreadItemPayload::Sleep(_)
|
||||
| ThreadItemPayload::ImageGeneration(_)
|
||||
| ThreadItemPayload::EnteredReviewMode { .. }
|
||||
| ThreadItemPayload::ExitedReviewMode { .. }
|
||||
| ThreadItemPayload::ContextCompaction { .. } => {}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn turn_status(status: &TurnStatus) -> &'static str {
|
||||
match status {
|
||||
TurnStatus::Completed => "completed",
|
||||
TurnStatus::Interrupted => "interrupted",
|
||||
TurnStatus::Failed => "failed",
|
||||
TurnStatus::InProgress => "inProgress",
|
||||
}
|
||||
}
|
||||
|
||||
fn sqlite_integer(value: u64, field: &str) -> ThreadStoreResult<i64> {
|
||||
i64::try_from(value).map_err(|_| ThreadStoreError::Internal {
|
||||
message: format!("{field} exceeds SQLite integer range"),
|
||||
})
|
||||
}
|
||||
|
||||
fn thread_history_error(err: impl std::fmt::Display) -> ThreadStoreError {
|
||||
ThreadStoreError::Internal {
|
||||
message: format!("failed to access thread history: {err}"),
|
||||
}
|
||||
}
|
||||
|
||||
impl From<sqlx::Error> for ThreadStoreError {
|
||||
fn from(err: sqlx::Error) -> Self {
|
||||
thread_history_error(err)
|
||||
}
|
||||
}
|
||||
|
||||
fn thread_history_delete_error(err: impl std::fmt::Display) -> ThreadStoreError {
|
||||
ThreadStoreError::Internal {
|
||||
message: format!("failed to delete thread history: {err}"),
|
||||
}
|
||||
}
|
||||
455
codex-rs/thread-store/src/local/thread_history/read.rs
Normal file
455
codex-rs/thread-store/src/local/thread_history/read.rs
Normal file
@@ -0,0 +1,455 @@
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::protocol::ThreadHistoryMode;
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
use sqlx::Row;
|
||||
|
||||
use super::super::LocalThreadStore;
|
||||
use super::super::rollout_lineage::RolloutLineage;
|
||||
use super::segment_paging::page_item_rows;
|
||||
use super::segment_paging::page_turn_rows;
|
||||
use super::segment_paging::validate_page_size;
|
||||
use super::sqlite_integer;
|
||||
use super::turn_lookup::find_source_turn;
|
||||
use crate::ItemPage;
|
||||
use crate::ListItemsParams;
|
||||
use crate::ListTurnsParams;
|
||||
use crate::StoredThreadItem;
|
||||
use crate::StoredTurn;
|
||||
use crate::StoredTurnError;
|
||||
use crate::StoredTurnItemsView;
|
||||
use crate::StoredTurnStatus;
|
||||
use crate::ThreadStoreError;
|
||||
use crate::ThreadStoreResult;
|
||||
use crate::TurnPage;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "read_tests.rs"]
|
||||
mod tests;
|
||||
|
||||
#[derive(Clone, Deserialize, PartialEq, Eq, Serialize)]
|
||||
#[serde(tag = "kind", rename_all = "camelCase")]
|
||||
pub(super) enum CursorScope {
|
||||
Turns,
|
||||
ItemsByCreatedAtOrdinal,
|
||||
ItemsByUpdatedAtOrdinal,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub(super) struct HistoryCursor {
|
||||
pub requested_thread_id: ThreadId,
|
||||
pub rollout_ordinal: u64,
|
||||
pub include_anchor: bool,
|
||||
pub scope: CursorScope,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub(super) struct RolloutHistoryPosition {
|
||||
pub rollout_ordinal: i64,
|
||||
}
|
||||
|
||||
pub(super) struct StoredTurnRow {
|
||||
pub position: RolloutHistoryPosition,
|
||||
pub turn_id: String,
|
||||
pub root_turn_id: Option<String>,
|
||||
pub status: StoredTurnStatus,
|
||||
pub error: Option<StoredTurnError>,
|
||||
pub started_at: Option<i64>,
|
||||
pub completed_at: Option<i64>,
|
||||
pub duration_ms: Option<i64>,
|
||||
pub first_user_item_id: Option<String>,
|
||||
pub final_agent_item_id: Option<String>,
|
||||
pub summary_items: Vec<StoredThreadItem>,
|
||||
}
|
||||
|
||||
#[derive(sqlx_macros::FromRow)]
|
||||
pub(super) struct StoredSummaryColumns {
|
||||
summary_first_user_turn_id: Option<String>,
|
||||
summary_first_user_item_id: Option<String>,
|
||||
summary_first_user_rollout_ordinal: Option<i64>,
|
||||
summary_first_user_updated_at_ordinal: Option<i64>,
|
||||
summary_first_user_created_at_ms: Option<i64>,
|
||||
summary_first_user_started_at_ms: Option<i64>,
|
||||
summary_first_user_completed_at_ms: Option<i64>,
|
||||
summary_first_user_item_json: Option<String>,
|
||||
summary_final_agent_turn_id: Option<String>,
|
||||
summary_final_agent_item_id: Option<String>,
|
||||
summary_final_agent_rollout_ordinal: Option<i64>,
|
||||
summary_final_agent_updated_at_ordinal: Option<i64>,
|
||||
summary_final_agent_created_at_ms: Option<i64>,
|
||||
summary_final_agent_started_at_ms: Option<i64>,
|
||||
summary_final_agent_completed_at_ms: Option<i64>,
|
||||
summary_final_agent_item_json: Option<String>,
|
||||
}
|
||||
|
||||
struct StoredSummaryItemColumns {
|
||||
turn_id: Option<String>,
|
||||
item_id: Option<String>,
|
||||
rollout_ordinal: Option<i64>,
|
||||
updated_at_ordinal: Option<i64>,
|
||||
created_at_ms: Option<i64>,
|
||||
started_at_ms: Option<i64>,
|
||||
completed_at_ms: Option<i64>,
|
||||
item_json: Option<String>,
|
||||
}
|
||||
|
||||
pub(super) struct StoredThreadItemRow {
|
||||
pub position: RolloutHistoryPosition,
|
||||
pub item: StoredThreadItem,
|
||||
}
|
||||
|
||||
pub(in crate::local) async fn list_turns(
|
||||
store: &LocalThreadStore,
|
||||
params: ListTurnsParams,
|
||||
) -> ThreadStoreResult<TurnPage> {
|
||||
validate_thread_for_paginated_reads(
|
||||
store,
|
||||
params.thread_id,
|
||||
params.include_archived,
|
||||
"list_turns",
|
||||
)
|
||||
.await?;
|
||||
validate_page_size(params.page_size)?;
|
||||
let lineage = store
|
||||
.resolve_rollout_lineage_for_history_page(params.thread_id)
|
||||
.await?;
|
||||
let pool = store.thread_history_db().await?;
|
||||
let page = page_turn_rows(
|
||||
pool,
|
||||
params.thread_id,
|
||||
&lineage,
|
||||
params.cursor.as_deref(),
|
||||
params.page_size,
|
||||
params.sort_direction,
|
||||
params.items_view,
|
||||
)
|
||||
.await?;
|
||||
let mut turns = Vec::with_capacity(page.rows.len());
|
||||
for turn in page.rows {
|
||||
let items = match params.items_view {
|
||||
StoredTurnItemsView::NotLoaded => Vec::new(),
|
||||
StoredTurnItemsView::Summary
|
||||
if matches!(turn.status, StoredTurnStatus::Interrupted)
|
||||
&& turn.first_user_item_id.is_none()
|
||||
&& turn.final_agent_item_id.is_none() =>
|
||||
{
|
||||
// Synthetic fork-boundary rows are interrupted without local summary IDs.
|
||||
// Load their summary from the earliest visible source turn.
|
||||
load_inherited_summary_items(pool, &lineage, &turn).await?
|
||||
}
|
||||
StoredTurnItemsView::Summary => turn.summary_items,
|
||||
};
|
||||
turns.push(StoredTurn {
|
||||
turn_id: turn.turn_id,
|
||||
root_turn_id: turn.root_turn_id,
|
||||
items,
|
||||
items_view: params.items_view,
|
||||
status: turn.status,
|
||||
error: turn.error,
|
||||
started_at: turn.started_at,
|
||||
completed_at: turn.completed_at,
|
||||
duration_ms: turn.duration_ms,
|
||||
});
|
||||
}
|
||||
|
||||
Ok(TurnPage {
|
||||
turns,
|
||||
next_cursor: page.next_cursor,
|
||||
backwards_cursor: page.backwards_cursor,
|
||||
})
|
||||
}
|
||||
|
||||
pub(in crate::local) async fn list_items(
|
||||
store: &LocalThreadStore,
|
||||
mut params: ListItemsParams,
|
||||
) -> ThreadStoreResult<ItemPage> {
|
||||
validate_thread_for_paginated_reads(
|
||||
store,
|
||||
params.thread_id,
|
||||
params.include_archived,
|
||||
"list_items",
|
||||
)
|
||||
.await?;
|
||||
if let Some(ids) = ¶ms.item_ids {
|
||||
if params.turn_id.is_none()
|
||||
|| params.position.is_some()
|
||||
|| params.after_updated_at_ordinal.is_some()
|
||||
|| params.before_updated_at_ordinal.is_some()
|
||||
|| params.sort_key != crate::ItemSortKey::CreatedAtOrdinal
|
||||
|| !(1..=100).contains(&ids.len())
|
||||
{
|
||||
return Err(ThreadStoreError::InvalidRequest {
|
||||
message: "itemIds requires turnId, 1 to 100 IDs, and no cursor or update replay"
|
||||
.to_string(),
|
||||
});
|
||||
}
|
||||
params.page_size = ids.len();
|
||||
params.sort_direction = crate::SortDirection::Asc;
|
||||
}
|
||||
validate_page_size(params.page_size)?;
|
||||
let lineage = store
|
||||
.resolve_rollout_lineage_for_history_page(params.thread_id)
|
||||
.await?;
|
||||
let pool = store.thread_history_db().await?;
|
||||
let page = page_item_rows(pool, &lineage, ¶ms).await?;
|
||||
|
||||
Ok(ItemPage {
|
||||
items: page.rows.into_iter().map(|row| row.item).collect(),
|
||||
next_cursor: page.next_cursor,
|
||||
backwards_cursor: page.backwards_cursor,
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) async fn validate_thread_for_paginated_reads(
|
||||
store: &LocalThreadStore,
|
||||
thread_id: ThreadId,
|
||||
include_archived: bool,
|
||||
operation: &'static str,
|
||||
) -> ThreadStoreResult<()> {
|
||||
let Some(state_db) = store.state_db().await else {
|
||||
return Err(ThreadStoreError::Unsupported { operation });
|
||||
};
|
||||
let Some(metadata) =
|
||||
state_db
|
||||
.get_thread(thread_id)
|
||||
.await
|
||||
.map_err(|err| ThreadStoreError::Internal {
|
||||
message: format!("failed to read thread metadata: {err}"),
|
||||
})?
|
||||
else {
|
||||
return Err(ThreadStoreError::Unsupported { operation });
|
||||
};
|
||||
if metadata.archived_at.is_some() && !include_archived {
|
||||
return Err(ThreadStoreError::InvalidRequest {
|
||||
message: format!("thread {thread_id} is archived"),
|
||||
});
|
||||
}
|
||||
match metadata.history_mode {
|
||||
ThreadHistoryMode::Legacy => Err(ThreadStoreError::Unsupported { operation }),
|
||||
ThreadHistoryMode::Paginated => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
async fn load_inherited_summary_items(
|
||||
pool: &sqlx::SqlitePool,
|
||||
lineage: &RolloutLineage,
|
||||
turn: &StoredTurnRow,
|
||||
) -> ThreadStoreResult<Vec<StoredThreadItem>> {
|
||||
let source = find_source_turn(pool, lineage, turn.turn_id.as_str()).await?;
|
||||
let Some(segment) = lineage
|
||||
.segments()
|
||||
.iter()
|
||||
.find(|segment| segment.rollout_id() == source.rollout_id)
|
||||
else {
|
||||
return Ok(Vec::new());
|
||||
};
|
||||
let start_ordinal = sqlite_integer(segment.start_ordinal(), "rollout ordinal")?;
|
||||
let end_ordinal = segment
|
||||
.end_ordinal()
|
||||
.map(|ordinal| sqlite_integer(ordinal, "rollout ordinal"))
|
||||
.transpose()?;
|
||||
let rows = sqlx::query(
|
||||
r#"
|
||||
SELECT turn_id, item_id, updated_at_ordinal, created_at_ms, started_at_ms, completed_at_ms, item_json
|
||||
FROM thread_items
|
||||
WHERE thread_id = ?
|
||||
AND turn_id = ?
|
||||
AND rollout_ordinal >= ?
|
||||
AND (? IS NULL OR rollout_ordinal < ?)
|
||||
AND (item_id = ? OR item_id = ?)
|
||||
ORDER BY rollout_ordinal ASC
|
||||
"#,
|
||||
)
|
||||
.bind(source.rollout_id.to_string())
|
||||
.bind(turn.turn_id.as_str())
|
||||
.bind(start_ordinal)
|
||||
.bind(end_ordinal)
|
||||
.bind(end_ordinal)
|
||||
.bind(source.first_user_item_id)
|
||||
.bind(source.final_agent_item_id)
|
||||
.fetch_all(pool)
|
||||
.await
|
||||
.map_err(super::thread_history_error)?;
|
||||
rows.into_iter().map(stored_thread_item).collect()
|
||||
}
|
||||
|
||||
pub(super) fn parse_cursor(
|
||||
cursor: Option<&str>,
|
||||
requested_thread_id: ThreadId,
|
||||
scope: CursorScope,
|
||||
) -> ThreadStoreResult<Option<HistoryCursor>> {
|
||||
let Some(cursor) = cursor else {
|
||||
return Ok(None);
|
||||
};
|
||||
let cursor_value: HistoryCursor =
|
||||
serde_json::from_str(cursor).map_err(|_| invalid_cursor(cursor))?;
|
||||
if cursor_value.requested_thread_id != requested_thread_id || cursor_value.scope != scope {
|
||||
return Err(invalid_cursor(cursor));
|
||||
}
|
||||
Ok(Some(cursor_value))
|
||||
}
|
||||
|
||||
pub(super) fn serialize_cursor(
|
||||
requested_thread_id: ThreadId,
|
||||
scope: CursorScope,
|
||||
rollout_ordinal: i64,
|
||||
include_anchor: bool,
|
||||
) -> ThreadStoreResult<String> {
|
||||
let rollout_ordinal =
|
||||
u64::try_from(rollout_ordinal).map_err(|_| invalid_cursor("negative rollout ordinal"))?;
|
||||
serde_json::to_string(&HistoryCursor {
|
||||
requested_thread_id,
|
||||
rollout_ordinal,
|
||||
include_anchor,
|
||||
scope,
|
||||
})
|
||||
.map_err(super::thread_history_error)
|
||||
}
|
||||
|
||||
pub(super) fn stored_turn_row(row: sqlx::sqlite::SqliteRow) -> ThreadStoreResult<StoredTurnRow> {
|
||||
let status = match row.try_get::<String, _>("status")?.as_str() {
|
||||
"completed" => StoredTurnStatus::Completed,
|
||||
"interrupted" => StoredTurnStatus::Interrupted,
|
||||
"failed" => StoredTurnStatus::Failed,
|
||||
"inProgress" => StoredTurnStatus::InProgress,
|
||||
status => {
|
||||
return Err(ThreadStoreError::Internal {
|
||||
message: format!("unknown stored turn status: {status}"),
|
||||
});
|
||||
}
|
||||
};
|
||||
let error_json = row.try_get::<Option<String>, _>("error_json")?;
|
||||
let error = error_json
|
||||
.as_deref()
|
||||
.map(serde_json::from_str)
|
||||
.transpose()
|
||||
.map_err(super::thread_history_error)?;
|
||||
Ok(StoredTurnRow {
|
||||
position: RolloutHistoryPosition {
|
||||
rollout_ordinal: row.try_get("rollout_ordinal")?,
|
||||
},
|
||||
turn_id: row.try_get("turn_id")?,
|
||||
root_turn_id: row.try_get("root_turn_id")?,
|
||||
status,
|
||||
error,
|
||||
started_at: row.try_get("started_at")?,
|
||||
completed_at: row.try_get("completed_at")?,
|
||||
duration_ms: row.try_get("duration_ms")?,
|
||||
first_user_item_id: row.try_get("first_user_item_id")?,
|
||||
final_agent_item_id: row.try_get("final_agent_item_id")?,
|
||||
summary_items: Vec::new(),
|
||||
})
|
||||
}
|
||||
|
||||
impl StoredSummaryColumns {
|
||||
pub(super) fn into_stored_items(self) -> ThreadStoreResult<Vec<StoredThreadItem>> {
|
||||
let mut summary_items = [
|
||||
StoredSummaryItemColumns {
|
||||
turn_id: self.summary_first_user_turn_id,
|
||||
item_id: self.summary_first_user_item_id,
|
||||
rollout_ordinal: self.summary_first_user_rollout_ordinal,
|
||||
updated_at_ordinal: self.summary_first_user_updated_at_ordinal,
|
||||
created_at_ms: self.summary_first_user_created_at_ms,
|
||||
started_at_ms: self.summary_first_user_started_at_ms,
|
||||
completed_at_ms: self.summary_first_user_completed_at_ms,
|
||||
item_json: self.summary_first_user_item_json,
|
||||
}
|
||||
.into_stored_item()?,
|
||||
StoredSummaryItemColumns {
|
||||
turn_id: self.summary_final_agent_turn_id,
|
||||
item_id: self.summary_final_agent_item_id,
|
||||
rollout_ordinal: self.summary_final_agent_rollout_ordinal,
|
||||
updated_at_ordinal: self.summary_final_agent_updated_at_ordinal,
|
||||
created_at_ms: self.summary_final_agent_created_at_ms,
|
||||
started_at_ms: self.summary_final_agent_started_at_ms,
|
||||
completed_at_ms: self.summary_final_agent_completed_at_ms,
|
||||
item_json: self.summary_final_agent_item_json,
|
||||
}
|
||||
.into_stored_item()?,
|
||||
]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.collect::<Vec<_>>();
|
||||
summary_items.sort_by_key(|(rollout_ordinal, _)| *rollout_ordinal);
|
||||
Ok(summary_items.into_iter().map(|(_, item)| item).collect())
|
||||
}
|
||||
}
|
||||
|
||||
impl StoredSummaryItemColumns {
|
||||
fn into_stored_item(self) -> ThreadStoreResult<Option<(i64, StoredThreadItem)>> {
|
||||
let Some(item_id) = self.item_id else {
|
||||
return Ok(None);
|
||||
};
|
||||
let (
|
||||
Some(turn_id),
|
||||
Some(rollout_ordinal),
|
||||
Some(updated_at_ordinal),
|
||||
Some(created_at_ms),
|
||||
Some(item_json),
|
||||
) = (
|
||||
self.turn_id,
|
||||
self.rollout_ordinal,
|
||||
self.updated_at_ordinal,
|
||||
self.created_at_ms,
|
||||
self.item_json,
|
||||
)
|
||||
else {
|
||||
return Err(ThreadStoreError::Internal {
|
||||
message: "stored summary item is missing joined columns".to_string(),
|
||||
});
|
||||
};
|
||||
Ok(Some((
|
||||
rollout_ordinal,
|
||||
StoredThreadItem {
|
||||
turn_id,
|
||||
item_id,
|
||||
updated_at_ordinal: stored_updated_at_ordinal(updated_at_ordinal)?,
|
||||
created_at_ms,
|
||||
started_at_ms: self.started_at_ms,
|
||||
completed_at_ms: self.completed_at_ms,
|
||||
item_json: item_json.into_bytes(),
|
||||
},
|
||||
)))
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn stored_thread_item_row(
|
||||
row: sqlx::sqlite::SqliteRow,
|
||||
) -> ThreadStoreResult<StoredThreadItemRow> {
|
||||
let rollout_ordinal = row.try_get::<i64, _>("rollout_ordinal")?;
|
||||
if rollout_ordinal < 0 {
|
||||
return Err(ThreadStoreError::Internal {
|
||||
message: format!("invalid stored item rollout ordinal: {rollout_ordinal}"),
|
||||
});
|
||||
}
|
||||
Ok(StoredThreadItemRow {
|
||||
position: RolloutHistoryPosition { rollout_ordinal },
|
||||
item: stored_thread_item(row)?,
|
||||
})
|
||||
}
|
||||
|
||||
fn stored_thread_item(row: sqlx::sqlite::SqliteRow) -> ThreadStoreResult<StoredThreadItem> {
|
||||
let updated_at_ordinal = stored_updated_at_ordinal(row.try_get("updated_at_ordinal")?)?;
|
||||
Ok(StoredThreadItem {
|
||||
turn_id: row.try_get("turn_id")?,
|
||||
item_id: row.try_get("item_id")?,
|
||||
updated_at_ordinal,
|
||||
created_at_ms: row.try_get("created_at_ms")?,
|
||||
started_at_ms: row.try_get("started_at_ms")?,
|
||||
completed_at_ms: row.try_get("completed_at_ms")?,
|
||||
item_json: row.try_get::<String, _>("item_json")?.into_bytes(),
|
||||
})
|
||||
}
|
||||
|
||||
fn stored_updated_at_ordinal(updated_at_ordinal: i64) -> ThreadStoreResult<u64> {
|
||||
u64::try_from(updated_at_ordinal).map_err(|_| ThreadStoreError::Internal {
|
||||
message: format!("invalid stored item updated-at ordinal: {updated_at_ordinal}"),
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn invalid_cursor(cursor: &str) -> ThreadStoreError {
|
||||
ThreadStoreError::InvalidRequest {
|
||||
message: format!("invalid cursor: {cursor}"),
|
||||
}
|
||||
}
|
||||
1939
codex-rs/thread-store/src/local/thread_history/read_tests.rs
Normal file
1939
codex-rs/thread-store/src/local/thread_history/read_tests.rs
Normal file
File diff suppressed because it is too large
Load Diff
262
codex-rs/thread-store/src/local/thread_history/realtime.rs
Normal file
262
codex-rs/thread-store/src/local/thread_history/realtime.rs
Normal file
@@ -0,0 +1,262 @@
|
||||
use codex_app_server_protocol::ThreadItem;
|
||||
use codex_app_server_protocol::ThreadTimelineEntry;
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::realtime::RealtimeItem;
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
|
||||
use super::super::LocalThreadStore;
|
||||
use super::read::validate_thread_for_paginated_reads;
|
||||
use super::segment_paging::validate_page_size;
|
||||
use super::sqlite_integer;
|
||||
use super::thread_history_error;
|
||||
use crate::ListTimelineParams;
|
||||
use crate::ThreadStoreError;
|
||||
use crate::ThreadStoreResult;
|
||||
use crate::TimelinePage;
|
||||
|
||||
#[derive(Deserialize, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct TimelineCursor {
|
||||
thread_id: ThreadId,
|
||||
position: u64,
|
||||
kind: u8,
|
||||
id: String,
|
||||
}
|
||||
|
||||
// A rollout record can materialize both an item and a turn boundary. Keep the
|
||||
// boundary order stable, including when the page cuts through one ordinal.
|
||||
pub(super) fn entry_key(entry: &ThreadTimelineEntry) -> (u64, u8, &str) {
|
||||
match entry {
|
||||
ThreadTimelineEntry::TurnStarted {
|
||||
position, turn_id, ..
|
||||
} => (*position, 0, turn_id),
|
||||
ThreadTimelineEntry::Item { position, item, .. } => (*position, 1, item.id()),
|
||||
ThreadTimelineEntry::Realtime { position, item } => (*position, 2, &item.id),
|
||||
ThreadTimelineEntry::TurnCompleted {
|
||||
position, turn_id, ..
|
||||
} => (*position, 3, turn_id),
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::local) async fn list_timeline(
|
||||
store: &LocalThreadStore,
|
||||
params: ListTimelineParams,
|
||||
) -> ThreadStoreResult<TimelinePage> {
|
||||
validate_thread_for_paginated_reads(
|
||||
store,
|
||||
params.thread_id,
|
||||
/*include_archived*/ false,
|
||||
"thread/timeline/list",
|
||||
)
|
||||
.await?;
|
||||
validate_page_size(params.page_size)?;
|
||||
|
||||
let lineage = store
|
||||
.resolve_rollout_lineage_for_history_page(params.thread_id)
|
||||
.await?;
|
||||
let pool = store.thread_history_db().await?;
|
||||
let cursor = params
|
||||
.cursor
|
||||
.as_deref()
|
||||
.map(serde_json::from_str::<TimelineCursor>)
|
||||
.transpose()
|
||||
.map_err(|_| ThreadStoreError::InvalidRequest {
|
||||
message: "invalid thread timeline cursor".to_string(),
|
||||
})?
|
||||
.map(|cursor| {
|
||||
if cursor.thread_id != params.thread_id {
|
||||
Err(ThreadStoreError::InvalidRequest {
|
||||
message: "thread timeline cursor belongs to another thread".to_string(),
|
||||
})
|
||||
} else {
|
||||
Ok(cursor)
|
||||
}
|
||||
})
|
||||
.transpose()?;
|
||||
let cursor_position = cursor.as_ref().map(|cursor| cursor.position);
|
||||
let cursor_ordinal = cursor_position
|
||||
.map(|position| sqlite_integer(position, "rollout ordinal"))
|
||||
.transpose()?
|
||||
.unwrap_or(i64::MAX);
|
||||
let cursor_kind = cursor.as_ref().map_or(4, |cursor| cursor.kind);
|
||||
let cursor_id = cursor.as_ref().map_or("", |cursor| cursor.id.as_str());
|
||||
|
||||
let mut rows = Vec::new();
|
||||
let max_rows = params.page_size + 1;
|
||||
for segment in lineage.segments().iter().rev() {
|
||||
let remaining = max_rows.saturating_sub(rows.len());
|
||||
if remaining == 0 {
|
||||
break;
|
||||
}
|
||||
if cursor_position.is_some_and(|position| position < segment.start_ordinal()) {
|
||||
continue;
|
||||
}
|
||||
let upper = segment
|
||||
.end_ordinal()
|
||||
.map(|value| sqlite_integer(value, "rollout ordinal"))
|
||||
.transpose()?
|
||||
.unwrap_or(i64::MAX);
|
||||
let segment_rows = sqlx::query_as::<
|
||||
_,
|
||||
(
|
||||
i64,
|
||||
i64,
|
||||
String,
|
||||
Option<String>,
|
||||
String,
|
||||
Option<i64>,
|
||||
Option<i64>,
|
||||
),
|
||||
>(
|
||||
r#"
|
||||
WITH starts AS (
|
||||
SELECT rollout_ordinal, 0 AS kind, turn_id AS id, turn_id,
|
||||
json_object('type', 'turnStarted', 'position', rollout_ordinal,
|
||||
'turnId', turn_id, 'startedAt', started_at) AS item_json
|
||||
FROM thread_turns
|
||||
WHERE thread_id = ?1 AND rollout_ordinal >= ?2
|
||||
AND rollout_ordinal < ?3 AND rollout_ordinal <= ?4
|
||||
AND (rollout_ordinal, 0, turn_id) < (?4, ?5, ?6)
|
||||
ORDER BY rollout_ordinal DESC, turn_id DESC LIMIT ?7
|
||||
), items AS (
|
||||
SELECT rollout_ordinal, 1 AS kind, item_id AS id, turn_id, item_json, started_at_ms, completed_at_ms
|
||||
FROM thread_items
|
||||
WHERE thread_id = ?1 AND rollout_ordinal >= ?2
|
||||
AND rollout_ordinal < ?3 AND rollout_ordinal <= ?4
|
||||
AND (rollout_ordinal, 1, item_id) < (?4, ?5, ?6)
|
||||
ORDER BY rollout_ordinal DESC, item_id DESC LIMIT ?7
|
||||
), realtime AS (
|
||||
SELECT rollout_ordinal, 2 AS kind, item_id AS id, NULL AS turn_id, item_json
|
||||
FROM thread_realtime_items
|
||||
WHERE thread_id = ?1 AND rollout_ordinal >= ?2
|
||||
AND rollout_ordinal < ?3 AND rollout_ordinal <= ?4
|
||||
AND (rollout_ordinal, 2, item_id) < (?4, ?5, ?6)
|
||||
ORDER BY rollout_ordinal DESC, item_id DESC LIMIT ?7
|
||||
), ends AS (
|
||||
SELECT rollout_end_ordinal AS rollout_ordinal, 3 AS kind, turn_id AS id, turn_id,
|
||||
json_object('type', 'turnCompleted', 'position', rollout_end_ordinal,
|
||||
'turnId', turn_id, 'status', status, 'error', json(error_json),
|
||||
'startedAt', started_at, 'completedAt', completed_at,
|
||||
'durationMs', duration_ms) AS item_json
|
||||
FROM thread_turns
|
||||
WHERE thread_id = ?1 AND rollout_end_ordinal >= ?2
|
||||
AND rollout_end_ordinal < ?3 AND rollout_end_ordinal <= ?4
|
||||
AND (rollout_end_ordinal, 3, turn_id) < (?4, ?5, ?6)
|
||||
ORDER BY rollout_end_ordinal DESC, turn_id DESC LIMIT ?7
|
||||
)
|
||||
SELECT *, NULL, NULL FROM starts
|
||||
UNION ALL SELECT * FROM items
|
||||
UNION ALL SELECT *, NULL, NULL FROM realtime
|
||||
UNION ALL SELECT *, NULL, NULL FROM ends
|
||||
ORDER BY rollout_ordinal DESC, kind DESC, id DESC
|
||||
LIMIT ?7
|
||||
"#,
|
||||
)
|
||||
.bind(segment.rollout_id().to_string())
|
||||
.bind(sqlite_integer(segment.start_ordinal(), "rollout ordinal")?)
|
||||
.bind(upper)
|
||||
.bind(cursor_ordinal)
|
||||
.bind(i64::from(cursor_kind))
|
||||
.bind(cursor_id)
|
||||
.bind(i64::try_from(remaining).map_err(thread_history_error)?)
|
||||
.fetch_all(pool)
|
||||
.await
|
||||
.map_err(thread_history_error)?;
|
||||
|
||||
for (position, kind, _id, turn_id, item_json, started_at_ms, completed_at_ms) in
|
||||
segment_rows
|
||||
{
|
||||
let position = u64::try_from(position).map_err(thread_history_error)?;
|
||||
rows.push(match kind {
|
||||
0 | 3 => serde_json::from_str::<ThreadTimelineEntry>(&item_json)
|
||||
.map_err(thread_history_error)?,
|
||||
1 => ThreadTimelineEntry::Item {
|
||||
position,
|
||||
turn_id: turn_id.ok_or_else(|| thread_history_error("missing turn ID"))?,
|
||||
item: Box::new(ThreadItem {
|
||||
payload: serde_json::from_str(&item_json).map_err(thread_history_error)?,
|
||||
started_at_ms,
|
||||
completed_at_ms,
|
||||
}),
|
||||
},
|
||||
2 => ThreadTimelineEntry::Realtime {
|
||||
position,
|
||||
item: serde_json::from_str::<RealtimeItem>(&item_json)
|
||||
.map_err(thread_history_error)?
|
||||
.into(),
|
||||
},
|
||||
_ => return Err(thread_history_error("invalid timeline entry kind")),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
let has_more = rows.len() > params.page_size;
|
||||
rows.truncate(params.page_size);
|
||||
let next_cursor = if has_more {
|
||||
rows.last()
|
||||
.map(|entry| {
|
||||
let (position, kind, id) = entry_key(entry);
|
||||
serde_json::to_string(&TimelineCursor {
|
||||
thread_id: params.thread_id,
|
||||
position,
|
||||
kind,
|
||||
id: id.to_string(),
|
||||
})
|
||||
.map_err(thread_history_error)
|
||||
})
|
||||
.transpose()?
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let (page_start, page_start_kind, page_start_id) =
|
||||
rows.last().map(entry_key).unwrap_or_default();
|
||||
let mut active_realtime_session_at_page_start = None;
|
||||
for segment in lineage.segments().iter().rev() {
|
||||
let upper = page_start.min(
|
||||
segment
|
||||
.end_ordinal()
|
||||
.map(|ordinal| ordinal.saturating_sub(1))
|
||||
.unwrap_or(u64::MAX),
|
||||
);
|
||||
if upper < segment.start_ordinal() {
|
||||
continue;
|
||||
}
|
||||
let boundary = sqlx::query_as::<_, (String, String)>(
|
||||
r#"
|
||||
SELECT item_type, json_extract(item_json, '$.realtime_session_id')
|
||||
FROM thread_realtime_items
|
||||
WHERE thread_id = ?
|
||||
AND rollout_ordinal >= ?
|
||||
AND rollout_ordinal <= ?
|
||||
AND (rollout_ordinal, 2, item_id) < (?, ?, ?)
|
||||
AND item_type IN ('realtime_session_started', 'realtime_session_closed')
|
||||
ORDER BY rollout_ordinal DESC
|
||||
LIMIT 1
|
||||
"#,
|
||||
)
|
||||
.bind(segment.rollout_id().to_string())
|
||||
.bind(sqlite_integer(segment.start_ordinal(), "rollout ordinal")?)
|
||||
.bind(sqlite_integer(upper, "rollout ordinal")?)
|
||||
.bind(sqlite_integer(page_start, "rollout ordinal")?)
|
||||
.bind(i64::from(page_start_kind))
|
||||
.bind(page_start_id)
|
||||
.fetch_optional(pool)
|
||||
.await
|
||||
.map_err(thread_history_error)?;
|
||||
if let Some((item_type, session_id)) = boundary {
|
||||
if item_type == "realtime_session_started" {
|
||||
active_realtime_session_at_page_start = Some(session_id);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
rows.reverse();
|
||||
Ok(TimelinePage {
|
||||
items: rows,
|
||||
next_cursor,
|
||||
active_realtime_session_at_page_start,
|
||||
})
|
||||
}
|
||||
501
codex-rs/thread-store/src/local/thread_history/search.rs
Normal file
501
codex-rs/thread-store/src/local/thread_history/search.rs
Normal file
@@ -0,0 +1,501 @@
|
||||
use std::borrow::Cow;
|
||||
use std::collections::HashMap;
|
||||
|
||||
use codex_app_server_protocol::ThreadItemPayload;
|
||||
use codex_app_server_protocol::UserInput;
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::protocol::strip_user_message_prefix;
|
||||
use futures::TryStreamExt;
|
||||
use pulldown_cmark::Event;
|
||||
use pulldown_cmark::Parser;
|
||||
use pulldown_cmark::TagEnd;
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
use sqlx::Row;
|
||||
|
||||
use super::super::LocalThreadStore;
|
||||
use super::read::CursorScope;
|
||||
use super::read::serialize_cursor;
|
||||
use super::read::validate_thread_for_paginated_reads;
|
||||
use super::sqlite_integer;
|
||||
use super::thread_history_error;
|
||||
use super::turn_lookup::find_visible_turn;
|
||||
use crate::SearchTextRange;
|
||||
use crate::SearchThreadOccurrencesParams;
|
||||
use crate::StoredThreadOccurrence;
|
||||
use crate::ThreadOccurrenceSearchPage;
|
||||
use crate::ThreadStoreError;
|
||||
use crate::ThreadStoreResult;
|
||||
|
||||
const SNIPPET_CONTEXT_BEFORE_CHARS: usize = 48;
|
||||
const SNIPPET_CONTEXT_AFTER_CHARS: usize = 96;
|
||||
|
||||
#[derive(Deserialize, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct SearchCursor {
|
||||
thread_id: ThreadId,
|
||||
search_term: String,
|
||||
next_rollout_ordinal: i64,
|
||||
next_occurrence_index: usize,
|
||||
}
|
||||
|
||||
struct CandidateRow {
|
||||
turn_id: String,
|
||||
item_id: String,
|
||||
rollout_ordinal: i64,
|
||||
item_json: String,
|
||||
turn_rollout_ordinal: i64,
|
||||
}
|
||||
|
||||
pub(in crate::local) async fn search_thread_occurrences(
|
||||
store: &LocalThreadStore,
|
||||
params: SearchThreadOccurrencesParams,
|
||||
) -> ThreadStoreResult<ThreadOccurrenceSearchPage> {
|
||||
if params.search_term.trim().is_empty() {
|
||||
return Err(ThreadStoreError::InvalidRequest {
|
||||
message: "thread/searchOccurrences requires search_term".to_string(),
|
||||
});
|
||||
}
|
||||
if params.page_size == 0 {
|
||||
return Err(ThreadStoreError::InvalidRequest {
|
||||
message: "thread/searchOccurrences requires page_size greater than zero".to_string(),
|
||||
});
|
||||
}
|
||||
validate_thread_for_paginated_reads(
|
||||
store,
|
||||
params.thread_id,
|
||||
/*include_archived*/ true,
|
||||
"thread/searchOccurrences",
|
||||
)
|
||||
.await?;
|
||||
let cursor = parse_cursor(
|
||||
params.cursor.as_deref(),
|
||||
params.thread_id,
|
||||
¶ms.search_term,
|
||||
)?;
|
||||
let matcher = LiteralMatcher::new(params.search_term.as_str());
|
||||
let lineage = store
|
||||
.resolve_rollout_lineage_for_history_page(params.thread_id)
|
||||
.await?;
|
||||
let cursor_segment = cursor
|
||||
.as_ref()
|
||||
.map(|cursor| {
|
||||
lineage
|
||||
.segment_index_for_ordinal(
|
||||
u64::try_from(cursor.next_rollout_ordinal)
|
||||
.map_err(|_| invalid_cursor("negative rollout ordinal"))?,
|
||||
)
|
||||
.ok_or_else(|| invalid_cursor("position outside thread lineage"))
|
||||
})
|
||||
.transpose()?;
|
||||
let pool = store.thread_history_db().await?;
|
||||
let mut items = Vec::with_capacity(params.page_size);
|
||||
let mut effective_turn_ordinals = HashMap::new();
|
||||
for (segment_index, segment) in lineage
|
||||
.segments()
|
||||
.iter()
|
||||
.enumerate()
|
||||
.skip(cursor_segment.unwrap_or(0))
|
||||
{
|
||||
let segment_start_ordinal = sqlite_integer(segment.start_ordinal(), "rollout ordinal")?;
|
||||
let next_rollout_ordinal = if Some(segment_index) == cursor_segment {
|
||||
cursor
|
||||
.as_ref()
|
||||
.map_or(0, |cursor| cursor.next_rollout_ordinal)
|
||||
} else {
|
||||
segment_start_ordinal
|
||||
};
|
||||
let end_rollout_ordinal = segment
|
||||
.end_ordinal()
|
||||
.map(|ordinal| sqlite_integer(ordinal, "rollout ordinal"))
|
||||
.transpose()?
|
||||
.unwrap_or(i64::MAX);
|
||||
let mut rows = sqlx::query(
|
||||
r#"
|
||||
SELECT turn_id, item_id, rollout_ordinal, item_json, turn_rollout_ordinal
|
||||
FROM (
|
||||
SELECT
|
||||
items.turn_id,
|
||||
items.item_id,
|
||||
items.rollout_ordinal,
|
||||
items.item_json,
|
||||
turns.rollout_ordinal AS turn_rollout_ordinal
|
||||
FROM thread_items AS items
|
||||
JOIN thread_turns AS turns
|
||||
ON turns.thread_id = items.thread_id
|
||||
AND turns.turn_id = items.turn_id
|
||||
WHERE items.thread_id = ?
|
||||
AND (
|
||||
items.item_type = 'userMessage'
|
||||
OR (
|
||||
items.item_type = 'agentMessage'
|
||||
AND json_extract(items.item_json, '$.phase') = 'partial_answer'
|
||||
)
|
||||
)
|
||||
AND items.rollout_ordinal >= ?
|
||||
AND items.rollout_ordinal < ?
|
||||
AND turns.rollout_ordinal >= ?
|
||||
AND turns.rollout_ordinal < ?
|
||||
|
||||
UNION ALL
|
||||
|
||||
SELECT
|
||||
items.turn_id,
|
||||
items.item_id,
|
||||
items.rollout_ordinal,
|
||||
items.item_json,
|
||||
turns.rollout_ordinal AS turn_rollout_ordinal
|
||||
FROM thread_turns AS turns
|
||||
JOIN thread_items AS items
|
||||
ON items.thread_id = turns.thread_id
|
||||
AND items.turn_id = turns.turn_id
|
||||
AND items.item_id = turns.final_agent_item_id
|
||||
WHERE turns.thread_id = ?
|
||||
AND turns.final_agent_item_id IS NOT NULL
|
||||
AND items.rollout_ordinal >= ?
|
||||
AND items.rollout_ordinal < ?
|
||||
AND turns.rollout_ordinal >= ?
|
||||
AND turns.rollout_ordinal < ?
|
||||
)
|
||||
ORDER BY rollout_ordinal ASC
|
||||
"#,
|
||||
)
|
||||
.bind(segment.rollout_id().to_string())
|
||||
.bind(next_rollout_ordinal)
|
||||
.bind(end_rollout_ordinal)
|
||||
.bind(segment_start_ordinal)
|
||||
.bind(end_rollout_ordinal)
|
||||
.bind(segment.rollout_id().to_string())
|
||||
.bind(next_rollout_ordinal)
|
||||
.bind(end_rollout_ordinal)
|
||||
.bind(segment_start_ordinal)
|
||||
.bind(end_rollout_ordinal)
|
||||
.fetch(pool);
|
||||
|
||||
let mut matching_rows = Vec::new();
|
||||
let mut matching_occurrences = 0_usize;
|
||||
while let Some(row) = rows.try_next().await.map_err(thread_history_error)? {
|
||||
let row = candidate_row(row)?;
|
||||
let item = serde_json::from_str::<ThreadItemPayload>(row.item_json.as_str()).map_err(
|
||||
|err| ThreadStoreError::Internal {
|
||||
message: format!("failed to deserialize stored thread item: {err}"),
|
||||
},
|
||||
)?;
|
||||
let Some(text) = searchable_text(&item) else {
|
||||
continue;
|
||||
};
|
||||
let first_occurrence_index = cursor
|
||||
.as_ref()
|
||||
.filter(|cursor| cursor.next_rollout_ordinal == row.rollout_ordinal)
|
||||
.map_or(0, |cursor| cursor.next_occurrence_index);
|
||||
let remaining = params
|
||||
.page_size
|
||||
.saturating_add(1)
|
||||
.saturating_sub(items.len())
|
||||
.saturating_sub(matching_occurrences);
|
||||
let matches = matcher.find_ranges(
|
||||
text.as_ref(),
|
||||
first_occurrence_index.saturating_add(remaining),
|
||||
);
|
||||
if matches.len() <= first_occurrence_index {
|
||||
continue;
|
||||
}
|
||||
matching_occurrences += matches.len() - first_occurrence_index;
|
||||
matching_rows.push((row, text.into_owned(), matches, first_occurrence_index));
|
||||
if matching_occurrences
|
||||
== params
|
||||
.page_size
|
||||
.saturating_add(1)
|
||||
.saturating_sub(items.len())
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
drop(rows);
|
||||
|
||||
for (row, text, matches, first_occurrence_index) in matching_rows {
|
||||
let turn_rollout_ordinal = if segment_index + 1 == lineage.segments().len() {
|
||||
row.turn_rollout_ordinal
|
||||
} else if let Some(ordinal) = effective_turn_ordinals.get(&row.turn_id) {
|
||||
*ordinal
|
||||
} else {
|
||||
let ordinal = find_visible_turn(pool, &lineage, row.turn_id.as_str())
|
||||
.await?
|
||||
.rollout_ordinal;
|
||||
effective_turn_ordinals.insert(row.turn_id.clone(), ordinal);
|
||||
ordinal
|
||||
};
|
||||
let turn_cursor = serialize_cursor(
|
||||
params.thread_id,
|
||||
CursorScope::Turns,
|
||||
turn_rollout_ordinal,
|
||||
/*include_anchor*/ true,
|
||||
)?;
|
||||
for (occurrence_index, matched) in
|
||||
matches.into_iter().enumerate().skip(first_occurrence_index)
|
||||
{
|
||||
if items.len() == params.page_size {
|
||||
return Ok(ThreadOccurrenceSearchPage {
|
||||
items,
|
||||
next_cursor: Some(serialize_cursor_for_search(SearchCursor {
|
||||
thread_id: params.thread_id,
|
||||
search_term: params.search_term,
|
||||
next_rollout_ordinal: row.rollout_ordinal,
|
||||
next_occurrence_index: occurrence_index,
|
||||
})?),
|
||||
});
|
||||
}
|
||||
items.push(occurrence_in_item(
|
||||
row.turn_id.as_str(),
|
||||
row.item_id.as_str(),
|
||||
text.as_str(),
|
||||
matched,
|
||||
turn_cursor.as_str(),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(ThreadOccurrenceSearchPage {
|
||||
items,
|
||||
next_cursor: None,
|
||||
})
|
||||
}
|
||||
|
||||
fn candidate_row(row: sqlx::sqlite::SqliteRow) -> ThreadStoreResult<CandidateRow> {
|
||||
let rollout_ordinal = row.try_get::<i64, _>("rollout_ordinal")?;
|
||||
let turn_rollout_ordinal = row.try_get::<i64, _>("turn_rollout_ordinal")?;
|
||||
if rollout_ordinal < 0 || turn_rollout_ordinal < 0 {
|
||||
return Err(ThreadStoreError::Internal {
|
||||
message: "invalid stored thread history ordinal".to_string(),
|
||||
});
|
||||
}
|
||||
Ok(CandidateRow {
|
||||
turn_id: row.try_get("turn_id")?,
|
||||
item_id: row.try_get("item_id")?,
|
||||
rollout_ordinal,
|
||||
item_json: row.try_get("item_json")?,
|
||||
turn_rollout_ordinal,
|
||||
})
|
||||
}
|
||||
|
||||
fn parse_cursor(
|
||||
cursor: Option<&str>,
|
||||
thread_id: ThreadId,
|
||||
search_term: &str,
|
||||
) -> ThreadStoreResult<Option<SearchCursor>> {
|
||||
let Some(cursor) = cursor else {
|
||||
return Ok(None);
|
||||
};
|
||||
let cursor_value: SearchCursor =
|
||||
serde_json::from_str(cursor).map_err(|_| invalid_cursor(cursor))?;
|
||||
if cursor_value.thread_id != thread_id
|
||||
|| cursor_value.search_term != search_term
|
||||
|| cursor_value.next_rollout_ordinal < 0
|
||||
{
|
||||
return Err(invalid_cursor(cursor));
|
||||
}
|
||||
Ok(Some(cursor_value))
|
||||
}
|
||||
|
||||
fn serialize_cursor_for_search(cursor: SearchCursor) -> ThreadStoreResult<String> {
|
||||
serde_json::to_string(&cursor).map_err(thread_history_error)
|
||||
}
|
||||
|
||||
fn invalid_cursor(cursor: &str) -> ThreadStoreError {
|
||||
ThreadStoreError::InvalidRequest {
|
||||
message: format!("invalid cursor: {cursor}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn searchable_text(item: &ThreadItemPayload) -> Option<Cow<'_, str>> {
|
||||
match item {
|
||||
ThreadItemPayload::UserMessage { content, .. } => {
|
||||
let mut text_parts = content
|
||||
.iter()
|
||||
.filter_map(|input| match input {
|
||||
UserInput::Text { text, .. } => Some(strip_user_message_prefix(text)),
|
||||
UserInput::Image { .. }
|
||||
| UserInput::LocalImage { .. }
|
||||
| UserInput::Audio { .. }
|
||||
| UserInput::LocalAudio { .. }
|
||||
| UserInput::Skill { .. }
|
||||
| UserInput::Mention { .. } => None,
|
||||
})
|
||||
.filter(|text| !text.is_empty())
|
||||
.peekable();
|
||||
let first = text_parts.next()?;
|
||||
match text_parts.next() {
|
||||
None => Some(Cow::Borrowed(first)),
|
||||
Some(second) => {
|
||||
let mut parts = vec![first, second];
|
||||
parts.extend(text_parts);
|
||||
Some(Cow::Owned(parts.concat()))
|
||||
}
|
||||
}
|
||||
}
|
||||
ThreadItemPayload::AgentMessage { text, .. } => {
|
||||
let text = markdown_to_search_text(text);
|
||||
(!text.is_empty()).then_some(Cow::Owned(text))
|
||||
}
|
||||
ThreadItemPayload::HookPrompt { .. }
|
||||
| ThreadItemPayload::FunctionCallOutput { .. }
|
||||
| ThreadItemPayload::Plan { .. }
|
||||
| ThreadItemPayload::Reasoning { .. }
|
||||
| ThreadItemPayload::CommandExecution { .. }
|
||||
| ThreadItemPayload::FileChange { .. }
|
||||
| ThreadItemPayload::McpToolCall { .. }
|
||||
| ThreadItemPayload::DynamicToolCall { .. }
|
||||
| ThreadItemPayload::CollabAgentToolCall { .. }
|
||||
| ThreadItemPayload::SubAgentActivity { .. }
|
||||
| ThreadItemPayload::WebSearch(_)
|
||||
| ThreadItemPayload::ImageView { .. }
|
||||
| ThreadItemPayload::Sleep(_)
|
||||
| ThreadItemPayload::ImageGeneration(_)
|
||||
| ThreadItemPayload::EnteredReviewMode { .. }
|
||||
| ThreadItemPayload::ExitedReviewMode { .. }
|
||||
| ThreadItemPayload::ContextCompaction { .. } => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn markdown_to_search_text(markdown: &str) -> String {
|
||||
let mut text = String::new();
|
||||
for event in Parser::new(markdown.trim()) {
|
||||
match event {
|
||||
Event::Text(value)
|
||||
| Event::Code(value)
|
||||
| Event::Html(value)
|
||||
| Event::InlineHtml(value) => text.push_str(&value),
|
||||
Event::SoftBreak | Event::HardBreak | Event::Rule => text.push(' '),
|
||||
Event::End(
|
||||
TagEnd::Paragraph
|
||||
| TagEnd::Heading(_)
|
||||
| TagEnd::BlockQuote
|
||||
| TagEnd::CodeBlock
|
||||
| TagEnd::List(_)
|
||||
| TagEnd::Item
|
||||
| TagEnd::Table
|
||||
| TagEnd::TableHead
|
||||
| TagEnd::TableRow
|
||||
| TagEnd::TableCell,
|
||||
) => text.push(' '),
|
||||
Event::Start(_)
|
||||
| Event::End(
|
||||
TagEnd::Emphasis
|
||||
| TagEnd::Strong
|
||||
| TagEnd::Strikethrough
|
||||
| TagEnd::Link
|
||||
| TagEnd::HtmlBlock
|
||||
| TagEnd::FootnoteDefinition
|
||||
| TagEnd::Image
|
||||
| TagEnd::MetadataBlock(_),
|
||||
)
|
||||
| Event::FootnoteReference(_)
|
||||
| Event::TaskListMarker(_) => {}
|
||||
}
|
||||
}
|
||||
text.split_whitespace().collect::<Vec<_>>().join(" ")
|
||||
}
|
||||
|
||||
struct LiteralMatcher {
|
||||
lowercase_needle: String,
|
||||
}
|
||||
|
||||
impl LiteralMatcher {
|
||||
fn new(needle: &str) -> Self {
|
||||
Self {
|
||||
lowercase_needle: needle.to_lowercase(),
|
||||
}
|
||||
}
|
||||
|
||||
fn find_ranges(&self, text: &str, limit: usize) -> Vec<std::ops::Range<usize>> {
|
||||
let lowercase_text = text.to_lowercase();
|
||||
let mut spans = Vec::with_capacity(text.chars().count());
|
||||
let mut lowercase_start = 0;
|
||||
for (original_start, character) in text.char_indices() {
|
||||
let lowercase_end =
|
||||
lowercase_start + character.to_lowercase().map(char::len_utf8).sum::<usize>();
|
||||
spans.push((
|
||||
lowercase_start..lowercase_end,
|
||||
original_start..original_start + character.len_utf8(),
|
||||
));
|
||||
lowercase_start = lowercase_end;
|
||||
}
|
||||
|
||||
// Use two-pointer method to find matches in linear time.
|
||||
let mut start_span = 0;
|
||||
let mut end_span = 0;
|
||||
lowercase_text
|
||||
.match_indices(self.lowercase_needle.as_str())
|
||||
.take(limit)
|
||||
.filter_map(|(start, matched)| {
|
||||
let end = start.saturating_add(matched.len());
|
||||
while spans.get(start_span)?.0.end <= start {
|
||||
start_span += 1;
|
||||
}
|
||||
while spans.get(end_span)?.0.end <= end.saturating_sub(1) {
|
||||
end_span += 1;
|
||||
}
|
||||
let original_start = spans.get(start_span)?.1.start;
|
||||
let original_end = spans.get(end_span)?.1.end;
|
||||
Some(original_start..original_end)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
fn occurrence_in_item(
|
||||
turn_id: &str,
|
||||
item_id: &str,
|
||||
text: &str,
|
||||
matched: std::ops::Range<usize>,
|
||||
turn_cursor: &str,
|
||||
) -> StoredThreadOccurrence {
|
||||
let snippet_start = char_start_before(text, matched.start, SNIPPET_CONTEXT_BEFORE_CHARS);
|
||||
let snippet_end = char_end_after(text, matched.end, SNIPPET_CONTEXT_AFTER_CHARS);
|
||||
let leading_ellipsis = snippet_start > 0;
|
||||
let trailing_ellipsis = snippet_end < text.len();
|
||||
let mut snippet = String::new();
|
||||
if leading_ellipsis {
|
||||
snippet.push_str("... ");
|
||||
}
|
||||
snippet.push_str(&text[snippet_start..snippet_end]);
|
||||
if trailing_ellipsis {
|
||||
snippet.push_str(" ...");
|
||||
}
|
||||
let snippet_match_start =
|
||||
if leading_ellipsis { 4 } else { 0 } + utf16_len(&text[snippet_start..matched.start]);
|
||||
let match_len = utf16_len(&text[matched]);
|
||||
|
||||
StoredThreadOccurrence {
|
||||
turn_id: turn_id.to_string(),
|
||||
item_id: item_id.to_string(),
|
||||
snippet,
|
||||
snippet_match_range: SearchTextRange {
|
||||
start: snippet_match_start,
|
||||
end: snippet_match_start.saturating_add(match_len),
|
||||
},
|
||||
turn_cursor: turn_cursor.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn utf16_len(text: &str) -> u32 {
|
||||
u32::try_from(text.encode_utf16().count()).unwrap_or(u32::MAX)
|
||||
}
|
||||
|
||||
fn char_start_before(text: &str, byte_index: usize, chars_before: usize) -> usize {
|
||||
text[..byte_index]
|
||||
.char_indices()
|
||||
.rev()
|
||||
.nth(chars_before)
|
||||
.map(|(index, _)| index)
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
fn char_end_after(text: &str, byte_index: usize, chars_after: usize) -> usize {
|
||||
text[byte_index..]
|
||||
.char_indices()
|
||||
.nth(chars_after)
|
||||
.map(|(offset, _)| byte_index.saturating_add(offset))
|
||||
.unwrap_or(text.len())
|
||||
}
|
||||
615
codex-rs/thread-store/src/local/thread_history/segment_paging.rs
Normal file
615
codex-rs/thread-store/src/local/thread_history/segment_paging.rs
Normal file
@@ -0,0 +1,615 @@
|
||||
use codex_protocol::ThreadId;
|
||||
use sqlx::FromRow;
|
||||
use sqlx::QueryBuilder;
|
||||
use sqlx::Sqlite;
|
||||
|
||||
use super::super::rollout_lineage::RolloutLineage;
|
||||
use super::super::rollout_lineage::RolloutLineageSegment;
|
||||
use super::read::CursorScope;
|
||||
use super::read::HistoryCursor;
|
||||
use super::read::RolloutHistoryPosition;
|
||||
use super::read::StoredSummaryColumns;
|
||||
use super::read::StoredThreadItemRow;
|
||||
use super::read::StoredTurnRow;
|
||||
use super::read::invalid_cursor;
|
||||
use super::read::parse_cursor;
|
||||
use super::read::serialize_cursor;
|
||||
use super::read::stored_thread_item_row;
|
||||
use super::read::stored_turn_row;
|
||||
use super::thread_history_error;
|
||||
use crate::ItemSortKey;
|
||||
use crate::ListItemsParams;
|
||||
use crate::ListItemsPosition;
|
||||
use crate::SortDirection;
|
||||
use crate::StoredTurnItemsView;
|
||||
use crate::ThreadStoreError;
|
||||
use crate::ThreadStoreResult;
|
||||
|
||||
pub(super) struct SegmentPage<T> {
|
||||
pub rows: Vec<T>,
|
||||
pub next_cursor: Option<String>,
|
||||
pub backwards_cursor: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum UpdateOrdinalBoundary {
|
||||
After(u64),
|
||||
Before(u64),
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum HistoryOrdinalColumn {
|
||||
Rollout,
|
||||
UpdatedAt,
|
||||
}
|
||||
|
||||
impl HistoryOrdinalColumn {
|
||||
fn push(self, query: &mut QueryBuilder<Sqlite>) {
|
||||
query.push(match self {
|
||||
Self::Rollout => "rollout_ordinal",
|
||||
Self::UpdatedAt => "updated_at_ordinal",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn push_update_ordinal_boundary(
|
||||
query: &mut QueryBuilder<Sqlite>,
|
||||
boundary: UpdateOrdinalBoundary,
|
||||
) -> ThreadStoreResult<()> {
|
||||
match boundary {
|
||||
UpdateOrdinalBoundary::After(ordinal) => {
|
||||
query
|
||||
.push(" AND updated_at_ordinal > ")
|
||||
.push_bind(sqlite_integer(ordinal)?);
|
||||
}
|
||||
UpdateOrdinalBoundary::Before(ordinal) => {
|
||||
query
|
||||
.push(" AND updated_at_ordinal < ")
|
||||
.push_bind(sqlite_integer(ordinal)?);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn validate_page_size(page_size: usize) -> ThreadStoreResult<()> {
|
||||
if page_size == 0 {
|
||||
return Err(ThreadStoreError::InvalidRequest {
|
||||
message: "page size must be positive".to_string(),
|
||||
});
|
||||
}
|
||||
let limit = page_size.checked_add(1).ok_or_else(page_size_too_large)?;
|
||||
i64::try_from(limit).map_err(|_| page_size_too_large())?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) async fn page_turn_rows(
|
||||
pool: &sqlx::SqlitePool,
|
||||
requested_thread_id: ThreadId,
|
||||
lineage: &RolloutLineage,
|
||||
cursor: Option<&str>,
|
||||
page_size: usize,
|
||||
direction: SortDirection,
|
||||
items_view: StoredTurnItemsView,
|
||||
) -> ThreadStoreResult<SegmentPage<StoredTurnRow>> {
|
||||
let cursor = parse_cursor(cursor, requested_thread_id, CursorScope::Turns)?;
|
||||
let ordinal_column = HistoryOrdinalColumn::Rollout;
|
||||
let mut rows = Vec::new();
|
||||
for (segment_index, segment, segment_cursor) in
|
||||
segments_from_cursor(lineage, direction, cursor.as_ref())?
|
||||
{
|
||||
let remaining = remaining_limit(page_size, rows.len())?;
|
||||
if remaining == 0 {
|
||||
break;
|
||||
}
|
||||
let mut query = QueryBuilder::<Sqlite>::new("");
|
||||
if matches!(items_view, StoredTurnItemsView::Summary) {
|
||||
query.push("WITH page_turns AS (");
|
||||
}
|
||||
query.push(
|
||||
r#"SELECT
|
||||
turn_id,
|
||||
root_turn_id,
|
||||
rollout_ordinal,
|
||||
status,
|
||||
error_json,
|
||||
started_at,
|
||||
completed_at,
|
||||
duration_ms,
|
||||
first_user_item_id,
|
||||
final_agent_item_id
|
||||
FROM thread_turns
|
||||
WHERE thread_id =
|
||||
"#,
|
||||
);
|
||||
query.push_bind(segment.rollout_id().to_string());
|
||||
push_segment_range(&mut query, segment, ordinal_column)?;
|
||||
for newer_segment in &lineage.segments()[segment_index + 1..] {
|
||||
query
|
||||
.push(" AND NOT EXISTS (SELECT 1 FROM thread_turns AS newer_turn WHERE newer_turn.thread_id = ")
|
||||
.push_bind(newer_segment.rollout_id().to_string())
|
||||
.push(" AND newer_turn.turn_id = thread_turns.turn_id AND newer_turn.rollout_ordinal >= ")
|
||||
.push_bind(sqlite_integer(newer_segment.start_ordinal())?);
|
||||
if let Some(end_ordinal) = newer_segment.end_ordinal() {
|
||||
query
|
||||
.push(" AND newer_turn.rollout_ordinal < ")
|
||||
.push_bind(sqlite_integer(end_ordinal)?);
|
||||
}
|
||||
query.push(")");
|
||||
}
|
||||
push_cursor_clause(&mut query, direction, segment_cursor, ordinal_column)?;
|
||||
push_order_and_limit(&mut query, direction, remaining, ordinal_column);
|
||||
if matches!(items_view, StoredTurnItemsView::Summary) {
|
||||
query.push(
|
||||
r#"
|
||||
)
|
||||
SELECT
|
||||
page_turns.*,
|
||||
first_user.turn_id AS summary_first_user_turn_id,
|
||||
first_user.item_id AS summary_first_user_item_id,
|
||||
first_user.rollout_ordinal AS summary_first_user_rollout_ordinal,
|
||||
first_user.updated_at_ordinal AS summary_first_user_updated_at_ordinal,
|
||||
first_user.created_at_ms AS summary_first_user_created_at_ms,
|
||||
first_user.started_at_ms AS summary_first_user_started_at_ms,
|
||||
first_user.completed_at_ms AS summary_first_user_completed_at_ms,
|
||||
first_user.item_json AS summary_first_user_item_json,
|
||||
final_agent.turn_id AS summary_final_agent_turn_id,
|
||||
final_agent.item_id AS summary_final_agent_item_id,
|
||||
final_agent.rollout_ordinal AS summary_final_agent_rollout_ordinal,
|
||||
final_agent.updated_at_ordinal AS summary_final_agent_updated_at_ordinal,
|
||||
final_agent.created_at_ms AS summary_final_agent_created_at_ms,
|
||||
final_agent.started_at_ms AS summary_final_agent_started_at_ms,
|
||||
final_agent.completed_at_ms AS summary_final_agent_completed_at_ms,
|
||||
final_agent.item_json AS summary_final_agent_item_json
|
||||
FROM page_turns
|
||||
LEFT JOIN thread_items AS first_user
|
||||
ON first_user.thread_id =
|
||||
"#,
|
||||
);
|
||||
push_summary_item_join(&mut query, segment, "first_user", "first_user_item_id")?;
|
||||
query.push(
|
||||
r#"
|
||||
LEFT JOIN thread_items AS final_agent
|
||||
ON final_agent.thread_id =
|
||||
"#,
|
||||
);
|
||||
push_summary_item_join(&mut query, segment, "final_agent", "final_agent_item_id")?;
|
||||
let order = match direction {
|
||||
SortDirection::Asc => "ASC",
|
||||
SortDirection::Desc => "DESC",
|
||||
};
|
||||
query
|
||||
.push(" ORDER BY page_turns.rollout_ordinal ")
|
||||
.push(order);
|
||||
}
|
||||
rows.extend(
|
||||
query
|
||||
.build()
|
||||
.fetch_all(pool)
|
||||
.await
|
||||
.map_err(thread_history_error)?
|
||||
.into_iter()
|
||||
.map(|row| {
|
||||
let summary_items = if matches!(items_view, StoredTurnItemsView::Summary) {
|
||||
StoredSummaryColumns::from_row(&row)?.into_stored_items()?
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
let mut turn = stored_turn_row(row)?;
|
||||
turn.summary_items = summary_items;
|
||||
Ok(turn)
|
||||
})
|
||||
.collect::<ThreadStoreResult<Vec<_>>>()?,
|
||||
);
|
||||
}
|
||||
finish_page(requested_thread_id, CursorScope::Turns, rows, page_size)
|
||||
}
|
||||
|
||||
fn push_summary_item_join(
|
||||
query: &mut QueryBuilder<Sqlite>,
|
||||
segment: &RolloutLineageSegment,
|
||||
alias: &str,
|
||||
item_id_column: &str,
|
||||
) -> ThreadStoreResult<()> {
|
||||
query
|
||||
.push_bind(segment.rollout_id().to_string())
|
||||
.push(" AND ")
|
||||
.push(alias)
|
||||
.push(".turn_id = page_turns.turn_id AND ")
|
||||
.push(alias)
|
||||
.push(".item_id = page_turns.")
|
||||
.push(item_id_column)
|
||||
.push(" AND ")
|
||||
.push(alias)
|
||||
.push(".rollout_ordinal >= ")
|
||||
.push_bind(sqlite_integer(segment.start_ordinal())?);
|
||||
if let Some(end_ordinal) = segment.end_ordinal() {
|
||||
query
|
||||
.push(" AND ")
|
||||
.push(alias)
|
||||
.push(".rollout_ordinal < ")
|
||||
.push_bind(sqlite_integer(end_ordinal)?);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) async fn page_item_rows(
|
||||
pool: &sqlx::SqlitePool,
|
||||
lineage: &RolloutLineage,
|
||||
params: &ListItemsParams,
|
||||
) -> ThreadStoreResult<SegmentPage<StoredThreadItemRow>> {
|
||||
let (cursor, anchor_item_id) = match params.position.as_ref() {
|
||||
Some(ListItemsPosition::Cursor(cursor)) => (Some(cursor.as_str()), None),
|
||||
Some(ListItemsPosition::ItemAnchor { item_id }) => (None, Some(item_id.as_str())),
|
||||
None => (None, None),
|
||||
};
|
||||
let update_boundary = match (
|
||||
params.after_updated_at_ordinal,
|
||||
params.before_updated_at_ordinal,
|
||||
) {
|
||||
(Some(_), Some(_)) => {
|
||||
return Err(ThreadStoreError::InvalidRequest {
|
||||
message: "after and before update ordinals are mutually exclusive".to_string(),
|
||||
});
|
||||
}
|
||||
(Some(ordinal), None) => Some(UpdateOrdinalBoundary::After(ordinal)),
|
||||
(None, Some(ordinal)) => Some(UpdateOrdinalBoundary::Before(ordinal)),
|
||||
(None, None) => None,
|
||||
};
|
||||
if anchor_item_id.is_some()
|
||||
&& (params.sort_key != ItemSortKey::CreatedAtOrdinal || update_boundary.is_some())
|
||||
{
|
||||
return Err(ThreadStoreError::InvalidRequest {
|
||||
message: "item anchors require creation-order paging without an update boundary"
|
||||
.to_string(),
|
||||
});
|
||||
}
|
||||
if matches!(params.sort_key, ItemSortKey::UpdatedAtOrdinal) {
|
||||
let Some(update_boundary) = update_boundary else {
|
||||
return Err(ThreadStoreError::InvalidRequest {
|
||||
message: "update-ordinal item sorting requires an update boundary".to_string(),
|
||||
});
|
||||
};
|
||||
return page_updated_item_rows(pool, lineage, params, cursor, update_boundary).await;
|
||||
}
|
||||
let cursor = if let Some(anchor_item_id) = anchor_item_id {
|
||||
let turn_id = params
|
||||
.turn_id
|
||||
.as_deref()
|
||||
.filter(|id| !id.is_empty())
|
||||
.ok_or_else(|| ThreadStoreError::InvalidRequest {
|
||||
message: "turnId is required when cursor is an item anchor".to_string(),
|
||||
})?;
|
||||
if anchor_item_id.is_empty() {
|
||||
return Err(invalid_item_anchor());
|
||||
}
|
||||
let mut anchor = None;
|
||||
for segment in lineage.segments() {
|
||||
let mut query = QueryBuilder::<Sqlite>::new(
|
||||
"SELECT rollout_ordinal FROM thread_items WHERE thread_id = ",
|
||||
);
|
||||
query.push_bind(segment.rollout_id().to_string());
|
||||
query.push(" AND item_id = ").push_bind(anchor_item_id);
|
||||
push_segment_range(&mut query, segment, HistoryOrdinalColumn::Rollout)?;
|
||||
query.push(" AND turn_id = ").push_bind(turn_id);
|
||||
if let Some(ordinal) = query
|
||||
.build_query_scalar::<i64>()
|
||||
.fetch_optional(pool)
|
||||
.await
|
||||
.map_err(thread_history_error)?
|
||||
{
|
||||
anchor = Some(ordinal);
|
||||
break;
|
||||
}
|
||||
}
|
||||
Some(HistoryCursor {
|
||||
requested_thread_id: params.thread_id,
|
||||
rollout_ordinal: u64::try_from(anchor.ok_or_else(invalid_item_anchor)?)
|
||||
.map_err(thread_history_error)?,
|
||||
include_anchor: false,
|
||||
scope: CursorScope::ItemsByCreatedAtOrdinal,
|
||||
})
|
||||
} else {
|
||||
parse_cursor(
|
||||
cursor,
|
||||
params.thread_id,
|
||||
CursorScope::ItemsByCreatedAtOrdinal,
|
||||
)?
|
||||
};
|
||||
let ordinal_column = HistoryOrdinalColumn::Rollout;
|
||||
let mut rows = Vec::new();
|
||||
for (_, segment, segment_cursor) in
|
||||
segments_from_cursor(lineage, params.sort_direction, cursor.as_ref())?
|
||||
{
|
||||
let remaining = remaining_limit(params.page_size, rows.len())?;
|
||||
if remaining == 0 {
|
||||
break;
|
||||
}
|
||||
let mut query = QueryBuilder::<Sqlite>::new(
|
||||
r#"
|
||||
SELECT turn_id, item_id, rollout_ordinal, updated_at_ordinal, created_at_ms, started_at_ms, completed_at_ms, item_json
|
||||
FROM thread_items"#,
|
||||
);
|
||||
if params.item_ids.is_some() {
|
||||
// Seek each requested ID instead of scanning the turn in rollout order.
|
||||
query.push(" INDEXED BY sqlite_autoindex_thread_items_1");
|
||||
} else if params.turn_id.is_some() && update_boundary.is_none() {
|
||||
// A thread-wide index can scan earlier turns when a turn's final page is underfilled.
|
||||
query.push(" INDEXED BY idx_thread_items_by_turn_page");
|
||||
}
|
||||
query
|
||||
.push(" WHERE thread_id = ")
|
||||
.push_bind(segment.rollout_id().to_string());
|
||||
push_segment_range(&mut query, segment, ordinal_column)?;
|
||||
if let Some(update_boundary) = update_boundary {
|
||||
push_segment_range(&mut query, segment, HistoryOrdinalColumn::UpdatedAt)?;
|
||||
push_update_ordinal_boundary(&mut query, update_boundary)?;
|
||||
}
|
||||
if let Some(turn_id) = params.turn_id.as_deref() {
|
||||
query.push(" AND turn_id = ").push_bind(turn_id);
|
||||
}
|
||||
if let Some(item_ids) = params.item_ids.as_deref() {
|
||||
query.push(" AND item_id IN (");
|
||||
let mut ids = query.separated(", ");
|
||||
for item_id in item_ids {
|
||||
ids.push_bind(item_id);
|
||||
}
|
||||
ids.push_unseparated(")");
|
||||
}
|
||||
push_cursor_clause(
|
||||
&mut query,
|
||||
params.sort_direction,
|
||||
segment_cursor,
|
||||
ordinal_column,
|
||||
)?;
|
||||
push_order_and_limit(&mut query, params.sort_direction, remaining, ordinal_column);
|
||||
rows.extend(
|
||||
query
|
||||
.build()
|
||||
.fetch_all(pool)
|
||||
.await
|
||||
.map_err(thread_history_error)?
|
||||
.into_iter()
|
||||
.map(stored_thread_item_row)
|
||||
.collect::<ThreadStoreResult<Vec<_>>>()?,
|
||||
);
|
||||
}
|
||||
finish_page(
|
||||
params.thread_id,
|
||||
CursorScope::ItemsByCreatedAtOrdinal,
|
||||
rows,
|
||||
params.page_size,
|
||||
)
|
||||
}
|
||||
|
||||
async fn page_updated_item_rows(
|
||||
pool: &sqlx::SqlitePool,
|
||||
lineage: &RolloutLineage,
|
||||
params: &ListItemsParams,
|
||||
cursor: Option<&str>,
|
||||
update_boundary: UpdateOrdinalBoundary,
|
||||
) -> ThreadStoreResult<SegmentPage<StoredThreadItemRow>> {
|
||||
let cursor = parse_cursor(
|
||||
cursor,
|
||||
params.thread_id,
|
||||
CursorScope::ItemsByUpdatedAtOrdinal,
|
||||
)?;
|
||||
let ordinal_column = HistoryOrdinalColumn::UpdatedAt;
|
||||
let mut rows = Vec::new();
|
||||
for (_, segment, segment_cursor) in
|
||||
segments_from_cursor(lineage, params.sort_direction, cursor.as_ref())?
|
||||
{
|
||||
let remaining = remaining_limit(params.page_size, rows.len())?;
|
||||
if remaining == 0 {
|
||||
break;
|
||||
}
|
||||
let mut query = QueryBuilder::<Sqlite>::new(
|
||||
r#"
|
||||
SELECT turn_id, item_id, updated_at_ordinal AS rollout_ordinal, updated_at_ordinal, created_at_ms, started_at_ms, completed_at_ms, item_json
|
||||
FROM thread_items
|
||||
WHERE thread_id =
|
||||
"#,
|
||||
);
|
||||
query.push_bind(segment.rollout_id().to_string());
|
||||
push_segment_range(&mut query, segment, ordinal_column)?;
|
||||
push_update_ordinal_boundary(&mut query, update_boundary)?;
|
||||
if let Some(turn_id) = params.turn_id.as_deref() {
|
||||
query.push(" AND turn_id = ").push_bind(turn_id);
|
||||
}
|
||||
push_cursor_clause(
|
||||
&mut query,
|
||||
params.sort_direction,
|
||||
segment_cursor,
|
||||
ordinal_column,
|
||||
)?;
|
||||
push_order_and_limit(&mut query, params.sort_direction, remaining, ordinal_column);
|
||||
rows.extend(
|
||||
query
|
||||
.build()
|
||||
.fetch_all(pool)
|
||||
.await
|
||||
.map_err(thread_history_error)?
|
||||
.into_iter()
|
||||
.map(stored_thread_item_row)
|
||||
.collect::<ThreadStoreResult<Vec<_>>>()?,
|
||||
);
|
||||
}
|
||||
finish_page(
|
||||
params.thread_id,
|
||||
CursorScope::ItemsByUpdatedAtOrdinal,
|
||||
rows,
|
||||
params.page_size,
|
||||
)
|
||||
}
|
||||
|
||||
fn segments_from_cursor<'a>(
|
||||
lineage: &'a RolloutLineage,
|
||||
direction: SortDirection,
|
||||
cursor: Option<&'a HistoryCursor>,
|
||||
) -> ThreadStoreResult<Vec<(usize, &'a RolloutLineageSegment, Option<&'a HistoryCursor>)>> {
|
||||
let segments = lineage.segments();
|
||||
let cursor_index = cursor
|
||||
.map(|cursor| {
|
||||
lineage
|
||||
.segment_index_for_ordinal(cursor.rollout_ordinal)
|
||||
.ok_or_else(|| invalid_cursor("position outside thread lineage"))
|
||||
})
|
||||
.transpose()?;
|
||||
let indexes: Vec<usize> = match direction {
|
||||
SortDirection::Asc => (cursor_index.unwrap_or(0)..segments.len()).collect(),
|
||||
SortDirection::Desc => {
|
||||
let end = cursor_index.unwrap_or_else(|| segments.len().saturating_sub(1));
|
||||
(0..=end).rev().collect()
|
||||
}
|
||||
};
|
||||
Ok(indexes
|
||||
.into_iter()
|
||||
.map(|index| {
|
||||
let segment_cursor = if Some(index) == cursor_index {
|
||||
cursor
|
||||
} else {
|
||||
None
|
||||
};
|
||||
(index, &segments[index], segment_cursor)
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
fn push_segment_range(
|
||||
query: &mut QueryBuilder<Sqlite>,
|
||||
segment: &RolloutLineageSegment,
|
||||
ordinal_column: HistoryOrdinalColumn,
|
||||
) -> ThreadStoreResult<()> {
|
||||
query.push(" AND ");
|
||||
ordinal_column.push(query);
|
||||
query
|
||||
.push(" >= ")
|
||||
.push_bind(sqlite_integer(segment.start_ordinal())?);
|
||||
if let Some(end_ordinal) = segment.end_ordinal() {
|
||||
query.push(" AND ");
|
||||
ordinal_column.push(query);
|
||||
query.push(" < ").push_bind(sqlite_integer(end_ordinal)?);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn push_cursor_clause(
|
||||
query: &mut QueryBuilder<Sqlite>,
|
||||
direction: SortDirection,
|
||||
cursor: Option<&HistoryCursor>,
|
||||
ordinal_column: HistoryOrdinalColumn,
|
||||
) -> ThreadStoreResult<()> {
|
||||
if let Some(cursor) = cursor {
|
||||
let comparator = match (direction, cursor.include_anchor) {
|
||||
(SortDirection::Asc, true) => ">=",
|
||||
(SortDirection::Asc, false) => ">",
|
||||
(SortDirection::Desc, true) => "<=",
|
||||
(SortDirection::Desc, false) => "<",
|
||||
};
|
||||
query.push(" AND ");
|
||||
ordinal_column.push(query);
|
||||
query
|
||||
.push(" ")
|
||||
.push(comparator)
|
||||
.push(" ")
|
||||
.push_bind(sqlite_integer(cursor.rollout_ordinal)?);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn push_order_and_limit(
|
||||
query: &mut QueryBuilder<Sqlite>,
|
||||
direction: SortDirection,
|
||||
limit: i64,
|
||||
ordinal_column: HistoryOrdinalColumn,
|
||||
) {
|
||||
let order = match direction {
|
||||
SortDirection::Asc => "ASC",
|
||||
SortDirection::Desc => "DESC",
|
||||
};
|
||||
query.push(" ORDER BY ");
|
||||
ordinal_column.push(query);
|
||||
query.push(" ").push(order).push(" LIMIT ").push_bind(limit);
|
||||
}
|
||||
|
||||
fn remaining_limit(page_size: usize, row_count: usize) -> ThreadStoreResult<i64> {
|
||||
let limit = page_size
|
||||
.checked_add(1)
|
||||
.and_then(|limit| limit.checked_sub(row_count))
|
||||
.ok_or_else(page_size_too_large)?;
|
||||
i64::try_from(limit).map_err(|_| page_size_too_large())
|
||||
}
|
||||
|
||||
fn finish_page<T: HasPosition>(
|
||||
requested_thread_id: ThreadId,
|
||||
scope: CursorScope,
|
||||
mut rows: Vec<T>,
|
||||
page_size: usize,
|
||||
) -> ThreadStoreResult<SegmentPage<T>> {
|
||||
let has_more = rows.len() > page_size;
|
||||
rows.truncate(page_size);
|
||||
let backwards_cursor = rows
|
||||
.first()
|
||||
.map(|row| {
|
||||
serialize_cursor(
|
||||
requested_thread_id,
|
||||
scope.clone(),
|
||||
row.position().rollout_ordinal,
|
||||
/*include_anchor*/ true,
|
||||
)
|
||||
})
|
||||
.transpose()?;
|
||||
let next_cursor = if has_more {
|
||||
rows.last()
|
||||
.map(|row| {
|
||||
serialize_cursor(
|
||||
requested_thread_id,
|
||||
scope,
|
||||
row.position().rollout_ordinal,
|
||||
/*include_anchor*/ false,
|
||||
)
|
||||
})
|
||||
.transpose()?
|
||||
} else {
|
||||
None
|
||||
};
|
||||
Ok(SegmentPage {
|
||||
rows,
|
||||
next_cursor,
|
||||
backwards_cursor,
|
||||
})
|
||||
}
|
||||
|
||||
trait HasPosition {
|
||||
fn position(&self) -> RolloutHistoryPosition;
|
||||
}
|
||||
|
||||
impl HasPosition for StoredTurnRow {
|
||||
fn position(&self) -> RolloutHistoryPosition {
|
||||
self.position
|
||||
}
|
||||
}
|
||||
|
||||
impl HasPosition for StoredThreadItemRow {
|
||||
fn position(&self) -> RolloutHistoryPosition {
|
||||
self.position
|
||||
}
|
||||
}
|
||||
|
||||
fn sqlite_integer(value: u64) -> ThreadStoreResult<i64> {
|
||||
i64::try_from(value).map_err(|_| ThreadStoreError::InvalidRequest {
|
||||
message: "rollout ordinal exceeds SQLite integer range".to_string(),
|
||||
})
|
||||
}
|
||||
|
||||
fn page_size_too_large() -> ThreadStoreError {
|
||||
ThreadStoreError::InvalidRequest {
|
||||
message: "page size is too large".to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn invalid_item_anchor() -> ThreadStoreError {
|
||||
ThreadStoreError::InvalidRequest {
|
||||
message: "cursor.itemId does not identify an item in the requested history scope"
|
||||
.to_string(),
|
||||
}
|
||||
}
|
||||
100
codex-rs/thread-store/src/local/thread_history/turn_lookup.rs
Normal file
100
codex-rs/thread-store/src/local/thread_history/turn_lookup.rs
Normal file
@@ -0,0 +1,100 @@
|
||||
use codex_protocol::ThreadId;
|
||||
use sqlx::Row;
|
||||
|
||||
use super::super::rollout_lineage::RolloutLineage;
|
||||
use super::super::rollout_lineage::RolloutLineageSegment;
|
||||
use super::sqlite_integer;
|
||||
use crate::ThreadStoreError;
|
||||
use crate::ThreadStoreResult;
|
||||
|
||||
pub(in crate::local) struct TurnRow {
|
||||
pub rollout_id: ThreadId,
|
||||
pub rollout_ordinal: i64,
|
||||
pub rollout_byte_offset: Option<i64>,
|
||||
pub rollout_end_ordinal: Option<i64>,
|
||||
pub rollout_end_byte_offset: Option<i64>,
|
||||
pub status: String,
|
||||
pub first_user_item_id: Option<String>,
|
||||
pub final_agent_item_id: Option<String>,
|
||||
}
|
||||
|
||||
pub(in crate::local) async fn find_source_turn(
|
||||
pool: &sqlx::SqlitePool,
|
||||
lineage: &RolloutLineage,
|
||||
turn_id: &str,
|
||||
) -> ThreadStoreResult<TurnRow> {
|
||||
find_turn(pool, lineage.segments().iter(), turn_id).await
|
||||
}
|
||||
|
||||
pub(in crate::local) async fn find_visible_turn(
|
||||
pool: &sqlx::SqlitePool,
|
||||
lineage: &RolloutLineage,
|
||||
turn_id: &str,
|
||||
) -> ThreadStoreResult<TurnRow> {
|
||||
find_turn(pool, lineage.segments().iter().rev(), turn_id).await
|
||||
}
|
||||
|
||||
async fn find_turn<'a>(
|
||||
pool: &sqlx::SqlitePool,
|
||||
segments: impl Iterator<Item = &'a RolloutLineageSegment>,
|
||||
turn_id: &str,
|
||||
) -> ThreadStoreResult<TurnRow> {
|
||||
for segment in segments {
|
||||
if let Some(row) = query_turn_row(pool, segment, turn_id).await? {
|
||||
return Ok(row);
|
||||
}
|
||||
}
|
||||
Err(ThreadStoreError::InvalidRequest {
|
||||
message: format!("turn not found: {turn_id}"),
|
||||
})
|
||||
}
|
||||
|
||||
async fn query_turn_row(
|
||||
pool: &sqlx::SqlitePool,
|
||||
segment: &RolloutLineageSegment,
|
||||
turn_id: &str,
|
||||
) -> ThreadStoreResult<Option<TurnRow>> {
|
||||
let end_ordinal = segment
|
||||
.end_ordinal()
|
||||
.map(|ordinal| sqlite_integer(ordinal, "rollout ordinal"))
|
||||
.transpose()?;
|
||||
sqlx::query(
|
||||
r#"
|
||||
SELECT
|
||||
rollout_ordinal,
|
||||
rollout_byte_offset,
|
||||
rollout_end_ordinal,
|
||||
rollout_end_byte_offset,
|
||||
status,
|
||||
first_user_item_id,
|
||||
final_agent_item_id
|
||||
FROM thread_turns
|
||||
WHERE thread_id = ?
|
||||
AND turn_id = ?
|
||||
AND rollout_ordinal >= ?
|
||||
AND (? IS NULL OR rollout_ordinal < ?)
|
||||
"#,
|
||||
)
|
||||
.bind(segment.rollout_id().to_string())
|
||||
.bind(turn_id)
|
||||
.bind(sqlite_integer(segment.start_ordinal(), "rollout ordinal")?)
|
||||
.bind(end_ordinal)
|
||||
.bind(end_ordinal)
|
||||
.fetch_optional(pool)
|
||||
.await
|
||||
.map_err(|err| ThreadStoreError::Internal {
|
||||
message: format!("failed to resolve logical turn: {err}"),
|
||||
})
|
||||
.map(|row| {
|
||||
row.map(|row| TurnRow {
|
||||
rollout_id: segment.rollout_id(),
|
||||
rollout_ordinal: row.get("rollout_ordinal"),
|
||||
rollout_byte_offset: row.get("rollout_byte_offset"),
|
||||
rollout_end_ordinal: row.get("rollout_end_ordinal"),
|
||||
rollout_end_byte_offset: row.get("rollout_end_byte_offset"),
|
||||
status: row.get("status"),
|
||||
first_user_item_id: row.get("first_user_item_id"),
|
||||
final_agent_item_id: row.get("final_agent_item_id"),
|
||||
})
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,432 @@
|
||||
//! Reads durable history into bounded batches ending at complete records, each with a checkpoint.
|
||||
|
||||
use std::io::BufRead;
|
||||
use std::io::BufReader;
|
||||
use std::io::Read;
|
||||
use std::io::Seek;
|
||||
use std::io::SeekFrom;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use chrono::DateTime;
|
||||
use codex_app_server_protocol::ThreadHistoryChangeSet;
|
||||
use codex_app_server_protocol::project_rollout_line;
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_rollout::RolloutItem;
|
||||
use tracing::warn;
|
||||
|
||||
use super::LocalThreadStore;
|
||||
use super::rollout_lineage::AncestorReads;
|
||||
use super::thread_history::ProjectedRolloutLine;
|
||||
use super::thread_history::RolloutProjectionStep;
|
||||
use crate::ThreadStoreError;
|
||||
use crate::ThreadStoreResult;
|
||||
|
||||
#[path = "thread_history_materialization_pipeline.rs"]
|
||||
mod pipeline;
|
||||
|
||||
const SQLITE_PROJECTION_METRIC: &str = "codex.thread_history.sqlite_projection";
|
||||
const SQLITE_PROJECTION_ANOMALY_METRIC: &str = "codex.thread_history.sqlite_projection.anomaly";
|
||||
const BATCH_SOURCE_BYTES: u64 = 1024 * 1024;
|
||||
const BATCH_STEPS: usize = 256;
|
||||
|
||||
struct ProjectionRollout {
|
||||
path: PathBuf,
|
||||
reads: AncestorReads,
|
||||
}
|
||||
|
||||
pub(super) async fn materialize_to_sqlite(
|
||||
store: &LocalThreadStore,
|
||||
thread_id: ThreadId,
|
||||
rollout_path: &Path,
|
||||
) -> ThreadStoreResult<()> {
|
||||
materialize_to_sqlite_with_reads(store, thread_id, rollout_path, &AncestorReads::default())
|
||||
.await
|
||||
}
|
||||
|
||||
/// Project this rollout and identify an unreadable ancestor before committing a batch.
|
||||
pub(super) async fn materialize_to_sqlite_with_reads(
|
||||
store: &LocalThreadStore,
|
||||
thread_id: ThreadId,
|
||||
rollout_path: &Path,
|
||||
reads: &AncestorReads,
|
||||
) -> ThreadStoreResult<()> {
|
||||
if store.state_db.is_none() {
|
||||
return Ok(());
|
||||
}
|
||||
let rollout = ProjectionRollout {
|
||||
path: rollout_path.to_owned(),
|
||||
reads: reads.clone(),
|
||||
};
|
||||
let result = materialize_to_sqlite_with_state_db(store, thread_id, rollout).await;
|
||||
record_projection_outcome(&result);
|
||||
result
|
||||
}
|
||||
|
||||
async fn materialize_to_sqlite_with_state_db(
|
||||
store: &LocalThreadStore,
|
||||
thread_id: ThreadId,
|
||||
rollout: ProjectionRollout,
|
||||
) -> ThreadStoreResult<()> {
|
||||
let projection_state = super::thread_history::projection_state(store, thread_id).await?;
|
||||
let start_offset = projection_state
|
||||
.as_ref()
|
||||
.map_or(0, |state| state.next_byte_offset);
|
||||
if rollout
|
||||
.reads
|
||||
.cutoff(&rollout.path)
|
||||
.is_some_and(|end| start_offset >= end.end_byte_offset)
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
if projection_state.is_none()
|
||||
&& !rollout.reads.tracks(&rollout.path)
|
||||
&& codex_rollout::existing_rollout_path(&rollout.path)
|
||||
.await
|
||||
.is_none()
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
let session_meta = codex_rollout::read_session_meta_line(&rollout.path)
|
||||
.await
|
||||
.map_err(|err| {
|
||||
rollout.reads.record_failure(&rollout.path);
|
||||
ThreadStoreError::Internal {
|
||||
message: format!(
|
||||
"failed to read rollout metadata {}: {err}",
|
||||
rollout.path.display()
|
||||
),
|
||||
}
|
||||
})?
|
||||
.meta;
|
||||
let initial_ordinal = session_meta
|
||||
.history_base
|
||||
.map_or(0, |base| base.end_ordinal_exclusive);
|
||||
let subagent_history_start_ordinal = session_meta.subagent_history_start_ordinal;
|
||||
let expected_ordinal = projection_state
|
||||
.as_ref()
|
||||
.map_or(initial_ordinal, |state| state.next_ordinal);
|
||||
pipeline::read_and_apply(
|
||||
store,
|
||||
thread_id,
|
||||
rollout,
|
||||
start_offset,
|
||||
expected_ordinal,
|
||||
initial_ordinal,
|
||||
subagent_history_start_ordinal,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Read and project the complete durable prefix in one blocking task.
|
||||
fn read_projection_batches(
|
||||
rollout: &ProjectionRollout,
|
||||
start_offset: u64,
|
||||
expected_ordinal: u64,
|
||||
thread_id: ThreadId,
|
||||
subagent_history_start_ordinal: Option<u64>,
|
||||
is_cancelled: impl Fn() -> bool,
|
||||
mut emit: impl FnMut(Vec<RolloutProjectionStep>, u64) -> ThreadStoreResult<()>,
|
||||
) -> ThreadStoreResult<()> {
|
||||
let rollout_path = &rollout.path;
|
||||
let mut file = match rollout.reads.open(rollout_path, &is_cancelled) {
|
||||
Ok(file) => file,
|
||||
Err(err)
|
||||
if err.kind() == std::io::ErrorKind::NotFound
|
||||
&& start_offset == 0
|
||||
&& !rollout.reads.tracks(rollout_path) =>
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
Err(err) => return Err(thread_store_io_error(err)),
|
||||
};
|
||||
let file_end_offset = match rollout.reads.cutoff(rollout_path) {
|
||||
Some(end) => end.end_byte_offset,
|
||||
None => file.seek(SeekFrom::End(0)).map_err(thread_store_io_error)?,
|
||||
};
|
||||
let byte_count = file_end_offset.checked_sub(start_offset).ok_or_else(|| {
|
||||
rollout.reads.record_failure(rollout_path);
|
||||
ThreadStoreError::Internal {
|
||||
message: format!(
|
||||
"durable rollout shrank before projection: {}",
|
||||
rollout_path.display()
|
||||
),
|
||||
}
|
||||
})?;
|
||||
file.seek(SeekFrom::Start(start_offset))
|
||||
.map_err(thread_store_io_error)?;
|
||||
// Freeze this pass at the captured end, without retaining the entire durable suffix.
|
||||
let mut reader = BufReader::new(file.take(byte_count));
|
||||
let mut line_bytes = Vec::new();
|
||||
// Only project the newline-terminated prefix; leave a trailing partial record for the next
|
||||
// pass.
|
||||
let mut next_ordinal = expected_ordinal;
|
||||
let mut next_offset = start_offset;
|
||||
let mut line_start_offset = start_offset;
|
||||
let mut batch_start_offset = start_offset;
|
||||
let mut batch = Vec::new();
|
||||
loop {
|
||||
if is_cancelled() {
|
||||
return Err(thread_store_io_error(std::io::Error::other(
|
||||
"rollout read cancelled",
|
||||
)));
|
||||
}
|
||||
// Flush only between complete records: an ordinal gap and its following line must
|
||||
// share a checkpoint. Byte-only progress from skipped records also bounds batches.
|
||||
if next_offset - batch_start_offset >= BATCH_SOURCE_BYTES || batch.len() >= BATCH_STEPS {
|
||||
emit(std::mem::take(&mut batch), next_offset)?;
|
||||
batch_start_offset = next_offset;
|
||||
}
|
||||
line_bytes.clear();
|
||||
if reader
|
||||
.read_until(b'\n', &mut line_bytes)
|
||||
.map_err(thread_store_io_error)?
|
||||
== 0
|
||||
{
|
||||
break;
|
||||
}
|
||||
if !line_bytes.ends_with(b"\n") {
|
||||
break;
|
||||
}
|
||||
let line_end_offset = line_start_offset
|
||||
.checked_add(u64::try_from(line_bytes.len()).map_err(|_| {
|
||||
ThreadStoreError::Internal {
|
||||
message: "durable rollout byte offset overflow".to_string(),
|
||||
}
|
||||
})?)
|
||||
.ok_or_else(|| ThreadStoreError::Internal {
|
||||
message: "durable rollout byte offset overflow".to_string(),
|
||||
})?;
|
||||
if line_bytes.iter().all(u8::is_ascii_whitespace) {
|
||||
next_offset = line_end_offset;
|
||||
line_start_offset = line_end_offset;
|
||||
continue;
|
||||
}
|
||||
let value = match serde_json::from_slice::<serde_json::Value>(&line_bytes) {
|
||||
Ok(value) => value,
|
||||
Err(err) => {
|
||||
warn!(
|
||||
thread_id = %thread_id,
|
||||
rollout_path = %rollout_path.display(),
|
||||
line_start_byte_offset = line_start_offset,
|
||||
line_end_byte_offset = line_end_offset,
|
||||
expected_ordinal = next_ordinal,
|
||||
error = %err,
|
||||
"skipping malformed rollout line during projection"
|
||||
);
|
||||
record_projection_anomaly(ProjectionAnomaly::MalformedJson);
|
||||
next_offset = line_end_offset;
|
||||
line_start_offset = line_end_offset;
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let raw_ordinal = value.get("ordinal").and_then(serde_json::Value::as_u64);
|
||||
let line = match codex_rollout::decode_rollout_line(value) {
|
||||
Ok(line) => line,
|
||||
Err(err) => {
|
||||
warn!(
|
||||
thread_id = %thread_id,
|
||||
rollout_path = %rollout_path.display(),
|
||||
line_start_byte_offset = line_start_offset,
|
||||
line_end_byte_offset = line_end_offset,
|
||||
expected_ordinal = next_ordinal,
|
||||
line_ordinal = ?raw_ordinal,
|
||||
error = %err,
|
||||
"skipping unknown rollout line during projection"
|
||||
);
|
||||
record_projection_anomaly(ProjectionAnomaly::UnknownLine);
|
||||
// Unknown records only advance the byte checkpoint. A writer that could not
|
||||
// decode this line may have reused its ordinal, so let the next decoded line
|
||||
// resolve reuse versus a gap.
|
||||
next_offset = line_end_offset;
|
||||
line_start_offset = line_end_offset;
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let ordinal = match line.ordinal {
|
||||
Some(ordinal) => ordinal,
|
||||
None => {
|
||||
warn!(
|
||||
thread_id = %thread_id,
|
||||
rollout_path = %rollout_path.display(),
|
||||
line_start_byte_offset = line_start_offset,
|
||||
line_end_byte_offset = line_end_offset,
|
||||
expected_ordinal = next_ordinal,
|
||||
"skipping paginated rollout line without an ordinal"
|
||||
);
|
||||
record_projection_anomaly(ProjectionAnomaly::MissingOrdinal);
|
||||
next_offset = line_end_offset;
|
||||
line_start_offset = line_end_offset;
|
||||
continue;
|
||||
}
|
||||
};
|
||||
if ordinal < next_ordinal {
|
||||
warn!(
|
||||
thread_id = %thread_id,
|
||||
rollout_path = %rollout_path.display(),
|
||||
line_start_byte_offset = line_start_offset,
|
||||
line_end_byte_offset = line_end_offset,
|
||||
expected_ordinal = next_ordinal,
|
||||
line_ordinal = ordinal,
|
||||
"skipping duplicate or regressed rollout ordinal during projection"
|
||||
);
|
||||
record_projection_anomaly(ProjectionAnomaly::DuplicateOrRegressedOrdinal);
|
||||
next_offset = line_end_offset;
|
||||
line_start_offset = line_end_offset;
|
||||
continue;
|
||||
}
|
||||
let is_inherited_subagent_history =
|
||||
subagent_history_start_ordinal.is_some_and(|start| ordinal < start);
|
||||
let changes = if is_inherited_subagent_history {
|
||||
ThreadHistoryChangeSet::default()
|
||||
} else {
|
||||
project_rollout_line(&line)
|
||||
};
|
||||
let fallback_created_at_ms = if changes
|
||||
.changed_items
|
||||
.iter()
|
||||
.any(|change| change.item.started_at_ms.is_none())
|
||||
|| (!is_inherited_subagent_history
|
||||
&& matches!(&line.item, RolloutItem::RealtimeItem(_)))
|
||||
{
|
||||
match DateTime::parse_from_rfc3339(line.timestamp.as_str()) {
|
||||
Ok(timestamp) => Some(timestamp.timestamp_millis()),
|
||||
Err(err) => {
|
||||
warn!(
|
||||
thread_id = %thread_id,
|
||||
rollout_path = %rollout_path.display(),
|
||||
line_start_byte_offset = line_start_offset,
|
||||
line_end_byte_offset = line_end_offset,
|
||||
expected_ordinal = next_ordinal,
|
||||
line_ordinal = ordinal,
|
||||
error = %err,
|
||||
"skipping rollout line with invalid timestamp during projection"
|
||||
);
|
||||
record_projection_anomaly(ProjectionAnomaly::InvalidTimestamp);
|
||||
let end_ordinal_exclusive =
|
||||
ordinal
|
||||
.checked_add(1)
|
||||
.ok_or_else(|| ThreadStoreError::Internal {
|
||||
message: "rollout ordinal exceeds SQLite integer range".to_string(),
|
||||
})?;
|
||||
batch.push(RolloutProjectionStep::SkippedOrdinalRange {
|
||||
start_ordinal: next_ordinal,
|
||||
end_ordinal_exclusive,
|
||||
});
|
||||
next_ordinal = end_ordinal_exclusive;
|
||||
next_offset = line_end_offset;
|
||||
line_start_offset = line_end_offset;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if ordinal > next_ordinal {
|
||||
warn!(
|
||||
thread_id = %thread_id,
|
||||
rollout_path = %rollout_path.display(),
|
||||
line_start_byte_offset = line_start_offset,
|
||||
line_end_byte_offset = line_end_offset,
|
||||
expected_ordinal = next_ordinal,
|
||||
line_ordinal = ordinal,
|
||||
skipped_ordinal_start = next_ordinal,
|
||||
skipped_ordinal_end_exclusive = ordinal,
|
||||
"skipping missing rollout ordinal range during projection"
|
||||
);
|
||||
record_projection_anomaly(ProjectionAnomaly::ForwardOrdinalGap);
|
||||
batch.push(RolloutProjectionStep::SkippedOrdinalRange {
|
||||
start_ordinal: next_ordinal,
|
||||
end_ordinal_exclusive: ordinal,
|
||||
});
|
||||
}
|
||||
let next_line_ordinal =
|
||||
ordinal
|
||||
.checked_add(1)
|
||||
.ok_or_else(|| ThreadStoreError::Internal {
|
||||
message: "rollout ordinal exceeds SQLite integer range".to_string(),
|
||||
})?;
|
||||
batch.push(RolloutProjectionStep::Line(Box::new(
|
||||
ProjectedRolloutLine {
|
||||
ordinal,
|
||||
start_byte_offset: line_start_offset,
|
||||
end_byte_offset: line_end_offset,
|
||||
fallback_created_at_ms,
|
||||
changes,
|
||||
realtime_item: match line.item {
|
||||
RolloutItem::RealtimeItem(item) if !is_inherited_subagent_history => Some(item),
|
||||
_ => None,
|
||||
},
|
||||
},
|
||||
)));
|
||||
next_ordinal = next_line_ordinal;
|
||||
next_offset = line_end_offset;
|
||||
line_start_offset = line_end_offset;
|
||||
}
|
||||
if reader.get_ref().limit() != 0 {
|
||||
return Err(thread_store_io_error(std::io::Error::new(
|
||||
std::io::ErrorKind::UnexpectedEof,
|
||||
"durable rollout shrank during projection",
|
||||
)));
|
||||
}
|
||||
if next_offset != batch_start_offset {
|
||||
emit(batch, next_offset)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum ProjectionAnomaly {
|
||||
MalformedJson,
|
||||
UnknownLine,
|
||||
MissingOrdinal,
|
||||
DuplicateOrRegressedOrdinal,
|
||||
ForwardOrdinalGap,
|
||||
InvalidTimestamp,
|
||||
}
|
||||
|
||||
impl ProjectionAnomaly {
|
||||
fn tag(self) -> &'static str {
|
||||
match self {
|
||||
Self::MalformedJson => "malformed_json",
|
||||
Self::UnknownLine => "unknown_line",
|
||||
Self::MissingOrdinal => "missing_ordinal",
|
||||
Self::DuplicateOrRegressedOrdinal => "duplicate_or_regressed_ordinal",
|
||||
Self::ForwardOrdinalGap => "forward_ordinal_gap",
|
||||
Self::InvalidTimestamp => "invalid_timestamp",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn record_projection_outcome(result: &ThreadStoreResult<()>) {
|
||||
let Some(metrics) = codex_otel::global() else {
|
||||
return;
|
||||
};
|
||||
let outcome = if result.is_ok() { "success" } else { "error" };
|
||||
let _ = metrics.counter(
|
||||
SQLITE_PROJECTION_METRIC,
|
||||
/*inc*/ 1,
|
||||
&[("outcome", outcome)],
|
||||
);
|
||||
}
|
||||
|
||||
fn record_projection_anomaly(anomaly: ProjectionAnomaly) {
|
||||
let Some(metrics) = codex_otel::global() else {
|
||||
return;
|
||||
};
|
||||
let _ = metrics.counter(
|
||||
SQLITE_PROJECTION_ANOMALY_METRIC,
|
||||
/*inc*/ 1,
|
||||
&[("kind", anomaly.tag())],
|
||||
);
|
||||
}
|
||||
|
||||
fn thread_store_io_error(err: std::io::Error) -> ThreadStoreError {
|
||||
ThreadStoreError::Internal {
|
||||
message: err.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "thread_history_materialization_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,105 @@
|
||||
//! Pipes bounded rollout batches into short SQLite transactions, committing each checkpoint.
|
||||
|
||||
use codex_protocol::ThreadId;
|
||||
|
||||
use super::super::LocalThreadStore;
|
||||
use super::super::thread_history::RolloutProjectionStep;
|
||||
use super::super::thread_history::apply_projection;
|
||||
use super::ProjectionRollout;
|
||||
use super::read_projection_batches;
|
||||
use crate::ThreadStoreError;
|
||||
use crate::ThreadStoreResult;
|
||||
|
||||
const QUEUED_BATCHES: usize = 2;
|
||||
|
||||
pub(super) enum ProjectionMessage {
|
||||
Batch {
|
||||
projections: Vec<RolloutProjectionStep>,
|
||||
next_offset: u64,
|
||||
},
|
||||
Complete,
|
||||
Failed(ThreadStoreError),
|
||||
}
|
||||
|
||||
pub(super) async fn read_and_apply(
|
||||
store: &LocalThreadStore,
|
||||
thread_id: ThreadId,
|
||||
rollout: ProjectionRollout,
|
||||
start_offset: u64,
|
||||
expected_ordinal: u64,
|
||||
initial_ordinal: u64,
|
||||
subagent_history_start_ordinal: Option<u64>,
|
||||
) -> ThreadStoreResult<()> {
|
||||
// Two queued batches, one being produced and one being consumed. Each is limited by
|
||||
// source bytes and step count; an oversized individual record remains indivisible.
|
||||
let (sender, receiver) = tokio::sync::mpsc::channel(QUEUED_BATCHES);
|
||||
let (stop, keep_running) = tokio::sync::oneshot::channel::<()>();
|
||||
let span = tracing::Span::current();
|
||||
let worker = tokio::task::spawn_blocking(move || {
|
||||
let _entered = span.enter();
|
||||
let read = read_projection_batches(
|
||||
&rollout,
|
||||
start_offset,
|
||||
expected_ordinal,
|
||||
thread_id,
|
||||
subagent_history_start_ordinal,
|
||||
|| stop.is_closed(),
|
||||
|projections, next_offset| {
|
||||
sender
|
||||
.blocking_send(ProjectionMessage::Batch {
|
||||
projections,
|
||||
next_offset,
|
||||
})
|
||||
.map_err(|_| ThreadStoreError::Internal {
|
||||
message: "projection consumer stopped".to_string(),
|
||||
})
|
||||
},
|
||||
);
|
||||
let completion = match read {
|
||||
Ok(()) => ProjectionMessage::Complete,
|
||||
Err(error) => ProjectionMessage::Failed(error),
|
||||
};
|
||||
let _ = sender.blocking_send(completion);
|
||||
});
|
||||
let result = apply_batches(store, thread_id, start_offset, initial_ordinal, receiver).await;
|
||||
// apply_batches drops the receiver on error, unblocking any pending producer send.
|
||||
drop(keep_running);
|
||||
worker.await.map_err(|err| ThreadStoreError::Internal {
|
||||
message: format!("projection producer failed: {err}"),
|
||||
})?;
|
||||
result
|
||||
}
|
||||
|
||||
pub(super) async fn apply_batches(
|
||||
store: &LocalThreadStore,
|
||||
thread_id: ThreadId,
|
||||
mut start_offset: u64,
|
||||
initial_ordinal: u64,
|
||||
mut receiver: tokio::sync::mpsc::Receiver<ProjectionMessage>,
|
||||
) -> ThreadStoreResult<()> {
|
||||
// Receive before opening the transaction so a slow reader cannot hold the SQLite writer.
|
||||
while let Some(message) = receiver.recv().await {
|
||||
match message {
|
||||
ProjectionMessage::Batch {
|
||||
projections,
|
||||
next_offset,
|
||||
} => {
|
||||
apply_projection(
|
||||
store,
|
||||
thread_id,
|
||||
start_offset,
|
||||
next_offset,
|
||||
initial_ordinal,
|
||||
projections,
|
||||
)
|
||||
.await?;
|
||||
start_offset = next_offset;
|
||||
}
|
||||
ProjectionMessage::Complete => return Ok(()),
|
||||
ProjectionMessage::Failed(error) => return Err(error),
|
||||
}
|
||||
}
|
||||
Err(ThreadStoreError::Internal {
|
||||
message: "projection producer stopped before successful completion".to_string(),
|
||||
})
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
216
codex-rs/thread-store/src/local/thread_rollout_resolver.rs
Normal file
216
codex-rs/thread-store/src/local/thread_rollout_resolver.rs
Normal file
@@ -0,0 +1,216 @@
|
||||
//! Resolves a thread ID to the rollout file the thread currently uses.
|
||||
//!
|
||||
//! 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.
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::protocol::ThreadHistoryMode;
|
||||
use codex_rollout::find_archived_thread_path_by_id_str;
|
||||
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::ThreadStoreError;
|
||||
use crate::ThreadStoreResult;
|
||||
|
||||
/// One thread resolved to the concrete rollout file it currently uses.
|
||||
///
|
||||
/// 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)]
|
||||
pub(super) struct ResolvedThreadRollout {
|
||||
pub(super) thread_id: ThreadId,
|
||||
pub(super) rollout_id: ThreadId,
|
||||
pub(super) path: PathBuf,
|
||||
pub(super) location: RolloutLocation,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(super) enum RolloutLocation {
|
||||
Unarchived,
|
||||
Archived,
|
||||
}
|
||||
|
||||
pub(super) async fn resolve_current(
|
||||
store: &LocalThreadStore,
|
||||
thread_id: ThreadId,
|
||||
) -> ThreadStoreResult<Option<ResolvedThreadRollout>> {
|
||||
resolve(store, thread_id, LookupScope::ExcludeArchived).await
|
||||
}
|
||||
|
||||
pub(super) async fn resolve_current_including_archived(
|
||||
store: &LocalThreadStore,
|
||||
thread_id: ThreadId,
|
||||
) -> ThreadStoreResult<Option<ResolvedThreadRollout>> {
|
||||
resolve(store, thread_id, LookupScope::IncludeArchived).await
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum LookupScope {
|
||||
ExcludeArchived,
|
||||
IncludeArchived,
|
||||
}
|
||||
|
||||
impl LookupScope {
|
||||
fn accepts(self, location: RolloutLocation) -> bool {
|
||||
match self {
|
||||
Self::ExcludeArchived => location == RolloutLocation::Unarchived,
|
||||
Self::IncludeArchived => true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolves a thread's selected rollout in this order:
|
||||
///
|
||||
/// 1. The live writer, when one exists.
|
||||
/// 2. SQLite's selected rollout path.
|
||||
/// 3. Filesystem fallback for threads SQLite does not identify as paginated.
|
||||
/// 4. Archived filesystem fallback, when requested.
|
||||
async fn resolve(
|
||||
store: &LocalThreadStore,
|
||||
thread_id: ThreadId,
|
||||
scope: LookupScope,
|
||||
) -> ThreadStoreResult<Option<ResolvedThreadRollout>> {
|
||||
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?
|
||||
{
|
||||
return Ok(Some(resolved));
|
||||
}
|
||||
|
||||
let state_db_ctx = store.state_db().await;
|
||||
if let Some(state_db_ctx) = state_db_ctx.as_deref() {
|
||||
match state_db_ctx.get_thread(thread_id).await {
|
||||
Ok(Some(metadata)) => {
|
||||
// Once SQLite identifies a thread as paginated, its rollout path is
|
||||
// authoritative: after `thread/revert`, a scan could find an older immutable
|
||||
// rollout for the same thread. Filesystem fallback remains available when SQLite
|
||||
// has no row or identifies the thread as legacy.
|
||||
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;
|
||||
}
|
||||
}
|
||||
if metadata.history_mode == ThreadHistoryMode::Paginated {
|
||||
return Ok(None);
|
||||
}
|
||||
}
|
||||
Ok(None) => {}
|
||||
Err(err) => {
|
||||
return Err(ThreadStoreError::Internal {
|
||||
message: format!("failed to read thread metadata for {thread_id}: {err}"),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
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(),
|
||||
)
|
||||
.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?
|
||||
{
|
||||
return Ok(Some(resolved));
|
||||
}
|
||||
if !scope.accepts(RolloutLocation::Archived) {
|
||||
return Ok(None);
|
||||
}
|
||||
let path = find_archived_thread_path_by_id_str(
|
||||
store.config.codex_home.as_path(),
|
||||
&thread_id.to_string(),
|
||||
state_db_ctx.as_deref(),
|
||||
)
|
||||
.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,
|
||||
None => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
async fn resolve_path_in_scope(
|
||||
store: &LocalThreadStore,
|
||||
thread_id: ThreadId,
|
||||
path: PathBuf,
|
||||
scope: LookupScope,
|
||||
) -> ThreadStoreResult<Option<ResolvedThreadRollout>> {
|
||||
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)
|
||||
}
|
||||
|
||||
fn location_for_path(store: &LocalThreadStore, path: &std::path::Path) -> RolloutLocation {
|
||||
if rollout_path_is_archived(store.config.codex_home.as_path(), path) {
|
||||
RolloutLocation::Archived
|
||||
} else {
|
||||
RolloutLocation::Unarchived
|
||||
}
|
||||
}
|
||||
|
||||
async fn resolve_path(
|
||||
thread_id: ThreadId,
|
||||
path: PathBuf,
|
||||
location: RolloutLocation,
|
||||
) -> ThreadStoreResult<ResolvedThreadRollout> {
|
||||
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,
|
||||
thread_id: ThreadId,
|
||||
history_mode: ThreadHistoryMode,
|
||||
) -> ThreadStoreResult<ThreadId> {
|
||||
Ok(match codex_rollout::rollout_id_from_path(path) {
|
||||
Some(rollout_id) => rollout_id,
|
||||
None => {
|
||||
if history_mode == ThreadHistoryMode::Paginated {
|
||||
return Err(ThreadStoreError::InvalidRequest {
|
||||
message: format!(
|
||||
"paginated rollout path `{}` does not have a canonical rollout filename",
|
||||
path.display()
|
||||
),
|
||||
});
|
||||
}
|
||||
thread_id
|
||||
}
|
||||
})
|
||||
}
|
||||
99
codex-rs/thread-store/src/local/thread_sections.rs
Normal file
99
codex-rs/thread-store/src/local/thread_sections.rs
Normal file
@@ -0,0 +1,99 @@
|
||||
use super::LocalThreadStore;
|
||||
use crate::CreateThreadSectionParams;
|
||||
use crate::DeleteThreadSectionParams;
|
||||
use crate::ListThreadSectionsParams;
|
||||
use crate::RenameThreadSectionParams;
|
||||
use crate::StoredThreadSection;
|
||||
use crate::StoredThreadSectionsPage;
|
||||
use crate::ThreadStoreError;
|
||||
use crate::ThreadStoreResult;
|
||||
use codex_rollout::StateDbHandle;
|
||||
|
||||
pub(super) async fn list_thread_sections(
|
||||
store: &LocalThreadStore,
|
||||
params: ListThreadSectionsParams,
|
||||
) -> ThreadStoreResult<StoredThreadSectionsPage> {
|
||||
let state_db = state_db(store, "threadSection/list")?;
|
||||
let page = state_db
|
||||
.list_thread_sections(params.cursor.as_deref(), params.limit)
|
||||
.await
|
||||
.map_err(|err| section_error("list", err))?;
|
||||
|
||||
Ok(StoredThreadSectionsPage {
|
||||
sections: page
|
||||
.sections
|
||||
.into_iter()
|
||||
.map(|section| StoredThreadSection {
|
||||
id: section.id,
|
||||
name: section.name,
|
||||
appearance: section.appearance,
|
||||
})
|
||||
.collect(),
|
||||
next_cursor: page.next_cursor,
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) async fn create_thread_section(
|
||||
store: &LocalThreadStore,
|
||||
params: CreateThreadSectionParams,
|
||||
) -> ThreadStoreResult<StoredThreadSection> {
|
||||
let state_db = state_db(store, "threadSection/create")?;
|
||||
let section = state_db
|
||||
.create_thread_section(¶ms.name, params.appearance)
|
||||
.await
|
||||
.map_err(|err| section_error("create", err))?;
|
||||
|
||||
Ok(StoredThreadSection {
|
||||
id: section.id,
|
||||
name: section.name,
|
||||
appearance: section.appearance,
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) async fn rename_thread_section(
|
||||
store: &LocalThreadStore,
|
||||
params: RenameThreadSectionParams,
|
||||
) -> ThreadStoreResult<Option<StoredThreadSection>> {
|
||||
let state_db = state_db(store, "threadSection/update")?;
|
||||
let section = state_db
|
||||
.rename_thread_section(¶ms.section_id, ¶ms.name, params.appearance)
|
||||
.await
|
||||
.map_err(|err| section_error("update", err))?;
|
||||
|
||||
Ok(section.map(|section| StoredThreadSection {
|
||||
id: section.id,
|
||||
name: section.name,
|
||||
appearance: section.appearance,
|
||||
}))
|
||||
}
|
||||
|
||||
pub(super) async fn delete_thread_section(
|
||||
store: &LocalThreadStore,
|
||||
params: DeleteThreadSectionParams,
|
||||
) -> ThreadStoreResult<bool> {
|
||||
let state_db = state_db(store, "threadSection/delete")?;
|
||||
state_db
|
||||
.delete_thread_section(¶ms.section_id)
|
||||
.await
|
||||
.map_err(|err| section_error("delete", err))
|
||||
}
|
||||
|
||||
fn state_db<'store>(
|
||||
store: &'store LocalThreadStore,
|
||||
operation: &'static str,
|
||||
) -> ThreadStoreResult<&'store StateDbHandle> {
|
||||
store
|
||||
.state_db
|
||||
.as_ref()
|
||||
.ok_or(ThreadStoreError::Unsupported { operation })
|
||||
}
|
||||
|
||||
fn section_error(operation: &str, error: impl std::fmt::Display) -> ThreadStoreError {
|
||||
ThreadStoreError::Internal {
|
||||
message: format!("failed to {operation} thread section: {error}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "thread_sections_tests.rs"]
|
||||
mod tests;
|
||||
84
codex-rs/thread-store/src/local/thread_sections_tests.rs
Normal file
84
codex-rs/thread-store/src/local/thread_sections_tests.rs
Normal file
@@ -0,0 +1,84 @@
|
||||
use super::LocalThreadStore;
|
||||
use crate::CreateThreadSectionParams;
|
||||
use crate::DeleteThreadSectionParams;
|
||||
use crate::ListThreadSectionsParams;
|
||||
use crate::RenameThreadSectionParams;
|
||||
use crate::StoredThreadSection;
|
||||
use crate::ThreadStore;
|
||||
use crate::ThreadStoreError;
|
||||
use crate::local::test_support::test_config;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[tokio::test]
|
||||
async fn local_thread_sections_require_sqlite_and_preserve_section_identity() {
|
||||
let home = tempfile::TempDir::new().expect("temp dir");
|
||||
let config = test_config(home.path());
|
||||
let unsupported_store = LocalThreadStore::new(config.clone(), /*state_db*/ None);
|
||||
assert!(!unsupported_store.supports_thread_sections());
|
||||
assert!(matches!(
|
||||
unsupported_store
|
||||
.create_thread_section(CreateThreadSectionParams {
|
||||
name: "Research".to_string(),
|
||||
appearance: None,
|
||||
})
|
||||
.await,
|
||||
Err(ThreadStoreError::Unsupported {
|
||||
operation: "threadSection/create"
|
||||
})
|
||||
));
|
||||
|
||||
let runtime = codex_state::StateRuntime::init(
|
||||
config.sqlite.clone(),
|
||||
config.default_model_provider_id.clone(),
|
||||
)
|
||||
.await
|
||||
.expect("state db should initialize");
|
||||
let store = LocalThreadStore::new(config, Some(runtime));
|
||||
assert!(store.supports_thread_sections());
|
||||
|
||||
let appearance = codex_state::ThreadSectionAppearance {
|
||||
icon: Some("folder".to_string()),
|
||||
color: Some("purple".to_string()),
|
||||
};
|
||||
let section = store
|
||||
.create_thread_section(CreateThreadSectionParams {
|
||||
name: "Research".to_string(),
|
||||
appearance: Some(appearance.clone()),
|
||||
})
|
||||
.await
|
||||
.expect("create section");
|
||||
let sections = store
|
||||
.list_thread_sections(ListThreadSectionsParams {
|
||||
cursor: None,
|
||||
limit: 10,
|
||||
})
|
||||
.await
|
||||
.expect("list sections");
|
||||
assert!(sections.sections.contains(§ion));
|
||||
|
||||
let renamed = store
|
||||
.rename_thread_section(RenameThreadSectionParams {
|
||||
section_id: section.id.clone(),
|
||||
name: "Planning".to_string(),
|
||||
appearance: None,
|
||||
})
|
||||
.await
|
||||
.expect("rename section");
|
||||
assert_eq!(
|
||||
renamed,
|
||||
Some(StoredThreadSection {
|
||||
id: section.id.clone(),
|
||||
name: "Planning".to_string(),
|
||||
appearance: Some(appearance),
|
||||
})
|
||||
);
|
||||
|
||||
assert!(
|
||||
store
|
||||
.delete_thread_section(DeleteThreadSectionParams {
|
||||
section_id: section.id,
|
||||
})
|
||||
.await
|
||||
.expect("delete section")
|
||||
);
|
||||
}
|
||||
203
codex-rs/thread-store/src/local/timestamp_metadata_tests.rs
Normal file
203
codex-rs/thread-store/src/local/timestamp_metadata_tests.rs
Normal file
@@ -0,0 +1,203 @@
|
||||
//! Verifies narrow SQLite activity updates preserve metadata and repair fallbacks.
|
||||
|
||||
use super::test_support::test_config;
|
||||
use super::test_support::write_session_file_with_history_mode;
|
||||
use super::*;
|
||||
use chrono::Utc;
|
||||
use codex_protocol::protocol::TokenUsage;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[tokio::test]
|
||||
async fn activity_updates_repair_missing_rows_then_touch_only_activity_columns() {
|
||||
for history_mode in [ThreadHistoryMode::Legacy, ThreadHistoryMode::Paginated] {
|
||||
let home = tempfile::TempDir::new().expect("temp dir");
|
||||
let config = test_config(home.path());
|
||||
let runtime = codex_state::StateRuntime::init(
|
||||
config.sqlite.clone(),
|
||||
config.default_model_provider_id.clone(),
|
||||
)
|
||||
.await
|
||||
.expect("initialize state db");
|
||||
let pool = config
|
||||
.sqlite
|
||||
.open_read_write_pool(&config.sqlite.state_db_path())
|
||||
.await
|
||||
.expect("open SQL observer");
|
||||
let store = LocalThreadStore::new(config, Some(runtime.clone()));
|
||||
let id = uuid::Uuid::new_v4();
|
||||
let thread_id = ThreadId::from_string(&id.to_string()).expect("thread id");
|
||||
let path = write_session_file_with_history_mode(
|
||||
home.path(),
|
||||
"2025-01-03T12-00-00",
|
||||
id,
|
||||
history_mode,
|
||||
)
|
||||
.expect("write canonical history");
|
||||
let mut params = UpdateThreadMetadataParams {
|
||||
thread_id,
|
||||
patch: ThreadMetadataPatch {
|
||||
updated_at: Some(Utc::now()),
|
||||
..Default::default()
|
||||
},
|
||||
include_archived: false,
|
||||
};
|
||||
// Missing rows must still be reconstructed from their canonical history.
|
||||
store
|
||||
.update_thread_metadata(params.clone())
|
||||
.await
|
||||
.expect("reconstruct missing metadata");
|
||||
let mut expected = runtime
|
||||
.get_thread(thread_id)
|
||||
.await
|
||||
.expect("read repaired metadata")
|
||||
.expect("repaired row");
|
||||
assert_eq!(
|
||||
(&expected.rollout_path, expected.history_mode),
|
||||
(&path, history_mode)
|
||||
);
|
||||
sqlx::raw_sql(
|
||||
r#"
|
||||
CREATE TABLE timestamp_writes(kind TEXT);
|
||||
CREATE TRIGGER count_timestamp AFTER UPDATE OF updated_at_ms ON threads
|
||||
BEGIN INSERT INTO timestamp_writes VALUES ('timestamp'); END;
|
||||
CREATE TRIGGER count_full_row AFTER UPDATE OF title ON threads
|
||||
BEGIN INSERT INTO timestamp_writes VALUES ('full'); END;
|
||||
"#,
|
||||
)
|
||||
.execute(&pool)
|
||||
.await
|
||||
.expect("install write counters");
|
||||
|
||||
store
|
||||
.update_thread_metadata(params.clone())
|
||||
.await
|
||||
.expect("touch existing metadata");
|
||||
let actual = runtime
|
||||
.get_thread(thread_id)
|
||||
.await
|
||||
.expect("read touched metadata")
|
||||
.expect("touched row");
|
||||
assert!(actual.updated_at > expected.updated_at);
|
||||
expected.updated_at = actual.updated_at;
|
||||
assert_eq!(actual, expected);
|
||||
let writes: Vec<String> =
|
||||
sqlx::query_scalar("SELECT kind FROM timestamp_writes ORDER BY rowid")
|
||||
.fetch_all(&pool)
|
||||
.await
|
||||
.expect("read write counters");
|
||||
assert_eq!(writes, vec!["timestamp"]);
|
||||
|
||||
params.patch.token_usage = Some(TokenUsage {
|
||||
total_tokens: 123,
|
||||
..Default::default()
|
||||
});
|
||||
store
|
||||
.update_thread_metadata(params.clone())
|
||||
.await
|
||||
.expect("update token usage");
|
||||
let actual = runtime
|
||||
.get_thread(thread_id)
|
||||
.await
|
||||
.expect("read token usage")
|
||||
.expect("updated row");
|
||||
assert!(actual.updated_at > expected.updated_at);
|
||||
expected.updated_at = actual.updated_at;
|
||||
expected.tokens_used = 123;
|
||||
assert_eq!(actual, expected);
|
||||
|
||||
store
|
||||
.stage_pending_thread_metadata(
|
||||
thread_id,
|
||||
ThreadMetadataPatch {
|
||||
model: Some("staged-model".to_string()),
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect("stage metadata");
|
||||
store
|
||||
.update_thread_metadata(params.clone())
|
||||
.await
|
||||
.expect("apply staged metadata");
|
||||
let actual = runtime
|
||||
.get_thread(thread_id)
|
||||
.await
|
||||
.expect("read staged metadata")
|
||||
.expect("updated row");
|
||||
expected.model = Some("staged-model".to_string());
|
||||
expected.updated_at = actual.updated_at;
|
||||
assert_eq!(actual, expected);
|
||||
assert!(
|
||||
store
|
||||
.pending_thread_metadata
|
||||
.lock(thread_id)
|
||||
.await
|
||||
.is_none()
|
||||
);
|
||||
let mut writes: Vec<String> = sqlx::query_scalar("SELECT kind FROM timestamp_writes")
|
||||
.fetch_all(&pool)
|
||||
.await
|
||||
.expect("read write counters");
|
||||
writes.sort();
|
||||
assert_eq!(writes, vec!["full", "timestamp", "timestamp", "timestamp"]);
|
||||
|
||||
sqlx::query(
|
||||
"UPDATE threads SET preview = '', first_user_message = 'older message' WHERE id = ?",
|
||||
)
|
||||
.bind(thread_id.to_string())
|
||||
.execute(&pool)
|
||||
.await
|
||||
.expect("prepare legacy preview");
|
||||
store
|
||||
.update_thread_metadata(params.clone())
|
||||
.await
|
||||
.expect("backfill preview");
|
||||
let repaired = runtime
|
||||
.get_thread(thread_id)
|
||||
.await
|
||||
.expect("read preview")
|
||||
.expect("thread");
|
||||
assert_eq!(repaired.preview.as_deref(), Some("older message"));
|
||||
|
||||
let parent = ThreadId::new();
|
||||
let source = serde_json::json!({
|
||||
"subagent": { "thread_spawn": { "parent_thread_id": parent, "depth": 1 } }
|
||||
});
|
||||
sqlx::query("UPDATE threads SET source = ? WHERE id = ?")
|
||||
.bind(source.to_string())
|
||||
.bind(thread_id.to_string())
|
||||
.execute(&pool)
|
||||
.await
|
||||
.expect("prepare child missing its spawn edge");
|
||||
sqlx::raw_sql(
|
||||
"DELETE FROM timestamp_writes;
|
||||
CREATE TRIGGER count_edge_attempts BEFORE INSERT ON thread_spawn_edges
|
||||
BEGIN INSERT INTO timestamp_writes VALUES ('edge'); END;",
|
||||
)
|
||||
.execute(&pool)
|
||||
.await
|
||||
.expect("track spawn-edge writes");
|
||||
store
|
||||
.update_thread_metadata(params.clone())
|
||||
.await
|
||||
.expect("repair missing edge");
|
||||
assert_eq!(
|
||||
runtime
|
||||
.list_thread_spawn_children(parent)
|
||||
.await
|
||||
.expect("children"),
|
||||
vec![thread_id]
|
||||
);
|
||||
store
|
||||
.update_thread_metadata(params)
|
||||
.await
|
||||
.expect("update indexed child");
|
||||
let writes: Vec<String> =
|
||||
sqlx::query_scalar("SELECT kind FROM timestamp_writes ORDER BY kind")
|
||||
.fetch_all(&pool)
|
||||
.await
|
||||
.expect("read child write counters");
|
||||
assert_eq!(writes, vec!["edge", "full", "timestamp", "timestamp"]);
|
||||
pool.close().await;
|
||||
}
|
||||
}
|
||||
373
codex-rs/thread-store/src/local/unarchive_thread.rs
Normal file
373
codex-rs/thread-store/src/local/unarchive_thread.rs
Normal file
@@ -0,0 +1,373 @@
|
||||
use super::LocalThreadStore;
|
||||
use super::helpers::owned_rollout_paths_from_index;
|
||||
use super::helpers::restore_rollout_moves;
|
||||
use super::helpers::rollout_path_is_archived;
|
||||
use super::helpers::scoped_rollout_path;
|
||||
use super::helpers::touch_modified_time;
|
||||
use super::helpers::validated_rollout_file_name;
|
||||
use crate::ArchiveThreadParams;
|
||||
use crate::ReadThreadParams;
|
||||
use crate::StoredThread;
|
||||
use crate::ThreadStoreError;
|
||||
use crate::ThreadStoreResult;
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_rollout::RolloutReferenceIndex;
|
||||
use codex_rollout::rollout_date_parts;
|
||||
use tracing::warn;
|
||||
|
||||
use super::thread_rollout_resolver;
|
||||
use super::thread_rollout_resolver::RolloutLocation;
|
||||
|
||||
pub(super) async fn unarchive_threads(
|
||||
store: &LocalThreadStore,
|
||||
params: ArchiveThreadParams,
|
||||
descendant_thread_ids: Vec<ThreadId>,
|
||||
) -> ThreadStoreResult<(StoredThread, Vec<ThreadId>)> {
|
||||
let parent_thread_id = params.thread_id;
|
||||
let requested_ids: Vec<_> = std::iter::once(parent_thread_id)
|
||||
.chain(descendant_thread_ids)
|
||||
.collect();
|
||||
// Keep the index stable against other mutations in this store, using archive's lock order.
|
||||
let mut lock_thread_ids = requested_ids.clone();
|
||||
lock_thread_ids.sort_unstable_by_key(ToString::to_string);
|
||||
lock_thread_ids.dedup();
|
||||
let mut _lifecycle_guards = Vec::with_capacity(lock_thread_ids.len());
|
||||
for thread_id in lock_thread_ids {
|
||||
_lifecycle_guards.push(store.live_writer_locks.lock_lifecycle(thread_id).await);
|
||||
}
|
||||
// Hold ownership while discovering and moving rollouts, as archive does. A busy
|
||||
// descendant remains a best-effort failure rather than blocking the parent's restore.
|
||||
let mut thread_ids = Vec::new();
|
||||
let mut _writer_guards = Vec::new();
|
||||
for (index, thread_id) in requested_ids.into_iter().enumerate() {
|
||||
match store.acquire_writer_lock(thread_id) {
|
||||
Ok(guard) => {
|
||||
_writer_guards.push(guard);
|
||||
thread_ids.push(thread_id);
|
||||
}
|
||||
Err(err) if index == 0 => return Err(err),
|
||||
Err(err) => warn!("failed to unarchive spawned descendant thread {thread_id}: {err}"),
|
||||
}
|
||||
}
|
||||
// Like archive, discover candidate rollouts once for the entire subtree.
|
||||
let reference_index = RolloutReferenceIndex::scan_archived_threads(
|
||||
store.config.codex_home.as_path(),
|
||||
&thread_ids,
|
||||
)
|
||||
.await
|
||||
.map_err(|err| ThreadStoreError::Internal {
|
||||
message: format!("failed to scan thread rollout files: {err}"),
|
||||
})?;
|
||||
unarchive_thread_with_index(store, parent_thread_id, &reference_index)
|
||||
.await?
|
||||
.ok_or_else(|| ThreadStoreError::InvalidRequest {
|
||||
message: format!("no archived rollout found for thread id {parent_thread_id}"),
|
||||
})?;
|
||||
let root = super::read_thread::read_thread(
|
||||
store,
|
||||
ReadThreadParams {
|
||||
thread_id: parent_thread_id,
|
||||
include_archived: false,
|
||||
include_history: false,
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
let mut restored = vec![parent_thread_id];
|
||||
for thread_id in thread_ids.into_iter().skip(1) {
|
||||
match unarchive_thread_with_index(store, thread_id, &reference_index).await {
|
||||
Ok(Some(thread_id)) => restored.push(thread_id),
|
||||
Ok(None) => {}
|
||||
Err(err) => warn!("failed to unarchive spawned descendant thread {thread_id}: {err}"),
|
||||
}
|
||||
}
|
||||
Ok((root, restored))
|
||||
}
|
||||
|
||||
async fn unarchive_thread_with_index(
|
||||
store: &LocalThreadStore,
|
||||
thread_id: ThreadId,
|
||||
reference_index: &RolloutReferenceIndex,
|
||||
) -> ThreadStoreResult<Option<ThreadId>> {
|
||||
let state_db_ctx = store.state_db().await;
|
||||
let Some(selected_archived_path) =
|
||||
thread_rollout_resolver::resolve_current_including_archived(store, thread_id)
|
||||
.await?
|
||||
.filter(|resolved| resolved.location == RolloutLocation::Archived)
|
||||
.map(|resolved| resolved.path)
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
|
||||
let mut rollout_paths = owned_rollout_paths_from_index(reference_index, thread_id);
|
||||
if !rollout_paths.contains(&selected_archived_path) {
|
||||
rollout_paths.push(selected_archived_path.clone());
|
||||
}
|
||||
let mut restored_path = None;
|
||||
let mut rollout_moves = Vec::new();
|
||||
for rollout_path in rollout_paths {
|
||||
if !rollout_path_is_archived(store.config.codex_home.as_path(), rollout_path.as_path()) {
|
||||
continue;
|
||||
}
|
||||
let canonical_archived_path = scoped_rollout_path(
|
||||
store
|
||||
.config
|
||||
.codex_home
|
||||
.join(codex_rollout::ARCHIVED_SESSIONS_SUBDIR),
|
||||
rollout_path.as_path(),
|
||||
"archived",
|
||||
)?;
|
||||
let file_name =
|
||||
validated_rollout_file_name(canonical_archived_path.as_path(), rollout_path.as_path())?;
|
||||
let Some((year, month, day)) = rollout_date_parts(&file_name) else {
|
||||
return Err(ThreadStoreError::InvalidRequest {
|
||||
message: format!(
|
||||
"rollout path `{}` missing filename timestamp",
|
||||
rollout_path.display()
|
||||
),
|
||||
});
|
||||
};
|
||||
let dest_dir = store
|
||||
.config
|
||||
.codex_home
|
||||
.join(codex_rollout::SESSIONS_SUBDIR)
|
||||
.join(year)
|
||||
.join(month)
|
||||
.join(day);
|
||||
std::fs::create_dir_all(&dest_dir).map_err(|err| ThreadStoreError::Internal {
|
||||
message: format!("failed to unarchive thread: {err}"),
|
||||
})?;
|
||||
let destination = dest_dir.join(&file_name);
|
||||
if rollout_path == selected_archived_path {
|
||||
restored_path = Some(destination.clone());
|
||||
}
|
||||
if !rollout_moves
|
||||
.iter()
|
||||
.any(|(source, _)| source == &canonical_archived_path)
|
||||
{
|
||||
rollout_moves.push((canonical_archived_path, destination));
|
||||
}
|
||||
}
|
||||
let restored_path = restored_path.ok_or_else(|| ThreadStoreError::Internal {
|
||||
message: format!("failed to unarchive selected rollout for thread {thread_id}"),
|
||||
})?;
|
||||
|
||||
for (index, (source, destination)) in rollout_moves.iter().enumerate() {
|
||||
if let Err(err) = std::fs::rename(source, destination) {
|
||||
if let Err(restore_err) = restore_rollout_moves(&rollout_moves[..index]) {
|
||||
return Err(ThreadStoreError::Internal {
|
||||
message: format!(
|
||||
"failed to unarchive thread: {err}; failed to restore moved rollouts: {restore_err}"
|
||||
),
|
||||
});
|
||||
}
|
||||
return Err(ThreadStoreError::Internal {
|
||||
message: format!("failed to unarchive thread: {err}"),
|
||||
});
|
||||
}
|
||||
}
|
||||
if let Err(err) = touch_modified_time(restored_path.as_path()) {
|
||||
if let Err(restore_err) = restore_rollout_moves(&rollout_moves) {
|
||||
return Err(ThreadStoreError::Internal {
|
||||
message: format!(
|
||||
"failed to update unarchived thread timestamp: {err}; failed to restore moved rollouts: {restore_err}"
|
||||
),
|
||||
});
|
||||
}
|
||||
return Err(ThreadStoreError::Internal {
|
||||
message: format!("failed to update unarchived thread timestamp: {err}"),
|
||||
});
|
||||
}
|
||||
|
||||
if let Some(ctx) = state_db_ctx
|
||||
&& let Err(err) = ctx
|
||||
.mark_unarchived(thread_id, restored_path.as_path())
|
||||
.await
|
||||
{
|
||||
if let Err(restore_err) = restore_rollout_moves(&rollout_moves) {
|
||||
return Err(ThreadStoreError::Internal {
|
||||
message: format!(
|
||||
"failed to update unarchived thread metadata: {err}; failed to restore moved rollouts: {restore_err}"
|
||||
),
|
||||
});
|
||||
}
|
||||
return Err(ThreadStoreError::Internal {
|
||||
message: format!("failed to update unarchived thread metadata: {err}"),
|
||||
});
|
||||
}
|
||||
|
||||
// Descendants need only their restored id for notifications, not metadata hydration.
|
||||
Ok(Some(thread_id))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use chrono::Utc;
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::protocol::SessionSource;
|
||||
use codex_utils_absolute_path::test_support::PathExt;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tempfile::TempDir;
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::*;
|
||||
use crate::ThreadStore;
|
||||
use crate::local::LocalThreadStore;
|
||||
use crate::local::test_support::test_config;
|
||||
use crate::local::test_support::write_archived_session_file;
|
||||
use crate::local::test_support::write_session_file;
|
||||
|
||||
#[tokio::test]
|
||||
async fn unarchive_thread_restores_rollout_and_returns_updated_thread() {
|
||||
let home = TempDir::new().expect("temp dir");
|
||||
let store = LocalThreadStore::new(test_config(home.path()), /*state_db*/ None);
|
||||
let uuid = Uuid::from_u128(203);
|
||||
let thread_id = ThreadId::from_string(&uuid.to_string()).expect("valid thread id");
|
||||
let archived_path = write_archived_session_file(home.path(), "2025-01-03T13-00-00", uuid)
|
||||
.expect("archived session file");
|
||||
|
||||
let thread = store
|
||||
.unarchive_thread(ArchiveThreadParams { thread_id })
|
||||
.await
|
||||
.expect("unarchive thread");
|
||||
|
||||
assert!(!archived_path.exists());
|
||||
let restored_path = home
|
||||
.path()
|
||||
.join("sessions/2025/01/03")
|
||||
.join(archived_path.file_name().expect("file name"));
|
||||
assert!(restored_path.exists());
|
||||
assert_eq!(thread.thread_id, thread_id);
|
||||
assert_eq!(thread.rollout_path, Some(restored_path));
|
||||
assert_eq!(thread.archived_at, None);
|
||||
assert_eq!(thread.preview, "Archived user message");
|
||||
assert_eq!(
|
||||
thread.first_user_message.as_deref(),
|
||||
Some("Archived user message")
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn unarchive_thread_rejects_a_cross_process_writer() {
|
||||
let home = TempDir::new().expect("temp dir");
|
||||
let store = LocalThreadStore::new(test_config(home.path()), /*state_db*/ None);
|
||||
let owner = LocalThreadStore::new(test_config(home.path()), /*state_db*/ None);
|
||||
let uuid = Uuid::from_u128(205);
|
||||
let thread_id = ThreadId::from_string(&uuid.to_string()).expect("valid thread id");
|
||||
let archived_path = write_archived_session_file(home.path(), "2025-01-03T13-00-00", uuid)
|
||||
.expect("archived session file");
|
||||
let writer_guard = owner
|
||||
.acquire_writer_lock(thread_id)
|
||||
.expect("acquire writer lock");
|
||||
|
||||
let error = store
|
||||
.unarchive_thread(ArchiveThreadParams { thread_id })
|
||||
.await
|
||||
.expect_err("active writer should block unarchive");
|
||||
|
||||
assert!(matches!(error, ThreadStoreError::Conflict { .. }));
|
||||
assert!(archived_path.exists());
|
||||
drop(writer_guard);
|
||||
store
|
||||
.unarchive_thread(ArchiveThreadParams { thread_id })
|
||||
.await
|
||||
.expect("unarchive after writer exits");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn unarchive_thread_deduplicates_rollout_paths_and_updates_sqlite_metadata() {
|
||||
let home = TempDir::new().expect("temp dir");
|
||||
let config = test_config(home.path());
|
||||
let uuid = Uuid::from_u128(204);
|
||||
let thread_id = ThreadId::from_string(&uuid.to_string()).expect("valid thread id");
|
||||
let archived_path = write_archived_session_file(home.path(), "2025-01-03T13-00-00", uuid)
|
||||
.expect("archived session file");
|
||||
let alternate_directory = archived_path
|
||||
.parent()
|
||||
.expect("archived session directory")
|
||||
.join("alternate");
|
||||
std::fs::create_dir(&alternate_directory).expect("alternate archived session directory");
|
||||
let selected_archived_path = alternate_directory
|
||||
.join("..")
|
||||
.join(archived_path.file_name().expect("file name"));
|
||||
let runtime = codex_state::StateRuntime::init(
|
||||
codex_state::SqliteConfig::new_for_testing(home.path().abs()),
|
||||
config.default_model_provider_id.clone(),
|
||||
)
|
||||
.await
|
||||
.expect("state db should initialize");
|
||||
let store = LocalThreadStore::new(config.clone(), Some(runtime.clone()));
|
||||
runtime
|
||||
.mark_backfill_complete(/*last_watermark*/ None)
|
||||
.await
|
||||
.expect("backfill should be complete");
|
||||
let mut builder = codex_state::ThreadMetadataBuilder::new(
|
||||
thread_id,
|
||||
selected_archived_path,
|
||||
Utc::now(),
|
||||
SessionSource::Cli,
|
||||
);
|
||||
builder.model_provider = Some(config.default_model_provider_id.clone());
|
||||
builder.cwd = home.path().to_path_buf();
|
||||
builder.cli_version = Some("test_version".to_string());
|
||||
let mut metadata = builder.build(config.default_model_provider_id.as_str());
|
||||
metadata.archived_at = Some(metadata.updated_at);
|
||||
metadata.section = Some(codex_state::ThreadSection {
|
||||
id: codex_state::PINNED_THREAD_SECTION_ID.to_string(),
|
||||
name: codex_state::PINNED_THREAD_SECTION_NAME.to_string(),
|
||||
appearance: None,
|
||||
});
|
||||
runtime
|
||||
.upsert_thread(&metadata)
|
||||
.await
|
||||
.expect("state db upsert should succeed");
|
||||
|
||||
let child_uuid = Uuid::from_u128(208);
|
||||
let child_id = ThreadId::from_string(&child_uuid.to_string()).expect("valid child id");
|
||||
let child_path =
|
||||
write_archived_session_file(home.path(), "2025-01-03T13-00-00", child_uuid)
|
||||
.expect("child rollout");
|
||||
let mut child_metadata = metadata.clone();
|
||||
child_metadata.id = child_id;
|
||||
child_metadata.rollout_path = child_path.clone();
|
||||
runtime
|
||||
.upsert_thread(&child_metadata)
|
||||
.await
|
||||
.expect("child metadata");
|
||||
std::fs::write(&child_path, "invalid session metadata\n").expect("malformed child rollout");
|
||||
|
||||
let active_uuid = Uuid::from_u128(209);
|
||||
let active_id = ThreadId::from_string(&active_uuid.to_string()).expect("valid active id");
|
||||
let active_path = write_session_file(home.path(), "2025-01-03T13-00-00", active_uuid)
|
||||
.expect("active rollout");
|
||||
let (unarchived, restored_ids) = store
|
||||
.unarchive_threads(ArchiveThreadParams { thread_id }, vec![active_id, child_id])
|
||||
.await
|
||||
.expect("unarchive threads");
|
||||
assert!(active_path.is_file());
|
||||
assert_eq!(restored_ids, vec![thread_id, child_id]);
|
||||
assert!(!child_path.exists());
|
||||
assert_eq!(unarchived.section, metadata.section);
|
||||
|
||||
let restored_path = home
|
||||
.path()
|
||||
.join("sessions/2025/01/03")
|
||||
.join(archived_path.file_name().expect("file name"));
|
||||
let updated = runtime
|
||||
.get_thread(thread_id)
|
||||
.await
|
||||
.expect("state db read should succeed")
|
||||
.expect("thread metadata should exist");
|
||||
assert_eq!(updated.rollout_path, restored_path);
|
||||
assert_eq!(updated.archived_at, None);
|
||||
assert_eq!(updated.recency_at, metadata.recency_at);
|
||||
assert_eq!(updated.section, metadata.section);
|
||||
|
||||
let child = runtime.get_thread(child_id).await.unwrap().unwrap();
|
||||
assert_eq!(child.archived_at, None);
|
||||
assert_eq!(
|
||||
child.rollout_path,
|
||||
restored_path.with_file_name(child_path.file_name().unwrap())
|
||||
);
|
||||
assert!(child.rollout_path.is_file());
|
||||
}
|
||||
}
|
||||
2477
codex-rs/thread-store/src/local/update_thread_metadata.rs
Normal file
2477
codex-rs/thread-store/src/local/update_thread_metadata.rs
Normal file
File diff suppressed because it is too large
Load Diff
67
codex-rs/thread-store/src/local_history_account.rs
Normal file
67
codex-rs/thread-store/src/local_history_account.rs
Normal file
@@ -0,0 +1,67 @@
|
||||
//! Account matching for local discovery. Pre-enforcement threads remain shared.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use codex_protocol::ThreadId;
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
|
||||
/// The current ChatGPT identity for account-scoped local history discovery.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct LocalHistoryAccount {
|
||||
pub user_id: Option<String>,
|
||||
pub account_id: Option<String>,
|
||||
}
|
||||
|
||||
impl LocalHistoryAccount {
|
||||
/// Newly scoped threads must match each creator ID; older history stays shared.
|
||||
/// Reuse `original_paths` only within the page identified by `page_thread_ids`.
|
||||
pub async fn includes(
|
||||
&self,
|
||||
codex_home: &Path,
|
||||
thread_id: ThreadId,
|
||||
rollout_path: Option<&Path>,
|
||||
page_thread_ids: &[ThreadId],
|
||||
original_paths: &mut Option<HashMap<ThreadId, PathBuf>>,
|
||||
) -> bool {
|
||||
let Some(path) = rollout_path else {
|
||||
return false;
|
||||
};
|
||||
let Ok(header) = codex_rollout::read_session_meta_line(path).await else {
|
||||
return false;
|
||||
};
|
||||
let mut meta = header.meta;
|
||||
if meta.id != thread_id {
|
||||
return false;
|
||||
}
|
||||
if !meta.account_scoped
|
||||
&& codex_rollout::rollout_id_from_path(path).is_some_and(|id| id != thread_id)
|
||||
{
|
||||
// An older binary can drop the marker on revert; consult the original rollout.
|
||||
// Resolve the page together so each reverted thread does not rescan all history.
|
||||
if original_paths.is_none() {
|
||||
*original_paths = Some(
|
||||
codex_rollout::find_rollout_paths_by_rollout_ids(codex_home, page_thread_ids)
|
||||
.await,
|
||||
);
|
||||
}
|
||||
let Some(original) = original_paths
|
||||
.as_ref()
|
||||
.and_then(|paths| paths.get(&thread_id))
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
let Ok(header) = codex_rollout::read_session_meta_line(original).await else {
|
||||
return false;
|
||||
};
|
||||
meta = header.meta;
|
||||
}
|
||||
meta.id == thread_id
|
||||
&& (!meta.account_scoped
|
||||
|| ((meta.creator_user_id.is_none() || meta.creator_user_id == self.user_id)
|
||||
&& (meta.creator_account_id.is_none()
|
||||
|| meta.creator_account_id == self.account_id)))
|
||||
}
|
||||
}
|
||||
28
codex-rs/thread-store/src/original_history.rs
Normal file
28
codex-rs/thread-store/src/original_history.rs
Normal file
@@ -0,0 +1,28 @@
|
||||
//! Fixed ranges of original records for live, forward-only history consumers.
|
||||
//! Positions identify persisted source records; they do not acknowledge downstream writes.
|
||||
|
||||
use codex_protocol::protocol::HistoryPosition;
|
||||
use codex_rollout::RolloutItem;
|
||||
|
||||
/// Capture the current complete tail, optionally reading records after a saved position.
|
||||
/// This API deliberately provides no implicit backfill or restart recovery.
|
||||
pub enum OriginalHistoryRequest {
|
||||
/// Return only the current complete end position.
|
||||
Tail,
|
||||
/// Freeze the current complete tail and read originals after this position.
|
||||
/// Appends beyond that cutoff are excluded from the returned records.
|
||||
After(HistoryPosition),
|
||||
}
|
||||
|
||||
/// One original record and the exclusive position immediately after it.
|
||||
pub struct OriginalHistoryItem {
|
||||
pub item: RolloutItem,
|
||||
pub end: HistoryPosition,
|
||||
}
|
||||
|
||||
/// Original records in source order and their fixed upper boundary.
|
||||
/// A tail request returns no items. Reading never advances consumer progress.
|
||||
pub struct OriginalHistoryRead {
|
||||
pub items: Vec<OriginalHistoryItem>,
|
||||
pub end: HistoryPosition,
|
||||
}
|
||||
81
codex-rs/thread-store/src/projects.rs
Normal file
81
codex-rs/thread-store/src/projects.rs
Normal file
@@ -0,0 +1,81 @@
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use crate::SortDirection;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct StoredProjectRoot {
|
||||
pub path: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct StoredProject {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub roots: Vec<StoredProjectRoot>,
|
||||
pub metadata: BTreeMap<String, String>,
|
||||
pub position: i64,
|
||||
pub created_at_ms: i64,
|
||||
pub updated_at_ms: i64,
|
||||
pub recency_at_ms: Option<i64>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct StoredProjectsPage {
|
||||
pub projects: Vec<StoredProject>,
|
||||
pub next_cursor: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct ListProjectsParams {
|
||||
pub cursor: Option<String>,
|
||||
pub limit: usize,
|
||||
pub sort_key: codex_state::ProjectSortKey,
|
||||
pub sort_direction: SortDirection,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct CreateProjectParams {
|
||||
pub name: String,
|
||||
pub roots: Vec<StoredProjectRoot>,
|
||||
pub metadata: BTreeMap<String, String>,
|
||||
pub thread_ids: Vec<String>,
|
||||
pub idempotency_key: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct CreatedProject {
|
||||
pub project: StoredProject,
|
||||
pub created: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct UpdateProjectParams {
|
||||
pub project_id: String,
|
||||
pub name: Option<String>,
|
||||
pub roots: Option<Vec<StoredProjectRoot>>,
|
||||
pub metadata: Option<BTreeMap<String, String>>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct MoveProjectParams {
|
||||
pub project_id: String,
|
||||
pub before_project_id: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum ProjectMoveOutcome {
|
||||
Unchanged,
|
||||
Moved,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct UpdatedProject {
|
||||
pub project: StoredProject,
|
||||
pub changed: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct DeletedProject {
|
||||
pub affected_active_thread_ids: Vec<String>,
|
||||
pub affected_archived_thread_ids: Vec<String>,
|
||||
}
|
||||
158
codex-rs/thread-store/src/queue_store.rs
Normal file
158
codex-rs/thread-store/src/queue_store.rs
Normal file
@@ -0,0 +1,158 @@
|
||||
use std::fmt::Display;
|
||||
use std::future::Future;
|
||||
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_rollout::StateDbHandle;
|
||||
use codex_state::QueuedUserSubmissionRecord;
|
||||
use codex_state::SqliteQueueStore;
|
||||
|
||||
use crate::MAX_QUEUE_ITEMS;
|
||||
use crate::ThreadStoreError;
|
||||
use crate::ThreadStoreFuture;
|
||||
|
||||
/// Storage-neutral persistence for ordered, thread-scoped user messages.
|
||||
pub trait QueueStore: Send + Sync {
|
||||
/// Return a stable revision that changes when another connection updates the queue.
|
||||
fn change_version(&self) -> ThreadStoreFuture<'_, i64>;
|
||||
|
||||
/// Return changed, loaded thread IDs and their durable revisions after `revision`.
|
||||
fn changes_since<'a>(
|
||||
&'a self,
|
||||
revision: i64,
|
||||
thread_ids: &'a [ThreadId],
|
||||
) -> ThreadStoreFuture<'a, Vec<(ThreadId, i64)>>;
|
||||
|
||||
fn enqueue(
|
||||
&self,
|
||||
thread_id: ThreadId,
|
||||
payload: String,
|
||||
) -> ThreadStoreFuture<'_, QueuedUserSubmissionRecord>;
|
||||
|
||||
fn list_page(
|
||||
&self,
|
||||
thread_id: ThreadId,
|
||||
offset: usize,
|
||||
limit: usize,
|
||||
) -> ThreadStoreFuture<'_, Vec<QueuedUserSubmissionRecord>>;
|
||||
|
||||
fn update(
|
||||
&self,
|
||||
thread_id: ThreadId,
|
||||
item_id: String,
|
||||
payload: String,
|
||||
) -> ThreadStoreFuture<'_, Option<QueuedUserSubmissionRecord>>;
|
||||
|
||||
fn delete(&self, thread_id: ThreadId, item_id: String) -> ThreadStoreFuture<'_, bool>;
|
||||
|
||||
/// Atomically replace queue order with every current item ID exactly once.
|
||||
///
|
||||
/// Returns [`ThreadStoreError::InvalidRequest`] when `item_ids` is not a
|
||||
/// permutation of the complete queue.
|
||||
fn reorder(&self, thread_id: ThreadId, item_ids: Vec<String>) -> ThreadStoreFuture<'_, ()>;
|
||||
}
|
||||
|
||||
/// Adapts the local state runtime to the shared queue-storage interface.
|
||||
#[derive(Clone)]
|
||||
pub struct LocalQueueStore {
|
||||
state_db: StateDbHandle,
|
||||
}
|
||||
|
||||
impl LocalQueueStore {
|
||||
pub fn new(state_db: StateDbHandle) -> Self {
|
||||
Self { state_db }
|
||||
}
|
||||
|
||||
fn queue(&self) -> &SqliteQueueStore {
|
||||
self.state_db.thread_queue()
|
||||
}
|
||||
}
|
||||
|
||||
fn queue_future<'a, T, E>(
|
||||
future: impl Future<Output = Result<T, E>> + Send + 'a,
|
||||
) -> ThreadStoreFuture<'a, T>
|
||||
where
|
||||
T: Send + 'a,
|
||||
E: Display + Send + 'a,
|
||||
{
|
||||
Box::pin(async move {
|
||||
future.await.map_err(|error| ThreadStoreError::Internal {
|
||||
message: format!("queue storage failed: {error}"),
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
impl QueueStore for LocalQueueStore {
|
||||
fn change_version(&self) -> ThreadStoreFuture<'_, i64> {
|
||||
queue_future(self.queue().change_version())
|
||||
}
|
||||
|
||||
fn changes_since<'a>(
|
||||
&'a self,
|
||||
revision: i64,
|
||||
thread_ids: &'a [ThreadId],
|
||||
) -> ThreadStoreFuture<'a, Vec<(ThreadId, i64)>> {
|
||||
queue_future(self.queue().changes_since(revision, thread_ids))
|
||||
}
|
||||
|
||||
fn enqueue(
|
||||
&self,
|
||||
thread_id: ThreadId,
|
||||
payload: String,
|
||||
) -> ThreadStoreFuture<'_, QueuedUserSubmissionRecord> {
|
||||
Box::pin(async move {
|
||||
self.queue()
|
||||
.enqueue(thread_id, &payload)
|
||||
.await
|
||||
.map_err(|error| match error.downcast_ref::<sqlx::Error>() {
|
||||
Some(sqlx::Error::RowNotFound) => ThreadStoreError::InvalidRequest {
|
||||
message: format!(
|
||||
"queue cannot contain more than {MAX_QUEUE_ITEMS} submissions"
|
||||
),
|
||||
},
|
||||
_ => ThreadStoreError::Internal {
|
||||
message: format!("queue storage failed: {error}"),
|
||||
},
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
fn list_page(
|
||||
&self,
|
||||
thread_id: ThreadId,
|
||||
offset: usize,
|
||||
limit: usize,
|
||||
) -> ThreadStoreFuture<'_, Vec<QueuedUserSubmissionRecord>> {
|
||||
queue_future(self.queue().list_page(thread_id, offset, limit))
|
||||
}
|
||||
|
||||
fn update(
|
||||
&self,
|
||||
thread_id: ThreadId,
|
||||
item_id: String,
|
||||
payload: String,
|
||||
) -> ThreadStoreFuture<'_, Option<QueuedUserSubmissionRecord>> {
|
||||
queue_future(async move { self.queue().update(thread_id, &item_id, &payload).await })
|
||||
}
|
||||
|
||||
fn delete(&self, thread_id: ThreadId, item_id: String) -> ThreadStoreFuture<'_, bool> {
|
||||
queue_future(async move { self.queue().delete(thread_id, &item_id).await })
|
||||
}
|
||||
|
||||
fn reorder(&self, thread_id: ThreadId, item_ids: Vec<String>) -> ThreadStoreFuture<'_, ()> {
|
||||
Box::pin(async move {
|
||||
self.queue()
|
||||
.reorder(thread_id, &item_ids)
|
||||
.await
|
||||
.map_err(|error| match error.downcast_ref::<std::io::Error>() {
|
||||
Some(error) if error.kind() == std::io::ErrorKind::InvalidInput => {
|
||||
ThreadStoreError::InvalidRequest {
|
||||
message: error.to_string(),
|
||||
}
|
||||
}
|
||||
_ => ThreadStoreError::Internal {
|
||||
message: format!("queue storage failed: {error}"),
|
||||
},
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
697
codex-rs/thread-store/src/store.rs
Normal file
697
codex-rs/thread-store/src/store.rs
Normal file
@@ -0,0 +1,697 @@
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::protocol::ThreadHistoryMode;
|
||||
use codex_rollout::RolloutItem;
|
||||
use std::any::Any;
|
||||
use std::fmt;
|
||||
use std::future::Future;
|
||||
use std::pin::Pin;
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::AddThreadAttachmentOutcome;
|
||||
use crate::AddThreadAttachmentParams;
|
||||
use crate::AppendThreadItemsParams;
|
||||
use crate::ArchiveThreadParams;
|
||||
use crate::ArchiveThreadsParams;
|
||||
use crate::CreateProjectParams;
|
||||
use crate::CreateThreadParams;
|
||||
use crate::CreateThreadSectionParams;
|
||||
use crate::CreatedProject;
|
||||
use crate::DeleteThreadParams;
|
||||
use crate::DeleteThreadSectionParams;
|
||||
use crate::DeleteThreadsParams;
|
||||
use crate::DeletedProject;
|
||||
use crate::ItemPage;
|
||||
use crate::ListItemsParams;
|
||||
use crate::ListProjectsParams;
|
||||
use crate::ListThreadAttachmentThreadsParams;
|
||||
use crate::ListThreadAttachmentsParams;
|
||||
use crate::ListThreadSectionsParams;
|
||||
use crate::ListThreadsParams;
|
||||
use crate::ListTurnsParams;
|
||||
use crate::LoadThreadHistoryParams;
|
||||
use crate::MoveProjectParams;
|
||||
use crate::MoveThreadToSectionParams;
|
||||
use crate::PrepareForkParams;
|
||||
use crate::PreparedFork;
|
||||
use crate::ProjectMoveOutcome;
|
||||
use crate::ReadThreadByRolloutPathParams;
|
||||
use crate::ReadThreadParams;
|
||||
use crate::RemoveThreadAttachmentOutcome;
|
||||
use crate::RemoveThreadAttachmentParams;
|
||||
use crate::RenameThreadSectionParams;
|
||||
use crate::ResumeThreadParams;
|
||||
use crate::RevertThreadParams;
|
||||
use crate::SearchThreadOccurrencesParams;
|
||||
use crate::SearchThreadsParams;
|
||||
use crate::StoredModelContext;
|
||||
use crate::StoredProject;
|
||||
use crate::StoredProjectsPage;
|
||||
use crate::StoredThread;
|
||||
use crate::StoredThreadHistory;
|
||||
use crate::StoredThreadSection;
|
||||
use crate::StoredThreadSectionsPage;
|
||||
use crate::ThreadAttachmentOwnerPage;
|
||||
use crate::ThreadAttachmentPage;
|
||||
use crate::ThreadMetadataPatch;
|
||||
use crate::ThreadOccurrenceSearchPage;
|
||||
use crate::ThreadPage;
|
||||
use crate::ThreadSearchPage;
|
||||
use crate::ThreadStoreError;
|
||||
use crate::ThreadStoreResult;
|
||||
use crate::TurnPage;
|
||||
use crate::UpdateProjectParams;
|
||||
use crate::UpdateThreadMetadataParams;
|
||||
use crate::UpdatedProject;
|
||||
|
||||
/// Future returned by [`ThreadStore`] operations.
|
||||
pub type ThreadStoreFuture<'a, T> = Pin<Box<dyn Future<Output = ThreadStoreResult<T>> + Send + 'a>>;
|
||||
|
||||
/// Data a [`ThreadStore`] has already loaded while preparing a thread for resume.
|
||||
///
|
||||
/// Core does not inspect this value. It gives the value back to the store when reopening the
|
||||
/// thread, allowing the store to reuse the loaded history and writer state instead of loading them
|
||||
/// again. The value can only be used once because it may own resources that cannot be copied.
|
||||
pub struct ThreadStoreResumePreparation {
|
||||
state: Box<dyn Any + Send>,
|
||||
}
|
||||
|
||||
impl ThreadStoreResumePreparation {
|
||||
pub fn new<T: Any + Send>(state: T) -> Self {
|
||||
Self {
|
||||
state: Box::new(state),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn downcast<T: Any + Send>(self) -> Result<T, Self> {
|
||||
match self.state.downcast::<T>() {
|
||||
Ok(state) => Ok(*state),
|
||||
Err(state) => Err(Self { state }),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for ThreadStoreResumePreparation {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("ThreadStoreResumePreparation")
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
/// Why thread persistence is being requested.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum PersistContext {
|
||||
/// Thread initialization or context injection is complete without starting a turn.
|
||||
ThreadPreparation,
|
||||
/// Standard persistence makes the thread and all queued items durable and readable.
|
||||
Standard,
|
||||
/// Copied subagent history may be enqueued so its durability fence can overlap relationship
|
||||
/// persistence. The caller must await standard persistence before acknowledging the child.
|
||||
SubagentSpawn,
|
||||
/// A turn is about to begin sampling after its input has been recorded.
|
||||
TurnStart,
|
||||
/// Accepted user input is being recorded before an active turn's next sampling request.
|
||||
/// This does not apply to tool outputs, cancellation, or task cleanup.
|
||||
SteeredUserInput,
|
||||
}
|
||||
|
||||
impl PersistContext {
|
||||
/// Whether a store may enqueue this checkpoint before returning and fence it at a later
|
||||
/// durability barrier. Stores may still choose to persist synchronously.
|
||||
pub fn allows_background_persistence(self) -> bool {
|
||||
match self {
|
||||
Self::ThreadPreparation | Self::Standard => false,
|
||||
Self::SubagentSpawn | Self::TurnStart | Self::SteeredUserInput => true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Storage-neutral thread persistence boundary.
|
||||
pub trait ThreadStore: Any + Send + Sync {
|
||||
/// Return this store as [`Any`] for implementation-owned escape hatches.
|
||||
fn as_any(&self) -> &dyn Any;
|
||||
|
||||
/// Returns the history mode to use when history does not carry a persisted mode.
|
||||
///
|
||||
/// The default is legacy so existing stores stay compatible. Stores whose durable contract is
|
||||
/// already paginated should override this instead of relying on core to infer storage behavior.
|
||||
fn default_history_mode(&self) -> ThreadHistoryMode {
|
||||
ThreadHistoryMode::Legacy
|
||||
}
|
||||
|
||||
/// Creates a new live thread.
|
||||
fn create_thread(&self, params: CreateThreadParams) -> ThreadStoreFuture<'_, ()>;
|
||||
|
||||
/// Stages host-owned metadata for a thread ID reserved before Core starts the thread.
|
||||
///
|
||||
/// The entry remains in memory until the first successful metadata update for that thread.
|
||||
/// Callers must remove it if startup fails before the store opens a live thread.
|
||||
fn stage_pending_thread_metadata(
|
||||
&self,
|
||||
_thread_id: ThreadId,
|
||||
_patch: ThreadMetadataPatch,
|
||||
) -> ThreadStoreFuture<'_, ()> {
|
||||
Box::pin(async {
|
||||
Err(ThreadStoreError::Unsupported {
|
||||
operation: "stage_pending_thread_metadata",
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// Reads metadata staged for a reserved thread without persisting it.
|
||||
fn read_pending_thread_metadata(
|
||||
&self,
|
||||
_thread_id: ThreadId,
|
||||
) -> ThreadStoreFuture<'_, Option<ThreadMetadataPatch>> {
|
||||
Box::pin(async { Ok(None) })
|
||||
}
|
||||
|
||||
/// Removes host-owned metadata staged for a reserved thread ID.
|
||||
fn remove_pending_thread_metadata(&self, _thread_id: ThreadId) -> ThreadStoreFuture<'_, ()> {
|
||||
Box::pin(async {
|
||||
Err(ThreadStoreError::Unsupported {
|
||||
operation: "remove_pending_thread_metadata",
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// Reopens an existing thread for live appends and returns its authoritative replay context.
|
||||
///
|
||||
/// Stored snapshots supplied by callers may predate writer acquisition. Implementations must
|
||||
/// include writes committed before acquisition in the returned context. Explicitly supplied
|
||||
/// histories without a canonical session header retain their import/override semantics.
|
||||
/// A supplied revision may enable reuse of the shared snapshot after validation; missing or
|
||||
/// unrecognized revisions must not be treated as proof that stored history is unchanged.
|
||||
/// On failure, implementations must release any writer acquired by this operation.
|
||||
fn resume_thread(
|
||||
&self,
|
||||
params: ResumeThreadParams,
|
||||
) -> ThreadStoreFuture<'_, Arc<Vec<RolloutItem>>>;
|
||||
|
||||
/// Reopens a thread using implementation-owned state prepared before Core startup.
|
||||
///
|
||||
/// Stores should only override this when they also produce the preparation. The returned
|
||||
/// history and failure cleanup guarantees are the same as [`Self::resume_thread`].
|
||||
fn resume_thread_with_preparation(
|
||||
&self,
|
||||
_params: ResumeThreadParams,
|
||||
_preparation: ThreadStoreResumePreparation,
|
||||
) -> ThreadStoreFuture<'_, Arc<Vec<RolloutItem>>> {
|
||||
Box::pin(async {
|
||||
Err(ThreadStoreError::Unsupported {
|
||||
operation: "resume_thread_with_preparation",
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// Appends raw rollout items to a live thread.
|
||||
///
|
||||
/// Implementations should apply the shared rollout persistence policy before writing durable
|
||||
/// replay history and before updating any implementation-owned projections.
|
||||
fn append_items(&self, params: AppendThreadItemsParams) -> ThreadStoreFuture<'_, ()>;
|
||||
|
||||
/// Records metadata derived from rollout items.
|
||||
/// Unlike [`Self::update_thread_metadata`], this allows the write to be deferred.
|
||||
///
|
||||
/// The default implementation awaits the update. Deferred writes must respect the
|
||||
/// flush and shutdown guarantees documented by [`Self::persist_thread`].
|
||||
fn record_thread_metadata(
|
||||
&self,
|
||||
params: UpdateThreadMetadataParams,
|
||||
) -> ThreadStoreFuture<'_, ()> {
|
||||
Box::pin(async move { self.update_thread_metadata(params).await.map(|_| ()) })
|
||||
}
|
||||
|
||||
/// Materializes the thread if persistence is lazy, then persists all queued items.
|
||||
///
|
||||
/// Preparation checkpoints may leave disposable preparation data in memory without
|
||||
/// activating storage. Standard persistence must complete before returning. Contexts that allow background
|
||||
/// persistence may complete asynchronously when the implementation enqueues the checkpoint
|
||||
/// before returning, fences it with subsequent flush or shutdown operations, and surfaces
|
||||
/// failures through those operations.
|
||||
fn persist_thread(
|
||||
&self,
|
||||
thread_id: ThreadId,
|
||||
context: PersistContext,
|
||||
) -> ThreadStoreFuture<'_, ()>;
|
||||
|
||||
/// Flushes all queued items and returns once they are durable/readable.
|
||||
fn flush_thread(&self, thread_id: ThreadId) -> ThreadStoreFuture<'_, ()>;
|
||||
|
||||
/// Flushes pending items and closes the live thread writer.
|
||||
/// Stores with opt-in disposable preparations may discard an unactivated preparation.
|
||||
fn shutdown_thread(&self, thread_id: ThreadId) -> ThreadStoreFuture<'_, ()>;
|
||||
|
||||
/// Discards the live thread writer without forcing pending in-memory items to become durable.
|
||||
///
|
||||
/// Core calls this when session initialization fails after a live writer has been created.
|
||||
/// Implementations should release any live writer resources for the thread while preserving
|
||||
/// already-durable thread data.
|
||||
fn discard_thread(&self, thread_id: ThreadId) -> ThreadStoreFuture<'_, ()>;
|
||||
|
||||
/// Loads persisted history for resume, fork, and memory jobs.
|
||||
fn load_history(
|
||||
&self,
|
||||
params: LoadThreadHistoryParams,
|
||||
) -> ThreadStoreFuture<'_, StoredThreadHistory>;
|
||||
|
||||
/// Captures a complete tail, optionally reading originals after a saved position.
|
||||
/// Local storage uses one reader for the cutoff and records; compressed rollouts
|
||||
/// are decoded once per call. It supports append-only paginated roots;
|
||||
/// other histories and backends must fail explicitly rather than omit originals.
|
||||
/// Callers flush pending writes before capturing a boundary and own progress.
|
||||
fn read_original_history(
|
||||
&self,
|
||||
_thread_id: ThreadId,
|
||||
_request: crate::OriginalHistoryRequest,
|
||||
) -> ThreadStoreFuture<'_, crate::OriginalHistoryRead> {
|
||||
Box::pin(async {
|
||||
Err(ThreadStoreError::Unsupported {
|
||||
operation: "read_original_history",
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// Loads the persisted rollout items needed to reconstruct the latest model-visible context.
|
||||
///
|
||||
/// Implementations that cannot perform a targeted read may return the full persisted history.
|
||||
fn load_latest_model_context(
|
||||
&self,
|
||||
_params: LoadThreadHistoryParams,
|
||||
) -> ThreadStoreFuture<'_, StoredModelContext> {
|
||||
Box::pin(async {
|
||||
Err(ThreadStoreError::Unsupported {
|
||||
operation: "load_latest_model_context",
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// Checks whether a previously loaded model context still represents the stored history.
|
||||
///
|
||||
/// Stores that cannot validate the opaque revision must return false. A false result or an
|
||||
/// error requires a fresh read. This does not acquire writer ownership;
|
||||
/// [`Self::resume_thread`] must still validate the snapshot after acquisition.
|
||||
fn is_model_context_current(
|
||||
&self,
|
||||
_params: LoadThreadHistoryParams,
|
||||
_revision: String,
|
||||
) -> ThreadStoreFuture<'_, bool> {
|
||||
Box::pin(async { Ok(false) })
|
||||
}
|
||||
|
||||
/// Freezes source history and model context used to initialize a referenced fork.
|
||||
///
|
||||
/// Stores without reference-backed fork support can retain this default implementation.
|
||||
fn prepare_fork(&self, _params: PrepareForkParams) -> ThreadStoreFuture<'_, PreparedFork> {
|
||||
Box::pin(async {
|
||||
Err(ThreadStoreError::Unsupported {
|
||||
operation: "prepare_fork",
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// Reverts a paginated thread's durable history so it ends immediately before
|
||||
/// `before_turn_id`.
|
||||
///
|
||||
/// Callers must close the thread's live writer first. The logical thread id and semantic
|
||||
/// metadata stay unchanged.
|
||||
///
|
||||
/// Stores without paginated revert support can retain this default implementation.
|
||||
fn revert_thread(&self, _params: RevertThreadParams) -> ThreadStoreFuture<'_, ()> {
|
||||
Box::pin(async {
|
||||
Err(ThreadStoreError::Unsupported {
|
||||
operation: "revert_thread",
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// Reads a thread summary and optionally its persisted history.
|
||||
fn read_thread(&self, params: ReadThreadParams) -> ThreadStoreFuture<'_, StoredThread>;
|
||||
|
||||
/// Reads a rollout-backed thread by path when the store supports path-addressed lookups.
|
||||
///
|
||||
/// Deprecated: new callers should use [`ThreadStore::read_thread`] instead.
|
||||
fn read_thread_by_rollout_path(
|
||||
&self,
|
||||
params: ReadThreadByRolloutPathParams,
|
||||
) -> ThreadStoreFuture<'_, StoredThread>;
|
||||
|
||||
/// Lists stored threads matching the supplied filters.
|
||||
fn list_threads(&self, params: ListThreadsParams) -> ThreadStoreFuture<'_, ThreadPage>;
|
||||
|
||||
/// Whether this store can discover and manage independently persisted thread sections.
|
||||
fn supports_thread_sections(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
/// Lists independently persisted thread sections.
|
||||
fn list_thread_sections(
|
||||
&self,
|
||||
_params: ListThreadSectionsParams,
|
||||
) -> ThreadStoreFuture<'_, StoredThreadSectionsPage> {
|
||||
Box::pin(async {
|
||||
Err(ThreadStoreError::Unsupported {
|
||||
operation: "threadSection/list",
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// Creates a custom thread section with a stable, server-assigned identity.
|
||||
fn create_thread_section(
|
||||
&self,
|
||||
_params: CreateThreadSectionParams,
|
||||
) -> ThreadStoreFuture<'_, StoredThreadSection> {
|
||||
Box::pin(async {
|
||||
Err(ThreadStoreError::Unsupported {
|
||||
operation: "threadSection/create",
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// Renames a custom thread section, returning `None` when it does not exist.
|
||||
fn rename_thread_section(
|
||||
&self,
|
||||
_params: RenameThreadSectionParams,
|
||||
) -> ThreadStoreFuture<'_, Option<StoredThreadSection>> {
|
||||
Box::pin(async {
|
||||
Err(ThreadStoreError::Unsupported {
|
||||
operation: "threadSection/update",
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// Deletes a custom thread section and reports whether it existed.
|
||||
fn delete_thread_section(
|
||||
&self,
|
||||
_params: DeleteThreadSectionParams,
|
||||
) -> ThreadStoreFuture<'_, bool> {
|
||||
Box::pin(async {
|
||||
Err(ThreadStoreError::Unsupported {
|
||||
operation: "threadSection/delete",
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether this store can persist and discover thread-owned attachments.
|
||||
fn supports_thread_attachments(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
/// Copies current attachment membership into a newly persisted fork.
|
||||
///
|
||||
/// Copies must be atomic and use new attachment IDs. The destination must be empty;
|
||||
/// subsequent membership changes on either thread must remain independent.
|
||||
fn copy_thread_attachments(
|
||||
&self,
|
||||
_source_thread_id: ThreadId,
|
||||
_destination_thread_id: ThreadId,
|
||||
) -> ThreadStoreFuture<'_, ()> {
|
||||
Box::pin(async {
|
||||
Err(ThreadStoreError::Unsupported {
|
||||
operation: "copy_thread_attachments",
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// Attaches an attachment, returning an existing attachment for repeated requests.
|
||||
fn add_thread_attachment(
|
||||
&self,
|
||||
_params: AddThreadAttachmentParams,
|
||||
) -> ThreadStoreFuture<'_, AddThreadAttachmentOutcome> {
|
||||
Box::pin(async {
|
||||
Err(ThreadStoreError::Unsupported {
|
||||
operation: "thread/attachment/add",
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// Lists attachments belonging to one persisted thread.
|
||||
fn list_thread_attachments(
|
||||
&self,
|
||||
_params: ListThreadAttachmentsParams,
|
||||
) -> ThreadStoreFuture<'_, ThreadAttachmentPage> {
|
||||
Box::pin(async {
|
||||
Err(ThreadStoreError::Unsupported {
|
||||
operation: "thread/attachment/list",
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// Lists owners of an exact attachment identity, without thread browser visibility filters.
|
||||
/// Results describe persisted membership, not an atomic claim on the referenced resource.
|
||||
fn list_thread_attachment_threads(
|
||||
&self,
|
||||
_params: ListThreadAttachmentThreadsParams,
|
||||
) -> ThreadStoreFuture<'_, ThreadAttachmentOwnerPage> {
|
||||
Box::pin(async {
|
||||
Err(ThreadStoreError::Unsupported {
|
||||
operation: "thread/attachmentOwner/list",
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// Removes an attachment and reports whether it existed.
|
||||
fn remove_thread_attachment(
|
||||
&self,
|
||||
_params: RemoveThreadAttachmentParams,
|
||||
) -> ThreadStoreFuture<'_, RemoveThreadAttachmentOutcome> {
|
||||
Box::pin(async {
|
||||
Err(ThreadStoreError::Unsupported {
|
||||
operation: "thread/attachment/remove",
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether this store supports durable host-owned projects.
|
||||
fn supports_projects(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn list_projects(
|
||||
&self,
|
||||
_params: ListProjectsParams,
|
||||
) -> ThreadStoreFuture<'_, StoredProjectsPage> {
|
||||
Box::pin(async {
|
||||
Err(ThreadStoreError::Unsupported {
|
||||
operation: "project/list",
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
fn read_project(&self, _project_id: String) -> ThreadStoreFuture<'_, Option<StoredProject>> {
|
||||
Box::pin(async {
|
||||
Err(ThreadStoreError::Unsupported {
|
||||
operation: "project/read",
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
fn create_project(
|
||||
&self,
|
||||
_params: CreateProjectParams,
|
||||
) -> ThreadStoreFuture<'_, CreatedProject> {
|
||||
Box::pin(async {
|
||||
Err(ThreadStoreError::Unsupported {
|
||||
operation: "project/create",
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
fn update_project(
|
||||
&self,
|
||||
_params: UpdateProjectParams,
|
||||
) -> ThreadStoreFuture<'_, Option<UpdatedProject>> {
|
||||
Box::pin(async {
|
||||
Err(ThreadStoreError::Unsupported {
|
||||
operation: "project/update",
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
fn move_project(
|
||||
&self,
|
||||
_params: MoveProjectParams,
|
||||
) -> ThreadStoreFuture<'_, Option<ProjectMoveOutcome>> {
|
||||
Box::pin(async {
|
||||
Err(ThreadStoreError::Unsupported {
|
||||
operation: "project/move",
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
fn delete_project(&self, _project_id: String) -> ThreadStoreFuture<'_, Option<DeletedProject>> {
|
||||
Box::pin(async {
|
||||
Err(ThreadStoreError::Unsupported {
|
||||
operation: "project/delete",
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether paginated threads can hydrate durable history through turn and item lists.
|
||||
fn supports_paginated_history_lists(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
/// Searches stored threads and returns search-only preview metadata.
|
||||
fn search_threads(
|
||||
&self,
|
||||
_params: SearchThreadsParams,
|
||||
) -> ThreadStoreFuture<'_, ThreadSearchPage> {
|
||||
Box::pin(async {
|
||||
Err(ThreadStoreError::Unsupported {
|
||||
operation: "thread/search",
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// Searches visible message occurrences within one paginated thread.
|
||||
fn search_thread_occurrences(
|
||||
&self,
|
||||
_params: SearchThreadOccurrencesParams,
|
||||
) -> ThreadStoreFuture<'_, ThreadOccurrenceSearchPage> {
|
||||
Box::pin(async {
|
||||
Err(ThreadStoreError::Unsupported {
|
||||
operation: "thread/searchOccurrences",
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// Lists turns within a stored thread.
|
||||
fn list_turns(&self, _params: ListTurnsParams) -> ThreadStoreFuture<'_, TurnPage> {
|
||||
Box::pin(async {
|
||||
Err(ThreadStoreError::Unsupported {
|
||||
operation: "list_turns",
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// Lists persisted items within a stored thread, optionally filtered to a turn.
|
||||
fn list_items(&self, _params: ListItemsParams) -> ThreadStoreFuture<'_, ItemPage> {
|
||||
Box::pin(async {
|
||||
Err(ThreadStoreError::Unsupported {
|
||||
operation: "list_items",
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// Lists bounded ordinary and realtime thread history in rollout order.
|
||||
fn list_timeline(
|
||||
&self,
|
||||
_params: crate::ListTimelineParams,
|
||||
) -> ThreadStoreFuture<'_, crate::TimelinePage> {
|
||||
Box::pin(async {
|
||||
Err(ThreadStoreError::Unsupported {
|
||||
operation: "thread/timeline/list",
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// Applies a literal metadata patch and returns the updated thread when one was materialized.
|
||||
///
|
||||
/// `None` means the update succeeded without materializing a thread, for example because the
|
||||
/// implementation filtered the patch to a no-op. Callers that require a `StoredThread` must
|
||||
/// perform a fallback read.
|
||||
///
|
||||
/// Implementations should apply the supplied fields directly. Policy such as deciding whether
|
||||
/// an append-derived preview should be emitted belongs above the store.
|
||||
fn update_thread_metadata(
|
||||
&self,
|
||||
params: UpdateThreadMetadataParams,
|
||||
) -> ThreadStoreFuture<'_, Option<StoredThread>>;
|
||||
|
||||
/// Moves a thread to, within, or out of a server-ordered section.
|
||||
fn move_thread_to_section(
|
||||
&self,
|
||||
_params: MoveThreadToSectionParams,
|
||||
) -> ThreadStoreFuture<'_, ()> {
|
||||
Box::pin(async {
|
||||
Err(ThreadStoreError::Unsupported {
|
||||
operation: "thread/section/move",
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// Archives a thread.
|
||||
fn archive_thread(&self, params: ArchiveThreadParams) -> ThreadStoreFuture<'_, ()>;
|
||||
|
||||
/// Archives threads in order, returning the successfully archived thread ids.
|
||||
///
|
||||
/// The first thread must archive successfully; later failures are best effort.
|
||||
fn archive_threads(
|
||||
&self,
|
||||
params: ArchiveThreadsParams,
|
||||
) -> ThreadStoreFuture<'_, Vec<ThreadId>> {
|
||||
Box::pin(async move {
|
||||
let mut archived_thread_ids = Vec::new();
|
||||
for thread_id in params.thread_ids {
|
||||
match self.archive_thread(ArchiveThreadParams { thread_id }).await {
|
||||
Ok(()) => archived_thread_ids.push(thread_id),
|
||||
Err(err) if archived_thread_ids.is_empty() => return Err(err),
|
||||
Err(err) => tracing::warn!("failed to archive thread {thread_id}: {err}"),
|
||||
}
|
||||
}
|
||||
Ok(archived_thread_ids)
|
||||
})
|
||||
}
|
||||
|
||||
/// Unarchives a thread and returns its updated metadata.
|
||||
fn unarchive_thread(&self, params: ArchiveThreadParams) -> ThreadStoreFuture<'_, StoredThread>;
|
||||
|
||||
/// Restores threads in order, returning the first thread's metadata and restored ids.
|
||||
///
|
||||
/// The requested thread must restore successfully; active descendants are skipped and
|
||||
/// descendant failures are best effort. Stores can share rollout discovery work.
|
||||
fn unarchive_threads(
|
||||
&self,
|
||||
params: ArchiveThreadParams,
|
||||
descendant_thread_ids: Vec<ThreadId>,
|
||||
) -> ThreadStoreFuture<'_, (StoredThread, Vec<ThreadId>)> {
|
||||
Box::pin(async move {
|
||||
let thread_id = params.thread_id;
|
||||
let root = self.unarchive_thread(params).await?;
|
||||
let mut restored = vec![thread_id];
|
||||
for thread_id in descendant_thread_ids {
|
||||
let result = async {
|
||||
let thread = self
|
||||
.read_thread(ReadThreadParams {
|
||||
thread_id,
|
||||
include_archived: true,
|
||||
include_history: false,
|
||||
})
|
||||
.await?;
|
||||
if thread.archived_at.is_some() {
|
||||
self.unarchive_thread(ArchiveThreadParams { thread_id })
|
||||
.await?;
|
||||
restored.push(thread_id);
|
||||
}
|
||||
Ok::<_, ThreadStoreError>(())
|
||||
}
|
||||
.await;
|
||||
if let Err(err) = result {
|
||||
tracing::warn!("failed to unarchive thread {thread_id}: {err}");
|
||||
}
|
||||
}
|
||||
Ok((root, restored))
|
||||
})
|
||||
}
|
||||
|
||||
/// Deletes a thread's persisted rollout data and associated metadata.
|
||||
/// Success includes cleanup of associated persisted state; callers must not repeat it.
|
||||
fn delete_thread(&self, params: DeleteThreadParams) -> ThreadStoreFuture<'_, ()>;
|
||||
|
||||
/// Deletes threads and their associated persisted state in order, treating already-missing
|
||||
/// members as deleted.
|
||||
///
|
||||
/// Stores with request-scoped delete preflight should override this instead of repeating
|
||||
/// that work through [`ThreadStore::delete_thread`].
|
||||
fn delete_threads(&self, params: DeleteThreadsParams) -> ThreadStoreFuture<'_, ()> {
|
||||
Box::pin(async move {
|
||||
for thread_id in params.thread_ids {
|
||||
match self.delete_thread(DeleteThreadParams { thread_id }).await {
|
||||
Ok(()) | Err(ThreadStoreError::ThreadNotFound { .. }) => {}
|
||||
Err(err) => return Err(err),
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
}
|
||||
50
codex-rs/thread-store/src/thread_attachments.rs
Normal file
50
codex-rs/thread-store/src/thread_attachments.rs
Normal file
@@ -0,0 +1,50 @@
|
||||
//! Typed parameters for attachment operations on stored threads.
|
||||
|
||||
use crate::ThreadAttachmentArchiveFilter;
|
||||
use codex_protocol::ThreadId;
|
||||
use serde_json::Value;
|
||||
|
||||
/// Parameters for attaching a thread-owned attachment.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct AddThreadAttachmentParams {
|
||||
/// Thread that owns the attachment.
|
||||
pub thread_id: ThreadId,
|
||||
/// Client-defined attachment type.
|
||||
pub attachment_type: String,
|
||||
/// Stable attachment identity within its thread and type.
|
||||
pub identity_key: String,
|
||||
/// Bounded, client-defined attachment metadata.
|
||||
pub payload: Value,
|
||||
}
|
||||
|
||||
/// Parameters for listing attachments owned by one thread.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct ListThreadAttachmentsParams {
|
||||
/// Thread whose attachments should be returned.
|
||||
pub thread_id: ThreadId,
|
||||
/// Opaque cursor returned by a previous attachment listing.
|
||||
pub cursor: Option<String>,
|
||||
/// Maximum number of attachments to return.
|
||||
pub limit: usize,
|
||||
}
|
||||
|
||||
/// Parameters for removing a thread-owned attachment.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct RemoveThreadAttachmentParams {
|
||||
/// Thread that owns the attachment.
|
||||
pub thread_id: ThreadId,
|
||||
/// Client-defined attachment type.
|
||||
pub attachment_type: String,
|
||||
/// Stable attachment identity within its thread and type.
|
||||
pub identity_key: String,
|
||||
}
|
||||
|
||||
/// Parameters for finding all owners of one attachment identity in this store.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct ListThreadAttachmentThreadsParams {
|
||||
pub attachment_type: String,
|
||||
pub identity_key: String,
|
||||
pub archive_filter: ThreadAttachmentArchiveFilter,
|
||||
pub cursor: Option<String>,
|
||||
pub limit: usize,
|
||||
}
|
||||
945
codex-rs/thread-store/src/thread_metadata_sync.rs
Normal file
945
codex-rs/thread-store/src/thread_metadata_sync.rs
Normal file
@@ -0,0 +1,945 @@
|
||||
use std::time::Duration;
|
||||
use std::time::Instant;
|
||||
|
||||
use chrono::DateTime;
|
||||
use chrono::NaiveDateTime;
|
||||
use chrono::Utc;
|
||||
use codex_git_utils::collect_git_info;
|
||||
use codex_git_utils::get_git_repo_root;
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::items::TurnItem;
|
||||
use codex_protocol::protocol::EventMsg;
|
||||
use codex_protocol::protocol::GitInfo;
|
||||
use codex_protocol::protocol::SessionSource;
|
||||
use codex_protocol::protocol::ThreadHistoryMode;
|
||||
use codex_protocol::protocol::ThreadMemoryMode;
|
||||
use codex_protocol::protocol::UserMessageEvent;
|
||||
use codex_protocol::protocol::strip_user_message_prefix;
|
||||
use codex_protocol::protocol::user_message_preview;
|
||||
use codex_rollout::RolloutItem;
|
||||
use codex_state::ThreadMetadata;
|
||||
|
||||
use crate::CreateThreadParams;
|
||||
use crate::GitInfoPatch;
|
||||
use crate::ResumeThreadParams;
|
||||
use crate::ThreadMetadataPatch;
|
||||
use crate::types::canonical_history_mode_from_rollout_items;
|
||||
|
||||
const THREAD_UPDATED_AT_TOUCH_INTERVAL: Duration = Duration::from_secs(5);
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "thread_metadata_sync_preview_tests.rs"]
|
||||
mod preview_tests;
|
||||
|
||||
/// Live-thread helper that derives metadata updates from appended rollout items.
|
||||
///
|
||||
/// Stores receive raw rollout items plus explicit metadata patches. This helper
|
||||
/// keeps append-derived metadata observation in the live layer without owning persistence-policy
|
||||
/// filtering or making `append_items` infer metadata inside a `ThreadStore` implementation.
|
||||
pub(crate) struct ThreadMetadataSync {
|
||||
thread_id: ThreadId,
|
||||
cwd_seen: bool,
|
||||
preview_seen: bool,
|
||||
first_user_message_seen: bool,
|
||||
title_seen: bool,
|
||||
pending_update: Option<ThreadMetadataPatch>,
|
||||
pending_update_generation: u64,
|
||||
last_touch_persisted_at: Option<Instant>,
|
||||
defer_create_update_until_history_exists: bool,
|
||||
defer_resume_update_until_append: bool,
|
||||
}
|
||||
|
||||
pub(crate) struct PendingThreadMetadataPatch {
|
||||
pub(crate) patch: ThreadMetadataPatch,
|
||||
generation: u64,
|
||||
}
|
||||
|
||||
impl ThreadMetadataSync {
|
||||
pub(crate) async fn for_create(params: &CreateThreadParams) -> Self {
|
||||
let created_at = Utc::now();
|
||||
let cwd = params.metadata.cwd.clone().unwrap_or_default();
|
||||
let git_info = if get_git_repo_root(cwd.as_path()).is_some() {
|
||||
collect_git_info(cwd.as_path()).await.map(|info| GitInfo {
|
||||
commit_hash: info.commit_hash,
|
||||
branch: info.branch,
|
||||
repository_url: info.repository_url,
|
||||
})
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let guardian_review = codex_state::is_guardian_review_source(¶ms.source);
|
||||
let update = ThreadMetadataPatch {
|
||||
name: (guardian_review && params.history_mode == ThreadHistoryMode::Paginated)
|
||||
.then(|| Some(codex_state::GUARDIAN_THREAD_TITLE.to_string())),
|
||||
title: guardian_review.then(|| codex_state::GUARDIAN_THREAD_TITLE.to_string()),
|
||||
preview: guardian_review.then(|| codex_state::GUARDIAN_THREAD_PREVIEW.to_string()),
|
||||
model_provider: Some(params.metadata.model_provider.clone()),
|
||||
created_at: Some(created_at),
|
||||
updated_at: Some(created_at),
|
||||
source: Some(params.source.clone()),
|
||||
originator: (!params.originator.is_empty()).then(|| params.originator.clone()),
|
||||
creator_user_id: params.creator_user_id.clone(),
|
||||
creator_account_id: params.creator_account_id.clone(),
|
||||
thread_source: Some(params.thread_source.clone()),
|
||||
agent_nickname: Some(params.source.get_nickname()),
|
||||
agent_role: Some(params.source.get_agent_role()),
|
||||
agent_path: Some(params.source.get_agent_path().map(Into::into)),
|
||||
cwd: Some(cwd.clone()),
|
||||
cli_version: Some(env!("CARGO_PKG_VERSION").to_string()),
|
||||
git_info: git_info.map(git_info_patch_from_observation),
|
||||
memory_mode: Some(params.metadata.memory_mode),
|
||||
..Default::default()
|
||||
};
|
||||
Self {
|
||||
thread_id: params.thread_id,
|
||||
cwd_seen: !cwd.as_os_str().is_empty(),
|
||||
preview_seen: guardian_review,
|
||||
first_user_message_seen: guardian_review,
|
||||
title_seen: guardian_review,
|
||||
pending_update: Some(update),
|
||||
pending_update_generation: 1,
|
||||
last_touch_persisted_at: None,
|
||||
defer_create_update_until_history_exists: true,
|
||||
defer_resume_update_until_append: false,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn for_resume(
|
||||
params: &ResumeThreadParams,
|
||||
metadata: Option<&ThreadMetadata>,
|
||||
) -> Self {
|
||||
let guardian_review = metadata.is_some_and(|metadata| {
|
||||
serde_json::from_str::<SessionSource>(&metadata.source)
|
||||
.as_ref()
|
||||
.is_ok_and(codex_state::is_guardian_review_source)
|
||||
});
|
||||
let mut sync = Self {
|
||||
thread_id: params.thread_id,
|
||||
cwd_seen: params
|
||||
.metadata
|
||||
.cwd
|
||||
.as_ref()
|
||||
.is_some_and(|cwd| !cwd.as_os_str().is_empty()),
|
||||
preview_seen: guardian_review
|
||||
|| metadata
|
||||
.and_then(|metadata| metadata.preview.as_deref())
|
||||
.is_some_and(|preview| !preview.is_empty()),
|
||||
first_user_message_seen: guardian_review
|
||||
|| metadata.is_some_and(|metadata| metadata.first_user_message.is_some()),
|
||||
title_seen: guardian_review
|
||||
|| metadata.is_some_and(|metadata| !metadata.title.is_empty()),
|
||||
pending_update: None,
|
||||
pending_update_generation: 0,
|
||||
last_touch_persisted_at: None,
|
||||
defer_create_update_until_history_exists: false,
|
||||
defer_resume_update_until_append: false,
|
||||
};
|
||||
if let Some(history) = params.history.as_deref() {
|
||||
sync.record_resume_history(history);
|
||||
}
|
||||
sync
|
||||
}
|
||||
|
||||
pub(crate) fn record_resume_history(&mut self, history: &[RolloutItem]) {
|
||||
let update = self.observe_resume_history(history);
|
||||
self.merge_pending_update(update);
|
||||
self.defer_resume_update_until_append = self.pending_update.is_some();
|
||||
}
|
||||
|
||||
pub(crate) fn take_pending_update(&self) -> Option<PendingThreadMetadataPatch> {
|
||||
self.pending_update
|
||||
.clone()
|
||||
.map(|patch| PendingThreadMetadataPatch {
|
||||
patch,
|
||||
generation: self.pending_update_generation,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn take_pending_update_for_existing_history(
|
||||
&self,
|
||||
) -> Option<PendingThreadMetadataPatch> {
|
||||
if self.defer_create_update_until_history_exists {
|
||||
return None;
|
||||
}
|
||||
if self.defer_resume_update_until_append {
|
||||
return None;
|
||||
}
|
||||
self.take_pending_update()
|
||||
}
|
||||
|
||||
pub(crate) fn mark_pending_update_applied(&mut self, update: &PendingThreadMetadataPatch) {
|
||||
if self.pending_update_generation == update.generation {
|
||||
self.pending_update = None;
|
||||
}
|
||||
if update.patch.updated_at.is_some() {
|
||||
self.last_touch_persisted_at = Some(Instant::now());
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn observe_appended_items(
|
||||
&mut self,
|
||||
items: &[RolloutItem],
|
||||
) -> Option<PendingThreadMetadataPatch> {
|
||||
self.defer_create_update_until_history_exists = false;
|
||||
self.defer_resume_update_until_append = false;
|
||||
let affects_metadata = items
|
||||
.iter()
|
||||
.any(codex_state::rollout_item_affects_thread_metadata);
|
||||
let advances_recency = items
|
||||
.iter()
|
||||
.any(|item| matches!(item, RolloutItem::EventMsg(EventMsg::TurnStarted(_))));
|
||||
let mut update = if affects_metadata {
|
||||
self.observe_items(items)?
|
||||
} else {
|
||||
thread_updated_at_touch()
|
||||
};
|
||||
if advances_recency {
|
||||
update.advance_recency_at = Some(Utc::now());
|
||||
}
|
||||
self.merge_pending_update(Some(update));
|
||||
if !affects_metadata
|
||||
&& !self
|
||||
.pending_update
|
||||
.as_ref()
|
||||
.is_some_and(update_has_metadata_facts)
|
||||
&& self.last_touch_persisted_at.is_some_and(|last_touch| {
|
||||
Instant::now().duration_since(last_touch) < THREAD_UPDATED_AT_TOUCH_INTERVAL
|
||||
})
|
||||
{
|
||||
return None;
|
||||
}
|
||||
self.take_pending_update()
|
||||
}
|
||||
|
||||
fn observe_items(&mut self, items: &[RolloutItem]) -> Option<ThreadMetadataPatch> {
|
||||
self.observe_items_with_update(
|
||||
items,
|
||||
ThreadMetadataPatch {
|
||||
updated_at: Some(Utc::now()),
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
fn observe_resume_history(&mut self, items: &[RolloutItem]) -> Option<ThreadMetadataPatch> {
|
||||
let mut update = self.observe_items_with_update(items, ThreadMetadataPatch::default())?;
|
||||
if matches!(
|
||||
canonical_history_mode_from_rollout_items(items),
|
||||
ThreadHistoryMode::Paginated
|
||||
) {
|
||||
// Paginated rollouts never append metadata-only SessionMeta updates. Do not reapply
|
||||
// initial metadata when resume history is flushed after the first append.
|
||||
update.git_info = None;
|
||||
update.memory_mode = None;
|
||||
}
|
||||
Some(update)
|
||||
}
|
||||
|
||||
fn observe_items_with_update(
|
||||
&mut self,
|
||||
items: &[RolloutItem],
|
||||
mut update: ThreadMetadataPatch,
|
||||
) -> Option<ThreadMetadataPatch> {
|
||||
if items.is_empty() {
|
||||
return None;
|
||||
}
|
||||
for item in items {
|
||||
match item {
|
||||
RolloutItem::SessionMeta(meta_line) if meta_line.meta.id == self.thread_id => {
|
||||
// Never derive display metadata from the synthetic prompt.
|
||||
if codex_state::is_guardian_review_source(&meta_line.meta.source) {
|
||||
self.preview_seen = true;
|
||||
self.first_user_message_seen = true;
|
||||
self.title_seen = true;
|
||||
update.preview = Some(codex_state::GUARDIAN_THREAD_PREVIEW.to_string());
|
||||
}
|
||||
update.created_at = parse_session_timestamp(meta_line.meta.timestamp.as_str());
|
||||
update.creator_user_id = meta_line.meta.creator_user_id.clone();
|
||||
update.creator_account_id = meta_line.meta.creator_account_id.clone();
|
||||
update.source = Some(meta_line.meta.source.clone());
|
||||
if !meta_line.meta.originator.is_empty() {
|
||||
update.originator = Some(meta_line.meta.originator.clone());
|
||||
}
|
||||
update.thread_source = Some(meta_line.meta.thread_source.clone());
|
||||
update.agent_nickname = Some(meta_line.meta.agent_nickname.clone());
|
||||
update.agent_role = Some(meta_line.meta.agent_role.clone());
|
||||
update.agent_path = Some(meta_line.meta.agent_path.clone());
|
||||
if let Some(model_provider) = meta_line.meta.model_provider.clone()
|
||||
&& !model_provider.is_empty()
|
||||
{
|
||||
update.model_provider = Some(model_provider);
|
||||
}
|
||||
if !meta_line.meta.cli_version.is_empty() {
|
||||
update.cli_version = Some(meta_line.meta.cli_version.clone());
|
||||
}
|
||||
if !meta_line.meta.cwd.as_os_str().is_empty() {
|
||||
self.cwd_seen = true;
|
||||
update.cwd = Some(meta_line.meta.cwd.clone());
|
||||
}
|
||||
if let Some(git_info) = meta_line.git.clone() {
|
||||
update.git_info = Some(git_info_patch_from_observation(git_info));
|
||||
}
|
||||
if let Some(memory_mode) = meta_line.meta.memory_mode.as_deref()
|
||||
&& let Some(memory_mode) = parse_memory_mode(memory_mode)
|
||||
{
|
||||
update.memory_mode = Some(memory_mode);
|
||||
}
|
||||
}
|
||||
RolloutItem::TurnContext(turn_ctx) => {
|
||||
if !self.cwd_seen {
|
||||
self.cwd_seen = true;
|
||||
update.cwd = Some(turn_ctx.cwd.clone().into_path_buf());
|
||||
}
|
||||
update.model = Some(turn_ctx.model.clone());
|
||||
update.reasoning_effort = Some(turn_ctx.effort.clone());
|
||||
update.approval_mode = Some(turn_ctx.approval_policy);
|
||||
update.permission_profile = Some(turn_ctx.permission_profile.clone());
|
||||
}
|
||||
RolloutItem::EventMsg(EventMsg::UserMessage(user)) => {
|
||||
self.observe_user_message(user, &mut update);
|
||||
}
|
||||
RolloutItem::EventMsg(EventMsg::ItemCompleted(event)) => {
|
||||
if let TurnItem::UserMessage(user) = &event.item
|
||||
&& (!self.first_user_message_seen || !self.preview_seen || !self.title_seen)
|
||||
{
|
||||
self.observe_user_message(
|
||||
&user.as_legacy_user_message_event(),
|
||||
&mut update,
|
||||
);
|
||||
} else if let TurnItem::FunctionCallOutput(output) = &event.item
|
||||
&& !self.preview_seen
|
||||
&& let Some(preview) = codex_state::delegated_output_preview(output)
|
||||
{
|
||||
self.preview_seen = true;
|
||||
update.preview = Some(preview);
|
||||
}
|
||||
}
|
||||
RolloutItem::EventMsg(EventMsg::TokenCount(token_count)) => {
|
||||
if let Some(info) = token_count.info.as_ref() {
|
||||
update.token_usage = Some(info.total_token_usage.clone());
|
||||
}
|
||||
}
|
||||
RolloutItem::EventMsg(EventMsg::ThreadGoalUpdated(event)) => {
|
||||
if !self.preview_seen {
|
||||
let objective = event.goal.objective.trim();
|
||||
if !objective.is_empty() {
|
||||
self.preview_seen = true;
|
||||
update.preview = Some(objective.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
RolloutItem::EventMsg(EventMsg::ThreadSettingsApplied(event)) => {
|
||||
let settings = &event.thread_settings;
|
||||
self.cwd_seen = true;
|
||||
update.model = Some(settings.model.clone());
|
||||
update.model_provider = Some(settings.model_provider_id.clone());
|
||||
update.reasoning_effort = Some(settings.reasoning_effort.clone());
|
||||
update.cwd = Some(settings.cwd.clone().into_path_buf());
|
||||
update.approval_mode = Some(settings.approval_policy);
|
||||
update.permission_profile = Some(settings.permission_profile.clone());
|
||||
}
|
||||
RolloutItem::DynamicToolsUpdated { .. }
|
||||
| RolloutItem::SessionMeta(_)
|
||||
| RolloutItem::EventMsg(_)
|
||||
| RolloutItem::ResponseItem(_)
|
||||
| RolloutItem::InterAgentCommunication(_)
|
||||
| RolloutItem::InterAgentCommunicationMetadata { .. }
|
||||
| RolloutItem::Compacted(_)
|
||||
| RolloutItem::RealtimeItem(_)
|
||||
| RolloutItem::TokenUsageRecord(_)
|
||||
| RolloutItem::RetainedContext(_)
|
||||
| RolloutItem::SecurityRiskScore(_)
|
||||
| RolloutItem::WorldState(_) => {}
|
||||
}
|
||||
}
|
||||
Some(update)
|
||||
}
|
||||
|
||||
fn observe_user_message(&mut self, user: &UserMessageEvent, update: &mut ThreadMetadataPatch) {
|
||||
if (!self.first_user_message_seen || !self.preview_seen)
|
||||
&& let Some(preview) = user_message_preview(user)
|
||||
{
|
||||
if !self.first_user_message_seen {
|
||||
self.first_user_message_seen = true;
|
||||
update.first_user_message = Some(preview.clone());
|
||||
}
|
||||
if !self.preview_seen {
|
||||
self.preview_seen = true;
|
||||
update.preview = Some(preview);
|
||||
}
|
||||
}
|
||||
if !self.title_seen {
|
||||
let title = strip_user_message_prefix(user.message.as_str());
|
||||
if !title.is_empty() {
|
||||
self.title_seen = true;
|
||||
update.title = Some(title.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn merge_pending_update(&mut self, update: Option<ThreadMetadataPatch>) {
|
||||
let Some(update) = update else {
|
||||
return;
|
||||
};
|
||||
match self.pending_update.as_mut() {
|
||||
Some(pending_update) => pending_update.merge(update),
|
||||
None => self.pending_update = Some(update),
|
||||
}
|
||||
self.pending_update_generation = self.pending_update_generation.wrapping_add(1);
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_memory_mode(value: &str) -> Option<ThreadMemoryMode> {
|
||||
match value {
|
||||
"enabled" => Some(ThreadMemoryMode::Enabled),
|
||||
"disabled" => Some(ThreadMemoryMode::Disabled),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_session_timestamp(value: &str) -> Option<DateTime<Utc>> {
|
||||
DateTime::parse_from_rfc3339(value)
|
||||
.map(|timestamp| timestamp.with_timezone(&Utc))
|
||||
.or_else(|_| {
|
||||
NaiveDateTime::parse_from_str(value, "%Y-%m-%dT%H-%M-%S")
|
||||
.map(|timestamp| DateTime::from_naive_utc_and_offset(timestamp, Utc))
|
||||
})
|
||||
.ok()
|
||||
}
|
||||
|
||||
fn thread_updated_at_touch() -> ThreadMetadataPatch {
|
||||
ThreadMetadataPatch {
|
||||
updated_at: Some(Utc::now()),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn update_has_metadata_facts(update: &ThreadMetadataPatch) -> bool {
|
||||
update.rollout_path.is_some()
|
||||
|| update.preview.is_some()
|
||||
|| update.title.is_some()
|
||||
|| update.model_provider.is_some()
|
||||
|| update.model.is_some()
|
||||
|| update.reasoning_effort.is_some()
|
||||
|| update.created_at.is_some()
|
||||
|| update.advance_recency_at.is_some()
|
||||
|| update.source.is_some()
|
||||
|| update.originator.is_some()
|
||||
|| update.creator_user_id.is_some()
|
||||
|| update.creator_account_id.is_some()
|
||||
|| update.thread_source.is_some()
|
||||
|| update.agent_nickname.is_some()
|
||||
|| update.agent_role.is_some()
|
||||
|| update.agent_path.is_some()
|
||||
|| update.cwd.is_some()
|
||||
|| update.cli_version.is_some()
|
||||
|| update.approval_mode.is_some()
|
||||
|| update.permission_profile.is_some()
|
||||
|| update.token_usage.is_some()
|
||||
|| update.first_user_message.is_some()
|
||||
|| update.git_info.is_some()
|
||||
|| update.memory_mode.is_some()
|
||||
}
|
||||
|
||||
fn git_info_patch_from_observation(git_info: GitInfo) -> GitInfoPatch {
|
||||
GitInfoPatch {
|
||||
sha: git_info.commit_hash.map(|sha| Some(sha.0)),
|
||||
branch: git_info.branch.map(Some),
|
||||
origin_url: git_info.repository_url.map(Some),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::sync::Arc;
|
||||
|
||||
use codex_protocol::config_types::ApprovalsReviewer;
|
||||
use codex_protocol::config_types::CollaborationMode;
|
||||
use codex_protocol::config_types::ModeKind;
|
||||
use codex_protocol::config_types::ReasoningSummary;
|
||||
use codex_protocol::config_types::Settings;
|
||||
use codex_protocol::items::UserMessageItem;
|
||||
use codex_protocol::models::PermissionProfile;
|
||||
use codex_protocol::openai_models::ReasoningEffort;
|
||||
use codex_protocol::protocol::AskForApproval;
|
||||
use codex_protocol::protocol::ItemCompletedEvent;
|
||||
use codex_protocol::protocol::SessionMeta;
|
||||
use codex_protocol::protocol::SessionMetaLine;
|
||||
use codex_protocol::protocol::SessionSource;
|
||||
use codex_protocol::protocol::SubAgentSource;
|
||||
use codex_protocol::protocol::ThreadGoal;
|
||||
use codex_protocol::protocol::ThreadGoalStatus;
|
||||
use codex_protocol::protocol::ThreadGoalUpdatedEvent;
|
||||
use codex_protocol::protocol::ThreadSettingsAppliedEvent;
|
||||
use codex_protocol::protocol::ThreadSettingsSnapshot;
|
||||
use codex_protocol::protocol::TurnStartedEvent;
|
||||
use codex_protocol::protocol::UserMessageEvent;
|
||||
use codex_protocol::user_input::UserInput;
|
||||
use codex_rollout::CompactedItem;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
use super::*;
|
||||
use crate::CreateThreadParams;
|
||||
use crate::ThreadPersistenceMetadata;
|
||||
|
||||
#[tokio::test]
|
||||
async fn create_metadata_records_originator_without_project() {
|
||||
let thread_id = ThreadId::new();
|
||||
let sync = ThreadMetadataSync::for_create(&CreateThreadParams {
|
||||
attached_thread: false,
|
||||
creator_user_id: None,
|
||||
creator_account_id: None,
|
||||
session_id: thread_id.into(),
|
||||
thread_id,
|
||||
extra_config: None,
|
||||
forked_from_id: None,
|
||||
parent_thread_id: None,
|
||||
source: SessionSource::Exec,
|
||||
thread_source: None,
|
||||
originator: "test_originator".to_string(),
|
||||
base_instructions: codex_protocol::models::BaseInstructions::default(),
|
||||
dynamic_tools: Vec::new(),
|
||||
selected_capability_roots: Vec::new(),
|
||||
multi_agent_version: None,
|
||||
history_mode: ThreadHistoryMode::Legacy,
|
||||
history_base: None,
|
||||
subagent_history_start_ordinal: None,
|
||||
initial_window_id: codex_protocol::ContextWindowId::new_uuid_v7().to_string(),
|
||||
runtime_workspace_roots: None,
|
||||
metadata: ThreadPersistenceMetadata {
|
||||
cwd: None,
|
||||
model_provider: "test-provider".to_string(),
|
||||
memory_mode: ThreadMemoryMode::Enabled,
|
||||
},
|
||||
})
|
||||
.await;
|
||||
|
||||
let update = sync.take_pending_update().expect("pending metadata update");
|
||||
assert_eq!(
|
||||
(update.patch.project_id, update.patch.originator.as_deref()),
|
||||
(None, Some("test_originator")),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn guardian_resume_without_session_meta_preserves_compact_metadata() {
|
||||
let thread_id = ThreadId::new();
|
||||
let mut metadata = codex_state::ThreadMetadataBuilder::new(
|
||||
thread_id,
|
||||
Default::default(),
|
||||
Utc::now(),
|
||||
SessionSource::SubAgent(SubAgentSource::Other("guardian".to_string())),
|
||||
)
|
||||
.build("test-provider");
|
||||
metadata.history_mode = ThreadHistoryMode::Paginated;
|
||||
|
||||
let sync = ThreadMetadataSync::for_resume(
|
||||
&resume_params(
|
||||
thread_id,
|
||||
vec![RolloutItem::EventMsg(EventMsg::ItemCompleted(
|
||||
ItemCompletedEvent {
|
||||
content_token_count: None,
|
||||
thread_id,
|
||||
turn_id: "turn-1".to_string(),
|
||||
item: TurnItem::UserMessage(UserMessageItem::new(&[UserInput::Text {
|
||||
text: "large synthetic guardian prompt".to_string(),
|
||||
text_elements: Vec::new(),
|
||||
}])),
|
||||
started_at_ms: Some(0),
|
||||
completed_at_ms: 0,
|
||||
},
|
||||
))],
|
||||
),
|
||||
Some(&metadata),
|
||||
);
|
||||
|
||||
let update = sync.take_pending_update().expect("pending metadata update");
|
||||
assert_eq!(update.patch.name, None);
|
||||
assert_eq!(update.patch.title, None);
|
||||
assert_eq!(update.patch.preview, None);
|
||||
assert_eq!(update.patch.first_user_message, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resume_history_keeps_derived_metadata_pending_until_applied() {
|
||||
let thread_id = ThreadId::new();
|
||||
let mut sync = resume_sync(
|
||||
thread_id,
|
||||
vec![
|
||||
RolloutItem::SessionMeta(Box::new(session_meta(thread_id))),
|
||||
RolloutItem::EventMsg(EventMsg::UserMessage(user_message("hello metadata"))),
|
||||
],
|
||||
);
|
||||
|
||||
let update = sync.take_pending_update().expect("pending metadata update");
|
||||
assert_eq!(
|
||||
update
|
||||
.patch
|
||||
.created_at
|
||||
.expect("created_at should come from session metadata")
|
||||
.to_rfc3339(),
|
||||
"2025-01-03T12:00:00+00:00"
|
||||
);
|
||||
assert_eq!(update.patch.preview.as_deref(), Some("hello metadata"));
|
||||
assert_eq!(update.patch.originator.as_deref(), Some("test_originator"));
|
||||
assert_eq!(update.patch.title.as_deref(), Some("hello metadata"));
|
||||
assert_eq!(
|
||||
update.patch.first_user_message.as_deref(),
|
||||
Some("hello metadata")
|
||||
);
|
||||
assert_eq!(update.patch.updated_at, None);
|
||||
assert!(
|
||||
sync.take_pending_update().is_some(),
|
||||
"taking the pending update should not drop retry state"
|
||||
);
|
||||
|
||||
sync.mark_pending_update_applied(&update);
|
||||
assert!(sync.take_pending_update().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn goal_update_sets_preview_without_overriding_existing_preview() {
|
||||
let thread_id = ThreadId::new();
|
||||
let sync = resume_sync(
|
||||
thread_id,
|
||||
vec![
|
||||
RolloutItem::EventMsg(EventMsg::ThreadGoalUpdated(goal_update(
|
||||
thread_id,
|
||||
"ship the refactor",
|
||||
))),
|
||||
RolloutItem::EventMsg(EventMsg::UserMessage(user_message("first user text"))),
|
||||
],
|
||||
);
|
||||
|
||||
let update = sync.take_pending_update().expect("pending metadata update");
|
||||
assert_eq!(update.patch.preview.as_deref(), Some("ship the refactor"));
|
||||
assert_eq!(update.patch.title.as_deref(), Some("first user text"));
|
||||
assert_eq!(
|
||||
update.patch.first_user_message.as_deref(),
|
||||
Some("first user text")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn later_user_messages_do_not_emit_existing_preview_fields() {
|
||||
let thread_id = ThreadId::new();
|
||||
let mut sync = resume_sync(
|
||||
thread_id,
|
||||
vec![RolloutItem::EventMsg(EventMsg::UserMessage(user_message(
|
||||
"first user text",
|
||||
)))],
|
||||
);
|
||||
let pending = sync.take_pending_update().expect("pending resume metadata");
|
||||
sync.mark_pending_update_applied(&pending);
|
||||
|
||||
let update = sync
|
||||
.observe_appended_items(&[RolloutItem::EventMsg(EventMsg::UserMessage(user_message(
|
||||
"later user text",
|
||||
)))])
|
||||
.expect("updated_at touch");
|
||||
|
||||
assert_eq!(update.patch.preview, None);
|
||||
assert_eq!(update.patch.title, None);
|
||||
assert_eq!(update.patch.first_user_message, None);
|
||||
assert!(update.patch.updated_at.is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn completed_user_message_items_emit_metadata_fields() {
|
||||
let thread_id = ThreadId::new();
|
||||
let mut sync = resume_sync(thread_id, Vec::new());
|
||||
let update = sync
|
||||
.observe_appended_items(&[RolloutItem::EventMsg(EventMsg::ItemCompleted(
|
||||
ItemCompletedEvent {
|
||||
content_token_count: None,
|
||||
thread_id,
|
||||
turn_id: "turn-1".to_string(),
|
||||
item: TurnItem::UserMessage(UserMessageItem::new(&[UserInput::Text {
|
||||
text: "first user text".to_string(),
|
||||
text_elements: Vec::new(),
|
||||
}])),
|
||||
started_at_ms: Some(0),
|
||||
completed_at_ms: 0,
|
||||
},
|
||||
))])
|
||||
.expect("completed user message metadata update");
|
||||
|
||||
assert_eq!(update.patch.preview.as_deref(), Some("first user text"));
|
||||
assert_eq!(update.patch.title.as_deref(), Some("first user text"));
|
||||
assert_eq!(
|
||||
update.patch.first_user_message.as_deref(),
|
||||
Some("first user text")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn metadata_irrelevant_items_coalesce_updated_at_touches() {
|
||||
let thread_id = ThreadId::new();
|
||||
let mut sync = resume_sync(thread_id, Vec::new());
|
||||
let item = RolloutItem::Compacted(Box::new(CompactedItem {
|
||||
message: "compacted".to_string(),
|
||||
replacement_history: None,
|
||||
retained_context: None,
|
||||
guardian_history: None,
|
||||
mcp_resource_origins: None,
|
||||
window_number: None,
|
||||
first_window_id: None,
|
||||
previous_window_id: None,
|
||||
window_id: None,
|
||||
compaction_response_id: None,
|
||||
latest_token_usage_record: None,
|
||||
resume_metadata: None,
|
||||
}));
|
||||
|
||||
let first = sync
|
||||
.observe_appended_items(std::slice::from_ref(&item))
|
||||
.expect("first touch should apply immediately");
|
||||
assert!(first.patch.updated_at.is_some());
|
||||
sync.mark_pending_update_applied(&first);
|
||||
|
||||
assert!(
|
||||
sync.observe_appended_items(std::slice::from_ref(&item))
|
||||
.is_none(),
|
||||
"second touch inside the coalescing window should wait for a barrier"
|
||||
);
|
||||
assert!(
|
||||
sync.take_pending_update().is_some(),
|
||||
"coalesced touches still flush at the next barrier"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn turn_start_advances_recency_at_without_changing_updated_at_behavior() {
|
||||
let thread_id = ThreadId::new();
|
||||
let mut sync = resume_sync(thread_id, Vec::new());
|
||||
|
||||
let update = sync
|
||||
.observe_appended_items(&[RolloutItem::EventMsg(EventMsg::TurnStarted(
|
||||
TurnStartedEvent {
|
||||
turn_attribution: None,
|
||||
turn_id: "turn-1".to_string(),
|
||||
root_turn_id: None,
|
||||
trace_id: None,
|
||||
started_at: None,
|
||||
model_context_window: None,
|
||||
collaboration_mode_kind: Default::default(),
|
||||
},
|
||||
))])
|
||||
.expect("turn start metadata update");
|
||||
|
||||
assert!(update.patch.updated_at.is_some());
|
||||
assert!(update.patch.advance_recency_at.is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn thread_settings_applied_updates_live_metadata() {
|
||||
let thread_id = ThreadId::new();
|
||||
let mut sync = resume_sync(thread_id, Vec::new());
|
||||
let permission_profile = PermissionProfile::workspace_write();
|
||||
let cwd = std::env::current_dir()
|
||||
.expect("current directory")
|
||||
.join("updated/workspace");
|
||||
|
||||
let mut item = RolloutItem::EventMsg(EventMsg::ThreadSettingsApplied(
|
||||
ThreadSettingsAppliedEvent {
|
||||
thread_id: None,
|
||||
thread_settings: ThreadSettingsSnapshot {
|
||||
disabled_plugin_ids: Vec::new(),
|
||||
model: "gpt-5.2-codex".to_string(),
|
||||
model_provider_id: "updated-provider".to_string(),
|
||||
service_tier: None,
|
||||
approval_policy: AskForApproval::Never,
|
||||
approvals_reviewer: ApprovalsReviewer::User,
|
||||
requested_approvals_reviewer: None,
|
||||
permission_profile: permission_profile.clone(),
|
||||
active_permission_profile: None,
|
||||
cwd: cwd.clone().try_into().expect("absolute settings cwd"),
|
||||
runtime_workspace_roots: None,
|
||||
reasoning_effort: Some(ReasoningEffort::Ultra),
|
||||
reasoning_summary: Some(ReasoningSummary::Auto),
|
||||
personality: None,
|
||||
collaboration_mode: CollaborationMode {
|
||||
mode: ModeKind::Default,
|
||||
settings: Settings {
|
||||
model: "gpt-5.2-codex".to_string(),
|
||||
reasoning_effort: Some(ReasoningEffort::Ultra),
|
||||
developer_instructions: None,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
));
|
||||
|
||||
let update = sync
|
||||
.observe_appended_items(&[item.clone()])
|
||||
.expect("thread settings metadata update");
|
||||
|
||||
assert_eq!(update.patch.model.as_deref(), Some("gpt-5.2-codex"));
|
||||
assert_eq!(
|
||||
update.patch.model_provider.as_deref(),
|
||||
Some("updated-provider")
|
||||
);
|
||||
assert_eq!(
|
||||
update.patch.reasoning_effort,
|
||||
Some(Some(ReasoningEffort::Ultra))
|
||||
);
|
||||
assert_eq!(update.patch.cwd, Some(cwd));
|
||||
assert_eq!(update.patch.approval_mode, Some(AskForApproval::Never));
|
||||
assert_eq!(update.patch.permission_profile, Some(permission_profile));
|
||||
|
||||
let RolloutItem::EventMsg(EventMsg::ThreadSettingsApplied(event)) = &mut item else {
|
||||
panic!("thread settings applied item");
|
||||
};
|
||||
event.thread_settings.reasoning_effort = None;
|
||||
event
|
||||
.thread_settings
|
||||
.collaboration_mode
|
||||
.settings
|
||||
.reasoning_effort = None;
|
||||
|
||||
let update = sync
|
||||
.observe_appended_items(&[item])
|
||||
.expect("thread settings clear metadata update");
|
||||
assert_eq!(update.patch.reasoning_effort, Some(None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resume_history_waits_for_append_before_flushing_metadata() {
|
||||
let thread_id = ThreadId::new();
|
||||
let mut sync = resume_sync(
|
||||
thread_id,
|
||||
vec![
|
||||
RolloutItem::SessionMeta(Box::new(session_meta(thread_id))),
|
||||
RolloutItem::EventMsg(EventMsg::UserMessage(user_message("hello metadata"))),
|
||||
],
|
||||
);
|
||||
|
||||
assert!(
|
||||
sync.take_pending_update_for_existing_history().is_none(),
|
||||
"resume-only metadata should not flush without a new append"
|
||||
);
|
||||
assert!(
|
||||
sync.observe_appended_items(&[RolloutItem::EventMsg(EventMsg::UserMessage(
|
||||
user_message("new append"),
|
||||
))])
|
||||
.is_some(),
|
||||
"the first append should flush resume metadata together with append metadata"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paginated_resume_history_does_not_reapply_initial_metadata() {
|
||||
let thread_id = ThreadId::new();
|
||||
let mut meta = session_meta(thread_id);
|
||||
meta.meta.history_mode = ThreadHistoryMode::Paginated;
|
||||
meta.meta.memory_mode = Some("disabled".to_string());
|
||||
meta.git = Some(GitInfo {
|
||||
commit_hash: None,
|
||||
branch: Some("stale-branch".to_string()),
|
||||
repository_url: None,
|
||||
});
|
||||
let sync = resume_sync(
|
||||
thread_id,
|
||||
vec![
|
||||
RolloutItem::SessionMeta(Box::new(meta)),
|
||||
RolloutItem::EventMsg(EventMsg::UserMessage(user_message("hello metadata"))),
|
||||
],
|
||||
);
|
||||
|
||||
let update = sync.take_pending_update().expect("pending metadata update");
|
||||
assert_eq!(update.patch.git_info, None);
|
||||
assert_eq!(update.patch.memory_mode, None);
|
||||
assert_eq!(update.patch.preview.as_deref(), Some("hello metadata"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resume_preserves_existing_display_metadata_and_initializes_missing_title() {
|
||||
let thread_id = ThreadId::new();
|
||||
let mut metadata = codex_state::ThreadMetadataBuilder::new(
|
||||
thread_id,
|
||||
Default::default(),
|
||||
Utc::now(),
|
||||
SessionSource::Exec,
|
||||
)
|
||||
.build("test-provider");
|
||||
metadata.preview = Some("goal-first preview".to_string());
|
||||
metadata.first_user_message = Some("[Image]".to_string());
|
||||
let params = resume_params(
|
||||
thread_id,
|
||||
vec![RolloutItem::EventMsg(EventMsg::UserMessage(user_message(
|
||||
"first textual user message",
|
||||
)))],
|
||||
);
|
||||
|
||||
let sync = ThreadMetadataSync::for_resume(¶ms, Some(&metadata));
|
||||
let update = sync.take_pending_update().expect("pending metadata update");
|
||||
|
||||
assert_eq!(update.patch.preview, None);
|
||||
assert_eq!(update.patch.first_user_message, None);
|
||||
assert_eq!(
|
||||
update.patch.title.as_deref(),
|
||||
Some("first textual user message")
|
||||
);
|
||||
}
|
||||
|
||||
fn resume_sync(thread_id: ThreadId, history: Vec<RolloutItem>) -> ThreadMetadataSync {
|
||||
ThreadMetadataSync::for_resume(&resume_params(thread_id, history), /*metadata*/ None)
|
||||
}
|
||||
|
||||
fn resume_params(thread_id: ThreadId, history: Vec<RolloutItem>) -> ResumeThreadParams {
|
||||
ResumeThreadParams {
|
||||
history_revision: None,
|
||||
thread_id,
|
||||
rollout_path: None,
|
||||
history: Some(Arc::new(history)),
|
||||
include_archived: false,
|
||||
metadata: ThreadPersistenceMetadata {
|
||||
cwd: None,
|
||||
model_provider: "test-provider".to_string(),
|
||||
memory_mode: ThreadMemoryMode::Enabled,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn user_message(message: &str) -> UserMessageEvent {
|
||||
UserMessageEvent {
|
||||
client_id: None,
|
||||
message: message.to_string(),
|
||||
images: None,
|
||||
local_images: Vec::new(),
|
||||
text_elements: Vec::new(),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn session_meta(thread_id: ThreadId) -> SessionMetaLine {
|
||||
SessionMetaLine {
|
||||
meta: SessionMeta {
|
||||
session_id: thread_id.into(),
|
||||
id: thread_id,
|
||||
timestamp: "2025-01-03T12:00:00Z".to_string(),
|
||||
source: SessionSource::Exec,
|
||||
originator: "test_originator".to_string(),
|
||||
..Default::default()
|
||||
},
|
||||
git: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn goal_update(thread_id: ThreadId, objective: &str) -> ThreadGoalUpdatedEvent {
|
||||
ThreadGoalUpdatedEvent {
|
||||
thread_id,
|
||||
turn_id: None,
|
||||
goal: ThreadGoal {
|
||||
thread_id,
|
||||
objective: objective.to_string(),
|
||||
status: ThreadGoalStatus::Active,
|
||||
token_budget: None,
|
||||
tokens_used: 0,
|
||||
time_used_seconds: 0,
|
||||
created_at: 0,
|
||||
updated_at: 0,
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
//! Verify delegated inputs emit a preview-only live metadata patch exactly once.
|
||||
|
||||
use super::*;
|
||||
use crate::ThreadPersistenceMetadata;
|
||||
use codex_protocol::items::FunctionCallOutputItem;
|
||||
use codex_protocol::models::FunctionCallOutputBody;
|
||||
use codex_protocol::protocol::ItemCompletedEvent;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn delegated_output_emits_only_first_preview_in_live_patch() {
|
||||
let thread_id = ThreadId::new();
|
||||
let mut sync = ThreadMetadataSync::for_resume(
|
||||
&ResumeThreadParams {
|
||||
thread_id,
|
||||
rollout_path: None,
|
||||
history: None,
|
||||
history_revision: None,
|
||||
include_archived: false,
|
||||
metadata: ThreadPersistenceMetadata {
|
||||
cwd: None,
|
||||
model_provider: "test-provider".to_string(),
|
||||
memory_mode: ThreadMemoryMode::Enabled,
|
||||
},
|
||||
},
|
||||
/*metadata*/ None,
|
||||
);
|
||||
for (index, text) in ["first task", "later task"].into_iter().enumerate() {
|
||||
let item = RolloutItem::EventMsg(EventMsg::ItemCompleted(ItemCompletedEvent {
|
||||
content_token_count: None,
|
||||
thread_id,
|
||||
turn_id: "turn".to_string(),
|
||||
item: TurnItem::FunctionCallOutput(FunctionCallOutputItem {
|
||||
id: format!("output-{index}"),
|
||||
name: "create_thread".to_string(),
|
||||
namespace: Some("codex_tui".to_string()),
|
||||
output: FunctionCallOutputBody::Text(format!(
|
||||
"<codex_delegation>\n <source_thread_id>source</source_thread_id>\n <input>{text}</input>\n</codex_delegation>"
|
||||
)),
|
||||
}),
|
||||
started_at_ms: Some(0),
|
||||
completed_at_ms: 0,
|
||||
}));
|
||||
let update = sync.observe_appended_items(&[item]);
|
||||
if index == 0 {
|
||||
let update = update.expect("first delegated preview patch");
|
||||
let expected = ThreadMetadataPatch {
|
||||
preview: Some(text.to_string()),
|
||||
updated_at: update.patch.updated_at,
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(
|
||||
serde_json::to_value(&update.patch).unwrap(),
|
||||
serde_json::to_value(expected).unwrap()
|
||||
);
|
||||
sync.mark_pending_update_applied(&update);
|
||||
} else {
|
||||
assert_eq!(update.and_then(|update| update.patch.preview), None);
|
||||
}
|
||||
}
|
||||
}
|
||||
52
codex-rs/thread-store/src/thread_sections.rs
Normal file
52
codex-rs/thread-store/src/thread_sections.rs
Normal file
@@ -0,0 +1,52 @@
|
||||
/// Parameters for listing independently persisted thread sections.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct ListThreadSectionsParams {
|
||||
/// Opaque cursor returned by a previous section listing.
|
||||
pub cursor: Option<String>,
|
||||
/// Maximum number of sections to return.
|
||||
pub limit: usize,
|
||||
}
|
||||
|
||||
/// Parameters for creating a thread section.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct CreateThreadSectionParams {
|
||||
/// User-facing section name.
|
||||
pub name: String,
|
||||
pub appearance: Option<codex_state::ThreadSectionAppearance>,
|
||||
}
|
||||
|
||||
/// Parameters for renaming a thread section.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct RenameThreadSectionParams {
|
||||
/// Stable identifier of the section to rename.
|
||||
pub section_id: String,
|
||||
/// Replacement user-facing section name.
|
||||
pub name: String,
|
||||
pub appearance: Option<Option<codex_state::ThreadSectionAppearance>>,
|
||||
}
|
||||
|
||||
/// Parameters for deleting a thread section.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct DeleteThreadSectionParams {
|
||||
/// Stable identifier of the section to delete.
|
||||
pub section_id: String,
|
||||
}
|
||||
|
||||
/// An independently persisted thread section and its user-facing name.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct StoredThreadSection {
|
||||
/// Stable, server-owned section identifier.
|
||||
pub id: String,
|
||||
/// User-facing section name.
|
||||
pub name: String,
|
||||
pub appearance: Option<codex_state::ThreadSectionAppearance>,
|
||||
}
|
||||
|
||||
/// A cursor-paginated page of independently persisted thread sections.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct StoredThreadSectionsPage {
|
||||
/// Sections returned for this page.
|
||||
pub sections: Vec<StoredThreadSection>,
|
||||
/// Opaque cursor to continue listing sections.
|
||||
pub next_cursor: Option<String>,
|
||||
}
|
||||
1190
codex-rs/thread-store/src/types.rs
Normal file
1190
codex-rs/thread-store/src/types.rs
Normal file
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user