Skip to content
Merged
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 @@ -228,6 +228,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 @@ -314,12 +315,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.
3 changes: 3 additions & 0 deletions NEXT_CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,9 @@ changes go in their respective binding's NEXT_CHANGELOG.
allowed directories. A transfer fails after `HttpConfig::request_timeout`
without progress. On Unix a GET can also write into an existing pipe or
character device as the download arrives.
- 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

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
Comment thread
oss-reviewer-bot[bot] marked this conversation as resolved.
Resolved
Comment thread
aakash-saravanan-db 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 @@ -1248,6 +1253,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
9 changes: 5 additions & 4 deletions include/databricks_kernel.h
Original file line number Diff line number Diff line change
Expand Up @@ -628,10 +628,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 @@ -642,6 +640,9 @@ 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
Comment thread
oss-reviewer-bot[bot] marked this conversation as resolved.
Resolved
* for Arrow results. Sets the session default; defaults to "true".
* The C ABI has no per-statement compression setter.
* - "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
1 change: 1 addition & 0 deletions napi/NEXT_CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ layout, or npm publishing. Pure-kernel changes go in the root
- `ConnectionOptions.port`: an optional connection port. A value outside
`0..=65535`, or a host the kernel can't combine with the port, gives
`InvalidArgument`.
- `ExecuteOptions.lz4Compression` overrides Arrow result LZ4 compression per statement.

### Changed

Expand Down
5 changes: 4 additions & 1 deletion napi/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
* `key:value` wire shape NodeJS Thrift's `serializeQueryTags`
* produces (`lib/utils/queryTags.ts`). Backslashes in keys are
* doubled; backslash/colon/comma in values are backslash-escaped.
* - `lz4Compression` — override the session default for Arrow result compression
*
* `rowLimit` (SEA `row_limit`) is exposed here and threaded onto the kernel
* `StatementSpec`. `positionalParams` (`?`) and `namedParams` (`:name`)
Expand Down Expand Up @@ -68,6 +69,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 Expand Up @@ -1077,7 +1080,7 @@ export declare class Connection {
* uses (`runAsync: true`): the SEA backend submits, returns a
* pending operation handle, and polls to terminal during
* fetch. Option semantics (statementConf / queryTags /
* rowLimit / positional + named params) match `executeStatement`.
* rowLimit / lz4Compression / positional + named params) match `executeStatement`.
* Submit always sends `wait_timeout=0s` so the call returns
* immediately; the caller drives completion via `status()` /
* `awaitResult()`. Only the blocking-vs-pending return contract
Expand Down
26 changes: 20 additions & 6 deletions napi/src/connection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ use crate::util::guarded;
/// `key:value` wire shape NodeJS Thrift's `serializeQueryTags`
/// produces (`lib/utils/queryTags.ts`). Backslashes in keys are
/// doubled; backslash/colon/comma in values are backslash-escaped.
/// - `lz4Compression` — override the session default for Arrow result compression
///
/// `rowLimit` (SEA `row_limit`) is exposed here and threaded onto the kernel
/// `StatementSpec`. `positionalParams` (`?`) and `namedParams` (`:name`)
Expand Down Expand Up @@ -102,6 +103,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 +193,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 +219,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 +298,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 +346,7 @@ impl Connection {
statement_conf,
query_tags,
row_limit,
lz4_compression,
positional_params,
named_params,
raw_params,
Expand Down Expand Up @@ -387,6 +392,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 +421,7 @@ impl Connection {
statement_conf,
query_tags,
row_limit,
lz4_compression,
positional_params,
named_params,
raw_params,
Expand Down Expand Up @@ -460,6 +467,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 +503,7 @@ impl Connection {
statement_conf,
query_tags,
row_limit,
lz4_compression,
positional_params,
named_params,
raw_params,
Expand All @@ -518,7 +527,7 @@ impl Connection {
/// uses (`runAsync: true`): the SEA backend submits, returns a
/// pending operation handle, and polls to terminal during
/// fetch. Option semantics (statementConf / queryTags /
/// rowLimit / positional + named params) match `executeStatement`.
/// rowLimit / lz4Compression / positional + named params) match `executeStatement`.
/// Submit always sends `wait_timeout=0s` so the call returns
/// immediately; the caller drives completion via `status()` /
/// `awaitResult()`. Only the blocking-vs-pending return contract
Expand All @@ -533,6 +542,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 +583,7 @@ impl Connection {
statement_conf,
query_tags,
row_limit,
lz4_compression,
positional_params,
named_params,
raw_params,
Expand Down Expand Up @@ -756,6 +767,7 @@ mod tests {
None,
None,
None,
Some(false),
vec![],
vec![],
vec![raw()],
Expand All @@ -778,6 +790,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 +802,7 @@ mod tests {
None,
None,
None,
None,
vec![TypedValue::Int32(1)],
vec![],
vec![raw()],
Expand Down
1 change: 1 addition & 0 deletions pyo3/NEXT_CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ changes go in the root `NEXT_CHANGELOG.md`.
- `Session(..., port=None)`: an optional connection port. A value outside
`0..=65535` raises `ValueError`; a host the kernel can't combine with the port
raises `KernelError` (`InvalidArgument`).
- `Statement.set_lz4_compression` overrides Arrow result LZ4 compression per statement.

### Changed
- Allow pyarrow 24.x through 26.x on Python 3.10+ (`pyarrow>=23.0.1,<27`),
Expand Down
11 changes: 11 additions & 0 deletions pyo3/src/statement.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,17 @@ impl Statement {
Ok(())
}

/// Set LZ4 compression for Arrow results.
///
/// The setting persists across ``set_sql`` calls until changed or reset with
/// ``None``. ``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
Loading
Loading