mirror of
https://github.com/openai/codex.git
synced 2026-11-27 23:50:52 +00:00
Simplify thread initialization profiling
This commit is contained in:
@@ -61,7 +61,6 @@ use crate::facts::SkillInvocation;
|
||||
use crate::facts::SkillInvokedInput;
|
||||
use crate::facts::SubAgentThreadStartedInput;
|
||||
use crate::facts::ThreadInitializationMode;
|
||||
use crate::facts::ThreadInitializationProfile;
|
||||
use crate::facts::TrackEventsContext;
|
||||
use crate::facts::TurnCodexErrorFact;
|
||||
use crate::facts::TurnProfile;
|
||||
@@ -115,9 +114,7 @@ use codex_app_server_protocol::ThreadArchiveResponse;
|
||||
use codex_app_server_protocol::ThreadItem;
|
||||
use codex_app_server_protocol::ThreadResumeResponse;
|
||||
use codex_app_server_protocol::ThreadSource as AppServerThreadSource;
|
||||
use codex_app_server_protocol::ThreadStartParams;
|
||||
use codex_app_server_protocol::ThreadStartResponse;
|
||||
use codex_app_server_protocol::ThreadStartSource;
|
||||
use codex_app_server_protocol::ThreadStatus as AppServerThreadStatus;
|
||||
use codex_app_server_protocol::Turn;
|
||||
use codex_app_server_protocol::TurnCompletedNotification;
|
||||
@@ -413,64 +410,6 @@ fn sample_turn_profile() -> TurnProfile {
|
||||
}
|
||||
}
|
||||
|
||||
fn sample_thread_initialization_profile() -> ThreadInitializationProfile {
|
||||
ThreadInitializationProfile {
|
||||
duration_ms: 110,
|
||||
app_server_duration_ms: 10,
|
||||
core_duration_ms: 100,
|
||||
existing_thread_lookup_ms: 5,
|
||||
configuration_resolution_ms: 10,
|
||||
session_dependency_loading_ms: 20,
|
||||
session_construction_ms: 25,
|
||||
mcp_startup_ms: 15,
|
||||
session_activation_ms: 15,
|
||||
thread_registration_ms: 10,
|
||||
thread_persistence_ms: 12,
|
||||
state_db_loading_ms: 8,
|
||||
auth_and_mcp_discovery_ms: 17,
|
||||
plugin_and_skill_warmup_ms: 19,
|
||||
}
|
||||
}
|
||||
|
||||
fn expected_thread_initialized_event(
|
||||
app_server_client: serde_json::Value,
|
||||
runtime: serde_json::Value,
|
||||
ephemeral: bool,
|
||||
initialization_mode: &str,
|
||||
profile: Option<ThreadInitializationProfile>,
|
||||
) -> serde_json::Value {
|
||||
let mut event_params = json!({
|
||||
"thread_id": "thread-1",
|
||||
"session_id": "session-thread-1",
|
||||
"app_server_client": app_server_client,
|
||||
"runtime": runtime,
|
||||
"model": "gpt-5",
|
||||
"ephemeral": ephemeral,
|
||||
"thread_source": "user",
|
||||
"initialization_mode": initialization_mode,
|
||||
"subagent_source": null,
|
||||
"parent_thread_id": null,
|
||||
"forked_from_thread_id": null,
|
||||
"created_at": 1,
|
||||
});
|
||||
if let Some(profile) = profile {
|
||||
event_params
|
||||
.as_object_mut()
|
||||
.expect("event params object")
|
||||
.extend(
|
||||
serde_json::to_value(profile)
|
||||
.expect("serialize thread initialization profile")
|
||||
.as_object()
|
||||
.expect("thread initialization profile object")
|
||||
.clone(),
|
||||
);
|
||||
}
|
||||
json!({
|
||||
"event_type": "codex_thread_initialized",
|
||||
"event_params": event_params,
|
||||
})
|
||||
}
|
||||
|
||||
fn sample_turn_steer_request(
|
||||
thread_id: &str,
|
||||
expected_turn_id: &str,
|
||||
@@ -588,7 +527,6 @@ async fn ingest_rejected_turn_steer(
|
||||
AnalyticsFact::ClientResponse {
|
||||
connection_id: 8,
|
||||
request_id: RequestId::Integer(6),
|
||||
thread_initialization_profile: None,
|
||||
response: Box::new(sample_thread_resume_response(
|
||||
"thread-2", /*ephemeral*/ false, "gpt-5",
|
||||
)),
|
||||
@@ -662,7 +600,6 @@ async fn ingest_turn_prerequisites(
|
||||
AnalyticsFact::ClientResponse {
|
||||
connection_id: 7,
|
||||
request_id: RequestId::Integer(1),
|
||||
thread_initialization_profile: None,
|
||||
response: Box::new(sample_thread_start_response(
|
||||
"thread-2", /*ephemeral*/ false, "gpt-5",
|
||||
)),
|
||||
@@ -688,7 +625,6 @@ async fn ingest_turn_prerequisites(
|
||||
AnalyticsFact::ClientResponse {
|
||||
connection_id: 7,
|
||||
request_id: RequestId::Integer(3),
|
||||
thread_initialization_profile: None,
|
||||
response: Box::new(sample_turn_start_response("turn-2")),
|
||||
},
|
||||
out,
|
||||
@@ -753,7 +689,6 @@ async fn ingest_review_prerequisites(
|
||||
AnalyticsFact::ClientResponse {
|
||||
connection_id: 7,
|
||||
request_id: RequestId::Integer(1),
|
||||
thread_initialization_profile: None,
|
||||
response: Box::new(sample_thread_start_response(
|
||||
"thread-1", /*ephemeral*/ false, "gpt-5",
|
||||
)),
|
||||
@@ -1417,8 +1352,8 @@ fn thread_initialized_event_serializes_expected_shape() {
|
||||
let event = TrackEventRequest::ThreadInitialized(ThreadInitializedEvent {
|
||||
event_type: "codex_thread_initialized",
|
||||
event_params: ThreadInitializedEventParams {
|
||||
thread_id: "thread-1".to_string(),
|
||||
session_id: "session-thread-1".to_string(),
|
||||
thread_id: "thread-0".to_string(),
|
||||
session_id: "session-thread-0".to_string(),
|
||||
app_server_client: CodexAppServerClientMetadata {
|
||||
product_client_id: DEFAULT_ORIGINATOR.to_string(),
|
||||
client_name: Some("codex-tui".to_string()),
|
||||
@@ -1440,7 +1375,7 @@ fn thread_initialized_event_serializes_expected_shape() {
|
||||
parent_thread_id: None,
|
||||
forked_from_thread_id: None,
|
||||
created_at: 1,
|
||||
profile: Some(sample_thread_initialization_profile()),
|
||||
profile: None,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -1448,24 +1383,34 @@ fn thread_initialized_event_serializes_expected_shape() {
|
||||
|
||||
assert_eq!(
|
||||
payload,
|
||||
expected_thread_initialized_event(
|
||||
json!({
|
||||
"product_client_id": DEFAULT_ORIGINATOR,
|
||||
"client_name": "codex-tui",
|
||||
"client_version": "1.0.0",
|
||||
"rpc_transport": "stdio",
|
||||
"experimental_api_enabled": true
|
||||
}),
|
||||
json!({
|
||||
"codex_rs_version": "0.1.0",
|
||||
"runtime_os": "macos",
|
||||
"runtime_os_version": "15.3.1",
|
||||
"runtime_arch": "aarch64"
|
||||
}),
|
||||
true,
|
||||
"new",
|
||||
Some(sample_thread_initialization_profile()),
|
||||
)
|
||||
json!({
|
||||
"event_type": "codex_thread_initialized",
|
||||
"event_params": {
|
||||
"thread_id": "thread-0",
|
||||
"session_id": "session-thread-0",
|
||||
"app_server_client": {
|
||||
"product_client_id": DEFAULT_ORIGINATOR,
|
||||
"client_name": "codex-tui",
|
||||
"client_version": "1.0.0",
|
||||
"rpc_transport": "stdio",
|
||||
"experimental_api_enabled": true
|
||||
},
|
||||
"runtime": {
|
||||
"codex_rs_version": "0.1.0",
|
||||
"runtime_os": "macos",
|
||||
"runtime_os_version": "15.3.1",
|
||||
"runtime_arch": "aarch64"
|
||||
},
|
||||
"model": "gpt-5",
|
||||
"ephemeral": true,
|
||||
"thread_source": "user",
|
||||
"initialization_mode": "new",
|
||||
"subagent_source": null,
|
||||
"parent_thread_id": null,
|
||||
"forked_from_thread_id": null,
|
||||
"created_at": 1
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1654,7 +1599,6 @@ async fn initialize_caches_client_and_thread_lifecycle_publishes_once_initialize
|
||||
AnalyticsFact::ClientResponse {
|
||||
connection_id: 7,
|
||||
request_id: RequestId::Integer(1),
|
||||
thread_initialization_profile: None,
|
||||
response: Box::new(sample_thread_start_response(
|
||||
"thread-no-client",
|
||||
/*ephemeral*/ false,
|
||||
@@ -1701,7 +1645,6 @@ async fn initialize_caches_client_and_thread_lifecycle_publishes_once_initialize
|
||||
AnalyticsFact::ClientResponse {
|
||||
connection_id: 7,
|
||||
request_id: RequestId::Integer(2),
|
||||
thread_initialization_profile: None,
|
||||
response: Box::new(sample_thread_resume_response(
|
||||
"thread-1", /*ephemeral*/ true, "gpt-5",
|
||||
)),
|
||||
@@ -1710,85 +1653,42 @@ async fn initialize_caches_client_and_thread_lifecycle_publishes_once_initialize
|
||||
)
|
||||
.await;
|
||||
|
||||
let payload = serde_json::to_value(&events).expect("serialize events");
|
||||
assert_eq!(payload.as_array().expect("events array").len(), 1);
|
||||
assert_eq!(payload[0]["event_type"], "codex_thread_initialized");
|
||||
assert_eq!(payload[0]["event_params"]["session_id"], "session-thread-1");
|
||||
assert_eq!(
|
||||
serde_json::to_value(events).expect("serialize events"),
|
||||
json!([expected_thread_initialized_event(
|
||||
json!({
|
||||
"product_client_id": DEFAULT_ORIGINATOR,
|
||||
"client_name": "codex-tui",
|
||||
"client_version": "1.0.0",
|
||||
"rpc_transport": "websocket",
|
||||
"experimental_api_enabled": false
|
||||
}),
|
||||
json!({
|
||||
"codex_rs_version": "0.99.0",
|
||||
"runtime_os": "linux",
|
||||
"runtime_os_version": "24.04",
|
||||
"runtime_arch": "x86_64"
|
||||
}),
|
||||
true,
|
||||
"resumed",
|
||||
None,
|
||||
)])
|
||||
payload[0]["event_params"]["app_server_client"]["product_client_id"],
|
||||
DEFAULT_ORIGINATOR
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cleared_thread_start_uses_existing_initialized_event_with_profile() {
|
||||
let mut reducer = AnalyticsReducer::default();
|
||||
let mut events = Vec::new();
|
||||
ingest_initialize(&mut reducer, &mut events).await;
|
||||
|
||||
reducer
|
||||
.ingest(
|
||||
AnalyticsFact::ClientRequest {
|
||||
connection_id: 7,
|
||||
request_id: RequestId::Integer(2),
|
||||
request: Box::new(ClientRequest::ThreadStart {
|
||||
request_id: RequestId::Integer(2),
|
||||
params: ThreadStartParams {
|
||||
session_start_source: Some(ThreadStartSource::Clear),
|
||||
..Default::default()
|
||||
},
|
||||
}),
|
||||
},
|
||||
&mut events,
|
||||
)
|
||||
.await;
|
||||
reducer
|
||||
.ingest(
|
||||
AnalyticsFact::ClientResponse {
|
||||
connection_id: 7,
|
||||
request_id: RequestId::Integer(2),
|
||||
thread_initialization_profile: Some(sample_thread_initialization_profile()),
|
||||
response: Box::new(sample_thread_start_response(
|
||||
"thread-1", /*ephemeral*/ false, "gpt-5",
|
||||
)),
|
||||
},
|
||||
&mut events,
|
||||
)
|
||||
.await;
|
||||
|
||||
assert_eq!(
|
||||
serde_json::to_value(events).expect("serialize events"),
|
||||
json!([expected_thread_initialized_event(
|
||||
json!({
|
||||
"product_client_id": "codex-tui",
|
||||
"client_name": "codex-tui",
|
||||
"client_version": "1.0.0",
|
||||
"rpc_transport": "stdio",
|
||||
"experimental_api_enabled": null
|
||||
}),
|
||||
json!({
|
||||
"codex_rs_version": "0.1.0",
|
||||
"runtime_os": "macos",
|
||||
"runtime_os_version": "15.3.1",
|
||||
"runtime_arch": "aarch64"
|
||||
}),
|
||||
false,
|
||||
"cleared",
|
||||
Some(sample_thread_initialization_profile()),
|
||||
)])
|
||||
payload[0]["event_params"]["app_server_client"]["client_name"],
|
||||
"codex-tui"
|
||||
);
|
||||
assert_eq!(
|
||||
payload[0]["event_params"]["app_server_client"]["client_version"],
|
||||
"1.0.0"
|
||||
);
|
||||
assert_eq!(
|
||||
payload[0]["event_params"]["app_server_client"]["rpc_transport"],
|
||||
"websocket"
|
||||
);
|
||||
assert_eq!(
|
||||
payload[0]["event_params"]["app_server_client"]["experimental_api_enabled"],
|
||||
false
|
||||
);
|
||||
assert_eq!(
|
||||
payload[0]["event_params"]["runtime"]["codex_rs_version"],
|
||||
"0.99.0"
|
||||
);
|
||||
assert_eq!(payload[0]["event_params"]["runtime"]["runtime_os"], "linux");
|
||||
assert_eq!(
|
||||
payload[0]["event_params"]["runtime"]["runtime_os_version"],
|
||||
"24.04"
|
||||
);
|
||||
assert_eq!(
|
||||
payload[0]["event_params"]["runtime"]["runtime_arch"],
|
||||
"x86_64"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1817,7 +1717,6 @@ async fn unrelated_client_requests_are_ignored_by_reducer() {
|
||||
AnalyticsFact::ClientResponse {
|
||||
connection_id: 7,
|
||||
request_id: RequestId::Integer(3),
|
||||
thread_initialization_profile: None,
|
||||
response: Box::new(sample_turn_start_response("turn-2")),
|
||||
},
|
||||
&mut events,
|
||||
@@ -1841,7 +1740,6 @@ async fn unrelated_client_responses_are_ignored_by_reducer() {
|
||||
AnalyticsFact::ClientResponse {
|
||||
connection_id: 7,
|
||||
request_id: RequestId::Integer(9),
|
||||
thread_initialization_profile: None,
|
||||
response: Box::new(ClientResponsePayload::ThreadArchive(
|
||||
ThreadArchiveResponse {},
|
||||
)),
|
||||
@@ -1889,7 +1787,6 @@ async fn compaction_event_ingests_custom_fact() {
|
||||
AnalyticsFact::ClientResponse {
|
||||
connection_id: 7,
|
||||
request_id: RequestId::Integer(2),
|
||||
thread_initialization_profile: None,
|
||||
response: Box::new(sample_thread_resume_response_with_source(
|
||||
"thread-1",
|
||||
/*ephemeral*/ false,
|
||||
@@ -2006,7 +1903,6 @@ async fn guardian_review_event_ingests_custom_fact_with_optional_target_item() {
|
||||
AnalyticsFact::ClientResponse {
|
||||
connection_id: 7,
|
||||
request_id: RequestId::Integer(1),
|
||||
thread_initialization_profile: None,
|
||||
response: Box::new(sample_thread_start_response(
|
||||
"thread-guardian",
|
||||
/*ephemeral*/ false,
|
||||
@@ -2510,7 +2406,6 @@ async fn item_review_summaries_do_not_cross_threads_with_reused_item_ids() {
|
||||
AnalyticsFact::ClientResponse {
|
||||
connection_id: 7,
|
||||
request_id: RequestId::Integer(2),
|
||||
thread_initialization_profile: None,
|
||||
response: Box::new(sample_thread_start_response(
|
||||
"thread-2", /*ephemeral*/ false, "gpt-5",
|
||||
)),
|
||||
@@ -2796,7 +2691,6 @@ async fn subagent_thread_started_inherits_parent_connection_for_new_thread() {
|
||||
AnalyticsFact::ClientResponse {
|
||||
connection_id: 7,
|
||||
request_id: RequestId::Integer(1),
|
||||
thread_initialization_profile: None,
|
||||
response: Box::new(sample_thread_start_response(
|
||||
&parent_thread_id_string,
|
||||
/*ephemeral*/ false,
|
||||
@@ -3555,7 +3449,6 @@ async fn accepted_turn_steer_emits_expected_event() {
|
||||
AnalyticsFact::ClientResponse {
|
||||
connection_id: 7,
|
||||
request_id: RequestId::Integer(4),
|
||||
thread_initialization_profile: None,
|
||||
response: Box::new(sample_turn_steer_response("turn-2")),
|
||||
},
|
||||
&mut out,
|
||||
@@ -3727,7 +3620,6 @@ async fn turn_start_error_response_discards_pending_start_request() {
|
||||
AnalyticsFact::ClientResponse {
|
||||
connection_id: 7,
|
||||
request_id: RequestId::Integer(3),
|
||||
thread_initialization_profile: None,
|
||||
response: Box::new(sample_turn_start_response("turn-2")),
|
||||
},
|
||||
&mut out,
|
||||
@@ -4027,7 +3919,6 @@ async fn accepted_steers_increment_turn_steer_count() {
|
||||
AnalyticsFact::ClientResponse {
|
||||
connection_id: 7,
|
||||
request_id: RequestId::Integer(4),
|
||||
thread_initialization_profile: None,
|
||||
response: Box::new(sample_turn_steer_response("turn-2")),
|
||||
},
|
||||
&mut out,
|
||||
@@ -4075,7 +3966,6 @@ async fn accepted_steers_increment_turn_steer_count() {
|
||||
AnalyticsFact::ClientResponse {
|
||||
connection_id: 7,
|
||||
request_id: RequestId::Integer(6),
|
||||
thread_initialization_profile: None,
|
||||
response: Box::new(sample_turn_steer_response("turn-2")),
|
||||
},
|
||||
&mut out,
|
||||
|
||||
@@ -17,7 +17,8 @@ use crate::facts::PluginStateChangedInput;
|
||||
use crate::facts::SkillInvocation;
|
||||
use crate::facts::SkillInvokedInput;
|
||||
use crate::facts::SubAgentThreadStartedInput;
|
||||
use crate::facts::ThreadInitializationProfile;
|
||||
use crate::facts::ThreadInitializationFact;
|
||||
use crate::facts::ThreadInitializationInput;
|
||||
use crate::facts::TrackEventsContext;
|
||||
use crate::facts::TurnCodexErrorFact;
|
||||
use crate::facts::TurnProfileFact;
|
||||
@@ -32,7 +33,6 @@ use codex_app_server_protocol::RequestId;
|
||||
use codex_app_server_protocol::ServerNotification;
|
||||
use codex_app_server_protocol::ServerRequest;
|
||||
use codex_app_server_protocol::ServerResponse;
|
||||
use codex_app_server_protocol::ThreadStartSource;
|
||||
use codex_login::AuthManager;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_login::default_client::create_client;
|
||||
@@ -199,14 +199,10 @@ impl AnalyticsEventsClient {
|
||||
request_id: RequestId,
|
||||
request: &ClientRequest,
|
||||
) {
|
||||
let should_track = match request {
|
||||
ClientRequest::ThreadStart { params, .. } => {
|
||||
params.session_start_source == Some(ThreadStartSource::Clear)
|
||||
}
|
||||
ClientRequest::TurnStart { .. } | ClientRequest::TurnSteer { .. } => true,
|
||||
_ => false,
|
||||
};
|
||||
if !should_track {
|
||||
if !matches!(
|
||||
request,
|
||||
ClientRequest::TurnStart { .. } | ClientRequest::TurnSteer { .. }
|
||||
) {
|
||||
return;
|
||||
}
|
||||
self.record_fact(AnalyticsFact::ClientRequest {
|
||||
@@ -323,7 +319,6 @@ impl AnalyticsEventsClient {
|
||||
connection_id: u64,
|
||||
request_id: RequestId,
|
||||
response: ClientResponsePayload,
|
||||
thread_initialization_profile: Option<ThreadInitializationProfile>,
|
||||
) {
|
||||
if !matches!(
|
||||
response,
|
||||
@@ -339,10 +334,24 @@ impl AnalyticsEventsClient {
|
||||
connection_id,
|
||||
request_id,
|
||||
response: Box::new(response),
|
||||
thread_initialization_profile,
|
||||
});
|
||||
}
|
||||
|
||||
pub fn track_thread_initialization(
|
||||
&self,
|
||||
connection_id: u64,
|
||||
request_id: RequestId,
|
||||
fact: ThreadInitializationFact,
|
||||
) {
|
||||
self.record_fact(AnalyticsFact::Custom(
|
||||
CustomAnalyticsFact::ThreadInitialization(Box::new(ThreadInitializationInput {
|
||||
connection_id,
|
||||
request_id,
|
||||
fact,
|
||||
})),
|
||||
));
|
||||
}
|
||||
|
||||
pub fn track_error_response(
|
||||
&self,
|
||||
connection_id: u64,
|
||||
|
||||
@@ -20,9 +20,7 @@ use codex_app_server_protocol::ThreadArchiveParams;
|
||||
use codex_app_server_protocol::ThreadArchiveResponse;
|
||||
use codex_app_server_protocol::ThreadForkResponse;
|
||||
use codex_app_server_protocol::ThreadResumeResponse;
|
||||
use codex_app_server_protocol::ThreadStartParams;
|
||||
use codex_app_server_protocol::ThreadStartResponse;
|
||||
use codex_app_server_protocol::ThreadStartSource;
|
||||
use codex_app_server_protocol::ThreadStatus as AppServerThreadStatus;
|
||||
use codex_app_server_protocol::Turn;
|
||||
use codex_app_server_protocol::TurnStartParams;
|
||||
@@ -98,16 +96,6 @@ fn sample_turn_start_request() -> ClientRequest {
|
||||
}
|
||||
}
|
||||
|
||||
fn sample_thread_start_request() -> ClientRequest {
|
||||
ClientRequest::ThreadStart {
|
||||
request_id: RequestId::Integer(0),
|
||||
params: ThreadStartParams {
|
||||
session_start_source: Some(ThreadStartSource::Clear),
|
||||
..Default::default()
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn sample_turn_steer_request() -> ClientRequest {
|
||||
ClientRequest::TurnSteer {
|
||||
request_id: RequestId::Integer(2),
|
||||
@@ -234,7 +222,6 @@ fn track_request_only_enqueues_analytics_relevant_requests() {
|
||||
let (client, mut receiver) = client_with_receiver();
|
||||
|
||||
for (request_id, request) in [
|
||||
(RequestId::Integer(0), sample_thread_start_request()),
|
||||
(RequestId::Integer(1), sample_turn_start_request()),
|
||||
(RequestId::Integer(2), sample_turn_steer_request()),
|
||||
] {
|
||||
@@ -265,10 +252,7 @@ fn track_response_only_enqueues_analytics_relevant_responses() {
|
||||
(RequestId::Integer(4), sample_turn_start_response()),
|
||||
(RequestId::Integer(5), sample_turn_steer_response()),
|
||||
] {
|
||||
client.track_response(
|
||||
/*connection_id*/ 7, request_id, response,
|
||||
/*thread_initialization_profile*/ None,
|
||||
);
|
||||
client.track_response(/*connection_id*/ 7, request_id, response);
|
||||
assert!(matches!(
|
||||
receiver.try_recv(),
|
||||
Ok(AnalyticsFact::ClientResponse { .. })
|
||||
@@ -279,7 +263,6 @@ fn track_response_only_enqueues_analytics_relevant_responses() {
|
||||
/*connection_id*/ 7,
|
||||
RequestId::Integer(6),
|
||||
ClientResponsePayload::ThreadArchive(ThreadArchiveResponse {}),
|
||||
/*thread_initialization_profile*/ None,
|
||||
);
|
||||
assert!(matches!(receiver.try_recv(), Err(TryRecvError::Empty)));
|
||||
}
|
||||
|
||||
@@ -116,6 +116,19 @@ pub struct ThreadInitializationProfile {
|
||||
pub plugin_and_skill_warmup_ms: u64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct ThreadInitializationFact {
|
||||
pub initialization_mode: ThreadInitializationMode,
|
||||
pub profile: ThreadInitializationProfile,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct ThreadInitializationInput {
|
||||
pub connection_id: u64,
|
||||
pub request_id: RequestId,
|
||||
pub fact: ThreadInitializationFact,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct TurnTokenUsageFact {
|
||||
pub turn_id: String,
|
||||
@@ -476,7 +489,6 @@ pub(crate) enum AnalyticsFact {
|
||||
connection_id: u64,
|
||||
request_id: RequestId,
|
||||
response: Box<ClientResponsePayload>,
|
||||
thread_initialization_profile: Option<ThreadInitializationProfile>,
|
||||
},
|
||||
ErrorResponse {
|
||||
connection_id: u64,
|
||||
@@ -514,6 +526,7 @@ pub(crate) enum CustomAnalyticsFact {
|
||||
TurnResolvedConfig(Box<TurnResolvedConfigFact>),
|
||||
TurnTokenUsage(Box<TurnTokenUsageFact>),
|
||||
TurnProfile(Box<TurnProfileFact>),
|
||||
ThreadInitialization(Box<ThreadInitializationInput>),
|
||||
TurnCodexError(Box<TurnCodexErrorFact>),
|
||||
SkillInvoked(SkillInvokedInput),
|
||||
AppMentioned(AppMentionedInput),
|
||||
|
||||
@@ -36,6 +36,7 @@ pub use facts::InputError;
|
||||
pub use facts::InvocationType;
|
||||
pub use facts::SkillInvocation;
|
||||
pub use facts::SubAgentThreadStartedInput;
|
||||
pub use facts::ThreadInitializationFact;
|
||||
pub use facts::ThreadInitializationMode;
|
||||
pub use facts::ThreadInitializationProfile;
|
||||
pub use facts::TrackEventsContext;
|
||||
|
||||
@@ -69,6 +69,8 @@ use crate::facts::PluginStateChangedInput;
|
||||
use crate::facts::PluginUsedInput;
|
||||
use crate::facts::SkillInvokedInput;
|
||||
use crate::facts::SubAgentThreadStartedInput;
|
||||
use crate::facts::ThreadInitializationFact;
|
||||
use crate::facts::ThreadInitializationInput;
|
||||
use crate::facts::ThreadInitializationMode;
|
||||
use crate::facts::ThreadInitializationProfile;
|
||||
use crate::facts::TurnCodexError;
|
||||
@@ -110,7 +112,6 @@ use codex_app_server_protocol::ServerNotification;
|
||||
use codex_app_server_protocol::ServerRequest;
|
||||
use codex_app_server_protocol::ServerResponse;
|
||||
use codex_app_server_protocol::ThreadItem;
|
||||
use codex_app_server_protocol::ThreadStartSource;
|
||||
use codex_app_server_protocol::TurnSteerResponse;
|
||||
use codex_app_server_protocol::UserInput;
|
||||
use codex_app_server_protocol::WebSearchAction;
|
||||
@@ -135,6 +136,7 @@ use std::path::PathBuf;
|
||||
#[derive(Default)]
|
||||
pub(crate) struct AnalyticsReducer {
|
||||
requests: HashMap<(u64, RequestId), RequestState>,
|
||||
thread_initializations: HashMap<(u64, RequestId), ThreadInitializationFact>,
|
||||
turns: HashMap<String, TurnState>,
|
||||
connections: HashMap<u64, ConnectionState>,
|
||||
threads: HashMap<String, ThreadAnalyticsState>,
|
||||
@@ -296,7 +298,6 @@ impl ThreadMetadataState {
|
||||
}
|
||||
|
||||
enum RequestState {
|
||||
ClearedThreadStart,
|
||||
TurnStart(PendingTurnStartState),
|
||||
TurnSteer(PendingTurnSteerState),
|
||||
}
|
||||
@@ -409,16 +410,9 @@ impl AnalyticsReducer {
|
||||
connection_id,
|
||||
request_id,
|
||||
response,
|
||||
thread_initialization_profile,
|
||||
} => {
|
||||
if let Some(response) = response.into_client_response(request_id) {
|
||||
self.ingest_response(
|
||||
connection_id,
|
||||
response,
|
||||
thread_initialization_profile,
|
||||
out,
|
||||
)
|
||||
.await;
|
||||
self.ingest_response(connection_id, response, out).await;
|
||||
}
|
||||
}
|
||||
AnalyticsFact::ErrorResponse {
|
||||
@@ -481,6 +475,9 @@ impl AnalyticsReducer {
|
||||
CustomAnalyticsFact::TurnProfile(input) => {
|
||||
self.ingest_turn_profile(*input, out).await;
|
||||
}
|
||||
CustomAnalyticsFact::ThreadInitialization(input) => {
|
||||
self.ingest_thread_initialization(*input);
|
||||
}
|
||||
CustomAnalyticsFact::TurnCodexError(input) => {
|
||||
self.ingest_turn_codex_error(*input);
|
||||
}
|
||||
@@ -589,14 +586,6 @@ impl AnalyticsReducer {
|
||||
request: ClientRequest,
|
||||
) {
|
||||
match request {
|
||||
ClientRequest::ThreadStart { params, .. }
|
||||
if params.session_start_source == Some(ThreadStartSource::Clear) =>
|
||||
{
|
||||
self.requests.insert(
|
||||
(connection_id, request_id),
|
||||
RequestState::ClearedThreadStart,
|
||||
);
|
||||
}
|
||||
ClientRequest::TurnStart { params, .. } => {
|
||||
self.requests.insert(
|
||||
(connection_id, request_id),
|
||||
@@ -778,7 +767,6 @@ impl AnalyticsReducer {
|
||||
&mut self,
|
||||
connection_id: u64,
|
||||
response: ClientResponse,
|
||||
thread_initialization_profile: Option<ThreadInitializationProfile>,
|
||||
out: &mut Vec<TrackEventRequest>,
|
||||
) {
|
||||
match response {
|
||||
@@ -786,36 +774,51 @@ impl AnalyticsReducer {
|
||||
request_id,
|
||||
response,
|
||||
} => {
|
||||
let initialization_mode = match self.requests.remove(&(connection_id, request_id)) {
|
||||
Some(RequestState::ClearedThreadStart) => ThreadInitializationMode::Cleared,
|
||||
_ => ThreadInitializationMode::New,
|
||||
};
|
||||
let initialization = self
|
||||
.thread_initializations
|
||||
.remove(&(connection_id, request_id));
|
||||
self.emit_thread_initialized(
|
||||
connection_id,
|
||||
response.thread,
|
||||
response.model,
|
||||
initialization_mode,
|
||||
thread_initialization_profile,
|
||||
initialization
|
||||
.map(|initialization| initialization.initialization_mode)
|
||||
.unwrap_or(ThreadInitializationMode::New),
|
||||
initialization.map(|initialization| initialization.profile),
|
||||
out,
|
||||
);
|
||||
}
|
||||
ClientResponse::ThreadResume { response, .. } => {
|
||||
ClientResponse::ThreadResume {
|
||||
request_id,
|
||||
response,
|
||||
} => {
|
||||
let profile = self
|
||||
.thread_initializations
|
||||
.remove(&(connection_id, request_id))
|
||||
.map(|initialization| initialization.profile);
|
||||
self.emit_thread_initialized(
|
||||
connection_id,
|
||||
response.thread,
|
||||
response.model,
|
||||
ThreadInitializationMode::Resumed,
|
||||
thread_initialization_profile,
|
||||
profile,
|
||||
out,
|
||||
);
|
||||
}
|
||||
ClientResponse::ThreadFork { response, .. } => {
|
||||
ClientResponse::ThreadFork {
|
||||
request_id,
|
||||
response,
|
||||
} => {
|
||||
let profile = self
|
||||
.thread_initializations
|
||||
.remove(&(connection_id, request_id))
|
||||
.map(|initialization| initialization.profile);
|
||||
self.emit_thread_initialized(
|
||||
connection_id,
|
||||
response.thread,
|
||||
response.model,
|
||||
ThreadInitializationMode::Forked,
|
||||
thread_initialization_profile,
|
||||
profile,
|
||||
out,
|
||||
);
|
||||
}
|
||||
@@ -845,6 +848,11 @@ impl AnalyticsReducer {
|
||||
}
|
||||
}
|
||||
|
||||
fn ingest_thread_initialization(&mut self, input: ThreadInitializationInput) {
|
||||
self.thread_initializations
|
||||
.insert((input.connection_id, input.request_id), input.fact);
|
||||
}
|
||||
|
||||
fn ingest_server_request(&mut self, _connection_id: u64, request: ServerRequest) {
|
||||
match request {
|
||||
ServerRequest::CommandExecutionRequestApproval { request_id, params } => {
|
||||
@@ -1067,7 +1075,6 @@ impl AnalyticsReducer {
|
||||
out: &mut Vec<TrackEventRequest>,
|
||||
) {
|
||||
match request {
|
||||
RequestState::ClearedThreadStart => {}
|
||||
RequestState::TurnStart(_) => {}
|
||||
RequestState::TurnSteer(pending_request) => {
|
||||
self.ingest_turn_steer_error_response(
|
||||
|
||||
@@ -3,7 +3,6 @@ use std::future::Future;
|
||||
use std::sync::Arc;
|
||||
use std::sync::OnceLock;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
use std::time::Instant;
|
||||
|
||||
use crate::attestation::app_server_attestation_provider;
|
||||
use crate::config_manager::ConfigManager;
|
||||
@@ -533,7 +532,6 @@ impl MessageProcessor {
|
||||
transport: &AppServerTransport,
|
||||
session: Arc<ConnectionSessionState>,
|
||||
) {
|
||||
let request_started_at = Instant::now();
|
||||
let request_method = request.method.as_str();
|
||||
tracing::trace!(
|
||||
?connection_id,
|
||||
@@ -550,12 +548,7 @@ impl MessageProcessor {
|
||||
traceparent: trace.traceparent.clone(),
|
||||
tracestate: trace.tracestate.clone(),
|
||||
});
|
||||
let request_context = RequestContext::new(
|
||||
request_id.clone(),
|
||||
request_span,
|
||||
request_trace,
|
||||
request_started_at,
|
||||
);
|
||||
let request_context = RequestContext::new(request_id.clone(), request_span, request_trace);
|
||||
Self::run_request_with_context(
|
||||
Arc::clone(&self.outgoing),
|
||||
request_context.clone(),
|
||||
@@ -602,19 +595,14 @@ impl MessageProcessor {
|
||||
session: Arc<ConnectionSessionState>,
|
||||
outbound_initialized: &AtomicBool,
|
||||
) {
|
||||
let request_started_at = Instant::now();
|
||||
let request_id = ConnectionRequestId {
|
||||
connection_id,
|
||||
request_id: request.id().clone(),
|
||||
};
|
||||
let request_span =
|
||||
crate::app_server_tracing::typed_request_span(&request, connection_id, &session);
|
||||
let request_context = RequestContext::new(
|
||||
request_id.clone(),
|
||||
request_span,
|
||||
/*parent_trace*/ None,
|
||||
request_started_at,
|
||||
);
|
||||
let request_context =
|
||||
RequestContext::new(request_id.clone(), request_span, /*parent_trace*/ None);
|
||||
tracing::trace!(
|
||||
?connection_id,
|
||||
request_id = ?request_id.request_id,
|
||||
@@ -667,7 +655,10 @@ impl MessageProcessor {
|
||||
outgoing
|
||||
.register_request_context(request_context.clone())
|
||||
.await;
|
||||
request_fut.instrument(request_context.span()).await;
|
||||
request_context
|
||||
.thread_initialization_timing()
|
||||
.scope(request_fut.instrument(request_context.span()))
|
||||
.await;
|
||||
}
|
||||
|
||||
pub(crate) fn thread_created_receiver(&self) -> broadcast::Receiver<ThreadId> {
|
||||
@@ -1396,7 +1387,7 @@ impl MessageProcessor {
|
||||
match result {
|
||||
Ok(Some(response)) => {
|
||||
self.outgoing
|
||||
.send_response_as(request_id.clone(), response, None)
|
||||
.send_response_as(request_id.clone(), response)
|
||||
.await;
|
||||
}
|
||||
Ok(None) => {}
|
||||
|
||||
@@ -2,12 +2,10 @@ use std::collections::HashMap;
|
||||
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::ThreadInitializationProfile;
|
||||
use codex_app_server_protocol::ClientResponsePayload;
|
||||
use codex_app_server_protocol::JSONRPCErrorError;
|
||||
use codex_app_server_protocol::RequestId;
|
||||
@@ -16,6 +14,7 @@ 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;
|
||||
@@ -54,7 +53,7 @@ pub(crate) struct RequestContext {
|
||||
request_id: ConnectionRequestId,
|
||||
span: Span,
|
||||
parent_trace: Option<W3cTraceContext>,
|
||||
started_at: Instant,
|
||||
thread_initialization_timing: ThreadInitializationTiming,
|
||||
}
|
||||
|
||||
impl RequestContext {
|
||||
@@ -62,13 +61,12 @@ impl RequestContext {
|
||||
request_id: ConnectionRequestId,
|
||||
span: Span,
|
||||
parent_trace: Option<W3cTraceContext>,
|
||||
started_at: Instant,
|
||||
) -> Self {
|
||||
Self {
|
||||
request_id,
|
||||
span,
|
||||
parent_trace,
|
||||
started_at,
|
||||
thread_initialization_timing: ThreadInitializationTiming::begin_request(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -80,18 +78,12 @@ impl RequestContext {
|
||||
self.span.clone()
|
||||
}
|
||||
|
||||
fn record_turn_id(&self, turn_id: &str) {
|
||||
self.span.record("turn.id", turn_id);
|
||||
pub(crate) fn thread_initialization_timing(&self) -> ThreadInitializationTiming {
|
||||
self.thread_initialization_timing.clone()
|
||||
}
|
||||
|
||||
fn complete_thread_initialization_profile(
|
||||
&self,
|
||||
mut profile: ThreadInitializationProfile,
|
||||
) -> ThreadInitializationProfile {
|
||||
profile.duration_ms = duration_to_u64_ms(self.started_at.elapsed());
|
||||
profile.app_server_duration_ms =
|
||||
profile.duration_ms.saturating_sub(profile.core_duration_ms);
|
||||
profile
|
||||
fn record_turn_id(&self, turn_id: &str) {
|
||||
self.span.record("turn.id", turn_id);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -519,27 +511,13 @@ impl OutgoingMessageSender {
|
||||
where
|
||||
T: Into<ClientResponsePayload>,
|
||||
{
|
||||
self.send_response_as(request_id, response.into(), None)
|
||||
.await;
|
||||
}
|
||||
|
||||
pub(crate) async fn send_response_with_thread_initialization_profile<T>(
|
||||
&self,
|
||||
request_id: ConnectionRequestId,
|
||||
response: T,
|
||||
profile: ThreadInitializationProfile,
|
||||
) where
|
||||
T: Into<ClientResponsePayload>,
|
||||
{
|
||||
self.send_response_as(request_id, response.into(), Some(profile))
|
||||
.await;
|
||||
self.send_response_as(request_id, response.into()).await;
|
||||
}
|
||||
|
||||
pub(crate) async fn send_response_as(
|
||||
&self,
|
||||
request_id: ConnectionRequestId,
|
||||
response: ClientResponsePayload,
|
||||
thread_initialization_profile: Option<ThreadInitializationProfile>,
|
||||
) {
|
||||
let connection_id = request_id.connection_id;
|
||||
let request_id_for_analytics = request_id.request_id.clone();
|
||||
@@ -548,17 +526,20 @@ impl OutgoingMessageSender {
|
||||
.into_jsonrpc_parts_and_payload(request_id.request_id.clone())
|
||||
.map(|(id, result, response)| {
|
||||
if let Some(response) = response {
|
||||
let thread_initialization_profile =
|
||||
thread_initialization_profile.and_then(|profile| {
|
||||
request_context.as_ref().map(|request_context| {
|
||||
request_context.complete_thread_initialization_profile(profile)
|
||||
})
|
||||
});
|
||||
if let Some(thread_initialization) = request_context
|
||||
.as_ref()
|
||||
.and_then(|context| context.thread_initialization_timing.complete_request())
|
||||
{
|
||||
self.analytics_events_client.track_thread_initialization(
|
||||
connection_id.0,
|
||||
request_id_for_analytics.clone(),
|
||||
thread_initialization,
|
||||
);
|
||||
}
|
||||
self.analytics_events_client.track_response(
|
||||
connection_id.0,
|
||||
request_id_for_analytics,
|
||||
response,
|
||||
thread_initialization_profile,
|
||||
);
|
||||
}
|
||||
(id, result)
|
||||
@@ -728,10 +709,6 @@ fn now_unix_timestamp_ms() -> u64 {
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn duration_to_u64_ms(duration: std::time::Duration) -> u64 {
|
||||
u64::try_from(duration.as_millis()).unwrap_or(u64::MAX)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::time::Duration;
|
||||
@@ -1104,7 +1081,6 @@ mod tests {
|
||||
request_id.clone(),
|
||||
tracing::info_span!("app_server.request", rpc.method = "thread/start"),
|
||||
/*parent_trace*/ None,
|
||||
Instant::now(),
|
||||
))
|
||||
.await;
|
||||
assert_eq!(outgoing.request_context_count().await, 1);
|
||||
@@ -1220,7 +1196,6 @@ mod tests {
|
||||
closed_connection_request,
|
||||
tracing::info_span!("app_server.request", rpc.method = "turn/interrupt"),
|
||||
/*parent_trace*/ None,
|
||||
Instant::now(),
|
||||
))
|
||||
.await;
|
||||
outgoing
|
||||
@@ -1228,7 +1203,6 @@ mod tests {
|
||||
open_connection_request,
|
||||
tracing::info_span!("app_server.request", rpc.method = "turn/start"),
|
||||
/*parent_trace*/ None,
|
||||
Instant::now(),
|
||||
))
|
||||
.await;
|
||||
assert_eq!(outgoing.request_context_count().await, 2);
|
||||
|
||||
@@ -149,7 +149,6 @@ impl ConfigRequestProcessor {
|
||||
.send_response_as(
|
||||
request_id,
|
||||
ClientResponsePayload::ExperimentalFeatureEnablementSet(response),
|
||||
None,
|
||||
)
|
||||
.await;
|
||||
Ok(None)
|
||||
|
||||
@@ -662,13 +662,7 @@ pub(super) async fn handle_pending_thread_resume_request(
|
||||
reasoning_effort,
|
||||
initial_turns_page,
|
||||
};
|
||||
outgoing
|
||||
.send_response_with_thread_initialization_profile(
|
||||
request_id,
|
||||
response,
|
||||
pending.thread_initialization_profile,
|
||||
)
|
||||
.await;
|
||||
outgoing.send_response(request_id, response).await;
|
||||
// Match cold resume: metadata-only resume should attach the listener without
|
||||
// paying the cost of turn reconstruction for historical usage replay.
|
||||
if let Some(token_usage_thread) = token_usage_thread {
|
||||
|
||||
@@ -1055,7 +1055,7 @@ impl ThreadRequestProcessor {
|
||||
thread_id,
|
||||
thread,
|
||||
session_configured,
|
||||
thread_initialization_profile,
|
||||
..
|
||||
} = listener_task_context
|
||||
.thread_manager
|
||||
.start_thread_with_options(StartThreadOptions {
|
||||
@@ -1083,9 +1083,6 @@ impl ThreadRequestProcessor {
|
||||
CodexErr::InvalidRequest(message) => invalid_request(message),
|
||||
err => internal_error(format!("error creating thread: {err}")),
|
||||
})?;
|
||||
let thread_initialization_profile = thread_initialization_profile.ok_or_else(|| {
|
||||
internal_error("thread initialization profile missing for app-server thread/start")
|
||||
})?;
|
||||
let session_telemetry = thread.session_telemetry();
|
||||
session_telemetry.record_startup_phase(
|
||||
"thread_start_create_thread",
|
||||
@@ -1179,11 +1176,7 @@ impl ThreadRequestProcessor {
|
||||
let notif = thread_started_notification(thread);
|
||||
listener_task_context
|
||||
.outgoing
|
||||
.send_response_with_thread_initialization_profile(
|
||||
request_id,
|
||||
response,
|
||||
thread_initialization_profile,
|
||||
)
|
||||
.send_response(request_id, response)
|
||||
.instrument(tracing::info_span!(
|
||||
"app_server.thread_start.send_response",
|
||||
otel.name = "app_server.thread_start.send_response",
|
||||
@@ -2435,7 +2428,7 @@ impl ThreadRequestProcessor {
|
||||
.await
|
||||
{
|
||||
Ok(true) => return Ok(()),
|
||||
Ok(false) => {}
|
||||
Ok(false) => ThreadInitializationTiming::start_cold_resume_configuration(),
|
||||
Err(error) => {
|
||||
self.outgoing.send_error(request_id, error).await;
|
||||
return Ok(());
|
||||
@@ -2533,19 +2526,8 @@ impl ThreadRequestProcessor {
|
||||
thread_id,
|
||||
thread: codex_thread,
|
||||
session_configured,
|
||||
thread_initialization_profile,
|
||||
..
|
||||
}) => {
|
||||
let Some(thread_initialization_profile) = thread_initialization_profile else {
|
||||
self.outgoing
|
||||
.send_error(
|
||||
request_id,
|
||||
internal_error(
|
||||
"thread initialization profile missing for app-server thread/resume",
|
||||
),
|
||||
)
|
||||
.await;
|
||||
return Ok(());
|
||||
};
|
||||
if let Err(err) = Self::set_app_server_client_info(
|
||||
codex_thread.as_ref(),
|
||||
app_server_client_name,
|
||||
@@ -2666,13 +2648,7 @@ impl ThreadRequestProcessor {
|
||||
};
|
||||
|
||||
let connection_id = request_id.connection_id;
|
||||
self.outgoing
|
||||
.send_response_with_thread_initialization_profile(
|
||||
request_id,
|
||||
response,
|
||||
thread_initialization_profile,
|
||||
)
|
||||
.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.
|
||||
if let Some(token_usage_thread) = token_usage_thread {
|
||||
@@ -2731,7 +2707,7 @@ impl ThreadRequestProcessor {
|
||||
app_server_client_name: Option<String>,
|
||||
app_server_client_version: Option<String>,
|
||||
) -> Result<bool, JSONRPCErrorError> {
|
||||
let thread_initialization_timing = ThreadInitializationTiming::start();
|
||||
ThreadInitializationTiming::start_loaded_resume();
|
||||
let running_thread = if params.history.is_some() {
|
||||
if let Ok(existing_thread_id) = ThreadId::from_string(¶ms.thread_id)
|
||||
&& self
|
||||
@@ -2829,8 +2805,6 @@ impl ThreadRequestProcessor {
|
||||
}
|
||||
let redact_resume_payloads =
|
||||
should_redact_thread_resume_payloads(app_server_client_name.as_deref());
|
||||
let thread_initialization_profile =
|
||||
thread_initialization_timing.complete_existing_thread_lookup();
|
||||
let history_items = source_thread
|
||||
.history
|
||||
.as_ref()
|
||||
@@ -2886,7 +2860,6 @@ impl ThreadRequestProcessor {
|
||||
let command = crate::thread_state::ThreadListenerCommand::SendThreadResumeResponse(
|
||||
Box::new(crate::thread_state::PendingThreadResumeRequest {
|
||||
request_id: request_id.clone(),
|
||||
thread_initialization_profile,
|
||||
history_items,
|
||||
config_snapshot,
|
||||
instruction_sources,
|
||||
@@ -2903,6 +2876,7 @@ impl ThreadRequestProcessor {
|
||||
"failed to enqueue running thread resume for thread {existing_thread_id}: thread listener command channel is closed"
|
||||
)));
|
||||
}
|
||||
ThreadInitializationTiming::complete_core();
|
||||
return Ok(true);
|
||||
}
|
||||
Ok(false)
|
||||
@@ -3250,7 +3224,7 @@ impl ThreadRequestProcessor {
|
||||
thread_id,
|
||||
thread: forked_thread,
|
||||
session_configured,
|
||||
thread_initialization_profile,
|
||||
..
|
||||
} = self
|
||||
.thread_manager
|
||||
.fork_thread_from_history(
|
||||
@@ -3272,9 +3246,6 @@ impl ThreadRequestProcessor {
|
||||
CodexErr::InvalidRequest(message) => invalid_request(message),
|
||||
err => internal_error(format!("error forking thread: {err}")),
|
||||
})?;
|
||||
let thread_initialization_profile = thread_initialization_profile.ok_or_else(|| {
|
||||
internal_error("thread initialization profile missing for app-server thread/fork")
|
||||
})?;
|
||||
|
||||
Self::set_app_server_client_info(
|
||||
forked_thread.as_ref(),
|
||||
@@ -3389,13 +3360,7 @@ 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
|
||||
.send_response_with_thread_initialization_profile(
|
||||
request_id,
|
||||
response,
|
||||
thread_initialization_profile,
|
||||
)
|
||||
.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.
|
||||
if let Some(token_usage_thread) = token_usage_thread {
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
use crate::outgoing_message::ConnectionId;
|
||||
use crate::outgoing_message::ConnectionRequestId;
|
||||
use codex_analytics::ThreadInitializationProfile;
|
||||
use codex_app_server_protocol::RequestId;
|
||||
use codex_app_server_protocol::ThreadGoal;
|
||||
use codex_app_server_protocol::ThreadHistoryBuilder;
|
||||
@@ -30,7 +29,6 @@ type PendingInterruptQueue = Vec<ConnectionRequestId>;
|
||||
|
||||
pub(crate) struct PendingThreadResumeRequest {
|
||||
pub(crate) request_id: ConnectionRequestId,
|
||||
pub(crate) thread_initialization_profile: ThreadInitializationProfile,
|
||||
pub(crate) history_items: Vec<RolloutItem>,
|
||||
pub(crate) config_snapshot: ThreadConfigSnapshot,
|
||||
pub(crate) instruction_sources: Vec<AbsolutePathBuf>,
|
||||
|
||||
@@ -7,7 +7,6 @@ use codex_config::types::OtelExporterKind;
|
||||
use codex_config::types::OtelHttpProtocol;
|
||||
use codex_core::config::ConfigBuilder;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde::Deserialize;
|
||||
use serde_json::Value;
|
||||
use std::collections::HashMap;
|
||||
use std::path::Path;
|
||||
@@ -211,35 +210,52 @@ pub(crate) fn assert_basic_thread_initialized_event(
|
||||
}
|
||||
|
||||
pub(crate) fn assert_thread_initialization_profile(event: &Value) {
|
||||
let profile = parse_thread_initialization_profile(event);
|
||||
let profile = &event["event_params"];
|
||||
let value = |name: &str| {
|
||||
profile[name]
|
||||
.as_u64()
|
||||
.unwrap_or_else(|| panic!("thread initialization profile should include {name}"))
|
||||
};
|
||||
assert_eq!(
|
||||
(profile.duration_ms, profile.core_duration_ms),
|
||||
(value("duration_ms"), value("core_duration_ms")),
|
||||
(
|
||||
profile
|
||||
.app_server_duration_ms
|
||||
.saturating_add(profile.core_duration_ms),
|
||||
profile
|
||||
.existing_thread_lookup_ms
|
||||
.saturating_add(profile.configuration_resolution_ms)
|
||||
.saturating_add(profile.session_dependency_loading_ms)
|
||||
.saturating_add(profile.session_construction_ms)
|
||||
.saturating_add(profile.mcp_startup_ms)
|
||||
.saturating_add(profile.session_activation_ms)
|
||||
.saturating_add(profile.thread_registration_ms),
|
||||
value("app_server_duration_ms").saturating_add(value("core_duration_ms")),
|
||||
value("existing_thread_lookup_ms")
|
||||
.saturating_add(value("configuration_resolution_ms"))
|
||||
.saturating_add(value("session_dependency_loading_ms"))
|
||||
.saturating_add(value("session_construction_ms"))
|
||||
.saturating_add(value("mcp_startup_ms"))
|
||||
.saturating_add(value("session_activation_ms"))
|
||||
.saturating_add(value("thread_registration_ms")),
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
pub(crate) fn assert_loaded_resume_thread_initialization_profile(event: &Value) {
|
||||
let profile = parse_thread_initialization_profile(event);
|
||||
let expected = CapturedThreadInitializationProfile {
|
||||
duration_ms: profile.duration_ms,
|
||||
app_server_duration_ms: profile.app_server_duration_ms,
|
||||
core_duration_ms: profile.existing_thread_lookup_ms,
|
||||
existing_thread_lookup_ms: profile.existing_thread_lookup_ms,
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(profile, expected);
|
||||
let profile = &event["event_params"];
|
||||
let lookup_ms = profile["existing_thread_lookup_ms"]
|
||||
.as_u64()
|
||||
.expect("loaded resume should include existing thread lookup timing");
|
||||
assert_eq!(
|
||||
(
|
||||
profile["core_duration_ms"].as_u64(),
|
||||
profile["configuration_resolution_ms"].as_u64(),
|
||||
profile["session_dependency_loading_ms"].as_u64(),
|
||||
profile["session_construction_ms"].as_u64(),
|
||||
profile["mcp_startup_ms"].as_u64(),
|
||||
profile["session_activation_ms"].as_u64(),
|
||||
profile["thread_registration_ms"].as_u64(),
|
||||
),
|
||||
(
|
||||
Some(lookup_ms),
|
||||
Some(0),
|
||||
Some(0),
|
||||
Some(0),
|
||||
Some(0),
|
||||
Some(0),
|
||||
Some(0)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
pub(crate) async fn wait_for_thread_initialized_events(
|
||||
@@ -270,28 +286,3 @@ pub(crate) async fn wait_for_thread_initialized_events(
|
||||
})
|
||||
.await?
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Deserialize, PartialEq, Eq)]
|
||||
struct CapturedThreadInitializationProfile {
|
||||
duration_ms: u64,
|
||||
app_server_duration_ms: u64,
|
||||
core_duration_ms: u64,
|
||||
existing_thread_lookup_ms: u64,
|
||||
configuration_resolution_ms: u64,
|
||||
session_dependency_loading_ms: u64,
|
||||
session_construction_ms: u64,
|
||||
mcp_startup_ms: u64,
|
||||
session_activation_ms: u64,
|
||||
thread_registration_ms: u64,
|
||||
thread_persistence_ms: u64,
|
||||
state_db_loading_ms: u64,
|
||||
auth_and_mcp_discovery_ms: u64,
|
||||
plugin_and_skill_warmup_ms: u64,
|
||||
}
|
||||
|
||||
fn parse_thread_initialization_profile(event: &Value) -> CapturedThreadInitializationProfile {
|
||||
match serde_json::from_value(event["event_params"].clone()) {
|
||||
Ok(profile) => profile,
|
||||
Err(error) => panic!("thread initialized event should include a complete profile: {error}"),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -101,7 +101,6 @@ use wiremock::matchers::path;
|
||||
|
||||
use super::analytics::assert_basic_thread_initialized_event;
|
||||
use super::analytics::assert_loaded_resume_thread_initialization_profile;
|
||||
use super::analytics::assert_thread_initialization_profile;
|
||||
use super::analytics::mount_analytics_capture;
|
||||
use super::analytics::thread_initialized_event;
|
||||
use super::analytics::wait_for_analytics_payload;
|
||||
@@ -151,7 +150,8 @@ async fn wait_for_responses_request_count(
|
||||
async fn thread_resume_rejects_unmaterialized_thread() -> Result<()> {
|
||||
let server = create_mock_responses_server_repeating_assistant("Done").await;
|
||||
let codex_home = TempDir::new()?;
|
||||
create_config_toml(codex_home.path(), &server.uri())?;
|
||||
create_config_toml_with_chatgpt_base_url(codex_home.path(), &server.uri(), &server.uri())?;
|
||||
mount_analytics_capture(&server, codex_home.path()).await?;
|
||||
|
||||
let mut mcp = TestAppServer::new(codex_home.path()).await?;
|
||||
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
|
||||
@@ -471,8 +471,7 @@ async fn thread_resume_tracks_thread_initialized_analytics() -> Result<()> {
|
||||
let server = create_mock_responses_server_repeating_assistant("Done").await;
|
||||
|
||||
let codex_home = TempDir::new()?;
|
||||
create_config_toml_with_chatgpt_base_url(codex_home.path(), &server.uri(), &server.uri())?;
|
||||
mount_analytics_capture(&server, codex_home.path()).await?;
|
||||
create_config_toml(codex_home.path(), &server.uri())?;
|
||||
|
||||
let conversation_id = create_fake_rollout(
|
||||
codex_home.path(),
|
||||
@@ -3408,13 +3407,11 @@ async fn thread_resume_can_load_source_by_external_path() -> Result<()> {
|
||||
async fn thread_resume_supports_history_and_overrides() -> Result<()> {
|
||||
let server = create_mock_responses_server_repeating_assistant("Done").await;
|
||||
let codex_home = TempDir::new()?;
|
||||
create_config_toml_with_chatgpt_base_url(codex_home.path(), &server.uri(), &server.uri())?;
|
||||
mount_analytics_capture(&server, codex_home.path()).await?;
|
||||
create_config_toml(codex_home.path(), &server.uri())?;
|
||||
|
||||
let RestartedThreadFixture {
|
||||
mut mcp, thread_id, ..
|
||||
} = start_materialized_thread_and_restart(codex_home.path(), "seed history").await?;
|
||||
wait_for_thread_initialized_events(&server, DEFAULT_READ_TIMEOUT, 1).await?;
|
||||
|
||||
let history_text = "Hello from history";
|
||||
let history = vec![ResponseItem::Message {
|
||||
@@ -3451,13 +3448,6 @@ async fn thread_resume_supports_history_and_overrides() -> Result<()> {
|
||||
assert_eq!(resumed.preview, history_text);
|
||||
assert_eq!(resumed.status, ThreadStatus::Idle);
|
||||
|
||||
let events = wait_for_thread_initialized_events(&server, DEFAULT_READ_TIMEOUT, 2).await?;
|
||||
let event = events
|
||||
.last()
|
||||
.expect("history resume should emit a thread initialized event");
|
||||
assert_eq!(event["event_params"]["initialization_mode"], "resumed");
|
||||
assert_thread_initialization_profile(event);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -17,7 +17,6 @@ use codex_app_server_protocol::ServerNotification;
|
||||
use codex_app_server_protocol::ThreadSource;
|
||||
use codex_app_server_protocol::ThreadStartParams;
|
||||
use codex_app_server_protocol::ThreadStartResponse;
|
||||
use codex_app_server_protocol::ThreadStartSource;
|
||||
use codex_app_server_protocol::ThreadStartedNotification;
|
||||
use codex_app_server_protocol::ThreadStatus;
|
||||
use codex_app_server_protocol::ThreadStatusChangedNotification;
|
||||
@@ -484,44 +483,6 @@ async fn thread_start_tracks_thread_initialized_analytics() -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn thread_clear_tracks_cleared_thread_initialized_analytics() -> Result<()> {
|
||||
let server = create_mock_responses_server_repeating_assistant("Done").await;
|
||||
|
||||
let codex_home = TempDir::new()?;
|
||||
create_config_toml_with_chatgpt_base_url(codex_home.path(), &server.uri(), &server.uri())?;
|
||||
mount_analytics_capture(&server, codex_home.path()).await?;
|
||||
|
||||
let mut mcp = TestAppServer::new_without_managed_config(codex_home.path()).await?;
|
||||
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
|
||||
|
||||
let req_id = mcp
|
||||
.send_thread_start_request(ThreadStartParams {
|
||||
session_start_source: Some(ThreadStartSource::Clear),
|
||||
thread_source: Some(ThreadSource::User),
|
||||
..Default::default()
|
||||
})
|
||||
.await?;
|
||||
let resp: JSONRPCResponse = timeout(
|
||||
DEFAULT_READ_TIMEOUT,
|
||||
mcp.read_stream_until_response_message(RequestId::Integer(req_id)),
|
||||
)
|
||||
.await??;
|
||||
let ThreadStartResponse { thread, .. } = to_response::<ThreadStartResponse>(resp)?;
|
||||
|
||||
let payload = wait_for_analytics_payload(&server, DEFAULT_READ_TIMEOUT).await?;
|
||||
let event = thread_initialized_event(&payload)?;
|
||||
assert_basic_thread_initialized_event(
|
||||
event,
|
||||
&thread.id,
|
||||
&thread.session_id,
|
||||
"mock-model",
|
||||
"cleared",
|
||||
"user",
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn thread_start_respects_project_config_from_cwd() -> Result<()> {
|
||||
let server = create_mock_responses_server_repeating_assistant("Done").await;
|
||||
|
||||
@@ -30,7 +30,6 @@ use tokio::sync::Mutex;
|
||||
use tokio::time::timeout;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
use crate::ThreadInitializationTiming;
|
||||
use crate::config::Config;
|
||||
use crate::guardian::GuardianApprovalRequest;
|
||||
use crate::guardian::new_guardian_review_id;
|
||||
@@ -108,7 +107,6 @@ 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: ThreadInitializationTiming::start(),
|
||||
}))
|
||||
.or_cancel(&cancel_token)
|
||||
.await??;
|
||||
|
||||
@@ -108,7 +108,6 @@ mod thread_initialization_timing;
|
||||
mod thread_manager;
|
||||
pub(crate) mod web_search;
|
||||
pub(crate) mod windows_sandbox_read_grants;
|
||||
pub use codex_analytics::ThreadInitializationProfile;
|
||||
pub use thread_initialization_timing::ThreadInitializationTiming;
|
||||
pub use thread_manager::ForkSnapshot;
|
||||
pub use thread_manager::NewThread;
|
||||
|
||||
@@ -36,8 +36,6 @@ use crate::realtime_conversation::RealtimeConversationManager;
|
||||
use crate::session_prefix::format_subagent_notification_message;
|
||||
use crate::skills::SkillRenderSideEffects;
|
||||
use crate::skills_load_input_from_config;
|
||||
use crate::thread_initialization_timing::ThreadInitializationPhase;
|
||||
use crate::thread_initialization_timing::ThreadInitializationTiming;
|
||||
use crate::turn_metadata::TurnMetadataState;
|
||||
use crate::turn_timing::now_unix_timestamp_ms;
|
||||
use async_channel::Receiver;
|
||||
@@ -423,7 +421,6 @@ 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(
|
||||
@@ -504,7 +501,6 @@ impl Codex {
|
||||
thread_store,
|
||||
attestation_provider,
|
||||
inherited_multi_agent_version,
|
||||
thread_initialization_timing,
|
||||
} = args;
|
||||
let (tx_sub, rx_sub) = async_channel::bounded(SUBMISSION_CHANNEL_CAPACITY);
|
||||
let (tx_event, rx_event) = async_channel::unbounded();
|
||||
@@ -650,14 +646,12 @@ impl Codex {
|
||||
parent_rollout_thread_trace,
|
||||
attestation_provider,
|
||||
multi_agent_version,
|
||||
thread_initialization_timing.clone(),
|
||||
))
|
||||
.await
|
||||
.map_err(|e| {
|
||||
error!("Failed to create session: {e:#}");
|
||||
map_session_init_error(&e, &config.codex_home)
|
||||
})?;
|
||||
thread_initialization_timing.transition_to(ThreadInitializationPhase::ThreadRegistration);
|
||||
let thread_id = session.thread_id;
|
||||
|
||||
// This task will run until Op::Shutdown is received.
|
||||
|
||||
@@ -493,7 +493,6 @@ impl Session {
|
||||
parent_rollout_thread_trace: ThreadTraceContext,
|
||||
attestation_provider: Option<Arc<dyn AttestationProvider>>,
|
||||
multi_agent_version: Option<MultiAgentVersion>,
|
||||
thread_initialization_timing: ThreadInitializationTiming,
|
||||
) -> anyhow::Result<Arc<Self>> {
|
||||
debug!(
|
||||
"Configuring session: model={}; provider={:?}",
|
||||
@@ -533,12 +532,13 @@ impl Session {
|
||||
// - initialize thread persistence with new or resumed session info
|
||||
// - perform default shell discovery
|
||||
// - load history metadata (skipped for subagents)
|
||||
thread_initialization_timing
|
||||
.transition_to(ThreadInitializationPhase::SessionDependencyLoading);
|
||||
let thread_persistence_timing = thread_initialization_timing.clone();
|
||||
ThreadInitializationTiming::transition_to(
|
||||
ThreadInitializationPhase::SessionDependencyLoading,
|
||||
);
|
||||
let thread_persistence_fut = async {
|
||||
let _timing_guard = thread_persistence_timing
|
||||
.begin_session_dependency(SessionDependencyBranch::ThreadPersistence);
|
||||
let _timing_guard = ThreadInitializationTiming::begin_session_dependency(
|
||||
SessionDependencyBranch::ThreadPersistence,
|
||||
);
|
||||
if config.ephemeral {
|
||||
Ok::<_, anyhow::Error>(None)
|
||||
} else {
|
||||
@@ -600,10 +600,10 @@ impl Session {
|
||||
otel.name = "session_init.thread_persistence",
|
||||
session_init.ephemeral = config.ephemeral,
|
||||
));
|
||||
let state_db_timing = thread_initialization_timing.clone();
|
||||
let state_db_fut = async {
|
||||
let _timing_guard =
|
||||
state_db_timing.begin_session_dependency(SessionDependencyBranch::StateDbLoading);
|
||||
let _timing_guard = ThreadInitializationTiming::begin_session_dependency(
|
||||
SessionDependencyBranch::StateDbLoading,
|
||||
);
|
||||
if config.ephemeral {
|
||||
None
|
||||
} else if let Some(local_store) =
|
||||
@@ -623,10 +623,10 @@ impl Session {
|
||||
let auth_manager_clone = Arc::clone(&auth_manager);
|
||||
let config_for_mcp = Arc::clone(&config);
|
||||
let mcp_manager_for_mcp = Arc::clone(&mcp_manager);
|
||||
let auth_and_mcp_timing = thread_initialization_timing.clone();
|
||||
let auth_and_mcp_fut = async move {
|
||||
let _timing_guard = auth_and_mcp_timing
|
||||
.begin_session_dependency(SessionDependencyBranch::AuthAndMcpDiscovery);
|
||||
let _timing_guard = ThreadInitializationTiming::begin_session_dependency(
|
||||
SessionDependencyBranch::AuthAndMcpDiscovery,
|
||||
);
|
||||
let auth = auth_manager_clone.auth().await;
|
||||
let mcp_servers = mcp_manager_for_mcp
|
||||
.effective_servers(&config_for_mcp, auth.as_ref())
|
||||
@@ -644,10 +644,10 @@ impl Session {
|
||||
otel.name = "session_init.auth_mcp",
|
||||
));
|
||||
|
||||
let plugin_and_skill_warmup_timing = thread_initialization_timing.clone();
|
||||
let plugin_and_skill_warmup_fut = async {
|
||||
let _timing_guard = plugin_and_skill_warmup_timing
|
||||
.begin_session_dependency(SessionDependencyBranch::PluginAndSkillWarmup);
|
||||
let _timing_guard = ThreadInitializationTiming::begin_session_dependency(
|
||||
SessionDependencyBranch::PluginAndSkillWarmup,
|
||||
);
|
||||
warm_plugins_and_skills_for_session_init(
|
||||
Arc::clone(&config),
|
||||
Arc::clone(&environment_manager),
|
||||
@@ -674,7 +674,7 @@ impl Session {
|
||||
auth_and_mcp_fut,
|
||||
plugin_and_skill_warmup_fut
|
||||
);
|
||||
thread_initialization_timing.transition_to(ThreadInitializationPhase::SessionConstruction);
|
||||
ThreadInitializationTiming::transition_to(ThreadInitializationPhase::SessionConstruction);
|
||||
|
||||
for err in &plugin_skill_errors {
|
||||
error!(
|
||||
@@ -1129,7 +1129,7 @@ impl Session {
|
||||
sess.send_event_raw(event).await;
|
||||
}
|
||||
|
||||
thread_initialization_timing.transition_to(ThreadInitializationPhase::McpStartup);
|
||||
ThreadInitializationTiming::transition_to(ThreadInitializationPhase::McpStartup);
|
||||
let mut required_mcp_servers: Vec<String> = mcp_servers
|
||||
.iter()
|
||||
.filter(|(_, server)| server.enabled() && server.required())
|
||||
@@ -1236,8 +1236,7 @@ impl Session {
|
||||
anyhow::bail!("required MCP servers failed to initialize: {details}");
|
||||
}
|
||||
}
|
||||
thread_initialization_timing
|
||||
.transition_to(ThreadInitializationPhase::SessionActivation);
|
||||
ThreadInitializationTiming::transition_to(ThreadInitializationPhase::SessionActivation);
|
||||
sess.schedule_startup_prewarm(session_configuration.base_instructions.clone())
|
||||
.await;
|
||||
let session_start_source = match &initial_history {
|
||||
@@ -1261,6 +1260,9 @@ impl Session {
|
||||
match session_result {
|
||||
Ok(sess) => {
|
||||
live_thread_init.commit();
|
||||
ThreadInitializationTiming::transition_to(
|
||||
ThreadInitializationPhase::ThreadRegistration,
|
||||
);
|
||||
Ok(sess)
|
||||
}
|
||||
Err(err) => {
|
||||
|
||||
@@ -4673,7 +4673,6 @@ 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()),
|
||||
ThreadInitializationTiming::start(),
|
||||
)
|
||||
.await;
|
||||
|
||||
@@ -5022,7 +5021,6 @@ async fn make_session_with_config_and_rx(
|
||||
codex_rollout_trace::ThreadTraceContext::disabled(),
|
||||
/*attestation_provider*/ None,
|
||||
Some(config.multi_agent_version_from_features()),
|
||||
ThreadInitializationTiming::start(),
|
||||
)
|
||||
.await?;
|
||||
|
||||
@@ -5135,7 +5133,6 @@ 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()),
|
||||
ThreadInitializationTiming::start(),
|
||||
)
|
||||
.await?;
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
use super::*;
|
||||
use crate::ThreadInitializationTiming;
|
||||
use crate::compact::InitialContextInjection;
|
||||
use crate::environment_selection::ResolvedTurnEnvironments;
|
||||
use crate::exec_policy::ExecPolicyManager;
|
||||
@@ -736,7 +735,6 @@ async fn guardian_subagent_does_not_inherit_parent_exec_policy_rules() {
|
||||
thread_store,
|
||||
attestation_provider: None,
|
||||
inherited_multi_agent_version: None,
|
||||
thread_initialization_timing: ThreadInitializationTiming::start(),
|
||||
})
|
||||
.await
|
||||
.expect("spawn guardian subagent");
|
||||
|
||||
@@ -1,12 +1,16 @@
|
||||
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::ThreadInitializationFact;
|
||||
use codex_analytics::ThreadInitializationMode;
|
||||
use codex_analytics::ThreadInitializationProfile;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
#[repr(usize)]
|
||||
pub(crate) enum ThreadInitializationPhase {
|
||||
ExistingThreadLookup,
|
||||
ConfigurationResolution,
|
||||
@@ -18,7 +22,6 @@ pub(crate) enum ThreadInitializationPhase {
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
#[repr(usize)]
|
||||
pub(crate) enum SessionDependencyBranch {
|
||||
ThreadPersistence,
|
||||
StateDbLoading,
|
||||
@@ -26,23 +29,22 @@ pub(crate) enum SessionDependencyBranch {
|
||||
PluginAndSkillWarmup,
|
||||
}
|
||||
|
||||
const PHASE_COUNT: usize = 7;
|
||||
const DEPENDENCY_BRANCH_COUNT: usize = 4;
|
||||
|
||||
/// Monotonic timing state for a thread initialization operation.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ThreadInitializationTiming {
|
||||
state: Arc<Mutex<ThreadInitializationTimingState>>,
|
||||
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>>);
|
||||
|
||||
#[derive(Debug)]
|
||||
struct ThreadInitializationTimingState {
|
||||
started_at: Instant,
|
||||
last_transition_at: Instant,
|
||||
active_phase: ThreadInitializationPhase,
|
||||
phase_durations: [Duration; PHASE_COUNT],
|
||||
dependency_branch_durations: [Duration; DEPENDENCY_BRANCH_COUNT],
|
||||
completed_profile: Option<ThreadInitializationProfile>,
|
||||
request_started_at: Instant,
|
||||
last_transition_at: Option<Instant>,
|
||||
active_phase: Option<ThreadInitializationPhase>,
|
||||
initialization_mode: Option<ThreadInitializationMode>,
|
||||
profile: ThreadInitializationProfile,
|
||||
core_complete: bool,
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
@@ -53,87 +55,152 @@ pub(crate) struct SessionDependencyTimingGuard {
|
||||
}
|
||||
|
||||
impl ThreadInitializationTiming {
|
||||
/// Starts timing in the existing-thread lookup phase at the current monotonic instant.
|
||||
pub fn start() -> Self {
|
||||
Self::start_at(Instant::now())
|
||||
pub fn begin_request() -> Self {
|
||||
Self::new_at(Instant::now())
|
||||
}
|
||||
|
||||
pub(crate) fn start_configuration_resolution() -> Self {
|
||||
let timing = Self::start();
|
||||
timing.transition_to(ThreadInitializationPhase::ConfigurationResolution);
|
||||
timing
|
||||
pub async fn scope<F>(&self, future: F) -> F::Output
|
||||
where
|
||||
F: Future,
|
||||
{
|
||||
ACTIVE_THREAD_INITIALIZATION_TIMING
|
||||
.scope(self.clone(), future)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Completes a lookup-only initialization, such as resuming an already loaded thread.
|
||||
pub fn complete_existing_thread_lookup(&self) -> ThreadInitializationProfile {
|
||||
self.complete_at(Instant::now())
|
||||
pub fn start_loaded_resume() {
|
||||
Self::start_current(
|
||||
ThreadInitializationMode::Resumed,
|
||||
ThreadInitializationPhase::ExistingThreadLookup,
|
||||
);
|
||||
}
|
||||
|
||||
pub(crate) fn transition_to(&self, phase: ThreadInitializationPhase) {
|
||||
self.transition_at(Instant::now(), phase);
|
||||
pub fn start_cold_resume_configuration() {
|
||||
Self::transition_to(ThreadInitializationPhase::ConfigurationResolution);
|
||||
}
|
||||
|
||||
pub fn complete_core() {
|
||||
Self::with_current(|timing| timing.complete_core_at(Instant::now()));
|
||||
}
|
||||
|
||||
pub fn complete_request(&self) -> Option<ThreadInitializationFact> {
|
||||
self.complete_request_at(Instant::now())
|
||||
}
|
||||
|
||||
pub(crate) fn start_configuration_resolution(mode: ThreadInitializationMode) {
|
||||
Self::start_current(mode, ThreadInitializationPhase::ConfigurationResolution);
|
||||
}
|
||||
|
||||
pub(crate) fn start_existing_thread_lookup() {
|
||||
Self::start_current(
|
||||
ThreadInitializationMode::Resumed,
|
||||
ThreadInitializationPhase::ExistingThreadLookup,
|
||||
);
|
||||
}
|
||||
|
||||
pub(crate) fn transition_to(phase: ThreadInitializationPhase) {
|
||||
Self::with_current(|timing| timing.transition_at(Instant::now(), phase));
|
||||
}
|
||||
|
||||
pub(crate) fn begin_session_dependency(
|
||||
&self,
|
||||
branch: SessionDependencyBranch,
|
||||
) -> SessionDependencyTimingGuard {
|
||||
SessionDependencyTimingGuard {
|
||||
timing: self.clone(),
|
||||
branch,
|
||||
started_at: Instant::now(),
|
||||
}
|
||||
) -> Option<SessionDependencyTimingGuard> {
|
||||
ACTIVE_THREAD_INITIALIZATION_TIMING
|
||||
.try_with(|timing| SessionDependencyTimingGuard {
|
||||
timing: timing.clone(),
|
||||
branch,
|
||||
started_at: Instant::now(),
|
||||
})
|
||||
.ok()
|
||||
}
|
||||
|
||||
pub(crate) fn complete(&self) -> ThreadInitializationProfile {
|
||||
self.complete_at(Instant::now())
|
||||
fn start_current(mode: ThreadInitializationMode, phase: ThreadInitializationPhase) {
|
||||
Self::with_current(|timing| timing.start_core_at(Instant::now(), mode, phase));
|
||||
}
|
||||
|
||||
fn start_at(started_at: Instant) -> Self {
|
||||
Self {
|
||||
state: Arc::new(Mutex::new(ThreadInitializationTimingState {
|
||||
started_at,
|
||||
last_transition_at: started_at,
|
||||
active_phase: ThreadInitializationPhase::ExistingThreadLookup,
|
||||
phase_durations: [Duration::ZERO; PHASE_COUNT],
|
||||
dependency_branch_durations: [Duration::ZERO; DEPENDENCY_BRANCH_COUNT],
|
||||
completed_profile: None,
|
||||
})),
|
||||
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,
|
||||
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.completed_profile.is_some() {
|
||||
if state.core_complete || state.last_transition_at.is_none() {
|
||||
return;
|
||||
}
|
||||
state.advance(now);
|
||||
state.active_phase = phase;
|
||||
state.active_phase = Some(phase);
|
||||
}
|
||||
|
||||
fn record_session_dependency(&self, branch: SessionDependencyBranch, duration: Duration) {
|
||||
fn complete_core_at(&self, now: Instant) {
|
||||
let mut state = self.state();
|
||||
if state.completed_profile.is_some() {
|
||||
if state.core_complete || state.last_transition_at.is_none() {
|
||||
return;
|
||||
}
|
||||
let branch_duration = &mut state.dependency_branch_durations[branch as usize];
|
||||
*branch_duration = branch_duration.saturating_add(duration);
|
||||
state.advance(now);
|
||||
state.profile.core_duration_ms = core_duration_ms(&state.profile);
|
||||
state.active_phase = None;
|
||||
state.core_complete = true;
|
||||
}
|
||||
|
||||
fn complete_at(&self, now: Instant) -> ThreadInitializationProfile {
|
||||
fn complete_request_at(&self, now: Instant) -> Option<ThreadInitializationFact> {
|
||||
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(ThreadInitializationFact {
|
||||
initialization_mode: state.initialization_mode?,
|
||||
profile,
|
||||
})
|
||||
}
|
||||
|
||||
fn record_dependency(&self, branch: SessionDependencyBranch, duration: Duration) {
|
||||
let mut state = self.state();
|
||||
state.complete(now)
|
||||
if state.core_complete || state.last_transition_at.is_none() {
|
||||
return;
|
||||
}
|
||||
let duration_ms = duration_to_u64_ms(duration);
|
||||
*dependency_duration_mut(&mut state.profile, branch) = duration_ms;
|
||||
}
|
||||
|
||||
fn state(&self) -> std::sync::MutexGuard<'_, ThreadInitializationTimingState> {
|
||||
self.state
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
fn state(&self) -> MutexGuard<'_, ThreadInitializationTimingState> {
|
||||
self.0.lock().unwrap_or_else(PoisonError::into_inner)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for SessionDependencyTimingGuard {
|
||||
fn drop(&mut self) {
|
||||
self.timing.record_session_dependency(
|
||||
self.timing.record_dependency(
|
||||
self.branch,
|
||||
Instant::now().saturating_duration_since(self.started_at),
|
||||
);
|
||||
@@ -142,75 +209,59 @@ impl Drop for SessionDependencyTimingGuard {
|
||||
|
||||
impl ThreadInitializationTimingState {
|
||||
fn advance(&mut self, now: Instant) {
|
||||
let elapsed = now.saturating_duration_since(self.last_transition_at);
|
||||
self.last_transition_at = now;
|
||||
let phase_duration = &mut self.phase_durations[self.active_phase as usize];
|
||||
*phase_duration = phase_duration.saturating_add(elapsed);
|
||||
}
|
||||
|
||||
fn complete(&mut self, now: Instant) -> ThreadInitializationProfile {
|
||||
if let Some(profile) = self.completed_profile.as_ref() {
|
||||
return *profile;
|
||||
}
|
||||
|
||||
self.advance(now);
|
||||
let mut phase_durations_ms = self.phase_durations.map(duration_to_u64_ms);
|
||||
let elapsed_ms = duration_to_u64_ms(now.saturating_duration_since(self.started_at));
|
||||
let classified_ms = phase_durations_ms
|
||||
.iter()
|
||||
.copied()
|
||||
.fold(0_u64, u64::saturating_add);
|
||||
let active_phase_ms = &mut phase_durations_ms[self.active_phase as usize];
|
||||
*active_phase_ms = active_phase_ms.saturating_add(elapsed_ms.saturating_sub(classified_ms));
|
||||
let dependency_branch_durations_ms =
|
||||
self.dependency_branch_durations.map(duration_to_u64_ms);
|
||||
let profile = profile_from_durations(phase_durations_ms, dependency_branch_durations_ms);
|
||||
self.completed_profile = Some(profile);
|
||||
profile
|
||||
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);
|
||||
*phase_duration = phase_duration.saturating_add(duration_ms);
|
||||
}
|
||||
}
|
||||
|
||||
fn profile_from_durations(
|
||||
phase_durations_ms: [u64; PHASE_COUNT],
|
||||
dependency_branch_durations_ms: [u64; DEPENDENCY_BRANCH_COUNT],
|
||||
) -> ThreadInitializationProfile {
|
||||
let [
|
||||
existing_thread_lookup_ms,
|
||||
configuration_resolution_ms,
|
||||
session_dependency_loading_ms,
|
||||
session_construction_ms,
|
||||
mcp_startup_ms,
|
||||
session_activation_ms,
|
||||
thread_registration_ms,
|
||||
] = phase_durations_ms;
|
||||
let [
|
||||
thread_persistence_ms,
|
||||
state_db_loading_ms,
|
||||
auth_and_mcp_discovery_ms,
|
||||
plugin_and_skill_warmup_ms,
|
||||
] = dependency_branch_durations_ms;
|
||||
let core_duration_ms = phase_durations_ms
|
||||
.iter()
|
||||
.copied()
|
||||
.fold(0_u64, u64::saturating_add);
|
||||
ThreadInitializationProfile {
|
||||
duration_ms: core_duration_ms,
|
||||
core_duration_ms,
|
||||
existing_thread_lookup_ms,
|
||||
configuration_resolution_ms,
|
||||
session_dependency_loading_ms,
|
||||
session_construction_ms,
|
||||
mcp_startup_ms,
|
||||
session_activation_ms,
|
||||
thread_registration_ms,
|
||||
thread_persistence_ms,
|
||||
state_db_loading_ms,
|
||||
auth_and_mcp_discovery_ms,
|
||||
plugin_and_skill_warmup_ms,
|
||||
..Default::default()
|
||||
fn phase_duration_mut(
|
||||
profile: &mut ThreadInitializationProfile,
|
||||
phase: ThreadInitializationPhase,
|
||||
) -> &mut u64 {
|
||||
match phase {
|
||||
ThreadInitializationPhase::ExistingThreadLookup => &mut profile.existing_thread_lookup_ms,
|
||||
ThreadInitializationPhase::ConfigurationResolution => {
|
||||
&mut profile.configuration_resolution_ms
|
||||
}
|
||||
ThreadInitializationPhase::SessionDependencyLoading => {
|
||||
&mut profile.session_dependency_loading_ms
|
||||
}
|
||||
ThreadInitializationPhase::SessionConstruction => &mut profile.session_construction_ms,
|
||||
ThreadInitializationPhase::McpStartup => &mut profile.mcp_startup_ms,
|
||||
ThreadInitializationPhase::SessionActivation => &mut profile.session_activation_ms,
|
||||
ThreadInitializationPhase::ThreadRegistration => &mut profile.thread_registration_ms,
|
||||
}
|
||||
}
|
||||
|
||||
fn dependency_duration_mut(
|
||||
profile: &mut ThreadInitializationProfile,
|
||||
branch: SessionDependencyBranch,
|
||||
) -> &mut u64 {
|
||||
match branch {
|
||||
SessionDependencyBranch::ThreadPersistence => &mut profile.thread_persistence_ms,
|
||||
SessionDependencyBranch::StateDbLoading => &mut profile.state_db_loading_ms,
|
||||
SessionDependencyBranch::AuthAndMcpDiscovery => &mut profile.auth_and_mcp_discovery_ms,
|
||||
SessionDependencyBranch::PluginAndSkillWarmup => &mut profile.plugin_and_skill_warmup_ms,
|
||||
}
|
||||
}
|
||||
|
||||
fn core_duration_ms(profile: &ThreadInitializationProfile) -> u64 {
|
||||
profile
|
||||
.existing_thread_lookup_ms
|
||||
.saturating_add(profile.configuration_resolution_ms)
|
||||
.saturating_add(profile.session_dependency_loading_ms)
|
||||
.saturating_add(profile.session_construction_ms)
|
||||
.saturating_add(profile.mcp_startup_ms)
|
||||
.saturating_add(profile.session_activation_ms)
|
||||
.saturating_add(profile.thread_registration_ms)
|
||||
}
|
||||
|
||||
fn duration_to_u64_ms(duration: Duration) -> u64 {
|
||||
u64::try_from(duration.as_millis()).unwrap_or(u64::MAX)
|
||||
}
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
use std::time::Duration;
|
||||
use std::time::Instant;
|
||||
|
||||
use codex_analytics::ThreadInitializationFact;
|
||||
use codex_analytics::ThreadInitializationMode;
|
||||
use codex_analytics::ThreadInitializationProfile;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
@@ -9,84 +11,108 @@ use super::ThreadInitializationPhase;
|
||||
use super::ThreadInitializationTiming;
|
||||
|
||||
#[test]
|
||||
fn thread_initialization_profile_breaks_down_core_phases() {
|
||||
let started_at = Instant::now();
|
||||
let timing = ThreadInitializationTiming::start_at(started_at);
|
||||
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.transition_at(
|
||||
started_at + Duration::from_millis(10),
|
||||
timing.start_core_at(
|
||||
core_started_at,
|
||||
ThreadInitializationMode::Cleared,
|
||||
ThreadInitializationPhase::ConfigurationResolution,
|
||||
);
|
||||
timing.transition_at(
|
||||
started_at + Duration::from_millis(30),
|
||||
core_started_at + Duration::from_millis(10),
|
||||
ThreadInitializationPhase::ExistingThreadLookup,
|
||||
);
|
||||
timing.transition_at(
|
||||
core_started_at + Duration::from_millis(15),
|
||||
ThreadInitializationPhase::ConfigurationResolution,
|
||||
);
|
||||
timing.transition_at(
|
||||
core_started_at + Duration::from_millis(30),
|
||||
ThreadInitializationPhase::SessionDependencyLoading,
|
||||
);
|
||||
timing.record_session_dependency(
|
||||
timing.record_dependency(
|
||||
SessionDependencyBranch::ThreadPersistence,
|
||||
Duration::from_millis(12),
|
||||
);
|
||||
timing.record_session_dependency(
|
||||
timing.record_dependency(
|
||||
SessionDependencyBranch::StateDbLoading,
|
||||
Duration::from_millis(8),
|
||||
);
|
||||
timing.record_session_dependency(
|
||||
timing.record_dependency(
|
||||
SessionDependencyBranch::AuthAndMcpDiscovery,
|
||||
Duration::from_millis(15),
|
||||
);
|
||||
timing.record_session_dependency(
|
||||
timing.record_dependency(
|
||||
SessionDependencyBranch::PluginAndSkillWarmup,
|
||||
Duration::from_millis(18),
|
||||
);
|
||||
timing.transition_at(
|
||||
started_at + Duration::from_millis(50),
|
||||
core_started_at + Duration::from_millis(50),
|
||||
ThreadInitializationPhase::SessionConstruction,
|
||||
);
|
||||
timing.transition_at(
|
||||
started_at + Duration::from_millis(80),
|
||||
core_started_at + Duration::from_millis(80),
|
||||
ThreadInitializationPhase::McpStartup,
|
||||
);
|
||||
timing.transition_at(
|
||||
started_at + Duration::from_millis(120),
|
||||
core_started_at + Duration::from_millis(120),
|
||||
ThreadInitializationPhase::SessionActivation,
|
||||
);
|
||||
timing.transition_at(
|
||||
started_at + Duration::from_millis(170),
|
||||
core_started_at + Duration::from_millis(170),
|
||||
ThreadInitializationPhase::ThreadRegistration,
|
||||
);
|
||||
|
||||
timing.complete_core_at(core_started_at + Duration::from_millis(230));
|
||||
assert_eq!(
|
||||
timing.complete_at(started_at + Duration::from_millis(230)),
|
||||
ThreadInitializationProfile {
|
||||
duration_ms: 230,
|
||||
app_server_duration_ms: 0,
|
||||
core_duration_ms: 230,
|
||||
existing_thread_lookup_ms: 10,
|
||||
configuration_resolution_ms: 20,
|
||||
session_dependency_loading_ms: 20,
|
||||
session_construction_ms: 30,
|
||||
mcp_startup_ms: 40,
|
||||
session_activation_ms: 50,
|
||||
thread_registration_ms: 60,
|
||||
thread_persistence_ms: 12,
|
||||
state_db_loading_ms: 8,
|
||||
auth_and_mcp_discovery_ms: 15,
|
||||
plugin_and_skill_warmup_ms: 18,
|
||||
}
|
||||
timing.complete_request_at(request_started_at + Duration::from_millis(275)),
|
||||
Some(ThreadInitializationFact {
|
||||
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,
|
||||
session_dependency_loading_ms: 20,
|
||||
session_construction_ms: 30,
|
||||
mcp_startup_ms: 40,
|
||||
session_activation_ms: 50,
|
||||
thread_registration_ms: 60,
|
||||
thread_persistence_ms: 12,
|
||||
state_db_loading_ms: 8,
|
||||
auth_and_mcp_discovery_ms: 15,
|
||||
plugin_and_skill_warmup_ms: 18,
|
||||
},
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn loaded_resume_records_only_existing_thread_lookup() {
|
||||
let started_at = Instant::now();
|
||||
let timing = ThreadInitializationTiming::start_at(started_at);
|
||||
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(
|
||||
core_started_at,
|
||||
ThreadInitializationMode::Resumed,
|
||||
ThreadInitializationPhase::ExistingThreadLookup,
|
||||
);
|
||||
timing.complete_core_at(core_started_at + Duration::from_millis(17));
|
||||
|
||||
assert_eq!(
|
||||
timing.complete_at(started_at + Duration::from_millis(17)),
|
||||
ThreadInitializationProfile {
|
||||
duration_ms: 17,
|
||||
core_duration_ms: 17,
|
||||
existing_thread_lookup_ms: 17,
|
||||
..Default::default()
|
||||
}
|
||||
timing.complete_request_at(request_started_at + Duration::from_millis(25)),
|
||||
Some(ThreadInitializationFact {
|
||||
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()
|
||||
},
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
use crate::SkillsManager;
|
||||
use crate::ThreadInitializationProfile;
|
||||
use crate::agent::AgentControl;
|
||||
use crate::attestation::AttestationProvider;
|
||||
use crate::codex_thread::CodexThread;
|
||||
@@ -20,6 +19,7 @@ use crate::tasks::interrupted_turn_history_marker;
|
||||
use crate::thread_initialization_timing::ThreadInitializationPhase;
|
||||
use crate::thread_initialization_timing::ThreadInitializationTiming;
|
||||
use codex_analytics::AnalyticsEventsClient;
|
||||
use codex_analytics::ThreadInitializationMode;
|
||||
use codex_app_server_protocol::ThreadHistoryBuilder;
|
||||
use codex_app_server_protocol::TurnStatus;
|
||||
use codex_core_plugins::PluginsManager;
|
||||
@@ -115,7 +115,6 @@ pub struct NewThread {
|
||||
pub thread_id: ThreadId,
|
||||
pub thread: Arc<CodexThread>,
|
||||
pub session_configured: SessionConfiguredEvent,
|
||||
pub thread_initialization_profile: Option<ThreadInitializationProfile>,
|
||||
}
|
||||
|
||||
// TODO(ccunningham): Add an explicit non-interrupting live-turn snapshot once
|
||||
@@ -588,19 +587,21 @@ impl ThreadManager {
|
||||
&self,
|
||||
options: StartThreadOptions,
|
||||
) -> CodexResult<NewThread> {
|
||||
self.start_thread_with_options_and_fork_source(
|
||||
options,
|
||||
/*forked_from_thread_id*/ None,
|
||||
ThreadInitializationTiming::start_configuration_resolution(),
|
||||
)
|
||||
.await
|
||||
let initialization_mode = match &options.initial_history {
|
||||
InitialHistory::Cleared => ThreadInitializationMode::Cleared,
|
||||
InitialHistory::Forked(_) => ThreadInitializationMode::Forked,
|
||||
InitialHistory::New => ThreadInitializationMode::New,
|
||||
InitialHistory::Resumed(_) => ThreadInitializationMode::Resumed,
|
||||
};
|
||||
ThreadInitializationTiming::start_configuration_resolution(initialization_mode);
|
||||
self.start_thread_with_options_and_fork_source(options, /*forked_from_thread_id*/ None)
|
||||
.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
|
||||
@@ -624,7 +625,6 @@ impl ThreadManager {
|
||||
options.parent_trace,
|
||||
options.environments,
|
||||
/*user_shell_override*/ None,
|
||||
thread_initialization_timing,
|
||||
))
|
||||
.await
|
||||
}
|
||||
@@ -636,8 +636,6 @@ impl ThreadManager {
|
||||
forked_from_thread_id: ThreadId,
|
||||
mut options: StartThreadOptions,
|
||||
) -> CodexResult<NewThread> {
|
||||
let thread_initialization_timing =
|
||||
ThreadInitializationTiming::start_configuration_resolution();
|
||||
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;
|
||||
@@ -664,12 +662,8 @@ impl ThreadManager {
|
||||
inherited_multi_agent_version,
|
||||
),
|
||||
);
|
||||
self.start_thread_with_options_and_fork_source(
|
||||
options,
|
||||
Some(forked_from_thread_id),
|
||||
thread_initialization_timing,
|
||||
)
|
||||
.await
|
||||
self.start_thread_with_options_and_fork_source(options, Some(forked_from_thread_id))
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn resume_thread_from_rollout(
|
||||
@@ -679,15 +673,13 @@ impl ThreadManager {
|
||||
auth_manager: Arc<AuthManager>,
|
||||
parent_trace: Option<W3cTraceContext>,
|
||||
) -> CodexResult<NewThread> {
|
||||
let thread_initialization_timing =
|
||||
ThreadInitializationTiming::start_configuration_resolution();
|
||||
ThreadInitializationTiming::start_existing_thread_lookup();
|
||||
let initial_history = self.initial_history_from_rollout_path(rollout_path).await?;
|
||||
Box::pin(self.resume_thread_with_history_with_timing(
|
||||
Box::pin(self.resume_thread_with_history(
|
||||
config,
|
||||
initial_history,
|
||||
auth_manager,
|
||||
parent_trace,
|
||||
thread_initialization_timing,
|
||||
))
|
||||
.await
|
||||
}
|
||||
@@ -699,26 +691,7 @@ impl ThreadManager {
|
||||
auth_manager: Arc<AuthManager>,
|
||||
parent_trace: Option<W3cTraceContext>,
|
||||
) -> CodexResult<NewThread> {
|
||||
Box::pin(self.resume_thread_with_history_with_timing(
|
||||
config,
|
||||
initial_history,
|
||||
auth_manager,
|
||||
parent_trace,
|
||||
ThreadInitializationTiming::start_configuration_resolution(),
|
||||
))
|
||||
.await
|
||||
}
|
||||
|
||||
async fn resume_thread_with_history_with_timing(
|
||||
&self,
|
||||
config: Config,
|
||||
initial_history: InitialHistory,
|
||||
auth_manager: Arc<AuthManager>,
|
||||
parent_trace: Option<W3cTraceContext>,
|
||||
thread_initialization_timing: ThreadInitializationTiming,
|
||||
) -> CodexResult<NewThread> {
|
||||
thread_initialization_timing
|
||||
.transition_to(ThreadInitializationPhase::ConfigurationResolution);
|
||||
ThreadInitializationTiming::start_existing_thread_lookup();
|
||||
let environments = default_thread_environment_selections(
|
||||
self.state.environment_manager.as_ref(),
|
||||
&config.cwd,
|
||||
@@ -742,7 +715,6 @@ impl ThreadManager {
|
||||
parent_trace,
|
||||
environments,
|
||||
/*user_shell_override*/ None,
|
||||
thread_initialization_timing,
|
||||
))
|
||||
.await
|
||||
}
|
||||
@@ -752,8 +724,6 @@ impl ThreadManager {
|
||||
config: Config,
|
||||
user_shell_override: crate::shell::Shell,
|
||||
) -> CodexResult<NewThread> {
|
||||
let thread_initialization_timing =
|
||||
ThreadInitializationTiming::start_configuration_resolution();
|
||||
let environments = default_thread_environment_selections(
|
||||
self.state.environment_manager.as_ref(),
|
||||
&config.cwd,
|
||||
@@ -771,7 +741,6 @@ impl ThreadManager {
|
||||
/*parent_trace*/ None,
|
||||
environments,
|
||||
/*user_shell_override*/ Some(user_shell_override),
|
||||
thread_initialization_timing,
|
||||
))
|
||||
.await
|
||||
}
|
||||
@@ -783,8 +752,6 @@ impl ThreadManager {
|
||||
auth_manager: Arc<AuthManager>,
|
||||
user_shell_override: crate::shell::Shell,
|
||||
) -> CodexResult<NewThread> {
|
||||
let thread_initialization_timing =
|
||||
ThreadInitializationTiming::start_configuration_resolution();
|
||||
let initial_history = self.initial_history_from_rollout_path(rollout_path).await?;
|
||||
let environments = default_thread_environment_selections(
|
||||
self.state.environment_manager.as_ref(),
|
||||
@@ -809,7 +776,6 @@ impl ThreadManager {
|
||||
/*parent_trace*/ None,
|
||||
environments,
|
||||
/*user_shell_override*/ Some(user_shell_override),
|
||||
thread_initialization_timing,
|
||||
))
|
||||
.await
|
||||
}
|
||||
@@ -887,19 +853,13 @@ impl ThreadManager {
|
||||
where
|
||||
S: Into<ForkSnapshot>,
|
||||
{
|
||||
let thread_initialization_timing =
|
||||
ThreadInitializationTiming::start_configuration_resolution();
|
||||
ThreadInitializationTiming::start_configuration_resolution(
|
||||
ThreadInitializationMode::Forked,
|
||||
);
|
||||
let snapshot = snapshot.into();
|
||||
let history = self.initial_history_from_rollout_path(path).await?;
|
||||
self.fork_thread_with_initial_history(
|
||||
snapshot,
|
||||
config,
|
||||
history,
|
||||
thread_source,
|
||||
parent_trace,
|
||||
thread_initialization_timing,
|
||||
)
|
||||
.await
|
||||
self.fork_thread_from_history(snapshot, config, history, thread_source, parent_trace)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn initial_history_from_rollout_path(
|
||||
@@ -932,13 +892,15 @@ impl ThreadManager {
|
||||
where
|
||||
S: Into<ForkSnapshot>,
|
||||
{
|
||||
ThreadInitializationTiming::start_configuration_resolution(
|
||||
ThreadInitializationMode::Forked,
|
||||
);
|
||||
self.fork_thread_with_initial_history(
|
||||
snapshot.into(),
|
||||
config,
|
||||
history,
|
||||
thread_source,
|
||||
parent_trace,
|
||||
ThreadInitializationTiming::start_configuration_resolution(),
|
||||
)
|
||||
.await
|
||||
}
|
||||
@@ -950,7 +912,6 @@ 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.
|
||||
@@ -989,7 +950,6 @@ impl ThreadManager {
|
||||
parent_trace,
|
||||
environments,
|
||||
/*user_shell_override*/ None,
|
||||
thread_initialization_timing,
|
||||
))
|
||||
.await
|
||||
}
|
||||
@@ -1176,8 +1136,6 @@ impl ThreadManagerState {
|
||||
inherited_exec_policy: Option<Arc<crate::exec_policy::ExecPolicyManager>>,
|
||||
environments: Option<Vec<TurnEnvironmentSelection>>,
|
||||
) -> CodexResult<NewThread> {
|
||||
let thread_initialization_timing =
|
||||
ThreadInitializationTiming::start_configuration_resolution();
|
||||
let environments = environments.unwrap_or_else(|| {
|
||||
default_thread_environment_selections(self.environment_manager.as_ref(), &config.cwd)
|
||||
});
|
||||
@@ -1197,7 +1155,6 @@ impl ThreadManagerState {
|
||||
/*parent_trace*/ None,
|
||||
environments,
|
||||
/*user_shell_override*/ None,
|
||||
thread_initialization_timing,
|
||||
))
|
||||
.await
|
||||
}
|
||||
@@ -1206,8 +1163,6 @@ impl ThreadManagerState {
|
||||
&self,
|
||||
options: ResumeThreadWithHistoryOptions,
|
||||
) -> CodexResult<NewThread> {
|
||||
let thread_initialization_timing =
|
||||
ThreadInitializationTiming::start_configuration_resolution();
|
||||
let ResumeThreadWithHistoryOptions {
|
||||
config,
|
||||
initial_history,
|
||||
@@ -1236,7 +1191,6 @@ impl ThreadManagerState {
|
||||
/*parent_trace*/ None,
|
||||
environments,
|
||||
/*user_shell_override*/ None,
|
||||
thread_initialization_timing,
|
||||
))
|
||||
.await
|
||||
}
|
||||
@@ -1255,8 +1209,6 @@ impl ThreadManagerState {
|
||||
inherited_exec_policy: Option<Arc<crate::exec_policy::ExecPolicyManager>>,
|
||||
environments: Option<Vec<TurnEnvironmentSelection>>,
|
||||
) -> CodexResult<NewThread> {
|
||||
let thread_initialization_timing =
|
||||
ThreadInitializationTiming::start_configuration_resolution();
|
||||
let environments = environments.unwrap_or_else(|| {
|
||||
default_thread_environment_selections(self.environment_manager.as_ref(), &config.cwd)
|
||||
});
|
||||
@@ -1276,7 +1228,6 @@ impl ThreadManagerState {
|
||||
/*parent_trace*/ None,
|
||||
environments,
|
||||
/*user_shell_override*/ None,
|
||||
thread_initialization_timing,
|
||||
))
|
||||
.await
|
||||
}
|
||||
@@ -1297,7 +1248,6 @@ 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,
|
||||
@@ -1315,7 +1265,6 @@ impl ThreadManagerState {
|
||||
parent_trace,
|
||||
environments,
|
||||
user_shell_override,
|
||||
thread_initialization_timing,
|
||||
))
|
||||
.await
|
||||
}
|
||||
@@ -1338,12 +1287,9 @@ impl ThreadManagerState {
|
||||
parent_trace: Option<W3cTraceContext>,
|
||||
environments: Vec<TurnEnvironmentSelection>,
|
||||
user_shell_override: Option<crate::shell::Shell>,
|
||||
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
|
||||
.transition_to(ThreadInitializationPhase::ExistingThreadLookup);
|
||||
let mut threads = self.threads.write().await;
|
||||
if let Some(thread) = threads.get(&resumed.conversation_id).cloned() {
|
||||
if thread.is_running() {
|
||||
@@ -1355,20 +1301,20 @@ impl ThreadManagerState {
|
||||
resumed.conversation_id
|
||||
)));
|
||||
}
|
||||
return Ok(NewThread {
|
||||
let new_thread = NewThread {
|
||||
thread_id: resumed.conversation_id,
|
||||
session_configured: thread.session_configured(),
|
||||
thread,
|
||||
thread_initialization_profile: Some(
|
||||
thread_initialization_timing.complete_existing_thread_lookup(),
|
||||
),
|
||||
});
|
||||
};
|
||||
ThreadInitializationTiming::complete_core();
|
||||
return Ok(new_thread);
|
||||
}
|
||||
threads.remove(&resumed.conversation_id);
|
||||
}
|
||||
}
|
||||
thread_initialization_timing
|
||||
.transition_to(ThreadInitializationPhase::ConfigurationResolution);
|
||||
ThreadInitializationTiming::transition_to(
|
||||
ThreadInitializationPhase::ConfigurationResolution,
|
||||
);
|
||||
let environment_selections =
|
||||
resolve_environment_selections(self.environment_manager.as_ref(), &environments)?;
|
||||
let parent_rollout_thread_trace = self
|
||||
@@ -1413,16 +1359,15 @@ 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: thread_initialization_timing.clone(),
|
||||
}))
|
||||
.await?;
|
||||
let mut new_thread = self
|
||||
let new_thread = self
|
||||
.finalize_thread_spawn(codex, thread_id, tracked_session_source)
|
||||
.await?;
|
||||
if is_resumed_thread {
|
||||
new_thread.thread.emit_thread_resume_lifecycle().await;
|
||||
}
|
||||
new_thread.thread_initialization_profile = Some(thread_initialization_timing.complete());
|
||||
ThreadInitializationTiming::complete_core();
|
||||
Ok(new_thread)
|
||||
}
|
||||
|
||||
@@ -1457,7 +1402,6 @@ impl ThreadManagerState {
|
||||
thread_id,
|
||||
thread,
|
||||
session_configured,
|
||||
thread_initialization_profile: None,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -66,7 +66,6 @@ pub async fn run_codex_tool_session(
|
||||
thread_id,
|
||||
thread,
|
||||
session_configured,
|
||||
..
|
||||
} = match thread_manager.start_thread(config.clone()).await {
|
||||
Ok(res) => res,
|
||||
Err(e) => {
|
||||
|
||||
Reference in New Issue
Block a user