Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CONNECTION_PARAMETERS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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` |
Expand Down Expand Up @@ -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` |
Expand Down
2 changes: 2 additions & 0 deletions NEXT_CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
5 changes: 5 additions & 0 deletions include/databricks_kernel.h
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
5 changes: 4 additions & 1 deletion napi/src/database.rs
Original file line number Diff line number Diff line change
Expand Up @@ -230,7 +230,10 @@ pub struct ConnectionOptions {
pub schema: Option<String>,
/// 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<HashMap<String, String>>,
/// Select whether `GEOMETRY` / `GEOGRAPHY` results use their native Arrow
/// representation. `true` (the default) requests Arrow
Expand Down
6 changes: 5 additions & 1 deletion pyo3/src/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
47 changes: 47 additions & 0 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<usize>,

/// 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.
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -1190,6 +1196,7 @@ pub(crate) enum ClientConfKey {
CloudfetchEnabled,
CloudfetchLinkPrefetchWindow,
CloudfetchMaxChunksInMemory,
CloudfetchDownloadAhead,
InlineMaxChunksInMemory,
ComplexTypesAsJson,
IntervalsAsString,
Expand All @@ -1202,6 +1209,7 @@ impl ClientConfKey {
Self::CloudfetchEnabled,
Self::CloudfetchLinkPrefetchWindow,
Self::CloudfetchMaxChunksInMemory,
Self::CloudfetchDownloadAhead,
Self::InlineMaxChunksInMemory,
Self::ComplexTypesAsJson,
Self::IntervalsAsString,
Expand All @@ -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",
Expand Down Expand Up @@ -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::<usize>()
.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)?;
}
Expand Down Expand Up @@ -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!(
Expand Down
76 changes: 69 additions & 7 deletions src/reader/cloudfetch/chunk_downloader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -86,6 +102,20 @@ impl ChunkDownloader {
link: &CloudFetchLink,
attempt_timeout: Option<Duration>,
) -> Result<Vec<RecordBatch>> {
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<Duration>,
) -> Result<PreparedDownload> {
let start = Instant::now();

debug!(
Expand Down Expand Up @@ -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<Duration>,
) -> Result<(Vec<RecordBatch>, 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<Vec<RecordBatch>> {
let size_mb = bytes.len() as f64 / 1024.0 / 1024.0;
let speed_mbps = size_mb / elapsed.as_secs_f64();

Expand All @@ -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",
Expand Down
Loading
Loading