Skip to content

Commit 320a3c0

Browse files
committed
fix(codex-api): send keepalive pings on the Responses WebSocket
The Responses WebSocket pump loop only answered server pings; it never initiated one and had no keepalive timer, so a quiet reasoning turn left the socket fully idle. Proxies and CDNs in front of the endpoint (Cloudflare's default is a 100s idle-WebSocket timeout) then close it mid-turn, surfacing as "idle timeout waiting for websocket" and a reconnect loop. Add a keepalive arm to the pump select! that sends a Ping every 30s, well under the idle window, plus a unit test asserting the pump emits a client-initiated ping.
1 parent d7f298f commit 320a3c0

1 file changed

Lines changed: 64 additions & 2 deletions

File tree

‎codex-rs/codex-api/src/endpoint/responses_websocket.rs‎

Lines changed: 64 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,15 @@ use tungstenite::extensions::compression::deflate::DeflateConfig;
4747
use tungstenite::protocol::WebSocketConfig;
4848
use url::Url;
4949

50+
/// Interval between client-initiated WebSocket keepalive pings.
51+
///
52+
/// Proxies and CDNs in front of the Responses endpoint close idle WebSocket
53+
/// connections after a fixed inactivity window (Cloudflare's default is 100s).
54+
/// A long, quiet reasoning turn sends no frames in either direction, so without
55+
/// a keepalive the connection is torn down mid-turn. Pinging well under that
56+
/// window keeps it alive.
57+
const WEBSOCKET_KEEPALIVE_INTERVAL: Duration = Duration::from_secs(30);
58+
5059
struct WsStream {
5160
tx_command: mpsc::Sender<WsCommand>,
5261
rx_message: mpsc::UnboundedReceiver<Result<Message, WsError>>,
@@ -61,12 +70,18 @@ enum WsCommand {
6170
}
6271

6372
impl WsStream {
64-
fn new(inner: WebSocketStream<MaybeTlsStream<TcpStream>>) -> Self {
73+
fn new(
74+
inner: WebSocketStream<MaybeTlsStream<TcpStream>>,
75+
keepalive_interval: Duration,
76+
) -> Self {
6577
let (tx_command, mut rx_command) = mpsc::channel::<WsCommand>(32);
6678
let (tx_message, rx_message) = mpsc::unbounded_channel::<Result<Message, WsError>>();
6779

6880
let pump_task = tokio::spawn(async move {
6981
let mut inner = inner;
82+
let mut keepalive =
83+
tokio::time::interval_at(Instant::now() + keepalive_interval, keepalive_interval);
84+
keepalive.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
7085
loop {
7186
tokio::select! {
7287
command = rx_command.recv() => {
@@ -114,6 +129,12 @@ impl WsStream {
114129
}
115130
}
116131
}
132+
_ = keepalive.tick() => {
133+
if let Err(err) = inner.send(Message::Ping(Vec::new().into())).await {
134+
let _ = tx_message.send(Err(err));
135+
break;
136+
}
137+
}
117138
}
118139
}
119140
});
@@ -496,7 +517,7 @@ async fn connect_websocket(
496517
let _ = turn_state.set(header_value.to_string());
497518
}
498519
Ok((
499-
WsStream::new(stream),
520+
WsStream::new(stream, WEBSOCKET_KEEPALIVE_INTERVAL),
500521
response.status(),
501522
reasoning_included,
502523
models_etag,
@@ -853,6 +874,47 @@ mod tests {
853874
assert!(config.extensions.permessage_deflate.is_some());
854875
}
855876

877+
#[tokio::test]
878+
async fn pump_task_sends_keepalive_pings() {
879+
use tokio::net::TcpListener;
880+
use tokio_tungstenite::accept_async;
881+
use tokio_tungstenite::connect_async;
882+
883+
let listener = TcpListener::bind("127.0.0.1:0")
884+
.await
885+
.expect("bind loopback listener");
886+
let addr = listener.local_addr().expect("read local addr");
887+
888+
// Server side: accept one connection and report whether it ever receives a
889+
// client-initiated ping frame.
890+
let server = tokio::spawn(async move {
891+
let (tcp, _) = listener.accept().await.expect("accept connection");
892+
let mut server_ws = accept_async(tcp).await.expect("server handshake");
893+
loop {
894+
match server_ws.next().await {
895+
Some(Ok(Message::Ping(_))) => return true,
896+
Some(Ok(_)) => continue,
897+
Some(Err(_)) | None => return false,
898+
}
899+
}
900+
});
901+
902+
let (client_stream, _) = connect_async(format!("ws://{addr}"))
903+
.await
904+
.expect("client handshake");
905+
// Hold the stream for the lifetime of the test; dropping it aborts the pump task.
906+
let _ws_stream = WsStream::new(client_stream, Duration::from_millis(50));
907+
908+
let received_ping = tokio::time::timeout(Duration::from_secs(5), server)
909+
.await
910+
.expect("timed out waiting for keepalive ping")
911+
.expect("server task panicked");
912+
assert!(
913+
received_ping,
914+
"pump task should send a client-initiated keepalive ping"
915+
);
916+
}
917+
856918
#[test]
857919
fn parse_wrapped_websocket_error_event_maps_to_transport_http() {
858920
let payload = json!({

0 commit comments

Comments
 (0)