mirror of
https://github.com/openai/codex.git
synced 2026-12-02 00:31:03 +00:00
Link startup prewarm to the first turn's OpenTelemetry trace (#65105)
## Why Startup prewarm runs in the session startup trace, while the first turn can run in a separate trace. The first-turn trace needs a way to show which prewarm task it resolved, including when the wait times out. ## What changed Record `startup_prewarm.resolve` at info level under the first-turn span. Capture the startup prewarm span context when scheduling the task and attach it as an OpenTelemetry span link during resolution. If the prewarm span is filtered out, omit the link. ## Testing Check exported spans for first-turn parentage, link behavior with the prewarm span enabled or filtered out, and no second resolution on a later turn. Add a regression test for retaining the link on timeout. GitOrigin-RevId: ef4a19be64ecf145b17527081960e50adca3b92e
This commit is contained in:
@@ -214,6 +214,7 @@ async fn cancelled_startup_does_not_record_unselected_review_evidence() {
|
||||
tokio::spawn(std::future::pending()),
|
||||
std::time::Instant::now(),
|
||||
crate::client::WEBSOCKET_CONNECT_TIMEOUT,
|
||||
/*producer_span_link*/ None,
|
||||
),
|
||||
)
|
||||
.await;
|
||||
|
||||
@@ -13,6 +13,7 @@ use tokio::task::JoinHandle;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
use tokio_util::task::AbortOnDropHandle;
|
||||
use tracing::Instrument;
|
||||
use tracing::Span;
|
||||
use tracing::info;
|
||||
use tracing::info_span;
|
||||
use tracing::instrument;
|
||||
@@ -28,6 +29,7 @@ use codex_features::Feature;
|
||||
use codex_otel::STARTUP_PREWARM_AGE_AT_FIRST_TURN_METRIC;
|
||||
use codex_otel::STARTUP_PREWARM_DURATION_METRIC;
|
||||
use codex_otel::SessionTelemetry;
|
||||
use codex_otel::SpanLink;
|
||||
use codex_protocol::error::Result as CodexResult;
|
||||
use codex_protocol::models::BaseInstructions;
|
||||
use codex_protocol::models::ContentItem;
|
||||
@@ -56,6 +58,7 @@ pub(crate) struct SessionStartupPrewarmHandle {
|
||||
task: AbortOnDropHandle<CodexResult<ModelClientSession>>,
|
||||
started_at: Instant,
|
||||
timeout: Duration,
|
||||
producer_span_link: Option<SpanLink>,
|
||||
}
|
||||
|
||||
pub(crate) enum SessionStartupPrewarmResolution {
|
||||
@@ -72,11 +75,13 @@ impl SessionStartupPrewarmHandle {
|
||||
task: JoinHandle<CodexResult<ModelClientSession>>,
|
||||
started_at: Instant,
|
||||
timeout: Duration,
|
||||
producer_span_link: Option<SpanLink>,
|
||||
) -> Self {
|
||||
Self {
|
||||
task: AbortOnDropHandle::new(task),
|
||||
started_at,
|
||||
timeout,
|
||||
producer_span_link,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -85,7 +90,7 @@ impl SessionStartupPrewarmHandle {
|
||||
let _ = self.task.await;
|
||||
}
|
||||
|
||||
#[instrument(name = "startup_prewarm.resolve", level = "trace", skip_all)]
|
||||
#[instrument(name = "startup_prewarm.resolve", level = "info", skip_all)]
|
||||
async fn resolve(
|
||||
self,
|
||||
session_telemetry: &SessionTelemetry,
|
||||
@@ -96,9 +101,13 @@ impl SessionStartupPrewarmHandle {
|
||||
mut task,
|
||||
started_at,
|
||||
timeout,
|
||||
producer_span_link,
|
||||
} = self;
|
||||
let age_at_first_turn = started_at.elapsed();
|
||||
let remaining = timeout.saturating_sub(age_at_first_turn);
|
||||
if let Some(producer_span_link) = producer_span_link {
|
||||
producer_span_link.add_to(&Span::current());
|
||||
}
|
||||
|
||||
let resolution = if task.is_finished() {
|
||||
Self::resolution_from_join_result(task.await, started_at)
|
||||
@@ -267,8 +276,9 @@ impl Session {
|
||||
otel.name = "startup_prewarm",
|
||||
thread.id = %self.thread_id(),
|
||||
prewarm.input = input_label,
|
||||
)
|
||||
.or_current();
|
||||
);
|
||||
// Capture before or_current() can substitute the startup request span.
|
||||
let producer_span_link = SpanLink::capture(&prewarm_span);
|
||||
let startup_prewarm = tokio::spawn(
|
||||
async move {
|
||||
let result = schedule_startup_prewarm_inner(startup_prewarm_session, input).await;
|
||||
@@ -285,12 +295,13 @@ impl Session {
|
||||
);
|
||||
result
|
||||
}
|
||||
.instrument(prewarm_span),
|
||||
.instrument(prewarm_span.or_current()),
|
||||
);
|
||||
state.set_session_startup_prewarm(SessionStartupPrewarmHandle::new(
|
||||
startup_prewarm,
|
||||
started_at,
|
||||
websocket_connect_timeout,
|
||||
producer_span_link,
|
||||
));
|
||||
}
|
||||
|
||||
|
||||
@@ -669,6 +669,7 @@ async fn regular_turn_emits_turn_started_with_trace_id_without_waiting_for_start
|
||||
handle,
|
||||
std::time::Instant::now(),
|
||||
crate::client::WEBSOCKET_CONNECT_TIMEOUT,
|
||||
/*producer_span_link*/ None,
|
||||
),
|
||||
)
|
||||
.await;
|
||||
@@ -794,6 +795,57 @@ async fn request_mcp_server_elicitation_waits_for_user_response(
|
||||
assert!(rx.try_recv().is_err());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn timed_out_startup_prewarm_keeps_its_span_link() -> anyhow::Result<()> {
|
||||
use crate::session::startup_prewarm::SessionStartupPrewarmHandle;
|
||||
use crate::session::startup_prewarm::SessionStartupPrewarmResolution;
|
||||
use anyhow::Context as _;
|
||||
use opentelemetry::trace::TracerProvider as _;
|
||||
use opentelemetry_sdk::trace::InMemorySpanExporter;
|
||||
use opentelemetry_sdk::trace::SdkTracerProvider;
|
||||
use tracing_subscriber::layer::SubscriberExt;
|
||||
|
||||
let (session, _) = make_session_and_context().await;
|
||||
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("prewarm-timeout")));
|
||||
let _guard = tracing::subscriber::set_default(subscriber);
|
||||
let prewarm = info_span!(parent: None, "startup_prewarm");
|
||||
let prewarm_context = prewarm.context().span().span_context().clone();
|
||||
let link = codex_otel::SpanLink::capture(&prewarm);
|
||||
session
|
||||
.set_session_startup_prewarm(SessionStartupPrewarmHandle::new(
|
||||
tokio::spawn(std::future::pending().instrument(prewarm)),
|
||||
Instant::now(),
|
||||
Duration::ZERO,
|
||||
link,
|
||||
))
|
||||
.await;
|
||||
let resolution = session
|
||||
.consume_startup_prewarm_for_regular_turn(&CancellationToken::new())
|
||||
.await;
|
||||
assert!(matches!(
|
||||
resolution,
|
||||
SessionStartupPrewarmResolution::Unavailable {
|
||||
status: "timed_out",
|
||||
..
|
||||
}
|
||||
));
|
||||
let spans = exported.get_finished_spans()?;
|
||||
let resolve = spans
|
||||
.iter()
|
||||
.find(|span| span.name == "startup_prewarm.resolve")
|
||||
.context("resolve span")?;
|
||||
let [link] = resolve.links.links.as_slice() else {
|
||||
anyhow::bail!("expected one link from the timed-out wait");
|
||||
};
|
||||
assert_eq!(link.span_context, prewarm_context);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn interrupting_regular_turn_waiting_on_startup_prewarm_emits_turn_aborted() {
|
||||
let (sess, tc, rx) = make_session_and_context_with_rx().await;
|
||||
@@ -808,6 +860,7 @@ async fn interrupting_regular_turn_waiting_on_startup_prewarm_emits_turn_aborted
|
||||
handle,
|
||||
std::time::Instant::now(),
|
||||
crate::client::WEBSOCKET_CONNECT_TIMEOUT,
|
||||
/*producer_span_link*/ None,
|
||||
),
|
||||
)
|
||||
.await;
|
||||
|
||||
@@ -5,6 +5,7 @@ use std::sync::Arc;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
use std::sync::atomic::Ordering;
|
||||
|
||||
use anyhow::Context as _;
|
||||
use codex_api::WS_REQUEST_HEADER_TRACEPARENT_CLIENT_METADATA_KEY;
|
||||
use codex_api::WS_REQUEST_HEADER_TRACESTATE_CLIENT_METADATA_KEY;
|
||||
use codex_protocol::protocol::W3cTraceContext;
|
||||
@@ -15,6 +16,7 @@ use core_test_support::responses::start_websocket_server;
|
||||
use core_test_support::skip_if_no_network;
|
||||
use core_test_support::test_codex::test_codex;
|
||||
use opentelemetry::trace::TracerProvider as _;
|
||||
use opentelemetry_sdk::trace::InMemorySpanExporter;
|
||||
use opentelemetry_sdk::trace::SdkTracerProvider;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tracing::Instrument;
|
||||
@@ -27,7 +29,10 @@ async fn websocket_startup_prewarm_propagates_trace() -> anyhow::Result<()> {
|
||||
|
||||
let include_prewarm_span = Arc::new(AtomicBool::new(false));
|
||||
let filter_setting = Arc::clone(&include_prewarm_span);
|
||||
let provider = SdkTracerProvider::builder().build();
|
||||
let exported = InMemorySpanExporter::default();
|
||||
let provider = SdkTracerProvider::builder()
|
||||
.with_simple_exporter(exported.clone())
|
||||
.build();
|
||||
tracing::subscriber::set_global_default(
|
||||
tracing_subscriber::registry()
|
||||
.with(
|
||||
@@ -40,13 +45,17 @@ async fn websocket_startup_prewarm_propagates_trace() -> anyhow::Result<()> {
|
||||
)?;
|
||||
|
||||
for enabled in [false, true] {
|
||||
exported.reset();
|
||||
include_prewarm_span.store(enabled, Ordering::Relaxed);
|
||||
assert_prewarm_and_turn_trace().await?;
|
||||
assert_prewarm_and_turn_trace(&exported, enabled).await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn assert_prewarm_and_turn_trace() -> anyhow::Result<()> {
|
||||
async fn assert_prewarm_and_turn_trace(
|
||||
exported: &InMemorySpanExporter,
|
||||
include_prewarm_span: bool,
|
||||
) -> anyhow::Result<()> {
|
||||
let request_span = |trace_id: &str, tracestate: &str| {
|
||||
let span = tracing::info_span!(parent: None, "request");
|
||||
assert!(codex_otel::set_parent_from_w3c_trace_context(
|
||||
@@ -60,6 +69,7 @@ async fn assert_prewarm_and_turn_trace() -> anyhow::Result<()> {
|
||||
};
|
||||
let start_trace_id = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
|
||||
let turn_trace_id = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb";
|
||||
let later_turn_trace_id = "cccccccccccccccccccccccccccccccc";
|
||||
let server = start_websocket_server(vec![vec![
|
||||
vec![ev_response_created("warm-1"), ev_completed("warm-1")],
|
||||
vec![
|
||||
@@ -67,6 +77,11 @@ async fn assert_prewarm_and_turn_trace() -> anyhow::Result<()> {
|
||||
ev_assistant_message("msg-1", "done"),
|
||||
ev_completed("resp-1"),
|
||||
],
|
||||
vec![
|
||||
ev_response_created("resp-2"),
|
||||
ev_assistant_message("msg-2", "done again"),
|
||||
ev_completed("resp-2"),
|
||||
],
|
||||
]])
|
||||
.await;
|
||||
let test = test_codex()
|
||||
@@ -117,7 +132,50 @@ async fn assert_prewarm_and_turn_trace() -> anyhow::Result<()> {
|
||||
expected_state,
|
||||
);
|
||||
}
|
||||
test.submit_text_turn("hello again")
|
||||
.instrument(request_span(later_turn_trace_id, "vendor=later"))
|
||||
.await?;
|
||||
test.codex.shutdown_and_wait().await?;
|
||||
server.shutdown().await;
|
||||
|
||||
let spans = exported.get_finished_spans()?;
|
||||
let resolve_spans: Vec<_> = spans
|
||||
.iter()
|
||||
.filter(|span| span.name == "startup_prewarm.resolve")
|
||||
.collect();
|
||||
let [resolve] = resolve_spans.as_slice() else {
|
||||
panic!("expected one prewarm resolution across both turns, got {resolve_spans:?}");
|
||||
};
|
||||
let first_turn = spans
|
||||
.iter()
|
||||
.find(|span| {
|
||||
span.name == "session_task.turn"
|
||||
&& span.span_context.trace_id().to_string() == turn_trace_id
|
||||
})
|
||||
.context("first turn span")?;
|
||||
assert_eq!(
|
||||
resolve.span_context.trace_id(),
|
||||
first_turn.span_context.trace_id()
|
||||
);
|
||||
assert_eq!(resolve.parent_span_id, first_turn.span_context.span_id());
|
||||
let prewarm = spans.iter().find(|span| span.name == "startup_prewarm");
|
||||
let expected_links = if include_prewarm_span {
|
||||
let prewarm = prewarm.context("startup prewarm span")?;
|
||||
assert_eq!(prewarm.span_context.trace_id().to_string(), start_trace_id);
|
||||
vec![(
|
||||
prewarm.span_context.trace_id(),
|
||||
prewarm.span_context.span_id(),
|
||||
)]
|
||||
} else {
|
||||
assert!(prewarm.is_none());
|
||||
Vec::new()
|
||||
};
|
||||
let actual_links: Vec<_> = resolve
|
||||
.links
|
||||
.links
|
||||
.iter()
|
||||
.map(|link| (link.span_context.trace_id(), link.span_context.span_id()))
|
||||
.collect();
|
||||
assert_eq!(actual_links, expected_links);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -44,6 +44,7 @@ pub use crate::skill_invocation::SkillInvocationEvent;
|
||||
pub use crate::skill_invocation::SkillInvocationType;
|
||||
pub use crate::subagent::SubagentStopAction;
|
||||
pub use crate::subagent::SubagentTurnStatus;
|
||||
pub use crate::trace_context::SpanLink;
|
||||
pub use crate::trace_context::context_from_w3c_trace_context;
|
||||
pub use crate::trace_context::current_span_trace_id;
|
||||
pub use crate::trace_context::current_span_w3c_trace_context;
|
||||
|
||||
@@ -9,6 +9,7 @@ use std::sync::RwLock;
|
||||
use codex_protocol::protocol::W3cTraceContext;
|
||||
use opentelemetry::Context;
|
||||
use opentelemetry::propagation::TextMapPropagator;
|
||||
use opentelemetry::trace::SpanContext;
|
||||
use opentelemetry::trace::TraceContextExt;
|
||||
use opentelemetry::trace::TraceState;
|
||||
use opentelemetry_sdk::propagation::TraceContextPropagator;
|
||||
@@ -26,6 +27,24 @@ static TRACEPARENT_CONTEXT: OnceLock<Option<Context>> = OnceLock::new();
|
||||
static TRACESTATE_ENTRIES: OnceLock<RwLock<BTreeMap<String, BTreeMap<String, String>>>> =
|
||||
OnceLock::new();
|
||||
|
||||
/// A native OpenTelemetry link target that can outlive the source span.
|
||||
pub struct SpanLink(SpanContext);
|
||||
|
||||
impl SpanLink {
|
||||
/// Captures the span's own context if OpenTelemetry assigned it valid IDs.
|
||||
pub fn capture(span: &Span) -> Option<Self> {
|
||||
let context = span.context();
|
||||
let span = context.span();
|
||||
let span_context = span.span_context();
|
||||
span_context.is_valid().then(|| Self(span_context.clone()))
|
||||
}
|
||||
|
||||
/// Adds the link to the destination span without changing its parent.
|
||||
pub fn add_to(self, span: &Span) {
|
||||
span.add_link(self.0);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn current_span_w3c_trace_context() -> Option<W3cTraceContext> {
|
||||
span_w3c_trace_context(&Span::current())
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user