diff --git a/CHANGELOG.md b/CHANGELOG.md index aca699b1..ce2b08bd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -25,6 +25,19 @@ cadences and may not move in lockstep with the crate. tables server-side). ### Fixed +- **CloudFetch download timeout** — a stalled cloud-storage response no + longer hangs the result stream indefinitely. The chunk downloader now + bounds each HTTP GET + body read with a per-chunk deadline + (`CloudFetchConfig::download_timeout`, default 5 minutes via + `DEFAULT_DOWNLOAD_TIMEOUT_SECS`), returning a retriable timeout on expiry + so the provider retry loop can react. The deadline is per *attempt*: the + retry loop re-applies it on each retry, so the worst-case bound for a + repeatedly-stalling chunk is `max_retries * download_timeout`. reqwest's + client-level timeout only covers the header phase, not the + separately-awaited `response.bytes()`, which previously let a wedged read + block for the full CI job window. 5 min matches the ADBC C# driver default; + the Python (Thrift) driver uses a 60s between-bytes read timeout for the + same purpose. - **Metadata conformance (catalog match-all wildcard)** — a *literal* catalog `%`, `*`, or `""` reaching `Metadata::list_schemas` / `list_tables` is now scoped verbatim (`SHOW … IN [CATALOG] \`%\``) and diff --git a/src/reader/cloudfetch/chunk_downloader.rs b/src/reader/cloudfetch/chunk_downloader.rs index b0aa8ac9..31fa3846 100644 --- a/src/reader/cloudfetch/chunk_downloader.rs +++ b/src/reader/cloudfetch/chunk_downloader.rs @@ -28,7 +28,7 @@ use crate::types::sea::CompressionCodec; use arrow_array::RecordBatch; use reqwest::Method; use std::sync::Arc; -use std::time::Instant; +use std::time::{Duration, Instant}; /// Downloads Arrow data from cloud storage presigned URLs. /// @@ -42,6 +42,7 @@ pub struct ChunkDownloader { http_client: Arc, compression: CompressionCodec, speed_threshold_mbps: f64, + download_timeout: Duration, } impl ChunkDownloader { @@ -51,15 +52,22 @@ impl ChunkDownloader { /// * `http_client` - HTTP client for making requests /// * `compression` - Compression codec used by the server /// * `speed_threshold_mbps` - Log warning if speed falls below this (MB/s) + /// * `download_timeout` - Per-*attempt* download deadline (HTTP GET + body + /// read); a stall that exceeds it fails with a retriable timeout rather + /// than hanging. Because the provider retry loop re-invokes `download()` + /// with a fresh deadline each time, the worst-case bound for a single + /// chunk that keeps stalling is `max_retries * download_timeout`. pub fn new( http_client: Arc, compression: CompressionCodec, speed_threshold_mbps: f64, + download_timeout: Duration, ) -> Self { Self { http_client, compression, speed_threshold_mbps, + download_timeout, } } @@ -89,17 +97,35 @@ impl ChunkDownloader { .build() .map_err(|e| Error::io().message(format!("Failed to build download request: {}", e)))?; - // Execute without auth (presigned URLs have their own auth) - let response = self - .http_client - .execute_without_auth(request, RequestType::CloudFetchDownload) - .await?; - - // Read response body - let bytes = response - .bytes() - .await - .map_err(|e| Error::io().message(format!("Failed to read download response: {}", e)))?; + // Bound the whole HTTP GET + body read with a per-chunk deadline so a + // stalled cloud-storage response fails with a retriable timeout rather + // than hanging the result stream. reqwest's client-level timeout only + // covers `execute()` (the header phase); the separately-awaited + // `response.bytes()` below is where a wedged blob read would otherwise + // block indefinitely (the reyden nightly hang). Mirrors the ADBC C# + // driver's per-download deadline. + let download_fut = async { + // Execute without auth (presigned URLs have their own auth) + let response = self + .http_client + .execute_without_auth(request, RequestType::CloudFetchDownload) + .await?; + + // Read response body + response.bytes().await.map_err(|e| { + Error::io().message(format!("Failed to read download response: {}", e)) + }) + }; + + let bytes = match tokio::time::timeout(self.download_timeout, download_fut).await { + Ok(result) => result?, + Err(_elapsed) => { + return Err(Error::timeout().message(format!( + "CloudFetch chunk {} download exceeded {:?} timeout (url {})", + link.chunk_index, self.download_timeout, link.url + ))); + } + }; let elapsed = start.elapsed(); let size_mb = bytes.len() as f64 / 1024.0 / 1024.0; @@ -221,11 +247,92 @@ mod tests { ); let auth = Arc::new(PersonalAccessToken::new("test-token".to_string())); http_client.set_auth_provider(auth); - let downloader = ChunkDownloader::new(http_client, CompressionCodec::None, 0.1); + let downloader = ChunkDownloader::new( + http_client, + CompressionCodec::None, + 0.1, + Duration::from_secs(300), + ); assert_eq!(downloader.speed_threshold_mbps, 0.1); } + /// A stalled cloud-storage response must fail with a timeout within the + /// configured per-chunk `download_timeout`, not hang. Regression for the + /// reyden nightly where a fault-injected CloudFetch stall wedged + /// `response.bytes()` for ~52 min until the CI job cap killed it. + /// + /// The wedge the fix targets is specifically the *body read*: reqwest's + /// client-level timeout covers `execute()` (headers), while the + /// separately-awaited `response.bytes()` is where a stalled blob read + /// blocks (see the comment on `download`). So this test must reproduce + /// that phase, not just a slow header response — a raw TCP server sends + /// the status line + `Content-Length` headers immediately, then stalls + /// mid-body forever. `execute()` therefore returns promptly and it is the + /// body read that hangs until the per-chunk `tokio::time::timeout` fires. + #[tokio::test] + async fn download_times_out_when_response_body_stalls() { + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + use tokio::net::TcpListener; + + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + + // Accept one connection, flush headers promising a body we never + // finish sending, then hold the socket open so the body read wedges. + tokio::spawn(async move { + if let Ok((mut socket, _)) = listener.accept().await { + // Drain the request line/headers so the client can proceed. + let mut buf = [0u8; 1024]; + let _ = socket.read(&mut buf).await; + // Headers flushed immediately: execute() completes here. + let _ = socket + .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 1048576\r\n\r\n") + .await; + let _ = socket.flush().await; + // A few body bytes, then stall indefinitely: bytes() hangs. + let _ = socket.write_all(b"partial").await; + let _ = socket.flush().await; + tokio::time::sleep(Duration::from_secs(60)).await; + } + }); + + let http_client = Arc::new( + DatabricksHttpClient::with_default_retry(HttpClientConfig::default()).unwrap(), + ); + http_client.set_auth_provider(Arc::new(PersonalAccessToken::new("test-token".to_string()))); + + // Tiny per-chunk timeout so the test resolves quickly. + let downloader = ChunkDownloader::new( + http_client, + CompressionCodec::None, + 0.1, + Duration::from_millis(200), + ); + + let link = CloudFetchLink { + url: format!("http://{}/chunk0", addr), + ..create_test_link() + }; + + let start = Instant::now(); + let result = downloader.download(&link).await; + let elapsed = start.elapsed(); + + assert!(result.is_err(), "a stalled download must error, not hang"); + assert!( + elapsed < Duration::from_secs(3), + "download must give up near its 200ms timeout, took {:?}", + elapsed + ); + let err = result.unwrap_err(); + assert!( + err.to_string().to_lowercase().contains("timeout") + || err.to_string().to_lowercase().contains("timed out"), + "error should indicate a timeout, got: {err}" + ); + } + // Note: Full download tests require mocking the HTTP layer // Integration tests should be added in a separate test module diff --git a/src/reader/cloudfetch/streaming_provider.rs b/src/reader/cloudfetch/streaming_provider.rs index 4de607eb..df247b63 100644 --- a/src/reader/cloudfetch/streaming_provider.rs +++ b/src/reader/cloudfetch/streaming_provider.rs @@ -1455,6 +1455,7 @@ mod tests { http_client, CompressionCodec::None, 0.1, + std::time::Duration::from_secs(300), )); #[derive(Debug)] diff --git a/src/reader/mod.rs b/src/reader/mod.rs index 5e0328de..ce629ffa 100644 --- a/src/reader/mod.rs +++ b/src/reader/mod.rs @@ -463,6 +463,7 @@ impl ResultReaderFactory { self.http_client.clone(), compression, self.config.speed_threshold_mbps, + self.config.download_timeout, )); let provider = StreamingCloudFetchProvider::new( diff --git a/src/types/cloudfetch.rs b/src/types/cloudfetch.rs index 56406ed9..f8fd3fcf 100644 --- a/src/types/cloudfetch.rs +++ b/src/types/cloudfetch.rs @@ -33,6 +33,21 @@ pub const LINK_EXPIRY_BUFFER_SECS: i64 = 30; /// Used as a fallback when `chunk_ready_timeout` is not configured. pub const DEFAULT_CHUNK_READY_TIMEOUT_SECS: u64 = 30; +/// Default per-chunk download timeout (in seconds). +/// +/// Bounds a single CloudFetch chunk download (HTTP GET + body read) so a +/// stalled cloud-storage response fails with a retriable timeout instead of +/// hanging the whole result stream. Without it, `response.bytes()` on a +/// wedged connection blocks indefinitely — see the reyden nightly hang. Set +/// to 5 minutes to match the ADBC C# driver's default download timeout; the +/// Python (Thrift) driver uses a 60s between-bytes read timeout for the same +/// purpose. This is a total per-attempt deadline (not idle-based), so a +/// genuinely large chunk must complete within it. Note it bounds a single +/// attempt: the provider retry loop re-applies a fresh deadline per attempt, +/// so the worst-case bound for a repeatedly-stalling chunk is +/// `max_retries * download_timeout`. +pub const DEFAULT_DOWNLOAD_TIMEOUT_SECS: u64 = 300; + /// Configuration for CloudFetch streaming. #[derive(Debug, Clone)] pub struct CloudFetchConfig { @@ -46,6 +61,12 @@ pub struct CloudFetchConfig { pub retry_delay: Duration, /// Timeout for waiting for a chunk to be ready. pub chunk_ready_timeout: Option, + /// Per-*attempt* download timeout (HTTP GET + body read). A stalled + /// download that exceeds this fails with a retriable timeout rather than + /// hanging; the retry loop re-applies it per attempt, so the worst-case + /// bound for a repeatedly-stalling chunk is `max_retries * download_timeout`. + /// Defaults to [`DEFAULT_DOWNLOAD_TIMEOUT_SECS`]. + pub download_timeout: Duration, /// Log warning if download speed falls below this threshold (MB/s). pub speed_threshold_mbps: f64, /// Whether CloudFetch is enabled. @@ -72,6 +93,7 @@ impl Default for CloudFetchConfig { max_retries: 5, retry_delay: Duration::from_millis(1500), chunk_ready_timeout: Some(Duration::from_secs(30)), + download_timeout: Duration::from_secs(DEFAULT_DOWNLOAD_TIMEOUT_SECS), speed_threshold_mbps: 0.1, enabled: true, batch_merge_target_rows: 0,