Return startup timing with MCP connection attempts (#63647)

## What changed

Have the MCP connection pool return an optional startup measurement
alongside the connection result. For a new connection, measure through
lease registration when required, including when registration fails.
If a chat falls back to opening its own connection, start the timer at
the fallback. Joining an existing connection produces no startup
measurement.

## Testing

Pool tests cover timing a lease-open timeout on a new connection,
omitting timing for the same timeout on a reused connection, and
recording timing when a chat falls back to its own connection.

GitOrigin-RevId: 364963ca2f4e7bd8338c8acc9a7869e3a7a6e9c4
This commit is contained in:
jif
2026-11-24 14:18:12 +00:00
committed by copyberry
parent 75df5098a6
commit 264f7d60f5
4 changed files with 149 additions and 99 deletions
+84 -72
View File
@@ -32,6 +32,7 @@ use crate::client_tool_catalog::ClientToolCatalog;
use crate::client_tool_catalog::ToolCatalogSnapshot;
use crate::rmcp_client::ManagedClient;
use crate::rmcp_client::ManagedClientFuture;
use crate::rmcp_client::StartupMeasurement;
use crate::rmcp_client::StartupOutcomeError;
use crate::rmcp_client::list_tools_for_client_uncached;
use crate::server::McpServerConnectionIdentity;
@@ -128,7 +129,7 @@ struct LeaseOwners;
#[derive(Clone, Copy, PartialEq, Eq)]
enum AcquisitionRole {
Creator,
Creator(Instant),
Joiner,
}
@@ -148,7 +149,7 @@ impl Entry {
cache_context: Option<&McpToolCatalogCacheContext>,
) -> Result<Arc<ClientToolCatalog>, StartupOutcomeError> {
// Listing must not update another chat's catalog or wait for its calls.
let listed = if role == AcquisitionRole::Creator {
let listed = if matches!(role, AcquisitionRole::Creator(_)) {
client.tool_catalog.read(|snapshot| snapshot).await
} else {
let fetch_ticket = cache_context.map(|context| (context, context.begin_fetch()));
@@ -204,8 +205,6 @@ pub(crate) struct ConnectionLease {
pub(crate) struct ConnectionSlot {
state: Mutex<SlotState>,
shutdown_tasks: OnceLock<TaskTracker>,
/// Set only if this acquisition started the selected connection.
pub(crate) started_at: OnceLock<Instant>,
}
#[derive(Default)]
@@ -257,6 +256,12 @@ impl ConnectionSharing {
}
}
pub(crate) struct ConnectionAttempt {
pub(crate) result: Result<ManagedClient, StartupOutcomeError>,
/// Only new connections are timed, through lease registration even if it fails.
pub(crate) measurement: Option<StartupMeasurement>,
}
impl McpConnectionPool {
pub(crate) async fn connect(
&self,
@@ -266,71 +271,82 @@ impl McpConnectionPool {
tool_catalog_cache_context: Option<McpToolCatalogCacheContext>,
cancellation: CancellationToken,
start: impl Fn(CancellationToken, Option<CancellationToken>) -> ManagedClientFuture + Sync,
) -> Result<ManagedClient, StartupOutcomeError> {
let (lease, role) = self
.acquire(key, &slot, Arc::clone(&capabilities), &cancellation, &start)
.or_cancel(&cancellation)
.await
.unwrap_or(Err(StartupOutcomeError::Cancelled))?;
let outcome = tokio::select! {
outcome = lease.entry.client.clone() => Some(outcome),
() = lease.entry.sharing_declined.cancelled(), if role == AcquisitionRole::Joiner => None,
() = cancellation.cancelled() => return Err(StartupOutcomeError::Cancelled),
};
match outcome {
Some(Ok(mut client))
if role == AcquisitionRole::Creator
|| matches!(client.connection_sharing, ConnectionSharing::Negotiated) =>
{
let shared_capabilities = lease
.entry
.capabilities
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.clone();
let server_tracks_leases = shared_capabilities
.as_ref()
.and_then(|caps| caps.get("extensions"))
.and_then(|caps| caps.get(LEASE_CAPABILITY))
.is_some();
*capabilities
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner) = shared_capabilities;
client.connection_sharing =
if matches!(client.connection_sharing, ConnectionSharing::Negotiated) {
client.client.enable_request_cancellation();
client.tool_catalog = lease
.entry
.tool_catalog_for_chat(
&client,
role,
tool_catalog_cache_context.as_ref(),
)
) -> ConnectionAttempt {
let mut started_at = None;
let result = async {
let (lease, role) = self
.acquire(key, &slot, Arc::clone(&capabilities), &cancellation, &start)
.or_cancel(&cancellation)
.await
.unwrap_or(Err(StartupOutcomeError::Cancelled))?;
let outcome = tokio::select! {
outcome = lease.entry.client.clone() => Some(outcome),
() = lease.entry.sharing_declined.cancelled(), if role == AcquisitionRole::Joiner => None,
() = cancellation.cancelled() => return Err(StartupOutcomeError::Cancelled),
};
let mut client = match (role, outcome) {
(AcquisitionRole::Creator(start), Some(result)) => {
started_at = Some(start);
result?
}
(AcquisitionRole::Joiner, Some(Ok(client)))
if matches!(client.connection_sharing, ConnectionSharing::Negotiated) =>
{
client
}
_ => {
// Older or failed servers leave other chats to initialize privately
// with their own elicitation authority.
drop(lease);
started_at = Some(Instant::now());
return start(cancellation, /*sharing_declined*/ None).await;
}
};
let shared_capabilities = lease
.entry
.capabilities
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.clone();
let server_tracks_leases = shared_capabilities
.as_ref()
.and_then(|caps| caps.get("extensions"))
.and_then(|caps| caps.get(LEASE_CAPABILITY))
.is_some();
*capabilities
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner) = shared_capabilities;
client.connection_sharing =
if matches!(client.connection_sharing, ConnectionSharing::Negotiated) {
client.client.enable_request_cancellation();
client.tool_catalog = lease
.entry
.tool_catalog_for_chat(
&client,
role,
tool_catalog_cache_context.as_ref(),
)
.or_cancel(&cancellation)
.await
.unwrap_or(Err(StartupOutcomeError::Cancelled))?;
if server_tracks_leases {
lease
.open_on_server(Arc::clone(&client.client))
.or_cancel(&cancellation)
.await
.unwrap_or(Err(StartupOutcomeError::Cancelled))?;
if server_tracks_leases {
lease
.open_on_server(Arc::clone(&client.client))
.or_cancel(&cancellation)
.await
.unwrap_or(Err(StartupOutcomeError::Cancelled))?;
}
ConnectionSharing::Shared(lease)
} else {
lease.entry.remove_from_pool();
ConnectionSharing::Owned(lease)
};
Ok(client)
}
Some(Err(error)) if role == AcquisitionRole::Creator => Err(error),
_ => {
// Older or failed servers leave other chats to initialize privately
// with their own elicitation authority.
drop(lease);
let _ = slot.started_at.set(Instant::now());
start(cancellation, /*sharing_declined*/ None).await
}
}
ConnectionSharing::Shared(lease)
} else {
lease.entry.remove_from_pool();
ConnectionSharing::Owned(lease)
};
Ok(client)
}
.await;
ConnectionAttempt {
measurement: started_at.map(|start| StartupMeasurement::new(start, &result)),
result,
}
}
@@ -343,7 +359,6 @@ impl McpConnectionPool {
start: impl Fn(CancellationToken, Option<CancellationToken>) -> ManagedClientFuture,
) -> Result<(Arc<ConnectionLease>, AcquisitionRole), StartupOutcomeError> {
loop {
let mut started_at = None;
let (lease, role) = {
let mut state = slot
.state
@@ -379,7 +394,7 @@ impl McpConnectionPool {
} else {
let startup_cancellation = CancellationToken::new();
let sharing_declined = CancellationToken::new();
started_at = Some(Instant::now());
let started_at = Instant::now();
let client =
start(startup_cancellation.clone(), Some(sharing_declined.clone()));
// Startup belongs to the connection, including if its first chat is cancelled.
@@ -397,7 +412,7 @@ impl McpConnectionPool {
pool: Arc::downgrade(&self.entries),
});
entries.push(Arc::downgrade(&entry));
(entry, owner, AcquisitionRole::Creator)
(entry, owner, AcquisitionRole::Creator(started_at))
};
let lease = Arc::new(ConnectionLease {
entry,
@@ -416,9 +431,6 @@ impl McpConnectionPool {
lease.release();
continue;
}
if let Some(started_at) = started_at {
let _ = slot.started_at.set(started_at);
}
return Ok((lease, role));
}
}
@@ -11,6 +11,7 @@ use crate::runtime::McpRuntimeContext;
use codex_config::McpServerConfig;
use codex_exec_server::EnvironmentManager;
use codex_login::CodexAuth;
use codex_protocol::protocol::McpStartupStatus;
use codex_rmcp_client::Elicitation;
use codex_rmcp_client::InProcessTransportFactory;
use codex_rmcp_client::RmcpClient;
@@ -312,7 +313,7 @@ impl LeasePeer {
}
}
fn attach(&self) -> tokio::task::JoinHandle<Result<ManagedClient, StartupOutcomeError>> {
fn attach(&self) -> tokio::task::JoinHandle<ConnectionAttempt> {
let pool = self.pool.clone();
let key = self.key.clone();
let transport = self.transport.clone();
@@ -354,7 +355,7 @@ impl LeasePeer {
let open = self.next("codex/connection/open").await;
open.reply(json!({}));
(
attach.await.unwrap().unwrap(),
attach.await.unwrap().result.unwrap(),
open.message["params"]["leaseId"].clone(),
)
}
@@ -415,6 +416,24 @@ async fn dropping_lease_outside_runtime_releases_it() {
release.reply(json!({}));
}
#[tokio::test(start_paused = true)]
async fn failed_lease_open_on_a_new_connection_is_timed() {
let mut peer = LeasePeer::new();
let attach = peer.attach();
let _open = peer.next("codex/connection/open").await;
tokio::time::advance(LEASE_REQUEST_TIMEOUT).await;
let attempt = attach.await.unwrap();
let Err(StartupOutcomeError::Failed { error, .. }) = attempt.result else {
panic!("expected lease open to fail");
};
let status = McpStartupStatus::Failed {
error,
reason: None,
};
let measurement = attempt.measurement.unwrap();
assert!(measurement.duration_ms_for(&status).is_some());
}
#[tokio::test(start_paused = true)]
async fn timed_out_open_is_released_after_the_server_acknowledges_it() {
let mut peer = LeasePeer::new();
@@ -422,7 +441,9 @@ async fn timed_out_open_is_released_after_the_server_acknowledges_it() {
let attach = peer.attach();
let open = peer.next("codex/connection/open").await;
tokio::time::advance(LEASE_REQUEST_TIMEOUT).await;
assert!(attach.await.unwrap().is_err());
let attempt = attach.await.unwrap();
assert!(attempt.result.is_err());
assert!(attempt.measurement.is_none());
assert!(
tokio::time::timeout(Duration::from_secs(1), peer.frames.recv())
.await
@@ -474,9 +495,12 @@ async fn shared_startup_survives_first_chat_cancellation_and_rejects_released_bi
assert!(futures::poll!(&mut second).is_pending());
started.notified().await;
first_cancel.cancel();
assert!(matches!(first.await, Err(StartupOutcomeError::Cancelled)));
assert!(matches!(
first.await.result,
Err(StartupOutcomeError::Cancelled)
));
release.notify_one();
let client = second.await.unwrap();
let client = second.await.result.unwrap();
assert_eq!(starts.load(Ordering::SeqCst), 1);
assert!(!client.client.is_closed().await);
@@ -490,6 +514,7 @@ async fn shared_startup_survives_first_chat_cancellation_and_rejects_released_bi
&launch,
)
.await
.result
.unwrap();
let mut config = crate::mcp::tests::test_mcp_config(std::env::temp_dir());
config.server_permissions.insert(
@@ -667,6 +692,7 @@ async fn callback_during_startup_releases_waiting_chats_without_sharing_authorit
})
.await
.expect("the joining chat must start before the first finishes")
.result
.unwrap();
first
.call_tool(
@@ -685,7 +711,12 @@ async fn callback_during_startup_releases_waiting_chats_without_sharing_authorit
assert!(first.client.is_closed().await);
release_second.notify_one();
let second = second.await.unwrap();
let attempt = second.await;
assert!(
attempt.measurement.is_some(),
"private startup should be timed"
);
let second = attempt.result.unwrap();
assert_eq!(starts.load(Ordering::SeqCst), 2);
assert_eq!(*callbacks.lock().unwrap(), ["first", "second"]);
second
@@ -738,6 +769,7 @@ async fn new_chat_relists_tools_without_invalidating_or_waiting_for_existing_cal
&launch,
)
.await
.result
.unwrap();
let before = first.tool_catalog.read(|snapshot| snapshot).await;
let release_call = Notify::new();
@@ -761,6 +793,7 @@ async fn new_chat_relists_tools_without_invalidating_or_waiting_for_existing_cal
)
.await
.expect("new chats must not wait for existing calls")
.result
.unwrap();
assert_eq!(starts.load(Ordering::SeqCst), 1);
assert_eq!(
@@ -803,7 +836,7 @@ async fn new_chat_relists_tools_without_invalidating_or_waiting_for_existing_cal
&launch,
)
.await;
assert!(failed.is_err());
assert!(failed.result.is_err());
let _cancelled =
tokio::time::timeout(Duration::from_secs(1), server.cancelled_listings.acquire())
.await
+21 -19
View File
@@ -283,7 +283,10 @@ pub(crate) struct StartupMeasurement {
}
impl StartupMeasurement {
fn new(started_at: Instant, outcome: &Result<ManagedClient, StartupOutcomeError>) -> Self {
pub(crate) fn new(
started_at: Instant,
outcome: &Result<ManagedClient, StartupOutcomeError>,
) -> Self {
Self {
duration_ms: elapsed_ms(started_at),
succeeded: outcome.is_ok(),
@@ -651,9 +654,9 @@ impl AsyncManagedClient {
let startup_complete = Arc::clone(&startup_complete);
let server_capabilities = Arc::clone(&server_capabilities);
let client = async move {
let outcome = pool
let attempt = pool
.connect(
Arc::clone(&slot),
slot,
key,
server_capabilities,
pool_catalog,
@@ -667,22 +670,21 @@ impl AsyncManagedClient {
.shared()
},
)
.await
.map(|mut client| {
if matches!(client.connection_sharing, ConnectionSharing::Shared(_)) {
client.shared_elicitation =
Some(Arc::new(startup.elicitation_requests.make_sender(
startup.server_key.clone(),
startup.server_key.name().to_owned(),
startup.tx_event.clone(),
&startup.client_mcp_extensions,
)));
}
client
});
// Include lease registration, but don't count joining an existing connection.
if let Some(&started_at) = slot.started_at.get() {
let _ = initial_measurement.set(StartupMeasurement::new(started_at, &outcome));
.await;
let outcome = attempt.result.map(|mut client| {
if matches!(client.connection_sharing, ConnectionSharing::Shared(_)) {
client.shared_elicitation =
Some(Arc::new(startup.elicitation_requests.make_sender(
startup.server_key.clone(),
startup.server_key.name().to_owned(),
startup.tx_event.clone(),
&startup.client_mcp_extensions,
)));
}
client
});
if let Some(measurement) = attempt.measurement {
let _ = initial_measurement.set(measurement);
}
startup_complete.store(true, Ordering::Release);
outcome
@@ -39,6 +39,7 @@ async fn forced_refresh_replaces_pending_connection_without_interrupting_other_c
&*launch,
)
.await
.result
}
.boxed()
.shared()
@@ -120,9 +121,10 @@ async fn forced_refresh_replaces_pending_connection_without_interrupting_other_c
)
.await
.expect("forced refresh must not wait for the old startup")
.result
.unwrap();
release.notify_one();
let other = other.await.unwrap();
let other = other.await.result.unwrap();
other
.call_tool(
"test".to_string(),
@@ -145,6 +147,7 @@ async fn forced_refresh_replaces_pending_connection_without_interrupting_other_c
&*launch,
)
.await
.result
.unwrap();
assert_eq!(starts.load(Ordering::SeqCst), 2);