Skip to content
Open
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
7 changes: 4 additions & 3 deletions CONNECTION_PARAMETERS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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` |
Expand Down Expand Up @@ -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.
4 changes: 4 additions & 0 deletions NEXT_CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 4 additions & 0 deletions adbc/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
27 changes: 27 additions & 0 deletions adbc/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand Down Expand Up @@ -372,6 +374,9 @@ impl DatabaseConfig {
CLOUDFETCH_ENABLED | "databricks.cloudfetch.enabled" => {
self.result.cloudfetch_enabled = boolean_compat(value, key)?
}
ENABLE_QUERY_RESULT_LZ4_COMPRESSION => {
Comment thread
oss-reviewer-bot[bot] marked this conversation as resolved.
Resolved
Comment thread
oss-reviewer-bot[bot] marked this conversation as resolved.
Resolved
self.result.lz4_compression_enabled = boolean_compat(value, key)?
}
PROTOCOL => {
let protocol = string_value(value, key)?;
if !protocol.eq_ignore_ascii_case("rest") {
Expand Down Expand Up @@ -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();
Expand Down
8 changes: 4 additions & 4 deletions include/databricks_kernel.h
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Low — PyO3 (set_lz4_compression) and napi (lz4Compression) expose the per-statement override, but the C ABI only gets the session-level client-conf key. ODBC and Go hosts therefore can't override compression per statement. Add a kernel_statement_set_lz4_compression setter, or document that the C ABI only supports the session default.

🔀 Found by Claude Opus 5.5 · the judge couldn't confirm it

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The C ABI exposes the session default through kernel_session_config_set_client_conf, which takes KernelSessionConfig in the header. ODBC's connection-string setting uses that path. Per-statement overrides are exposed by the Rust, PyO3 and napi interfaces. This is the scope confirmed in the accepted clarification.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Still open at b305326: include/databricks_kernel.h:597-598 does not say the C ABI supports only the session default, and there is no statement setter.

* 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).
Expand Down
2 changes: 2 additions & 0 deletions napi/NEXT_CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 2 additions & 0 deletions napi/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
23 changes: 18 additions & 5 deletions napi/src/connection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<i64>,
/// Request LZ4 compression for Arrow results. Omit to use the session default.
pub lz4_compression: Option<bool>,
/// 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
Expand Down Expand Up @@ -190,6 +192,7 @@ fn build_statement(
statement_conf: Option<HashMap<String, String>>,
query_tags: Option<HashMap<String, Option<String>>>,
row_limit: Option<i64>,
lz4_compression: Option<bool>,
positional_params: Vec<TypedValue>,
named_params: Vec<(String, TypedValue)>,
raw_params: Vec<RawParameterInput>,
Expand All @@ -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()
Expand Down Expand Up @@ -293,11 +297,10 @@ impl Connection {
mut options: Option<ExecuteOptions>,
) -> napi::Result<Statement> {
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())
Expand Down Expand Up @@ -342,6 +345,7 @@ impl Connection {
statement_conf,
query_tags,
row_limit,
lz4_compression,
positional_params,
named_params,
raw_params,
Expand Down Expand Up @@ -387,6 +391,7 @@ impl Connection {
) -> napi::Result<napi::Either<Statement, AsyncStatement>> {
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())
Expand Down Expand Up @@ -415,6 +420,7 @@ impl Connection {
statement_conf,
query_tags,
row_limit,
lz4_compression,
positional_params,
named_params,
raw_params,
Expand Down Expand Up @@ -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())
Expand Down Expand Up @@ -495,6 +502,7 @@ impl Connection {
statement_conf,
query_tags,
row_limit,
lz4_compression,
positional_params,
named_params,
raw_params,
Expand Down Expand Up @@ -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())
Expand Down Expand Up @@ -573,6 +582,7 @@ impl Connection {
statement_conf,
query_tags,
row_limit,
lz4_compression,
positional_params,
named_params,
raw_params,
Expand Down Expand Up @@ -756,6 +766,7 @@ mod tests {
None,
None,
None,
Some(false),
vec![],
vec![],
vec![raw()],
Expand All @@ -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" }])
Expand All @@ -789,6 +801,7 @@ mod tests {
None,
None,
None,
None,
vec![TypedValue::Int32(1)],
vec![],
vec![raw()],
Expand Down
2 changes: 2 additions & 0 deletions pyo3/NEXT_CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
8 changes: 8 additions & 0 deletions pyo3/src/statement.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<bool>) -> PyResult<()> {
Comment thread
oss-reviewer-bot[bot] marked this conversation as resolved.
Resolved
Comment thread
oss-reviewer-bot[bot] marked this conversation as resolved.
Resolved
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<i64>) -> PyResult<()> {
let inner = alive_mut!(self, "Statement");
Expand Down
4 changes: 3 additions & 1 deletion pyo3/tests/sql_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
Expand All @@ -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))
Expand Down
15 changes: 15 additions & 0 deletions pyo3/tests/test_fetch.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
3 changes: 2 additions & 1 deletion pyo3/tests/test_module.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Comment thread
oss-reviewer-bot[bot] marked this conversation as resolved.
Resolved
17 changes: 6 additions & 11 deletions src/c_abi/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down
10 changes: 9 additions & 1 deletion src/client/sea.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
Expand All @@ -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(),
};
Expand Down
Loading
Loading