mirror of
https://github.com/openai/codex.git
synced 2026-11-25 23:30:49 +00:00
Own thread initialization timing per operation
This commit is contained in:
@@ -113,6 +113,12 @@ pub struct ThreadInitializationProfile {
|
||||
pub thread_registration_ms: u64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct CompletedCoreThreadInitialization {
|
||||
pub initialization_mode: ThreadInitializationMode,
|
||||
pub profile: ThreadInitializationProfile,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct CompletedThreadInitialization {
|
||||
pub initialization_mode: ThreadInitializationMode,
|
||||
|
||||
@@ -31,6 +31,7 @@ pub use facts::CompactionReason;
|
||||
pub use facts::CompactionStatus;
|
||||
pub use facts::CompactionStrategy;
|
||||
pub use facts::CompactionTrigger;
|
||||
pub use facts::CompletedCoreThreadInitialization;
|
||||
pub use facts::CompletedThreadInitialization;
|
||||
pub use facts::HookRunFact;
|
||||
pub use facts::InputError;
|
||||
|
||||
@@ -1273,7 +1273,7 @@ impl AnalyticsReducer {
|
||||
&session_source,
|
||||
thread.thread_source.map(Into::into),
|
||||
parent_thread_id,
|
||||
initialization_mode,
|
||||
initialization.mode,
|
||||
);
|
||||
self.threads.insert(
|
||||
thread_id.clone(),
|
||||
|
||||
@@ -828,26 +828,24 @@ impl MessageProcessor {
|
||||
let rpc_gate = Arc::clone(&session.rpc_gate);
|
||||
let processor = Arc::clone(self);
|
||||
let span = request_context.span();
|
||||
let timing_context = request_context.clone();
|
||||
let request = QueuedInitializedRequest::new(
|
||||
rpc_gate,
|
||||
timing_context
|
||||
.scope_thread_initialization(async move {
|
||||
let processor_for_request = Arc::clone(&processor);
|
||||
let result = processor_for_request
|
||||
.handle_initialized_client_request(
|
||||
connection_request_id,
|
||||
codex_request,
|
||||
request_context,
|
||||
app_server_client_name,
|
||||
client_version,
|
||||
)
|
||||
.await;
|
||||
if let Err(error) = result {
|
||||
processor.outgoing.send_error(error_request_id, error).await;
|
||||
}
|
||||
})
|
||||
.instrument(span),
|
||||
async move {
|
||||
let processor_for_request = Arc::clone(&processor);
|
||||
let result = processor_for_request
|
||||
.handle_initialized_client_request(
|
||||
connection_request_id,
|
||||
codex_request,
|
||||
request_context,
|
||||
app_server_client_name,
|
||||
client_version,
|
||||
)
|
||||
.await;
|
||||
if let Err(error) = result {
|
||||
processor.outgoing.send_error(error_request_id, error).await;
|
||||
}
|
||||
}
|
||||
.instrument(span),
|
||||
);
|
||||
|
||||
if let Some(scope) = serialization_scope {
|
||||
|
||||
@@ -1,13 +1,15 @@
|
||||
use std::collections::HashMap;
|
||||
use std::future::Future;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::AtomicI64;
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::time::Instant;
|
||||
use std::time::SystemTime;
|
||||
use std::time::UNIX_EPOCH;
|
||||
|
||||
use codex_analytics::AnalyticsEventsClient;
|
||||
use codex_analytics::CompletedCoreThreadInitialization;
|
||||
use codex_analytics::CompletedThreadInitialization;
|
||||
use codex_analytics::ThreadInitializationProfile;
|
||||
use codex_analytics::ThreadInitializationResponseFact;
|
||||
use codex_app_server_protocol::ClientResponsePayload;
|
||||
use codex_app_server_protocol::JSONRPCErrorError;
|
||||
@@ -17,7 +19,6 @@ use codex_app_server_protocol::ServerNotification;
|
||||
use codex_app_server_protocol::ServerRequest;
|
||||
use codex_app_server_protocol::ServerRequestPayload;
|
||||
use codex_app_server_protocol::ServerResponse;
|
||||
use codex_core::ThreadInitializationTiming;
|
||||
use codex_otel::span_w3c_trace_context;
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::protocol::W3cTraceContext;
|
||||
@@ -55,7 +56,8 @@ pub(crate) struct RequestContext {
|
||||
request_id: ConnectionRequestId,
|
||||
span: Span,
|
||||
parent_trace: Option<W3cTraceContext>,
|
||||
thread_initialization_timing: ThreadInitializationTiming,
|
||||
request_started_at: Instant,
|
||||
thread_initialization: Option<CompletedCoreThreadInitialization>,
|
||||
}
|
||||
|
||||
impl RequestContext {
|
||||
@@ -63,12 +65,22 @@ impl RequestContext {
|
||||
request_id: ConnectionRequestId,
|
||||
span: Span,
|
||||
parent_trace: Option<W3cTraceContext>,
|
||||
) -> Self {
|
||||
Self::new_at(request_id, span, parent_trace, Instant::now())
|
||||
}
|
||||
|
||||
fn new_at(
|
||||
request_id: ConnectionRequestId,
|
||||
span: Span,
|
||||
parent_trace: Option<W3cTraceContext>,
|
||||
request_started_at: Instant,
|
||||
) -> Self {
|
||||
Self {
|
||||
request_id,
|
||||
span,
|
||||
parent_trace,
|
||||
thread_initialization_timing: ThreadInitializationTiming::begin_request(),
|
||||
request_started_at,
|
||||
thread_initialization: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -80,19 +92,40 @@ impl RequestContext {
|
||||
self.span.clone()
|
||||
}
|
||||
|
||||
pub(crate) fn scope_thread_initialization<F>(
|
||||
&self,
|
||||
future: F,
|
||||
) -> impl Future<Output = F::Output> + Send + 'static
|
||||
where
|
||||
F: Future + Send + 'static,
|
||||
{
|
||||
let timing = self.thread_initialization_timing.clone();
|
||||
async move { timing.scope(future).await }
|
||||
fn record_thread_initialization(&mut self, initialization: CompletedCoreThreadInitialization) {
|
||||
let Some(current) = self.thread_initialization.as_mut() else {
|
||||
self.thread_initialization = Some(initialization);
|
||||
return;
|
||||
};
|
||||
if current.initialization_mode != initialization.initialization_mode {
|
||||
warn!("ignored mismatched thread initialization timing segment");
|
||||
return;
|
||||
}
|
||||
merge_core_thread_initialization_profiles(&mut current.profile, initialization.profile);
|
||||
}
|
||||
|
||||
fn complete_thread_initialization(&self) -> Option<CompletedThreadInitialization> {
|
||||
self.thread_initialization_timing.complete_request()
|
||||
self.complete_thread_initialization_at(Instant::now())
|
||||
}
|
||||
|
||||
fn complete_thread_initialization_at(
|
||||
&self,
|
||||
completed_at: Instant,
|
||||
) -> Option<CompletedThreadInitialization> {
|
||||
let initialization = self.thread_initialization?;
|
||||
let mut profile = initialization.profile;
|
||||
profile.duration_ms = u64::try_from(
|
||||
completed_at
|
||||
.saturating_duration_since(self.request_started_at)
|
||||
.as_millis(),
|
||||
)
|
||||
.unwrap_or(u64::MAX);
|
||||
profile.app_server_duration_ms =
|
||||
profile.duration_ms.saturating_sub(profile.core_duration_ms);
|
||||
Some(CompletedThreadInitialization {
|
||||
initialization_mode: initialization.initialization_mode,
|
||||
profile,
|
||||
})
|
||||
}
|
||||
|
||||
fn record_turn_id(&self, turn_id: &str) {
|
||||
@@ -100,6 +133,36 @@ impl RequestContext {
|
||||
}
|
||||
}
|
||||
|
||||
fn merge_core_thread_initialization_profiles(
|
||||
profile: &mut ThreadInitializationProfile,
|
||||
segment: ThreadInitializationProfile,
|
||||
) {
|
||||
profile.core_duration_ms = profile
|
||||
.core_duration_ms
|
||||
.saturating_add(segment.core_duration_ms);
|
||||
profile.existing_thread_lookup_ms = profile
|
||||
.existing_thread_lookup_ms
|
||||
.saturating_add(segment.existing_thread_lookup_ms);
|
||||
profile.configuration_resolution_ms = profile
|
||||
.configuration_resolution_ms
|
||||
.saturating_add(segment.configuration_resolution_ms);
|
||||
profile.session_dependency_loading_ms = profile
|
||||
.session_dependency_loading_ms
|
||||
.saturating_add(segment.session_dependency_loading_ms);
|
||||
profile.session_construction_ms = profile
|
||||
.session_construction_ms
|
||||
.saturating_add(segment.session_construction_ms);
|
||||
profile.mcp_startup_ms = profile
|
||||
.mcp_startup_ms
|
||||
.saturating_add(segment.mcp_startup_ms);
|
||||
profile.session_activation_ms = profile
|
||||
.session_activation_ms
|
||||
.saturating_add(segment.session_activation_ms);
|
||||
profile.thread_registration_ms = profile
|
||||
.thread_registration_ms
|
||||
.saturating_add(segment.thread_registration_ms);
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) enum OutgoingEnvelope {
|
||||
ToConnection {
|
||||
@@ -276,6 +339,17 @@ impl OutgoingMessageSender {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn record_thread_initialization(
|
||||
&self,
|
||||
request_id: &ConnectionRequestId,
|
||||
initialization: CompletedCoreThreadInitialization,
|
||||
) {
|
||||
let mut request_contexts = self.request_contexts.lock().await;
|
||||
if let Some(request_context) = request_contexts.get_mut(request_id) {
|
||||
request_context.record_thread_initialization(initialization);
|
||||
}
|
||||
}
|
||||
|
||||
async fn take_request_context(
|
||||
&self,
|
||||
request_id: &ConnectionRequestId,
|
||||
@@ -730,6 +804,7 @@ fn now_unix_timestamp_ms() -> u64 {
|
||||
mod tests {
|
||||
use std::time::Duration;
|
||||
|
||||
use codex_analytics::ThreadInitializationMode;
|
||||
use codex_app_server_protocol::AccountLoginCompletedNotification;
|
||||
use codex_app_server_protocol::AccountRateLimitsUpdatedNotification;
|
||||
use codex_app_server_protocol::AccountUpdatedNotification;
|
||||
@@ -759,6 +834,62 @@ mod tests {
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn request_context_combines_core_initialization_segments() {
|
||||
let request_started_at = Instant::now();
|
||||
let mut request_context = RequestContext::new_at(
|
||||
ConnectionRequestId {
|
||||
connection_id: ConnectionId(42),
|
||||
request_id: RequestId::Integer(7),
|
||||
},
|
||||
tracing::info_span!("app_server.request", rpc.method = "thread/resume"),
|
||||
/*parent_trace*/ None,
|
||||
request_started_at,
|
||||
);
|
||||
request_context.record_thread_initialization(CompletedCoreThreadInitialization {
|
||||
initialization_mode: ThreadInitializationMode::Resumed,
|
||||
profile: ThreadInitializationProfile {
|
||||
core_duration_ms: 17,
|
||||
existing_thread_lookup_ms: 17,
|
||||
..Default::default()
|
||||
},
|
||||
});
|
||||
request_context.record_thread_initialization(CompletedCoreThreadInitialization {
|
||||
initialization_mode: ThreadInitializationMode::Resumed,
|
||||
profile: ThreadInitializationProfile {
|
||||
core_duration_ms: 213,
|
||||
configuration_resolution_ms: 13,
|
||||
session_dependency_loading_ms: 20,
|
||||
session_construction_ms: 30,
|
||||
mcp_startup_ms: 40,
|
||||
session_activation_ms: 50,
|
||||
thread_registration_ms: 60,
|
||||
..Default::default()
|
||||
},
|
||||
});
|
||||
|
||||
assert_eq!(
|
||||
request_context.complete_thread_initialization_at(
|
||||
request_started_at + Duration::from_millis(275),
|
||||
),
|
||||
Some(CompletedThreadInitialization {
|
||||
initialization_mode: ThreadInitializationMode::Resumed,
|
||||
profile: ThreadInitializationProfile {
|
||||
duration_ms: 275,
|
||||
app_server_duration_ms: 45,
|
||||
core_duration_ms: 230,
|
||||
existing_thread_lookup_ms: 17,
|
||||
configuration_resolution_ms: 13,
|
||||
session_dependency_loading_ms: 20,
|
||||
session_construction_ms: 30,
|
||||
mcp_startup_ms: 40,
|
||||
session_activation_ms: 50,
|
||||
thread_registration_ms: 60,
|
||||
},
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn verify_server_notification_serialization() {
|
||||
let notification =
|
||||
|
||||
@@ -1055,7 +1055,7 @@ impl ThreadRequestProcessor {
|
||||
thread_id,
|
||||
thread,
|
||||
session_configured,
|
||||
..
|
||||
thread_initialization,
|
||||
} = listener_task_context
|
||||
.thread_manager
|
||||
.start_thread_with_options(StartThreadOptions {
|
||||
@@ -1174,6 +1174,10 @@ impl ThreadRequestProcessor {
|
||||
reasoning_effort: config_snapshot.reasoning_effort,
|
||||
};
|
||||
let notif = thread_started_notification(thread);
|
||||
listener_task_context
|
||||
.outgoing
|
||||
.record_thread_initialization(&request_id, thread_initialization)
|
||||
.await;
|
||||
listener_task_context
|
||||
.outgoing
|
||||
.send_response(request_id, response)
|
||||
@@ -2526,7 +2530,7 @@ impl ThreadRequestProcessor {
|
||||
thread_id,
|
||||
thread: codex_thread,
|
||||
session_configured,
|
||||
..
|
||||
thread_initialization,
|
||||
}) => {
|
||||
if let Err(err) = Self::set_app_server_client_info(
|
||||
codex_thread.as_ref(),
|
||||
@@ -2648,6 +2652,9 @@ impl ThreadRequestProcessor {
|
||||
};
|
||||
|
||||
let connection_id = request_id.connection_id;
|
||||
self.outgoing
|
||||
.record_thread_initialization(&request_id, thread_initialization)
|
||||
.await;
|
||||
self.outgoing.send_response(request_id, response).await;
|
||||
// `excludeTurns` is explicitly the cheap resume path, so avoid
|
||||
// rebuilding history only to attribute a replayed usage update.
|
||||
@@ -2707,7 +2714,7 @@ impl ThreadRequestProcessor {
|
||||
app_server_client_name: Option<String>,
|
||||
app_server_client_version: Option<String>,
|
||||
) -> Result<bool, JSONRPCErrorError> {
|
||||
ThreadInitializationTiming::resume_lookup_started();
|
||||
let thread_initialization_timing = ThreadInitializationTiming::begin_resumed_lookup();
|
||||
let running_thread = if params.history.is_some() {
|
||||
if let Ok(existing_thread_id) = ThreadId::from_string(¶ms.thread_id)
|
||||
&& self
|
||||
@@ -2784,6 +2791,12 @@ impl ThreadRequestProcessor {
|
||||
ThreadShutdownResult::Complete => {
|
||||
self.thread_manager.remove_thread(&existing_thread_id).await;
|
||||
self.finalize_thread_teardown(existing_thread_id).await;
|
||||
self.outgoing
|
||||
.record_thread_initialization(
|
||||
request_id,
|
||||
thread_initialization_timing.complete(),
|
||||
)
|
||||
.await;
|
||||
return Ok(false);
|
||||
}
|
||||
ThreadShutdownResult::SubmitFailed => {
|
||||
@@ -2876,9 +2889,14 @@ impl ThreadRequestProcessor {
|
||||
"failed to enqueue running thread resume for thread {existing_thread_id}: thread listener command channel is closed"
|
||||
)));
|
||||
}
|
||||
ThreadInitializationTiming::core_completed();
|
||||
self.outgoing
|
||||
.record_thread_initialization(request_id, thread_initialization_timing.complete())
|
||||
.await;
|
||||
return Ok(true);
|
||||
}
|
||||
self.outgoing
|
||||
.record_thread_initialization(request_id, thread_initialization_timing.complete())
|
||||
.await;
|
||||
Ok(false)
|
||||
}
|
||||
|
||||
@@ -3224,7 +3242,7 @@ impl ThreadRequestProcessor {
|
||||
thread_id,
|
||||
thread: forked_thread,
|
||||
session_configured,
|
||||
..
|
||||
thread_initialization,
|
||||
} = self
|
||||
.thread_manager
|
||||
.fork_thread_from_history(
|
||||
@@ -3360,6 +3378,9 @@ impl ThreadRequestProcessor {
|
||||
let notif = thread_started_notification(thread);
|
||||
let connection_id = request_id.connection_id;
|
||||
let token_usage_thread = include_turns.then(|| response.thread.clone());
|
||||
self.outgoing
|
||||
.record_thread_initialization(&request_id, thread_initialization)
|
||||
.await;
|
||||
self.outgoing.send_response(request_id, response).await;
|
||||
// `excludeTurns` is the cheap fork path, so skip restored usage replay
|
||||
// instead of rebuilding history only to attribute a historical update.
|
||||
|
||||
@@ -50,6 +50,7 @@ use crate::session::SUBMISSION_CHANNEL_CAPACITY;
|
||||
use crate::session::emit_subagent_session_started;
|
||||
use crate::session::session::Session;
|
||||
use crate::session::turn_context::TurnContext;
|
||||
use crate::thread_initialization_timing::ThreadInitializationTiming;
|
||||
use codex_login::AuthManager;
|
||||
use codex_models_manager::manager::SharedModelsManager;
|
||||
use codex_protocol::error::CodexErr;
|
||||
@@ -79,6 +80,7 @@ pub(crate) async fn run_codex_thread_interactive(
|
||||
let (tx_ops, rx_ops) = async_channel::bounded(SUBMISSION_CHANNEL_CAPACITY);
|
||||
let conversation_history = initial_history.unwrap_or(InitialHistory::New);
|
||||
let forked_from_thread_id = conversation_history.forked_from_id();
|
||||
let thread_initialization_timing = ThreadInitializationTiming::begin(&conversation_history);
|
||||
let CodexSpawnOk { codex, .. } = Box::pin(Codex::spawn(CodexSpawnArgs {
|
||||
config,
|
||||
installation_id: parent_session.installation_id.clone(),
|
||||
@@ -107,6 +109,7 @@ pub(crate) async fn run_codex_thread_interactive(
|
||||
thread_store: Arc::clone(&parent_session.services.thread_store),
|
||||
attestation_provider: parent_session.services.attestation_provider.clone(),
|
||||
inherited_multi_agent_version: Some(MultiAgentVersion::Disabled),
|
||||
thread_initialization_timing,
|
||||
}))
|
||||
.or_cancel(&cancel_token)
|
||||
.await??;
|
||||
|
||||
@@ -303,6 +303,7 @@ use crate::stream_events_utils::HandleOutputCtx;
|
||||
#[cfg(test)]
|
||||
use crate::stream_events_utils::handle_output_item_done;
|
||||
use crate::tasks::ReviewTask;
|
||||
use crate::thread_initialization_timing::ThreadInitializationTiming;
|
||||
use crate::tools::network_approval::NetworkApprovalService;
|
||||
use crate::tools::network_approval::build_blocked_request_observer;
|
||||
use crate::tools::network_approval::build_network_policy_decider;
|
||||
@@ -387,6 +388,7 @@ pub(crate) type SessionLoopTermination = Shared<BoxFuture<'static, ()>>;
|
||||
pub struct CodexSpawnOk {
|
||||
pub codex: Codex,
|
||||
pub thread_id: ThreadId,
|
||||
pub(crate) thread_initialization_timing: ThreadInitializationTiming,
|
||||
}
|
||||
|
||||
pub(crate) struct CodexSpawnArgs {
|
||||
@@ -421,6 +423,7 @@ pub(crate) struct CodexSpawnArgs {
|
||||
pub(crate) thread_store: Arc<dyn ThreadStore>,
|
||||
pub(crate) attestation_provider: Option<Arc<dyn AttestationProvider>>,
|
||||
pub(crate) inherited_multi_agent_version: Option<MultiAgentVersion>,
|
||||
pub(crate) thread_initialization_timing: ThreadInitializationTiming,
|
||||
}
|
||||
|
||||
pub(crate) fn resolve_multi_agent_version(
|
||||
@@ -501,6 +504,7 @@ impl Codex {
|
||||
thread_store,
|
||||
attestation_provider,
|
||||
inherited_multi_agent_version,
|
||||
mut thread_initialization_timing,
|
||||
} = args;
|
||||
let (tx_sub, rx_sub) = async_channel::bounded(SUBMISSION_CHANNEL_CAPACITY);
|
||||
let (tx_event, rx_event) = async_channel::unbounded();
|
||||
@@ -646,6 +650,7 @@ impl Codex {
|
||||
parent_rollout_thread_trace,
|
||||
attestation_provider,
|
||||
multi_agent_version,
|
||||
&mut thread_initialization_timing,
|
||||
))
|
||||
.await
|
||||
.map_err(|e| {
|
||||
@@ -669,7 +674,11 @@ impl Codex {
|
||||
session_loop_termination: session_loop_termination_from_handle(session_loop_handle),
|
||||
};
|
||||
|
||||
Ok(CodexSpawnOk { codex, thread_id })
|
||||
Ok(CodexSpawnOk {
|
||||
codex,
|
||||
thread_id,
|
||||
thread_initialization_timing,
|
||||
})
|
||||
}
|
||||
|
||||
/// Submit the `op` wrapped in a `Submission` with a unique ID.
|
||||
|
||||
@@ -491,6 +491,7 @@ impl Session {
|
||||
parent_rollout_thread_trace: ThreadTraceContext,
|
||||
attestation_provider: Option<Arc<dyn AttestationProvider>>,
|
||||
multi_agent_version: Option<MultiAgentVersion>,
|
||||
thread_initialization_timing: &mut ThreadInitializationTiming,
|
||||
) -> anyhow::Result<Arc<Self>> {
|
||||
debug!(
|
||||
"Configuring session: model={}; provider={:?}",
|
||||
@@ -530,7 +531,7 @@ impl Session {
|
||||
// - initialize thread persistence with new or resumed session info
|
||||
// - perform default shell discovery
|
||||
// - load history metadata (skipped for subagents)
|
||||
ThreadInitializationTiming::session_dependency_loading_started();
|
||||
thread_initialization_timing.session_dependency_loading_started();
|
||||
let thread_persistence_fut = async {
|
||||
if config.ephemeral {
|
||||
Ok::<_, anyhow::Error>(None)
|
||||
@@ -655,7 +656,7 @@ impl Session {
|
||||
auth_and_mcp_fut,
|
||||
plugin_and_skill_warmup_fut
|
||||
);
|
||||
ThreadInitializationTiming::session_construction_started();
|
||||
thread_initialization_timing.session_construction_started();
|
||||
|
||||
for err in &plugin_skill_errors {
|
||||
error!(
|
||||
@@ -1110,7 +1111,7 @@ impl Session {
|
||||
sess.send_event_raw(event).await;
|
||||
}
|
||||
|
||||
ThreadInitializationTiming::mcp_startup_started();
|
||||
thread_initialization_timing.mcp_startup_started();
|
||||
let mut required_mcp_servers: Vec<String> = mcp_servers
|
||||
.iter()
|
||||
.filter(|(_, server)| server.enabled() && server.required())
|
||||
@@ -1217,7 +1218,7 @@ impl Session {
|
||||
anyhow::bail!("required MCP servers failed to initialize: {details}");
|
||||
}
|
||||
}
|
||||
ThreadInitializationTiming::session_activation_started();
|
||||
thread_initialization_timing.session_activation_started();
|
||||
sess.schedule_startup_prewarm(session_configuration.base_instructions.clone())
|
||||
.await;
|
||||
let session_start_source = match &initial_history {
|
||||
@@ -1241,7 +1242,7 @@ impl Session {
|
||||
match session_result {
|
||||
Ok(sess) => {
|
||||
live_thread_init.commit();
|
||||
ThreadInitializationTiming::thread_registration_started();
|
||||
thread_initialization_timing.thread_registration_started();
|
||||
Ok(sess)
|
||||
}
|
||||
Err(err) => {
|
||||
|
||||
@@ -4648,6 +4648,7 @@ async fn session_new_fails_when_zsh_fork_enabled_without_packaged_zsh() {
|
||||
config.codex_home.clone(),
|
||||
/*bundled_skills_enabled*/ true,
|
||||
));
|
||||
let mut thread_initialization_timing = ThreadInitializationTiming::begin(&InitialHistory::New);
|
||||
let result = Session::new(
|
||||
session_configuration,
|
||||
Arc::clone(&config),
|
||||
@@ -4673,6 +4674,7 @@ async fn session_new_fails_when_zsh_fork_enabled_without_packaged_zsh() {
|
||||
codex_rollout_trace::ThreadTraceContext::disabled(),
|
||||
/*attestation_provider*/ None,
|
||||
Some(config.multi_agent_version_from_features()),
|
||||
&mut thread_initialization_timing,
|
||||
)
|
||||
.await;
|
||||
|
||||
@@ -4995,6 +4997,7 @@ async fn make_session_with_config_and_rx(
|
||||
config.codex_home.clone(),
|
||||
/*bundled_skills_enabled*/ true,
|
||||
));
|
||||
let mut thread_initialization_timing = ThreadInitializationTiming::begin(&InitialHistory::New);
|
||||
|
||||
let session = Session::new(
|
||||
session_configuration,
|
||||
@@ -5021,6 +5024,7 @@ async fn make_session_with_config_and_rx(
|
||||
codex_rollout_trace::ThreadTraceContext::disabled(),
|
||||
/*attestation_provider*/ None,
|
||||
Some(config.multi_agent_version_from_features()),
|
||||
&mut thread_initialization_timing,
|
||||
)
|
||||
.await?;
|
||||
|
||||
@@ -5100,6 +5104,7 @@ async fn make_session_with_history_source_and_agent_control_and_rx(
|
||||
config.codex_home.clone(),
|
||||
/*bundled_skills_enabled*/ true,
|
||||
));
|
||||
let mut thread_initialization_timing = ThreadInitializationTiming::begin(&initial_history);
|
||||
|
||||
let session = Session::new(
|
||||
session_configuration,
|
||||
@@ -5133,6 +5138,7 @@ async fn make_session_with_history_source_and_agent_control_and_rx(
|
||||
codex_rollout_trace::ThreadTraceContext::disabled(),
|
||||
/*attestation_provider*/ None,
|
||||
Some(config.multi_agent_version_from_features()),
|
||||
&mut thread_initialization_timing,
|
||||
)
|
||||
.await?;
|
||||
|
||||
|
||||
@@ -702,6 +702,7 @@ async fn guardian_subagent_does_not_inherit_parent_exec_policy_rules() {
|
||||
codex_thread_store::LocalThreadStoreConfig::from_config(&config),
|
||||
/*state_db*/ None,
|
||||
));
|
||||
let thread_initialization_timing = ThreadInitializationTiming::begin(&InitialHistory::New);
|
||||
|
||||
let CodexSpawnOk { codex, .. } = Codex::spawn(CodexSpawnArgs {
|
||||
config,
|
||||
@@ -735,6 +736,7 @@ async fn guardian_subagent_does_not_inherit_parent_exec_policy_rules() {
|
||||
thread_store,
|
||||
attestation_provider: None,
|
||||
inherited_multi_agent_version: None,
|
||||
thread_initialization_timing,
|
||||
})
|
||||
.await
|
||||
.expect("spawn guardian subagent");
|
||||
|
||||
@@ -1,15 +1,12 @@
|
||||
use std::future::Future;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::MutexGuard;
|
||||
use std::sync::PoisonError;
|
||||
use std::time::Duration;
|
||||
use std::time::Instant;
|
||||
|
||||
use codex_analytics::CompletedThreadInitialization;
|
||||
use codex_analytics::CompletedCoreThreadInitialization;
|
||||
use codex_analytics::ThreadInitializationMode;
|
||||
use codex_analytics::ThreadInitializationProfile;
|
||||
|
||||
use codex_protocol::protocol::InitialHistory;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum ThreadInitializationPhase {
|
||||
ExistingThreadLookup,
|
||||
@@ -21,185 +18,122 @@ enum ThreadInitializationPhase {
|
||||
ThreadRegistration,
|
||||
}
|
||||
|
||||
tokio::task_local! {
|
||||
static ACTIVE_THREAD_INITIALIZATION_TIMING: ThreadInitializationTiming;
|
||||
}
|
||||
|
||||
/// Request-scoped monotonic timing for app-server thread initialization.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ThreadInitializationTiming(Arc<Mutex<ThreadInitializationTimingState>>);
|
||||
|
||||
/// Monotonic timing state owned by one thread initialization operation.
|
||||
#[derive(Debug)]
|
||||
struct ThreadInitializationTimingState {
|
||||
request_started_at: Instant,
|
||||
last_transition_at: Option<Instant>,
|
||||
active_phase: Option<ThreadInitializationPhase>,
|
||||
initialization_mode: Option<ThreadInitializationMode>,
|
||||
pub struct ThreadInitializationTiming {
|
||||
last_transition_at: Instant,
|
||||
active_phase: ThreadInitializationPhase,
|
||||
initialization_mode: ThreadInitializationMode,
|
||||
profile: ThreadInitializationProfile,
|
||||
core_complete: bool,
|
||||
}
|
||||
|
||||
impl ThreadInitializationTiming {
|
||||
pub fn begin_request() -> Self {
|
||||
Self::new_at(Instant::now())
|
||||
pub(crate) fn begin(initial_history: &InitialHistory) -> Self {
|
||||
let (initialization_mode, phase) = match initial_history {
|
||||
InitialHistory::New => (
|
||||
ThreadInitializationMode::New,
|
||||
ThreadInitializationPhase::ConfigurationResolution,
|
||||
),
|
||||
InitialHistory::Cleared => (
|
||||
ThreadInitializationMode::Cleared,
|
||||
ThreadInitializationPhase::ConfigurationResolution,
|
||||
),
|
||||
InitialHistory::Forked(_) => (
|
||||
ThreadInitializationMode::Forked,
|
||||
ThreadInitializationPhase::ConfigurationResolution,
|
||||
),
|
||||
InitialHistory::Resumed(_) => (
|
||||
ThreadInitializationMode::Resumed,
|
||||
ThreadInitializationPhase::ExistingThreadLookup,
|
||||
),
|
||||
};
|
||||
Self::new_at(Instant::now(), initialization_mode, phase)
|
||||
}
|
||||
|
||||
pub async fn scope<F>(&self, future: F) -> F::Output
|
||||
where
|
||||
F: Future,
|
||||
{
|
||||
ACTIVE_THREAD_INITIALIZATION_TIMING
|
||||
.scope(self.clone(), future)
|
||||
.await
|
||||
}
|
||||
|
||||
pub fn resume_lookup_started() {
|
||||
Self::start_current(
|
||||
pub fn begin_resumed_lookup() -> Self {
|
||||
Self::new_at(
|
||||
Instant::now(),
|
||||
ThreadInitializationMode::Resumed,
|
||||
ThreadInitializationPhase::ExistingThreadLookup,
|
||||
);
|
||||
)
|
||||
}
|
||||
|
||||
pub fn core_completed() {
|
||||
Self::with_current(|timing| timing.complete_core_at(Instant::now()));
|
||||
pub(crate) fn begin_forked() -> Self {
|
||||
Self::new_at(
|
||||
Instant::now(),
|
||||
ThreadInitializationMode::Forked,
|
||||
ThreadInitializationPhase::ConfigurationResolution,
|
||||
)
|
||||
}
|
||||
|
||||
pub fn complete_request(&self) -> Option<CompletedThreadInitialization> {
|
||||
self.complete_request_at(Instant::now())
|
||||
pub(crate) fn existing_thread_lookup_started(&mut self) {
|
||||
self.transition_to(ThreadInitializationPhase::ExistingThreadLookup);
|
||||
}
|
||||
|
||||
pub(crate) fn new_thread_started() {
|
||||
Self::start_configuration_resolution(ThreadInitializationMode::New);
|
||||
pub(crate) fn configuration_resolution_started(&mut self) {
|
||||
self.transition_to(ThreadInitializationPhase::ConfigurationResolution);
|
||||
}
|
||||
|
||||
pub(crate) fn cleared_thread_started() {
|
||||
Self::start_configuration_resolution(ThreadInitializationMode::Cleared);
|
||||
pub(crate) fn session_dependency_loading_started(&mut self) {
|
||||
self.transition_to(ThreadInitializationPhase::SessionDependencyLoading);
|
||||
}
|
||||
|
||||
pub(crate) fn forked_thread_started() {
|
||||
Self::start_configuration_resolution(ThreadInitializationMode::Forked);
|
||||
pub(crate) fn session_construction_started(&mut self) {
|
||||
self.transition_to(ThreadInitializationPhase::SessionConstruction);
|
||||
}
|
||||
|
||||
pub(crate) fn resumed_thread_started() {
|
||||
Self::start_configuration_resolution(ThreadInitializationMode::Resumed);
|
||||
pub(crate) fn mcp_startup_started(&mut self) {
|
||||
self.transition_to(ThreadInitializationPhase::McpStartup);
|
||||
}
|
||||
|
||||
pub(crate) fn configuration_resolution_started() {
|
||||
Self::transition_to(ThreadInitializationPhase::ConfigurationResolution);
|
||||
pub(crate) fn session_activation_started(&mut self) {
|
||||
self.transition_to(ThreadInitializationPhase::SessionActivation);
|
||||
}
|
||||
|
||||
pub(crate) fn session_dependency_loading_started() {
|
||||
Self::transition_to(ThreadInitializationPhase::SessionDependencyLoading);
|
||||
pub(crate) fn thread_registration_started(&mut self) {
|
||||
self.transition_to(ThreadInitializationPhase::ThreadRegistration);
|
||||
}
|
||||
|
||||
pub(crate) fn session_construction_started() {
|
||||
Self::transition_to(ThreadInitializationPhase::SessionConstruction);
|
||||
pub fn complete(self) -> CompletedCoreThreadInitialization {
|
||||
self.complete_at(Instant::now())
|
||||
}
|
||||
|
||||
pub(crate) fn mcp_startup_started() {
|
||||
Self::transition_to(ThreadInitializationPhase::McpStartup);
|
||||
fn transition_to(&mut self, phase: ThreadInitializationPhase) {
|
||||
self.transition_at(Instant::now(), phase);
|
||||
}
|
||||
|
||||
pub(crate) fn session_activation_started() {
|
||||
Self::transition_to(ThreadInitializationPhase::SessionActivation);
|
||||
}
|
||||
|
||||
pub(crate) fn thread_registration_started() {
|
||||
Self::transition_to(ThreadInitializationPhase::ThreadRegistration);
|
||||
}
|
||||
|
||||
fn transition_to(phase: ThreadInitializationPhase) {
|
||||
Self::with_current(|timing| timing.transition_at(Instant::now(), phase));
|
||||
}
|
||||
|
||||
fn start_configuration_resolution(mode: ThreadInitializationMode) {
|
||||
Self::start_current(mode, ThreadInitializationPhase::ConfigurationResolution);
|
||||
}
|
||||
|
||||
fn start_current(mode: ThreadInitializationMode, phase: ThreadInitializationPhase) {
|
||||
Self::with_current(|timing| timing.start_core_at(Instant::now(), mode, phase));
|
||||
}
|
||||
|
||||
fn with_current(f: impl FnOnce(&Self)) {
|
||||
let _ = ACTIVE_THREAD_INITIALIZATION_TIMING.try_with(f);
|
||||
}
|
||||
|
||||
fn new_at(request_started_at: Instant) -> Self {
|
||||
Self(Arc::new(Mutex::new(ThreadInitializationTimingState {
|
||||
request_started_at,
|
||||
last_transition_at: None,
|
||||
active_phase: None,
|
||||
initialization_mode: None,
|
||||
fn new_at(
|
||||
started_at: Instant,
|
||||
initialization_mode: ThreadInitializationMode,
|
||||
active_phase: ThreadInitializationPhase,
|
||||
) -> Self {
|
||||
Self {
|
||||
last_transition_at: started_at,
|
||||
active_phase,
|
||||
initialization_mode,
|
||||
profile: ThreadInitializationProfile::default(),
|
||||
core_complete: false,
|
||||
})))
|
||||
}
|
||||
|
||||
fn start_core_at(
|
||||
&self,
|
||||
now: Instant,
|
||||
mode: ThreadInitializationMode,
|
||||
phase: ThreadInitializationPhase,
|
||||
) {
|
||||
let mut state = self.state();
|
||||
if state.last_transition_at.is_some() || state.core_complete {
|
||||
return;
|
||||
}
|
||||
state.last_transition_at = Some(now);
|
||||
state.active_phase = Some(phase);
|
||||
state.initialization_mode = Some(mode);
|
||||
}
|
||||
|
||||
fn transition_at(&self, now: Instant, phase: ThreadInitializationPhase) {
|
||||
let mut state = self.state();
|
||||
if state.core_complete || state.last_transition_at.is_none() {
|
||||
return;
|
||||
fn transition_at(&mut self, now: Instant, phase: ThreadInitializationPhase) {
|
||||
self.advance(now);
|
||||
self.active_phase = phase;
|
||||
}
|
||||
|
||||
fn complete_at(mut self, now: Instant) -> CompletedCoreThreadInitialization {
|
||||
self.advance(now);
|
||||
self.profile.core_duration_ms = core_duration_ms(&self.profile);
|
||||
CompletedCoreThreadInitialization {
|
||||
initialization_mode: self.initialization_mode,
|
||||
profile: self.profile,
|
||||
}
|
||||
state.advance(now);
|
||||
state.active_phase = Some(phase);
|
||||
}
|
||||
|
||||
fn complete_core_at(&self, now: Instant) {
|
||||
let mut state = self.state();
|
||||
if state.core_complete || state.last_transition_at.is_none() {
|
||||
return;
|
||||
}
|
||||
state.advance(now);
|
||||
state.profile.core_duration_ms = core_duration_ms(&state.profile);
|
||||
state.active_phase = None;
|
||||
state.core_complete = true;
|
||||
}
|
||||
|
||||
fn complete_request_at(&self, now: Instant) -> Option<CompletedThreadInitialization> {
|
||||
let state = self.state();
|
||||
if !state.core_complete {
|
||||
return None;
|
||||
}
|
||||
let mut profile = state.profile;
|
||||
profile.duration_ms =
|
||||
duration_to_u64_ms(now.saturating_duration_since(state.request_started_at));
|
||||
profile.app_server_duration_ms =
|
||||
profile.duration_ms.saturating_sub(profile.core_duration_ms);
|
||||
Some(CompletedThreadInitialization {
|
||||
initialization_mode: state.initialization_mode?,
|
||||
profile,
|
||||
})
|
||||
}
|
||||
|
||||
fn state(&self) -> MutexGuard<'_, ThreadInitializationTimingState> {
|
||||
self.0.lock().unwrap_or_else(PoisonError::into_inner)
|
||||
}
|
||||
}
|
||||
|
||||
impl ThreadInitializationTimingState {
|
||||
fn advance(&mut self, now: Instant) {
|
||||
let (Some(previous), Some(phase)) =
|
||||
(self.last_transition_at.replace(now), self.active_phase)
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let duration_ms = duration_to_u64_ms(now.saturating_duration_since(previous));
|
||||
let phase_duration = phase_duration_mut(&mut self.profile, phase);
|
||||
let duration_ms =
|
||||
duration_to_u64_ms(now.saturating_duration_since(self.last_transition_at));
|
||||
self.last_transition_at = now;
|
||||
let phase_duration = phase_duration_mut(&mut self.profile, self.active_phase);
|
||||
*phase_duration = phase_duration.saturating_add(duration_ms);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use std::time::Duration;
|
||||
use std::time::Instant;
|
||||
|
||||
use codex_analytics::CompletedThreadInitialization;
|
||||
use codex_analytics::CompletedCoreThreadInitialization;
|
||||
use codex_analytics::ThreadInitializationMode;
|
||||
use codex_analytics::ThreadInitializationProfile;
|
||||
use pretty_assertions::assert_eq;
|
||||
@@ -10,12 +10,9 @@ use super::ThreadInitializationPhase;
|
||||
use super::ThreadInitializationTiming;
|
||||
|
||||
#[test]
|
||||
fn thread_initialization_profile_breaks_down_request_and_core_time() {
|
||||
let request_started_at = Instant::now();
|
||||
let core_started_at = request_started_at + Duration::from_millis(20);
|
||||
let timing = ThreadInitializationTiming::new_at(request_started_at);
|
||||
|
||||
timing.start_core_at(
|
||||
fn thread_initialization_profile_breaks_down_core_time() {
|
||||
let core_started_at = Instant::now();
|
||||
let mut timing = ThreadInitializationTiming::new_at(
|
||||
core_started_at,
|
||||
ThreadInitializationMode::Cleared,
|
||||
ThreadInitializationPhase::ConfigurationResolution,
|
||||
@@ -31,14 +28,11 @@ fn thread_initialization_profile_breaks_down_request_and_core_time() {
|
||||
] {
|
||||
timing.transition_at(core_started_at + Duration::from_millis(elapsed_ms), phase);
|
||||
}
|
||||
timing.complete_core_at(core_started_at + Duration::from_millis(230));
|
||||
assert_eq!(
|
||||
timing.complete_request_at(request_started_at + Duration::from_millis(275)),
|
||||
Some(CompletedThreadInitialization {
|
||||
timing.complete_at(core_started_at + Duration::from_millis(230)),
|
||||
CompletedCoreThreadInitialization {
|
||||
initialization_mode: ThreadInitializationMode::Cleared,
|
||||
profile: ThreadInitializationProfile {
|
||||
duration_ms: 275,
|
||||
app_server_duration_ms: 45,
|
||||
core_duration_ms: 230,
|
||||
existing_thread_lookup_ms: 5,
|
||||
configuration_resolution_ms: 25,
|
||||
@@ -47,34 +41,30 @@ fn thread_initialization_profile_breaks_down_request_and_core_time() {
|
||||
mcp_startup_ms: 40,
|
||||
session_activation_ms: 50,
|
||||
thread_registration_ms: 60,
|
||||
..Default::default()
|
||||
},
|
||||
})
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn loaded_resume_records_only_existing_thread_lookup() {
|
||||
let request_started_at = Instant::now();
|
||||
let core_started_at = request_started_at + Duration::from_millis(3);
|
||||
let timing = ThreadInitializationTiming::new_at(request_started_at);
|
||||
timing.start_core_at(
|
||||
let core_started_at = Instant::now();
|
||||
let timing = ThreadInitializationTiming::new_at(
|
||||
core_started_at,
|
||||
ThreadInitializationMode::Resumed,
|
||||
ThreadInitializationPhase::ExistingThreadLookup,
|
||||
);
|
||||
timing.complete_core_at(core_started_at + Duration::from_millis(17));
|
||||
|
||||
assert_eq!(
|
||||
timing.complete_request_at(request_started_at + Duration::from_millis(25)),
|
||||
Some(CompletedThreadInitialization {
|
||||
timing.complete_at(core_started_at + Duration::from_millis(17)),
|
||||
CompletedCoreThreadInitialization {
|
||||
initialization_mode: ThreadInitializationMode::Resumed,
|
||||
profile: ThreadInitializationProfile {
|
||||
duration_ms: 25,
|
||||
app_server_duration_ms: 8,
|
||||
core_duration_ms: 17,
|
||||
existing_thread_lookup_ms: 17,
|
||||
..Default::default()
|
||||
},
|
||||
})
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
@@ -18,6 +18,7 @@ use crate::tasks::InterruptedTurnHistoryMarker;
|
||||
use crate::tasks::interrupted_turn_history_marker;
|
||||
use crate::thread_initialization_timing::ThreadInitializationTiming;
|
||||
use codex_analytics::AnalyticsEventsClient;
|
||||
use codex_analytics::CompletedCoreThreadInitialization;
|
||||
use codex_app_server_protocol::ThreadHistoryBuilder;
|
||||
use codex_app_server_protocol::TurnStatus;
|
||||
use codex_core_plugins::PluginsManager;
|
||||
@@ -113,6 +114,13 @@ pub struct NewThread {
|
||||
pub thread_id: ThreadId,
|
||||
pub thread: Arc<CodexThread>,
|
||||
pub session_configured: SessionConfiguredEvent,
|
||||
pub thread_initialization: CompletedCoreThreadInitialization,
|
||||
}
|
||||
|
||||
struct RegisteredThread {
|
||||
thread_id: ThreadId,
|
||||
thread: Arc<CodexThread>,
|
||||
session_configured: SessionConfiguredEvent,
|
||||
}
|
||||
|
||||
// TODO(ccunningham): Add an explicit non-interrupting live-turn snapshot once
|
||||
@@ -585,20 +593,21 @@ impl ThreadManager {
|
||||
&self,
|
||||
options: StartThreadOptions,
|
||||
) -> CodexResult<NewThread> {
|
||||
match &options.initial_history {
|
||||
InitialHistory::Cleared => ThreadInitializationTiming::cleared_thread_started(),
|
||||
InitialHistory::Forked(_) => ThreadInitializationTiming::forked_thread_started(),
|
||||
InitialHistory::New => ThreadInitializationTiming::new_thread_started(),
|
||||
InitialHistory::Resumed(_) => ThreadInitializationTiming::resumed_thread_started(),
|
||||
}
|
||||
self.start_thread_with_options_and_fork_source(options, /*forked_from_thread_id*/ None)
|
||||
.await
|
||||
let thread_initialization_timing =
|
||||
ThreadInitializationTiming::begin(&options.initial_history);
|
||||
self.start_thread_with_options_and_fork_source(
|
||||
options,
|
||||
/*forked_from_thread_id*/ None,
|
||||
thread_initialization_timing,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn start_thread_with_options_and_fork_source(
|
||||
&self,
|
||||
options: StartThreadOptions,
|
||||
forked_from_thread_id: Option<ThreadId>,
|
||||
thread_initialization_timing: ThreadInitializationTiming,
|
||||
) -> CodexResult<NewThread> {
|
||||
let (resumed_session_source, resumed_thread_source) = options
|
||||
.initial_history
|
||||
@@ -622,6 +631,7 @@ impl ThreadManager {
|
||||
options.parent_trace,
|
||||
options.environments,
|
||||
/*user_shell_override*/ None,
|
||||
thread_initialization_timing,
|
||||
))
|
||||
.await
|
||||
}
|
||||
@@ -633,6 +643,7 @@ impl ThreadManager {
|
||||
forked_from_thread_id: ThreadId,
|
||||
mut options: StartThreadOptions,
|
||||
) -> CodexResult<NewThread> {
|
||||
let thread_initialization_timing = ThreadInitializationTiming::begin_forked();
|
||||
let fork_source = self.get_thread(forked_from_thread_id).await?;
|
||||
// Persist queued rollout updates before reading the fork snapshot.
|
||||
fork_source.ensure_rollout_materialized().await;
|
||||
@@ -659,8 +670,12 @@ impl ThreadManager {
|
||||
inherited_multi_agent_version,
|
||||
),
|
||||
);
|
||||
self.start_thread_with_options_and_fork_source(options, Some(forked_from_thread_id))
|
||||
.await
|
||||
self.start_thread_with_options_and_fork_source(
|
||||
options,
|
||||
Some(forked_from_thread_id),
|
||||
thread_initialization_timing,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn resume_thread_from_rollout(
|
||||
@@ -670,13 +685,14 @@ impl ThreadManager {
|
||||
auth_manager: Arc<AuthManager>,
|
||||
parent_trace: Option<W3cTraceContext>,
|
||||
) -> CodexResult<NewThread> {
|
||||
ThreadInitializationTiming::resume_lookup_started();
|
||||
let thread_initialization_timing = ThreadInitializationTiming::begin_resumed_lookup();
|
||||
let initial_history = self.initial_history_from_rollout_path(rollout_path).await?;
|
||||
Box::pin(self.resume_thread_with_history(
|
||||
Box::pin(self.resume_thread_with_history_and_timing(
|
||||
config,
|
||||
initial_history,
|
||||
auth_manager,
|
||||
parent_trace,
|
||||
thread_initialization_timing,
|
||||
))
|
||||
.await
|
||||
}
|
||||
@@ -688,7 +704,25 @@ impl ThreadManager {
|
||||
auth_manager: Arc<AuthManager>,
|
||||
parent_trace: Option<W3cTraceContext>,
|
||||
) -> CodexResult<NewThread> {
|
||||
ThreadInitializationTiming::resume_lookup_started();
|
||||
let thread_initialization_timing = ThreadInitializationTiming::begin(&initial_history);
|
||||
self.resume_thread_with_history_and_timing(
|
||||
config,
|
||||
initial_history,
|
||||
auth_manager,
|
||||
parent_trace,
|
||||
thread_initialization_timing,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn resume_thread_with_history_and_timing(
|
||||
&self,
|
||||
config: Config,
|
||||
initial_history: InitialHistory,
|
||||
auth_manager: Arc<AuthManager>,
|
||||
parent_trace: Option<W3cTraceContext>,
|
||||
thread_initialization_timing: ThreadInitializationTiming,
|
||||
) -> CodexResult<NewThread> {
|
||||
let environments = default_thread_environment_selections(
|
||||
self.state.environment_manager.as_ref(),
|
||||
&config.cwd,
|
||||
@@ -712,6 +746,7 @@ impl ThreadManager {
|
||||
parent_trace,
|
||||
environments,
|
||||
/*user_shell_override*/ None,
|
||||
thread_initialization_timing,
|
||||
))
|
||||
.await
|
||||
}
|
||||
@@ -738,6 +773,7 @@ impl ThreadManager {
|
||||
/*parent_trace*/ None,
|
||||
environments,
|
||||
/*user_shell_override*/ Some(user_shell_override),
|
||||
ThreadInitializationTiming::begin(&InitialHistory::New),
|
||||
))
|
||||
.await
|
||||
}
|
||||
@@ -749,6 +785,7 @@ impl ThreadManager {
|
||||
auth_manager: Arc<AuthManager>,
|
||||
user_shell_override: crate::shell::Shell,
|
||||
) -> CodexResult<NewThread> {
|
||||
let thread_initialization_timing = ThreadInitializationTiming::begin_resumed_lookup();
|
||||
let initial_history = self.initial_history_from_rollout_path(rollout_path).await?;
|
||||
let environments = default_thread_environment_selections(
|
||||
self.state.environment_manager.as_ref(),
|
||||
@@ -773,6 +810,7 @@ impl ThreadManager {
|
||||
/*parent_trace*/ None,
|
||||
environments,
|
||||
/*user_shell_override*/ Some(user_shell_override),
|
||||
thread_initialization_timing,
|
||||
))
|
||||
.await
|
||||
}
|
||||
@@ -850,11 +888,18 @@ impl ThreadManager {
|
||||
where
|
||||
S: Into<ForkSnapshot>,
|
||||
{
|
||||
ThreadInitializationTiming::forked_thread_started();
|
||||
let thread_initialization_timing = ThreadInitializationTiming::begin_forked();
|
||||
let snapshot = snapshot.into();
|
||||
let history = self.initial_history_from_rollout_path(path).await?;
|
||||
self.fork_thread_from_history(snapshot, config, history, thread_source, parent_trace)
|
||||
.await
|
||||
self.fork_thread_with_initial_history(
|
||||
snapshot,
|
||||
config,
|
||||
history,
|
||||
thread_source,
|
||||
parent_trace,
|
||||
thread_initialization_timing,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn initial_history_from_rollout_path(
|
||||
@@ -887,13 +932,14 @@ impl ThreadManager {
|
||||
where
|
||||
S: Into<ForkSnapshot>,
|
||||
{
|
||||
ThreadInitializationTiming::forked_thread_started();
|
||||
let thread_initialization_timing = ThreadInitializationTiming::begin_forked();
|
||||
self.fork_thread_with_initial_history(
|
||||
snapshot.into(),
|
||||
config,
|
||||
history,
|
||||
thread_source,
|
||||
parent_trace,
|
||||
thread_initialization_timing,
|
||||
)
|
||||
.await
|
||||
}
|
||||
@@ -905,6 +951,7 @@ impl ThreadManager {
|
||||
history: InitialHistory,
|
||||
thread_source: Option<ThreadSource>,
|
||||
parent_trace: Option<W3cTraceContext>,
|
||||
thread_initialization_timing: ThreadInitializationTiming,
|
||||
) -> CodexResult<NewThread> {
|
||||
// `forked_from_id()` describes this history's existing lineage. When
|
||||
// forking a resumed thread, the child copies the resumed thread itself.
|
||||
@@ -943,6 +990,7 @@ impl ThreadManager {
|
||||
parent_trace,
|
||||
environments,
|
||||
/*user_shell_override*/ None,
|
||||
thread_initialization_timing,
|
||||
))
|
||||
.await
|
||||
}
|
||||
@@ -1129,12 +1177,14 @@ impl ThreadManagerState {
|
||||
inherited_exec_policy: Option<Arc<crate::exec_policy::ExecPolicyManager>>,
|
||||
environments: Option<Vec<TurnEnvironmentSelection>>,
|
||||
) -> CodexResult<NewThread> {
|
||||
let initial_history = InitialHistory::New;
|
||||
let thread_initialization_timing = ThreadInitializationTiming::begin(&initial_history);
|
||||
let environments = environments.unwrap_or_else(|| {
|
||||
default_thread_environment_selections(self.environment_manager.as_ref(), &config.cwd)
|
||||
});
|
||||
Box::pin(self.spawn_thread_with_source(
|
||||
config,
|
||||
InitialHistory::New,
|
||||
initial_history,
|
||||
Arc::clone(&self.auth_manager),
|
||||
agent_control,
|
||||
session_source,
|
||||
@@ -1148,6 +1198,7 @@ impl ThreadManagerState {
|
||||
/*parent_trace*/ None,
|
||||
environments,
|
||||
/*user_shell_override*/ None,
|
||||
thread_initialization_timing,
|
||||
))
|
||||
.await
|
||||
}
|
||||
@@ -1165,6 +1216,7 @@ impl ThreadManagerState {
|
||||
inherited_shell_snapshot,
|
||||
inherited_exec_policy,
|
||||
} = options;
|
||||
let thread_initialization_timing = ThreadInitializationTiming::begin(&initial_history);
|
||||
let environments =
|
||||
default_thread_environment_selections(self.environment_manager.as_ref(), &config.cwd);
|
||||
let thread_source = initial_history.get_resumed_thread_source();
|
||||
@@ -1184,6 +1236,7 @@ impl ThreadManagerState {
|
||||
/*parent_trace*/ None,
|
||||
environments,
|
||||
/*user_shell_override*/ None,
|
||||
thread_initialization_timing,
|
||||
))
|
||||
.await
|
||||
}
|
||||
@@ -1202,6 +1255,7 @@ impl ThreadManagerState {
|
||||
inherited_exec_policy: Option<Arc<crate::exec_policy::ExecPolicyManager>>,
|
||||
environments: Option<Vec<TurnEnvironmentSelection>>,
|
||||
) -> CodexResult<NewThread> {
|
||||
let thread_initialization_timing = ThreadInitializationTiming::begin(&initial_history);
|
||||
let environments = environments.unwrap_or_else(|| {
|
||||
default_thread_environment_selections(self.environment_manager.as_ref(), &config.cwd)
|
||||
});
|
||||
@@ -1221,6 +1275,7 @@ impl ThreadManagerState {
|
||||
/*parent_trace*/ None,
|
||||
environments,
|
||||
/*user_shell_override*/ None,
|
||||
thread_initialization_timing,
|
||||
))
|
||||
.await
|
||||
}
|
||||
@@ -1241,6 +1296,7 @@ impl ThreadManagerState {
|
||||
parent_trace: Option<W3cTraceContext>,
|
||||
environments: Vec<TurnEnvironmentSelection>,
|
||||
user_shell_override: Option<crate::shell::Shell>,
|
||||
thread_initialization_timing: ThreadInitializationTiming,
|
||||
) -> CodexResult<NewThread> {
|
||||
Box::pin(self.spawn_thread_with_source(
|
||||
config,
|
||||
@@ -1258,6 +1314,7 @@ impl ThreadManagerState {
|
||||
parent_trace,
|
||||
environments,
|
||||
user_shell_override,
|
||||
thread_initialization_timing,
|
||||
))
|
||||
.await
|
||||
}
|
||||
@@ -1280,9 +1337,11 @@ impl ThreadManagerState {
|
||||
parent_trace: Option<W3cTraceContext>,
|
||||
environments: Vec<TurnEnvironmentSelection>,
|
||||
user_shell_override: Option<crate::shell::Shell>,
|
||||
mut thread_initialization_timing: ThreadInitializationTiming,
|
||||
) -> CodexResult<NewThread> {
|
||||
let is_resumed_thread = matches!(&initial_history, InitialHistory::Resumed(_));
|
||||
if let InitialHistory::Resumed(resumed) = &initial_history {
|
||||
thread_initialization_timing.existing_thread_lookup_started();
|
||||
let mut threads = self.threads.write().await;
|
||||
if let Some(thread) = threads.get(&resumed.conversation_id).cloned() {
|
||||
if thread.is_running() {
|
||||
@@ -1298,14 +1357,14 @@ impl ThreadManagerState {
|
||||
thread_id: resumed.conversation_id,
|
||||
session_configured: thread.session_configured(),
|
||||
thread,
|
||||
thread_initialization: thread_initialization_timing.complete(),
|
||||
};
|
||||
ThreadInitializationTiming::core_completed();
|
||||
return Ok(new_thread);
|
||||
}
|
||||
threads.remove(&resumed.conversation_id);
|
||||
}
|
||||
}
|
||||
ThreadInitializationTiming::configuration_resolution_started();
|
||||
thread_initialization_timing.configuration_resolution_started();
|
||||
let environment_selections =
|
||||
resolve_environment_selections(self.environment_manager.as_ref(), &environments)?;
|
||||
let parent_rollout_thread_trace = self
|
||||
@@ -1321,7 +1380,9 @@ impl ThreadManagerState {
|
||||
)
|
||||
.await;
|
||||
let CodexSpawnOk {
|
||||
codex, thread_id, ..
|
||||
codex,
|
||||
thread_id,
|
||||
thread_initialization_timing,
|
||||
} = Box::pin(Codex::spawn(CodexSpawnArgs {
|
||||
config,
|
||||
installation_id: self.installation_id.clone(),
|
||||
@@ -1350,16 +1411,24 @@ impl ThreadManagerState {
|
||||
thread_store: Arc::clone(&self.thread_store),
|
||||
attestation_provider: self.attestation_provider.clone(),
|
||||
inherited_multi_agent_version: multi_agent_version,
|
||||
thread_initialization_timing,
|
||||
}))
|
||||
.await?;
|
||||
let new_thread = self
|
||||
let registered_thread = self
|
||||
.finalize_thread_spawn(codex, thread_id, tracked_session_source)
|
||||
.await?;
|
||||
if is_resumed_thread {
|
||||
new_thread.thread.emit_thread_resume_lifecycle().await;
|
||||
registered_thread
|
||||
.thread
|
||||
.emit_thread_resume_lifecycle()
|
||||
.await;
|
||||
}
|
||||
ThreadInitializationTiming::core_completed();
|
||||
Ok(new_thread)
|
||||
Ok(NewThread {
|
||||
thread_id: registered_thread.thread_id,
|
||||
thread: registered_thread.thread,
|
||||
session_configured: registered_thread.session_configured,
|
||||
thread_initialization: thread_initialization_timing.complete(),
|
||||
})
|
||||
}
|
||||
|
||||
async fn finalize_thread_spawn(
|
||||
@@ -1367,7 +1436,7 @@ impl ThreadManagerState {
|
||||
codex: Codex,
|
||||
thread_id: ThreadId,
|
||||
session_source: SessionSource,
|
||||
) -> CodexResult<NewThread> {
|
||||
) -> CodexResult<RegisteredThread> {
|
||||
let event = codex.next_event().await?;
|
||||
let session_configured = match event {
|
||||
Event {
|
||||
@@ -1389,7 +1458,7 @@ impl ThreadManagerState {
|
||||
session_source,
|
||||
));
|
||||
e.insert(thread.clone());
|
||||
return Ok(NewThread {
|
||||
return Ok(RegisteredThread {
|
||||
thread_id,
|
||||
thread,
|
||||
session_configured,
|
||||
|
||||
Reference in New Issue
Block a user