mirror of
https://github.com/openai/codex.git
synced 2026-12-02 00:31:03 +00:00
Trace MCP runtime refresh contention (#64800)
## Why MCP refresh traces show how long an operation waits for the refresh gate, but they lack the timing and operation labels needed to identify which refresh held it. ## What changed - Tag refresh wait and hold spans with a shared gate ID and the operation name so overlapping spans show which operation held the gate while another waited. - Carry the scheduling trace context into background MCP prewarm and add a span for the Apps catalog refresh. ## Testing - Add a test that checks the exported wait and hold spans share a gate ID and overlap while a second operation waits for the permit. - Make the worktree TUI test wait for the `Ready` run state before submitting input, since a directory change can appear while the composer is still busy. GitOrigin-RevId: be2b6d2a82e4a5b553fb3f335850865f04a181ee
This commit is contained in:
@@ -513,7 +513,7 @@ pub(super) async fn shutdown_session_runtime(sess: &Arc<Session>) {
|
||||
}
|
||||
sess.stop_mcp_prewarm_worker().await;
|
||||
{
|
||||
let _refresh = sess.mcp_refresh.acquire().await;
|
||||
let _refresh = sess.mcp_refresh.acquire("shutdown").await;
|
||||
sess.mcp_refresh.close();
|
||||
}
|
||||
sess.wait_for_apps_tool_refresh().await;
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
use super::mcp_refresh::McpRefreshPermit;
|
||||
use super::*;
|
||||
use crate::McpRefreshReason;
|
||||
use crate::environment_selection::TurnEnvironmentSnapshot;
|
||||
@@ -38,7 +39,6 @@ use codex_protocol::openai_models::GuardianScope;
|
||||
use codex_rmcp_client::Elicitation;
|
||||
use rmcp::model::ElicitationAction;
|
||||
use serde_json::Map;
|
||||
use tokio::sync::SemaphorePermit;
|
||||
|
||||
const TOOL_SUGGESTION_ACTION_INSTALL: &str = "install";
|
||||
const TOOL_SUGGESTION_ACTION_KEY: &str = "suggest_type";
|
||||
@@ -230,7 +230,7 @@ impl Session {
|
||||
self: &Arc<Self>,
|
||||
captured_executor_discovery_v2: Option<&[ExecutorCapabilityDiscoveryV2Snapshot]>,
|
||||
) {
|
||||
let Ok(_refresh) = self.mcp_refresh.acquire().await else {
|
||||
let Ok(_refresh) = self.mcp_refresh.acquire("reconcile").await else {
|
||||
error!("MCP runtime refresh semaphore closed");
|
||||
return;
|
||||
};
|
||||
@@ -348,12 +348,13 @@ impl Session {
|
||||
}
|
||||
|
||||
/// Refreshes Apps tools on the published thread runtime and returns that client's snapshot.
|
||||
#[tracing::instrument(name = "mcp.runtime.apps_catalog_refresh", skip_all)]
|
||||
pub(crate) async fn refresh_codex_apps_tools(
|
||||
self: &Arc<Self>,
|
||||
) -> anyhow::Result<codex_mcp::CodexAppsToolSnapshot> {
|
||||
let permit = self
|
||||
.mcp_refresh
|
||||
.acquire()
|
||||
.acquire("apps_catalog")
|
||||
.await
|
||||
.context("MCP runtime refresh semaphore closed")?;
|
||||
let _in_flight = self.mcp_refresh.apps_refreshes.token();
|
||||
@@ -366,7 +367,7 @@ impl Session {
|
||||
}
|
||||
let permit = self
|
||||
.mcp_refresh
|
||||
.acquire()
|
||||
.acquire("apps_catalog")
|
||||
.await
|
||||
.context("MCP runtime refresh semaphore closed")?;
|
||||
self.fetch_apps_catalog(permit)
|
||||
@@ -376,7 +377,7 @@ impl Session {
|
||||
|
||||
async fn fetch_apps_catalog(
|
||||
self: &Arc<Self>,
|
||||
permit: SemaphorePermit<'_>,
|
||||
permit: McpRefreshPermit<'_>,
|
||||
) -> anyhow::Result<Option<codex_mcp::CodexAppsToolSnapshot>> {
|
||||
self.reconcile_mcp_runtime(/*captured_executor_discovery_v2*/ None)
|
||||
.await;
|
||||
@@ -401,7 +402,7 @@ impl Session {
|
||||
) -> anyhow::Result<Vec<codex_mcp::ToolInfo>> {
|
||||
let _refresh = self
|
||||
.mcp_refresh
|
||||
.acquire()
|
||||
.acquire("apps_hard_refresh")
|
||||
.await
|
||||
.map_err(|_| anyhow::anyhow!("MCP runtime refresh semaphore closed"))?;
|
||||
// This is forced work even when there was no pending invalidation.
|
||||
@@ -523,7 +524,7 @@ impl Session {
|
||||
)
|
||||
.await;
|
||||
if !recovered_oauth_servers.is_empty()
|
||||
&& let Ok(_refresh) = self.mcp_refresh.acquire().await
|
||||
&& let Ok(_refresh) = self.mcp_refresh.acquire("oauth_recovery").await
|
||||
&& self
|
||||
.services
|
||||
.mcp_runtime
|
||||
@@ -575,7 +576,7 @@ impl Session {
|
||||
// Keep the binding and its final executor inventory projection together.
|
||||
let _refresh = self
|
||||
.mcp_refresh
|
||||
.acquire()
|
||||
.acquire("resolve_for_step")
|
||||
.await
|
||||
.map_err(|_| CodexErr::TurnAborted)?;
|
||||
self.reconcile_mcp_runtime(captured_executor_discovery_v2)
|
||||
@@ -898,7 +899,7 @@ impl Session {
|
||||
added_servers: HashMap<String, McpServerConfig>,
|
||||
elicitation_reviewer: Option<ElicitationReviewerHandle>,
|
||||
) {
|
||||
let Ok(_refresh) = self.mcp_refresh.acquire().await else {
|
||||
let Ok(_refresh) = self.mcp_refresh.acquire("skill_dependencies").await else {
|
||||
error!("MCP runtime refresh semaphore closed");
|
||||
return;
|
||||
};
|
||||
|
||||
@@ -5,6 +5,10 @@
|
||||
|
||||
use super::*;
|
||||
use crate::McpRefreshReason;
|
||||
use codex_otel::current_span_w3c_trace_context;
|
||||
use codex_otel::set_parent_from_w3c_trace_context;
|
||||
use codex_protocol::protocol::W3cTraceContext;
|
||||
use tracing::Instrument;
|
||||
|
||||
impl Session {
|
||||
pub(crate) fn reproject_mcp_on_next_turn(&self) {
|
||||
@@ -31,27 +35,27 @@ impl Session {
|
||||
|
||||
pub(super) fn start_mcp_prewarm_worker(
|
||||
self: &Arc<Self>,
|
||||
requests: async_channel::Receiver<()>,
|
||||
requests: async_channel::Receiver<Option<W3cTraceContext>>,
|
||||
mut auth_changes: tokio::sync::watch::Receiver<u64>,
|
||||
) {
|
||||
let session = Arc::downgrade(self);
|
||||
let shutdown = self.mcp_prewarm_shutdown.clone();
|
||||
let worker = self.services.runtime_handle.spawn(async move {
|
||||
loop {
|
||||
let auth_changed = tokio::select! {
|
||||
let (auth_changed, parent_trace) = tokio::select! {
|
||||
biased;
|
||||
_ = shutdown.cancelled() => break,
|
||||
request = requests.recv() => {
|
||||
if request.is_err() {
|
||||
let Ok(parent_trace) = request else {
|
||||
break;
|
||||
}
|
||||
false
|
||||
};
|
||||
(false, parent_trace)
|
||||
},
|
||||
auth_change = auth_changes.changed() => {
|
||||
if auth_change.is_err() {
|
||||
break;
|
||||
}
|
||||
true
|
||||
(true, None)
|
||||
},
|
||||
};
|
||||
let Some(session) = session.upgrade() else {
|
||||
@@ -60,10 +64,14 @@ impl Session {
|
||||
if auth_changed {
|
||||
session.mark_mcp_runtime_dirty(McpRefreshReason::AuthChangeNotification);
|
||||
}
|
||||
let span = tracing::info_span!("mcp.runtime.prewarm", auth_changed);
|
||||
if let Some(parent_trace) = parent_trace {
|
||||
set_parent_from_w3c_trace_context(&span, &parent_trace);
|
||||
}
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = shutdown.cancelled() => break,
|
||||
_ = session.refresh_mcp_if_dirty() => {},
|
||||
_ = session.refresh_mcp_if_dirty().instrument(span) => {},
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -74,7 +82,9 @@ impl Session {
|
||||
}
|
||||
|
||||
pub(super) fn schedule_mcp_prewarm(&self) {
|
||||
let _ = self.mcp_prewarm_tx.try_send(());
|
||||
let _ = self
|
||||
.mcp_prewarm_tx
|
||||
.try_send(current_span_w3c_trace_context());
|
||||
}
|
||||
|
||||
pub(super) async fn stop_mcp_prewarm_worker(&self) {
|
||||
|
||||
@@ -8,6 +8,8 @@ use tokio::sync::AcquireError;
|
||||
use tokio::sync::Semaphore;
|
||||
use tokio::sync::SemaphorePermit;
|
||||
use tokio_util::task::TaskTracker;
|
||||
use tracing::Instrument;
|
||||
use uuid::Uuid;
|
||||
|
||||
/// Owns MCP invalidation and the single gate used to publish runtime updates.
|
||||
pub(super) struct McpRefresh {
|
||||
@@ -15,6 +17,7 @@ pub(super) struct McpRefresh {
|
||||
// Kept separate from pending so prewarm cannot claim work reserved for a real turn.
|
||||
on_next_turn: AtomicBool,
|
||||
gate: Semaphore,
|
||||
gate_id: Uuid,
|
||||
pub(super) apps_refreshes: TaskTracker,
|
||||
}
|
||||
|
||||
@@ -26,6 +29,7 @@ impl McpRefresh {
|
||||
Self {
|
||||
pending: Mutex::default(),
|
||||
on_next_turn: AtomicBool::new(false),
|
||||
gate_id: Uuid::new_v4(),
|
||||
gate: Semaphore::new(/*permits*/ 1),
|
||||
apps_refreshes,
|
||||
}
|
||||
@@ -93,9 +97,17 @@ impl McpRefresh {
|
||||
}
|
||||
}
|
||||
|
||||
#[tracing::instrument(name = "mcp.runtime.refresh_wait", skip_all)]
|
||||
pub(super) async fn acquire(&self) -> Result<SemaphorePermit<'_>, AcquireError> {
|
||||
self.gate.acquire().await
|
||||
pub(super) async fn acquire(
|
||||
&self,
|
||||
operation: &'static str,
|
||||
) -> Result<McpRefreshPermit<'_>, AcquireError> {
|
||||
let wait = tracing::info_span!("mcp.runtime.refresh_wait", mcp.refresh.gate_id = %self.gate_id, mcp.refresh.operation = operation);
|
||||
let permit = self.gate.acquire().instrument(wait).await?;
|
||||
let hold = tracing::info_span!("mcp.runtime.refresh_hold", mcp.refresh.gate_id = %self.gate_id, mcp.refresh.operation = operation);
|
||||
Ok(McpRefreshPermit {
|
||||
_hold: hold,
|
||||
_permit: permit,
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn close(&self) {
|
||||
@@ -103,6 +115,13 @@ impl McpRefresh {
|
||||
}
|
||||
}
|
||||
|
||||
/// Field order closes the hold span before releasing the permit, even on cancellation.
|
||||
/// Match waits to overlapping holds by gate ID; RPCs keep their original parents.
|
||||
pub(super) struct McpRefreshPermit<'a> {
|
||||
_hold: tracing::Span,
|
||||
_permit: SemaphorePermit<'a>,
|
||||
}
|
||||
|
||||
/// Restores a claimed refresh when its task is cancelled before publication.
|
||||
pub(super) struct McpRefreshInvalidationGuard<'a> {
|
||||
refresh: &'a McpRefresh,
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
//! Verifies that refreshes consume their own causes and preserve concurrent work.
|
||||
|
||||
use super::*;
|
||||
use opentelemetry::trace::TracerProvider;
|
||||
use opentelemetry_sdk::trace::InMemorySpanExporter;
|
||||
use opentelemetry_sdk::trace::SdkTracerProvider;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tracing_subscriber::prelude::*;
|
||||
|
||||
#[test]
|
||||
fn next_turn_reprojection_is_not_claimed_by_prewarm() {
|
||||
@@ -49,3 +53,46 @@ fn refresh_keeps_concurrent_invalidations_and_restores_unpublished_causes() {
|
||||
drop(next);
|
||||
assert!(refresh.claim(thread_id).is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn wait_overlaps_hold_on_same_gate() -> anyhow::Result<()> {
|
||||
let exported = InMemorySpanExporter::default();
|
||||
let provider = SdkTracerProvider::builder()
|
||||
.with_simple_exporter(exported.clone())
|
||||
.build();
|
||||
let subscriber = tracing_subscriber::registry().with(
|
||||
tracing_opentelemetry::layer()
|
||||
.with_tracer(provider.tracer("mcp-refresh-test"))
|
||||
.with_filter(tracing_subscriber::filter::filter_fn(
|
||||
codex_otel::OtelProvider::trace_export_filter,
|
||||
)),
|
||||
);
|
||||
let _interest_cache_guard =
|
||||
tracing::Dispatch::new(tracing::subscriber::NoSubscriber::default());
|
||||
let _subscriber_guard = tracing::subscriber::set_default(subscriber);
|
||||
let refresh = McpRefresh::new();
|
||||
|
||||
let owner = refresh.acquire("background").await?;
|
||||
let mut waiter = Box::pin(refresh.acquire("turn"));
|
||||
assert!(futures::poll!(waiter.as_mut()).is_pending());
|
||||
drop(owner);
|
||||
drop(waiter.await?);
|
||||
|
||||
let spans = exported.get_finished_spans()?;
|
||||
let gate = opentelemetry::KeyValue::new("mcp.refresh.gate_id", refresh.gate_id.to_string());
|
||||
let span = |name: &str, operation: &'static str| {
|
||||
let op = opentelemetry::KeyValue::new("mcp.refresh.operation", operation);
|
||||
spans
|
||||
.iter()
|
||||
.find(|s| s.name == name && s.attributes.contains(&op) && s.attributes.contains(&gate))
|
||||
.expect("exported permit span")
|
||||
};
|
||||
let hold = span("mcp.runtime.refresh_hold", "background");
|
||||
let wait = span("mcp.runtime.refresh_wait", "turn");
|
||||
let next = span("mcp.runtime.refresh_hold", "turn");
|
||||
assert!(hold.start_time <= wait.start_time);
|
||||
assert!(wait.start_time <= hold.end_time);
|
||||
assert!(hold.end_time <= wait.end_time);
|
||||
assert!(wait.end_time <= next.start_time);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -112,7 +112,7 @@ pub(crate) struct Session {
|
||||
pub(crate) mcp_tool_approval_metadata: std::sync::Mutex<McpToolApprovalMetadataMap>,
|
||||
pub(super) mcp_elicitation_reviewer_handle: OnceLock<codex_mcp::ElicitationReviewerHandle>,
|
||||
pub(super) mcp_elicitation_lifecycle_handle: OnceLock<codex_mcp::ElicitationLifecycle>,
|
||||
pub(super) mcp_prewarm_tx: async_channel::Sender<()>,
|
||||
pub(super) mcp_prewarm_tx: async_channel::Sender<Option<W3cTraceContext>>,
|
||||
pub(super) mcp_prewarm_shutdown: CancellationToken,
|
||||
pub(super) mcp_prewarm_task: std::sync::Mutex<Option<JoinHandle<()>>>,
|
||||
pub(crate) conversation: Arc<RealtimeConversationManager>,
|
||||
|
||||
@@ -685,7 +685,7 @@ async fn submitted_sparse_updates_preserve_captured_steps_and_ordering() {
|
||||
lookup.wait_until_blocked().await;
|
||||
let refresh = session
|
||||
.mcp_refresh
|
||||
.acquire()
|
||||
.acquire("test")
|
||||
.await
|
||||
.expect("MCP refresh lock");
|
||||
session.mark_mcp_runtime_dirty(McpRefreshReason::ExplicitInvalidation);
|
||||
|
||||
@@ -635,7 +635,7 @@ async fn automatic_admission_rechecks_plan_mode_without_committing_sparse_settin
|
||||
// rejection and its positive control inspect MCP's dirty state.
|
||||
let _mcp_refresh = session
|
||||
.mcp_refresh
|
||||
.acquire()
|
||||
.acquire("test")
|
||||
.await
|
||||
.expect("acquire MCP refresh gate");
|
||||
session.mcp_refresh.take_pending();
|
||||
|
||||
@@ -104,6 +104,8 @@ async fn picker_side_worktree_fork_and_cd_run_on_the_production_stack() -> Resul
|
||||
"features.worktrees=true",
|
||||
"-c",
|
||||
"features.shell_snapshot=false",
|
||||
"-c",
|
||||
"tui.status_line=['run-state']",
|
||||
"Reply with the marker requested by this test.",
|
||||
],
|
||||
)?;
|
||||
@@ -203,16 +205,8 @@ fn submit(terminal: &mut PtyCodex, input: &str) -> Result<()> {
|
||||
// while earlier characters are still buffered by paste-burst detection.
|
||||
terminal.write_input(format!("\x1b[200~{input}\x1b[201~").as_bytes())?;
|
||||
terminal.wait_for_screen(input)?;
|
||||
// Thread startup can keep the composer in queue mode after the history is visible.
|
||||
let deadline = Instant::now() + Duration::from_secs(/*secs*/ 30);
|
||||
while terminal.screen_contains("tab to queue message") {
|
||||
ensure!(
|
||||
Instant::now() < deadline,
|
||||
"composer remained busy before {input:?}"
|
||||
);
|
||||
terminal.read_output(Duration::from_millis(/*millis*/ 50))?;
|
||||
terminal.ensure_running()?;
|
||||
}
|
||||
// A worktree switch can acknowledge the new directory while the composer is still busy.
|
||||
terminal.wait_for_screen("Ready")?;
|
||||
terminal.write_input(b"\r")?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user