mirror of
https://github.com/openai/codex.git
synced 2026-11-22 23:00:42 +00:00
Keep discovered Apps tools available during startup recovery (#53672)
## Why A transient Apps MCP startup failure can remove cached tools that the model has already discovered, preventing a later Code Mode invocation from using them. ## What changed Keep cached Apps tools in the model's tool catalog while startup recovery runs. Let invocation readiness start or join a shared retry before acquiring the tool execution lock, while tool discovery remains nonblocking. Keep recovery running if a waiting invocation is cancelled. ## Testing Extend connection-manager tests to cover cached tool bindings and shared recovery. Add a Code Mode regression test that discovers a cached Calendar tool, invokes it after startup fails, and verifies that it succeeds after recovery while unrelated tools remain able to execute. GitOrigin-RevId: e888501a1050884a50a473e71b893cf6672fe256
This commit is contained in:
@@ -138,6 +138,21 @@ impl McpServerConnection {
|
||||
self.client.client().await
|
||||
}
|
||||
|
||||
async fn client_for_call(&self) -> Result<ManagedClient, StartupOutcomeError> {
|
||||
let result = self.client().await;
|
||||
if matches!(result, Err(StartupOutcomeError::Failed { .. }))
|
||||
&& !self.client.cancel_token.is_cancelled()
|
||||
&& let Some(reconnect) = &self.client.startup_reconnect
|
||||
{
|
||||
if let Some(attempt) = reconnect.reconnect_in_background() {
|
||||
return attempt.await;
|
||||
}
|
||||
// Recovery may have finished between reading the client and joining it.
|
||||
return self.client().await;
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
async fn shutdown(&self) {
|
||||
self.client.shutdown().await;
|
||||
}
|
||||
@@ -924,7 +939,8 @@ impl McpConnectionSet {
|
||||
let Some(view) = self.servers.get(server_name) else {
|
||||
return false;
|
||||
};
|
||||
view.connection.client.ready_transport().is_some() || view.connection.client().await.is_ok()
|
||||
view.connection.client.ready_transport().is_some()
|
||||
|| view.connection.client_for_call().await.is_ok()
|
||||
}
|
||||
|
||||
/// Stop all MCP clients owned by this manager and terminate stdio server processes.
|
||||
|
||||
@@ -364,7 +364,12 @@ impl McpConnectionSet {
|
||||
.client
|
||||
.startup_complete
|
||||
.load(Ordering::Acquire);
|
||||
let accepts_cached_catalog = view.startup_readiness == McpStartupReadiness::Catalog;
|
||||
// A transient Apps startup failure must not remove functions already discovered
|
||||
// by the model. Keep retrying even when the cached catalog supplies this step.
|
||||
view.connection.client.reconnect_failed_startup().await;
|
||||
let accepts_cached_catalog = view.startup_readiness == McpStartupReadiness::Catalog
|
||||
|| (view.connection.client.is_codex_apps_mcp_server
|
||||
&& !view.connection.client.cancel_token.is_cancelled());
|
||||
let cached_tools = if startup_pending
|
||||
|| (accepts_cached_catalog && view.connection.client.ready_client().is_none())
|
||||
{
|
||||
@@ -383,7 +388,6 @@ impl McpConnectionSet {
|
||||
{
|
||||
return None;
|
||||
}
|
||||
view.connection.client.reconnect_failed_startup().await;
|
||||
let Ok(mut client) = view.connection.client().await else {
|
||||
trace!(server_name = %server_name, "omitting MCP server without an exact ready client");
|
||||
return None;
|
||||
@@ -544,6 +548,7 @@ impl McpConnectionSet {
|
||||
if !view.tool_filter.allows(&advertised_tool.tool.name) {
|
||||
return None;
|
||||
}
|
||||
// Recovery belongs to readiness, before the caller acquires the tool execution lock.
|
||||
let mut client = view.connection.client().await.ok()?;
|
||||
client.tool_timeout = view.tool_timeout;
|
||||
let snapshot = client.tool_catalog.read(Arc::new).await;
|
||||
|
||||
@@ -4182,13 +4182,13 @@ async fn later_tool_list_retries_after_failed_reconnect_and_keeps_cached_tools()
|
||||
.boxed()
|
||||
.shared()
|
||||
});
|
||||
let manager = create_test_manager_with_failed_apps_startup(
|
||||
let manager = Arc::new(create_test_manager_with_failed_apps_startup(
|
||||
vec![create_test_tool(
|
||||
CODEX_APPS_MCP_SERVER_NAME,
|
||||
"cached_drive_search",
|
||||
)],
|
||||
reconnect_factory,
|
||||
);
|
||||
));
|
||||
|
||||
let first_reconnect_finished = reconnect_finished.notified();
|
||||
let tools = manager.list_all_tools().await;
|
||||
@@ -4202,6 +4202,19 @@ async fn later_tool_list_retries_after_failed_reconnect_and_keeps_cached_tools()
|
||||
first_reconnect_finished.await;
|
||||
assert_eq!(attempts.load(std::sync::atomic::Ordering::SeqCst), 1);
|
||||
|
||||
let failed_binding = capture_binding(&manager).await;
|
||||
assert_eq!(failed_binding.tools(), tools);
|
||||
assert!(
|
||||
manager
|
||||
.prepare_call_for_tool(
|
||||
Arc::clone(failed_binding.config()),
|
||||
&failed_binding.tools()[0],
|
||||
)
|
||||
.await
|
||||
.is_none()
|
||||
);
|
||||
assert_eq!(attempts.load(Ordering::SeqCst), 1);
|
||||
|
||||
let tools = manager.list_all_tools().await;
|
||||
assert_eq!(
|
||||
tools
|
||||
@@ -4287,10 +4300,7 @@ async fn tool_lists_do_not_block_and_share_codex_apps_startup_reconnect() {
|
||||
.shared()
|
||||
});
|
||||
let mut manager = create_test_manager_with_failed_apps_startup(
|
||||
vec![create_test_tool(
|
||||
CODEX_APPS_MCP_SERVER_NAME,
|
||||
"cached_drive_search",
|
||||
)],
|
||||
vec![create_test_tool(CODEX_APPS_MCP_SERVER_NAME, "drive_search")],
|
||||
reconnect_factory,
|
||||
);
|
||||
manager.set_test_server_metadata(
|
||||
@@ -4320,25 +4330,32 @@ async fn tool_lists_do_not_block_and_share_codex_apps_startup_reconnect() {
|
||||
.iter()
|
||||
.map(|tool| tool.callable_name.as_str())
|
||||
.collect::<Vec<_>>(),
|
||||
vec!["cached_drive_search"]
|
||||
vec!["drive_search"]
|
||||
);
|
||||
assert_eq!(
|
||||
second_tools
|
||||
.iter()
|
||||
.map(|tool| tool.callable_name.as_str())
|
||||
.collect::<Vec<_>>(),
|
||||
vec!["cached_drive_search"]
|
||||
vec!["drive_search"]
|
||||
);
|
||||
let pending_step = tokio::time::timeout(Duration::from_millis(10), capture_binding(&manager))
|
||||
.await
|
||||
.expect("step capture should not wait for reconnect");
|
||||
assert!(
|
||||
pending_step.tools().is_empty(),
|
||||
"a model step must not advertise cached tools without an exact ready client"
|
||||
);
|
||||
assert_eq!(pending_step.tools(), first_tools);
|
||||
// Readiness joins the retry that discovery started before call preparation.
|
||||
let mut ready = Box::pin(manager.wait_for_server_startup(CODEX_APPS_MCP_SERVER_NAME));
|
||||
assert!(futures::poll!(&mut ready).is_pending());
|
||||
assert_eq!(attempts.load(Ordering::SeqCst), 1);
|
||||
|
||||
release_reconnect.notify_one();
|
||||
tokio::task::yield_now().await;
|
||||
assert!(ready.await);
|
||||
assert!(
|
||||
manager
|
||||
.prepare_call_for_tool(Arc::clone(pending_step.config()), &pending_step.tools()[0])
|
||||
.await
|
||||
.is_some()
|
||||
);
|
||||
let tools = manager.list_all_tools().await;
|
||||
assert_eq!(
|
||||
tools
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
//! initializing the server, listing raw tools, applying per-server tool filters,
|
||||
//! and exposing cached Codex Apps tools while a client is still connecting.
|
||||
//! Initialization capabilities survive tool-discovery failures and reset on a new attempt.
|
||||
//! Apps discovery stays nonblocking; invocations can join the shared startup retry.
|
||||
//! Executor-discovered environment credentials remain executor-bound across those attempts.
|
||||
//! Higher-level aggregation and resource/tool APIs live in
|
||||
//! [`crate::connection_manager`].
|
||||
@@ -162,7 +163,7 @@ pub(crate) type ManagedClientFuture =
|
||||
struct CodexAppsStartupReconnectState {
|
||||
current_client: Option<ManagedClient>,
|
||||
last_error: Option<StartupOutcomeError>,
|
||||
reconnect_in_flight: bool,
|
||||
reconnect_in_flight: Option<ManagedClientFuture>,
|
||||
consecutive_failures: u32,
|
||||
retry_not_before: Option<TokioInstant>,
|
||||
}
|
||||
@@ -211,26 +212,24 @@ impl CodexAppsStartupReconnect {
|
||||
.clone()
|
||||
}
|
||||
|
||||
fn reconnect_in_background(self: &Arc<Self>) {
|
||||
{
|
||||
let mut state = self
|
||||
.state
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
if state.current_client.is_some() || state.reconnect_in_flight {
|
||||
return;
|
||||
}
|
||||
if state
|
||||
pub(crate) fn reconnect_in_background(self: &Arc<Self>) -> Option<ManagedClientFuture> {
|
||||
let mut state = self
|
||||
.state
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
if let Some(attempt) = &state.reconnect_in_flight {
|
||||
return Some(attempt.clone());
|
||||
}
|
||||
if state.current_client.is_some()
|
||||
|| state
|
||||
.retry_not_before
|
||||
.is_some_and(|retry_not_before| TokioInstant::now() < retry_not_before)
|
||||
{
|
||||
return;
|
||||
}
|
||||
state.reconnect_in_flight = true;
|
||||
{
|
||||
return None;
|
||||
}
|
||||
|
||||
let reconnect = Arc::clone(self);
|
||||
tokio::spawn(async move {
|
||||
let attempt = async move {
|
||||
let result = (reconnect.factory)().await;
|
||||
let startup_status_context = reconnect.startup_status_context.clone();
|
||||
let recovered = {
|
||||
@@ -238,10 +237,10 @@ impl CodexAppsStartupReconnect {
|
||||
.state
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
state.reconnect_in_flight = false;
|
||||
match result {
|
||||
state.reconnect_in_flight = None;
|
||||
match &result {
|
||||
Ok(client) => {
|
||||
state.current_client = Some(client);
|
||||
state.current_client = Some(client.clone());
|
||||
state.last_error = None;
|
||||
state.consecutive_failures = 0;
|
||||
state.retry_not_before = None;
|
||||
@@ -274,7 +273,15 @@ impl CodexAppsStartupReconnect {
|
||||
})
|
||||
.await;
|
||||
}
|
||||
});
|
||||
result
|
||||
}
|
||||
.boxed()
|
||||
.shared();
|
||||
state.reconnect_in_flight = Some(attempt.clone());
|
||||
drop(state);
|
||||
// Keep recovery running if the invocation waiting for it is cancelled.
|
||||
tokio::spawn(attempt.clone());
|
||||
Some(attempt)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -569,7 +576,7 @@ impl AsyncManagedClient {
|
||||
return;
|
||||
}
|
||||
if matches!(self.client().await, Err(StartupOutcomeError::Failed { .. })) {
|
||||
startup_reconnect.reconnect_in_background();
|
||||
let _ = startup_reconnect.reconnect_in_background();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -15,7 +15,7 @@ impl AsyncManagedClient {
|
||||
.state
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
if state.reconnect_in_flight {
|
||||
if state.reconnect_in_flight.is_some() {
|
||||
return Status::Starting;
|
||||
}
|
||||
state
|
||||
|
||||
Reference in New Issue
Block a user