From 4691f70cda81ad2b22c419d876d7aebbdbf878fe Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Fri, 27 Nov 2026 19:01:20 +0000 Subject: [PATCH 1/3] feat(results): make Arrow LZ4 compression configurable Signed-off-by: Aakash Saravanan --- CONNECTION_PARAMETERS.md | 7 ++-- adbc/README.md | 4 ++ adbc/src/config.rs | 27 +++++++++++++ include/databricks_kernel.h | 8 ++-- napi/index.d.ts | 2 + napi/src/connection.rs | 23 ++++++++--- pyo3/src/statement.rs | 8 ++++ src/c_abi/session.rs | 17 +++----- src/client/sea.rs | 10 ++++- src/client/transport.rs | 8 ++-- src/config.rs | 26 ++++++------ src/session.rs | 9 +++-- src/statement/mutable.rs | 1 + src/statement/spec.rs | 15 +++++-- src/types/sea.rs | 6 +-- tests/c/session_smoke.c | 2 + tests/v0_c_abi_result_config_wiremock.rs | 14 ++++--- tests/v0_execute_wiremock.rs | 50 ++++++++++++++++++++++++ tests/v0_metadata_wiremock.rs | 30 +++++++++++--- 19 files changed, 204 insertions(+), 63 deletions(-) diff --git a/CONNECTION_PARAMETERS.md b/CONNECTION_PARAMETERS.md index 2a11227d..c598c68a 100644 --- a/CONNECTION_PARAMETERS.md +++ b/CONNECTION_PARAMETERS.md @@ -171,6 +171,7 @@ Setting only one of `client_cert_pem` / `client_key_pem` is rejected at | Field | Description | Default | |-------|-------------|---------| | `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` | +| `lz4_compression_enabled` | Request LZ4 compression for Arrow results, including inline and CloudFetch delivery. Statements can override this default via `StatementSpec::lz4_compression`. | `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` | | `inline_max_chunks_in_memory` | Prefetch window for the inline-Arrow path (used when CloudFetch is disabled). `1` disables prefetching. | `4` | @@ -257,12 +258,12 @@ Each key mirrors a field of [`ResultConfig`](#resultconfig--result-handling-opti | Key | Description | Default | |-----|-------------|---------| | `cloudfetch_enabled` | Same knob as `ResultConfig::cloudfetch_enabled` — opt into CloudFetch (`false` forces the inline-Arrow path). | `true` | +| `lz4_compression_enabled` | Same knob as `ResultConfig::lz4_compression_enabled` — request LZ4 compression for Arrow results. | `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` | | `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` | -Compression (LZ4) is **not** a parameter: the kernel detects it from the -server's result manifest (`result_compression`) and decompresses -`LZ4_FRAME` payloads automatically. +The kernel reads the codec from the server's result manifest +(`result_compression`) and decompresses `LZ4_FRAME` payloads automatically. diff --git a/adbc/README.md b/adbc/README.md index de153783..38f1385f 100644 --- a/adbc/README.md +++ b/adbc/README.md @@ -63,6 +63,10 @@ and proxy behavior, TLS, logging, telemetry, result fetching, query execution, and metadata. Supply credentials at runtime and do not place them in source code, manifests, logs, or connection URLs. +LZ4 compression is enabled by default for Arrow query results. Set the database +option `adbc.databricks.enable_query_result_lz4_compression` to `"false"` or +integer `0` to request uncompressed results. + ## Supported functionality The driver supports query and update execution, parameter binding, diff --git a/adbc/src/config.rs b/adbc/src/config.rs index 65b42e9e..83ed3878 100644 --- a/adbc/src/config.rs +++ b/adbc/src/config.rs @@ -63,6 +63,8 @@ const GEOSPATIAL_REPRESENTATION: &str = "adbc.databricks.geospatial.result_repre const ENABLE_GEOSPATIAL: &str = "adbc.databricks.enable_geospatial_support"; const CLOUDFETCH_MAX_CHUNKS_IN_MEMORY: &str = "adbc.databricks.cloudfetch.max_chunks_in_memory"; const CLOUDFETCH_ENABLED: &str = "adbc.databricks.cloudfetch.enabled"; +const ENABLE_QUERY_RESULT_LZ4_COMPRESSION: &str = + "adbc.databricks.enable_query_result_lz4_compression"; const PROTOCOL: &str = "adbc.databricks.protocol"; pub(crate) const ESCAPE_CATALOG_NAME: &str = "adbc.databricks.metadata.escape_catalog_name"; @@ -372,6 +374,9 @@ impl DatabaseConfig { CLOUDFETCH_ENABLED | "databricks.cloudfetch.enabled" => { self.result.cloudfetch_enabled = boolean_compat(value, key)? } + ENABLE_QUERY_RESULT_LZ4_COMPRESSION => { + self.result.lz4_compression_enabled = boolean_compat(value, key)? + } PROTOCOL => { let protocol = string_value(value, key)?; if !protocol.eq_ignore_ascii_case("rest") { @@ -1244,6 +1249,28 @@ mod tests { assert!(config.result.cloudfetch_enabled); } + #[test] + fn lz4_compression_option_configures_kernel_result_codec() { + let mut config = DatabaseConfig::default(); + assert!(config.result.lz4_compression_enabled); + + let key = ENABLE_QUERY_RESULT_LZ4_COMPRESSION; + for (value, expected) in [ + ("false".into(), false), + ("true".into(), true), + (OptionValue::Int(0), false), + (OptionValue::Int(1), true), + ] { + config.set_option(key, value).unwrap(); + assert_eq!(config.result.lz4_compression_enabled, expected); + } + for value in ["bogus".into(), OptionValue::Int(2)] { + let error = config.set_option(key, value).unwrap_err(); + assert_eq!(error.status, Status::InvalidArguments); + assert!(config.result.lz4_compression_enabled); + } + } + #[test] fn complex_datatype_support_configures_kernel_result_shape() { let mut config = DatabaseConfig::default(); diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h index e167f181..15da232f 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -582,10 +582,8 @@ KernelStatusCode kernel_session_config_set_u2m_token_cache_config(KernelSessionC * * Counterpart to kernel_session_config_set_session_conf: that one carries * SERVER session confs (ANSI_MODE, TIMEZONE, ...) to the SEA wire; this one - * sets CLIENT-SIDE knobs that tune how the kernel fetches, buffers, and - * post-processes results and are NEVER sent to the server. The two channels - * are deliberately separate (conflating them is what made a client flag - * masquerade as a rejected server conf). + * configures how the kernel requests, fetches, buffers, and post-processes + * results. These keys are kept out of the server session configuration. * * Key/value (rather than one typed setter per knob) so the signature never * changes as new result knobs are added, and so a host that already has DSN @@ -596,6 +594,8 @@ KernelStatusCode kernel_session_config_set_u2m_token_cache_config(KernelSessionC * Recognised keys (case-insensitive): * - "cloudfetch_enabled" = "true"|"false" — false serves every result * through paged inline delivery without cloud-storage downloads. + * - "lz4_compression_enabled" = "true"|"false", for LZ4 compression + * for Arrow results. Defaults to "true". * - "cloudfetch_link_prefetch_window" = positive integer. * - "cloudfetch_max_chunks_in_memory" = positive integer (bounds peak RSS; * values above the kernel ceiling of 256 are clamped with a warning). diff --git a/napi/index.d.ts b/napi/index.d.ts index 064f856d..bcd71aa6 100644 --- a/napi/index.d.ts +++ b/napi/index.d.ts @@ -68,6 +68,8 @@ export interface ExecuteOptions { * `StatementSpec.row_limit`. Omitted ⇒ no driver-imposed cap. */ rowLimit?: number + /** Request LZ4 compression for Arrow results. Omit to use the session default. */ + lz4Compression?: boolean /** * Positional parameters, in 1-based wire order. Index `i` in this * Vec corresponds to the `i+1`-th `?` placeholder in the SQL. diff --git a/napi/src/connection.rs b/napi/src/connection.rs index 7aba91ff..bdd3b12a 100644 --- a/napi/src/connection.rs +++ b/napi/src/connection.rs @@ -102,6 +102,8 @@ pub struct ExecuteOptions { /// (SEA `row_limit`), independent of any SQL `LIMIT`. Maps to /// `StatementSpec.row_limit`. Omitted ⇒ no driver-imposed cap. pub row_limit: Option, + /// Request LZ4 compression for Arrow results. Omit to use the session default. + pub lz4_compression: Option, /// Positional parameters, in 1-based wire order. Index `i` in this /// Vec corresponds to the `i+1`-th `?` placeholder in the SQL. /// Each entry is a `{ sqlType, value }` pair — `value` is the @@ -190,6 +192,7 @@ fn build_statement( statement_conf: Option>, query_tags: Option>>, row_limit: Option, + lz4_compression: Option, positional_params: Vec, named_params: Vec<(String, TypedValue)>, raw_params: Vec, @@ -215,6 +218,7 @@ fn build_statement( } // `None` leaves the kernel's omit-the-field default in place. stmt.spec().row_limit(row_limit); + stmt.spec().lz4_compression(lz4_compression); // Bind positional params 1-based on the wire. for (i, value) in positional_params.into_iter().enumerate() { stmt.spec() @@ -293,11 +297,10 @@ impl Connection { mut options: Option, ) -> napi::Result { let inner = Arc::clone(&self.inner); - // Pull the scalar knobs out (both `i64`/`u32` are `Copy`) before - // the `.take()`s below consume the map fields out of `options`. - let row_limit = options.as_ref().and_then(|o| o.row_limit); // Decode positional params before `options` is consumed below; a - // malformed entry surfaces as InvalidArgument here, before any wire - // round-trip. + // Read scalar options before consuming the other fields in `options`. + let row_limit = options.as_ref().and_then(|o| o.row_limit); + let lz4_compression = options.as_ref().and_then(|o| o.lz4_compression); + // Invalid positional parameters fail here before any wire round-trip. let positional_params = options .as_mut() .and_then(|o| o.positional_params.take()) @@ -342,6 +345,7 @@ impl Connection { statement_conf, query_tags, row_limit, + lz4_compression, positional_params, named_params, raw_params, @@ -387,6 +391,7 @@ impl Connection { ) -> napi::Result> { let inner = Arc::clone(&self.inner); let row_limit = options.as_ref().and_then(|o| o.row_limit); + let lz4_compression = options.as_ref().and_then(|o| o.lz4_compression); let positional_params = options .as_mut() .and_then(|o| o.positional_params.take()) @@ -415,6 +420,7 @@ impl Connection { statement_conf, query_tags, row_limit, + lz4_compression, positional_params, named_params, raw_params, @@ -460,6 +466,7 @@ impl Connection { let inner = Arc::clone(&self.inner); // Same option decoding as `execute_statement`. let row_limit = options.as_ref().and_then(|o| o.row_limit); + let lz4_compression = options.as_ref().and_then(|o| o.lz4_compression); let positional_params = options .as_mut() .and_then(|o| o.positional_params.take()) @@ -495,6 +502,7 @@ impl Connection { statement_conf, query_tags, row_limit, + lz4_compression, positional_params, named_params, raw_params, @@ -533,6 +541,7 @@ impl Connection { // Same option decoding as `execute_statement` — malformed // params surface as InvalidArgument before any wire round-trip. let row_limit = options.as_ref().and_then(|o| o.row_limit); + let lz4_compression = options.as_ref().and_then(|o| o.lz4_compression); let positional_params = options .as_mut() .and_then(|o| o.positional_params.take()) @@ -573,6 +582,7 @@ impl Connection { statement_conf, query_tags, row_limit, + lz4_compression, positional_params, named_params, raw_params, @@ -756,6 +766,7 @@ mod tests { None, None, None, + Some(false), vec![], vec![], vec![raw()], @@ -778,6 +789,7 @@ mod tests { assert_eq!(statement_requests.len(), 1); let body: serde_json::Value = serde_json::from_slice(&statement_requests[0].body).expect("statement request is JSON"); + assert_eq!(body["result_compression"], "NONE"); assert_eq!( body["parameters"], json!([{ "ordinal": 1, "type": "INTERVAL MONTH", "value": "13" }]) @@ -789,6 +801,7 @@ mod tests { None, None, None, + None, vec![TypedValue::Int32(1)], vec![], vec![raw()], diff --git a/pyo3/src/statement.rs b/pyo3/src/statement.rs index 2777b114..806c76b8 100644 --- a/pyo3/src/statement.rs +++ b/pyo3/src/statement.rs @@ -66,6 +66,14 @@ impl Statement { Ok(()) } + /// Set LZ4 compression for Arrow results. ``None`` uses the session default. + #[pyo3(signature = (enabled))] + fn set_lz4_compression(&mut self, enabled: Option) -> PyResult<()> { + let inner = alive_mut!(self, "Statement"); + inner.stmt.spec().lz4_compression(enabled); + Ok(()) + } + /// Set the server-side row cap for this statement. ``None`` clears it. fn set_row_limit(&mut self, row_limit: Option) -> PyResult<()> { let inner = alive_mut!(self, "Statement"); diff --git a/src/c_abi/session.rs b/src/c_abi/session.rs index b3365f49..568b3f69 100644 --- a/src/c_abi/session.rs +++ b/src/c_abi/session.rs @@ -192,13 +192,8 @@ pub struct KernelSessionConfig { /// machine-local derived key. Only U2M auth reads it — PAT and M2M never /// touch the cache. See [`TokenCacheConfig`]. token_cache: TokenCacheConfig, - /// Client-side result-management knobs (CloudFetch / inline streaming - /// tuning, flat-text rendering). Populated by - /// `kernel_session_config_set_client_conf`; defaults to - /// [`ResultConfig::default`]. These are **client-side** behaviours - /// folded into the kernel's `ResultConfig` at `open()` — they never - /// reach the SEA wire (unlike [`Self::session_conf`]). See - /// [`ResultConfig`]. + /// Client-side result settings populated by + /// `kernel_session_config_set_client_conf`. See [`ResultConfig`]. result: ResultConfig, /// Telemetry collection/export knobs. Defaults to disabled; populated by /// `kernel_session_config_set_telemetry_config`. @@ -1363,10 +1358,8 @@ pub unsafe extern "C" fn kernel_session_config_set_u2m_token_cache_config( /// This is the client-side counterpart to /// `kernel_session_config_set_session_conf`: that one carries **server** /// session confs (`ANSI_MODE`, `TIMEZONE`, …) to the SEA wire; this one -/// sets **client-side** knobs that tune how the kernel fetches, buffers, -/// and post-processes results and are **never sent to the server**. The two -/// channels are deliberately separate (see #196 / #226 — conflating them is -/// what made a client flag masquerade as a rejected server conf). +/// configures how the kernel requests, fetches, buffers, and post-processes +/// results. These keys are kept out of the server session configuration. /// /// A key/value shape (rather than one typed setter per knob) is chosen so /// the signature never changes as `ResultConfig` grows new knobs, and so a @@ -1379,6 +1372,8 @@ pub unsafe extern "C" fn kernel_session_config_set_u2m_token_cache_config( /// [`ResultConfig`]: /// - `cloudfetch_enabled` = `"true"` / `"false"` — `false` serves every /// result through paged inline delivery without cloud-storage downloads. +/// - `lz4_compression_enabled` = `"true"` / `"false"`, for LZ4 +/// compression for Arrow results. Defaults to `"true"`. /// - `cloudfetch_link_prefetch_window` = positive integer — presigned URLs /// prefetched ahead of the consumer. /// - `cloudfetch_max_chunks_in_memory` = positive integer — decompressed diff --git a/src/client/sea.rs b/src/client/sea.rs index a5aa3563..e3017df1 100644 --- a/src/client/sea.rs +++ b/src/client/sea.rs @@ -664,6 +664,14 @@ impl SeaRestTransport { ), Some(SessionRoute::Realtime { .. }) => (None, None), }; + let compression = if params + .lz4_compression + .unwrap_or(self.config.lz4_compression_enabled) + { + "LZ4_FRAME" + } else { + "NONE" + }; let request_body = ExecuteStatementRequest { warehouse_id, statement: sql.to_string(), @@ -676,7 +684,7 @@ impl SeaRestTransport { wait_timeout: params.wait_timeout.clone(), on_wait_timeout: params.on_wait_timeout.clone(), row_limit: params.row_limit, - result_compression: Some("LZ4_FRAME".to_string()), + result_compression: Some(compression.to_string()), parameters: params.parameters.clone(), query_tags: params.query_tags.clone(), }; diff --git a/src/client/transport.rs b/src/client/transport.rs index 019d675c..d050a685 100644 --- a/src/client/transport.rs +++ b/src/client/transport.rs @@ -55,9 +55,8 @@ impl ExecutionTimeout { /// Backend-agnostic configuration for [`Transport`] implementations. /// /// Contains polling settings shared across SEA REST, SEA gRPC, and -/// Thrift backends. CloudFetch tuning lives on -/// [`crate::reader::ResultReaderFactory`] instead — the transport -/// never reads it. +/// Thrift backends. Result-reader buffering lives on +/// [`crate::reader::ResultReaderFactory`]. #[derive(Debug, Clone)] pub(crate) struct TransportConfig { /// Default polling ceiling for async and metadata execution (600s). @@ -70,6 +69,8 @@ pub(crate) struct TransportConfig { /// When false, session creation requests paged inline results without /// cloud-storage downloads. The value is fixed for the session lifetime. pub cloudfetch_enabled: bool, + /// Session default for LZ4 compression of Arrow results. + pub lz4_compression_enabled: bool, } impl Default for TransportConfig { @@ -79,6 +80,7 @@ impl Default for TransportConfig { poll_interval: Duration::from_millis(500), // Mirror `ResultConfig::default().cloudfetch_enabled`. cloudfetch_enabled: true, + lz4_compression_enabled: true, } } } diff --git a/src/config.rs b/src/config.rs index 9c1eb0a9..692ac39f 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1077,13 +1077,7 @@ impl std::fmt::Debug for TlsConfig { // ─── Result management (CloudFetch + future result knobs) ─────────────────── -/// Result-stream tuning. Today this is exclusively CloudFetch knobs; -/// future non-CloudFetch result-management options (chunk-size hints, -/// decompression strategy, max-row buffer, etc.) slot in here too — the -/// name is intentionally general. -/// -/// Renamed from `CloudFetchConfig` so the type doesn't fossilise around -/// one transport feature. +/// Result delivery, compression, buffering, and representation settings. #[non_exhaustive] #[derive(Debug, Clone)] pub struct ResultConfig { @@ -1095,6 +1089,9 @@ pub struct ResultConfig { /// Servers without this capability may reject session creation or the first statement. pub cloudfetch_enabled: bool, + /// Request LZ4 compression for Arrow results. Default: `true`. + pub lz4_compression_enabled: bool, + /// Number of presigned URLs to prefetch ahead of the consumer. pub cloudfetch_link_prefetch_window: usize, @@ -1157,6 +1154,7 @@ impl Default for ResultConfig { fn default() -> Self { Self { cloudfetch_enabled: true, + lz4_compression_enabled: true, cloudfetch_link_prefetch_window: 10, cloudfetch_max_chunks_in_memory: 16, inline_max_chunks_in_memory: 4, @@ -1188,6 +1186,7 @@ pub(crate) const CLOUDFETCH_MAX_CHUNKS_CEILING: usize = 256; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(crate) enum ClientConfKey { CloudfetchEnabled, + Lz4CompressionEnabled, CloudfetchLinkPrefetchWindow, CloudfetchMaxChunksInMemory, InlineMaxChunksInMemory, @@ -1200,6 +1199,7 @@ impl ClientConfKey { /// and to pin parity with [`ResultConfig`]'s fields in tests. pub(crate) const ALL: &'static [ClientConfKey] = &[ Self::CloudfetchEnabled, + Self::Lz4CompressionEnabled, Self::CloudfetchLinkPrefetchWindow, Self::CloudfetchMaxChunksInMemory, Self::InlineMaxChunksInMemory, @@ -1211,6 +1211,7 @@ impl ClientConfKey { pub(crate) const fn as_str(self) -> &'static str { match self { Self::CloudfetchEnabled => "cloudfetch_enabled", + Self::Lz4CompressionEnabled => "lz4_compression_enabled", Self::CloudfetchLinkPrefetchWindow => "cloudfetch_link_prefetch_window", Self::CloudfetchMaxChunksInMemory => "cloudfetch_max_chunks_in_memory", Self::InlineMaxChunksInMemory => "inline_max_chunks_in_memory", @@ -1238,11 +1239,9 @@ impl ResultConfig { /// DSN / connection-string attributes as key/value pairs). The key is /// resolved via [`ClientConfKey::parse`] (case-insensitive). /// - /// Unlike the server `session_conf` map, these knobs are **client-side** - /// and never reach the SEA wire — so this deliberately does NOT accept - /// server conf keys (`ANSI_MODE`, `TIMEZONE`, …); those remain in - /// `session_conf` and pass through unchanged. Keeping the two channels - /// separate is the point (see #226). + /// These knobs configure the client. Server keys such as `ANSI_MODE` + /// and `TIMEZONE` belong in `session_conf`, which sends them as server + /// settings. /// /// # Errors /// Returns `ErrorCode::InvalidArgument` when: @@ -1299,6 +1298,9 @@ impl ResultConfig { ClientConfKey::CloudfetchEnabled => { self.cloudfetch_enabled = parse_bool(value)?; } + ClientConfKey::Lz4CompressionEnabled => { + self.lz4_compression_enabled = parse_bool(value)?; + } ClientConfKey::CloudfetchLinkPrefetchWindow => { self.cloudfetch_link_prefetch_window = parse_positive_usize(value)?; } diff --git a/src/session.rs b/src/session.rs index ac2f462f..e9644ff5 100644 --- a/src/session.rs +++ b/src/session.rs @@ -391,6 +391,7 @@ impl Session { let defaults = config.defaults.clone().unwrap_or_default(); let transport_config = TransportConfig { cloudfetch_enabled: config.result.cloudfetch_enabled, + lz4_compression_enabled: config.result.lz4_compression_enabled, ..TransportConfig::default() }; let sea = Arc::new(SeaRestTransport::new( @@ -1290,9 +1291,7 @@ fn apply_client_result_overrides(config: &mut SessionConfig) { } } -/// Project the public [`ResultConfig`] (today only carries -/// CloudFetch knobs; future result-management options slot in here -/// too) onto the internal `CloudFetchConfig`. +/// Project the CloudFetch settings from [`ResultConfig`] onto the reader configuration. fn result_to_cloudfetch_config( result: &ResultConfig, ) -> crate::types::cloudfetch::CloudFetchConfig { @@ -2065,7 +2064,7 @@ mod retry_config_tests { } } - /// All six client-side result knobs are recognised in session_conf, + /// All client-side result knobs are recognised in session_conf, /// applied to the typed ResultConfig, and stripped so none reach the /// wire. Guards the parity between `ClientConfKey::ALL` and the /// session_conf sweep. @@ -2077,6 +2076,7 @@ mod retry_config_tests { K::CloudfetchEnabled.as_str().to_string(), "false".to_string(), ), + ("LZ4_COMPRESSION_ENABLED".to_string(), " FaLsE ".to_string()), ( K::CloudfetchLinkPrefetchWindow.as_str().to_string(), "7".to_string(), @@ -2102,6 +2102,7 @@ mod retry_config_tests { ])); apply_client_result_overrides(&mut cfg); assert!(!cfg.result.cloudfetch_enabled); + assert!(!cfg.result.lz4_compression_enabled); assert_eq!(cfg.result.cloudfetch_link_prefetch_window, 7); assert_eq!(cfg.result.cloudfetch_max_chunks_in_memory, 9); assert_eq!(cfg.result.inline_max_chunks_in_memory, 3); diff --git a/src/statement/mutable.rs b/src/statement/mutable.rs index 34baf1d1..0f573328 100644 --- a/src/statement/mutable.rs +++ b/src/statement/mutable.rs @@ -165,6 +165,7 @@ fn build_execute_params( wait_timeout, on_wait_timeout, row_limit: spec.row_limit, + lz4_compression: spec.lz4_compression, ..ExecuteParams::default() }; for (i, value) in spec.positional_params.iter().enumerate() { diff --git a/src/statement/spec.rs b/src/statement/spec.rs index 288bb0ae..650fff56 100644 --- a/src/statement/spec.rs +++ b/src/statement/spec.rs @@ -220,6 +220,9 @@ pub struct StatementSpec { /// omits the field, so the server applies no driver-imposed cap. pub row_limit: Option, + /// Override LZ4 compression for Arrow results. `None` uses the session default. + pub lz4_compression: Option, + /// Result wire format. pub result_format: ResultFormat, } @@ -234,10 +237,8 @@ impl StatementSpec { /// bound parameter — raw, positional-typed, and named-typed — so each /// `sql()` begins a fresh set of *bound parameters*. /// - /// Scope note: this clears the three parameter collections only. It does - /// **not** reset `statement_conf` (e.g. query tags) or `row_limit`, which - /// survive a `sql()` call and must be re-set explicitly if a reused handle - /// should not carry them into the next query. + /// Reused handles carry statement options such as `statement_conf`, + /// `row_limit`, and `lz4_compression` into the next query unless explicitly reset. /// /// This is the single reset point for the *bound parameters* of a reused /// statement handle. New SQL has its own parameter markers, so carrying @@ -393,6 +394,12 @@ impl StatementSpec { self } + /// Set the Arrow result compression override. `None` restores the session default. + pub fn lz4_compression(&mut self, enabled: Option) -> &mut Self { + self.lz4_compression = enabled; + self + } + /// Set the result wire format. pub fn result_format(&mut self, fmt: ResultFormat) -> &mut Self { self.result_format = fmt; diff --git a/src/types/sea.rs b/src/types/sea.rs index 8d988dad..73d9919f 100644 --- a/src/types/sea.rs +++ b/src/types/sea.rs @@ -401,10 +401,7 @@ pub struct ExecuteStatementRequest { pub on_wait_timeout: Option, #[serde(skip_serializing_if = "Option::is_none")] pub row_limit: Option, - /// Server-side compression for external-link result chunks. Set to - /// `Some("LZ4_FRAME")` so the cloud-fetch payload is LZ4-compressed - /// (matches Python/JDBC SEA default). Without it the server returns - /// uncompressed arrow bytes, doubling network transfer. + /// Requested Arrow result codec (`LZ4_FRAME` or `NONE`). #[serde(skip_serializing_if = "Option::is_none")] pub result_compression: Option, /// Positional parameters for parameterized queries. @@ -424,6 +421,7 @@ pub struct ExecuteParams { pub wait_timeout: Option, pub on_wait_timeout: Option, // "CONTINUE" or "CANCEL" pub row_limit: Option, + pub lz4_compression: Option, /// Parameters for parameterized query execution. pub parameters: Vec, /// Per-statement query tags, forwarded to the SEA request's native diff --git a/tests/c/session_smoke.c b/tests/c/session_smoke.c index f6b78c2c..758c477e 100644 --- a/tests/c/session_smoke.c +++ b/tests/c/session_smoke.c @@ -269,6 +269,8 @@ static void test_client_conf_setter(void) { KernelStatusCode rc = kernel_session_config_set_client_conf(config, "cloudfetch_enabled", "false"); CHECK(rc == KernelStatusCode_Success, "set_client_conf cloudfetch_enabled=false succeeds"); + rc = kernel_session_config_set_client_conf(config, "lz4_compression_enabled", "false"); + CHECK(rc == KernelStatusCode_Success, "set_client_conf lz4_compression_enabled=false succeeds"); rc = kernel_session_config_set_client_conf(config, "cloudfetch_max_chunks_in_memory", "32"); CHECK(rc == KernelStatusCode_Success, "set_client_conf max_chunks=32 succeeds"); rc = kernel_session_config_set_client_conf(config, "complex_types_as_json", "true"); diff --git a/tests/v0_c_abi_result_config_wiremock.rs b/tests/v0_c_abi_result_config_wiremock.rs index 79f1c3ca..a10400e4 100644 --- a/tests/v0_c_abi_result_config_wiremock.rs +++ b/tests/v0_c_abi_result_config_wiremock.rs @@ -286,12 +286,14 @@ fn c_abi_set_client_conf_rejects_unknown_key_and_bad_value() { ); // Unparseable value for a known bool key → InvalidArgument. - let key = CString::new("cloudfetch_enabled").unwrap(); - let bad_val = CString::new("flase").unwrap(); // typo - assert_eq!( - kernel_session_config_set_client_conf(config, key.as_ptr(), bad_val.as_ptr()), - KernelStatusCode::InvalidArgument - ); + for key in ["cloudfetch_enabled", "lz4_compression_enabled"] { + let key = CString::new(key).unwrap(); + let bad_val = CString::new("flase").unwrap(); // typo + assert_eq!( + kernel_session_config_set_client_conf(config, key.as_ptr(), bad_val.as_ptr()), + KernelStatusCode::InvalidArgument + ); + } let mut err = std::mem::MaybeUninit::::uninit(); assert!( kernel_get_last_error(err.as_mut_ptr()), diff --git a/tests/v0_execute_wiremock.rs b/tests/v0_execute_wiremock.rs index cd5f1924..b4c829ad 100644 --- a/tests/v0_execute_wiremock.rs +++ b/tests/v0_execute_wiremock.rs @@ -1616,6 +1616,56 @@ async fn execute_with_cloudfetch_enabled_sends_inline_or_external_links_disposit ); } +#[tokio::test] +async fn execute_lz4_compression_uses_statement_override_or_session_default() { + for (session_default, expected) in [ + (true, ["LZ4_FRAME", "NONE", "NONE", "LZ4_FRAME"]), + (false, ["NONE", "LZ4_FRAME", "LZ4_FRAME", "NONE"]), + ] { + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_delete_session(&server).await; + mount_close_any_statement(&server).await; + let batch = int64_batch("n", vec![1]); + mount_execute(&server, succeeded_inline_body("stmt-lz4", &batch)).await; + let session = if session_default { + open_session(&server).await + } else { + let mut result = ResultConfig::default(); + result.lz4_compression_enabled = false; + open_session_with_result(&server, result).await + }; + + let mut stmt = session.statement(); + for (sql, override_update) in [ + ("SELECT 1", None), + ("SELECT 1 AS n", Some(Some(!session_default))), + ("SELECT 1 AS m", None), + ("SELECT 1 AS p", Some(None)), + ] { + stmt.spec().sql(sql); + if let Some(override_value) = override_update { + stmt.spec().lz4_compression(override_value); + } + let mut executed = stmt.execute().await.unwrap(); + drain(executed.result_stream_mut()).await; + executed.close().await.unwrap(); + } + + let codecs: Vec<_> = server + .received_requests() + .await + .unwrap() + .iter() + .filter(|r| r.url.path() == "/api/2.0/sql/statements" && r.method.as_str() == "POST") + .map(|request| { + request.body_json::().unwrap()["result_compression"].clone() + }) + .collect(); + assert_eq!(codecs, expected); + } +} + #[tokio::test] async fn execute_with_cloudfetch_disabled_supports_paged_arrow_results() { let server = MockServer::start().await; diff --git a/tests/v0_metadata_wiremock.rs b/tests/v0_metadata_wiremock.rs index e23914ef..3b4fa684 100644 --- a/tests/v0_metadata_wiremock.rs +++ b/tests/v0_metadata_wiremock.rs @@ -38,7 +38,8 @@ use arrow_schema::{DataType, Field, Schema}; use base64::{engine::general_purpose::STANDARD, Engine}; use databricks_sql_kernel::metadata_v0::exact_catalog_and_pattern; use databricks_sql_kernel::{ - AuthConfig, ConnectionConfig, DefaultOpts, Identifier, LikePattern, ResultBatch, Session, + AuthConfig, ConnectionConfig, DefaultOpts, Identifier, LikePattern, ResultBatch, ResultConfig, + Session, SessionBuilder, }; use serde_json::json; use std::sync::Arc; @@ -51,8 +52,8 @@ async fn open_session(server: &MockServer) -> Session { open_session_with_default_catalog(server, None).await } -async fn open_session_with_default_catalog(server: &MockServer, catalog: Option<&str>) -> Session { - let builder = Session::builder() +fn session_builder(server: &MockServer) -> SessionBuilder { + Session::builder() .connection( ConnectionConfig::from_http_path(server.uri(), "/sql/1.0/warehouses/test_wh") .expect("valid http_path"), @@ -60,7 +61,11 @@ async fn open_session_with_default_catalog(server: &MockServer, catalog: Option< .auth(AuthConfig::Pat { token: "dapi_test_token".into(), identity_federation_client_id: None, - }); + }) +} + +async fn open_session_with_default_catalog(server: &MockServer, catalog: Option<&str>) -> Session { + let builder = session_builder(server); let builder = match catalog { Some(catalog) => { let mut defaults = DefaultOpts::default(); @@ -670,9 +675,22 @@ async fn list_catalogs_returns_table_cat_column() { "catalog", vec![Some("main"), Some("hive_metastore")], )]); - mount_execute(&server, succeeded_inline_response_body(&raw)).await; + Mock::given(method("POST")) + .and(path("/api/2.0/sql/statements")) + .and(body_partial_json(json!({ "result_compression": "NONE" }))) + .respond_with( + ResponseTemplate::new(200).set_body_string(succeeded_inline_response_body(&raw)), + ) + .mount(&server) + .await; - let session = open_session(&server).await; + let mut result = ResultConfig::default(); + result.lz4_compression_enabled = false; + let session = session_builder(&server) + .result(result) + .open() + .await + .unwrap(); let mut stream = session .metadata() .list_catalogs() From 2030ed4871c5a0c765ff256f2da4152cd1ce7226 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Fri, 27 Nov 2026 21:42:01 +0000 Subject: [PATCH 2/3] docs(results): record LZ4 controls and check Python exports Signed-off-by: Aakash Saravanan --- NEXT_CHANGELOG.md | 4 ++++ napi/NEXT_CHANGELOG.md | 2 ++ pyo3/NEXT_CHANGELOG.md | 2 ++ pyo3/tests/test_module.py | 3 ++- 4 files changed, 10 insertions(+), 1 deletion(-) diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index 2ebce050..a8d38ee7 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -11,6 +11,10 @@ changes go in their respective binding's NEXT_CHANGELOG. ### Added +- Configure the Arrow result LZ4 session default with `ResultConfig.lz4_compression_enabled` + (client config key `lz4_compression_enabled`) and override it with `StatementSpec::lz4_compression`. + ADBC exposes the default through `adbc.databricks.enable_query_result_lz4_compression`. + ### Changed ### Updated diff --git a/napi/NEXT_CHANGELOG.md b/napi/NEXT_CHANGELOG.md index 8597f31e..c9fd41ae 100644 --- a/napi/NEXT_CHANGELOG.md +++ b/napi/NEXT_CHANGELOG.md @@ -14,6 +14,8 @@ layout, or npm publishing. Pure-kernel changes go in the root ### Added +- `ExecuteOptions.lz4Compression` overrides Arrow result LZ4 compression per statement. + ### Changed ### Updated diff --git a/pyo3/NEXT_CHANGELOG.md b/pyo3/NEXT_CHANGELOG.md index e0881e54..0d9129ad 100644 --- a/pyo3/NEXT_CHANGELOG.md +++ b/pyo3/NEXT_CHANGELOG.md @@ -13,6 +13,8 @@ changes go in the root `NEXT_CHANGELOG.md`. ### Added +- `Statement.set_lz4_compression` overrides Arrow result LZ4 compression per statement. + ### Changed ### Updated diff --git a/pyo3/tests/test_module.py b/pyo3/tests/test_module.py index 4ea65618..728681cd 100644 --- a/pyo3/tests/test_module.py +++ b/pyo3/tests/test_module.py @@ -39,5 +39,6 @@ def test_exports_expected_classes(): assert expected.issubset(actual), f"missing exports: {expected - actual}" -def test_statement_exposes_row_limit(): +def test_statement_exposes_public_setters(): assert callable(k.Statement.set_row_limit) + assert callable(k.Statement.set_lz4_compression) From b305326f59ec67bcbfd9ff926674e3894578d138 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Fri, 27 Nov 2026 22:23:21 +0000 Subject: [PATCH 3/3] test(pyo3): verify statement compression reaches execute requests Signed-off-by: Aakash Saravanan --- pyo3/tests/sql_api.py | 4 +++- pyo3/tests/test_fetch.py | 15 +++++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/pyo3/tests/sql_api.py b/pyo3/tests/sql_api.py index e4335bdf..21c3d175 100644 --- a/pyo3/tests/sql_api.py +++ b/pyo3/tests/sql_api.py @@ -28,6 +28,7 @@ def sql_api(session_type, arrow_bytes=None): batches=[[1, 2]] if arrow_bytes else [], mode="buffered", requests=[], + statement_bodies=[], chunk_requested=threading.Event(), release_chunk=threading.Event(), statement_closed=threading.Event(), @@ -37,13 +38,14 @@ def sql_api(session_type, arrow_bytes=None): class Handler(BaseHTTPRequestHandler): def reply(self): - self.rfile.read(int(self.headers.get("Content-Length", 0))) + body = self.rfile.read(int(self.headers.get("Content-Length", 0))) path = self.path.split("?")[0] state.requests.append((self.command, path)) status, response = 200, {} if self.command == "POST" and path.endswith("/sessions"): response = {"session_id": "00000000-0000-0000-0000-000000000001"} elif self.command == "POST" and path.endswith("/statements"): + state.statement_bodies.append(json.loads(body)) pending = state.mode != "buffered" raw = arrow_bytes(state.batches) if state.batches else b"" count = sum(map(len, state.batches)) diff --git a/pyo3/tests/test_fetch.py b/pyo3/tests/test_fetch.py index e23e5f76..b26e5e9a 100644 --- a/pyo3/tests/test_fetch.py +++ b/pyo3/tests/test_fetch.py @@ -48,6 +48,21 @@ def execute(sql_api): return statement, statement.execute() +def test_statement_forwards_lz4_compression_override(sql_api): + statement = sql_api.session.statement() + try: + statement.set_sql("SELECT n") + statement.set_lz4_compression(False) + statement.execute().close() + assert sql_api.statement_bodies[-1]["result_compression"] == "NONE" + + statement.set_lz4_compression(None) + statement.execute().close() + assert sql_api.statement_bodies[-1]["result_compression"] == "LZ4_FRAME" + finally: + statement.close() + + @pytest.mark.parametrize("batches", [[], [[1, 2]], [[], [1, 2], [3]]]) def test_buffered_fetch_closes_once_after_exhaustion(sql_api, batches): sql_api.batches = batches