mirror of
https://github.com/openai/codex.git
synced 2026-12-02 00:31:03 +00:00
Support prepared creation of persisted threads (#64839)
## Why Thread stores can do work before Core starts, but the ordinary creation API has no way to pass that state back to the store when it creates the thread. ## What changed Pass optional, single-use `ThreadStoreCreatePreparation` from `StartThreadOptions` to `ThreadStore::create_thread_with_preparation` when creating a persisted thread, including a fork. Reject creation preparation for ephemeral or resumed threads. Stores that do not implement the prepared creation method return an unsupported-operation error. ## Testing Add a regression test that supplies creation preparation to a prepared fork and checks that it reaches the prepared creation method by asserting the default unsupported-operation error. GitOrigin-RevId: bc4d3e9e5d89dd7503aed75423bc9c9d42c7f7fc
This commit is contained in:
@@ -138,6 +138,7 @@ pub(crate) async fn run_codex_thread_interactive(
|
||||
code_mode_session_provider: parent_session.services.code_mode_service.session_provider(),
|
||||
extensions,
|
||||
conversation_history,
|
||||
create_preparation: None,
|
||||
resume_preparation: None,
|
||||
history_initialization,
|
||||
disabled_plugin_ids: (isolation == codex_extension_api::SessionIsolation::Inherit)
|
||||
|
||||
@@ -199,6 +199,7 @@ use codex_thread_store::PersistContext;
|
||||
use codex_thread_store::ReadThreadParams;
|
||||
use codex_thread_store::ResumeThreadParams;
|
||||
use codex_thread_store::ThreadStore;
|
||||
use codex_thread_store::ThreadStoreCreatePreparation;
|
||||
use codex_thread_store::ThreadStoreResumePreparation;
|
||||
use codex_utils_audio::prepare_response_items as prepare_audio_response_items;
|
||||
use codex_utils_git_discovery::GitRootDiscovery;
|
||||
@@ -554,6 +555,7 @@ pub(crate) struct SessionSpawnArgs {
|
||||
pub(crate) code_mode_session_provider: Arc<dyn codex_code_mode::CodeModeSessionProvider>,
|
||||
pub(crate) extensions: Arc<codex_extension_api::ExtensionRegistry<crate::config::Config>>,
|
||||
pub(crate) conversation_history: InitialHistory,
|
||||
pub(crate) create_preparation: Option<ThreadStoreCreatePreparation>,
|
||||
pub(crate) resume_preparation: Option<ThreadStoreResumePreparation>,
|
||||
pub(crate) history_initialization: HistoryInitialization,
|
||||
pub(crate) disabled_plugin_ids: Option<Vec<String>>,
|
||||
@@ -750,6 +752,7 @@ impl Session {
|
||||
code_mode_session_provider,
|
||||
extensions,
|
||||
conversation_history,
|
||||
create_preparation,
|
||||
resume_preparation,
|
||||
history_initialization,
|
||||
disabled_plugin_ids,
|
||||
@@ -1176,6 +1179,7 @@ impl Session {
|
||||
analytics_events_client,
|
||||
image_store,
|
||||
thread_store,
|
||||
create_preparation,
|
||||
resume_preparation,
|
||||
parent_rollout_thread_trace,
|
||||
attestation_provider,
|
||||
|
||||
@@ -835,6 +835,7 @@ impl Session {
|
||||
analytics_events_client: Option<AnalyticsEventsClient>,
|
||||
image_store: Arc<dyn AttachmentStore>,
|
||||
thread_store: Arc<dyn ThreadStore>,
|
||||
create_preparation: Option<ThreadStoreCreatePreparation>,
|
||||
resume_preparation: Option<ThreadStoreResumePreparation>,
|
||||
parent_rollout_thread_trace: ThreadTraceContext,
|
||||
attestation_provider: Option<Arc<dyn AttestationProvider>>,
|
||||
@@ -1191,13 +1192,30 @@ impl Session {
|
||||
Arc::clone(&thread_store),
|
||||
params,
|
||||
items,
|
||||
create_preparation,
|
||||
guard,
|
||||
)
|
||||
.await?
|
||||
} else {
|
||||
guard
|
||||
.acquire(LiveThread::create(Arc::clone(&thread_store), params))
|
||||
.await?
|
||||
match create_preparation {
|
||||
Some(preparation) => {
|
||||
guard
|
||||
.acquire(LiveThread::create_with_preparation(
|
||||
Arc::clone(&thread_store),
|
||||
params,
|
||||
preparation,
|
||||
))
|
||||
.await?
|
||||
}
|
||||
None => {
|
||||
guard
|
||||
.acquire(LiveThread::create(
|
||||
Arc::clone(&thread_store),
|
||||
params,
|
||||
))
|
||||
.await?
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
InitialHistory::Resumed(resumed_history) => {
|
||||
|
||||
@@ -7083,6 +7083,7 @@ async fn make_session_with_config_and_rx(
|
||||
codex_thread_store::LocalThreadStoreConfig::from_config(config.as_ref()),
|
||||
/*state_db*/ None,
|
||||
)),
|
||||
/*create_preparation*/ None,
|
||||
/*resume_preparation*/ None,
|
||||
codex_rollout_trace::ThreadTraceContext::disabled(),
|
||||
/*attestation_provider*/ None,
|
||||
@@ -7233,6 +7234,7 @@ async fn make_session_with_history_source_and_agent_control_and_rx(
|
||||
.expect("state db should initialize"),
|
||||
),
|
||||
)),
|
||||
/*create_preparation*/ None,
|
||||
/*resume_preparation*/ None,
|
||||
codex_rollout_trace::ThreadTraceContext::disabled(),
|
||||
/*attestation_provider*/ None,
|
||||
|
||||
@@ -1408,6 +1408,7 @@ async fn guardian_subagent_does_not_inherit_parent_exec_policy_rules() {
|
||||
code_mode_session_provider: Arc::new(codex_code_mode::DisabledCodeModeSessionProvider),
|
||||
extensions: codex_extension_api::empty_extension_registry(),
|
||||
conversation_history: InitialHistory::New,
|
||||
create_preparation: None,
|
||||
resume_preparation: None,
|
||||
history_initialization: HistoryInitialization::New,
|
||||
disabled_plugin_ids: None,
|
||||
|
||||
@@ -119,6 +119,7 @@ use codex_thread_store::StoredModelContext;
|
||||
use codex_thread_store::StoredThread;
|
||||
use codex_thread_store::ThreadMetadataPatch;
|
||||
use codex_thread_store::ThreadStore;
|
||||
use codex_thread_store::ThreadStoreCreatePreparation;
|
||||
use codex_thread_store::ThreadStoreError;
|
||||
use codex_thread_store::ThreadStoreResumePreparation;
|
||||
use codex_thread_store::UpdateThreadMetadataParams;
|
||||
@@ -380,6 +381,8 @@ pub struct StartThreadOptions {
|
||||
pub thread_instructions_provider: Option<Arc<dyn ThreadInstructionsProvider>>,
|
||||
pub allow_provider_model_fallback: bool,
|
||||
pub initial_history: InitialHistory,
|
||||
/// Store-owned state prepared before creating this thread.
|
||||
pub create_preparation: Option<ThreadStoreCreatePreparation>,
|
||||
/// Store-owned state prepared while loading the resumed history.
|
||||
pub resume_preparation: Option<ThreadStoreResumePreparation>,
|
||||
/// Parent captured for `start_thread`, including a parent not in the live registry.
|
||||
@@ -467,6 +470,7 @@ impl StartThreadOptions {
|
||||
allow_provider_model_fallback: false,
|
||||
initial_history: InitialHistory::New,
|
||||
inherited_multi_agent_version: None,
|
||||
create_preparation: None,
|
||||
resume_preparation: None,
|
||||
internal_parent: None,
|
||||
history_mode: None,
|
||||
@@ -2685,6 +2689,7 @@ impl ThreadManagerState {
|
||||
thread_instructions_provider,
|
||||
allow_provider_model_fallback,
|
||||
initial_history,
|
||||
create_preparation,
|
||||
resume_preparation,
|
||||
internal_parent: _,
|
||||
history_mode,
|
||||
@@ -2713,6 +2718,17 @@ impl ThreadManagerState {
|
||||
"thread store resume preparation requires a persisted resumed thread".to_string(),
|
||||
));
|
||||
}
|
||||
if create_preparation.is_some()
|
||||
&& (config.ephemeral
|
||||
|| !matches!(
|
||||
&initial_history,
|
||||
InitialHistory::New | InitialHistory::Cleared | InitialHistory::Forked(_)
|
||||
))
|
||||
{
|
||||
return Err(CodexErr::InvalidRequest(
|
||||
"thread store create preparation requires a persisted new thread".to_string(),
|
||||
));
|
||||
}
|
||||
let inherited_environments = captured_environments.or(inherited_environments);
|
||||
let session_source = session_source.unwrap_or_else(|| self.session_source.clone());
|
||||
if let Some(parent_id) = parent_thread_id
|
||||
@@ -3128,6 +3144,7 @@ impl ThreadManagerState {
|
||||
code_mode_session_provider: Arc::clone(&self.code_mode_session_provider),
|
||||
extensions,
|
||||
conversation_history: initial_history,
|
||||
create_preparation,
|
||||
resume_preparation,
|
||||
history_initialization: startup_context.history_initialization,
|
||||
disabled_plugin_ids,
|
||||
|
||||
@@ -20,6 +20,7 @@ use codex_protocol::user_input::UserInput;
|
||||
use codex_thread_store::InMemoryThreadStore;
|
||||
use codex_thread_store::InheritedHistoryVisibility;
|
||||
use codex_thread_store::PreparedFork;
|
||||
use codex_thread_store::ThreadStoreCreatePreparation;
|
||||
use core_test_support::responses::ev_completed;
|
||||
use core_test_support::responses::ev_response_created;
|
||||
use core_test_support::responses::sse;
|
||||
@@ -66,6 +67,40 @@ async fn prepared_fork_passes_inherited_history_visibility_to_store() -> anyhow:
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A supplied creation preparation must select the prepared store path instead of silently
|
||||
/// repeating ordinary thread creation.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn prepared_fork_uses_prepared_store_creation() -> anyhow::Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
|
||||
let server = MockServer::start().await;
|
||||
let test = test_codex().build_with_auto_env(&server).await?;
|
||||
let prepared = PreparedFork::with_source_revalidation(
|
||||
test.session_configured.thread_id,
|
||||
/*history_base*/ None,
|
||||
Arc::new(Vec::new()),
|
||||
);
|
||||
let mut options = test.start_thread_options().await;
|
||||
options.create_preparation = Some(ThreadStoreCreatePreparation::new(()));
|
||||
|
||||
let Err(error) = test
|
||||
.thread_manager
|
||||
.fork_prepared_thread(options, prepared, InheritedHistoryVisibility::Full)
|
||||
.await
|
||||
else {
|
||||
anyhow::bail!("prepared fork unexpectedly used ordinary thread creation");
|
||||
};
|
||||
assert!(
|
||||
matches!(
|
||||
error.details(),
|
||||
CodexErrorDetails::UnsupportedOperation(message)
|
||||
if message == "create_thread_with_preparation is not supported yet"
|
||||
),
|
||||
"unexpected prepared fork error: {error}"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn ephemeral_fork_skips_stored_title_lookup() -> anyhow::Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
|
||||
@@ -68,6 +68,7 @@ pub use store::PendingDaybreakPreference;
|
||||
pub use store::PersistContext;
|
||||
pub use store::ThreadSearchObserver;
|
||||
pub use store::ThreadStore;
|
||||
pub use store::ThreadStoreCreatePreparation;
|
||||
pub use store::ThreadStoreFuture;
|
||||
pub use store::ThreadStoreResumePreparation;
|
||||
pub use thread_attachments::AddThreadAttachmentParams;
|
||||
|
||||
@@ -26,6 +26,7 @@ use crate::StoredThread;
|
||||
use crate::StoredThreadHistory;
|
||||
use crate::ThreadMetadataPatch;
|
||||
use crate::ThreadStore;
|
||||
use crate::ThreadStoreCreatePreparation;
|
||||
use crate::ThreadStoreError;
|
||||
use crate::ThreadStoreFuture;
|
||||
use crate::ThreadStoreResult;
|
||||
@@ -138,6 +139,22 @@ impl LiveThread {
|
||||
pub async fn create(
|
||||
thread_store: Arc<dyn ThreadStore>,
|
||||
params: CreateThreadParams,
|
||||
) -> ThreadStoreResult<Self> {
|
||||
Self::create_inner(thread_store, params, /*preparation*/ None).await
|
||||
}
|
||||
|
||||
pub async fn create_with_preparation(
|
||||
thread_store: Arc<dyn ThreadStore>,
|
||||
params: CreateThreadParams,
|
||||
preparation: ThreadStoreCreatePreparation,
|
||||
) -> ThreadStoreResult<Self> {
|
||||
Self::create_inner(thread_store, params, Some(preparation)).await
|
||||
}
|
||||
|
||||
async fn create_inner(
|
||||
thread_store: Arc<dyn ThreadStore>,
|
||||
params: CreateThreadParams,
|
||||
preparation: Option<ThreadStoreCreatePreparation>,
|
||||
) -> ThreadStoreResult<Self> {
|
||||
let thread_id = params.thread_id;
|
||||
let history_mode = params.history_mode;
|
||||
@@ -151,7 +168,14 @@ impl LiveThread {
|
||||
};
|
||||
let metadata_sync =
|
||||
ThreadMetadataSync::for_create(¶ms, inherited_preview.as_deref()).await;
|
||||
thread_store.create_thread(params).await?;
|
||||
match preparation {
|
||||
Some(preparation) => {
|
||||
thread_store
|
||||
.create_thread_with_preparation(params, preparation)
|
||||
.await?;
|
||||
}
|
||||
None => thread_store.create_thread(params).await?,
|
||||
}
|
||||
Ok(Self {
|
||||
thread_id,
|
||||
history_mode,
|
||||
@@ -169,6 +193,7 @@ impl LiveThread {
|
||||
thread_store: Arc<dyn ThreadStore>,
|
||||
mut params: CreateThreadParams,
|
||||
inherited_model_context: &[RolloutItem],
|
||||
create_preparation: Option<ThreadStoreCreatePreparation>,
|
||||
guard: &mut LiveThreadInitGuard,
|
||||
) -> ThreadStoreResult<Self> {
|
||||
let persisted_prefix_item_count = inherited_model_context
|
||||
@@ -185,7 +210,18 @@ impl LiveThread {
|
||||
message: "inherited model context is too large".to_string(),
|
||||
})?,
|
||||
);
|
||||
let live_thread = guard.acquire(Self::create(thread_store, params)).await?;
|
||||
let live_thread = match create_preparation {
|
||||
Some(preparation) => {
|
||||
guard
|
||||
.acquire(Self::create_with_preparation(
|
||||
thread_store,
|
||||
params,
|
||||
preparation,
|
||||
))
|
||||
.await?
|
||||
}
|
||||
None => guard.acquire(Self::create(thread_store, params)).await?,
|
||||
};
|
||||
live_thread
|
||||
.persist_appended_items(inherited_model_context)
|
||||
.await?;
|
||||
|
||||
@@ -1352,6 +1352,7 @@ mod tests {
|
||||
store,
|
||||
params,
|
||||
&[user_message_item("legacy-only event"), parent.clone()],
|
||||
/*create_preparation*/ None,
|
||||
&mut guard,
|
||||
)
|
||||
.await
|
||||
|
||||
@@ -111,6 +111,37 @@ impl fmt::Debug for ThreadStoreResumePreparation {
|
||||
}
|
||||
}
|
||||
|
||||
/// Data a [`ThreadStore`] has prepared before Core creates a thread.
|
||||
///
|
||||
/// Core does not inspect this value. It gives the value back to the store when creating the
|
||||
/// thread, allowing the store to reuse work started before Core startup. The value can only be
|
||||
/// used once because it may own resources that cannot be copied.
|
||||
pub struct ThreadStoreCreatePreparation {
|
||||
state: Box<dyn Any + Send>,
|
||||
}
|
||||
|
||||
impl ThreadStoreCreatePreparation {
|
||||
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 ThreadStoreCreatePreparation {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("ThreadStoreCreatePreparation")
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
/// Why thread persistence is being requested.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum PersistContext {
|
||||
@@ -175,6 +206,22 @@ pub trait ThreadStore: Any + Send + Sync {
|
||||
/// Creates a new live thread.
|
||||
fn create_thread(&self, params: CreateThreadParams) -> ThreadStoreFuture<'_, ()>;
|
||||
|
||||
/// Creates a thread using implementation-owned state prepared before Core startup.
|
||||
///
|
||||
/// Stores should only override this when they also produce the preparation. Creation and
|
||||
/// failure cleanup guarantees are the same as [`Self::create_thread`].
|
||||
fn create_thread_with_preparation(
|
||||
&self,
|
||||
_params: CreateThreadParams,
|
||||
_preparation: ThreadStoreCreatePreparation,
|
||||
) -> ThreadStoreFuture<'_, ()> {
|
||||
Box::pin(async {
|
||||
Err(ThreadStoreError::Unsupported {
|
||||
operation: "create_thread_with_preparation",
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// 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.
|
||||
|
||||
Reference in New Issue
Block a user