Support metadata staging for reserved thread IDs (#38819)

## Why

Callers need to associate host-owned state with a thread before Core starts it.

## What changed

- Add `ThreadManager::reserve_thread_id` and allow new threads to start with the reserved ID. Reject reserved IDs when resuming an existing thread.
- Let thread stores stage metadata for a reserved ID. The local store merges staged values into the first successful metadata update and then removes them.
- Clear staged metadata when an unmaterialized thread shuts down or is discarded, and require the state database for staging.

## Testing

- Cover reserved ID generation and resume validation.
- Cover metadata persistence, merging, rollout-compatible updates, cleanup, and invalid staging requests.

GitOrigin-RevId: 3f9bc48f0f7764011cc90ea01349e497dda0a9e3
This commit is contained in:
Anton Panasenko
2026-08-16 00:57:28 +00:00
committed by copyberry
parent 5ba12929f8
commit fcdae21073
17 changed files with 650 additions and 21 deletions
+1
View File
@@ -120,6 +120,7 @@ pub(crate) async fn run_codex_thread_interactive(
environment_selections: parent_environments.to_selections(),
thread_extension_init: codex_extension_api::ExtensionDataInit::default(),
client_mcp_extensions: parent_session.services.client_mcp_extensions.clone(),
reserved_thread_id: None,
analytics_events_client: Some(parent_session.services.analytics_events_client.clone()),
thread_store: Arc::clone(&parent_session.services.thread_store),
attestation_provider: parent_session.services.attestation_provider.clone(),
+3
View File
@@ -422,6 +422,7 @@ pub(crate) struct SessionSpawnArgs {
pub(crate) environment_selections: Vec<TurnEnvironmentSelection>,
pub(crate) thread_extension_init: ExtensionDataInit,
pub(crate) client_mcp_extensions: ClientMcpExtensions,
pub(crate) reserved_thread_id: Option<ThreadId>,
pub(crate) analytics_events_client: Option<AnalyticsEventsClient>,
pub(crate) thread_store: Arc<dyn ThreadStore>,
pub(crate) attestation_provider: Option<Arc<dyn AttestationProvider>>,
@@ -514,6 +515,7 @@ impl Session {
environment_selections,
thread_extension_init,
client_mcp_extensions,
reserved_thread_id,
analytics_events_client,
thread_store,
attestation_provider,
@@ -742,6 +744,7 @@ impl Session {
thread_extension_init,
client_mcp_extensions,
agent_control,
reserved_thread_id,
environment_manager,
inherited_environments,
analytics_events_client,
+13 -3
View File
@@ -605,6 +605,7 @@ impl Session {
mut thread_extension_init: ExtensionDataInit,
client_mcp_extensions: ClientMcpExtensions,
agent_control: AgentControl,
reserved_thread_id: Option<ThreadId>,
environment_manager: Arc<EnvironmentManager>,
inherited_environments: Option<TurnEnvironmentSnapshot>,
analytics_events_client: Option<AnalyticsEventsClient>,
@@ -663,11 +664,20 @@ impl Session {
let multi_agent_version = multi_agent_version.map(OnceLock::from).unwrap_or_default();
let initial_multi_agent_version = multi_agent_version.get().copied();
let thread_id = match &initial_history {
InitialHistory::New | InitialHistory::Cleared | InitialHistory::Forked(_) => {
let thread_id = match (&initial_history, reserved_thread_id) {
(
InitialHistory::New | InitialHistory::Cleared | InitialHistory::Forked(_),
Some(thread_id),
) => thread_id,
(InitialHistory::New | InitialHistory::Cleared | InitialHistory::Forked(_), None) => {
agent_control.generate_thread_id()
}
InitialHistory::Resumed(resumed_history) => resumed_history.conversation_id,
(InitialHistory::Resumed(resumed_history), None) => resumed_history.conversation_id,
(InitialHistory::Resumed(_), Some(_)) => {
return Err(anyhow::anyhow!(
"reserved thread ID cannot be used when resuming a thread"
));
}
};
let resumed_session_id = match &initial_history {
InitialHistory::Resumed(resumed) => {
+3
View File
@@ -5695,6 +5695,7 @@ async fn session_new_fails_when_zsh_fork_enabled_without_packaged_zsh() {
codex_extension_api::ExtensionDataInit::default(),
ClientMcpExtensions::default(),
AgentControl::default(),
/*reserved_thread_id*/ None,
environment_manager,
/*inherited_environments*/ None,
/*analytics_events_client*/ None,
@@ -6122,6 +6123,7 @@ async fn make_session_with_config_and_rx(
codex_extension_api::ExtensionDataInit::default(),
ClientMcpExtensions::default(),
AgentControl::default(),
/*reserved_thread_id*/ None,
environment_manager,
/*inherited_environments*/ None,
/*analytics_events_client*/ None,
@@ -6240,6 +6242,7 @@ async fn make_session_with_history_source_and_agent_control_and_rx(
codex_extension_api::ExtensionDataInit::default(),
ClientMcpExtensions::default(),
agent_control,
/*reserved_thread_id*/ None,
environment_manager,
/*inherited_environments*/ None,
/*analytics_events_client*/ None,
@@ -832,6 +832,7 @@ async fn guardian_subagent_does_not_inherit_parent_exec_policy_rules() {
environment_selections: Vec::new(),
thread_extension_init: codex_extension_api::ExtensionDataInit::default(),
client_mcp_extensions: ClientMcpExtensions::default(),
reserved_thread_id: None,
analytics_events_client: None,
thread_store,
attestation_provider: None,
+15
View File
@@ -231,6 +231,8 @@ pub struct StartThreadOptions {
pub environments: Option<Vec<TurnEnvironmentSelection>>,
pub thread_extension_init: ExtensionDataInit,
pub client_mcp_extensions: ClientMcpExtensions,
/// Thread ID reserved before startup so the caller can associate host-owned state with it.
pub reserved_thread_id: Option<ThreadId>,
}
impl StartThreadOptions {
@@ -248,6 +250,7 @@ impl StartThreadOptions {
environments: None,
thread_extension_init: ExtensionDataInit::default(),
client_mcp_extensions: ClientMcpExtensions::default(),
reserved_thread_id: None,
}
}
}
@@ -891,6 +894,11 @@ impl ThreadManager {
Box::pin(self.start_thread_inner(options, /*forked_from_thread_id*/ None)).await
}
/// Allocates a thread ID before startup so a caller can associate host-owned state with it.
pub fn reserve_thread_id(&self) -> ThreadId {
self.state.thread_id_generator.as_ref()()
}
async fn start_thread_inner(
&self,
mut options: StartThreadOptions,
@@ -1755,6 +1763,7 @@ impl ThreadManagerState {
environments,
thread_extension_init,
client_mcp_extensions,
reserved_thread_id,
} = options;
let session_source = session_source.unwrap_or_else(|| self.session_source.clone());
let environments = environments.unwrap_or_else(|| {
@@ -1765,6 +1774,11 @@ impl ThreadManagerState {
)
});
let is_resumed_thread = matches!(&initial_history, InitialHistory::Resumed(_));
if reserved_thread_id.is_some() && matches!(&initial_history, InitialHistory::Resumed(_)) {
return Err(CodexErr::InvalidRequest(
"reserved thread ID cannot be used when resuming a thread".to_string(),
));
}
if let InitialHistory::Resumed(resumed) = &initial_history {
let mut threads = self.threads.write().await;
if let Some(thread) = threads.get(&resumed.conversation_id).cloned() {
@@ -1851,6 +1865,7 @@ impl ThreadManagerState {
environment_selections: environments,
thread_extension_init,
client_mcp_extensions,
reserved_thread_id,
analytics_events_client: self.analytics_events_client.clone(),
thread_store: Arc::clone(&self.thread_store),
attestation_provider: self.attestation_provider.clone(),
+56
View File
@@ -58,6 +58,62 @@ fn thread_id_generator_defaults_to_standard_ids() {
);
}
#[tokio::test]
async fn reserved_thread_id_is_used_without_changing_normal_id_generation() {
let temp_dir = tempdir().expect("tempdir");
let mut config = test_config().await;
config.codex_home = temp_dir.path().join("codex-home").abs();
config.cwd = config.codex_home.abs();
std::fs::create_dir_all(&config.codex_home).expect("create codex home");
let generated_ids = [
ThreadId::from_u128(/*value*/ 0x018f_0000_0000_7000_8000_0000_0000_0001),
ThreadId::from_u128(/*value*/ 0x018f_0000_0000_7000_8000_0000_0000_0002),
ThreadId::from_u128(/*value*/ 0x018f_0000_0000_7000_8000_0000_0000_0003),
];
let next_id = std::sync::atomic::AtomicUsize::new(0);
let manager = ThreadManager::with_models_provider_and_home_for_tests(
CodexAuth::from_api_key("dummy"),
config.model_provider.clone(),
config.codex_home.to_path_buf(),
Arc::new(codex_exec_server::EnvironmentManager::default_for_tests()),
)
.with_thread_id_generator(move || generated_ids[next_id.fetch_add(1, Ordering::Relaxed)]);
let reserved_id = manager.reserve_thread_id();
let mut reserved_options = StartThreadOptions::new(config.clone());
reserved_options.reserved_thread_id = Some(reserved_id);
let reserved = manager
.start_thread(reserved_options)
.await
.expect("start reserved thread");
let mut resumed_options = StartThreadOptions::new(config.clone());
resumed_options.initial_history = InitialHistory::Resumed(ResumedHistory {
conversation_id: reserved.thread_id,
history: Arc::new(Vec::new()),
rollout_path: None,
});
let resumed_id = manager.reserve_thread_id();
resumed_options.reserved_thread_id = Some(resumed_id);
let resume_error = manager
.start_thread(resumed_options)
.await
.err()
.expect("reject reserved ID for resume");
let generated = manager
.start_thread(StartThreadOptions::new(config.clone()))
.await
.expect("start generated thread");
assert_eq!(reserved.thread_id, generated_ids[0]);
assert!(matches!(
resume_error.details(),
codex_protocol::error::CodexErrorDetails::InvalidRequest(message)
if message == "reserved thread ID cannot be used when resuming a thread"
));
assert_eq!(generated.thread_id, generated_ids[2]);
}
/// One custom ID factory supplies identifiers for roots, actual child agents, and forks.
#[tokio::test]
async fn thread_id_generator_applies_to_roots_children_and_forks() {