Fix attestation routing during thread startup (#47912)

## Why

Thread startup can prewarm the Responses WebSocket before the creating client is registered with the thread, leaving the handshake unable to request attestation from that client.

## What changed

Reserve a thread ID and register the creating connection before starting the thread, including for ephemeral threads. Remove the thread state if startup fails.

## Testing

Extend the attestation round-trip test to cover persistent and ephemeral threads. Handle attestation requests while awaiting `thread/start` and `turn/start` responses, and verify the WebSocket handshake includes the expected `x-oai-attestation` header.

GitOrigin-RevId: 1bdb38bac641253eed58a2431658ab54d93819c5
This commit is contained in:
Charlie Marsh
2026-09-24 18:38:00 +00:00
committed by copyberry
parent 6743672ad7
commit a8a4f14087
2 changed files with 52 additions and 31 deletions
@@ -1481,7 +1481,15 @@ impl ThreadRequestProcessor {
)
.await?
};
start_options.reserved_thread_id = reserved_thread_id;
let thread_id = reserved_thread_id
.unwrap_or_else(|| listener_task_context.thread_manager.reserve_thread_id());
start_options.reserved_thread_id = Some(thread_id);
// Startup can prewarm the Responses socket before start_thread returns.
// Register the creating client first so that handshake can request attestation.
listener_task_context
.thread_state_manager
.try_add_connection_to_thread(thread_id, request_id.connection_id)
.await;
let create_thread_started_at = std::time::Instant::now();
let new_thread = listener_task_context
.thread_manager
@@ -1517,6 +1525,10 @@ impl ThreadRequestProcessor {
} = match new_thread {
Ok(new_thread) => new_thread,
Err(err) => {
listener_task_context
.thread_state_manager
.remove_thread_state(thread_id)
.await;
remove_pending_thread_metadata(thread_store.as_ref(), reserved_thread_id).await;
return Err(match err.details() {
CodexErrorDetails::InvalidRequest(message) => invalid_request(message.clone()),
@@ -9,7 +9,6 @@ use codex_app_server_protocol::AttestationGenerateResponse;
use codex_app_server_protocol::ClientInfo;
use codex_app_server_protocol::InitializeCapabilities;
use codex_app_server_protocol::JSONRPCMessage;
use codex_app_server_protocol::JSONRPCResponse;
use codex_app_server_protocol::RequestId;
use codex_app_server_protocol::ServerRequest;
use codex_app_server_protocol::ThreadStartParams;
@@ -25,6 +24,7 @@ use core_test_support::skip_if_no_network;
use pretty_assertions::assert_eq;
use std::path::Path;
use tempfile::TempDir;
use test_case::test_case;
use tokio::time::Duration;
use tokio::time::timeout;
@@ -32,9 +32,12 @@ const DEFAULT_READ_TIMEOUT: Duration = Duration::from_secs(60);
const ATTESTATION_HEADER: &str = "v1.integration-test";
const APP_SERVER_ATTESTATION_HEADER: &str = r#"{"v":1,"s":0,"t":"v1.integration-test"}"#;
#[test_case(ThreadStartParams::default(); "persistent")]
#[test_case(ThreadStartParams { ephemeral: Some(true), ..Default::default() }; "ephemeral")]
#[tokio::test]
async fn attestation_generate_round_trip_adds_header_to_responses_websocket_handshake() -> Result<()>
{
async fn attestation_generate_round_trip_adds_header_to_responses_websocket_handshake(
thread_start_params: ThreadStartParams,
) -> Result<()> {
skip_if_no_network!(Ok(()));
let websocket_server = start_websocket_server_with_headers(vec![WebSocketConnectionConfig {
@@ -96,37 +99,40 @@ async fn attestation_generate_round_trip_adds_header_to_responses_websocket_hand
};
let thread_request_id = mcp
.send_thread_start_request_with_auto_env(ThreadStartParams::default())
.send_thread_start_request_with_auto_env(thread_start_params)
.await?;
let thread_response: JSONRPCResponse = timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_stream_until_response_message(RequestId::Integer(thread_request_id)),
)
.await??;
let ThreadStartResponse { thread, .. } = to_response(thread_response)?;
let turn_request_id = mcp
.send_turn_start_request(TurnStartParams {
thread_id: thread.id,
client_user_message_id: None,
input: vec![V2UserInput::Text {
text: "Hello".to_string(),
text_elements: Vec::new(),
}],
..Default::default()
})
.await?;
let turn_response: JSONRPCResponse = timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_stream_until_response_message(RequestId::Integer(turn_request_id)),
)
.await??;
let _: TurnStartResponse = to_response(turn_response)?;
let mut turn_request_id = None;
let mut turn_started = false;
let mut turn_completed = false;
let mut attestation_requests = 0;
// Prewarming can request attestation before thread/start or turn/start responds.
// Service those requests immediately instead of buffering them behind RPC responses.
timeout(DEFAULT_READ_TIMEOUT, async {
loop {
match mcp.read_next_message().await? {
JSONRPCMessage::Response(response)
if response.id == RequestId::Integer(thread_request_id) =>
{
let ThreadStartResponse { thread, .. } = to_response(response)?;
turn_request_id = Some(RequestId::Integer(
mcp.send_turn_start_request(TurnStartParams {
thread_id: thread.id,
client_user_message_id: None,
input: vec![V2UserInput::Text {
text: "Hello".to_string(),
text_elements: Vec::new(),
}],
..Default::default()
})
.await?,
));
}
JSONRPCMessage::Response(response)
if turn_request_id.as_ref() == Some(&response.id) =>
{
let _: TurnStartResponse = to_response(response)?;
turn_started = true;
}
JSONRPCMessage::Request(request) => {
let request = ServerRequest::try_from(request)?;
let ServerRequest::AttestationGenerate { request_id, .. } = request else {
@@ -144,10 +150,13 @@ async fn attestation_generate_round_trip_adds_header_to_responses_websocket_hand
JSONRPCMessage::Notification(notification)
if notification.method == "turn/completed" =>
{
break Ok(());
turn_completed = true;
}
_ => {}
}
if turn_started && turn_completed {
break Ok(());
}
}
})
.await??;