mirror of
https://github.com/openai/codex.git
synced 2026-12-03 00:41:03 +00:00
Link accepted steer requests to active turn spans (#65315)
## Why A steer request can arrive in a separate trace from the turn it updates. Recording the turn ID on the input span leaves the relationship implicit in OpenTelemetry. ## What changed Capture the context of `session_task.turn` when the task starts. When the active turn accepts steering input, add an OpenTelemetry link from the request's `op.dispatch.turn_input` span to the task span. The link is visible even when trace-level input spans are disabled. ## Testing Extend the turn tracing integration test to check that both steering entry points link to the active task and that initial submissions and stale steer requests emit no link. GitOrigin-RevId: 1daecd06d8db8a80c8112dff5c65a58142bda4d6
This commit is contained in:
@@ -838,7 +838,16 @@ pub(super) async fn submission_loop(
|
||||
request: *request,
|
||||
turn_extension_init: sub.turn_extension_init,
|
||||
};
|
||||
let result = turn_input::handle(&sess, request, mode, sub.id.clone()).await;
|
||||
// Keep the link on the dispatch even when trace-level input spans are enabled.
|
||||
let result = turn_input::admit(
|
||||
&sess,
|
||||
&dispatch_span,
|
||||
request,
|
||||
mode,
|
||||
sub.id.clone(),
|
||||
/*realtime_handoff_id*/ None,
|
||||
)
|
||||
.await;
|
||||
let _ = reply.send(result);
|
||||
return false;
|
||||
}
|
||||
@@ -1133,7 +1142,7 @@ pub(super) async fn submission_loop(
|
||||
_ => false, // Ignore unknown ops; enum is non_exhaustive to allow extensions.
|
||||
}
|
||||
}
|
||||
.instrument(dispatch_span)
|
||||
.instrument(dispatch_span.clone())
|
||||
.await;
|
||||
drop(sub.residency_guard);
|
||||
if should_exit {
|
||||
|
||||
@@ -238,12 +238,13 @@ impl Session {
|
||||
..Default::default()
|
||||
});
|
||||
request.user_item_uuid = Some(prepared.id);
|
||||
match turn_input::handle_realtime_handoff(
|
||||
match turn_input::admit(
|
||||
self,
|
||||
request,
|
||||
&tracing::Span::none(),
|
||||
request.into(),
|
||||
mode,
|
||||
submission_id.clone(),
|
||||
prepared.id,
|
||||
Some(prepared.id),
|
||||
)
|
||||
.await
|
||||
{
|
||||
|
||||
@@ -12497,7 +12497,7 @@ async fn abort_gracefully_emits_marker_before_turn_aborted() {
|
||||
assert!(rx.try_recv().is_err());
|
||||
}
|
||||
|
||||
async fn submit_steer_only(
|
||||
pub(super) async fn submit_steer_only(
|
||||
sess: &Arc<Session>,
|
||||
input: Vec<ResolvedUserInput>,
|
||||
expected_turn_id: &str,
|
||||
|
||||
@@ -269,8 +269,9 @@ pub(super) async fn handle(
|
||||
mode: TurnInputMode,
|
||||
submission_id: String,
|
||||
) -> CodexResult<TurnInputSubmission> {
|
||||
handle_inner(
|
||||
admit(
|
||||
session,
|
||||
&tracing::Span::none(),
|
||||
request.into(),
|
||||
mode,
|
||||
submission_id,
|
||||
@@ -279,31 +280,15 @@ pub(super) async fn handle(
|
||||
.await
|
||||
}
|
||||
|
||||
pub(super) async fn handle_realtime_handoff(
|
||||
session: &Arc<Session>,
|
||||
request: TurnInputRequest,
|
||||
mode: TurnInputMode,
|
||||
submission_id: String,
|
||||
handoff_id: uuid::Uuid,
|
||||
) -> CodexResult<TurnInputSubmission> {
|
||||
handle_inner(
|
||||
session,
|
||||
request.into(),
|
||||
mode,
|
||||
submission_id,
|
||||
Some(handoff_id),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
#[tracing::instrument(
|
||||
name = "codex.turn_input",
|
||||
level = "trace",
|
||||
skip_all,
|
||||
fields(conversation.id = %session.thread_id, turn.id)
|
||||
)]
|
||||
async fn handle_inner(
|
||||
pub(super) async fn admit(
|
||||
session: &Arc<Session>,
|
||||
dispatch_span: &tracing::Span,
|
||||
mut request: WithTurnExtensionData<TurnInputRequest>,
|
||||
mode: TurnInputMode,
|
||||
submission_id: String,
|
||||
@@ -347,7 +332,14 @@ async fn handle_inner(
|
||||
}
|
||||
let result = match mode {
|
||||
TurnInputMode::StartOrSteer => {
|
||||
start_or_steer(session, request, submission_id, realtime_handoff_id).await
|
||||
start_or_steer(
|
||||
session,
|
||||
dispatch_span,
|
||||
request,
|
||||
submission_id,
|
||||
realtime_handoff_id,
|
||||
)
|
||||
.await
|
||||
}
|
||||
TurnInputMode::StartIfIdle => {
|
||||
let kind = match &request.request.input {
|
||||
@@ -402,6 +394,7 @@ async fn handle_inner(
|
||||
TurnInputMode::Steer { expected_turn_id } => {
|
||||
steer(
|
||||
session,
|
||||
dispatch_span,
|
||||
request,
|
||||
expected_turn_id,
|
||||
submission_id,
|
||||
@@ -410,7 +403,7 @@ async fn handle_inner(
|
||||
.await
|
||||
}
|
||||
};
|
||||
// Link this request's trace to the accepted turn, which may have an older trace.
|
||||
// Record the turn ID on the input span, including when it starts a new turn.
|
||||
if let Ok(
|
||||
TurnInputSubmission::Started { turn_id, .. } | TurnInputSubmission::Steered { turn_id, .. },
|
||||
) = &result
|
||||
@@ -484,8 +477,9 @@ fn user_input_metadata(
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn start_or_steer(
|
||||
async fn start_or_steer(
|
||||
session: &Arc<Session>,
|
||||
dispatch_span: &tracing::Span,
|
||||
request: WithTurnExtensionData<TurnInputRequest>,
|
||||
submission_id: String,
|
||||
realtime_handoff_id: Option<uuid::Uuid>,
|
||||
@@ -538,6 +532,7 @@ pub(super) async fn start_or_steer(
|
||||
let sender_messages = capture_sender_user_messages(session, &mut input).await;
|
||||
match session
|
||||
.steer_input(
|
||||
dispatch_span,
|
||||
&mut input,
|
||||
sender_messages.as_ref(),
|
||||
&mut additional_context,
|
||||
@@ -808,6 +803,7 @@ async fn start_if_idle(
|
||||
|
||||
async fn steer(
|
||||
session: &Arc<Session>,
|
||||
dispatch_span: &tracing::Span,
|
||||
request: WithTurnExtensionData<TurnInputRequest>,
|
||||
expected_turn_id: String,
|
||||
submission_id: String,
|
||||
@@ -842,6 +838,7 @@ async fn steer(
|
||||
.await?;
|
||||
match session
|
||||
.steer_input(
|
||||
dispatch_span,
|
||||
&mut input,
|
||||
/*sender_messages*/ None,
|
||||
&mut additional_context,
|
||||
@@ -1066,6 +1063,7 @@ impl Session {
|
||||
)]
|
||||
async fn steer_input(
|
||||
&self,
|
||||
dispatch_span: &tracing::Span,
|
||||
input: &mut SubmittedTurnInput,
|
||||
sender_messages: Option<&GuardianSenderMessages>,
|
||||
additional_context: &mut Option<BTreeMap<String, AdditionalContextEntry>>,
|
||||
@@ -1173,6 +1171,9 @@ impl Session {
|
||||
}],
|
||||
)
|
||||
.await;
|
||||
if let Some(link) = active_task.span_link.clone() {
|
||||
link.add_to(dispatch_span);
|
||||
}
|
||||
Ok((
|
||||
active_turn_id.clone(),
|
||||
active_task.turn_context.root_turn_id(),
|
||||
|
||||
@@ -3,6 +3,7 @@ use crate::config::Constrained;
|
||||
use crate::session::step_settings::StepSettingsUpdate;
|
||||
use crate::session::tests::make_session_and_context;
|
||||
use crate::session::tests::make_session_and_context_with_rx;
|
||||
use crate::session::tests::submit_steer_only;
|
||||
use crate::session::turn_context::TurnContext;
|
||||
use crate::state::TaskKind;
|
||||
use crate::tasks::SessionTask;
|
||||
@@ -94,26 +95,6 @@ async fn submit_start_only(
|
||||
.expect("start-only submission should be valid")
|
||||
}
|
||||
|
||||
async fn submit_steer_only(
|
||||
session: &Arc<Session>,
|
||||
input: Vec<ResolvedUserInput>,
|
||||
expected_turn_id: &str,
|
||||
) -> TurnInputSubmission {
|
||||
handle(
|
||||
session,
|
||||
TurnInputRequest::new(SubmittedTurnInput::UserInput {
|
||||
content: input,
|
||||
client_id: None,
|
||||
}),
|
||||
TurnInputMode::Steer {
|
||||
expected_turn_id: expected_turn_id.to_string(),
|
||||
},
|
||||
"test-submission".to_string(),
|
||||
)
|
||||
.await
|
||||
.expect("steer-only submission should be valid")
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[expect(
|
||||
clippy::await_holding_invalid_type,
|
||||
|
||||
@@ -104,6 +104,7 @@ pub(crate) enum TaskKind {
|
||||
}
|
||||
|
||||
pub(crate) struct RunningTask {
|
||||
pub(crate) span_link: Option<codex_otel::SpanLink>,
|
||||
pub(crate) done: Arc<Notify>,
|
||||
pub(crate) kind: TaskKind,
|
||||
pub(crate) task: Arc<dyn AnySessionTask>,
|
||||
|
||||
@@ -458,6 +458,7 @@ impl Session {
|
||||
codex.turn.token_usage.total_tokens = field::Empty,
|
||||
);
|
||||
let storage_originator = AuthStorageOriginator::from_client_name(&turn_context.originator);
|
||||
let span_link = codex_otel::SpanLink::capture(&task_span);
|
||||
let task_future = async move {
|
||||
let ctx_for_finish = Arc::clone(&ctx);
|
||||
let mut _tool_result_capture = None;
|
||||
@@ -542,6 +543,7 @@ impl Session {
|
||||
.start_timer(TURN_E2E_DURATION_METRIC, &[])
|
||||
.ok();
|
||||
let running_task = RunningTask {
|
||||
span_link,
|
||||
done,
|
||||
handle: AbortOnDropHandle::new(handle),
|
||||
kind: task_kind,
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
use codex_core::RecoverTurnRequest;
|
||||
use codex_core::StartIfIdleSubmission;
|
||||
use codex_core::StartThreadOptions;
|
||||
use codex_core::SteerSubmission;
|
||||
use codex_core::TurnInputRequest;
|
||||
use codex_core::TurnInputSubmission;
|
||||
use codex_protocol::dynamic_tools::DynamicToolFunctionSpec;
|
||||
@@ -62,8 +63,6 @@ enum Finish {
|
||||
}
|
||||
|
||||
#[test_case(Finish::Reply, false; "reply_disabled")]
|
||||
#[test_case(Finish::Interrupt, false; "interrupt_disabled")]
|
||||
#[test_case(Finish::Reply, true; "reply_enabled")]
|
||||
#[test_case(Finish::Interrupt, true; "interrupt_enabled")]
|
||||
#[tokio::test(flavor = "current_thread")]
|
||||
async fn steer_joins_existing_turn_without_extending_sampling(
|
||||
@@ -157,18 +156,32 @@ async fn steer_joins_existing_turn_without_extending_sampling(
|
||||
// the dispatch future and its trace remain alive until the host responds.
|
||||
let sampling = wait_for_span(&exported, |span| span.name == "codex.sampling").await?;
|
||||
let steer = tracing::info_span!(parent: None, "steer_request");
|
||||
assert_eq!(
|
||||
let request = input("New question").with_trace(codex_otel::span_w3c_trace_context(&steer));
|
||||
match finish {
|
||||
Finish::Reply => assert_eq!(
|
||||
test.codex.start_or_steer_turn(request).await?,
|
||||
TurnInputSubmission::Steered {
|
||||
root_turn_id: call.turn_id.clone(),
|
||||
turn_id: call.turn_id.clone(),
|
||||
}
|
||||
),
|
||||
Finish::Interrupt => assert_eq!(
|
||||
test.codex.steer_turn(request, call.turn_id.clone()).await?,
|
||||
SteerSubmission::Steered {
|
||||
turn_id: call.turn_id.clone(),
|
||||
}
|
||||
),
|
||||
}
|
||||
let stale = tracing::info_span!(parent: None, "stale_request");
|
||||
assert!(matches!(
|
||||
test.codex
|
||||
.start_or_steer_turn(
|
||||
input("New question").with_trace(codex_otel::span_w3c_trace_context(&steer)),
|
||||
.steer_turn(
|
||||
input("Stale steer").with_trace(codex_otel::span_w3c_trace_context(&stale)),
|
||||
"stale-turn".to_string(),
|
||||
)
|
||||
.await?,
|
||||
TurnInputSubmission::Steered {
|
||||
root_turn_id: call.turn_id.clone(),
|
||||
turn_id: call.turn_id.clone()
|
||||
}
|
||||
);
|
||||
let mut interrupted_capture = None;
|
||||
SteerSubmission::NotSubmitted { .. }
|
||||
));
|
||||
match finish {
|
||||
Finish::Reply => {
|
||||
let reply = mount_sse_once(
|
||||
@@ -207,7 +220,7 @@ async fn steer_joins_existing_turn_without_extending_sampling(
|
||||
})
|
||||
.await;
|
||||
let closed_at = std::time::Instant::now();
|
||||
interrupted_capture = Some((closed_at, observe_timing(timing_start, closed_at)));
|
||||
let captured = observe_timing(timing_start, closed_at);
|
||||
let reply = mount_sse_once(
|
||||
&server,
|
||||
sse(vec![
|
||||
@@ -238,6 +251,8 @@ async fn steer_joins_existing_turn_without_extending_sampling(
|
||||
})
|
||||
.await;
|
||||
reply.single_request();
|
||||
// Recovery reuses a turn ID, but must not mutate the closed capture.
|
||||
assert_eq!(observe_timing(timing_start, closed_at), captured);
|
||||
drop(recovery);
|
||||
let recovery = wait_for_span(&exported, |span| span.name == "recovery_request").await?;
|
||||
let admitted = wait_for_span(&exported, |span| {
|
||||
@@ -258,10 +273,6 @@ async fn steer_joins_existing_turn_without_extending_sampling(
|
||||
);
|
||||
}
|
||||
}
|
||||
if let Some((closed_at, captured)) = interrupted_capture {
|
||||
// Recovery reuses a turn ID, but must not mutate the closed capture.
|
||||
assert_eq!(observe_timing(timing_start, closed_at), captured);
|
||||
}
|
||||
let timing_end = std::time::Instant::now();
|
||||
let totals = observe_timing(timing_start, timing_end);
|
||||
if critical_path_timing {
|
||||
@@ -271,6 +282,12 @@ async fn steer_joins_existing_turn_without_extending_sampling(
|
||||
} else {
|
||||
assert_eq!(totals, None);
|
||||
}
|
||||
// The task can close while the incoming requests and session are still open.
|
||||
let task = wait_for_span(&exported, |span| {
|
||||
span.name == "session_task.turn"
|
||||
&& span.span_context.trace_id() == sampling.span_context.trace_id()
|
||||
})
|
||||
.await?;
|
||||
test.codex.submit(Op::Shutdown).await?;
|
||||
wait_for_event(&test.codex, |event| {
|
||||
matches!(event, EventMsg::ShutdownComplete)
|
||||
@@ -278,6 +295,7 @@ async fn steer_joins_existing_turn_without_extending_sampling(
|
||||
.await;
|
||||
drop(initial);
|
||||
drop(steer);
|
||||
drop(stale);
|
||||
// ShutdownComplete can precede the final dispatch span's drop. Wait for
|
||||
// its exported ready event rather than racing the last task cleanup.
|
||||
let tool_span = wait_for_span(&exported, |span| {
|
||||
@@ -289,6 +307,26 @@ async fn steer_joins_existing_turn_without_extending_sampling(
|
||||
.await?;
|
||||
let run_turn = wait_for_span(&exported, |span| span.name == "run_turn").await?;
|
||||
let spans = exported.get_finished_spans()?;
|
||||
let dispatch_for = |request: &str| {
|
||||
let parent = spans
|
||||
.iter()
|
||||
.find(|span| span.name == request)
|
||||
.unwrap_or_else(|| panic!("missing request span {request}"));
|
||||
spans
|
||||
.iter()
|
||||
.find(|span| {
|
||||
span.name == "op.dispatch.turn_input"
|
||||
&& span.span_context.trace_id() == parent.span_context.trace_id()
|
||||
&& span.parent_span_id == parent.span_context.span_id()
|
||||
})
|
||||
.unwrap_or_else(|| panic!("missing dispatch parented to {request}"))
|
||||
};
|
||||
assert!(dispatch_for("initial_request").links.is_empty());
|
||||
assert!(dispatch_for("stale_request").links.is_empty());
|
||||
let steer = dispatch_for("steer_request");
|
||||
assert_eq!(steer.links.len(), 1);
|
||||
assert_eq!(steer.links[0].span_context, task.span_context);
|
||||
assert!(steer.end_time <= task.end_time);
|
||||
let dispatch = spans
|
||||
.iter()
|
||||
.find(|span| {
|
||||
@@ -303,10 +341,6 @@ async fn steer_joins_existing_turn_without_extending_sampling(
|
||||
)),
|
||||
std::array::from_fn::<_, 2, _>(|_| (Some(thread_id.clone()), Some(call.turn_id.clone())))
|
||||
);
|
||||
let steer = spans
|
||||
.iter()
|
||||
.find(|span| span.name == "steer_request")
|
||||
.expect("steer request span exported");
|
||||
let accepted = spans
|
||||
.iter()
|
||||
.find(|span| {
|
||||
|
||||
@@ -28,6 +28,7 @@ static TRACESTATE_ENTRIES: OnceLock<RwLock<BTreeMap<String, BTreeMap<String, Str
|
||||
OnceLock::new();
|
||||
|
||||
/// A native OpenTelemetry link target that can outlive the source span.
|
||||
#[derive(Clone)]
|
||||
pub struct SpanLink(SpanContext);
|
||||
|
||||
impl SpanLink {
|
||||
|
||||
Reference in New Issue
Block a user