From 59d985042b55604eaf5e5f51f81608cacd41ab99 Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Thu, 26 Nov 2026 19:12:54 +0000 Subject: [PATCH] perf(cloudfetch): overlap request headers ahead of body admission Signed-off-by: Vu Anh Phung Co-authored-by: Isaac --- CONNECTION_PARAMETERS.md | 2 + NEXT_CHANGELOG.md | 2 + include/databricks_kernel.h | 5 + napi/src/database.rs | 5 +- pyo3/src/session.rs | 6 +- src/config.rs | 47 ++ src/reader/cloudfetch/chunk_downloader.rs | 76 ++- src/reader/cloudfetch/streaming_provider.rs | 607 +++++++++++++++++--- src/session.rs | 62 +- src/types/cloudfetch.rs | 3 + 10 files changed, 722 insertions(+), 93 deletions(-) diff --git a/CONNECTION_PARAMETERS.md b/CONNECTION_PARAMETERS.md index 2a11227d..362038e0 100644 --- a/CONNECTION_PARAMETERS.md +++ b/CONNECTION_PARAMETERS.md @@ -173,6 +173,7 @@ Setting only one of `client_cert_pem` / `client_key_pem` is rejected at | `cloudfetch_enabled` | Opt into CloudFetch (cloud-storage-backed download of large results via presigned URLs). Set `false` to force the inline-Arrow path (mirrors JDBC `EnableQueryResultDownload=0`). | `true` | | `cloudfetch_link_prefetch_window` | Number of presigned URLs to prefetch ahead of the consumer. | `10` | | `cloudfetch_max_chunks_in_memory` | Max decompressed CloudFetch chunks held in memory at once (bounds download parallelism and peak RSS). | `16` | +| `cloudfetch_download_ahead` | Extra CloudFetch GETs ahead of the decoded window (0–16, capped at the window). Bodies wait for admission; socket memory increases. Explicit `0` disables, overriding the connector-service flag. | Unspecified (missing flag: `0`) | | `inline_max_chunks_in_memory` | Prefetch window for the inline-Arrow path (used when CloudFetch is disabled). `1` disables prefetching. | `4` | | `complex_types_as_json` | Render complex columns (`ARRAY` / `MAP` / `STRUCT` / `VARIANT`) as compact JSON strings instead of native Arrow nested types. Top-level geo columns use `geospatial_result_representation`; nested geo leaves are normalized before the enclosing value is rendered as JSON. | `false` | | `intervals_as_string` | Render `INTERVAL` / `DURATION` columns as canonical Databricks text (e.g. `"Y-M"`, `"D HH:MM:SS.nnnnnnnnn"`) instead of native Arrow interval types. | `false` | @@ -259,6 +260,7 @@ Each key mirrors a field of [`ResultConfig`](#resultconfig--result-handling-opti | `cloudfetch_enabled` | Same knob as `ResultConfig::cloudfetch_enabled` — opt into CloudFetch (`false` forces the inline-Arrow path). | `true` | | `cloudfetch_link_prefetch_window` | Same knob as `ResultConfig::cloudfetch_link_prefetch_window` — number of presigned URLs to prefetch ahead of the consumer. | `10` | | `cloudfetch_max_chunks_in_memory` | Same knob as `ResultConfig::cloudfetch_max_chunks_in_memory` — max decompressed CloudFetch chunks held in memory at once. Values above `256` are clamped (with a warning) rather than rejected (peak RSS scales with this, so the ceiling bounds OOM risk). | `16` | +| `cloudfetch_download_ahead` | Same knob as `ResultConfig::cloudfetch_download_ahead`: integer 0–16; explicit zero disables. Also accepted through Python/Node `session_conf` (stripped before server transmission). Extra requests consume socket memory; decoded window is unchanged. | Unspecified (missing flag: `0`) | | `inline_max_chunks_in_memory` | Same knob as `ResultConfig::inline_max_chunks_in_memory` — prefetch window for the inline-Arrow path. `1` disables prefetching. | `4` | | `complex_types_as_json` | Same knob as `ResultConfig::complex_types_as_json` — render complex columns as compact JSON strings instead of native Arrow nested types. | `false` | | `intervals_as_string` | Same knob as `ResultConfig::intervals_as_string` — render `INTERVAL` / `DURATION` columns as canonical Databricks text instead of native Arrow interval types. | `false` | diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index 2ebce050..d2119022 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -11,6 +11,8 @@ changes go in their respective binding's NEXT_CHANGELOG. ### Added +- Opt-in CloudFetch request-ahead overlaps download headers without enlarging the decoded chunk window. Defaults remain unchanged. + ### Changed ### Updated diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h index e167f181..ebb0a01e 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -335,6 +335,10 @@ kernel_session_config_set_oauth_scopes(KernelSessionConfig* config, * consumed before session creation, and NEVER reach the wire. Client-only keys * (matched case-insensitively): * + * cloudfetch_download_ahead — integer 0..16, extra GETs ahead of the decoded + * window (capped at that window). Bodies wait for admission; socket memory + * increases. Unspecified defers to the server flag (missing means 0); + * explicit 0 disables, overriding the flag. * cloudfetch_max_chunks_in_memory — positive integer; how many decompressed * CloudFetch chunks the kernel holds in memory at once (bounds peak RSS on * large result sets; default 16). A value above the kernel ceiling (256) is @@ -597,6 +601,7 @@ KernelStatusCode kernel_session_config_set_u2m_token_cache_config(KernelSessionC * - "cloudfetch_enabled" = "true"|"false" — false serves every result * through paged inline delivery without cloud-storage downloads. * - "cloudfetch_link_prefetch_window" = positive integer. + * - "cloudfetch_download_ahead" = integer 0..16 (extra GETs; explicit 0 disables) * - "cloudfetch_max_chunks_in_memory" = positive integer (bounds peak RSS; * values above the kernel ceiling of 256 are clamped with a warning). * - "inline_max_chunks_in_memory" = positive integer (inline-Arrow prefetch diff --git a/napi/src/database.rs b/napi/src/database.rs index 4a8fbe3f..42fc3c8c 100644 --- a/napi/src/database.rs +++ b/napi/src/database.rs @@ -230,7 +230,10 @@ pub struct ConnectionOptions { pub schema: Option, /// Server-bound session conf (Spark conf, `ANSI_MODE`, `TIMEZONE`, /// query-tag presets, …). Forwarded verbatim to SEA - /// `session_confs`. Unknown keys are rejected server-side. + /// `session_confs`. `cloudfetch_download_ahead` (integer string 0..16) is + /// client-only and stripped: explicit zero disables, unspecified defers to + /// the server flag (default 0). Extra GETs consume socket memory without + /// enlarging the decoded window. Other unknown keys are rejected server-side. pub session_conf: Option>, /// Select whether `GEOMETRY` / `GEOGRAPHY` results use their native Arrow /// representation. `true` (the default) requests Arrow diff --git a/pyo3/src/session.rs b/pyo3/src/session.rs index c626ee89..d3d4e3b3 100644 --- a/pyo3/src/session.rs +++ b/pyo3/src/session.rs @@ -333,7 +333,11 @@ impl Session { /// which always take precedence; a caller header for either of those /// names is ignored. /// - /// `session_conf` is the server-bound session configuration map + /// `session_conf` also accepts `cloudfetch_download_ahead` (integer 0..16). + /// This client-only knob is stripped before transmission. Explicit zero + /// disables request-ahead; unspecified defers to the server flag (default 0). + /// Extra GETs consume socket memory without enlarging the decoded window. + /// `session_conf` is otherwise the server-bound session configuration map /// — passed through to SEA `session_confs` verbatim. Use for /// `ANSI_MODE`, `TIMEZONE`, `STATEMENT_TIMEOUT`, query-tag /// presets, etc. The kernel does not validate keys; the server diff --git a/src/config.rs b/src/config.rs index 9c1eb0a9..dae39542 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1102,6 +1102,11 @@ pub struct ResultConfig { /// Bounds parallelism and peak RSS. pub cloudfetch_max_chunks_in_memory: usize, + /// Extra CloudFetch GETs allowed ahead of the decoded chunk window (0..=16). + /// Bodies remain unread until admitted. Increases socket memory, not the + /// decoded window. None defers to the server flag (missing flag means 0). + pub cloudfetch_download_ahead: Option, + /// Maximum number of decompressed Arrow chunks the inline-Arrow /// streaming reader holds in memory at once. Analogue of /// [`Self::cloudfetch_max_chunks_in_memory`] for paged inline results. @@ -1159,6 +1164,7 @@ impl Default for ResultConfig { cloudfetch_enabled: true, cloudfetch_link_prefetch_window: 10, cloudfetch_max_chunks_in_memory: 16, + cloudfetch_download_ahead: None, inline_max_chunks_in_memory: 4, complex_types_as_json: false, intervals_as_string: false, @@ -1190,6 +1196,7 @@ pub(crate) enum ClientConfKey { CloudfetchEnabled, CloudfetchLinkPrefetchWindow, CloudfetchMaxChunksInMemory, + CloudfetchDownloadAhead, InlineMaxChunksInMemory, ComplexTypesAsJson, IntervalsAsString, @@ -1202,6 +1209,7 @@ impl ClientConfKey { Self::CloudfetchEnabled, Self::CloudfetchLinkPrefetchWindow, Self::CloudfetchMaxChunksInMemory, + Self::CloudfetchDownloadAhead, Self::InlineMaxChunksInMemory, Self::ComplexTypesAsJson, Self::IntervalsAsString, @@ -1213,6 +1221,7 @@ impl ClientConfKey { Self::CloudfetchEnabled => "cloudfetch_enabled", Self::CloudfetchLinkPrefetchWindow => "cloudfetch_link_prefetch_window", Self::CloudfetchMaxChunksInMemory => "cloudfetch_max_chunks_in_memory", + Self::CloudfetchDownloadAhead => "cloudfetch_download_ahead", Self::InlineMaxChunksInMemory => "inline_max_chunks_in_memory", Self::ComplexTypesAsJson => "complex_types_as_json", Self::IntervalsAsString => "intervals_as_string", @@ -1318,6 +1327,19 @@ impl ResultConfig { ClientConfKey::InlineMaxChunksInMemory => { self.inline_max_chunks_in_memory = parse_positive_usize(value)?; } + ClientConfKey::CloudfetchDownloadAhead => { + let lead = value + .trim() + .parse::() + .ok() + .filter(|lead| *lead <= 16) + .ok_or_else(|| { + crate::kernel_error::Error::invalid_argument().message( + "client conf 'cloudfetch_download_ahead' expects an integer in 0..=16", + ) + })?; + self.cloudfetch_download_ahead = Some(lead); + } ClientConfKey::ComplexTypesAsJson => { self.complex_types_as_json = parse_bool(value)?; } @@ -1577,6 +1599,31 @@ pub struct SessionConfig { mod tests { use super::*; + #[test] + fn download_ahead_client_conf_validates_without_overwriting_on_error() { + let mut result = ResultConfig::default(); + assert_eq!(result.cloudfetch_download_ahead, None); + for lead in ["0", "8", "16"] { + result + .apply_client_conf("CLOUDFETCH_DOWNLOAD_AHEAD", lead) + .unwrap(); + assert_eq!( + result.cloudfetch_download_ahead, + Some(lead.parse().unwrap()) + ); + } + for invalid in ["", "17", "-1", "1.5", "true", "18446744073709551616"] { + assert_eq!( + result + .apply_client_conf("cloudfetch_download_ahead", invalid) + .unwrap_err() + .code, + crate::ErrorCode::InvalidArgument + ); + assert_eq!(result.cloudfetch_download_ahead, Some(16)); + } + } + #[test] fn geospatial_result_representation_defaults_to_binary() { assert_eq!( diff --git a/src/reader/cloudfetch/chunk_downloader.rs b/src/reader/cloudfetch/chunk_downloader.rs index f22de8b9..ef2b3c38 100644 --- a/src/reader/cloudfetch/chunk_downloader.rs +++ b/src/reader/cloudfetch/chunk_downloader.rs @@ -30,6 +30,22 @@ use reqwest::Method; use std::sync::Arc; use std::time::{Duration, Instant}; +pub(crate) struct PreparedDownload { + response: reqwest::Response, + link: CloudFetchLink, + started: Instant, + headers_elapsed: Duration, + timeout: Duration, +} + +impl PreparedDownload { + pub(crate) fn matches(&self, link: &CloudFetchLink) -> bool { + self.link.url == link.url + && self.link.http_headers == link.http_headers + && self.started.elapsed() < self.timeout + } +} + /// Downloads Arrow data from cloud storage presigned URLs. /// /// Handles: @@ -86,6 +102,20 @@ impl ChunkDownloader { link: &CloudFetchLink, attempt_timeout: Option, ) -> Result> { + let prepared = self.prepare(link, attempt_timeout).await?; + let elapsed = prepared.headers_elapsed; + let start = Instant::now(); + let bytes = prepared.response.bytes().await.map_err(|error| { + Error::io().message(format!("Failed to read download response: {}", error)) + })?; + self.decode(link, &bytes, elapsed + start.elapsed()) + } + + pub(crate) async fn prepare( + &self, + link: &CloudFetchLink, + attempt_timeout: Option, + ) -> Result { let start = Instant::now(); debug!( @@ -123,13 +153,45 @@ impl ChunkDownloader { .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)))?; + Ok(PreparedDownload { + response, + link: link.clone(), + started: start, + headers_elapsed: start.elapsed(), + timeout: attempt_timeout + .unwrap_or(self.http_client.config().read_timeout) + .min(self.http_client.config().read_timeout), + }) + } - let elapsed = start.elapsed(); + pub(crate) async fn download_prepared( + &self, + link: &CloudFetchLink, + prepared: PreparedDownload, + attempt_timeout: Option, + ) -> Result<(Vec, Duration)> { + let headers_elapsed = prepared.headers_elapsed; + let start = Instant::now(); + match prepared.response.bytes().await { + Ok(bytes) => self + .decode(link, &bytes, headers_elapsed + start.elapsed()) + .map(|batches| (batches, headers_elapsed)), + Err(_) => self + .download( + link, + attempt_timeout.map(|timeout| timeout.saturating_sub(start.elapsed())), + ) + .await + .map(|batches| (batches, Duration::ZERO)), + } + } + + fn decode( + &self, + link: &CloudFetchLink, + bytes: &[u8], + elapsed: Duration, + ) -> Result> { let size_mb = bytes.len() as f64 / 1024.0 / 1024.0; let speed_mbps = size_mb / elapsed.as_secs_f64(); @@ -149,7 +211,7 @@ impl ChunkDownloader { } // Parse Arrow IPC data - let batches = parse_arrow_ipc(&bytes, self.compression)?; + let batches = parse_arrow_ipc(bytes, self.compression)?; debug!( "Parsed chunk {}: {} batches, {} total rows", diff --git a/src/reader/cloudfetch/streaming_provider.rs b/src/reader/cloudfetch/streaming_provider.rs index fc38026f..8fc89d07 100644 --- a/src/reader/cloudfetch/streaming_provider.rs +++ b/src/reader/cloudfetch/streaming_provider.rs @@ -22,7 +22,7 @@ use crate::kernel_error::{Error, ErrorCode, Result}; use crate::klog::{debug, error, info, warn}; -use crate::reader::cloudfetch::chunk_downloader::ChunkDownloader; +use crate::reader::cloudfetch::chunk_downloader::{ChunkDownloader, PreparedDownload}; use crate::reader::cloudfetch::link_fetcher::ChunkLinkFetcher; use crate::reader::ResultReaderMetrics; use crate::types::cloudfetch::{ @@ -120,7 +120,9 @@ pub struct StreamingCloudFetchProvider { schema: OnceLock, // Consumer state - current_chunk_index: AtomicI64, + current_chunk_index: Arc, + admission_changed: Arc, + download_ahead: usize, current_batch_buffer: Mutex>, // Download scheduling state @@ -219,6 +221,7 @@ struct RefreshCoordinator { /// `CancellationToken` / `Copy`. #[derive(Clone)] struct DownloadCtx { + admission: Option>, downloader: Arc, link_fetcher: Arc, chunks: Arc>, @@ -235,6 +238,31 @@ struct DownloadCtx { download_timeout: std::time::Duration, } +struct DownloadAdmission { + current: Arc, + changed: Arc, + window: usize, +} + +struct AheadDownload { + link: crate::types::cloudfetch::CloudFetchLink, + request: futures::future::BoxFuture<'static, Result>, +} + +impl DownloadAdmission { + async fn wait(&self, index: i64) { + loop { + let notified = self.changed.notified(); + tokio::pin!(notified); + notified.as_mut().enable(); + if index < self.current.load(Ordering::Acquire) + self.window as i64 { + return; + } + notified.await; + } + } +} + #[derive(Debug)] struct CloudFetchMetrics { total_chunks_present: Option, @@ -374,12 +402,21 @@ impl StreamingCloudFetchProvider { runtime_handle: tokio::runtime::Handle, ) -> Arc { let statement_id = link_fetcher.statement_id().map(Arc::from); + let current_chunk_index = Arc::new(AtomicI64::new(0)); + let admission_changed = Arc::new(Notify::new()); + let cancel_token = CancellationToken::new(); + let download_ahead = config + .download_ahead + .min(config.max_chunks_in_memory) + .min(16); let provider = Arc::new(Self { link_fetcher, chunk_downloader, config: config.clone(), schema: OnceLock::new(), - current_chunk_index: AtomicI64::new(0), + current_chunk_index, + admission_changed, + download_ahead, current_batch_buffer: Mutex::new(VecDeque::new()), next_download_index: AtomicI64::new(0), end_of_stream: AtomicBool::new(false), @@ -388,7 +425,7 @@ impl StreamingCloudFetchProvider { max_chunks_in_memory: config.max_chunks_in_memory, chunk_state_changed: Arc::new(Notify::new()), terminal_error: Mutex::new(None), - cancel_token: CancellationToken::new(), + cancel_token, runtime_handle, statement_id, refresh_coordinator: Arc::new(RefreshCoordinator::default()), @@ -423,7 +460,9 @@ impl StreamingCloudFetchProvider { max_chunks_in_memory: config.max_chunks_in_memory, config, schema: OnceLock::new(), - current_chunk_index: AtomicI64::new(0), + current_chunk_index: Arc::new(AtomicI64::new(0)), + admission_changed: Arc::new(Notify::new()), + download_ahead: 0, current_batch_buffer: Mutex::new(VecDeque::new()), next_download_index: AtomicI64::new(0), end_of_stream: AtomicBool::new(end_of_stream), @@ -663,6 +702,7 @@ impl StreamingCloudFetchProvider { fn advance_chunk(&self) -> (usize, i64) { let new_count = self.chunks_in_memory.fetch_sub(1, Ordering::Release) - 1; let next_chunk = self.current_chunk_index.fetch_add(1, Ordering::Release) + 1; + self.admission_changed.notify_waiters(); self.metrics.record_chunk_iterated(); (new_count, next_chunk) } @@ -743,7 +783,7 @@ impl StreamingCloudFetchProvider { loop { // Check if we have room for more downloads let current_in_memory = self.chunks_in_memory.load(Ordering::Acquire); - if current_in_memory >= self.max_chunks_in_memory { + if current_in_memory >= self.max_chunks_in_memory + self.download_ahead { debug!( "Memory limit reached: {}/{} chunks in memory, pausing downloads", current_in_memory, self.max_chunks_in_memory @@ -858,6 +898,13 @@ impl StreamingCloudFetchProvider { // stays clean. let chunk_index = next_index; let ctx = DownloadCtx { + admission: (self.download_ahead > 0).then(|| { + Arc::new(DownloadAdmission { + current: self.current_chunk_index.clone(), + changed: self.admission_changed.clone(), + window: self.max_chunks_in_memory, + }) + }), downloader: Arc::clone(&self.chunk_downloader), link_fetcher: Arc::clone(&self.link_fetcher), chunks: self.chunks.clone(), @@ -882,12 +929,21 @@ impl StreamingCloudFetchProvider { // forever and wedging the whole stream. Surfacing the panic as a // download error lets the reader fail cleanly instead of hanging. let rt = self.runtime_handle.clone(); + let cancel_token = self.cancel_token.clone(); self.runtime_handle.spawn(async move { let result = join_download_task(&rt, async move { Self::download_chunk_with_retry(chunk_index, &ctx).await }) .await; + if cancel_token.is_cancelled() { + if let Some(mut entry) = chunks.get_mut(&chunk_index) { + entry.state = ChunkState::Cancelled; + } + chunk_state_changed.notify_one(); + return; + } + match result { Ok(batches) => { // When batch merging is enabled, merge small batches within @@ -957,6 +1013,7 @@ impl StreamingCloudFetchProvider { ctx: &DownloadCtx, ) -> Result> { let mut attempts = 0; + let mut prepared = Self::prepare_ahead(chunk_index, ctx).await?; // Absolute end-to-end deadline for this chunk. Bounds the whole // retry loop — every HTTP attempt, link refresh, and backoff sleep @@ -1130,13 +1187,55 @@ impl StreamingCloudFetchProvider { // deadline is configured. let download_started = std::time::Instant::now(); let attempt_timeout = deadline.map(|d| d.saturating_duration_since(download_started)); - match ctx.downloader.download(&link, attempt_timeout).await { - Ok(batches) => { - ctx.metrics - .record_chunk_download(chunk_index, download_started.elapsed()); + let download = async { + let response = match prepared.take().filter(|ahead| { + ahead.link.url == link.url && ahead.link.http_headers == link.http_headers + }) { + Some(ahead) => ahead + .request + .await + .ok() + .filter(|response| response.matches(&link)), + None => None, + }; + match response { + Some(response) => { + ctx.downloader + .download_prepared(&link, response, attempt_timeout) + .await + } + None => ctx + .downloader + .download(&link, attempt_timeout) + .await + .map(|batches| (batches, std::time::Duration::ZERO)), + } + }; + let result = tokio::select! { + biased; + _ = ctx.cancel_token.cancelled() => { + return Err(Error::invalid_state().message("Download cancelled")); + } + result = async { + match attempt_timeout { + Some(timeout) => tokio::time::timeout(timeout, download).await + .unwrap_or_else(|_| Err(Self::download_deadline_error(chunk_index, ctx.download_timeout))), + None => download.await, + } + } => result, + }; + match result { + Ok((batches, headers_elapsed)) => { + ctx.metrics.record_chunk_download( + chunk_index, + download_started.elapsed() + headers_elapsed, + ); return Ok(batches); } Err(e) => { + if ctx.cancel_token.is_cancelled() { + return Err(e); + } // Refreshing a signed URL cannot repair certificate verification failures. if e.code == ErrorCode::NetworkError && !e.retryable { return Err(e); @@ -1236,6 +1335,45 @@ impl StreamingCloudFetchProvider { } } + async fn prepare_ahead(chunk_index: i64, ctx: &DownloadCtx) -> Result> { + let Some(admission) = &ctx.admission else { + return Ok(None); + }; + let link = ctx + .chunks + .get(&chunk_index) + .and_then(|entry| entry.link.clone()); + let mut ahead = link.filter(|link| !link.is_expired()).map(|link| { + let downloader = ctx.downloader.clone(); + let request_link = link.clone(); + let timeout = (!ctx.download_timeout.is_zero()).then_some(ctx.download_timeout); + AheadDownload { + link, + request: Box::pin(async move { downloader.prepare(&request_link, timeout).await }), + } + }); + tokio::select! { + biased; + _ = ctx.cancel_token.cancelled() => Err(Error::invalid_state().message("Download cancelled")), + _ = admission.wait(chunk_index) => Ok(ahead), + response = async { + match &mut ahead { + Some(ahead) => ahead.request.as_mut().await, + None => futures::future::pending().await, + } + } => { + if let Some(ahead) = &mut ahead { + ahead.request = Box::pin(std::future::ready(response)); + } + tokio::select! { + biased; + _ = ctx.cancel_token.cancelled() => Err(Error::invalid_state().message("Download cancelled")), + _ = admission.wait(chunk_index) => Ok(ahead), + } + } + } + } + pub(crate) fn metrics(&self) -> Option { let snapshot = self.metrics.snapshot(); // Surface metrics whenever *any* datum was captured, not just @@ -1914,70 +2052,97 @@ mod tests { use wiremock::matchers::{method, path}; use wiremock::{Mock, MockServer, ResponseTemplate}; - let server = MockServer::start().await; - let mut fetcher = MockLinkFetcher::new(8); - for i in 0..8 { - let batch = make_batch(&[i as i32]); - let mut bytes = Vec::new(); - { - let mut writer = StreamWriter::try_new(&mut bytes, &batch.schema()).unwrap(); - writer.write(&batch).unwrap(); - writer.finish().unwrap(); + for lead in [0, 2] { + let server = MockServer::start().await; + let mut fetcher = MockLinkFetcher::new(8); + for i in 0..8 { + let batch = make_batch(&[i as i32]); + let mut bytes = Vec::new(); + { + let mut writer = StreamWriter::try_new(&mut bytes, &batch.schema()).unwrap(); + writer.write(&batch).unwrap(); + writer.finish().unwrap(); + } + let route = format!("/chunk-{i}"); + Mock::given(method("GET")) + .and(path(&route)) + .respond_with(ResponseTemplate::new(200).set_body_bytes(bytes)) + .expect(1) + .mount(&server) + .await; + fetcher.links_by_index.get_mut(&i).unwrap().url = + format!("{}{route}", server.uri()); } - let route = format!("/chunk-{i}"); - Mock::given(method("GET")) - .and(path(&route)) - .respond_with(ResponseTemplate::new(200).set_body_bytes(bytes)) - .expect(1) - .mount(&server) - .await; - fetcher.links_by_index.get_mut(&i).unwrap().url = format!("{}{route}", server.uri()); - } - let fetcher = Arc::new(fetcher); - let client = DatabricksHttpClient::new( - HttpClientConfig::default(), - build_retry_configs( - &RetryConfig { - max_retries: 0, - ..RetryConfig::default() + let fetcher = Arc::new(fetcher); + let client = DatabricksHttpClient::new( + HttpClientConfig::default(), + build_retry_configs( + &RetryConfig { + max_retries: 0, + ..RetryConfig::default() + }, + &HashMap::new(), + ), + ) + .unwrap(); + let provider = StreamingCloudFetchProvider::new( + CloudFetchConfig { + max_chunks_in_memory: 2, + download_ahead: lead, + ..CloudFetchConfig::default() }, - &HashMap::new(), - ), - ) - .unwrap(); - let provider = StreamingCloudFetchProvider::new( - CloudFetchConfig { - max_chunks_in_memory: 2, - ..CloudFetchConfig::default() - }, - fetcher.clone(), - Arc::new(ChunkDownloader::new( - Arc::new(client), - CompressionCodec::None, - 0.1, - )), - Some(8), - tokio::runtime::Handle::current(), - ); - let mut values = Vec::new(); - tokio::time::timeout(std::time::Duration::from_secs(5), async { - while let Some(batch) = provider.next_batch().await.unwrap() { - let ids = batch - .column(0) - .as_any() - .downcast_ref::() - .unwrap(); - values.extend_from_slice(ids.values()); - assert!(provider.chunks_in_memory.load(Ordering::Acquire) <= 2); - } - }) - .await - .expect("all eight chunks must drain with a two-chunk window"); - assert_eq!(values, (0..8).collect::>()); - assert_eq!( - *fetcher.scheduled.lock().unwrap(), - (0..8).collect::>() - ); + fetcher.clone(), + Arc::new(ChunkDownloader::new( + Arc::new(client), + CompressionCodec::None, + 0.1, + )), + Some(8), + tokio::runtime::Handle::current(), + ); + tokio::time::timeout(std::time::Duration::from_secs(2), async { + while server.received_requests().await.unwrap().len() < 2 + lead { + tokio::time::sleep(std::time::Duration::from_millis(1)).await; + } + }) + .await + .expect("request-ahead must start GETs before the consumer releases a chunk"); + assert!( + provider + .chunks + .iter() + .filter(|entry| entry.batches.is_some()) + .count() + <= 2 + ); + let mut values = Vec::new(); + tokio::time::timeout(std::time::Duration::from_secs(5), async { + while let Some(batch) = provider.next_batch().await.unwrap() { + let ids = batch + .column(0) + .as_any() + .downcast_ref::() + .unwrap(); + values.extend_from_slice(ids.values()); + assert!(provider.chunks_in_memory.load(Ordering::Acquire) <= 2 + lead); + assert!( + provider + .chunks + .iter() + .filter(|entry| entry.batches.is_some()) + .count() + <= 2 + ); + } + }) + .await + .expect("all eight chunks must drain with a two-chunk window"); + assert_eq!(values, (0..8).collect::>()); + assert_eq!( + *fetcher.scheduled.lock().unwrap(), + (0..8).collect::>() + ); + } } /// Regression (PECOBLR-4026): a panicking download task must surface as an @@ -2084,6 +2249,7 @@ mod tests { let chunks = Arc::new(DashMap::new()); chunks.insert(0, entry_with_state(fetcher.link(), ChunkState::Downloading)); let ctx = DownloadCtx { + admission: None, downloader, link_fetcher: fetcher, chunks, @@ -2200,6 +2366,7 @@ mod tests { let chunks = Arc::new(DashMap::new()); chunks.insert(0, entry_with_state(fetcher.link(), ChunkState::Downloading)); DownloadCtx { + admission: None, downloader, link_fetcher: fetcher, chunks, @@ -2219,6 +2386,302 @@ mod tests { /// must be cut off by the deadline, not the static request_timeout. /// Without the per-attempt cap this hangs for the client's /// `request_timeout` (default 120s) per attempt. + fn ahead_ctx( + server: &MockServer, + timeout: Duration, + ) -> (DownloadCtx, Arc) { + let mut ctx = ctx_for(server, timeout, CancellationToken::new()); + let admission = Arc::new(DownloadAdmission { + current: Arc::new(AtomicI64::new(-1)), + changed: Arc::new(Notify::new()), + window: 1, + }); + ctx.admission = Some(admission.clone()); + (ctx, admission) + } + + fn nullable_payload() -> (Vec, RecordBatch) { + use arrow_array::{ArrayRef, BooleanArray, Float32Array, Float64Array, Int64Array}; + use arrow_ipc::writer::StreamWriter; + let batch = RecordBatch::try_from_iter(vec![ + ( + "integer", + Arc::new(Int64Array::from(vec![Some(4), None, Some(-9)])) as ArrayRef, + ), + ( + "boolean", + Arc::new(BooleanArray::from(vec![Some(true), None, Some(false)])) as ArrayRef, + ), + ( + "float", + Arc::new(Float32Array::from(vec![Some(1.25), None, Some(-4.5)])) as ArrayRef, + ), + ( + "double", + Arc::new(Float64Array::from(vec![Some(1.125), None, Some(-8.25)])) as ArrayRef, + ), + ]) + .unwrap(); + let mut bytes = Vec::new(); + { + let mut writer = StreamWriter::try_new(&mut bytes, &batch.schema()).unwrap(); + writer.write(&batch).unwrap(); + writer.finish().unwrap(); + } + (bytes, batch) + } + + async fn wait_for_request(server: &MockServer) { + tokio::time::timeout(Duration::from_secs(2), async { + while server.received_requests().await.unwrap().is_empty() { + tokio::time::sleep(Duration::from_millis(1)).await; + } + }) + .await + .unwrap(); + } + + #[tokio::test] + async fn ahead_wait_does_not_spend_download_budget() { + let server = MockServer::start().await; + let (bytes, expected) = nullable_payload(); + Mock::given(method("GET")) + .respond_with(ResponseTemplate::new(200).set_body_bytes(bytes)) + .expect(2) + .mount(&server) + .await; + let (mut ctx, admission) = ahead_ctx(&server, Duration::from_millis(100)); + ctx.chunks + .get_mut(&0) + .unwrap() + .link + .as_mut() + .unwrap() + .row_count = 3; + ctx.max_retries = 1; + let task = tokio::spawn(async move { + StreamingCloudFetchProvider::download_chunk_with_retry(0, &ctx).await + }); + wait_for_request(&server).await; + tokio::time::sleep(Duration::from_millis(220)).await; + assert!( + !task.is_finished(), + "a waiting chunk must not decode or exhaust its budget" + ); + admission.current.store(0, Ordering::Release); + admission.changed.notify_waiters(); + let batches = tokio::time::timeout(Duration::from_secs(2), task) + .await + .unwrap() + .unwrap() + .unwrap(); + assert_eq!(batches, vec![expected]); + } + + #[tokio::test] + async fn ahead_retains_pending_headers_when_admitted() { + let server = MockServer::start().await; + let (bytes, expected) = nullable_payload(); + Mock::given(method("GET")) + .respond_with( + ResponseTemplate::new(200) + .set_body_bytes(bytes) + .set_delay(Duration::from_millis(120)), + ) + .expect(1) + .mount(&server) + .await; + let (ctx, admission) = ahead_ctx(&server, Duration::from_secs(2)); + ctx.chunks + .get_mut(&0) + .unwrap() + .link + .as_mut() + .unwrap() + .row_count = 2; + let task = tokio::spawn(async move { + StreamingCloudFetchProvider::download_chunk_with_retry(0, &ctx).await + }); + wait_for_request(&server).await; + assert!(!task.is_finished()); + admission.current.store(0, Ordering::Release); + admission.changed.notify_waiters(); + let batches = tokio::time::timeout(Duration::from_secs(2), task) + .await + .unwrap() + .unwrap() + .unwrap(); + assert_eq!(batches, vec![expected.slice(0, 2)]); + } + + #[tokio::test] + async fn ahead_refreshes_link_changed_while_waiting() { + let server = MockServer::start().await; + let (bytes, expected) = nullable_payload(); + Mock::given(method("GET")) + .and(path("/chunk-0.arrow")) + .respond_with(ResponseTemplate::new(200).set_body_bytes(b"not arrow".to_vec())) + .expect(1) + .mount(&server) + .await; + Mock::given(method("GET")) + .and(path("/fresh")) + .respond_with(ResponseTemplate::new(200).set_body_bytes(bytes)) + .expect(1) + .mount(&server) + .await; + let (ctx, admission) = ahead_ctx(&server, Duration::from_secs(2)); + let chunks = ctx.chunks.clone(); + let task = tokio::spawn(async move { + StreamingCloudFetchProvider::download_chunk_with_retry(0, &ctx).await + }); + wait_for_request(&server).await; + { + let mut entry = chunks.get_mut(&0).unwrap(); + let link = entry.link.as_mut().unwrap(); + link.url = format!("{}/fresh", server.uri()); + link.row_count = 3; + } + admission.current.store(0, Ordering::Release); + admission.changed.notify_waiters(); + assert_eq!(task.await.unwrap().unwrap(), vec![expected]); + } + + #[tokio::test] + async fn ahead_cancel_releases_parked_response() { + let server = MockServer::start().await; + let (bytes, _) = nullable_payload(); + Mock::given(method("GET")) + .respond_with(ResponseTemplate::new(200).set_body_bytes(bytes)) + .expect(1) + .mount(&server) + .await; + let (ctx, _) = ahead_ctx(&server, Duration::from_secs(2)); + let cancel = ctx.cancel_token.clone(); + let metrics = ctx.metrics.clone(); + let task = tokio::spawn(async move { + StreamingCloudFetchProvider::download_chunk_with_retry(0, &ctx).await + }); + wait_for_request(&server).await; + cancel.cancel(); + let error = tokio::time::timeout(Duration::from_millis(200), task) + .await + .unwrap() + .unwrap() + .unwrap_err(); + assert!(error.message.contains("cancelled")); + assert_eq!(metrics.chunks_downloaded.load(Ordering::Acquire), 0); + } + + #[tokio::test] + async fn ahead_expired_link_is_refreshed_after_admission() { + #[derive(Debug)] + struct FreshLink(CloudFetchLink, Arc); + #[async_trait::async_trait] + impl ChunkLinkFetcher for FreshLink { + async fn fetch_links(&self, _: i64, _: i64) -> Result { + unreachable!() + } + async fn refetch_link(&self, _: i64, _: i64) -> Result { + unreachable!() + } + async fn refetch_links_from(&self, _: i64, _: i64) -> Result> { + self.1.fetch_add(1, Ordering::AcqRel); + Ok(vec![self.0.clone()]) + } + } + let server = MockServer::start().await; + let (bytes, expected) = nullable_payload(); + Mock::given(method("GET")) + .respond_with(ResponseTemplate::new(200).set_body_bytes(bytes)) + .expect(2) + .mount(&server) + .await; + let (mut ctx, admission) = ahead_ctx(&server, Duration::from_secs(2)); + let mut fresh = create_test_link(0); + fresh.url = format!("{}/fresh", server.uri()); + fresh.row_count = 3; + let refreshes = Arc::new(AtomicUsize::new(0)); + ctx.link_fetcher = Arc::new(FreshLink(fresh, refreshes.clone())); + let chunks = ctx.chunks.clone(); + let task = tokio::spawn(async move { + StreamingCloudFetchProvider::download_chunk_with_retry(0, &ctx).await + }); + wait_for_request(&server).await; + chunks + .get_mut(&0) + .unwrap() + .link + .as_mut() + .unwrap() + .expiration = chrono::Utc::now(); + admission.current.store(0, Ordering::Release); + admission.changed.notify_waiters(); + assert_eq!( + tokio::time::timeout(Duration::from_secs(2), task) + .await + .unwrap() + .unwrap() + .unwrap(), + vec![expected] + ); + assert_eq!(refreshes.load(Ordering::Acquire), 1); + } + + #[tokio::test] + async fn ahead_closed_idle_body_falls_back_without_retry_budget() { + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + let server = MockServer::start().await; + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let (bytes, expected) = nullable_payload(); + let (ready, received) = tokio::sync::oneshot::channel(); + let serving = tokio::spawn(async move { + let mut ready = Some(ready); + for attempt in 0..2 { + let (mut socket, _) = listener.accept().await.unwrap(); + let mut request = [0; 4096]; + socket.read(&mut request).await.unwrap(); + let length = bytes.len() + usize::from(attempt == 0); + let mut response = format!( + "HTTP/1.1 200 OK\r\nContent-Length: {length}\r\nConnection: close\r\n\r\n" + ) + .into_bytes(); + response.extend_from_slice(&bytes); + socket.write_all(&response).await.unwrap(); + socket.shutdown().await.unwrap(); + if let Some(ready) = ready.take() { + ready.send(()).unwrap(); + } + } + }); + let (mut ctx, admission) = ahead_ctx(&server, Duration::from_secs(2)); + { + let mut entry = ctx.chunks.get_mut(&0).unwrap(); + let link = entry.link.as_mut().unwrap(); + link.url = format!("http://{address}/chunk"); + link.row_count = 3; + } + ctx.max_retries = 1; + let task = tokio::spawn(async move { + StreamingCloudFetchProvider::download_chunk_with_retry(0, &ctx).await + }); + received.await.unwrap(); + tokio::time::sleep(Duration::from_millis(10)).await; + assert!(!task.is_finished()); + admission.current.store(0, Ordering::Release); + admission.changed.notify_waiters(); + assert_eq!( + tokio::time::timeout(Duration::from_secs(2), task) + .await + .unwrap() + .unwrap() + .unwrap(), + vec![expected] + ); + serving.await.unwrap(); + } + #[tokio::test] async fn stalled_body_is_bounded_by_deadline() { let server = MockServer::start().await; diff --git a/src/session.rs b/src/session.rs index ac2f462f..3f1baf53 100644 --- a/src/session.rs +++ b/src/session.rs @@ -79,6 +79,16 @@ use tracing::{info_span, Instrument, Span}; const TELEMETRY_ENABLED_FEATURE_FLAG: &str = "databricks.partnerplatform.clientConfigsFeatureFlags.enableTelemetryForKernel"; +const CLOUDFETCH_DOWNLOAD_AHEAD_FEATURE_FLAG: &str = + "databricks.partnerplatform.clientConfigsFeatureFlags.cloudFetchDownloadAheadForKernel"; + +fn cloudfetch_download_ahead(result: &ResultConfig, feature_flag: Option) -> usize { + result + .cloudfetch_download_ahead + .or_else(|| feature_flag.and_then(|lead| usize::try_from(lead).ok())) + .unwrap_or(0) + .min(16) +} fn telemetry_enabled(config: &TelemetryConfig, feature_flag: Option) -> bool { config.enabled.or(feature_flag).unwrap_or(false) @@ -399,10 +409,29 @@ impl Session { warehouse_id.clone(), transport_config, )); + let feature_flags = config + .driver_system_configuration + .as_ref() + .and_then(ClientIdentity::from_driver_system_configuration) + .map(|identity| FeatureFlagResolver::new(&host, Arc::clone(&http_client), identity)); + if let Some(feature_flags) = &feature_flags { + feature_flags.prepare_for_session_open().await; + } + let download_ahead_flag = match &feature_flags { + Some(flags) if config.result.cloudfetch_download_ahead.is_none() => { + flags + .get_int32(CLOUDFETCH_DOWNLOAD_AHEAD_FEATURE_FLAG) + .await + } + _ => None, + }; + let mut cloudfetch_config = result_to_cloudfetch_config(&config.result); + cloudfetch_config.download_ahead = + cloudfetch_download_ahead(&config.result, download_ahead_flag); let reader_factory = ResultReaderFactory::new( Arc::::downgrade(&sea), http_client.clone(), - result_to_cloudfetch_config(&config.result), + cloudfetch_config, result_to_post_process_options(&config.result), geospatial_result_representation, runtime_handle.clone(), @@ -419,17 +448,6 @@ impl Session { // The kernel synthesises no geospatial session-conf entry; // caller-supplied server-bound entries pass through unchanged. - // Resolve connector-service flags after authentication and immediately - // before CreateSession. The resolver populates the process-wide - // workspace cache; the session retains no private snapshot. - let feature_flags = config - .driver_system_configuration - .as_ref() - .and_then(ClientIdentity::from_driver_system_configuration) - .map(|identity| FeatureFlagResolver::new(&host, Arc::clone(&http_client), identity)); - if let Some(feature_flags) = &feature_flags { - feature_flags.prepare_for_session_open().await; - } let mut telemetry_config = config.telemetry.clone(); let telemetry_feature_flag = match &feature_flags { Some(flags) => flags.get_bool(TELEMETRY_ENABLED_FEATURE_FLAG).await, @@ -1300,6 +1318,7 @@ fn result_to_cloudfetch_config( enabled: result.cloudfetch_enabled, link_prefetch_window: result.cloudfetch_link_prefetch_window, max_chunks_in_memory: result.cloudfetch_max_chunks_in_memory, + download_ahead: cloudfetch_download_ahead(result, None), inline_max_chunks_in_memory: result.inline_max_chunks_in_memory, // Share one budget with the CloudFetch HTTP category // (see CLOUDFETCH_DOWNLOAD_BUDGET) so the provider retry loop and @@ -1697,6 +1716,20 @@ mod retry_config_tests { use crate::client::retry::RequestCategory; use std::time::Duration; + #[test] + fn download_ahead_client_override_wins_and_missing_flag_is_disabled() { + let mut result = ResultConfig::default(); + assert_eq!(cloudfetch_download_ahead(&result, None), 0); + assert_eq!(cloudfetch_download_ahead(&result, Some(8)), 8); + assert_eq!(cloudfetch_download_ahead(&result, Some(-1)), 0); + assert_eq!(cloudfetch_download_ahead(&result, Some(100)), 16); + for lead in [0, 4, 16] { + result.cloudfetch_download_ahead = Some(lead); + assert_eq!(cloudfetch_download_ahead(&result, Some(8)), lead); + assert_eq!(result_to_cloudfetch_config(&result).download_ahead, lead); + } + } + /// Build a minimal `SessionConfig` with the given `HttpConfig` for /// exercising `build_retry_configs_for_session` in isolation. fn config_with_http(http: HttpConfig) -> SessionConfig { @@ -2085,6 +2118,10 @@ mod retry_config_tests { K::CloudfetchMaxChunksInMemory.as_str().to_string(), "9".to_string(), ), + ( + K::CloudfetchDownloadAhead.as_str().to_string(), + "8".to_string(), + ), ( K::InlineMaxChunksInMemory.as_str().to_string(), "3".to_string(), @@ -2104,6 +2141,7 @@ mod retry_config_tests { assert!(!cfg.result.cloudfetch_enabled); assert_eq!(cfg.result.cloudfetch_link_prefetch_window, 7); assert_eq!(cfg.result.cloudfetch_max_chunks_in_memory, 9); + assert_eq!(cfg.result.cloudfetch_download_ahead, Some(8)); assert_eq!(cfg.result.inline_max_chunks_in_memory, 3); assert!(cfg.result.complex_types_as_json); assert!(cfg.result.intervals_as_string); diff --git a/src/types/cloudfetch.rs b/src/types/cloudfetch.rs index 278850c9..9f9fd4ee 100644 --- a/src/types/cloudfetch.rs +++ b/src/types/cloudfetch.rs @@ -36,6 +36,8 @@ pub const DEFAULT_CHUNK_READY_TIMEOUT_SECS: u64 = 30; /// Configuration for CloudFetch streaming. #[derive(Debug, Clone)] pub struct CloudFetchConfig { + /// Extra header-only downloads ahead of the decoded window; 0 disables. + pub download_ahead: usize, /// Number of chunk links to prefetch ahead of consumption. pub link_prefetch_window: usize, /// Maximum number of chunks to hold in memory (controls parallelism). @@ -80,6 +82,7 @@ pub struct CloudFetchConfig { impl Default for CloudFetchConfig { fn default() -> Self { Self { + download_ahead: 0, // Match JDBC default: prefetch 128 chunks ahead of consumer link_prefetch_window: 128, // Match JDBC default: cloudFetchThreadPoolSize = 16