From 813866826dc7c9b526dc0562420ec6e269eccfd1 Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Fri, 13 Nov 2026 19:30:54 +0000 Subject: [PATCH 1/3] perf(client): reuse the connection after CloseStatement and CancelStatement The close and cancel replies were dropped unread. Over HTTP/1.1 hyper only returns a connection to the pool once its body has been read, so when the server flushes the chunked {} body after the headers, the next request opened a new TCP/TLS connection. Read the body before returning. Co-authored-by: Isaac Signed-off-by: Vu Anh Phung --- NEXT_CHANGELOG.md | 1 + src/client/sea.rs | 82 ++++++++++++++++++++++++++++++++++++++++++----- 2 files changed, 75 insertions(+), 8 deletions(-) diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index 6aa75289..9e94f27d 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -26,6 +26,7 @@ changes go in their respective binding's NEXT_CHANGELOG. ### Fixed - `Session::open` authenticates once before resolving feature flags. A failed OAuth token request now fails the open immediately instead of being sent a second time by CreateSession. +- CloseStatement and CancelStatement read their response body, so the HTTP connection is reused instead of a new TCP/TLS connection being opened for the next request. --- *Note: When making changes, please add your change under the appropriate diff --git a/src/client/sea.rs b/src/client/sea.rs index 7003150f..981c5c70 100644 --- a/src/client/sea.rs +++ b/src/client/sea.rs @@ -1057,6 +1057,14 @@ impl SeaRestTransport { } } +/// Read a response body we don't need to its end. Over HTTP/1.1 hyper can only +/// return a connection to the pool once the body has been read, so dropping +/// the (`{}`) body of a close/cancel reply would make the next request open a +/// new TCP/TLS connection. The call already succeeded, so a read error is ignored. +async fn discard_body(response: reqwest::Response) { + let _ = response.bytes().await; +} + /// Convert a parsed `GetChunksResponse` into the kernel-facing /// `ChunkLinkFetchResult`. Extracted from `get_result_chunks` /// so the continuation derivation (top-level vs per-link @@ -1590,9 +1598,11 @@ impl Transport for SeaRestTransport { Error::invalid_argument().message(format!("Failed to build request: {e}")) })?; - self.http_client + let response = self + .http_client .execute(request, RequestType::CancelStatement) .await?; + discard_body(response).await; debug!("Canceled statement: {}", statement_id); @@ -1621,17 +1631,20 @@ impl Transport for SeaRestTransport { // already applied the SEA retry policy, so callers see only the // post-retry result; the `Drop` fire-and-forget fallback close still // runs on the kernel side if the explicit close errored. - if let Err(e) = self + match self .http_client .execute(request, RequestType::CloseStatement) .await { - crate::klog::warn!( - statement_id = %statement_id, - error = %e, - "close_statement failed after HTTP retries; surfacing to caller (Drop fallback close will run)" - ); - return Err(e); + Ok(response) => discard_body(response).await, + Err(e) => { + crate::klog::warn!( + statement_id = %statement_id, + error = %e, + "close_statement failed after HTTP retries; surfacing to caller (Drop fallback close will run)" + ); + return Err(e); + } } debug!("Closed statement: {}", statement_id); @@ -2817,6 +2830,59 @@ mod tests { .all(|request| request.headers.get(REALTIME_SESSION_HEADER).is_none())); } + /// Close and cancel replies are `{}` sent chunked, and a server may flush + /// the body after the headers. Their connections must still be reused. + #[tokio::test] + async fn close_and_cancel_reuse_the_connection() { + use std::sync::atomic::AtomicUsize; + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + let accepted = Arc::new(AtomicUsize::new(0)); + let accepted_by_server = Arc::clone(&accepted); + tokio::spawn(async move { + loop { + let Ok((mut socket, _)) = listener.accept().await else { + return; + }; + accepted_by_server.fetch_add(1, Ordering::SeqCst); + tokio::spawn(async move { + let mut buf = Vec::new(); + let mut chunk = [0u8; 1024]; + loop { + // These requests carry no body: a request ends at the blank line. + while !buf.windows(4).any(|w| w == b"\r\n\r\n") { + match socket.read(&mut chunk).await { + Ok(0) | Err(_) => return, + Ok(n) => buf.extend_from_slice(&chunk[..n]), + } + } + let end = buf.windows(4).position(|w| w == b"\r\n\r\n").unwrap() + 4; + buf.drain(..end); + let head = b"HTTP/1.1 200 OK\r\ncontent-type: application/json\r\n\ + transfer-encoding: chunked\r\n\r\n"; + if socket.write_all(head).await.is_err() || socket.flush().await.is_err() { + return; + } + tokio::time::sleep(std::time::Duration::from_millis(20)).await; + if socket.write_all(b"2\r\n{}\r\n0\r\n\r\n").await.is_err() { + return; + } + } + }); + } + }); + + let transport = create_test_client_against(&format!("http://{addr}")); + transport.close_statement("statement-1").await.unwrap(); + transport.close_statement("statement-2").await.unwrap(); + transport.cancel_statement("statement-3").await.unwrap(); + transport.close_statement("statement-3").await.unwrap(); + + assert_eq!(accepted.load(Ordering::SeqCst), 1); + } + #[tokio::test] async fn create_session_response_selects_session_statement_urls() { use wiremock::matchers::{body_json, method, path, query_param}; From 6c4977bdaa41ac9bca8549801cbc258999b1562a Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Fri, 13 Nov 2026 20:03:16 +0000 Subject: [PATCH 2/3] perf(client): bound the close/cancel body drain Wait at most 500 ms for the reply body, so a stalled body no longer holds a close or cancel that already succeeded until the request timeout; after the bound the connection is dropped as before. Co-authored-by: Isaac Signed-off-by: Vu Anh Phung --- src/client/sea.rs | 56 +++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 47 insertions(+), 9 deletions(-) diff --git a/src/client/sea.rs b/src/client/sea.rs index 981c5c70..158102ce 100644 --- a/src/client/sea.rs +++ b/src/client/sea.rs @@ -1057,12 +1057,17 @@ impl SeaRestTransport { } } +/// How long a close/cancel waits for its (`{}`) reply body before giving up. +const DISCARD_BODY_TIMEOUT: std::time::Duration = std::time::Duration::from_millis(500); + /// Read a response body we don't need to its end. Over HTTP/1.1 hyper can only /// return a connection to the pool once the body has been read, so dropping /// the (`{}`) body of a close/cancel reply would make the next request open a -/// new TCP/TLS connection. The call already succeeded, so a read error is ignored. +/// new TCP/TLS connection. The call already succeeded, so a read error is +/// ignored, and a stalled body is dropped after [`DISCARD_BODY_TIMEOUT`] +/// (losing only the connection) rather than delaying the caller. async fn discard_body(response: reqwest::Response) { - let _ = response.bytes().await; + let _ = tokio::time::timeout(DISCARD_BODY_TIMEOUT, response.bytes()).await; } /// Convert a parsed `GetChunksResponse` into the kernel-facing @@ -2830,16 +2835,17 @@ mod tests { .all(|request| request.headers.get(REALTIME_SESSION_HEADER).is_none())); } - /// Close and cancel replies are `{}` sent chunked, and a server may flush - /// the body after the headers. Their connections must still be reused. - #[tokio::test] - async fn close_and_cancel_reuse_the_connection() { - use std::sync::atomic::AtomicUsize; + /// Serves every request with chunked `{}` headers, then sends the body after + /// `body_delay` (never, if `None`). Returns the address and an accepted- + /// connection counter. + async fn spawn_close_reply_server( + body_delay: Option, + ) -> (std::net::SocketAddr, Arc) { use tokio::io::{AsyncReadExt, AsyncWriteExt}; let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); let addr = listener.local_addr().unwrap(); - let accepted = Arc::new(AtomicUsize::new(0)); + let accepted = Arc::new(std::sync::atomic::AtomicUsize::new(0)); let accepted_by_server = Arc::clone(&accepted); tokio::spawn(async move { loop { @@ -2865,7 +2871,12 @@ mod tests { if socket.write_all(head).await.is_err() || socket.flush().await.is_err() { return; } - tokio::time::sleep(std::time::Duration::from_millis(20)).await; + let Some(delay) = body_delay else { + // Stall: hold the connection open without a body. + let _ = socket.read(&mut chunk).await; + return; + }; + tokio::time::sleep(delay).await; if socket.write_all(b"2\r\n{}\r\n0\r\n\r\n").await.is_err() { return; } @@ -2873,6 +2884,15 @@ mod tests { }); } }); + (addr, accepted) + } + + /// Close and cancel replies are `{}` sent chunked, and a server may flush + /// the body after the headers. Their connections must still be reused. + #[tokio::test] + async fn close_and_cancel_reuse_the_connection() { + let (addr, accepted) = + spawn_close_reply_server(Some(std::time::Duration::from_millis(20))).await; let transport = create_test_client_against(&format!("http://{addr}")); transport.close_statement("statement-1").await.unwrap(); @@ -2883,6 +2903,24 @@ mod tests { assert_eq!(accepted.load(Ordering::SeqCst), 1); } + /// A body that never arrives must not hold up a close/cancel that already + /// succeeded beyond the short drain bound. + #[tokio::test] + async fn close_and_cancel_do_not_wait_for_a_stalled_body() { + let (addr, _) = spawn_close_reply_server(None).await; + + let transport = create_test_client_against(&format!("http://{addr}")); + let started = std::time::Instant::now(); + transport.close_statement("statement-1").await.unwrap(); + transport.cancel_statement("statement-2").await.unwrap(); + + assert!( + started.elapsed() < 2 * DISCARD_BODY_TIMEOUT + std::time::Duration::from_secs(2), + "took {:?}", + started.elapsed() + ); + } + #[tokio::test] async fn create_session_response_selects_session_statement_urls() { use wiremock::matchers::{body_json, method, path, query_param}; From 4dc6d91982036e9be35f03711f11f47627148db1 Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Fri, 13 Nov 2026 20:37:43 +0000 Subject: [PATCH 3/3] test(client): pause between calls in the connection-reuse test hyper returns an idle HTTP/1 connection to the pool from a spawned task, so let it run before the next call instead of relying on scheduling order. Co-authored-by: Isaac Signed-off-by: Vu Anh Phung --- src/client/sea.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/client/sea.rs b/src/client/sea.rs index 158102ce..df855d56 100644 --- a/src/client/sea.rs +++ b/src/client/sea.rs @@ -2895,9 +2895,15 @@ mod tests { spawn_close_reply_server(Some(std::time::Duration::from_millis(20))).await; let transport = create_test_client_against(&format!("http://{addr}")); + // hyper returns an idle HTTP/1 connection to the pool from a spawned + // task; pause between calls so the next one can't race ahead of it. + let pause = || tokio::time::sleep(std::time::Duration::from_millis(10)); transport.close_statement("statement-1").await.unwrap(); + pause().await; transport.close_statement("statement-2").await.unwrap(); + pause().await; transport.cancel_statement("statement-3").await.unwrap(); + pause().await; transport.close_statement("statement-3").await.unwrap(); assert_eq!(accepted.load(Ordering::SeqCst), 1);