From d41cc3657748966d8b69a802bc40e8d019022ceb Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Wed, 11 Nov 2026 22:38:50 +0000 Subject: [PATCH 01/39] feat(volume): complete SQL file transfers in the shared kernel Signed-off-by: Aakash Saravanan --- Cargo.toml | 2 +- adbc/README.md | 6 + adbc/src/statement.rs | 11 + include/databricks_kernel.h | 4 + napi/index.d.ts | 1 + napi/src/connection.rs | 21 ++ pyo3/src/statement.rs | 7 + src/c_abi/statement.rs | 26 ++ src/client/http.rs | 7 + src/client/sea.rs | 1 + src/reader/mod.rs | 2 + src/reader/post_processor/mod.rs | 1 + src/session.rs | 4 +- src/statement/executed_async.rs | 34 +- src/statement/mod.rs | 1 + src/statement/mutable.rs | 26 +- src/statement/spec.rs | 9 + src/statement/volume.rs | 521 +++++++++++++++++++++++++++++ src/types/sea.rs | 2 + tests/v0_async_execute_wiremock.rs | 57 ++++ 20 files changed, 727 insertions(+), 16 deletions(-) create mode 100644 src/statement/volume.rs diff --git a/Cargo.toml b/Cargo.toml index f428c382..19951cdf 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -91,7 +91,7 @@ moka = { version = "0.12.16", features = ["future"] } # Async utilities futures = "0.3" -tokio-util = "0.7" +tokio-util = { version = "0.7", features = ["io"] } async-trait = "0.1" # Error handling diff --git a/adbc/README.md b/adbc/README.md index 440f8018..e3e1730e 100644 --- a/adbc/README.md +++ b/adbc/README.md @@ -128,6 +128,12 @@ It preserves `%` wildcards and existing `\_` escapes and does not alter schema, table, or column patterns. Set it to `false` for raw ADBC catalog-pattern semantics. +`adbc.databricks.statement.staging_allowed_local_paths` accepts a JSON array +of local paths, for example `["/tmp/transfers"]`, and enables SQL PUT, GET, +and REMOVE file transfers. An empty array permits REMOVE and denies local +file access. Without the option, results remain available to callers that +handle transfers themselves. + Statement options include positional or named parameter style, query tags, the portable `adbc.apache.statement.query_timeout_s` client deadline (with `0` meaning unlimited), a millisecond Databricks client-timeout alias, server diff --git a/adbc/src/statement.rs b/adbc/src/statement.rs index 1a6b5899..90defb9d 100644 --- a/adbc/src/statement.rs +++ b/adbc/src/statement.rs @@ -470,6 +470,17 @@ impl Statement { return Ok(()); } match key { + "adbc.databricks.statement.staging_allowed_local_paths" => { + let paths = serde_json::from_str::>(&expect_string(value, key)?) + .map_err(|_| { + adbc_error( + "Expected a JSON array of allowed local paths", + Status::InvalidArguments, + ) + })?; + self.inner()?.spec().staging_allowed_local_paths = Some(paths); + Ok(()) + } ENABLE_DIRECT_RESULTS_OPTION => { self.enable_direct_results = expect_bool_string(value, key)?; Ok(()) diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h index 965c09b6..a91d2af7 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -688,6 +688,10 @@ KernelStatusCode kernel_session_rollback(kernel_session_t* session); * so a reused statement handle starts each query with a fresh parameter set. */ KernelStatusCode kernel_statement_set_sql(kernel_statement_t* stmt, const char* sql); +/** Configure a JSON array of allowed local paths for SQL file transfers. */ +KernelStatusCode kernel_statement_set_staging_allowed_local_paths( + kernel_statement_t* stmt, const char* paths_json, bool retain_result); + /* Typed positional parameter binding (1-based ordinal); the kernel infers the * SEA wire type from the C type. These are the "typed params" the * kernel_statement_bind_parameter contract refers to: within one statement they diff --git a/napi/index.d.ts b/napi/index.d.ts index bcb54502..01325ed8 100644 --- a/napi/index.d.ts +++ b/napi/index.d.ts @@ -38,6 +38,7 @@ * path is the one the production code uses. */ export interface ExecuteOptions { + stagingAllowedLocalPaths?: string[] /** * Per-statement Spark conf overlay. Merged on top of the * session-level `sessionConf` at execute time; this map wins diff --git a/napi/src/connection.rs b/napi/src/connection.rs index 7aba91ff..53f56031 100644 --- a/napi/src/connection.rs +++ b/napi/src/connection.rs @@ -102,6 +102,7 @@ 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, + pub staging_allowed_local_paths: 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 @@ -193,6 +194,7 @@ fn build_statement( positional_params: Vec, named_params: Vec<(String, TypedValue)>, raw_params: Vec, + staging_allowed_local_paths: Option>, ) -> napi::Result { // Positional/named mutual-exclusivity is enforced in the kernel's // `build_execute_params` (StatementSpec dispatch), so every binding @@ -200,6 +202,7 @@ fn build_statement( // No napi-layer guard needed here. let mut stmt = session.statement(); stmt.spec().sql(sql); + stmt.spec().staging_allowed_local_paths = staging_allowed_local_paths; // Set the explicit per-statement conf overlay first (only when non-empty) // so the kernel's `query_tags` merge can detect a dual definition against it. if let Some(conf) = statement_conf { @@ -322,6 +325,9 @@ impl Connection { // `queryTags` + `statementConf["query_tags"]` definition. let statement_conf = options.as_mut().and_then(|o| o.statement_conf.take()); let query_tags = options.as_mut().and_then(|o| o.query_tags.take()); + let staging_allowed_local_paths = options + .as_mut() + .and_then(|o| o.staging_allowed_local_paths.take()); guarded(async move { // Build the kernel `Statement` while holding the session lock, // then RELEASE the lock before `execute().await`. `Session::statement()` @@ -345,6 +351,7 @@ impl Connection { positional_params, named_params, raw_params, + staging_allowed_local_paths, )? // session lock released here }; @@ -405,6 +412,9 @@ impl Connection { .unwrap_or_default(); let statement_conf = options.as_mut().and_then(|o| o.statement_conf.take()); let query_tags = options.as_mut().and_then(|o| o.query_tags.take()); + let staging_allowed_local_paths = options + .as_mut() + .and_then(|o| o.staging_allowed_local_paths.take()); guarded(async move { let mut stmt = { let guard = inner.lock().await; @@ -418,6 +428,7 @@ impl Connection { positional_params, named_params, raw_params, + staging_allowed_local_paths, )? }; @@ -478,6 +489,9 @@ impl Connection { .unwrap_or_default(); let statement_conf = options.as_mut().and_then(|o| o.statement_conf.take()); let query_tags = options.as_mut().and_then(|o| o.query_tags.take()); + let staging_allowed_local_paths = options + .as_mut() + .and_then(|o| o.staging_allowed_local_paths.take()); guarded(async move { // Build the kernel `Statement` under the session lock, release // the lock, then hand the built statement to the @@ -498,6 +512,7 @@ impl Connection { positional_params, named_params, raw_params, + staging_allowed_local_paths, )? // session lock released here }; @@ -553,6 +568,9 @@ impl Connection { // kernel `StatementSpec` owns the merge + serialisation. let statement_conf = options.as_mut().and_then(|o| o.statement_conf.take()); let query_tags = options.as_mut().and_then(|o| o.query_tags.take()); + let staging_allowed_local_paths = options + .as_mut() + .and_then(|o| o.staging_allowed_local_paths.take()); guarded(async move { // Build the kernel `Statement` while holding the session lock, // then RELEASE the lock before `submit().await` — same shape as @@ -576,6 +594,7 @@ impl Connection { positional_params, named_params, raw_params, + staging_allowed_local_paths, )? // session lock released here }; @@ -759,6 +778,7 @@ mod tests { vec![], vec![], vec![raw()], + None, ) .expect("raw statement builds"); let dispatched_err = raw_stmt @@ -792,6 +812,7 @@ mod tests { vec![TypedValue::Int32(1)], vec![], vec![raw()], + None, ) .expect("mixed statement builds before dispatch validation"); let mixed_err = mixed_stmt diff --git a/pyo3/src/statement.rs b/pyo3/src/statement.rs index 7f2dc3e8..de89668f 100644 --- a/pyo3/src/statement.rs +++ b/pyo3/src/statement.rs @@ -66,6 +66,13 @@ impl Statement { Ok(()) } + /// Set the local paths permitted for SQL PUT and GET transfers. + fn set_staging_allowed_local_paths(&mut self, paths: Vec) -> PyResult<()> { + let inner = alive_mut!(self, "Statement"); + inner.stmt.spec().staging_allowed_local_paths = Some(paths); + 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/statement.rs b/src/c_abi/statement.rs index 5f10c9dd..34cb1f99 100644 --- a/src/c_abi/statement.rs +++ b/src/c_abi/statement.rs @@ -159,6 +159,32 @@ pub enum KernelStatementStatusKind { Closed = 5, } +/// Configure permitted local paths from a JSON array for SQL file transfers. +/// +/// # Safety +/// `stmt` must be live and `paths_json` must be a NUL-terminated UTF-8 string. +#[no_mangle] +pub unsafe extern "C" fn kernel_statement_set_staging_allowed_local_paths( + stmt: *mut kernel_statement_t, + paths_json: *const c_char, + retain_result: bool, +) -> KernelStatusCode { + with_statement(stmt, |stmt| { + if paths_json.is_null() { + return Err(Error::invalid_argument().message("paths_json must not be null")); + } + let json = CStr::from_ptr(paths_json) + .to_str() + .map_err(|_| Error::invalid_argument().message("paths_json must be UTF-8"))?; + let paths: Vec = serde_json::from_str(json).map_err(|_| { + Error::invalid_argument().message("paths_json must be an array of paths") + })?; + stmt.spec().staging_allowed_local_paths = Some(paths); + stmt.spec().retain_volume_operation_result = retain_result; + Ok(()) + }) +} + // ─── Crate-internal raw-handle helpers ─────────────────────────────────────── /// Box a [`Statement`] and erase it to the opaque C handle type. diff --git a/src/client/http.rs b/src/client/http.rs index e5f9ad0b..d120f7cd 100644 --- a/src/client/http.rs +++ b/src/client/http.rs @@ -736,6 +736,13 @@ impl DatabricksHttpClient { &self.client } + pub(crate) fn storage_retry_config(&self) -> RetryConfig { + self.retry_configs + .get(&RequestCategory::CloudFetch) + .cloned() + .unwrap_or_default() + } + /// Get the authorization header value. /// /// Returns an error if the auth provider has not been set via `set_auth_provider()`. diff --git a/src/client/sea.rs b/src/client/sea.rs index 2a490aac..d8e0d3d2 100644 --- a/src/client/sea.rs +++ b/src/client/sea.rs @@ -2429,6 +2429,7 @@ mod tests { error_details_json: None, }, manifest: Some(ResultManifest { + is_volume_operation: false, format: "ARROW_STREAM".to_string(), schema: ResultSchema { column_count: 0, diff --git a/src/reader/mod.rs b/src/reader/mod.rs index c9532fbf..067e22b6 100644 --- a/src/reader/mod.rs +++ b/src/reader/mod.rs @@ -1455,6 +1455,7 @@ mod tests { fn make_manifest(columns: Vec) -> ResultManifest { ResultManifest { + is_volume_operation: false, format: "ARROW_STREAM".to_string(), schema: ResultSchema { column_count: columns.len() as i32, @@ -2129,6 +2130,7 @@ mod tests { fn minimal_manifest(total_chunk_count: Option) -> ResultManifest { ResultManifest { + is_volume_operation: false, format: "ARROW_STREAM".to_string(), schema: ResultSchema { column_count: 0, diff --git a/src/reader/post_processor/mod.rs b/src/reader/post_processor/mod.rs index a57b5d5d..e5f142e0 100644 --- a/src/reader/post_processor/mod.rs +++ b/src/reader/post_processor/mod.rs @@ -467,6 +467,7 @@ mod tests { fn make_manifest(columns: Vec) -> ResultManifest { ResultManifest { + is_volume_operation: false, format: "ARROW_STREAM".to_string(), schema: ResultSchema { column_count: columns.len() as i32, diff --git a/src/session.rs b/src/session.rs index 1a64a209..c413704f 100644 --- a/src/session.rs +++ b/src/session.rs @@ -97,6 +97,7 @@ pub(crate) struct SessionInner { /// behind the trait object; future variants slot in via /// `TransportMode`. transport: Arc, + pub(crate) http_client: Arc, /// Server-issued session identifier. session_id: String, @@ -460,7 +461,7 @@ impl Session { &config.connection, &config.auth, config.driver_system_configuration.clone(), - http_client, + http_client.clone(), session_info.session_id.clone(), )); telemetry @@ -480,6 +481,7 @@ impl Session { Ok(Session { inner: Arc::new(SessionInner { transport, + http_client, session_id: session_info.session_id, config, runtime_handle, diff --git a/src/statement/executed_async.rs b/src/statement/executed_async.rs index 0fc9f09a..3abf1fbb 100644 --- a/src/statement/executed_async.rs +++ b/src/statement/executed_async.rs @@ -221,6 +221,8 @@ pub struct ExecutedAsyncStatement { /// don't `.await` and the poll loop releases the lock before /// every network round-trip. latest_status: Arc>, + pub(crate) volume_options: super::volume::VolumeOptions, + volume_completion: Arc>>, statement_telemetry: StatementTelemetry, /// Set once result materialisation hands success finalization to /// the returned `ResultStream`. @@ -331,6 +333,8 @@ impl ExecutedAsyncStatement { owning: true, session_attribution: SessionAttribution::Current, latest_status: Arc::new(std::sync::Mutex::new(initial_status)), + volume_options: super::volume::VolumeOptions::default(), + volume_completion: Arc::new(tokio::sync::OnceCell::new()), statement_telemetry, result_stream_owns_success_telemetry: AtomicBool::new(false), client_deadline, @@ -390,6 +394,8 @@ impl ExecutedAsyncStatement { owning: false, session_attribution, latest_status: Arc::new(std::sync::Mutex::new(initial_status)), + volume_options: super::volume::VolumeOptions::default(), + volume_completion: Arc::new(tokio::sync::OnceCell::new()), statement_telemetry: StatementTelemetry::noop(), result_stream_owns_success_telemetry: AtomicBool::new(false), client_deadline: None, @@ -408,16 +414,17 @@ impl ExecutedAsyncStatement { .lock() .map_err(|error| Error::internal().message(format!("Statement status lock: {error}")))? .clone(); - Ok(AsyncStatementReader { - inner: Self::new_read_only( - Arc::clone(&self.session), - self.statement_id.clone(), - self.valid.clone(), - Arc::clone(&self.owner_released), - self.session_attribution, - status, - ), - }) + let mut inner = Self::new_read_only( + Arc::clone(&self.session), + self.statement_id.clone(), + self.valid.clone(), + Arc::clone(&self.owner_released), + self.session_attribution, + status, + ); + inner.volume_options = self.volume_options.clone(); + inner.volume_completion = Arc::clone(&self.volume_completion); + Ok(AsyncStatementReader { inner }) } fn check_owner_available(&self) -> Result<()> { @@ -874,6 +881,13 @@ impl ExecutedAsyncStatement { if result.status.state == crate::types::sea::StatementState::Closed { self.closed.store(true, Ordering::Release); } + let result = super::volume::complete( + &self.session.http_client, + result, + &self.volume_options, + &self.volume_completion, + ) + .await?; let mut stream = ResultStream::from_reader(result.reader).await?; stream.attach_telemetry(self.statement_telemetry.clone()); // SEA carries no row count on the async status either; for a diff --git a/src/statement/mod.rs b/src/statement/mod.rs index 4f2f92df..1784fbfc 100644 --- a/src/statement/mod.rs +++ b/src/statement/mod.rs @@ -35,6 +35,7 @@ pub mod spec; pub(crate) mod timeout; pub(crate) mod validity; +pub(crate) mod volume; // Re-exports so wrappers can write `crate::statement::Statement` instead // of the deeper submodule paths. The crate-root re-exports in `lib.rs` diff --git a/src/statement/mutable.rs b/src/statement/mutable.rs index 5925fed9..8691ad9d 100644 --- a/src/statement/mutable.rs +++ b/src/statement/mutable.rs @@ -409,6 +409,13 @@ impl Statement { self.last_valid = Some(valid.clone()); self.last_closed = Some(Arc::clone(&closed)); + let result = super::volume::complete( + &self.session.http_client, + result, + &super::volume::VolumeOptions::from(&self.spec), + &tokio::sync::OnceCell::new(), + ) + .await?; let mut result_stream = ResultStream::from_reader(result.reader).await?; result_stream.attach_telemetry(telemetry_for_body.clone()); // SEA puts no row count on the status envelope; for a DML it @@ -535,7 +542,7 @@ impl Statement { self.last_valid = Some(valid.clone()); self.last_closed = Some(Arc::clone(&closed)); - Ok(ExecutedAsyncStatement::new( + let mut executed = ExecutedAsyncStatement::new( Arc::clone(&self.session), response.statement_id, valid, @@ -549,7 +556,9 @@ impl Statement { response.status, telemetry_for_body, timeout, - )) + ); + executed.volume_options = super::volume::VolumeOptions::from(&self.spec); + Ok(executed) } .instrument(span) .await; @@ -644,6 +653,13 @@ impl Statement { self.last_statement_id = Some(result.statement_id.clone()); self.last_valid = Some(valid.clone()); self.last_closed = Some(Arc::clone(&closed)); + let result = super::volume::complete( + &self.session.http_client, + result, + &super::volume::VolumeOptions::from(&self.spec), + &tokio::sync::OnceCell::new(), + ) + .await?; let mut result_stream = ResultStream::from_reader(result.reader).await?; result_stream.attach_telemetry(telemetry_for_body.clone()); let executed = ExecutedStatement::new( @@ -667,7 +683,7 @@ impl Statement { self.last_statement_id = Some(resp.statement_id.clone()); self.last_valid = Some(valid.clone()); self.last_closed = Some(Arc::clone(&closed)); - Ok(DirectStatement::Running(ExecutedAsyncStatement::new( + let mut executed = ExecutedAsyncStatement::new( Arc::clone(&self.session), resp.statement_id, valid, @@ -675,7 +691,9 @@ impl Statement { resp.status, telemetry_for_body, ExecutionTimeout::Default, - ))) + ); + executed.volume_options = super::volume::VolumeOptions::from(&self.spec); + Ok(DirectStatement::Running(executed)) } } } diff --git a/src/statement/spec.rs b/src/statement/spec.rs index 288bb0ae..e4f9fc2b 100644 --- a/src/statement/spec.rs +++ b/src/statement/spec.rs @@ -222,6 +222,15 @@ pub struct StatementSpec { /// Result wire format. pub result_format: ResultFormat, + + /// Local paths permitted for SQL file transfers. `None` leaves transfer + /// instructions available to a caller that handles them itself. An empty list + /// enables REMOVE while denying local file access. + pub staging_allowed_local_paths: Option>, + + /// Preserve the instruction row after a successful transfer for APIs + /// whose existing result contract includes that row. + pub retain_volume_operation_result: bool, } impl StatementSpec { diff --git a/src/statement/volume.rs b/src/statement/volume.rs new file mode 100644 index 00000000..101d944e --- /dev/null +++ b/src/statement/volume.rs @@ -0,0 +1,521 @@ +// Copyright (c) 2026 Databricks, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use crate::client::retry::{calculate_backoff, RequestType, RetryStrategy}; +use crate::client::transport::ExecuteResult; +use crate::client::DatabricksHttpClient; +use crate::kernel_error::{Error, ErrorCode, Result}; +use crate::reader::{EmptyReader, InMemoryReader}; +use crate::result_stream::{ResultBatch, ResultStream}; +use crate::statement::StatementSpec; +use arrow_array::{Array, MapArray, RecordBatch, StringArray}; +use futures::StreamExt; +use reqwest::Method; +use std::collections::HashMap; +use std::path::{Path, PathBuf}; +use tokio::io::AsyncWriteExt; +use tokio::sync::OnceCell; +use tokio_util::io::ReaderStream; + +#[derive(Clone, Default)] +pub(crate) struct VolumeOptions { + paths: Option>, + retain_result: bool, +} + +impl From<&StatementSpec> for VolumeOptions { + fn from(spec: &StatementSpec) -> Self { + Self { + paths: spec.staging_allowed_local_paths.clone(), + retain_result: spec.retain_volume_operation_result, + } + } +} + +pub(crate) async fn complete( + client: &DatabricksHttpClient, + mut result: ExecuteResult, + options: &VolumeOptions, + completion: &OnceCell>, +) -> Result { + let Some(paths) = &options.paths else { + return Ok(result); + }; + if !result + .manifest + .as_ref() + .is_some_and(|m| m.is_volume_operation) + { + return Ok(result); + } + let mut stream = ResultStream::from_reader(result.reader).await?; + let schema = stream.schema(); + let batch = match stream.next_batch().await? { + Some(ResultBatch::Arrow(batch)) if batch.num_rows() == 1 => batch.clone(), + _ => return Err(Error::invalid_state().message("Expected one file transfer instruction")), + }; + let row = stream + .next_row_in_batch() + .ok_or_else(|| Error::invalid_state().message("Missing file transfer instruction"))?; + if !(3..=4).contains(&row.num_columns()) { + return Err(Error::invalid_state().message("Invalid file transfer instruction columns")); + } + let operation = row.get_str(0)?.unwrap_or_default().to_owned(); + let url = row.get_str(1)?.unwrap_or_default().to_owned(); + let headers = instruction_headers(&batch)?; + let local_file = if row.num_columns() == 4 { + row.get_str(3)?.map(str::to_owned) + } else { + None + }; + if stream.next_batch().await?.is_some() { + return Err(Error::invalid_state().message("Expected one file transfer instruction")); + } + completion + .get_or_init(|| { + transfer( + client, + &operation, + &url, + &headers, + local_file.as_deref(), + paths, + ) + }) + .await + .clone() + .map_err(|e| { + e.with_error_code("FILE_TRANSFER_ERROR") + .with_sql_state("HY000") + .with_query_id(&result.statement_id) + })?; + result.reader = if options.retain_result { + Box::new(InMemoryReader::new(schema, vec![batch])) + } else { + Box::new(EmptyReader::new(schema)) + }; + Ok(result) +} + +fn instruction_headers(batch: &RecordBatch) -> Result> { + let invalid = || Error::invalid_state().message("Invalid file transfer headers"); + let column = batch.column(2); + if column.is_null(0) { + return Ok(HashMap::new()); + } + if let Some(map) = column.as_any().downcast_ref::() { + let entries = map.value(0); + let keys = entries + .column(0) + .as_any() + .downcast_ref::() + .ok_or_else(invalid)?; + let values = entries + .column(1) + .as_any() + .downcast_ref::() + .ok_or_else(invalid)?; + keys.iter() + .zip(values.iter()) + .map(|(key, value)| { + Ok(( + key.ok_or_else(invalid)?.to_owned(), + value.ok_or_else(invalid)?.to_owned(), + )) + }) + .collect() + } else if let Some(text) = column.as_any().downcast_ref::() { + serde_json::from_str(text.value(0)).map_err(|_| invalid()) + } else { + Err(invalid()) + } +} + +fn file_error(error: std::io::Error) -> Error { + Error::new( + if error.kind() == std::io::ErrorKind::NotFound { + ErrorCode::NotFound + } else { + ErrorCode::InvalidArgument + }, + format!("File transfer failed: {error}"), + ) +} + +fn resolved_path(path: &Path) -> Result { + match path.canonicalize() { + Ok(path) => Ok(path), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => { + let absolute = std::path::absolute(path).map_err(file_error)?; + let parent = absolute + .parent() + .ok_or_else(|| Error::invalid_argument().message("Invalid local file path"))?; + let name = absolute + .file_name() + .ok_or_else(|| Error::invalid_argument().message("Invalid local file path"))?; + Ok(parent.canonicalize().map_err(file_error)?.join(name)) + } + Err(error) => Err(file_error(error)), + } +} + +fn allowed_path(local_file: Option<&str>, paths: &[String]) -> Result { + let file = local_file.filter(|s| !s.is_empty()).ok_or_else(|| { + Error::invalid_argument().message("Local file path is required for PUT and GET") + })?; + let file = resolved_path(Path::new(file))?; + for base in paths { + let base = resolved_path(Path::new(base))?; + if file.starts_with(base) { + return Ok(file); + } + } + Err(Error::new( + ErrorCode::PermissionDenied, + "Local file operations are restricted to the configured allowed paths", + )) +} + +async fn transfer( + client: &DatabricksHttpClient, + operation: &str, + url: &str, + headers: &HashMap, + local_file: Option<&str>, + paths: &[String], +) -> Result<()> { + let method = match operation { + "PUT" => Method::PUT, + "GET" => Method::GET, + "REMOVE" => Method::DELETE, + _ => return Err(Error::invalid_state().message("Unsupported file transfer operation")), + }; + let parsed = reqwest::Url::parse(url) + .map_err(|_| Error::invalid_state().message("Invalid file transfer URL"))?; + if !matches!(parsed.scheme(), "https" | "http") { + return Err(Error::invalid_state().message("Invalid file transfer URL scheme")); + } + let local = if operation == "REMOVE" { + None + } else { + Some(allowed_path(local_file, paths)?) + }; + let response = send_transfer(client, method, parsed, headers, local.as_deref()).await?; + if !response.status().is_success() + && !(operation == "REMOVE" && response.status().as_u16() == 404) + { + return Err( + Error::from_http_status(response.status().as_u16()).message(format!( + "File transfer failed with HTTP {}", + response.status().as_u16() + )), + ); + } + if operation == "GET" { + let mut file = tokio::fs::File::create(local.as_ref().unwrap()) + .await + .map_err(file_error)?; + let mut body = response.bytes_stream(); + while let Some(bytes) = body.next().await { + let bytes = bytes + .map_err(|_| Error::new(ErrorCode::NetworkError, "File download interrupted"))?; + file.write_all(&bytes).await.map_err(file_error)?; + } + file.flush().await.map_err(file_error)?; + } + Ok(()) +} + +async fn send_transfer( + client: &DatabricksHttpClient, + method: Method, + url: reqwest::Url, + headers: &HashMap, + local: Option<&Path>, +) -> Result { + let config = client.storage_retry_config(); + let strategy = RetryStrategy::for_request(RequestType::CloudFetchDownload, &config); + let started = std::time::Instant::now(); + for attempt in 0..=config.max_retries { + let mut request = client.inner().request(method.clone(), url.clone()); + for (name, value) in headers { + request = request.header(name, value); + } + if method == Method::PUT { + let local = local + .ok_or_else(|| Error::invalid_argument().message("Missing local upload path"))?; + let metadata = tokio::fs::metadata(local).await.map_err(file_error)?; + if !metadata.is_file() { + return Err(Error::invalid_argument().message("Local upload path must be a file")); + } + // Each retry reopens the file so a streaming upload starts at byte zero. + let file = tokio::fs::File::open(local).await.map_err(file_error)?; + request = request + .header(reqwest::header::CONTENT_LENGTH, metadata.len()) + .body(reqwest::Body::wrap_stream(ReaderStream::new(file))); + } + // Presigned storage requests must omit workspace credentials and custom headers. + let response = request.send().await; + let (retryable, retry_after) = match &response { + Ok(response) => ( + strategy.is_retryable_status( + response.status(), + response + .headers() + .contains_key(reqwest::header::RETRY_AFTER), + ), + response + .headers() + .get(reqwest::header::RETRY_AFTER) + .and_then(|h| h.to_str().ok()), + ), + Err(error) => (strategy.is_retryable_error(error), None), + }; + if !retryable || attempt == config.max_retries { + return response + .map_err(|_| Error::new(ErrorCode::NetworkError, "File transfer request failed")); + } + let delay = calculate_backoff(&config, attempt, retry_after); + if started.elapsed().saturating_add(delay) >= config.overall_timeout { + return response + .map_err(|_| Error::new(ErrorCode::NetworkError, "File transfer request failed")); + } + tokio::time::sleep(delay).await; + } + unreachable!("retry loop always attempts the request") +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::client::HttpClientConfig; + use arrow_array::builder::{MapBuilder, StringBuilder}; + use std::sync::Arc; + use wiremock::matchers::{body_bytes, method, path}; + use wiremock::{Mock, MockServer, ResponseTemplate}; + + fn client() -> DatabricksHttpClient { + DatabricksHttpClient::with_default_retry(HttpClientConfig::default()).unwrap() + } + + fn instruction(operation: &str, url: &str, local: &str) -> RecordBatch { + let mut headers = MapBuilder::new(None, StringBuilder::new(), StringBuilder::new()); + headers.keys().append_value("x-file-header"); + headers.values().append_value("value"); + headers.append(true).unwrap(); + RecordBatch::try_from_iter(vec![ + ( + "operation", + Arc::new(StringArray::from(vec![operation])) as arrow_array::ArrayRef, + ), + ("url", Arc::new(StringArray::from(vec![url]))), + ("headers", Arc::new(headers.finish())), + ("local", Arc::new(StringArray::from(vec![local]))), + ]) + .unwrap() + } + + fn result(batch: RecordBatch, marker: bool) -> ExecuteResult { + ExecuteResult { + statement_id: "statement".into(), + reader: Box::new(InMemoryReader::new(batch.schema(), vec![batch])), + manifest: Some( + serde_json::from_value(serde_json::json!({ + "format": "ARROW_STREAM", "schema": {"column_count": 4}, + "is_volume_operation": marker + })) + .unwrap(), + ), + telemetry_result_format: crate::telemetry::ExecutionResultFormat::InlineArrow, + telemetry_is_compressed: false, + status: serde_json::from_value(serde_json::json!({"state":"SUCCEEDED"})).unwrap(), + } + } + + #[tokio::test] + async fn completes_transfer_once_and_preserves_requested_result() { + let server = MockServer::start().await; + Mock::given(method("GET")) + .and(path("/file")) + .respond_with(ResponseTemplate::new(200).set_body_bytes(b"file contents")) + .expect(1) + .mount(&server) + .await; + let dir = tempfile::tempdir().unwrap(); + let local = dir.path().join("download"); + let batch = instruction( + "GET", + &format!("{}/file", server.uri()), + local.to_str().unwrap(), + ); + let options = VolumeOptions { + paths: Some(vec![dir.path().to_str().unwrap().into()]), + retain_result: true, + }; + let completion = OnceCell::new(); + let http = client(); + for _ in 0..2 { + let completed = complete(&http, result(batch.clone(), true), &options, &completion) + .await + .unwrap(); + let mut reader = ResultStream::from_reader(completed.reader).await.unwrap(); + assert!(reader.next_batch().await.unwrap().is_some()); + assert!(reader.next_batch().await.unwrap().is_none()); + } + assert_eq!(tokio::fs::read(local).await.unwrap(), b"file contents"); + let request = server.received_requests().await.unwrap().remove(0); + assert!(!request.headers.contains_key("authorization")); + assert_eq!(request.headers["x-file-header"], "value"); + } + + #[tokio::test] + async fn streams_upload_and_accepts_missing_remove() { + let server = MockServer::start().await; + Mock::given(method("PUT")) + .and(path("/file")) + .and(body_bytes(b"upload")) + .respond_with(ResponseTemplate::new(200)) + .expect(1) + .mount(&server) + .await; + Mock::given(method("DELETE")) + .and(path("/file")) + .respond_with(ResponseTemplate::new(404)) + .expect(1) + .mount(&server) + .await; + let dir = tempfile::tempdir().unwrap(); + let local = dir.path().join("input"); + tokio::fs::write(&local, b"upload").await.unwrap(); + let roots = vec![dir.path().to_str().unwrap().into()]; + let http = client(); + transfer( + &http, + "PUT", + &format!("{}/file", server.uri()), + &HashMap::new(), + local.to_str(), + &roots, + ) + .await + .unwrap(); + transfer( + &http, + "REMOVE", + &format!("{}/file", server.uri()), + &HashMap::new(), + None, + &[], + ) + .await + .unwrap(); + } + + #[tokio::test] + async fn retries_upload_from_the_start() { + use std::sync::atomic::{AtomicUsize, Ordering}; + let server = MockServer::start().await; + let attempts = Arc::new(AtomicUsize::new(0)); + let observed = Arc::clone(&attempts); + Mock::given(method("PUT")) + .and(path("/file")) + .and(body_bytes(b"upload")) + .respond_with(move |_: &wiremock::Request| { + ResponseTemplate::new(if observed.fetch_add(1, Ordering::SeqCst) == 0 { + 503 + } else { + 200 + }) + }) + .expect(2) + .mount(&server) + .await; + let dir = tempfile::tempdir().unwrap(); + let file = dir.path().join("input"); + std::fs::write(&file, b"upload").unwrap(); + transfer( + &client(), + "PUT", + &format!("{}/file", server.uri()), + &HashMap::new(), + file.to_str(), + &[dir.path().to_str().unwrap().into()], + ) + .await + .unwrap(); + assert_eq!(attempts.load(Ordering::SeqCst), 2); + } + + #[tokio::test] + async fn marker_and_opt_in_are_both_required() { + let batch = instruction("GET", "http://127.0.0.1:1/file", "/unavailable"); + for (marker, options) in [ + ( + false, + VolumeOptions { + paths: Some(vec![]), + retain_result: false, + }, + ), + (true, VolumeOptions::default()), + ] { + let completed = complete( + &client(), + result(batch.clone(), marker), + &options, + &OnceCell::new(), + ) + .await + .unwrap(); + let mut reader = ResultStream::from_reader(completed.reader).await.unwrap(); + assert!(reader.next_batch().await.unwrap().is_some()); + } + } + + #[tokio::test] + async fn denies_outside_paths_before_storage_request() { + let dir = tempfile::tempdir().unwrap(); + let allowed = dir.path().join("allowed"); + std::fs::create_dir(&allowed).unwrap(); + let outside = dir.path().join("outside"); + let error = transfer( + &client(), + "GET", + "http://127.0.0.1:1/file", + &HashMap::new(), + outside.to_str(), + &[allowed.to_str().unwrap().into()], + ) + .await + .unwrap_err(); + assert_eq!(error.code, ErrorCode::PermissionDenied); + assert!(!outside.exists()); + } + + #[cfg(unix)] + #[test] + fn rejects_symlinks_that_escape_allowed_directory() { + let dir = tempfile::tempdir().unwrap(); + let allowed = dir.path().join("allowed"); + let outside = dir.path().join("outside"); + std::fs::create_dir(&allowed).unwrap(); + std::fs::create_dir(&outside).unwrap(); + std::os::unix::fs::symlink(&outside, allowed.join("link")).unwrap(); + assert!(allowed_path( + allowed.join("link/file").to_str(), + &[allowed.to_str().unwrap().into()] + ) + .is_err()); + } +} diff --git a/src/types/sea.rs b/src/types/sea.rs index 977a7b02..09b66573 100644 --- a/src/types/sea.rs +++ b/src/types/sea.rs @@ -184,6 +184,8 @@ pub struct ServiceError { /// Manifest describing the result set structure. #[derive(Debug, Clone, Deserialize)] pub struct ResultManifest { + #[serde(default)] + pub is_volume_operation: bool, pub format: String, pub schema: ResultSchema, /// Physical Arrow schema carried by SEA as a schema-only IPC stream. diff --git a/tests/v0_async_execute_wiremock.rs b/tests/v0_async_execute_wiremock.rs index 789a862f..6900d7d7 100644 --- a/tests/v0_async_execute_wiremock.rs +++ b/tests/v0_async_execute_wiremock.rs @@ -2274,3 +2274,60 @@ async fn await_result_succeeded_status_still_closes_statement() { ); // `_close` also verifies expect(1) when it drops at end of scope. } + +#[tokio::test] +async fn file_transfer_completion_is_shared_by_independent_readers() { + use arrow_array::StringArray; + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_delete_session(&server).await; + mount_close_any_statement(&server).await; + Mock::given(method("GET")) + .and(path("/storage/file")) + .respond_with(ResponseTemplate::new(200).set_body_bytes(b"download")) + .expect(1) + .mount(&server) + .await; + let dir = tempfile::tempdir().unwrap(); + let destination = dir.path().join("download"); + let batch = RecordBatch::try_from_iter(vec![ + ( + "operation", + Arc::new(StringArray::from(vec!["GET"])) as arrow_array::ArrayRef, + ), + ( + "url", + Arc::new(StringArray::from(vec![format!( + "{}/storage/file", + server.uri() + )])), + ), + ("headers", Arc::new(StringArray::from(vec!["{}"]))), + ( + "local", + Arc::new(StringArray::from(vec![destination.to_str().unwrap()])), + ), + ]) + .unwrap(); + let mut body: serde_json::Value = + serde_json::from_str(&succeeded_inline_body("transfer", &batch)).unwrap(); + body["manifest"]["is_volume_operation"] = json!(true); + mount_submit(&server, pending_body("transfer")).await; + mount_status_once(&server, "transfer", body.to_string()).await; + let session = open_session(&server).await; + let mut statement = session.statement(); + statement + .spec() + .sql("GET '/Volumes/c/s/v/file' TO '/tmp/download'"); + statement.spec().staging_allowed_local_paths = Some(vec![dir.path().to_str().unwrap().into()]); + let owner = statement.submit().await.unwrap(); + let first = owner.reader().unwrap(); + let second = owner.reader().unwrap(); + let (first, second) = tokio::join!(first.fetch_result(), second.fetch_result()); + for stream in [first, second] { + assert!(stream.unwrap().next_batch().await.unwrap().is_none()); + } + assert_eq!(std::fs::read(destination).unwrap(), b"download"); + owner.close().await.unwrap(); + session.close().await.unwrap(); +} From 87e4ea48819ab7e8f3494d6b203159c10c608387 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Wed, 11 Nov 2026 22:53:18 +0000 Subject: [PATCH 02/39] fix(volume): honor storage deadlines and independent allowed paths Signed-off-by: Aakash Saravanan --- adbc/README.md | 4 +- include/databricks_kernel.h | 2 +- napi/index.d.ts | 1 + napi/src/connection.rs | 1 + src/c_abi/statement.rs | 1 + src/statement/volume.rs | 84 ++++++++++++++++++++++++++++++++++++- 6 files changed, 88 insertions(+), 5 deletions(-) diff --git a/adbc/README.md b/adbc/README.md index e3e1730e..3c343768 100644 --- a/adbc/README.md +++ b/adbc/README.md @@ -131,8 +131,8 @@ semantics. `adbc.databricks.statement.staging_allowed_local_paths` accepts a JSON array of local paths, for example `["/tmp/transfers"]`, and enables SQL PUT, GET, and REMOVE file transfers. An empty array permits REMOVE and denies local -file access. Without the option, results remain available to callers that -handle transfers themselves. +file access. Successful transfers return no instruction rows. Without the +option, results remain available to callers that handle transfers themselves. Statement options include positional or named parameter style, query tags, the portable `adbc.apache.statement.query_timeout_s` client deadline (with `0` diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h index a91d2af7..f1a40844 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -688,7 +688,7 @@ KernelStatusCode kernel_session_rollback(kernel_session_t* session); * so a reused statement handle starts each query with a fresh parameter set. */ KernelStatusCode kernel_statement_set_sql(kernel_statement_t* stmt, const char* sql); -/** Configure a JSON array of allowed local paths for SQL file transfers. */ +/** Configure allowed local paths; retain_result keeps instructions after transfer. */ KernelStatusCode kernel_statement_set_staging_allowed_local_paths( kernel_statement_t* stmt, const char* paths_json, bool retain_result); diff --git a/napi/index.d.ts b/napi/index.d.ts index 01325ed8..8ffef883 100644 --- a/napi/index.d.ts +++ b/napi/index.d.ts @@ -38,6 +38,7 @@ * path is the one the production code uses. */ export interface ExecuteOptions { + /** Omit to handle instructions in the caller; an empty list denies local file access. */ stagingAllowedLocalPaths?: string[] /** * Per-statement Spark conf overlay. Merged on top of the diff --git a/napi/src/connection.rs b/napi/src/connection.rs index 53f56031..4b1ea4b0 100644 --- a/napi/src/connection.rs +++ b/napi/src/connection.rs @@ -102,6 +102,7 @@ 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, + /// Omit to handle instructions in the caller; an empty list denies local file access. pub staging_allowed_local_paths: Option>, /// 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/src/c_abi/statement.rs b/src/c_abi/statement.rs index 34cb1f99..48ac0e44 100644 --- a/src/c_abi/statement.rs +++ b/src/c_abi/statement.rs @@ -160,6 +160,7 @@ pub enum KernelStatementStatusKind { } /// Configure permitted local paths from a JSON array for SQL file transfers. +/// `retain_result` keeps the instruction row readable after a successful transfer. /// /// # Safety /// `stmt` must be live and `paths_json` must be a NUL-terminated UTF-8 string. diff --git a/src/statement/volume.rs b/src/statement/volume.rs index 101d944e..9421c0e3 100644 --- a/src/statement/volume.rs +++ b/src/statement/volume.rs @@ -176,7 +176,9 @@ fn allowed_path(local_file: Option<&str>, paths: &[String]) -> Result { })?; let file = resolved_path(Path::new(file))?; for base in paths { - let base = resolved_path(Path::new(base))?; + let Ok(base) = resolved_path(Path::new(base)) else { + continue; + }; if file.starts_with(base) { return Ok(file); } @@ -248,7 +250,18 @@ async fn send_transfer( let strategy = RetryStrategy::for_request(RequestType::CloudFetchDownload, &config); let started = std::time::Instant::now(); for attempt in 0..=config.max_retries { - let mut request = client.inner().request(method.clone(), url.clone()); + let remaining = config.overall_timeout.saturating_sub(started.elapsed()); + if remaining.is_zero() { + return Err(Error::new( + ErrorCode::Timeout, + "File transfer deadline exceeded", + )); + } + // Large files need the storage budget rather than the SQL request timeout. + let mut request = client + .inner() + .request(method.clone(), url.clone()) + .timeout(remaining); for (name, value) in headers { request = request.header(name, value); } @@ -503,6 +516,73 @@ mod tests { assert!(!outside.exists()); } + #[tokio::test] + async fn download_body_uses_storage_deadline() { + use crate::client::retry::{RequestCategory, RetryConfig}; + use std::time::Duration; + use tokio::io::AsyncReadExt; + for (budget, succeeds) in [(1000, true), (40, false)] { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let server = tokio::spawn(async move { + let (mut socket, _) = listener.accept().await.unwrap(); + let mut request = Vec::new(); + while !request.ends_with(b"\r\n\r\n") { + request.push(socket.read_u8().await.unwrap()); + } + socket + .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 4\r\nConnection: close\r\n\r\n") + .await + .unwrap(); + tokio::time::sleep(Duration::from_millis(100)).await; + let _ = socket.write_all(b"data").await; + }); + let config = HttpClientConfig { + read_timeout: Duration::from_millis(10), + ..Default::default() + }; + let retry = RetryConfig { + overall_timeout: Duration::from_millis(budget), + max_retries: 0, + ..Default::default() + }; + let http = DatabricksHttpClient::new( + config, + HashMap::from([(RequestCategory::CloudFetch, retry)]), + ) + .unwrap(); + let dir = tempfile::tempdir().unwrap(); + let file = dir.path().join("download"); + let result = transfer( + &http, + "GET", + &format!("http://{address}/file"), + &HashMap::new(), + file.to_str(), + &[dir.path().to_str().unwrap().into()], + ) + .await; + assert_eq!(result.is_ok(), succeeds); + if succeeds { + assert_eq!(std::fs::read(&file).unwrap(), b"data"); + } else { + assert_eq!(result.unwrap_err().code, ErrorCode::NetworkError); + } + server.await.unwrap(); + } + } + + #[test] + fn unresolvable_allowed_root_does_not_hide_later_root() { + let dir = tempfile::tempdir().unwrap(); + let file = dir.path().join("download"); + let paths = vec![ + dir.path().join("missing/nested").to_str().unwrap().into(), + dir.path().to_str().unwrap().into(), + ]; + assert_eq!(allowed_path(file.to_str(), &paths).unwrap(), file); + } + #[cfg(unix)] #[test] fn rejects_symlinks_that_escape_allowed_directory() { From 9c4ab90bae4f4ec01488722cd115e48524d89fad Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Wed, 11 Nov 2026 22:54:34 +0000 Subject: [PATCH 03/39] docs(napi): synchronize generated public binding declarations Signed-off-by: Aakash Saravanan --- napi/index.d.ts | 1825 +++++++++++++++++++++--------------------- napi/index.js | 918 +++++++++++++++------ napi/src/database.rs | 2 +- 3 files changed, 1582 insertions(+), 1163 deletions(-) diff --git a/napi/index.d.ts b/napi/index.d.ts index 8ffef883..c4702bd6 100644 --- a/napi/index.d.ts +++ b/napi/index.d.ts @@ -1,367 +1,809 @@ -/* tslint:disable */ -/* eslint-disable */ - /* auto-generated by NAPI-RS */ - +/* eslint-disable */ /** - * Per-statement options for `Connection.executeStatement`. - * - * Mirrors the kernel `StatementSpec` knobs that are safe to thread - * through napi without a kernel-side change. Today this covers: - * - `statementConf` — per-statement Spark conf overlay - * (`StatementSpec.statement_conf` → SEA `parameters` / - * Thrift `confOverlay`) - * - `queryTags` — convenience wrapper over `statementConf` with - * key `query_tags`; serialised to the same comma-separated - * `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. + * Opaque result-fetch handle returned by + * `AsyncStatement.awaitResult()`. Wraps a kernel `ResultStream` + * directly; structurally analogous to the sync `Statement`'s + * fetch-side surface (`fetchNextBatch` / `schema` / + * `statementId`). * - * `rowLimit` (SEA `row_limit`) is exposed here and threaded onto the kernel - * `StatementSpec`. `positionalParams` (`?`) and `namedParams` (`:name`) - * carry bound query parameters, decoded via `params::parse_typed_value`. - * `rawParams` forwards pre-marshalled SEA parameters unchanged. - * (There is no `queryTimeoutSecs`: it abused the SEA `wait_timeout` inline-hold - * window and was removed — a real per-statement timeout is `STATEMENT_TIMEOUT`.) + * `cancel()` / `close()` are not exposed: the parent + * `AsyncStatement` owns server-side lifecycle. A `close()` here + * would create dual-ownership of the same statement_id with + * inconsistent close semantics. Callers `close()` the parent + * `AsyncStatement` after they're done fetching. * - * **Tag-order caveat (M4 parity note).** The napi `queryTags` field - * is a Rust `HashMap` whose iteration order is - * non-deterministic, so the serialised `query_tags` value may have - * a different key order than Thrift's `serializeQueryTags` (which - * iterates `Object.keys(...)` in insertion order) for the same - * input. The SEA server is order-insensitive on conf values, so - * the two are functionally equivalent. If a caller needs - * byte-identical Thrift parity, the JS adapter pre-serialises via - * `serializeQueryTags` and writes the result into - * `statementConf["query_tags"]` directly — see - * `KernelSessionBackend.executeStatement` in the NodeJS driver. This - * path is the one the production code uses. + * Schema is cached at construction so it survives the underlying + * stream being drained; mirrors the sync `Statement.schema()` + * post-close contract. */ -export interface ExecuteOptions { - /** Omit to handle instructions in the caller; an empty list denies local file access. */ - stagingAllowedLocalPaths?: string[] +export declare class AsyncResultHandle { /** - * Per-statement Spark conf overlay. Merged on top of the - * session-level `sessionConf` at execute time; this map wins - * on key collisions. Unknown keys are rejected by the server. + * Server-issued statement id. Cached at construction; readable + * for log correlation. Matches the parent `AsyncStatement`'s + * `statementId`. */ - statementConf?: Record + get statementId(): string /** - * Query tags as key→value pairs. Serialised to a comma- - * separated `key:value` string (backslash-escaping `\`, `:`, - * `,`) and placed into `statementConf["query_tags"]`, matching - * NodeJS Thrift's `serializeQueryTags` wire shape. Passing - * both `queryTags` AND a `query_tags` key in `statementConf` - * raises `InvalidArgument` — the caller's intent is ambiguous - * so we refuse to silently pick one over the other. - * - * A **`null`** value emits a **bare key** (no colon) — e.g. - * `{ production: null }` → `"production"` — matching the - * connectors' `key`-only tag form. - * - * See the struct-level "Tag-order caveat" for the - * HashMap-iteration-order vs `Object.keys`-iteration-order - * divergence and the byte-identical-Thrift-parity workaround. + * Pull the next batch of results. Returns `null` when the + * stream is exhausted. The returned `ArrowBatch.ipcBytes` is a + * complete Arrow IPC stream (schema header + 1 record-batch + * message), suitable for handing to `apache-arrow`'s + * `RecordBatchReader`. Byte-identical to the sync + * `Statement.fetchNextBatch()` payload for the same query. */ - queryTags?: Record + fetchNextBatch(): Promise /** - * Server-side cap on the number of rows this statement returns - * (SEA `row_limit`), independent of any SQL `LIMIT`. Maps to - * `StatementSpec.row_limit`. Omitted ⇒ no driver-imposed cap. + * Result schema as an Arrow IPC payload (schema header only, + * no record-batch message). Available before any batches have + * been fetched. Sync because the body has no `.await` — + * `encode_ipc_stream` is pure CPU work over the cached + * `Arc`. */ - rowLimit?: number + schema(): ArrowSchema +} + +/** + * Opaque async-statement handle. + * + * Returned by `Connection.submitStatement(...)` after the kernel + * `Statement::submit()` returns (server sent `wait_timeout=0s`, so + * the response carries a `statement_id` but the statement is still + * `Pending`/`Running`). JS drives polling via `status()` / + * `awaitResult()`. + * + * Concurrency shape: `status()`, `awaitResult()`, and `close()` take + * `inner.lock()` and hold the guard across the kernel `.await` (tokio + * `Mutex` is FIFO), so `status()` / `close()` queue behind any + * in-flight `awaitResult()` until it returns naturally. `cancel()` is + * the deliberate exception: it does **not** touch `inner` — it fires + * through the detached `AsyncStatementCanceller` (session + + * statement_id, captured at construction), so an explicit + * `stmt.cancel()` interrupts an in-flight `awaitResult()` instead of + * queueing behind it. The server-side cancel flips the statement + * terminal, which the parked `awaitResult()` poll loop observes + * (`Cancelled`) and returns on. The kernel's `AwaitResultCancelGuard` + * still covers the drop-cancel case (Promise.race / timeout) + * independently — see module docs. + */ +export declare class AsyncStatement { /** - * 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 - * string-encoded literal or `null` for SQL NULL. Mirrors - * `StatementSpec::positional_params`; decoded via [`parse_typed_value`]. + * Server-issued statement id. Cached at construction; readable + * even after `close()` so JS-side log lines can correlate + * against kernel / server logs which key on the same id. */ - positionalParams?: Array + get statementId(): string /** - * Named parameters (`:name` placeholders). Each carries its `name` - * alongside the `{ sqlType, value? }` pair. Mapped to a kernel - * `TypedValue` via the same [`parse_typed_value`] codec and bound with - * `StatementSpec::param_named`. Named is the SEA-spec-required public - * param form (`StatementParameter.name` is `openapi_required`); - * positional is the documented-undocumented variant. The two are - * mutually exclusive at the SQL level (`?` vs `:name`). + * One-shot status check. Returns a string enum matching the + * kernel `StatementStatus` shape: + * `'Pending' | 'Running' | 'Succeeded' | 'Failed' | + * 'Cancelled' | 'Closed' | 'Unknown'`. (`'Unknown'` is the + * `#[non_exhaustive]` forward-compat catch-all that + * `StatementStatus::as_str` can return — consumers switching on + * the state must handle it.) Returns + * `KernelError(InvalidStatementHandle)` if the statement has + * been explicitly `close()`d. + * + * The `Failed` variant collapses to the string `'Failed'` on + * the JS side; the underlying error envelope (sql_state / + * error_code / query_id) is surfaced by `awaitResult()`'s + * rejection, which is where callers actually need the typed + * error. `status()` is intended for polling progress UIs + * that only need the state name. */ - namedParams?: Array + status(): Promise + /** Rows modified by the statement (UPDATE / INSERT / DELETE / MERGE). */ + numModifiedRows(): Promise /** - * Pre-marshalled parameters passed through `StatementSpec::param_raw`. - * Omit `name` for positional values. Raw parameters cannot be mixed with - * typed parameters or combine named and positional markers. + * Server-supplied user-facing message (may contain SQL fragments — + * redact before centralised logging). */ - rawParams?: Array -} -/** - * A named bound parameter — a [`TypedValueInput`] plus its `:name`. Kept a - * distinct napi object (rather than an optional `name` on `TypedValueInput`) - * so the positional surface stays a clean ordered list with no name field. - */ -export interface NamedTypedValueInput { - name: string - sqlType: string - value?: string -} -/** - * Authentication mode selector crossing the napi boundary. The string - * literals are what napi-rs emits from this `#[napi(string_enum)]` — the - * NodeJS SEA adapter (`KernelAuth`) matches them verbatim (`'Pat'`, - * `'OAuthM2m'`, `'OAuthU2m'`, `'AzureSpM2m'`). - * - * Mirrors the kernel [`AuthConfig`] variants this binding supports. - * `OAuthFederation` / `External` are intentionally not exposed yet — the - * kernel marks federation as not-yet-implemented and `External` is a - * Rust-trait escape hatch with no JS-callback bridge. - */ -export const enum AuthMode { - /** Personal access token (`token`). */ - Pat = 'Pat', - /** OAuth 2.0 machine-to-machine — `oauthClientId` + `oauthClientSecret`. */ - OAuthM2m = 'OAuthM2m', + displayMessage(): Promise + /** Server-supplied diagnostic detail. */ + diagnosticInfo(): Promise + /** Server-supplied structured error detail (JSON), when enabled. */ + errorDetailsJson(): Promise /** - * OAuth 2.0 machine-to-machine with a JWT private-key client - * assertion — `oauthClientId` + `jwtKeyFile` + `jwtKid`. + * Block until the server reaches a terminal state, then return + * an `AsyncResultHandle` that wraps the materialised result + * stream. The handle exposes `fetchNextBatch()` / `schema()` + * for consuming the result, plus `statementId` for log + * correlation. + * + * Drop-cancel safety: kernel `await_result` installs + * `AwaitResultCancelGuard` which fires a fire-and-forget + * `cancel_statement` if the future is dropped mid-poll + * (timeout, tokio::select! loser, JS-side `Promise.race` + * loser). The `util::guarded` `catch_unwind` here covers the + * V8-panic-across-boundary case on top. Returns + * `KernelError(InvalidStatementHandle)` if the statement has + * been explicitly `close()`d. */ - OAuthM2mJwt = 'OAuthM2mJwt', + awaitResult(): Promise /** - * OAuth 2.0 user-to-machine (browser flow) — optional `oauthClientId` - * + `oauthRedirectPort`. + * Server-side cancel. Returns + * `KernelError(InvalidStatementHandle)` if the statement has + * been explicitly `close()`d. Idempotent against a server + * that already reached a terminal state — the kernel's + * `cancel_statement` is a no-op there. + * + * **Lock-free by design.** Unlike `status()` / `awaitResult()` / + * `close()`, this does not take `inner.lock()` — it fires through + * the detached `AsyncStatementCanceller` captured at construction. + * That lets `stmt.cancel()` interrupt an in-flight `awaitResult()` + * (which holds the mutex for the whole poll) instead of queueing + * behind it: the server-side cancel flips the statement terminal, + * the parked `awaitResult()` poll loop observes `Cancelled` and + * returns. The closed-state check reads a lock-free flag so a + * cancel after an explicit `close()` still surfaces + * `InvalidStatementHandle`. */ - OAuthU2m = 'OAuthU2m', + cancel(): Promise /** - * Azure Entra service-principal M2M — `azureClientId` + - * `azureClientSecret` (+ optional `azureTenantId` / - * `azureWorkspaceResourceId`). The kernel builds the Entra token - * endpoint + `.default` scope, auto-discovers the tenant from the - * workspace when `azureTenantId` is omitted, and — when - * `azureWorkspaceResourceId` is set — additionally sends the SP - * management token for an RBAC-only service principal. + * Explicit close. Idempotent — a second call on an + * already-closed handle returns `Ok(())`. On `Err`, the napi + * inner is already `None`, so a JS-side retry sees the + * closed-handle short-circuit and returns `Ok(())` without + * re-attempting the wire call. The kernel's own `Drop` + * fire-and-forget retry runs once in the background. */ - AzureSpM2m = 'AzureSpM2m' + close(): Promise } + /** - * A single extra HTTP header as an explicit `{ name, value }` pair. + * Handle returned by `Connection.executeStatementCancellable`. Owns the + * built-but-not-yet-executed kernel `Statement` plus a detached + * [`StatementCanceller`] captured before dispatch, so JS can fire a + * server-side cancel while the blocking `result()` is in flight. * - * An ordered list of these (`ConnectionOptions.custom_headers`) mirrors - * the kernel core's `Vec<(String, String)>` and the pyo3 binding's - * `http_headers`: order is preserved and duplicate `name`s are allowed. - * A struct (rather than a raw `[name, value]` tuple) because napi-rs - * does not marshal Rust tuples through `#[napi(object)]` fields; the - * struct is the idiomatic, self-documenting equivalent and maps to a JS - * `{ name: string, value: string }`. - */ -export interface HeaderEntry { - name: string - value: string -} -/** - * Programmatic HTTP/HTTPS proxy configuration, mirroring the kernel's - * internal [`ProxyConfig`]. Supplied as a structured object rather than a - * flattened URL so credentials never have to be percent-encoded into the URL - * and the bypass-host list can be expressed. - * - * - `url` — proxy endpoint, e.g. `"http://proxy.corp.example.com:8080"`. Must - * use the `http://` or `https://` scheme. - * - `username` / `password` — optional proxy basic-auth, applied via - * `reqwest`'s `Proxy::basic_auth` (not embedded in the URL). - * - `bypassHosts` — optional comma-separated host/domain list that should - * bypass the proxy (e.g. `"localhost,*.internal.corp"`). + * `pending` is `Arc>>` so `result()` can + * `.take()` the statement (the kernel `execute()` borrows it `&mut`, + * then it moves into the produced `Statement` wrapper to keep its + * `ValidityFlag` set — see `statement.rs`). A second `result()` call + * after the first resolved surfaces `InvalidStatementHandle`. */ -export interface ProxyInput { - url: string - username?: string - password?: string - bypassHosts?: string +export declare class CancellableExecution { + /** + * The server-issued statement id this execution targets, if the + * server has issued one yet (`null` before the initial submit + * round-trip publishes it mid-`result()`). Useful for log + * correlation while the blocking drive is in flight. + */ + get statementId(): string | null + /** + * Drive the blocking `execute()` and resolve to a `Statement` + * (identical to what `executeStatement` returns) once the kernel + * reaches a terminal state and the result stream is ready. + * + * Consumes the pending statement: a second `result()` call returns + * `KernelError(InvalidStatementHandle)`. The future is + * drop-cancel-safe — the kernel's per-execute `MidExecuteCancelState` + * guard fires a fire-and-forget `cancel_statement` if this future is + * dropped mid-flight (`Promise.race` / timeout loser), independently + * of an explicit `cancel()`. + * + * On a server-side cancel the kernel's blocking `execute()` currently + * surfaces `InvalidArgument` (a known kernel quirk — the async path + * returns `Cancelled`). When this handle's `cancel()` actually dispatched a + * server-side cancel, we normalise that into `Cancelled` here so JS callers + * can rely on a single cancelled-status code regardless of execution path. + * + * Three outcomes can race the blocking drive: (1) a natural terminal state + * → `Ok` or the genuine error; (2) an explicit `cancel()` that dispatched a + * server cancel → this `result()` rejects with a `Cancelled`-coded error + * (the normalisation above); (3) the future being **dropped** mid-flight + * (`Promise.race`/timeout loser) → the kernel's `MidExecuteCancelState` + * drop-guard fires a fire-and-forget `cancel_statement`, but there is no + * `result()` left to observe a code. Only (2) yields a `Cancelled` error. + */ + result(): Promise + /** + * Server-side cancel of the in-flight statement. + * + * Lock-free: fires the detached `StatementCanceller` captured at + * construction rather than taking the mutex `result()` holds, so it + * interrupts a still-running blocking `result()` instead of queueing + * behind it. No-op (returns `Ok`) if `result()` already finished + * successfully, or if no statement id has been observed yet (query still + * in its initial submit round-trip), and idempotent against a server + * already in a terminal state. + */ + cancel(): Promise } + /** - * JS-visible options for opening a Databricks SQL session. + * Opaque connection handle wrapping a kernel `Session`. * - * Authentication is selected by `authMode` (default [`AuthMode::Pat`]): - * - `Pat` — `token` required. - * - `OAuthM2m` — `oauthClientId` + `oauthClientSecret` required. - * - `OAuthU2m` — `oauthClientId` / `oauthRedirectPort` optional - * (defaults to the `databricks-sql-connector` client on port 8030). - * - `AzureSpM2m` — `azureClientId` + `azureClientSecret` required - * (+ optional `azureTenantId` / `azureWorkspaceResourceId`). + * `inner` is `Arc>>` so: + * - the Drop impl can clone the `Arc` and `.take()` the session on a + * background tokio task without holding `&mut self` (which Drop is + * forbidden from doing across an `await`), + * - `close()` can `.take()` the session to consume it for the kernel's + * move-by-value `Session::close(self)` signature. * - * Catalog / schema / sessionConf are applied once at session creation - * and remain in effect for every statement run on the resulting - * `Connection`. The SEA wire protocol carries them on - * `CreateSession`, not on `ExecuteStatement` — so there is no - * per-statement override path on this binding. + * **Concurrency shape** — both `executeStatement` and + * `submitStatement` build the kernel `Statement` under `inner.lock()` + * and then RELEASE the guard before the wire call + * (`stmt.execute().await` / `stmt.submit().await`). `Session::statement()` + * is `&self`-callable and only clones the session's internal `Arc`, so + * the built statement is independent of the guard. Concurrent + * `Promise.all([executeStatement(q1), submitStatement(q2)])` therefore + * serialise only for the microsecond statement-build, not the network + * round-trip, and `close()` never blocks behind an in-flight execute or + * submit. See + * `sea-workflow/jira-candidates/2026-05-24-napi-cancel-during-fetch.md`. */ -export interface ConnectionOptions { +export declare class Connection { /** - * Workspace host, e.g. `adb-…azuredatabricks.net`. The kernel - * normalises this — bare hostnames get `https://` prepended. + * Server-issued session id. Cached at construction; readable + * even after `close()` so JS-side log lines can correlate + * against kernel / server logs which key on the same id. */ - hostName: string + get sessionId(): string /** - * JDBC-style HTTP path, e.g. `/sql/1.0/warehouses/abc123`. The - * kernel parses out the warehouse id. + * Execute a SQL statement and return a Statement handle that + * streams batches via `fetchNextBatch()`. + * + * Catalog / schema / sessionConf are session-level + * (`openSession`). Per-statement options on `ExecuteOptions`: + * - `statementConf` — per-statement Spark conf overlay + * - `queryTags` — serialised to a comma-separated `key:value` + * string and placed in `statement_conf["query_tags"]`, + * matching NodeJS Thrift's `serializeQueryTags` wire shape + * + * `options` is omitted/`None` for the no-options path; passing + * `{ statementConf: {} }` (an empty map) is treated the same as + * omission to keep the wire shape stable for the common case. */ - httpPath: string + executeStatement(sql: string, options?: ExecuteOptions | undefined | null): Promise /** - * Authentication mode. Omitted ⇒ [`AuthMode::Pat`] (back-compat: - * existing PAT callers pass only `token`). + * directResults execute — the Thrift/JDBC model. Sends ExecuteStatement + * with no `wait_timeout` field (server applies its ~10s default inline wait + * and auto-closes on success) and returns WITHOUT polling past it: + * + * - a **`Statement`** (left arm) when the query finished within the inline + * wait — terminal, result ready inline, `close()` is a clean release; + * - an **`AsyncStatement`** (right arm) when it did not — a poll/cancel + * handle the caller drives (`status()` / `awaitResult()` / `cancel()`). + * + * JS distinguishes the arms by feature-detecting `awaitResult` (present + * only on `AsyncStatement`). This is the path that gives mid-run cancel for + * long queries WITHOUT the eager-handle / close-drives workaround: the + * returned handle always corresponds to a server-owned statement. + * + * **Load-bearing contract:** the kernel's `DirectStatement::{Completed, + * Running}` discriminant cannot ride on these opaque `#[napi]` classes, so + * consumers MUST feature-detect via `awaitResult` (the only member unique to + * `AsyncStatement`). `Statement` (the Completed arm) MUST NOT gain an + * `awaitResult` member, or every consumer silently misroutes. The pyo3 + * binding makes the same `await_result`-probe assumption. */ - authMode?: AuthMode + executeStatementDirect(sql: string, options?: ExecuteOptions | undefined | null): Promise /** - * Personal access token. Required (and non-empty) for - * [`AuthMode::Pat`]; ignored otherwise. + * Execute a SQL statement on the blocking (sync) path, but return a + * `CancellableExecution` handle so a concurrent JS task can cancel + * the query *while it is still running server-side*. + * + * `executeStatement` builds the kernel `Statement`, awaits the + * blocking `execute()`, and only then hands JS a `Statement` — so a + * query that runs for several seconds is uncancellable from JS on + * that path (there is no handle until the blocking call resolves). + * This method instead builds the statement, captures a detached + * `StatementCanceller` **before** dispatching `execute()`, and hands + * JS a `CancellableExecution` immediately. The caller drives the + * blocking execution via `result()` (resolves to the same + * `Statement` `executeStatement` returns) and can fire `cancel()` + * concurrently to interrupt a still-running query mid-COMPUTE. + * + * Option semantics are identical to `executeStatement`. + * Mirrors the pyo3 `Statement.canceller()` / `Statement.execute()` + * split (PR #121): obtain the canceller before the blocking drive. */ - token?: string + executeStatementCancellable(sql: string, options?: ExecuteOptions | undefined | null): Promise /** - * OAuth client id. Required for [`AuthMode::OAuthM2m`]; optional for - * [`AuthMode::OAuthU2m`] (defaults to `databricks-sql-connector`). + * Submit a SQL statement and return immediately with an + * `AsyncStatement` handle, without blocking until the query + * finishes. The kernel's `Statement::submit()` sends + * `wait_timeout=0s`, so the server responds as soon as it has a + * `statement_id` (state `Pending`/`Running`); JS drives polling + * via `AsyncStatement.status()` and materialises results with + * `AsyncStatement.awaitResult()`. + * + * This is the async-execution path the Thrift backend always + * 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`. + * 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 + * differs from `executeStatement`. */ - oauthClientId?: string - /** OAuth client secret. Required for [`AuthMode::OAuthM2m`]. */ - oauthClientSecret?: string + submitStatement(sql: string, options?: ExecuteOptions | undefined | null): Promise /** - * Localhost callback port for the [`AuthMode::OAuthU2m`] browser - * flow. Omitted ⇒ kernel default (8030). + * Explicit close. Awaits the server-side `DeleteSession` so the + * JS caller can observe failures (auth revoked mid-session, + * warehouse stopped, network error). Idempotent — a second call + * on an already-closed connection returns `Ok`. + * + * **Errors are terminal from the JS side.** The kernel session + * handle is consumed (`take()`) BEFORE the wire `DeleteSession` + * runs, because `Session::close` takes `self` by value. On `Err`, + * the napi `inner` is already `None`, so a JS-side retry sees a + * closed connection and returns `Ok(())` without re-attempting + * the wire call. The kernel's own `Drop` fire-and-forget retry + * runs once in the background — the JS caller can log the error + * but cannot drive a retry. If you need retry-on-failure + * semantics for `DeleteSession`, layer them above this method. */ - oauthRedirectPort?: number + close(): Promise /** - * OAuth scopes override (M2M / U2M). Omitted ⇒ kernel defaults - * (`["all-apis"]` for M2M; `["sql", "offline_access"]` for U2M). + * All catalogs visible to the session. + * + * JDBC `getCatalogs` shape: `TABLE_CAT: Utf8`. */ - oauthScopes?: Array + listCatalogs(): Promise /** - * OAuth token endpoint override. When omitted the kernel discovers the - * endpoint via the workspace's OIDC configuration. Set it to point the - * client-credentials / JWT client-assertion grant at the workspace's - * configured IdP token endpoint (e.g. Entra ID for Azure Databricks), - * which is required when that IdP — not Databricks-native OIDC — is the - * authority for [`AuthMode::OAuthM2m`] / [`AuthMode::OAuthM2mJwt`]. + * Schemas filtered by catalog (exact) and schema name pattern. An empty + * catalog matches nothing; non-empty catalogs remain exact identifiers. + * + * JDBC `getSchemas` shape: `TABLE_SCHEM, TABLE_CATALOG`. */ - tokenUrl?: string + listSchemas(catalog?: string | undefined | null, schemaPattern?: string | undefined | null): Promise /** - * U2M on-disk token-cache control (kernel path). Omitted ⇒ the kernel - * default (cache enabled, encrypted under a machine-local key, survives - * restarts). `false` disables on-disk persistence (re-login each fresh - * process); `true` keeps it enabled. Applies to [`AuthMode::OAuthU2m`]. + * Tables filtered by catalog (**pattern**), schema (pattern), table + * (pattern). + * + * The catalog is an ODBC/JDBC LIKE pattern (`%` / `_`), matching + * Thrift `getTables`: a wildcard catalog matches multiple catalogs; + * a literal name (or an escaped `\_` / `\%`) takes the fast exact + * path. `undefined`/omitted catalog means "all catalogs", while an + * **empty string** means "match nothing" (zero rows) — pass + * `undefined`, not `""`, for all catalogs. The catalog pattern is + * validated (whitespace-only / NUL / >255 bytes are rejected with an + * error). + * + * JDBC `getTables` shape: 10 columns. `tableTypes`, when provided, + * filters rows by `TABLE_TYPE` kernel-side. + * + * `tableTypes` is an advisory filter. Databricks `SHOW TABLES` does + * NOT honour the table-type filter server-side; the kernel applies + * it client-side after the result returns. Callers expecting + * server-side rejection of off-type tables should not rely on this. */ - tokenCacheEnabled?: boolean + listTables(catalog?: string | undefined | null, schemaPattern?: string | undefined | null, tablePattern?: string | undefined | null, tableTypes?: Array | undefined | null): Promise /** - * Optional passphrase for the U2M on-disk token cache (AES-256 key). - * Omitted/blank ⇒ a machine-local derived key. Supplying one is stronger. - * A passphrase with no explicit `tokenCacheEnabled` implies enabled. - * Applies to [`AuthMode::OAuthU2m`]. + * Columns of tables matching the filter. An empty catalog matches + * nothing; non-empty catalogs remain exact identifiers. + * + * JDBC `getColumns` shape: 23 columns. */ - tokenCachePassphrase?: string + listColumns(catalog?: string | undefined | null, schemaPattern?: string | undefined | null, tablePattern?: string | undefined | null, columnPattern?: string | undefined | null): Promise /** - * Path to the PEM private-key file. Required for - * [`AuthMode::OAuthM2mJwt`]. + * Functions visible to the session. An empty `catalog` is forwarded to + * SEA for native `GetFunctions`; `schemaPattern` and `functionPattern` are SQL LIKE. */ - jwtKeyFile?: string - /** JWT key id (`kid`). Required for [`AuthMode::OAuthM2mJwt`]. */ - jwtKid?: string + listFunctions(catalog?: string | undefined | null, schemaPattern?: string | undefined | null, functionPattern?: string | undefined | null): Promise /** - * Passphrase for an encrypted PKCS#8 key. Optional for - * [`AuthMode::OAuthM2mJwt`] (omit for an unencrypted key). + * Procedures visible to the session. `catalog` is exact; + * `schemaPattern` and `procedurePattern` are SQL LIKE. */ - jwtPassphrase?: string + listProcedures(catalog?: string | undefined | null, schemaPattern?: string | undefined | null, procedurePattern?: string | undefined | null): Promise /** - * JWT signing algorithm (`RS256`/`384`/`512`, `PS256`/`384`/`512`, - * `ES256`, `ES384`). Optional for [`AuthMode::OAuthM2mJwt`] - * (omitted ⇒ kernel default `RS256`). + * All table types (`TABLE`, `VIEW`, `SYSTEM TABLE`, …). + * No wire call — static in-memory result. */ - jwtAlgorithm?: string + listTableTypes(): Promise /** - * SP-wide Workload Identity Federation client id used during mandatory - * token exchange. Omitted selects BYOT / account-wide WIF. + * SQL data types supported by the workspace. + * No wire call — static in-memory result. */ - identityFederationClientId?: string + listTypeInfo(): Promise /** - * Azure Entra app-registration client id. Required for - * [`AuthMode::AzureSpM2m`]; ignored otherwise. + * Primary keys for the given table. All three identifiers are + * exact — ODBC `SQLPrimaryKeys` does not support patterns. */ - azureClientId?: string + getPrimaryKeys(catalog: string | undefined | null, schema: string | undefined | null, table: string): Promise /** - * Azure Entra app-registration client secret. Required for - * [`AuthMode::AzureSpM2m`]. + * Foreign-key relationships. The parent side is optional. When the + * foreign table is omitted, returns an empty result without issuing a + * server statement. When it is provided, its catalog and schema are + * required. All identifiers are exact — no LIKE patterns. */ - azureClientSecret?: string + getCrossReference(parentCatalog?: string | undefined | null, parentSchema?: string | undefined | null, parentTable?: string | undefined | null, foreignCatalog?: string | undefined | null, foreignSchema?: string | undefined | null, foreignTable?: string | undefined | null): Promise +} + +/** + * Opaque executed-statement handle. + * + * **Current concurrency shape** — every method takes `inner.lock()` + * and holds the guard across the kernel `.await`. tokio `Mutex` is + * FIFO, so cancel/close queue behind any in-flight `fetchNextBatch` + * until it returns naturally. This is a known limitation that exists + * because the napi shape has not yet been split into an + * `Arc` (for cancel/close, which the + * kernel exposes as `&self`-callable) plus a `Mutex>` only + * for the borrowed-mut fetch path. The lock-shape refactor needs a + * small kernel-side accessor and lands in a follow-up PR — see + * `sea-workflow/jira-candidates/2026-05-24-napi-cancel-during-fetch.md`. + * + * `schema` and `statement_id` are cached at construction so they + * survive `close()` — JS callers building error reports against a + * disposed statement can still read them. + */ +export declare class Statement { /** - * Azure Entra tenant id. Optional for [`AuthMode::AzureSpM2m`]; - * omitted ⇒ the kernel auto-discovers it from the workspace's - * `/aad/auth` redirect (matching the Thrift connector). + * Server-issued statement id. Cached at construction; readable + * even after `close()` so JS-side log lines can correlate against + * kernel / server logs which key on the same id. */ - azureTenantId?: string + get statementId(): string /** - * Azure workspace ARM resource id. Optional for [`AuthMode::AzureSpM2m`]; - * when set the kernel also sends the SP management token - * (`X-Databricks-Azure-SP-Management-Token`) + the - * `X-Databricks-Azure-Workspace-Resource-Id` header, so a service - * principal with an Azure RBAC role but no workspace membership can - * authenticate. Omitted ⇒ the data token authenticates alone. + * Number of rows modified by the statement (UPDATE / INSERT / + * DELETE / MERGE). `null` for SELECT and on warehouses that don't + * surface the counter. Mirrors Thrift's + * `TGetOperationStatusResp.numModifiedRows`. */ - azureWorkspaceResourceId?: string + numModifiedRows(): Promise /** - * Default catalog for statements executed on this session. - * Routed through the kernel's `DefaultOpts` and onto the SEA - * `CreateSession.catalog` wire field. + * Server-supplied user-facing message. Mirrors Thrift's + * `TGetOperationStatusResp.displayMessage`. **PII / sensitive- + * data note:** may contain SQL fragments or parameter values — + * redact before centralised logging. + * + * Populated on `Succeeded` / `Closed` paths (incl. an empty `Closed`). + * On terminal-error states (`Failed` / `Cancelled`) the kernel returns + * an Error instead of a `Statement`, and the same field rides on the JS + * Error envelope under the same `displayMessage` key. */ - catalog?: string + displayMessage(): Promise /** - * Default schema for statements executed on this session. - * Routed through the kernel's `DefaultOpts` and onto the SEA - * `CreateSession.schema` wire field. + * Server-supplied diagnostic detail — multi-line operator / + * stack context. Mirrors Thrift's + * `TGetOperationStatusResp.diagnosticInfo`. For support surfaces, + * not user-facing. Same reachability + PII caveats as + * `displayMessage`. */ - schema?: string + diagnosticInfo(): Promise /** - * Server-bound session conf (Spark conf, `ANSI_MODE`, `TIMEZONE`, - * query-tag presets, …). Forwarded verbatim to SEA - * `session_confs`. Unknown keys are rejected server-side. + * Server-supplied JSON blob with extended error details. Mirrors + * Thrift's `TGetOperationStatusResp.errorDetailsJson`. + * Pass-through string — JS callers parse with `JSON.parse` if + * they need structured access. + * + * **Server-side gating:** populated only when the workspace has + * `spark.databricks.sql.errorDetailsJson.enabled = true` on the + * underlying SQL cluster. The flag is internal-only / default- + * false in the Databricks runtime, so for most JS callers this + * will return `null`. Admin-enabled workspaces return content + * shaped like `{"errorClass": "...", "messageTemplate": "..."}`. + * + * **Unbounded:** when populated, server can return a multi-MB + * blob; size before logging. */ - sessionConf?: Record + errorDetailsJson(): Promise /** - * Select whether `GEOMETRY` / `GEOGRAPHY` results use their native Arrow - * representation. `true` (the default) requests Arrow - * `struct` values; `false` requests WKT / EWKT - * in Arrow UTF-8 values. The kernel normalizes both standard-warehouse - * text and Reyden native Arrow results locally and never sends this choice - * to SEA. + * Pull the next batch of results. Returns `null` when the stream + * is exhausted. The returned `ArrowBatch.ipcBytes` is a complete + * Arrow IPC stream (schema header + 1 record-batch message) + * suitable for handing to `apache-arrow`'s `RecordBatchReader`. + * + * On `Err`, the stream is in an unspecified state — call + * `close()` and discard the `Statement`. Subsequent + * `fetchNextBatch()` calls after an error are not guaranteed to + * succeed or fail consistently. */ - enableGeoSpatialSupport?: boolean + fetchNextBatch(): Promise /** - * Driver name reported in telemetry system configuration. Omitted ⇒ - * kernel default. + * Result schema as an Arrow IPC payload (schema header only, no + * record-batch message). Available before any batches have been + * fetched, and remains available after `close()` — the kernel + * materialises the schema eagerly so JS callers can build error + * reports against a disposed statement. + * + * Sync because the body has no `.await` — `encode_ipc_stream` is + * pure CPU work over an `Arc` already cached on the + * wrapper. Mirrors `pyo3/src/statement.rs::arrow_schema` (sync). + * napi-rs converts a panic in a sync `#[napi]` entry point into a + * thrown JS error via its own macro-expanded boundary, so the + * `util::guarded` `catch_unwind` wrapper that the `async fn` + * entry points use is not required for this method. */ - driverName?: string + schema(): ArrowSchema /** - * Driver version reported in telemetry system configuration. Omitted ⇒ - * kernel default. + * Server-side cancel. + * + * For executed statements: short-circuits to `Ok(())` if + * `fetchNextBatch` has already returned `null` (stream + * naturally exhausted) — matches the JDBC `Statement.cancel()` + * no-op-after-completion contract, so JS callers can fire cancel + * defensively without distinguishing "real cancel" from "raced + * with natural completion." + * + * For metadata streams: no-op (the kernel has no in-flight + * cancellation surface for metadata calls today). + * + * Returns `KernelError(InvalidStatementHandle)` if the statement + * has been explicitly `close()`d. */ - driverVersion?: string + cancel(): Promise /** - * Runtime name reported in telemetry system configuration. Omitted ⇒ - * kernel default. + * Explicit close. + * + * For executed statements: awaits the server-side `CloseStatement` + * so the JS caller can observe failures (auth revoked mid-session, + * network error, server-side error). Idempotent — a second call + * on an already-closed statement returns `Ok`. + * + * **Errors are terminal from the JS side.** The kernel executed + * handle is taken out of `inner` BEFORE the wire `CloseStatement` + * runs (so `Drop` knows there's nothing left to clean up). On + * `Err`, the napi `inner` is already `None`, so a JS-side retry + * sees a closed statement and returns `Ok(())` without re- + * attempting the wire call. The kernel-level `ExecutedStatement` + * has been consumed at that point and the value is dropped on + * the way out of the closure — the kernel's `ExecutedStatement:: + * Drop` then fires-and-forgets a single retry on the captured + * runtime. The JS caller can log the error but cannot drive a + * further retry. If you need retry-on-failure semantics for + * `CloseStatement`, layer them above this method. + * + * For metadata streams: drops the stream (no server round-trip + * needed — metadata results have no in-flight server-side + * resource to release). */ - runtimeName?: string + close(): Promise +} + +/** + * A single Arrow IPC stream payload encoding one record batch (plus + * the schema header so the JS-side reader is stateless). + */ +export interface ArrowBatch { /** - * Runtime version reported in telemetry system configuration. Omitted ⇒ - * kernel default. + * Arrow IPC stream payload (schema header + 1 record-batch + * message). Decode with `apache-arrow`'s `RecordBatchReader`. */ - runtimeVersion?: string + ipcBytes: Buffer +} + +/** + * An Arrow IPC stream payload encoding just the result schema (no + * record-batch messages). Returned by `Statement.schema()`. + */ +export interface ArrowSchema { /** - * Runtime vendor reported in telemetry system configuration. Omitted ⇒ - * kernel default. + * Arrow IPC stream payload (schema header only, no record-batch + * messages). Decode with `apache-arrow`'s `RecordBatchReader` — + * the reader will expose the schema and immediately end. */ - runtimeVendor?: string + ipcBytes: Buffer +} + +/** + * Authentication mode selector crossing the napi boundary. The string + * literals are what napi-rs emits from this `#[napi(string_enum)]` — the + * NodeJS SEA adapter (`KernelAuth`) matches them verbatim (`'Pat'`, + * `'OAuthM2m'`, `'OAuthU2m'`, `'AzureSpM2m'`). + * + * Mirrors the kernel [`AuthConfig`] variants this binding supports. + * `OAuthFederation` / `External` are intentionally not exposed yet — the + * kernel marks federation as not-yet-implemented and `External` is a + * Rust-trait escape hatch with no JS-callback bridge. + */ +export declare const enum AuthMode { + /** Personal access token (`token`). */ + Pat = 'Pat', + /** OAuth 2.0 machine-to-machine — `oauthClientId` + `oauthClientSecret`. */ + OAuthM2m = 'OAuthM2m', /** - * Operating system name reported in telemetry system configuration. - * Omitted ⇒ kernel default. + * OAuth 2.0 machine-to-machine with a JWT private-key client + * assertion — `oauthClientId` + `jwtKeyFile` + `jwtKid`. */ - osName?: string + OAuthM2mJwt = 'OAuthM2mJwt', /** - * Operating system version reported in telemetry system configuration. - * Omitted ⇒ kernel default. + * OAuth 2.0 user-to-machine (browser flow) — optional `oauthClientId` + * + `oauthRedirectPort`. + */ + OAuthU2m = 'OAuthU2m', + /** + * Azure Entra service-principal M2M — `azureClientId` + + * `azureClientSecret` (+ optional `azureTenantId` / + * `azureWorkspaceResourceId`). The kernel builds the Entra token + * endpoint + `.default` scope, auto-discovers the tenant from the + * workspace when `azureTenantId` is omitted, and — when + * `azureWorkspaceResourceId` is set — additionally sends the SP + * management token for an RBAC-only service principal. + */ + AzureSpM2m = 'AzureSpM2m' +} + +/** + * JS-visible options for opening a Databricks SQL session. + * + * Authentication is selected by `authMode` (default [`AuthMode::Pat`]): + * - `Pat` — `token` required. + * - `OAuthM2m` — `oauthClientId` + `oauthClientSecret` required. + * - `OAuthU2m` — `oauthClientId` / `oauthRedirectPort` optional + * (defaults to the `databricks-sql-connector` client on port 8030). + * - `AzureSpM2m` — `azureClientId` + `azureClientSecret` required + * (+ optional `azureTenantId` / `azureWorkspaceResourceId`). + * + * Catalog / schema / sessionConf are applied once at session creation + * and remain in effect for every statement run on the resulting + * `Connection`. The SEA wire protocol carries them on + * `CreateSession`, not on `ExecuteStatement` — so there is no + * per-statement override path on this binding. + */ +export interface ConnectionOptions { + /** + * Workspace host, e.g. `adb-…azuredatabricks.net`. The kernel + * normalises this — bare hostnames get `https://` prepended. + */ + hostName: string + /** + * JDBC-style HTTP path, e.g. `/sql/1.0/warehouses/abc123`. The + * kernel parses out the warehouse id. + */ + httpPath: string + /** + * Authentication mode. Omitted ⇒ [`AuthMode::Pat`] (back-compat: + * existing PAT callers pass only `token`). + */ + authMode?: AuthMode + /** + * Personal access token. Required (and non-empty) for + * [`AuthMode::Pat`]; ignored otherwise. + */ + token?: string + /** + * OAuth client id. Required for [`AuthMode::OAuthM2m`]; optional for + * [`AuthMode::OAuthU2m`] (defaults to `databricks-sql-connector`). + */ + oauthClientId?: string + /** OAuth client secret. Required for [`AuthMode::OAuthM2m`]. */ + oauthClientSecret?: string + /** + * Localhost callback port for the [`AuthMode::OAuthU2m`] browser + * flow. Omitted ⇒ kernel default (8030). + */ + oauthRedirectPort?: number + /** + * OAuth scopes override (M2M / U2M). Omitted ⇒ kernel defaults + * (`["all-apis"]` for M2M; `["sql", "offline_access"]` for U2M). + */ + oauthScopes?: Array + /** + * OAuth token endpoint override. When omitted the kernel discovers the + * endpoint via the workspace's OIDC configuration. Set it to point the + * client-credentials / JWT client-assertion grant at the workspace's + * configured IdP token endpoint (e.g. Entra ID for Azure Databricks), + * which is required when that IdP — not Databricks-native OIDC — is the + * authority for [`AuthMode::OAuthM2m`] / [`AuthMode::OAuthM2mJwt`]. + */ + tokenUrl?: string + /** + * U2M on-disk token-cache control (kernel path). Omitted ⇒ the kernel + * default (cache enabled, encrypted under a machine-local key, survives + * restarts). `false` disables on-disk persistence (re-login each fresh + * process); `true` keeps it enabled. Applies to [`AuthMode::OAuthU2m`]. + */ + tokenCacheEnabled?: boolean + /** + * Optional passphrase for the U2M on-disk token cache (AES-256 key). + * Omitted/blank ⇒ a machine-local derived key. Supplying one is stronger. + * A passphrase with no explicit `tokenCacheEnabled` implies enabled. + * Applies to [`AuthMode::OAuthU2m`]. + */ + tokenCachePassphrase?: string + /** + * Path to the PEM private-key file. Required for + * [`AuthMode::OAuthM2mJwt`]. + */ + jwtKeyFile?: string + /** JWT key id (`kid`). Required for [`AuthMode::OAuthM2mJwt`]. */ + jwtKid?: string + /** + * Passphrase for an encrypted PKCS#8 key. Optional for + * [`AuthMode::OAuthM2mJwt`] (omit for an unencrypted key). + */ + jwtPassphrase?: string + /** + * JWT signing algorithm (`RS256`/`384`/`512`, `PS256`/`384`/`512`, + * `ES256`, `ES384`). Optional for [`AuthMode::OAuthM2mJwt`] + * (omitted ⇒ kernel default `RS256`). + */ + jwtAlgorithm?: string + /** + * SP-wide Workload Identity Federation client id used during mandatory + * token exchange. Omitted selects BYOT / account-wide WIF. + */ + identityFederationClientId?: string + /** + * Azure Entra app-registration client id. Required for + * [`AuthMode::AzureSpM2m`]; ignored otherwise. + */ + azureClientId?: string + /** + * Azure Entra app-registration client secret. Required for + * [`AuthMode::AzureSpM2m`]. + */ + azureClientSecret?: string + /** + * Azure Entra tenant id. Optional for [`AuthMode::AzureSpM2m`]; + * omitted ⇒ the kernel auto-discovers it from the workspace's + * `/aad/auth` redirect (matching the Thrift connector). + */ + azureTenantId?: string + /** + * Azure workspace ARM resource id. Optional for [`AuthMode::AzureSpM2m`]; + * when set the kernel also sends the SP management token + * (`X-Databricks-Azure-SP-Management-Token`) + the + * `X-Databricks-Azure-Workspace-Resource-Id` header, so a service + * principal with an Azure RBAC role but no workspace membership can + * authenticate. Omitted ⇒ the data token authenticates alone. + */ + azureWorkspaceResourceId?: string + /** + * Default catalog for statements executed on this session. + * Routed through the kernel's `DefaultOpts` and onto the SEA + * `CreateSession.catalog` wire field. + */ + catalog?: string + /** + * Default schema for statements executed on this session. + * Routed through the kernel's `DefaultOpts` and onto the SEA + * `CreateSession.schema` wire field. + */ + schema?: 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. + */ + sessionConf?: Record + /** + * Select whether `GEOMETRY` / `GEOGRAPHY` results use their native Arrow + * representation. `true` (the default) requests Arrow + * `struct` values; `false` requests WKT / EWKT + * in Arrow UTF-8 values. The kernel normalizes both standard-warehouse + * text and native Arrow results locally and never sends this choice + * to SEA. + */ + enableGeoSpatialSupport?: boolean + /** + * Driver name reported in telemetry system configuration. Omitted ⇒ + * kernel default. + */ + driverName?: string + /** + * Driver version reported in telemetry system configuration. Omitted ⇒ + * kernel default. + */ + driverVersion?: string + /** + * Runtime name reported in telemetry system configuration. Omitted ⇒ + * kernel default. + */ + runtimeName?: string + /** + * Runtime version reported in telemetry system configuration. Omitted ⇒ + * kernel default. + */ + runtimeVersion?: string + /** + * Runtime vendor reported in telemetry system configuration. Omitted ⇒ + * kernel default. + */ + runtimeVendor?: string + /** + * Operating system name reported in telemetry system configuration. + * Omitted ⇒ kernel default. + */ + osName?: string + /** + * Operating system version reported in telemetry system configuration. + * Omitted ⇒ kernel default. */ osVersion?: string /** @@ -516,9 +958,7 @@ export interface ConnectionOptions { * `User-Agent` entry here. */ customHeaders?: Array - /** - * Whether SEA API responses may use HTTP compression. Defaults to false. - */ + /** Whether SEA API responses may use HTTP compression. Defaults to false. */ seaResponseCompressionEnabled?: boolean /** * Retry/backoff tuning — all optional. An unset field keeps the kernel's @@ -549,10 +989,13 @@ export interface ConnectionOptions { */ retryOverallTimeoutSecs?: number /** - * Enable kernel telemetry export. Omitted / `false` keeps telemetry - * disabled. When enabled, the kernel records operation telemetry below the - * binding layer and exports through the Databricks SQL driver telemetry - * endpoint. + * Enable kernel telemetry export. Tri-state: an explicit `true` or `false` + * takes precedence; when omitted, export defers to the + * `enableTelemetryForKernel` workspace feature flag, falling back to + * disabled when the flag is absent. Only an explicit `false` guarantees + * telemetry stays disabled. When enabled, the kernel records operation + * telemetry below the binding layer and exports through the Databricks SQL + * driver telemetry endpoint. */ telemetryEnabled?: boolean /** @@ -578,9 +1021,9 @@ export interface ConnectionOptions { /** Enable telemetry circuit-breaker protection. Omitted ⇒ kernel default. */ telemetryCircuitBreakerEnabled?: boolean /** - * Consecutive telemetry export failures before opening the circuit. Omitted - * ⇒ kernel default. Must be greater than zero when the circuit breaker is - * enabled. + * Consecutive telemetry export failures before opening the circuit. + * Omitted ⇒ kernel default. Must be greater than zero when the circuit + * breaker is enabled. */ telemetryCircuitBreakerThreshold?: number /** @@ -617,46 +1060,141 @@ export interface ConnectionOptions { */ socketTimeoutMs?: number } + /** - * Open a Databricks SQL session and return an opaque `Connection` - * wrapping the kernel `Session`. Authentication is selected by - * `options.auth_mode` (PAT / OAuth M2M / OAuth U2M) — see - * [`build_auth_config`]. - * - * The JS-visible name is `openSession` (napi-rs converts snake_case - * to camelCase for free functions). - */ -export declare function openSession(options: ConnectionOptions): Promise -/** - * One kernel log event, as handed to JS. `level` is a lower-case string - * (`error`/`warn`/`info`/`debug`/`trace`) the Node side maps onto its - * `LogLevel`; `target` is the originating `tracing` target (e.g. - * `databricks::sql::kernel`); `message` is the rendered event plus any - * structured `key=value` fields. - */ -export interface LogRecord { - level: string - target: string - message: string -} -/** - * Install (idempotently) the kernel→JS log bridge and set its level. + * Per-statement options for `Connection.executeStatement`. * - * `callback` is invoked with **an array of [`LogRecord`]s** (`(err, records)`) - * for each forwarded batch. `level` is one of - * `off`/`error`/`warn`/`info`/`debug`/`trace` (case-insensitive); unknown - * values fall back to `warn`. + * Mirrors the kernel `StatementSpec` knobs that are safe to thread + * through napi without a kernel-side change. Today this covers: + * - `statementConf` — per-statement Spark conf overlay + * (`StatementSpec.statement_conf` → SEA `parameters` / + * Thrift `confOverlay`) + * - `queryTags` — convenience wrapper over `statementConf` with + * key `query_tags`; serialised to the same comma-separated + * `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. * - * Safe to call more than once: the process-global subscriber is installed on - * the first call only, while every call refreshes the sink + level (last - * writer wins — see module docs). - */ -export declare function initKernelLogging(callback: (err: Error | null, arg: Array) => any, level: string): void -/** - * Snapshot of the bridge's runtime state for observability. + * `rowLimit` (SEA `row_limit`) is exposed here and threaded onto the kernel + * `StatementSpec`. `positionalParams` (`?`) and `namedParams` (`:name`) + * carry bound query parameters, decoded via `params::parse_typed_value`. + * `rawParams` forwards pre-marshalled SEA parameters unchanged. + * (There is no `queryTimeoutSecs`: it abused the SEA `wait_timeout` inline-hold + * window and was removed — a real per-statement timeout is `STATEMENT_TIMEOUT`.) * - * `installed` is `true` only when the process-global subscriber was - * successfully installed by *this* bridge (and the drain thread started); + * **Tag-order caveat (M4 parity note).** The napi `queryTags` field + * is a Rust `HashMap` whose iteration order is + * non-deterministic, so the serialised `query_tags` value may have + * a different key order than Thrift's `serializeQueryTags` (which + * iterates `Object.keys(...)` in insertion order) for the same + * input. The SEA server is order-insensitive on conf values, so + * the two are functionally equivalent. If a caller needs + * byte-identical Thrift parity, the JS adapter pre-serialises via + * `serializeQueryTags` and writes the result into + * `statementConf["query_tags"]` directly — see + * `KernelSessionBackend.executeStatement` in the NodeJS driver. This + * path is the one the production code uses. + */ +export interface ExecuteOptions { + /** + * Per-statement Spark conf overlay. Merged on top of the + * session-level `sessionConf` at execute time; this map wins + * on key collisions. Unknown keys are rejected by the server. + */ + statementConf?: Record + /** + * Query tags as key→value pairs. Serialised to a comma- + * separated `key:value` string (backslash-escaping `\`, `:`, + * `,`) and placed into `statementConf["query_tags"]`, matching + * NodeJS Thrift's `serializeQueryTags` wire shape. Passing + * both `queryTags` AND a `query_tags` key in `statementConf` + * raises `InvalidArgument` — the caller's intent is ambiguous + * so we refuse to silently pick one over the other. + * + * A **`null`** value emits a **bare key** (no colon) — e.g. + * `{ production: null }` → `"production"` — matching the + * connectors' `key`-only tag form. + * + * See the struct-level "Tag-order caveat" for the + * HashMap-iteration-order vs `Object.keys`-iteration-order + * divergence and the byte-identical-Thrift-parity workaround. + */ + queryTags?: Record + /** + * Server-side cap on the number of rows this statement returns + * (SEA `row_limit`), independent of any SQL `LIMIT`. Maps to + * `StatementSpec.row_limit`. Omitted ⇒ no driver-imposed cap. + */ + rowLimit?: number + /** Omit to handle instructions in the caller; an empty list denies local file access. */ + stagingAllowedLocalPaths?: Array + /** + * 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 + * string-encoded literal or `null` for SQL NULL. Mirrors + * `StatementSpec::positional_params`; decoded via [`parse_typed_value`]. + */ + positionalParams?: Array + /** + * Named parameters (`:name` placeholders). Each carries its `name` + * alongside the `{ sqlType, value? }` pair. Mapped to a kernel + * `TypedValue` via the same [`parse_typed_value`] codec and bound with + * `StatementSpec::param_named`. Named is the SEA-spec-required public + * param form (`StatementParameter.name` is `openapi_required`); + * positional is the documented-undocumented variant. The two are + * mutually exclusive at the SQL level (`?` vs `:name`). + */ + namedParams?: Array + /** + * Pre-marshalled parameters passed through `StatementSpec::param_raw`. + * Omit `name` for positional values. Raw parameters cannot be mixed with + * typed parameters or combine named and positional markers. + */ + rawParams?: Array +} + +/** + * A single extra HTTP header as an explicit `{ name, value }` pair. + * + * An ordered list of these (`ConnectionOptions.custom_headers`) mirrors + * the kernel core's `Vec<(String, String)>` and the pyo3 binding's + * `http_headers`: order is preserved and duplicate `name`s are allowed. + * A struct (rather than a raw `[name, value]` tuple) because napi-rs + * does not marshal Rust tuples through `#[napi(object)]` fields; the + * struct is the idiomatic, self-documenting equivalent and maps to a JS + * `{ name: string, value: string }`. + */ +export interface HeaderEntry { + name: string + value: string +} + +/** + * Install (idempotently) the kernel→JS log bridge and set its level. + * + * `callback` is invoked with **an array of [`LogRecord`]s** (`(err, records)`) + * for each forwarded batch. `level` is one of + * `off`/`error`/`warn`/`info`/`debug`/`trace` (case-insensitive); unknown + * values fall back to `warn`. + * + * Safe to call more than once: the process-global subscriber is installed on + * the first call only, while every call refreshes the sink + level (last + * writer wins — see module docs). + */ +export declare function initKernelLogging(callback: ((err: Error | null, arg: Array) => any), level: string): void + +/** + * Return the bridge's [`KernelLoggingStats`]. Safe to call before + * `initKernelLogging` (reports `installed: false`, `dropped: 0`). + */ +export declare function kernelLoggingStats(): KernelLoggingStats + +/** + * Snapshot of the bridge's runtime state for observability. + * + * `installed` is `true` only when the process-global subscriber was + * successfully installed by *this* bridge (and the drain thread started); * `false` means another global subscriber was already set or the drain * thread could not be spawned, so kernel logs are NOT reaching the JS sink. * `dropped` is the cumulative count of records discarded because the @@ -667,16 +1205,81 @@ export interface KernelLoggingStats { installed: boolean dropped: number } + /** - * Return the bridge's [`KernelLoggingStats`]. Safe to call before - * `initKernelLogging` (reports `installed: false`, `dropped: 0`). + * One kernel log event, as handed to JS. `level` is a lower-case string + * (`error`/`warn`/`info`/`debug`/`trace`) the Node side maps onto its + * `LogLevel`; `target` is the originating `tracing` target (e.g. + * `databricks::sql::kernel`); `message` is the rendered event plus any + * structured `key=value` fields. */ -export declare function kernelLoggingStats(): KernelLoggingStats +export interface LogRecord { + level: string + target: string + message: string +} + +/** + * A named bound parameter — a [`TypedValueInput`] plus its `:name`. Kept a + * distinct napi object (rather than an optional `name` on `TypedValueInput`) + * so the positional surface stays a clean ordered list with no name field. + */ +export interface NamedTypedValueInput { + name: string + sqlType: string + value?: string +} + +/** + * Open a Databricks SQL session and return an opaque `Connection` + * wrapping the kernel `Session`. Authentication is selected by + * `options.auth_mode` (PAT / OAuth M2M / OAuth U2M) — see + * [`build_auth_config`]. + * + * The JS-visible name is `openSession` (napi-rs converts snake_case + * to camelCase for free functions). + */ +export declare function openSession(options: ConnectionOptions): Promise + +/** + * Programmatic HTTP/HTTPS proxy configuration, mirroring the kernel's + * internal [`ProxyConfig`]. Supplied as a structured object rather than a + * flattened URL so credentials never have to be percent-encoded into the URL + * and the bypass-host list can be expressed. + * + * - `url` — proxy endpoint, e.g. `"http://proxy.corp.example.com:8080"`. Must + * use the `http://` or `https://` scheme. + * - `username` / `password` — optional proxy basic-auth, applied via + * `reqwest`'s `Proxy::basic_auth` (not embedded in the URL). + * - `bypassHosts` — optional comma-separated host/domain list that should + * bypass the proxy (e.g. `"localhost,*.internal.corp"`). + */ +export interface ProxyInput { + url: string + username?: string + password?: string + bypassHosts?: string +} + +/** + * A pre-marshalled SEA parameter that preserves `sql_type` verbatim. + * Omit `name` for positional markers; the kernel assigns their ordinals. + */ +export interface RawParameterInput { + /** Named marker name. Omit for a positional marker. */ + name?: string + /** Databricks SQL type name sent verbatim to SEA. */ + sqlType: string + /** String-encoded value. `None` represents SQL NULL. */ + value?: string +} + /** * Live-retarget the bridge's level (one of * `off`/`error`/`warn`/`info`/`debug`/`trace`, case-insensitive). */ export declare function setKernelLogLevel(level: string): void + /** * JS-visible binding for a single positional parameter. * @@ -710,41 +1313,7 @@ export interface TypedValueInput { */ value?: string } -/** - * A pre-marshalled SEA parameter that preserves `sql_type` verbatim. - * Omit `name` for positional markers; the kernel assigns their ordinals. - */ -export interface RawParameterInput { - /** Named marker name. Omit for a positional marker. */ - name?: string - /** Databricks SQL type name sent verbatim to SEA. */ - sqlType: string - /** String-encoded value. `None` represents SQL NULL. */ - value?: string -} -/** - * A single Arrow IPC stream payload encoding one record batch (plus - * the schema header so the JS-side reader is stateless). - */ -export interface ArrowBatch { - /** - * Arrow IPC stream payload (schema header + 1 record-batch - * message). Decode with `apache-arrow`'s `RecordBatchReader`. - */ - ipcBytes: Buffer -} -/** - * An Arrow IPC stream payload encoding just the result schema (no - * record-batch messages). Returned by `Statement.schema()`. - */ -export interface ArrowSchema { - /** - * Arrow IPC stream payload (schema header only, no record-batch - * messages). Decode with `apache-arrow`'s `RecordBatchReader` — - * the reader will expose the schema and immediately end. - */ - ipcBytes: Buffer -} + /** * Returns the native binding's crate version (`CARGO_PKG_VERSION`). * @@ -752,541 +1321,3 @@ export interface ArrowSchema { * loaded?" probe for the JS-side loader's structured diagnostics. */ export declare function version(): string -/** - * Opaque async-statement handle. - * - * Returned by `Connection.submitStatement(...)` after the kernel - * `Statement::submit()` returns (server sent `wait_timeout=0s`, so - * the response carries a `statement_id` but the statement is still - * `Pending`/`Running`). JS drives polling via `status()` / - * `awaitResult()`. - * - * Concurrency shape: `status()`, `awaitResult()`, and `close()` take - * `inner.lock()` and hold the guard across the kernel `.await` (tokio - * `Mutex` is FIFO), so `status()` / `close()` queue behind any - * in-flight `awaitResult()` until it returns naturally. `cancel()` is - * the deliberate exception: it does **not** touch `inner` — it fires - * through the detached `AsyncStatementCanceller` (session + - * statement_id, captured at construction), so an explicit - * `stmt.cancel()` interrupts an in-flight `awaitResult()` instead of - * queueing behind it. The server-side cancel flips the statement - * terminal, which the parked `awaitResult()` poll loop observes - * (`Cancelled`) and returns on. The kernel's `AwaitResultCancelGuard` - * still covers the drop-cancel case (Promise.race / timeout) - * independently — see module docs. - */ -export declare class AsyncStatement { - /** - * Server-issued statement id. Cached at construction; readable - * even after `close()` so JS-side log lines can correlate - * against kernel / server logs which key on the same id. - */ - get statementId(): string - /** - * One-shot status check. Returns a string enum matching the - * kernel `StatementStatus` shape: - * `'Pending' | 'Running' | 'Succeeded' | 'Failed' | - * 'Cancelled' | 'Closed' | 'Unknown'`. (`'Unknown'` is the - * `#[non_exhaustive]` forward-compat catch-all that - * `StatementStatus::as_str` can return — consumers switching on - * the state must handle it.) Returns - * `KernelError(InvalidStatementHandle)` if the statement has - * been explicitly `close()`d. - * - * The `Failed` variant collapses to the string `'Failed'` on - * the JS side; the underlying error envelope (sql_state / - * error_code / query_id) is surfaced by `awaitResult()`'s - * rejection, which is where callers actually need the typed - * error. `status()` is intended for polling progress UIs - * that only need the state name. - */ - status(): Promise - /** Rows modified by the statement (UPDATE / INSERT / DELETE / MERGE). */ - numModifiedRows(): Promise - /** - * Server-supplied user-facing message (may contain SQL fragments — - * redact before centralised logging). - */ - displayMessage(): Promise - /** Server-supplied diagnostic detail. */ - diagnosticInfo(): Promise - /** Server-supplied structured error detail (JSON), when enabled. */ - errorDetailsJson(): Promise - /** - * Block until the server reaches a terminal state, then return - * an `AsyncResultHandle` that wraps the materialised result - * stream. The handle exposes `fetchNextBatch()` / `schema()` - * for consuming the result, plus `statementId` for log - * correlation. - * - * Drop-cancel safety: kernel `await_result` installs - * `AwaitResultCancelGuard` which fires a fire-and-forget - * `cancel_statement` if the future is dropped mid-poll - * (timeout, tokio::select! loser, JS-side `Promise.race` - * loser). The `util::guarded` `catch_unwind` here covers the - * V8-panic-across-boundary case on top. Returns - * `KernelError(InvalidStatementHandle)` if the statement has - * been explicitly `close()`d. - */ - awaitResult(): Promise - /** - * Server-side cancel. Returns - * `KernelError(InvalidStatementHandle)` if the statement has - * been explicitly `close()`d. Idempotent against a server - * that already reached a terminal state — the kernel's - * `cancel_statement` is a no-op there. - * - * **Lock-free by design.** Unlike `status()` / `awaitResult()` / - * `close()`, this does not take `inner.lock()` — it fires through - * the detached `AsyncStatementCanceller` captured at construction. - * That lets `stmt.cancel()` interrupt an in-flight `awaitResult()` - * (which holds the mutex for the whole poll) instead of queueing - * behind it: the server-side cancel flips the statement terminal, - * the parked `awaitResult()` poll loop observes `Cancelled` and - * returns. The closed-state check reads a lock-free flag so a - * cancel after an explicit `close()` still surfaces - * `InvalidStatementHandle`. - */ - cancel(): Promise - /** - * Explicit close. Idempotent — a second call on an - * already-closed handle returns `Ok(())`. On `Err`, the napi - * inner is already `None`, so a JS-side retry sees the - * closed-handle short-circuit and returns `Ok(())` without - * re-attempting the wire call. The kernel's own `Drop` - * fire-and-forget retry runs once in the background. - */ - close(): Promise -} -/** - * Opaque result-fetch handle returned by - * `AsyncStatement.awaitResult()`. Wraps a kernel `ResultStream` - * directly; structurally analogous to the sync `Statement`'s - * fetch-side surface (`fetchNextBatch` / `schema` / - * `statementId`). - * - * `cancel()` / `close()` are not exposed: the parent - * `AsyncStatement` owns server-side lifecycle. A `close()` here - * would create dual-ownership of the same statement_id with - * inconsistent close semantics. Callers `close()` the parent - * `AsyncStatement` after they're done fetching. - * - * Schema is cached at construction so it survives the underlying - * stream being drained; mirrors the sync `Statement.schema()` - * post-close contract. - */ -export declare class AsyncResultHandle { - /** - * Server-issued statement id. Cached at construction; readable - * for log correlation. Matches the parent `AsyncStatement`'s - * `statementId`. - */ - get statementId(): string - /** - * Pull the next batch of results. Returns `null` when the - * stream is exhausted. The returned `ArrowBatch.ipcBytes` is a - * complete Arrow IPC stream (schema header + 1 record-batch - * message), suitable for handing to `apache-arrow`'s - * `RecordBatchReader`. Byte-identical to the sync - * `Statement.fetchNextBatch()` payload for the same query. - */ - fetchNextBatch(): Promise - /** - * Result schema as an Arrow IPC payload (schema header only, - * no record-batch message). Available before any batches have - * been fetched. Sync because the body has no `.await` — - * `encode_ipc_stream` is pure CPU work over the cached - * `Arc`. - */ - schema(): ArrowSchema -} -/** - * Handle returned by `Connection.executeStatementCancellable`. Owns the - * built-but-not-yet-executed kernel `Statement` plus a detached - * [`StatementCanceller`] captured before dispatch, so JS can fire a - * server-side cancel while the blocking `result()` is in flight. - * - * `pending` is `Arc>>` so `result()` can - * `.take()` the statement (the kernel `execute()` borrows it `&mut`, - * then it moves into the produced `Statement` wrapper to keep its - * `ValidityFlag` set — see `statement.rs`). A second `result()` call - * after the first resolved surfaces `InvalidStatementHandle`. - */ -export declare class CancellableExecution { - /** - * The server-issued statement id this execution targets, if the - * server has issued one yet (`null` before the initial submit - * round-trip publishes it mid-`result()`). Useful for log - * correlation while the blocking drive is in flight. - */ - get statementId(): string | null - /** - * Drive the blocking `execute()` and resolve to a `Statement` - * (identical to what `executeStatement` returns) once the kernel - * reaches a terminal state and the result stream is ready. - * - * Consumes the pending statement: a second `result()` call returns - * `KernelError(InvalidStatementHandle)`. The future is - * drop-cancel-safe — the kernel's per-execute `MidExecuteCancelState` - * guard fires a fire-and-forget `cancel_statement` if this future is - * dropped mid-flight (`Promise.race` / timeout loser), independently - * of an explicit `cancel()`. - * - * On a server-side cancel the kernel's blocking `execute()` currently - * surfaces `InvalidArgument` (a known kernel quirk — the async path - * returns `Cancelled`). When this handle's `cancel()` actually dispatched a - * server-side cancel, we normalise that into `Cancelled` here so JS callers - * can rely on a single cancelled-status code regardless of execution path. - * - * Three outcomes can race the blocking drive: (1) a natural terminal state - * → `Ok` or the genuine error; (2) an explicit `cancel()` that dispatched a - * server cancel → this `result()` rejects with a `Cancelled`-coded error - * (the normalisation above); (3) the future being **dropped** mid-flight - * (`Promise.race`/timeout loser) → the kernel's `MidExecuteCancelState` - * drop-guard fires a fire-and-forget `cancel_statement`, but there is no - * `result()` left to observe a code. Only (2) yields a `Cancelled` error. - */ - result(): Promise - /** - * Server-side cancel of the in-flight statement. - * - * Lock-free: fires the detached `StatementCanceller` captured at - * construction rather than taking the mutex `result()` holds, so it - * interrupts a still-running blocking `result()` instead of queueing - * behind it. No-op (returns `Ok`) if `result()` already finished - * successfully, or if no statement id has been observed yet (query still - * in its initial submit round-trip), and idempotent against a server - * already in a terminal state. - */ - cancel(): Promise -} -/** - * Opaque connection handle wrapping a kernel `Session`. - * - * `inner` is `Arc>>` so: - * - the Drop impl can clone the `Arc` and `.take()` the session on a - * background tokio task without holding `&mut self` (which Drop is - * forbidden from doing across an `await`), - * - `close()` can `.take()` the session to consume it for the kernel's - * move-by-value `Session::close(self)` signature. - * - * **Concurrency shape** — both `executeStatement` and - * `submitStatement` build the kernel `Statement` under `inner.lock()` - * and then RELEASE the guard before the wire call - * (`stmt.execute().await` / `stmt.submit().await`). `Session::statement()` - * is `&self`-callable and only clones the session's internal `Arc`, so - * the built statement is independent of the guard. Concurrent - * `Promise.all([executeStatement(q1), submitStatement(q2)])` therefore - * serialise only for the microsecond statement-build, not the network - * round-trip, and `close()` never blocks behind an in-flight execute or - * submit. See - * `sea-workflow/jira-candidates/2026-05-24-napi-cancel-during-fetch.md`. - */ -export declare class Connection { - /** - * Server-issued session id. Cached at construction; readable - * even after `close()` so JS-side log lines can correlate - * against kernel / server logs which key on the same id. - */ - get sessionId(): string - /** - * Execute a SQL statement and return a Statement handle that - * streams batches via `fetchNextBatch()`. - * - * Catalog / schema / sessionConf are session-level - * (`openSession`). Per-statement options on `ExecuteOptions`: - * - `statementConf` — per-statement Spark conf overlay - * - `queryTags` — serialised to a comma-separated `key:value` - * string and placed in `statement_conf["query_tags"]`, - * matching NodeJS Thrift's `serializeQueryTags` wire shape - * - * `options` is omitted/`None` for the no-options path; passing - * `{ statementConf: {} }` (an empty map) is treated the same as - * omission to keep the wire shape stable for the common case. - */ - executeStatement(sql: string, options?: ExecuteOptions | undefined | null): Promise - /** - * directResults execute — the Thrift/JDBC model. Sends ExecuteStatement - * with no `wait_timeout` field (server applies its ~10s default inline wait - * and auto-closes on success) and returns WITHOUT polling past it: - * - * - a **`Statement`** (left arm) when the query finished within the inline - * wait — terminal, result ready inline, `close()` is a clean release; - * - an **`AsyncStatement`** (right arm) when it did not — a poll/cancel - * handle the caller drives (`status()` / `awaitResult()` / `cancel()`). - * - * JS distinguishes the arms by feature-detecting `awaitResult` (present - * only on `AsyncStatement`). This is the path that gives mid-run cancel for - * long queries WITHOUT the eager-handle / close-drives workaround: the - * returned handle always corresponds to a server-owned statement. - * - * **Load-bearing contract:** the kernel's `DirectStatement::{Completed, - * Running}` discriminant cannot ride on these opaque `#[napi]` classes, so - * consumers MUST feature-detect via `awaitResult` (the only member unique to - * `AsyncStatement`). `Statement` (the Completed arm) MUST NOT gain an - * `awaitResult` member, or every consumer silently misroutes. The pyo3 - * binding makes the same `await_result`-probe assumption. - */ - executeStatementDirect(sql: string, options?: ExecuteOptions | undefined | null): Promise - /** - * Execute a SQL statement on the blocking (sync) path, but return a - * `CancellableExecution` handle so a concurrent JS task can cancel - * the query *while it is still running server-side*. - * - * `executeStatement` builds the kernel `Statement`, awaits the - * blocking `execute()`, and only then hands JS a `Statement` — so a - * query that runs for several seconds is uncancellable from JS on - * that path (there is no handle until the blocking call resolves). - * This method instead builds the statement, captures a detached - * `StatementCanceller` **before** dispatching `execute()`, and hands - * JS a `CancellableExecution` immediately. The caller drives the - * blocking execution via `result()` (resolves to the same - * `Statement` `executeStatement` returns) and can fire `cancel()` - * concurrently to interrupt a still-running query mid-COMPUTE. - * - * Option semantics are identical to `executeStatement`. - * Mirrors the pyo3 `Statement.canceller()` / `Statement.execute()` - * split (PR #121): obtain the canceller before the blocking drive. - */ - executeStatementCancellable(sql: string, options?: ExecuteOptions | undefined | null): Promise - /** - * Submit a SQL statement and return immediately with an - * `AsyncStatement` handle, without blocking until the query - * finishes. The kernel's `Statement::submit()` sends - * `wait_timeout=0s`, so the server responds as soon as it has a - * `statement_id` (state `Pending`/`Running`); JS drives polling - * via `AsyncStatement.status()` and materialises results with - * `AsyncStatement.awaitResult()`. - * - * This is the async-execution path the Thrift backend always - * 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`. - * 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 - * differs from `executeStatement`. - */ - submitStatement(sql: string, options?: ExecuteOptions | undefined | null): Promise - /** - * Explicit close. Awaits the server-side `DeleteSession` so the - * JS caller can observe failures (auth revoked mid-session, - * warehouse stopped, network error). Idempotent — a second call - * on an already-closed connection returns `Ok`. - * - * **Errors are terminal from the JS side.** The kernel session - * handle is consumed (`take()`) BEFORE the wire `DeleteSession` - * runs, because `Session::close` takes `self` by value. On `Err`, - * the napi `inner` is already `None`, so a JS-side retry sees a - * closed connection and returns `Ok(())` without re-attempting - * the wire call. The kernel's own `Drop` fire-and-forget retry - * runs once in the background — the JS caller can log the error - * but cannot drive a retry. If you need retry-on-failure - * semantics for `DeleteSession`, layer them above this method. - */ - close(): Promise - /** - * All catalogs visible to the session. - * - * JDBC `getCatalogs` shape: `TABLE_CAT: Utf8`. - */ - listCatalogs(): Promise - /** - * Schemas filtered by catalog (exact) and schema name pattern. - * - * JDBC `getSchemas` shape: `TABLE_SCHEM, TABLE_CATALOG`. - */ - listSchemas(catalog?: string | undefined | null, schemaPattern?: string | undefined | null): Promise - /** - * Tables filtered by catalog (exact), schema (pattern), table (pattern). - * - * JDBC `getTables` shape: 10 columns. `tableTypes`, when provided, - * filters rows by `TABLE_TYPE` kernel-side. - * - * `tableTypes` is an advisory filter. Databricks `SHOW TABLES` does - * NOT honour the table-type filter server-side; the kernel applies - * it client-side after the result returns. Callers expecting - * server-side rejection of off-type tables should not rely on this. - */ - listTables(catalog?: string | undefined | null, schemaPattern?: string | undefined | null, tablePattern?: string | undefined | null, tableTypes?: Array | undefined | null): Promise - /** - * Columns of tables matching the filter. - * - * JDBC `getColumns` shape: 23 columns. - */ - listColumns(catalog?: string | undefined | null, schemaPattern?: string | undefined | null, tablePattern?: string | undefined | null, columnPattern?: string | undefined | null): Promise - /** - * Functions visible to the session. `catalog` is exact; - * `schemaPattern` and `functionPattern` are SQL LIKE. - */ - listFunctions(catalog?: string | undefined | null, schemaPattern?: string | undefined | null, functionPattern?: string | undefined | null): Promise - /** - * Procedures visible to the session. `catalog` is exact; - * `schemaPattern` and `procedurePattern` are SQL LIKE. - */ - listProcedures(catalog?: string | undefined | null, schemaPattern?: string | undefined | null, procedurePattern?: string | undefined | null): Promise - /** - * All table types (`TABLE`, `VIEW`, `SYSTEM TABLE`, …). - * No wire call — static in-memory result. - */ - listTableTypes(): Promise - /** - * SQL data types supported by the workspace. - * No wire call — static in-memory result. - */ - listTypeInfo(): Promise - /** - * Primary keys for the given table. All three identifiers are - * exact — ODBC `SQLPrimaryKeys` does not support patterns. - */ - getPrimaryKeys(catalog: string | undefined | null, schema: string | undefined | null, table: string): Promise - /** - * Foreign-key relationships. The parent side is optional. When the - * foreign table is omitted, returns an empty result without issuing a - * server statement. When it is provided, its catalog and schema are - * required. All identifiers are exact — no LIKE patterns. - */ - getCrossReference(parentCatalog: string | undefined | null, parentSchema: string | undefined | null, parentTable: string | undefined | null, foreignCatalog: string | undefined | null, foreignSchema: string | undefined | null, foreignTable: string | undefined | null): Promise -} -/** - * Opaque executed-statement handle. - * - * **Current concurrency shape** — every method takes `inner.lock()` - * and holds the guard across the kernel `.await`. tokio `Mutex` is - * FIFO, so cancel/close queue behind any in-flight `fetchNextBatch` - * until it returns naturally. This is a known limitation that exists - * because the napi shape has not yet been split into an - * `Arc` (for cancel/close, which the - * kernel exposes as `&self`-callable) plus a `Mutex>` only - * for the borrowed-mut fetch path. The lock-shape refactor needs a - * small kernel-side accessor and lands in a follow-up PR — see - * `sea-workflow/jira-candidates/2026-05-24-napi-cancel-during-fetch.md`. - * - * `schema` and `statement_id` are cached at construction so they - * survive `close()` — JS callers building error reports against a - * disposed statement can still read them. - */ -export declare class Statement { - /** - * Server-issued statement id. Cached at construction; readable - * even after `close()` so JS-side log lines can correlate against - * kernel / server logs which key on the same id. - */ - get statementId(): string - /** - * Number of rows modified by the statement (UPDATE / INSERT / - * DELETE / MERGE). `null` for SELECT and on warehouses that don't - * surface the counter. Mirrors Thrift's - * `TGetOperationStatusResp.numModifiedRows`. - */ - numModifiedRows(): Promise - /** - * Server-supplied user-facing message. Mirrors Thrift's - * `TGetOperationStatusResp.displayMessage`. **PII / sensitive- - * data note:** may contain SQL fragments or parameter values — - * redact before centralised logging. - * - * Populated on `Succeeded` / `Closed` paths (incl. an empty `Closed`). - * On terminal-error states (`Failed` / `Cancelled`) the kernel returns - * an Error instead of a `Statement`, and the same field rides on the JS - * Error envelope under the same `displayMessage` key. - */ - displayMessage(): Promise - /** - * Server-supplied diagnostic detail — multi-line operator / - * stack context. Mirrors Thrift's - * `TGetOperationStatusResp.diagnosticInfo`. For support surfaces, - * not user-facing. Same reachability + PII caveats as - * `displayMessage`. - */ - diagnosticInfo(): Promise - /** - * Server-supplied JSON blob with extended error details. Mirrors - * Thrift's `TGetOperationStatusResp.errorDetailsJson`. - * Pass-through string — JS callers parse with `JSON.parse` if - * they need structured access. - * - * **Server-side gating:** populated only when the workspace has - * `spark.databricks.sql.errorDetailsJson.enabled = true` on the - * underlying SQL cluster. The flag is internal-only / default- - * false in the Databricks runtime, so for most JS callers this - * will return `null`. Admin-enabled workspaces return content - * shaped like `{"errorClass": "...", "messageTemplate": "..."}`. - * - * **Unbounded:** when populated, server can return a multi-MB - * blob; size before logging. - */ - errorDetailsJson(): Promise - /** - * Pull the next batch of results. Returns `null` when the stream - * is exhausted. The returned `ArrowBatch.ipcBytes` is a complete - * Arrow IPC stream (schema header + 1 record-batch message) - * suitable for handing to `apache-arrow`'s `RecordBatchReader`. - * - * On `Err`, the stream is in an unspecified state — call - * `close()` and discard the `Statement`. Subsequent - * `fetchNextBatch()` calls after an error are not guaranteed to - * succeed or fail consistently. - */ - fetchNextBatch(): Promise - /** - * Result schema as an Arrow IPC payload (schema header only, no - * record-batch message). Available before any batches have been - * fetched, and remains available after `close()` — the kernel - * materialises the schema eagerly so JS callers can build error - * reports against a disposed statement. - * - * Sync because the body has no `.await` — `encode_ipc_stream` is - * pure CPU work over an `Arc` already cached on the - * wrapper. Mirrors `pyo3/src/statement.rs::arrow_schema` (sync). - * napi-rs converts a panic in a sync `#[napi]` entry point into a - * thrown JS error via its own macro-expanded boundary, so the - * `util::guarded` `catch_unwind` wrapper that the `async fn` - * entry points use is not required for this method. - */ - schema(): ArrowSchema - /** - * Server-side cancel. - * - * For executed statements: short-circuits to `Ok(())` if - * `fetchNextBatch` has already returned `null` (stream - * naturally exhausted) — matches the JDBC `Statement.cancel()` - * no-op-after-completion contract, so JS callers can fire cancel - * defensively without distinguishing "real cancel" from "raced - * with natural completion." - * - * For metadata streams: no-op (the kernel has no in-flight - * cancellation surface for metadata calls today). - * - * Returns `KernelError(InvalidStatementHandle)` if the statement - * has been explicitly `close()`d. - */ - cancel(): Promise - /** - * Explicit close. - * - * For executed statements: awaits the server-side `CloseStatement` - * so the JS caller can observe failures (auth revoked mid-session, - * network error, server-side error). Idempotent — a second call - * on an already-closed statement returns `Ok`. - * - * **Errors are terminal from the JS side.** The kernel executed - * handle is taken out of `inner` BEFORE the wire `CloseStatement` - * runs (so `Drop` knows there's nothing left to clean up). On - * `Err`, the napi `inner` is already `None`, so a JS-side retry - * sees a closed statement and returns `Ok(())` without re- - * attempting the wire call. The kernel-level `ExecutedStatement` - * has been consumed at that point and the value is dropped on - * the way out of the closure — the kernel's `ExecutedStatement:: - * Drop` then fires-and-forgets a single retry on the captured - * runtime. The JS caller can log the error but cannot drive a - * further retry. If you need retry-on-failure semantics for - * `CloseStatement`, layer them above this method. - * - * For metadata streams: drops the stream (no server round-trip - * needed — metadata results have no in-flight server-side - * resource to release). - */ - close(): Promise -} diff --git a/napi/index.js b/napi/index.js index ad50ecc9..6902ddee 100644 --- a/napi/index.js +++ b/napi/index.js @@ -1,325 +1,713 @@ -/* tslint:disable */ +// prettier-ignore /* eslint-disable */ -/* prettier-ignore */ - +// @ts-nocheck /* auto-generated by NAPI-RS */ -const { existsSync, readFileSync } = require('fs') -const { join } = require('path') +const { readFileSync } = require('fs') +let nativeBinding = null +const loadErrors = [] -const { platform, arch } = process +const isMusl = () => { + let musl = false + if (process.platform === 'linux') { + musl = isMuslFromFilesystem() + if (musl === null) { + musl = isMuslFromReport() + } + if (musl === null) { + musl = isMuslFromChildProcess() + } + } + return musl +} -let nativeBinding = null -let localFileExisted = false -let loadError = null +const isFileMusl = (f) => f.includes('libc.musl-') || f.includes('ld-musl-') -function isMusl() { - // For Node 10 - if (!process.report || typeof process.report.getReport !== 'function') { - try { - const lddPath = require('child_process').execSync('which ldd').toString().trim() - return readFileSync(lddPath, 'utf8').includes('musl') - } catch (e) { +const isMuslFromFilesystem = () => { + try { + return readFileSync('/usr/bin/ldd', 'utf-8').includes('musl') + } catch { + return null + } +} + +const isMuslFromReport = () => { + let report = null + if (process.report && typeof process.report.getReport === 'function') { + process.report.excludeNetwork = true + report = process.report.getReport() + } + if (!report) { + return null + } + if (report.header && report.header.glibcVersionRuntime) { + return false + } + if (Array.isArray(report.sharedObjects)) { + if (report.sharedObjects.some(isFileMusl)) { return true } - } else { - const { glibcVersionRuntime } = process.report.getReport().header - return !glibcVersionRuntime } + return false } -switch (platform) { - case 'android': - switch (arch) { - case 'arm64': - localFileExisted = existsSync(join(__dirname, 'index.android-arm64.node')) +const isMuslFromChildProcess = () => { + try { + return require('child_process').execSync('ldd --version', { encoding: 'utf8' }).includes('musl') + } catch (e) { + // If we reach this case, we don't know if the system is musl or not, so is better to just fallback to false + return false + } +} + +function requireNative() { + if (process.env.NAPI_RS_NATIVE_LIBRARY_PATH) { + try { + return require(process.env.NAPI_RS_NATIVE_LIBRARY_PATH); + } catch (err) { + loadErrors.push(err) + } + } else if (process.platform === 'android') { + if (process.arch === 'arm64') { + try { + return require('./index.android-arm64.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@databricks/databricks-sql-kernel-android-arm64') + const bindingPackageVersion = require('@databricks/databricks-sql-kernel-android-arm64/package.json').version + if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else if (process.arch === 'arm') { + try { + return require('./index.android-arm-eabi.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@databricks/databricks-sql-kernel-android-arm-eabi') + const bindingPackageVersion = require('@databricks/databricks-sql-kernel-android-arm-eabi/package.json').version + if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else { + loadErrors.push(new Error(`Unsupported architecture on Android ${process.arch}`)) + } + } else if (process.platform === 'win32') { + if (process.arch === 'x64') { + if ((process.config && process.config.variables && process.config.variables.shlib_suffix === 'dll.a') || (process.config && process.config.variables && process.config.variables.node_target_type === 'shared_library')) { try { - if (localFileExisted) { - nativeBinding = require('./index.android-arm64.node') - } else { - nativeBinding = require('@databricks/databricks-sql-kernel-android-arm64') - } + return require('./index.win32-x64-gnu.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@databricks/databricks-sql-kernel-win32-x64-gnu') + const bindingPackageVersion = require('@databricks/databricks-sql-kernel-win32-x64-gnu/package.json').version + if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else { + try { + return require('./index.win32-x64-msvc.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@databricks/databricks-sql-kernel-win32-x64-msvc') + const bindingPackageVersion = require('@databricks/databricks-sql-kernel-win32-x64-msvc/package.json').version + if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } + } else if (process.arch === 'ia32') { + try { + return require('./index.win32-ia32-msvc.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@databricks/databricks-sql-kernel-win32-ia32-msvc') + const bindingPackageVersion = require('@databricks/databricks-sql-kernel-win32-ia32-msvc/package.json').version + if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else if (process.arch === 'arm64') { + try { + return require('./index.win32-arm64-msvc.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@databricks/databricks-sql-kernel-win32-arm64-msvc') + const bindingPackageVersion = require('@databricks/databricks-sql-kernel-win32-arm64-msvc/package.json').version + if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else { + loadErrors.push(new Error(`Unsupported architecture on Windows: ${process.arch}`)) + } + } else if (process.platform === 'darwin') { + try { + return require('./index.darwin-universal.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@databricks/databricks-sql-kernel-darwin-universal') + const bindingPackageVersion = require('@databricks/databricks-sql-kernel-darwin-universal/package.json').version + if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + if (process.arch === 'x64') { + try { + return require('./index.darwin-x64.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@databricks/databricks-sql-kernel-darwin-x64') + const bindingPackageVersion = require('@databricks/databricks-sql-kernel-darwin-x64/package.json').version + if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else if (process.arch === 'arm64') { + try { + return require('./index.darwin-arm64.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@databricks/databricks-sql-kernel-darwin-arm64') + const bindingPackageVersion = require('@databricks/databricks-sql-kernel-darwin-arm64/package.json').version + if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else { + loadErrors.push(new Error(`Unsupported architecture on macOS: ${process.arch}`)) + } + } else if (process.platform === 'freebsd') { + if (process.arch === 'x64') { + try { + return require('./index.freebsd-x64.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@databricks/databricks-sql-kernel-freebsd-x64') + const bindingPackageVersion = require('@databricks/databricks-sql-kernel-freebsd-x64/package.json').version + if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else if (process.arch === 'arm64') { + try { + return require('./index.freebsd-arm64.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@databricks/databricks-sql-kernel-freebsd-arm64') + const bindingPackageVersion = require('@databricks/databricks-sql-kernel-freebsd-arm64/package.json').version + if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else { + loadErrors.push(new Error(`Unsupported architecture on FreeBSD: ${process.arch}`)) + } + } else if (process.platform === 'linux') { + if (process.arch === 'x64') { + if (isMusl()) { + try { + return require('./index.linux-x64-musl.node') } catch (e) { - loadError = e + loadErrors.push(e) } - break - case 'arm': - localFileExisted = existsSync(join(__dirname, 'index.android-arm-eabi.node')) try { - if (localFileExisted) { - nativeBinding = require('./index.android-arm-eabi.node') - } else { - nativeBinding = require('@databricks/databricks-sql-kernel-android-arm-eabi') + const binding = require('@databricks/databricks-sql-kernel-linux-x64-musl') + const bindingPackageVersion = require('@databricks/databricks-sql-kernel-linux-x64-musl/package.json').version + if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) } + return binding } catch (e) { - loadError = e + loadErrors.push(e) } - break - default: - throw new Error(`Unsupported architecture on Android ${arch}`) - } - break - case 'win32': - switch (arch) { - case 'x64': - localFileExisted = existsSync( - join(__dirname, 'index.win32-x64-msvc.node') - ) + } else { try { - if (localFileExisted) { - nativeBinding = require('./index.win32-x64-msvc.node') - } else { - nativeBinding = require('@databricks/databricks-sql-kernel-win32-x64-msvc') - } + return require('./index.linux-x64-gnu.node') } catch (e) { - loadError = e + loadErrors.push(e) } - break - case 'ia32': - localFileExisted = existsSync( - join(__dirname, 'index.win32-ia32-msvc.node') - ) try { - if (localFileExisted) { - nativeBinding = require('./index.win32-ia32-msvc.node') - } else { - nativeBinding = require('@databricks/databricks-sql-kernel-win32-ia32-msvc') + const binding = require('@databricks/databricks-sql-kernel-linux-x64-gnu') + const bindingPackageVersion = require('@databricks/databricks-sql-kernel-linux-x64-gnu/package.json').version + if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) } + return binding } catch (e) { - loadError = e + loadErrors.push(e) } - break - case 'arm64': - localFileExisted = existsSync( - join(__dirname, 'index.win32-arm64-msvc.node') - ) + } + } else if (process.arch === 'arm64') { + if (isMusl()) { try { - if (localFileExisted) { - nativeBinding = require('./index.win32-arm64-msvc.node') - } else { - nativeBinding = require('@databricks/databricks-sql-kernel-win32-arm64-msvc') + return require('./index.linux-arm64-musl.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@databricks/databricks-sql-kernel-linux-arm64-musl') + const bindingPackageVersion = require('@databricks/databricks-sql-kernel-linux-arm64-musl/package.json').version + if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) } + return binding } catch (e) { - loadError = e + loadErrors.push(e) } - break - default: - throw new Error(`Unsupported architecture on Windows: ${arch}`) - } - break - case 'darwin': - localFileExisted = existsSync(join(__dirname, 'index.darwin-universal.node')) - try { - if (localFileExisted) { - nativeBinding = require('./index.darwin-universal.node') } else { - nativeBinding = require('@databricks/databricks-sql-kernel-darwin-universal') - } - break - } catch {} - switch (arch) { - case 'x64': - localFileExisted = existsSync(join(__dirname, 'index.darwin-x64.node')) try { - if (localFileExisted) { - nativeBinding = require('./index.darwin-x64.node') - } else { - nativeBinding = require('@databricks/databricks-sql-kernel-darwin-x64') - } + return require('./index.linux-arm64-gnu.node') } catch (e) { - loadError = e + loadErrors.push(e) } - break - case 'arm64': - localFileExisted = existsSync( - join(__dirname, 'index.darwin-arm64.node') - ) try { - if (localFileExisted) { - nativeBinding = require('./index.darwin-arm64.node') - } else { - nativeBinding = require('@databricks/databricks-sql-kernel-darwin-arm64') + const binding = require('@databricks/databricks-sql-kernel-linux-arm64-gnu') + const bindingPackageVersion = require('@databricks/databricks-sql-kernel-linux-arm64-gnu/package.json').version + if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) } + return binding } catch (e) { - loadError = e + loadErrors.push(e) } - break - default: - throw new Error(`Unsupported architecture on macOS: ${arch}`) - } - break - case 'freebsd': - if (arch !== 'x64') { - throw new Error(`Unsupported architecture on FreeBSD: ${arch}`) - } - localFileExisted = existsSync(join(__dirname, 'index.freebsd-x64.node')) - try { - if (localFileExisted) { - nativeBinding = require('./index.freebsd-x64.node') - } else { - nativeBinding = require('@databricks/databricks-sql-kernel-freebsd-x64') } - } catch (e) { - loadError = e - } - break - case 'linux': - switch (arch) { - case 'x64': - if (isMusl()) { - localFileExisted = existsSync( - join(__dirname, 'index.linux-x64-musl.node') - ) - try { - if (localFileExisted) { - nativeBinding = require('./index.linux-x64-musl.node') - } else { - nativeBinding = require('@databricks/databricks-sql-kernel-linux-x64-musl') - } - } catch (e) { - loadError = e - } - } else { - localFileExisted = existsSync( - join(__dirname, 'index.linux-x64-gnu.node') - ) - try { - if (localFileExisted) { - nativeBinding = require('./index.linux-x64-gnu.node') - } else { - nativeBinding = require('@databricks/databricks-sql-kernel-linux-x64-gnu') - } - } catch (e) { - loadError = e + } else if (process.arch === 'arm') { + if (isMusl()) { + try { + return require('./index.linux-arm-musleabihf.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@databricks/databricks-sql-kernel-linux-arm-musleabihf') + const bindingPackageVersion = require('@databricks/databricks-sql-kernel-linux-arm-musleabihf/package.json').version + if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) } + return binding + } catch (e) { + loadErrors.push(e) + } + } else { + try { + return require('./index.linux-arm-gnueabihf.node') + } catch (e) { + loadErrors.push(e) } - break - case 'arm64': - if (isMusl()) { - localFileExisted = existsSync( - join(__dirname, 'index.linux-arm64-musl.node') - ) - try { - if (localFileExisted) { - nativeBinding = require('./index.linux-arm64-musl.node') - } else { - nativeBinding = require('@databricks/databricks-sql-kernel-linux-arm64-musl') - } - } catch (e) { - loadError = e + try { + const binding = require('@databricks/databricks-sql-kernel-linux-arm-gnueabihf') + const bindingPackageVersion = require('@databricks/databricks-sql-kernel-linux-arm-gnueabihf/package.json').version + if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) } - } else { - localFileExisted = existsSync( - join(__dirname, 'index.linux-arm64-gnu.node') - ) - try { - if (localFileExisted) { - nativeBinding = require('./index.linux-arm64-gnu.node') - } else { - nativeBinding = require('@databricks/databricks-sql-kernel-linux-arm64-gnu') - } - } catch (e) { - loadError = e + return binding + } catch (e) { + loadErrors.push(e) + } + } + } else if (process.arch === 'loong64') { + if (isMusl()) { + try { + return require('./index.linux-loong64-musl.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@databricks/databricks-sql-kernel-linux-loong64-musl') + const bindingPackageVersion = require('@databricks/databricks-sql-kernel-linux-loong64-musl/package.json').version + if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) } + return binding + } catch (e) { + loadErrors.push(e) } - break - case 'arm': - if (isMusl()) { - localFileExisted = existsSync( - join(__dirname, 'index.linux-arm-musleabihf.node') - ) - try { - if (localFileExisted) { - nativeBinding = require('./index.linux-arm-musleabihf.node') - } else { - nativeBinding = require('@databricks/databricks-sql-kernel-linux-arm-musleabihf') - } - } catch (e) { - loadError = e + } else { + try { + return require('./index.linux-loong64-gnu.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@databricks/databricks-sql-kernel-linux-loong64-gnu') + const bindingPackageVersion = require('@databricks/databricks-sql-kernel-linux-loong64-gnu/package.json').version + if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) } - } else { - localFileExisted = existsSync( - join(__dirname, 'index.linux-arm-gnueabihf.node') - ) - try { - if (localFileExisted) { - nativeBinding = require('./index.linux-arm-gnueabihf.node') - } else { - nativeBinding = require('@databricks/databricks-sql-kernel-linux-arm-gnueabihf') - } - } catch (e) { - loadError = e + return binding + } catch (e) { + loadErrors.push(e) + } + } + } else if (process.arch === 'riscv64') { + if (isMusl()) { + try { + return require('./index.linux-riscv64-musl.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@databricks/databricks-sql-kernel-linux-riscv64-musl') + const bindingPackageVersion = require('@databricks/databricks-sql-kernel-linux-riscv64-musl/package.json').version + if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) } + return binding + } catch (e) { + loadErrors.push(e) } - break - case 'riscv64': - if (isMusl()) { - localFileExisted = existsSync( - join(__dirname, 'index.linux-riscv64-musl.node') - ) - try { - if (localFileExisted) { - nativeBinding = require('./index.linux-riscv64-musl.node') - } else { - nativeBinding = require('@databricks/databricks-sql-kernel-linux-riscv64-musl') - } - } catch (e) { - loadError = e + } else { + try { + return require('./index.linux-riscv64-gnu.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@databricks/databricks-sql-kernel-linux-riscv64-gnu') + const bindingPackageVersion = require('@databricks/databricks-sql-kernel-linux-riscv64-gnu/package.json').version + if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) } - } else { - localFileExisted = existsSync( - join(__dirname, 'index.linux-riscv64-gnu.node') - ) - try { - if (localFileExisted) { - nativeBinding = require('./index.linux-riscv64-gnu.node') - } else { - nativeBinding = require('@databricks/databricks-sql-kernel-linux-riscv64-gnu') - } - } catch (e) { - loadError = e + return binding + } catch (e) { + loadErrors.push(e) + } + } + } else if (process.arch === 'ppc64') { + try { + return require('./index.linux-ppc64-gnu.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@databricks/databricks-sql-kernel-linux-ppc64-gnu') + const bindingPackageVersion = require('@databricks/databricks-sql-kernel-linux-ppc64-gnu/package.json').version + if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else if (process.arch === 's390x') { + try { + return require('./index.linux-s390x-gnu.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@databricks/databricks-sql-kernel-linux-s390x-gnu') + const bindingPackageVersion = require('@databricks/databricks-sql-kernel-linux-s390x-gnu/package.json').version + if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else { + loadErrors.push(new Error(`Unsupported architecture on Linux: ${process.arch}`)) + } + } else if (process.platform === 'openharmony') { + if (process.arch === 'arm64') { + try { + return require('./index.openharmony-arm64.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@databricks/databricks-sql-kernel-openharmony-arm64') + const bindingPackageVersion = require('@databricks/databricks-sql-kernel-openharmony-arm64/package.json').version + if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else if (process.arch === 'x64') { + try { + return require('./index.openharmony-x64.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@databricks/databricks-sql-kernel-openharmony-x64') + const bindingPackageVersion = require('@databricks/databricks-sql-kernel-openharmony-x64/package.json').version + if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else if (process.arch === 'arm') { + try { + return require('./index.openharmony-arm.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@databricks/databricks-sql-kernel-openharmony-arm') + const bindingPackageVersion = require('@databricks/databricks-sql-kernel-openharmony-arm/package.json').version + if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else { + loadErrors.push(new Error(`Unsupported architecture on OpenHarmony: ${process.arch}`)) + } + } else { + loadErrors.push(new Error(`Unsupported OS: ${process.platform}, architecture: ${process.arch}`)) + } +} + +function createLoadErrorChain(errors) { + return errors.reduce((previous, current) => { + let message + try { + message = + current && typeof current.message === 'string' + ? current.message + : String(current) + } catch { + message = 'Unknown error' + } + const error = new Error(message) + error.cause = previous + return error + }, null) +} + +// NAPI_RS_FORCE_WASI is a tri-state flag: +// unset / any other value → native binding preferred, WASI is only a fallback +// 'true' → prefer WASI, but retain native as a lazy fallback +// 'error' → require WASI without initializing a native fallback +// Treating any non-empty string as truthy (the historical behavior) meant +// NAPI_RS_FORCE_WASI=false, NAPI_RS_FORCE_WASI=0, etc. inadvertently triggered +// the WASI path, causing ENOENT for packages shipped without a .wasi.cjs file. +// +// NAPI_RS_WASI_FLAVOR selects one exact generated flavor and implies strict +// WASI loading. It never crosses into another flavor or falls back to native. +const __napiWasiFlavors = ["wasm32-wasi"] +const __napiWasiFlavor = process.env.NAPI_RS_WASI_FLAVOR +const __napiWasiFlavorRequested = + typeof __napiWasiFlavor === 'string' && __napiWasiFlavor.length > 0 +if ( + __napiWasiFlavorRequested && + __napiWasiFlavors.indexOf(__napiWasiFlavor) === -1 +) { + throw new Error( + 'Unsupported WASI flavor "' + + __napiWasiFlavor + + '". Available flavors: ' + + __napiWasiFlavors.join(', '), + ) +} +const forceWasiError = process.env.NAPI_RS_FORCE_WASI === 'error' +const forceWasi = + process.env.NAPI_RS_FORCE_WASI === 'true' || + forceWasiError || + __napiWasiFlavorRequested + +if (!forceWasi) { + nativeBinding = requireNative() +} + +if (!nativeBinding || forceWasi) { + let wasiBinding = null + let wasiBindingLoaded = false + const wasiBindingErrors = [] + const __napiWasiResolveCandidate = (specifier, isPackage, localArtifacts) => { + try { + require.resolve(specifier) + } catch (resolveError) { + if (!resolveError || resolveError.code !== 'MODULE_NOT_FOUND') { + throw resolveError + } + if (isPackage) { + try { + require.resolve(specifier + '/package.json') + } catch (packageError) { + if (packageError && packageError.code === 'MODULE_NOT_FOUND') { + return resolveError } + // An exports restriction proves the package exists even when its + // package.json is not public. Preserve the root resolution failure. + throw resolveError } - break - case 's390x': - localFileExisted = existsSync( - join(__dirname, 'index.linux-s390x-gnu.node') - ) + // The package exists but its main/export target is broken. + throw resolveError + } + return resolveError + } + if (localArtifacts) { + let artifactError = null + for (let i = 0; i < localArtifacts.length; i++) { try { - if (localFileExisted) { - nativeBinding = require('./index.linux-s390x-gnu.node') - } else { - nativeBinding = require('@databricks/databricks-sql-kernel-linux-s390x-gnu') + require.resolve(localArtifacts[i]) + return null + } catch (resolveError) { + if (!resolveError || resolveError.code !== 'MODULE_NOT_FOUND') { + throw resolveError + } + artifactError = resolveError + } + } + return artifactError + } + return null + } + if (!wasiBindingLoaded && (!__napiWasiFlavorRequested || __napiWasiFlavor === "wasm32-wasi")) { + let candidateError = null + let candidateFailed = false + try { + candidateError = __napiWasiResolveCandidate('./index.wasi.cjs', false, ["./index.wasm32-wasi.debug.wasm","./index.wasm32-wasi.wasm"]) + candidateFailed = candidateError !== null + if (!candidateFailed) { + wasiBinding = require('./index.wasi.cjs') + nativeBinding = wasiBinding + wasiBindingLoaded = true + } + } catch (err) { + candidateError = err + candidateFailed = true + } + if (candidateFailed) { + wasiBindingErrors.push(candidateError) + loadErrors.push(candidateError) + } + } + if (!wasiBindingLoaded && (!__napiWasiFlavorRequested || __napiWasiFlavor === "wasm32-wasi")) { + let candidateError = null + let candidateFailed = false + try { + candidateError = __napiWasiResolveCandidate('@databricks/databricks-sql-kernel-wasm32-wasi', true, undefined) + candidateFailed = candidateError !== null + if (!candidateFailed) { + if (process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + const bindingPackageVersion = require('@databricks/databricks-sql-kernel-wasm32-wasi/package.json').version + if (bindingPackageVersion !== '1.4.0') { + throw new Error(`WASI binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) } - } catch (e) { - loadError = e } - break - default: - throw new Error(`Unsupported architecture on Linux: ${arch}`) + wasiBinding = require('@databricks/databricks-sql-kernel-wasm32-wasi') + nativeBinding = wasiBinding + wasiBindingLoaded = true + } + } catch (err) { + candidateError = err + candidateFailed = true } - break - default: - throw new Error(`Unsupported OS: ${platform}, architecture: ${arch}`) + if (candidateFailed) { + wasiBindingErrors.push(candidateError) + loadErrors.push(candidateError) + } + } + if ( + !wasiBindingLoaded && + forceWasi && + !forceWasiError && + !__napiWasiFlavorRequested + ) { + nativeBinding = requireNative() + } + if ((forceWasiError || __napiWasiFlavorRequested) && !wasiBindingLoaded) { + const error = new Error( + __napiWasiFlavorRequested + ? 'WASI binding for flavor "' + __napiWasiFlavor + '" not found' + : 'WASI binding not found and NAPI_RS_FORCE_WASI is set to error', + ) + error.cause = createLoadErrorChain(wasiBindingErrors) + throw error + } } if (!nativeBinding) { - if (loadError) { - throw loadError + if (loadErrors.length > 0) { + const error = new Error( + `Cannot find native binding. ` + + `npm has a bug related to optional dependencies (https://github.com/npm/cli/issues/4828). ` + + 'Please try `npm i` again after removing both package-lock.json and node_modules directory.', + ) + // assign instead of the `new Error(message, { cause })` options form, + // which Node < 16.9 silently ignores + error.cause = createLoadErrorChain(loadErrors) + throw error } throw new Error(`Failed to load native binding`) } -const { AsyncStatement, AsyncResultHandle, CancellableExecution, Connection, AuthMode, openSession, initKernelLogging, kernelLoggingStats, setKernelLogLevel, Statement, version } = nativeBinding - -module.exports.AsyncStatement = AsyncStatement -module.exports.AsyncResultHandle = AsyncResultHandle -module.exports.CancellableExecution = CancellableExecution -module.exports.Connection = Connection -module.exports.AuthMode = AuthMode -module.exports.openSession = openSession -module.exports.initKernelLogging = initKernelLogging -module.exports.kernelLoggingStats = kernelLoggingStats -module.exports.setKernelLogLevel = setKernelLogLevel -module.exports.Statement = Statement -module.exports.version = version +module.exports = nativeBinding +module.exports.AsyncResultHandle = nativeBinding.AsyncResultHandle +module.exports.AsyncStatement = nativeBinding.AsyncStatement +module.exports.CancellableExecution = nativeBinding.CancellableExecution +module.exports.Connection = nativeBinding.Connection +module.exports.Statement = nativeBinding.Statement +module.exports.AuthMode = nativeBinding.AuthMode +module.exports.initKernelLogging = nativeBinding.initKernelLogging +module.exports.kernelLoggingStats = nativeBinding.kernelLoggingStats +module.exports.openSession = nativeBinding.openSession +module.exports.setKernelLogLevel = nativeBinding.setKernelLogLevel +module.exports.version = nativeBinding.version diff --git a/napi/src/database.rs b/napi/src/database.rs index 4a8fbe3f..bcea5466 100644 --- a/napi/src/database.rs +++ b/napi/src/database.rs @@ -236,7 +236,7 @@ pub struct ConnectionOptions { /// representation. `true` (the default) requests Arrow /// `struct` values; `false` requests WKT / EWKT /// in Arrow UTF-8 values. The kernel normalizes both standard-warehouse - /// text and Reyden native Arrow results locally and never sends this choice + /// text and native Arrow results locally and never sends this choice /// to SEA. pub enable_geo_spatial_support: Option, /// Driver name reported in telemetry system configuration. Omitted ⇒ From bc39c7921acecd95e4eea0740becb883867a834b Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Wed, 11 Nov 2026 22:55:31 +0000 Subject: [PATCH 04/39] docs(napi): keep transfer declarations focused Signed-off-by: Aakash Saravanan --- napi/index.d.ts | 1805 +++++++++++++++++++++++------------------------ napi/index.js | 918 +++++++----------------- 2 files changed, 1152 insertions(+), 1571 deletions(-) diff --git a/napi/index.d.ts b/napi/index.d.ts index c4702bd6..8ffef883 100644 --- a/napi/index.d.ts +++ b/napi/index.d.ts @@ -1,811 +1,369 @@ -/* auto-generated by NAPI-RS */ +/* tslint:disable */ /* eslint-disable */ -/** - * Opaque result-fetch handle returned by - * `AsyncStatement.awaitResult()`. Wraps a kernel `ResultStream` - * directly; structurally analogous to the sync `Statement`'s - * fetch-side surface (`fetchNextBatch` / `schema` / - * `statementId`). - * - * `cancel()` / `close()` are not exposed: the parent - * `AsyncStatement` owns server-side lifecycle. A `close()` here - * would create dual-ownership of the same statement_id with - * inconsistent close semantics. Callers `close()` the parent - * `AsyncStatement` after they're done fetching. - * - * Schema is cached at construction so it survives the underlying - * stream being drained; mirrors the sync `Statement.schema()` - * post-close contract. - */ -export declare class AsyncResultHandle { - /** - * Server-issued statement id. Cached at construction; readable - * for log correlation. Matches the parent `AsyncStatement`'s - * `statementId`. - */ - get statementId(): string - /** - * Pull the next batch of results. Returns `null` when the - * stream is exhausted. The returned `ArrowBatch.ipcBytes` is a - * complete Arrow IPC stream (schema header + 1 record-batch - * message), suitable for handing to `apache-arrow`'s - * `RecordBatchReader`. Byte-identical to the sync - * `Statement.fetchNextBatch()` payload for the same query. - */ - fetchNextBatch(): Promise - /** - * Result schema as an Arrow IPC payload (schema header only, - * no record-batch message). Available before any batches have - * been fetched. Sync because the body has no `.await` — - * `encode_ipc_stream` is pure CPU work over the cached - * `Arc`. - */ - schema(): ArrowSchema -} + +/* auto-generated by NAPI-RS */ /** - * Opaque async-statement handle. + * Per-statement options for `Connection.executeStatement`. * - * Returned by `Connection.submitStatement(...)` after the kernel - * `Statement::submit()` returns (server sent `wait_timeout=0s`, so - * the response carries a `statement_id` but the statement is still - * `Pending`/`Running`). JS drives polling via `status()` / - * `awaitResult()`. + * Mirrors the kernel `StatementSpec` knobs that are safe to thread + * through napi without a kernel-side change. Today this covers: + * - `statementConf` — per-statement Spark conf overlay + * (`StatementSpec.statement_conf` → SEA `parameters` / + * Thrift `confOverlay`) + * - `queryTags` — convenience wrapper over `statementConf` with + * key `query_tags`; serialised to the same comma-separated + * `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. * - * Concurrency shape: `status()`, `awaitResult()`, and `close()` take - * `inner.lock()` and hold the guard across the kernel `.await` (tokio - * `Mutex` is FIFO), so `status()` / `close()` queue behind any - * in-flight `awaitResult()` until it returns naturally. `cancel()` is - * the deliberate exception: it does **not** touch `inner` — it fires - * through the detached `AsyncStatementCanceller` (session + - * statement_id, captured at construction), so an explicit - * `stmt.cancel()` interrupts an in-flight `awaitResult()` instead of - * queueing behind it. The server-side cancel flips the statement - * terminal, which the parked `awaitResult()` poll loop observes - * (`Cancelled`) and returns on. The kernel's `AwaitResultCancelGuard` - * still covers the drop-cancel case (Promise.race / timeout) - * independently — see module docs. + * `rowLimit` (SEA `row_limit`) is exposed here and threaded onto the kernel + * `StatementSpec`. `positionalParams` (`?`) and `namedParams` (`:name`) + * carry bound query parameters, decoded via `params::parse_typed_value`. + * `rawParams` forwards pre-marshalled SEA parameters unchanged. + * (There is no `queryTimeoutSecs`: it abused the SEA `wait_timeout` inline-hold + * window and was removed — a real per-statement timeout is `STATEMENT_TIMEOUT`.) + * + * **Tag-order caveat (M4 parity note).** The napi `queryTags` field + * is a Rust `HashMap` whose iteration order is + * non-deterministic, so the serialised `query_tags` value may have + * a different key order than Thrift's `serializeQueryTags` (which + * iterates `Object.keys(...)` in insertion order) for the same + * input. The SEA server is order-insensitive on conf values, so + * the two are functionally equivalent. If a caller needs + * byte-identical Thrift parity, the JS adapter pre-serialises via + * `serializeQueryTags` and writes the result into + * `statementConf["query_tags"]` directly — see + * `KernelSessionBackend.executeStatement` in the NodeJS driver. This + * path is the one the production code uses. */ -export declare class AsyncStatement { +export interface ExecuteOptions { + /** Omit to handle instructions in the caller; an empty list denies local file access. */ + stagingAllowedLocalPaths?: string[] /** - * Server-issued statement id. Cached at construction; readable - * even after `close()` so JS-side log lines can correlate - * against kernel / server logs which key on the same id. + * Per-statement Spark conf overlay. Merged on top of the + * session-level `sessionConf` at execute time; this map wins + * on key collisions. Unknown keys are rejected by the server. */ - get statementId(): string + statementConf?: Record /** - * One-shot status check. Returns a string enum matching the - * kernel `StatementStatus` shape: - * `'Pending' | 'Running' | 'Succeeded' | 'Failed' | - * 'Cancelled' | 'Closed' | 'Unknown'`. (`'Unknown'` is the - * `#[non_exhaustive]` forward-compat catch-all that - * `StatementStatus::as_str` can return — consumers switching on - * the state must handle it.) Returns - * `KernelError(InvalidStatementHandle)` if the statement has - * been explicitly `close()`d. + * Query tags as key→value pairs. Serialised to a comma- + * separated `key:value` string (backslash-escaping `\`, `:`, + * `,`) and placed into `statementConf["query_tags"]`, matching + * NodeJS Thrift's `serializeQueryTags` wire shape. Passing + * both `queryTags` AND a `query_tags` key in `statementConf` + * raises `InvalidArgument` — the caller's intent is ambiguous + * so we refuse to silently pick one over the other. * - * The `Failed` variant collapses to the string `'Failed'` on - * the JS side; the underlying error envelope (sql_state / - * error_code / query_id) is surfaced by `awaitResult()`'s - * rejection, which is where callers actually need the typed - * error. `status()` is intended for polling progress UIs - * that only need the state name. + * A **`null`** value emits a **bare key** (no colon) — e.g. + * `{ production: null }` → `"production"` — matching the + * connectors' `key`-only tag form. + * + * See the struct-level "Tag-order caveat" for the + * HashMap-iteration-order vs `Object.keys`-iteration-order + * divergence and the byte-identical-Thrift-parity workaround. */ - status(): Promise - /** Rows modified by the statement (UPDATE / INSERT / DELETE / MERGE). */ - numModifiedRows(): Promise + queryTags?: Record /** - * Server-supplied user-facing message (may contain SQL fragments — - * redact before centralised logging). + * Server-side cap on the number of rows this statement returns + * (SEA `row_limit`), independent of any SQL `LIMIT`. Maps to + * `StatementSpec.row_limit`. Omitted ⇒ no driver-imposed cap. */ - displayMessage(): Promise - /** Server-supplied diagnostic detail. */ - diagnosticInfo(): Promise - /** Server-supplied structured error detail (JSON), when enabled. */ - errorDetailsJson(): Promise + rowLimit?: number /** - * Block until the server reaches a terminal state, then return - * an `AsyncResultHandle` that wraps the materialised result - * stream. The handle exposes `fetchNextBatch()` / `schema()` - * for consuming the result, plus `statementId` for log - * correlation. - * - * Drop-cancel safety: kernel `await_result` installs - * `AwaitResultCancelGuard` which fires a fire-and-forget - * `cancel_statement` if the future is dropped mid-poll - * (timeout, tokio::select! loser, JS-side `Promise.race` - * loser). The `util::guarded` `catch_unwind` here covers the - * V8-panic-across-boundary case on top. Returns - * `KernelError(InvalidStatementHandle)` if the statement has - * been explicitly `close()`d. + * 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 + * string-encoded literal or `null` for SQL NULL. Mirrors + * `StatementSpec::positional_params`; decoded via [`parse_typed_value`]. */ - awaitResult(): Promise + positionalParams?: Array /** - * Server-side cancel. Returns - * `KernelError(InvalidStatementHandle)` if the statement has - * been explicitly `close()`d. Idempotent against a server - * that already reached a terminal state — the kernel's - * `cancel_statement` is a no-op there. - * - * **Lock-free by design.** Unlike `status()` / `awaitResult()` / - * `close()`, this does not take `inner.lock()` — it fires through - * the detached `AsyncStatementCanceller` captured at construction. - * That lets `stmt.cancel()` interrupt an in-flight `awaitResult()` - * (which holds the mutex for the whole poll) instead of queueing - * behind it: the server-side cancel flips the statement terminal, - * the parked `awaitResult()` poll loop observes `Cancelled` and - * returns. The closed-state check reads a lock-free flag so a - * cancel after an explicit `close()` still surfaces - * `InvalidStatementHandle`. + * Named parameters (`:name` placeholders). Each carries its `name` + * alongside the `{ sqlType, value? }` pair. Mapped to a kernel + * `TypedValue` via the same [`parse_typed_value`] codec and bound with + * `StatementSpec::param_named`. Named is the SEA-spec-required public + * param form (`StatementParameter.name` is `openapi_required`); + * positional is the documented-undocumented variant. The two are + * mutually exclusive at the SQL level (`?` vs `:name`). */ - cancel(): Promise + namedParams?: Array /** - * Explicit close. Idempotent — a second call on an - * already-closed handle returns `Ok(())`. On `Err`, the napi - * inner is already `None`, so a JS-side retry sees the - * closed-handle short-circuit and returns `Ok(())` without - * re-attempting the wire call. The kernel's own `Drop` - * fire-and-forget retry runs once in the background. + * Pre-marshalled parameters passed through `StatementSpec::param_raw`. + * Omit `name` for positional values. Raw parameters cannot be mixed with + * typed parameters or combine named and positional markers. */ - close(): Promise + rawParams?: Array } - /** - * Handle returned by `Connection.executeStatementCancellable`. Owns the - * built-but-not-yet-executed kernel `Statement` plus a detached - * [`StatementCanceller`] captured before dispatch, so JS can fire a - * server-side cancel while the blocking `result()` is in flight. + * A named bound parameter — a [`TypedValueInput`] plus its `:name`. Kept a + * distinct napi object (rather than an optional `name` on `TypedValueInput`) + * so the positional surface stays a clean ordered list with no name field. + */ +export interface NamedTypedValueInput { + name: string + sqlType: string + value?: string +} +/** + * Authentication mode selector crossing the napi boundary. The string + * literals are what napi-rs emits from this `#[napi(string_enum)]` — the + * NodeJS SEA adapter (`KernelAuth`) matches them verbatim (`'Pat'`, + * `'OAuthM2m'`, `'OAuthU2m'`, `'AzureSpM2m'`). * - * `pending` is `Arc>>` so `result()` can - * `.take()` the statement (the kernel `execute()` borrows it `&mut`, - * then it moves into the produced `Statement` wrapper to keep its - * `ValidityFlag` set — see `statement.rs`). A second `result()` call - * after the first resolved surfaces `InvalidStatementHandle`. + * Mirrors the kernel [`AuthConfig`] variants this binding supports. + * `OAuthFederation` / `External` are intentionally not exposed yet — the + * kernel marks federation as not-yet-implemented and `External` is a + * Rust-trait escape hatch with no JS-callback bridge. */ -export declare class CancellableExecution { +export const enum AuthMode { + /** Personal access token (`token`). */ + Pat = 'Pat', + /** OAuth 2.0 machine-to-machine — `oauthClientId` + `oauthClientSecret`. */ + OAuthM2m = 'OAuthM2m', /** - * The server-issued statement id this execution targets, if the - * server has issued one yet (`null` before the initial submit - * round-trip publishes it mid-`result()`). Useful for log - * correlation while the blocking drive is in flight. + * OAuth 2.0 machine-to-machine with a JWT private-key client + * assertion — `oauthClientId` + `jwtKeyFile` + `jwtKid`. */ - get statementId(): string | null + OAuthM2mJwt = 'OAuthM2mJwt', /** - * Drive the blocking `execute()` and resolve to a `Statement` - * (identical to what `executeStatement` returns) once the kernel - * reaches a terminal state and the result stream is ready. - * - * Consumes the pending statement: a second `result()` call returns - * `KernelError(InvalidStatementHandle)`. The future is - * drop-cancel-safe — the kernel's per-execute `MidExecuteCancelState` - * guard fires a fire-and-forget `cancel_statement` if this future is - * dropped mid-flight (`Promise.race` / timeout loser), independently - * of an explicit `cancel()`. - * - * On a server-side cancel the kernel's blocking `execute()` currently - * surfaces `InvalidArgument` (a known kernel quirk — the async path - * returns `Cancelled`). When this handle's `cancel()` actually dispatched a - * server-side cancel, we normalise that into `Cancelled` here so JS callers - * can rely on a single cancelled-status code regardless of execution path. - * - * Three outcomes can race the blocking drive: (1) a natural terminal state - * → `Ok` or the genuine error; (2) an explicit `cancel()` that dispatched a - * server cancel → this `result()` rejects with a `Cancelled`-coded error - * (the normalisation above); (3) the future being **dropped** mid-flight - * (`Promise.race`/timeout loser) → the kernel's `MidExecuteCancelState` - * drop-guard fires a fire-and-forget `cancel_statement`, but there is no - * `result()` left to observe a code. Only (2) yields a `Cancelled` error. + * OAuth 2.0 user-to-machine (browser flow) — optional `oauthClientId` + * + `oauthRedirectPort`. */ - result(): Promise + OAuthU2m = 'OAuthU2m', /** - * Server-side cancel of the in-flight statement. - * - * Lock-free: fires the detached `StatementCanceller` captured at - * construction rather than taking the mutex `result()` holds, so it - * interrupts a still-running blocking `result()` instead of queueing - * behind it. No-op (returns `Ok`) if `result()` already finished - * successfully, or if no statement id has been observed yet (query still - * in its initial submit round-trip), and idempotent against a server - * already in a terminal state. + * Azure Entra service-principal M2M — `azureClientId` + + * `azureClientSecret` (+ optional `azureTenantId` / + * `azureWorkspaceResourceId`). The kernel builds the Entra token + * endpoint + `.default` scope, auto-discovers the tenant from the + * workspace when `azureTenantId` is omitted, and — when + * `azureWorkspaceResourceId` is set — additionally sends the SP + * management token for an RBAC-only service principal. */ - cancel(): Promise + AzureSpM2m = 'AzureSpM2m' } - /** - * Opaque connection handle wrapping a kernel `Session`. + * A single extra HTTP header as an explicit `{ name, value }` pair. * - * `inner` is `Arc>>` so: - * - the Drop impl can clone the `Arc` and `.take()` the session on a - * background tokio task without holding `&mut self` (which Drop is - * forbidden from doing across an `await`), - * - `close()` can `.take()` the session to consume it for the kernel's - * move-by-value `Session::close(self)` signature. + * An ordered list of these (`ConnectionOptions.custom_headers`) mirrors + * the kernel core's `Vec<(String, String)>` and the pyo3 binding's + * `http_headers`: order is preserved and duplicate `name`s are allowed. + * A struct (rather than a raw `[name, value]` tuple) because napi-rs + * does not marshal Rust tuples through `#[napi(object)]` fields; the + * struct is the idiomatic, self-documenting equivalent and maps to a JS + * `{ name: string, value: string }`. + */ +export interface HeaderEntry { + name: string + value: string +} +/** + * Programmatic HTTP/HTTPS proxy configuration, mirroring the kernel's + * internal [`ProxyConfig`]. Supplied as a structured object rather than a + * flattened URL so credentials never have to be percent-encoded into the URL + * and the bypass-host list can be expressed. * - * **Concurrency shape** — both `executeStatement` and - * `submitStatement` build the kernel `Statement` under `inner.lock()` - * and then RELEASE the guard before the wire call - * (`stmt.execute().await` / `stmt.submit().await`). `Session::statement()` - * is `&self`-callable and only clones the session's internal `Arc`, so - * the built statement is independent of the guard. Concurrent - * `Promise.all([executeStatement(q1), submitStatement(q2)])` therefore - * serialise only for the microsecond statement-build, not the network - * round-trip, and `close()` never blocks behind an in-flight execute or - * submit. See - * `sea-workflow/jira-candidates/2026-05-24-napi-cancel-during-fetch.md`. + * - `url` — proxy endpoint, e.g. `"http://proxy.corp.example.com:8080"`. Must + * use the `http://` or `https://` scheme. + * - `username` / `password` — optional proxy basic-auth, applied via + * `reqwest`'s `Proxy::basic_auth` (not embedded in the URL). + * - `bypassHosts` — optional comma-separated host/domain list that should + * bypass the proxy (e.g. `"localhost,*.internal.corp"`). */ -export declare class Connection { +export interface ProxyInput { + url: string + username?: string + password?: string + bypassHosts?: string +} +/** + * JS-visible options for opening a Databricks SQL session. + * + * Authentication is selected by `authMode` (default [`AuthMode::Pat`]): + * - `Pat` — `token` required. + * - `OAuthM2m` — `oauthClientId` + `oauthClientSecret` required. + * - `OAuthU2m` — `oauthClientId` / `oauthRedirectPort` optional + * (defaults to the `databricks-sql-connector` client on port 8030). + * - `AzureSpM2m` — `azureClientId` + `azureClientSecret` required + * (+ optional `azureTenantId` / `azureWorkspaceResourceId`). + * + * Catalog / schema / sessionConf are applied once at session creation + * and remain in effect for every statement run on the resulting + * `Connection`. The SEA wire protocol carries them on + * `CreateSession`, not on `ExecuteStatement` — so there is no + * per-statement override path on this binding. + */ +export interface ConnectionOptions { /** - * Server-issued session id. Cached at construction; readable - * even after `close()` so JS-side log lines can correlate - * against kernel / server logs which key on the same id. + * Workspace host, e.g. `adb-…azuredatabricks.net`. The kernel + * normalises this — bare hostnames get `https://` prepended. */ - get sessionId(): string + hostName: string /** - * Execute a SQL statement and return a Statement handle that - * streams batches via `fetchNextBatch()`. - * - * Catalog / schema / sessionConf are session-level - * (`openSession`). Per-statement options on `ExecuteOptions`: - * - `statementConf` — per-statement Spark conf overlay - * - `queryTags` — serialised to a comma-separated `key:value` - * string and placed in `statement_conf["query_tags"]`, - * matching NodeJS Thrift's `serializeQueryTags` wire shape - * - * `options` is omitted/`None` for the no-options path; passing - * `{ statementConf: {} }` (an empty map) is treated the same as - * omission to keep the wire shape stable for the common case. + * JDBC-style HTTP path, e.g. `/sql/1.0/warehouses/abc123`. The + * kernel parses out the warehouse id. */ - executeStatement(sql: string, options?: ExecuteOptions | undefined | null): Promise + httpPath: string /** - * directResults execute — the Thrift/JDBC model. Sends ExecuteStatement - * with no `wait_timeout` field (server applies its ~10s default inline wait - * and auto-closes on success) and returns WITHOUT polling past it: - * - * - a **`Statement`** (left arm) when the query finished within the inline - * wait — terminal, result ready inline, `close()` is a clean release; - * - an **`AsyncStatement`** (right arm) when it did not — a poll/cancel - * handle the caller drives (`status()` / `awaitResult()` / `cancel()`). - * - * JS distinguishes the arms by feature-detecting `awaitResult` (present - * only on `AsyncStatement`). This is the path that gives mid-run cancel for - * long queries WITHOUT the eager-handle / close-drives workaround: the - * returned handle always corresponds to a server-owned statement. - * - * **Load-bearing contract:** the kernel's `DirectStatement::{Completed, - * Running}` discriminant cannot ride on these opaque `#[napi]` classes, so - * consumers MUST feature-detect via `awaitResult` (the only member unique to - * `AsyncStatement`). `Statement` (the Completed arm) MUST NOT gain an - * `awaitResult` member, or every consumer silently misroutes. The pyo3 - * binding makes the same `await_result`-probe assumption. + * Authentication mode. Omitted ⇒ [`AuthMode::Pat`] (back-compat: + * existing PAT callers pass only `token`). */ - executeStatementDirect(sql: string, options?: ExecuteOptions | undefined | null): Promise + authMode?: AuthMode /** - * Execute a SQL statement on the blocking (sync) path, but return a - * `CancellableExecution` handle so a concurrent JS task can cancel - * the query *while it is still running server-side*. - * - * `executeStatement` builds the kernel `Statement`, awaits the - * blocking `execute()`, and only then hands JS a `Statement` — so a - * query that runs for several seconds is uncancellable from JS on - * that path (there is no handle until the blocking call resolves). - * This method instead builds the statement, captures a detached - * `StatementCanceller` **before** dispatching `execute()`, and hands - * JS a `CancellableExecution` immediately. The caller drives the - * blocking execution via `result()` (resolves to the same - * `Statement` `executeStatement` returns) and can fire `cancel()` - * concurrently to interrupt a still-running query mid-COMPUTE. - * - * Option semantics are identical to `executeStatement`. - * Mirrors the pyo3 `Statement.canceller()` / `Statement.execute()` - * split (PR #121): obtain the canceller before the blocking drive. + * Personal access token. Required (and non-empty) for + * [`AuthMode::Pat`]; ignored otherwise. */ - executeStatementCancellable(sql: string, options?: ExecuteOptions | undefined | null): Promise + token?: string /** - * Submit a SQL statement and return immediately with an - * `AsyncStatement` handle, without blocking until the query - * finishes. The kernel's `Statement::submit()` sends - * `wait_timeout=0s`, so the server responds as soon as it has a - * `statement_id` (state `Pending`/`Running`); JS drives polling - * via `AsyncStatement.status()` and materialises results with - * `AsyncStatement.awaitResult()`. - * - * This is the async-execution path the Thrift backend always - * 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`. - * 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 - * differs from `executeStatement`. + * OAuth client id. Required for [`AuthMode::OAuthM2m`]; optional for + * [`AuthMode::OAuthU2m`] (defaults to `databricks-sql-connector`). */ - submitStatement(sql: string, options?: ExecuteOptions | undefined | null): Promise + oauthClientId?: string + /** OAuth client secret. Required for [`AuthMode::OAuthM2m`]. */ + oauthClientSecret?: string /** - * Explicit close. Awaits the server-side `DeleteSession` so the - * JS caller can observe failures (auth revoked mid-session, - * warehouse stopped, network error). Idempotent — a second call - * on an already-closed connection returns `Ok`. - * - * **Errors are terminal from the JS side.** The kernel session - * handle is consumed (`take()`) BEFORE the wire `DeleteSession` - * runs, because `Session::close` takes `self` by value. On `Err`, - * the napi `inner` is already `None`, so a JS-side retry sees a - * closed connection and returns `Ok(())` without re-attempting - * the wire call. The kernel's own `Drop` fire-and-forget retry - * runs once in the background — the JS caller can log the error - * but cannot drive a retry. If you need retry-on-failure - * semantics for `DeleteSession`, layer them above this method. + * Localhost callback port for the [`AuthMode::OAuthU2m`] browser + * flow. Omitted ⇒ kernel default (8030). */ - close(): Promise + oauthRedirectPort?: number /** - * All catalogs visible to the session. - * - * JDBC `getCatalogs` shape: `TABLE_CAT: Utf8`. + * OAuth scopes override (M2M / U2M). Omitted ⇒ kernel defaults + * (`["all-apis"]` for M2M; `["sql", "offline_access"]` for U2M). */ - listCatalogs(): Promise + oauthScopes?: Array /** - * Schemas filtered by catalog (exact) and schema name pattern. An empty - * catalog matches nothing; non-empty catalogs remain exact identifiers. - * - * JDBC `getSchemas` shape: `TABLE_SCHEM, TABLE_CATALOG`. + * OAuth token endpoint override. When omitted the kernel discovers the + * endpoint via the workspace's OIDC configuration. Set it to point the + * client-credentials / JWT client-assertion grant at the workspace's + * configured IdP token endpoint (e.g. Entra ID for Azure Databricks), + * which is required when that IdP — not Databricks-native OIDC — is the + * authority for [`AuthMode::OAuthM2m`] / [`AuthMode::OAuthM2mJwt`]. */ - listSchemas(catalog?: string | undefined | null, schemaPattern?: string | undefined | null): Promise + tokenUrl?: string /** - * Tables filtered by catalog (**pattern**), schema (pattern), table - * (pattern). - * - * The catalog is an ODBC/JDBC LIKE pattern (`%` / `_`), matching - * Thrift `getTables`: a wildcard catalog matches multiple catalogs; - * a literal name (or an escaped `\_` / `\%`) takes the fast exact - * path. `undefined`/omitted catalog means "all catalogs", while an - * **empty string** means "match nothing" (zero rows) — pass - * `undefined`, not `""`, for all catalogs. The catalog pattern is - * validated (whitespace-only / NUL / >255 bytes are rejected with an - * error). - * - * JDBC `getTables` shape: 10 columns. `tableTypes`, when provided, - * filters rows by `TABLE_TYPE` kernel-side. - * - * `tableTypes` is an advisory filter. Databricks `SHOW TABLES` does - * NOT honour the table-type filter server-side; the kernel applies - * it client-side after the result returns. Callers expecting - * server-side rejection of off-type tables should not rely on this. + * U2M on-disk token-cache control (kernel path). Omitted ⇒ the kernel + * default (cache enabled, encrypted under a machine-local key, survives + * restarts). `false` disables on-disk persistence (re-login each fresh + * process); `true` keeps it enabled. Applies to [`AuthMode::OAuthU2m`]. */ - listTables(catalog?: string | undefined | null, schemaPattern?: string | undefined | null, tablePattern?: string | undefined | null, tableTypes?: Array | undefined | null): Promise + tokenCacheEnabled?: boolean /** - * Columns of tables matching the filter. An empty catalog matches - * nothing; non-empty catalogs remain exact identifiers. - * - * JDBC `getColumns` shape: 23 columns. + * Optional passphrase for the U2M on-disk token cache (AES-256 key). + * Omitted/blank ⇒ a machine-local derived key. Supplying one is stronger. + * A passphrase with no explicit `tokenCacheEnabled` implies enabled. + * Applies to [`AuthMode::OAuthU2m`]. */ - listColumns(catalog?: string | undefined | null, schemaPattern?: string | undefined | null, tablePattern?: string | undefined | null, columnPattern?: string | undefined | null): Promise + tokenCachePassphrase?: string /** - * Functions visible to the session. An empty `catalog` is forwarded to - * SEA for native `GetFunctions`; `schemaPattern` and `functionPattern` are SQL LIKE. + * Path to the PEM private-key file. Required for + * [`AuthMode::OAuthM2mJwt`]. */ - listFunctions(catalog?: string | undefined | null, schemaPattern?: string | undefined | null, functionPattern?: string | undefined | null): Promise + jwtKeyFile?: string + /** JWT key id (`kid`). Required for [`AuthMode::OAuthM2mJwt`]. */ + jwtKid?: string /** - * Procedures visible to the session. `catalog` is exact; - * `schemaPattern` and `procedurePattern` are SQL LIKE. + * Passphrase for an encrypted PKCS#8 key. Optional for + * [`AuthMode::OAuthM2mJwt`] (omit for an unencrypted key). */ - listProcedures(catalog?: string | undefined | null, schemaPattern?: string | undefined | null, procedurePattern?: string | undefined | null): Promise + jwtPassphrase?: string /** - * All table types (`TABLE`, `VIEW`, `SYSTEM TABLE`, …). - * No wire call — static in-memory result. + * JWT signing algorithm (`RS256`/`384`/`512`, `PS256`/`384`/`512`, + * `ES256`, `ES384`). Optional for [`AuthMode::OAuthM2mJwt`] + * (omitted ⇒ kernel default `RS256`). */ - listTableTypes(): Promise + jwtAlgorithm?: string /** - * SQL data types supported by the workspace. - * No wire call — static in-memory result. + * SP-wide Workload Identity Federation client id used during mandatory + * token exchange. Omitted selects BYOT / account-wide WIF. */ - listTypeInfo(): Promise + identityFederationClientId?: string /** - * Primary keys for the given table. All three identifiers are - * exact — ODBC `SQLPrimaryKeys` does not support patterns. + * Azure Entra app-registration client id. Required for + * [`AuthMode::AzureSpM2m`]; ignored otherwise. */ - getPrimaryKeys(catalog: string | undefined | null, schema: string | undefined | null, table: string): Promise + azureClientId?: string /** - * Foreign-key relationships. The parent side is optional. When the - * foreign table is omitted, returns an empty result without issuing a - * server statement. When it is provided, its catalog and schema are - * required. All identifiers are exact — no LIKE patterns. + * Azure Entra app-registration client secret. Required for + * [`AuthMode::AzureSpM2m`]. */ - getCrossReference(parentCatalog?: string | undefined | null, parentSchema?: string | undefined | null, parentTable?: string | undefined | null, foreignCatalog?: string | undefined | null, foreignSchema?: string | undefined | null, foreignTable?: string | undefined | null): Promise -} - -/** - * Opaque executed-statement handle. - * - * **Current concurrency shape** — every method takes `inner.lock()` - * and holds the guard across the kernel `.await`. tokio `Mutex` is - * FIFO, so cancel/close queue behind any in-flight `fetchNextBatch` - * until it returns naturally. This is a known limitation that exists - * because the napi shape has not yet been split into an - * `Arc` (for cancel/close, which the - * kernel exposes as `&self`-callable) plus a `Mutex>` only - * for the borrowed-mut fetch path. The lock-shape refactor needs a - * small kernel-side accessor and lands in a follow-up PR — see - * `sea-workflow/jira-candidates/2026-05-24-napi-cancel-during-fetch.md`. - * - * `schema` and `statement_id` are cached at construction so they - * survive `close()` — JS callers building error reports against a - * disposed statement can still read them. - */ -export declare class Statement { + azureClientSecret?: string /** - * Server-issued statement id. Cached at construction; readable - * even after `close()` so JS-side log lines can correlate against - * kernel / server logs which key on the same id. + * Azure Entra tenant id. Optional for [`AuthMode::AzureSpM2m`]; + * omitted ⇒ the kernel auto-discovers it from the workspace's + * `/aad/auth` redirect (matching the Thrift connector). */ - get statementId(): string + azureTenantId?: string /** - * Number of rows modified by the statement (UPDATE / INSERT / - * DELETE / MERGE). `null` for SELECT and on warehouses that don't - * surface the counter. Mirrors Thrift's - * `TGetOperationStatusResp.numModifiedRows`. + * Azure workspace ARM resource id. Optional for [`AuthMode::AzureSpM2m`]; + * when set the kernel also sends the SP management token + * (`X-Databricks-Azure-SP-Management-Token`) + the + * `X-Databricks-Azure-Workspace-Resource-Id` header, so a service + * principal with an Azure RBAC role but no workspace membership can + * authenticate. Omitted ⇒ the data token authenticates alone. */ - numModifiedRows(): Promise + azureWorkspaceResourceId?: string /** - * Server-supplied user-facing message. Mirrors Thrift's - * `TGetOperationStatusResp.displayMessage`. **PII / sensitive- - * data note:** may contain SQL fragments or parameter values — - * redact before centralised logging. - * - * Populated on `Succeeded` / `Closed` paths (incl. an empty `Closed`). - * On terminal-error states (`Failed` / `Cancelled`) the kernel returns - * an Error instead of a `Statement`, and the same field rides on the JS - * Error envelope under the same `displayMessage` key. + * Default catalog for statements executed on this session. + * Routed through the kernel's `DefaultOpts` and onto the SEA + * `CreateSession.catalog` wire field. */ - displayMessage(): Promise + catalog?: string /** - * Server-supplied diagnostic detail — multi-line operator / - * stack context. Mirrors Thrift's - * `TGetOperationStatusResp.diagnosticInfo`. For support surfaces, - * not user-facing. Same reachability + PII caveats as - * `displayMessage`. + * Default schema for statements executed on this session. + * Routed through the kernel's `DefaultOpts` and onto the SEA + * `CreateSession.schema` wire field. */ - diagnosticInfo(): Promise + schema?: string /** - * Server-supplied JSON blob with extended error details. Mirrors - * Thrift's `TGetOperationStatusResp.errorDetailsJson`. - * Pass-through string — JS callers parse with `JSON.parse` if - * they need structured access. - * - * **Server-side gating:** populated only when the workspace has - * `spark.databricks.sql.errorDetailsJson.enabled = true` on the - * underlying SQL cluster. The flag is internal-only / default- - * false in the Databricks runtime, so for most JS callers this - * will return `null`. Admin-enabled workspaces return content - * shaped like `{"errorClass": "...", "messageTemplate": "..."}`. - * - * **Unbounded:** when populated, server can return a multi-MB - * blob; size before logging. + * Server-bound session conf (Spark conf, `ANSI_MODE`, `TIMEZONE`, + * query-tag presets, …). Forwarded verbatim to SEA + * `session_confs`. Unknown keys are rejected server-side. */ - errorDetailsJson(): Promise + sessionConf?: Record /** - * Pull the next batch of results. Returns `null` when the stream - * is exhausted. The returned `ArrowBatch.ipcBytes` is a complete - * Arrow IPC stream (schema header + 1 record-batch message) - * suitable for handing to `apache-arrow`'s `RecordBatchReader`. - * - * On `Err`, the stream is in an unspecified state — call - * `close()` and discard the `Statement`. Subsequent - * `fetchNextBatch()` calls after an error are not guaranteed to - * succeed or fail consistently. + * Select whether `GEOMETRY` / `GEOGRAPHY` results use their native Arrow + * representation. `true` (the default) requests Arrow + * `struct` values; `false` requests WKT / EWKT + * in Arrow UTF-8 values. The kernel normalizes both standard-warehouse + * text and Reyden native Arrow results locally and never sends this choice + * to SEA. */ - fetchNextBatch(): Promise + enableGeoSpatialSupport?: boolean /** - * Result schema as an Arrow IPC payload (schema header only, no - * record-batch message). Available before any batches have been - * fetched, and remains available after `close()` — the kernel - * materialises the schema eagerly so JS callers can build error - * reports against a disposed statement. - * - * Sync because the body has no `.await` — `encode_ipc_stream` is - * pure CPU work over an `Arc` already cached on the - * wrapper. Mirrors `pyo3/src/statement.rs::arrow_schema` (sync). - * napi-rs converts a panic in a sync `#[napi]` entry point into a - * thrown JS error via its own macro-expanded boundary, so the - * `util::guarded` `catch_unwind` wrapper that the `async fn` - * entry points use is not required for this method. + * Driver name reported in telemetry system configuration. Omitted ⇒ + * kernel default. */ - schema(): ArrowSchema + driverName?: string /** - * Server-side cancel. - * - * For executed statements: short-circuits to `Ok(())` if - * `fetchNextBatch` has already returned `null` (stream - * naturally exhausted) — matches the JDBC `Statement.cancel()` - * no-op-after-completion contract, so JS callers can fire cancel - * defensively without distinguishing "real cancel" from "raced - * with natural completion." - * - * For metadata streams: no-op (the kernel has no in-flight - * cancellation surface for metadata calls today). - * - * Returns `KernelError(InvalidStatementHandle)` if the statement - * has been explicitly `close()`d. + * Driver version reported in telemetry system configuration. Omitted ⇒ + * kernel default. */ - cancel(): Promise + driverVersion?: string /** - * Explicit close. - * - * For executed statements: awaits the server-side `CloseStatement` - * so the JS caller can observe failures (auth revoked mid-session, - * network error, server-side error). Idempotent — a second call - * on an already-closed statement returns `Ok`. - * - * **Errors are terminal from the JS side.** The kernel executed - * handle is taken out of `inner` BEFORE the wire `CloseStatement` - * runs (so `Drop` knows there's nothing left to clean up). On - * `Err`, the napi `inner` is already `None`, so a JS-side retry - * sees a closed statement and returns `Ok(())` without re- - * attempting the wire call. The kernel-level `ExecutedStatement` - * has been consumed at that point and the value is dropped on - * the way out of the closure — the kernel's `ExecutedStatement:: - * Drop` then fires-and-forgets a single retry on the captured - * runtime. The JS caller can log the error but cannot drive a - * further retry. If you need retry-on-failure semantics for - * `CloseStatement`, layer them above this method. - * - * For metadata streams: drops the stream (no server round-trip - * needed — metadata results have no in-flight server-side - * resource to release). + * Runtime name reported in telemetry system configuration. Omitted ⇒ + * kernel default. */ - close(): Promise -} - -/** - * A single Arrow IPC stream payload encoding one record batch (plus - * the schema header so the JS-side reader is stateless). - */ -export interface ArrowBatch { + runtimeName?: string /** - * Arrow IPC stream payload (schema header + 1 record-batch - * message). Decode with `apache-arrow`'s `RecordBatchReader`. + * Runtime version reported in telemetry system configuration. Omitted ⇒ + * kernel default. */ - ipcBytes: Buffer -} - -/** - * An Arrow IPC stream payload encoding just the result schema (no - * record-batch messages). Returned by `Statement.schema()`. - */ -export interface ArrowSchema { + runtimeVersion?: string /** - * Arrow IPC stream payload (schema header only, no record-batch - * messages). Decode with `apache-arrow`'s `RecordBatchReader` — - * the reader will expose the schema and immediately end. + * Runtime vendor reported in telemetry system configuration. Omitted ⇒ + * kernel default. */ - ipcBytes: Buffer -} - -/** - * Authentication mode selector crossing the napi boundary. The string - * literals are what napi-rs emits from this `#[napi(string_enum)]` — the - * NodeJS SEA adapter (`KernelAuth`) matches them verbatim (`'Pat'`, - * `'OAuthM2m'`, `'OAuthU2m'`, `'AzureSpM2m'`). - * - * Mirrors the kernel [`AuthConfig`] variants this binding supports. - * `OAuthFederation` / `External` are intentionally not exposed yet — the - * kernel marks federation as not-yet-implemented and `External` is a - * Rust-trait escape hatch with no JS-callback bridge. - */ -export declare const enum AuthMode { - /** Personal access token (`token`). */ - Pat = 'Pat', - /** OAuth 2.0 machine-to-machine — `oauthClientId` + `oauthClientSecret`. */ - OAuthM2m = 'OAuthM2m', + runtimeVendor?: string /** - * OAuth 2.0 machine-to-machine with a JWT private-key client - * assertion — `oauthClientId` + `jwtKeyFile` + `jwtKid`. + * Operating system name reported in telemetry system configuration. + * Omitted ⇒ kernel default. */ - OAuthM2mJwt = 'OAuthM2mJwt', + osName?: string /** - * OAuth 2.0 user-to-machine (browser flow) — optional `oauthClientId` - * + `oauthRedirectPort`. + * Operating system version reported in telemetry system configuration. + * Omitted ⇒ kernel default. */ - OAuthU2m = 'OAuthU2m', - /** - * Azure Entra service-principal M2M — `azureClientId` + - * `azureClientSecret` (+ optional `azureTenantId` / - * `azureWorkspaceResourceId`). The kernel builds the Entra token - * endpoint + `.default` scope, auto-discovers the tenant from the - * workspace when `azureTenantId` is omitted, and — when - * `azureWorkspaceResourceId` is set — additionally sends the SP - * management token for an RBAC-only service principal. - */ - AzureSpM2m = 'AzureSpM2m' -} - -/** - * JS-visible options for opening a Databricks SQL session. - * - * Authentication is selected by `authMode` (default [`AuthMode::Pat`]): - * - `Pat` — `token` required. - * - `OAuthM2m` — `oauthClientId` + `oauthClientSecret` required. - * - `OAuthU2m` — `oauthClientId` / `oauthRedirectPort` optional - * (defaults to the `databricks-sql-connector` client on port 8030). - * - `AzureSpM2m` — `azureClientId` + `azureClientSecret` required - * (+ optional `azureTenantId` / `azureWorkspaceResourceId`). - * - * Catalog / schema / sessionConf are applied once at session creation - * and remain in effect for every statement run on the resulting - * `Connection`. The SEA wire protocol carries them on - * `CreateSession`, not on `ExecuteStatement` — so there is no - * per-statement override path on this binding. - */ -export interface ConnectionOptions { - /** - * Workspace host, e.g. `adb-…azuredatabricks.net`. The kernel - * normalises this — bare hostnames get `https://` prepended. - */ - hostName: string - /** - * JDBC-style HTTP path, e.g. `/sql/1.0/warehouses/abc123`. The - * kernel parses out the warehouse id. - */ - httpPath: string - /** - * Authentication mode. Omitted ⇒ [`AuthMode::Pat`] (back-compat: - * existing PAT callers pass only `token`). - */ - authMode?: AuthMode - /** - * Personal access token. Required (and non-empty) for - * [`AuthMode::Pat`]; ignored otherwise. - */ - token?: string - /** - * OAuth client id. Required for [`AuthMode::OAuthM2m`]; optional for - * [`AuthMode::OAuthU2m`] (defaults to `databricks-sql-connector`). - */ - oauthClientId?: string - /** OAuth client secret. Required for [`AuthMode::OAuthM2m`]. */ - oauthClientSecret?: string - /** - * Localhost callback port for the [`AuthMode::OAuthU2m`] browser - * flow. Omitted ⇒ kernel default (8030). - */ - oauthRedirectPort?: number - /** - * OAuth scopes override (M2M / U2M). Omitted ⇒ kernel defaults - * (`["all-apis"]` for M2M; `["sql", "offline_access"]` for U2M). - */ - oauthScopes?: Array - /** - * OAuth token endpoint override. When omitted the kernel discovers the - * endpoint via the workspace's OIDC configuration. Set it to point the - * client-credentials / JWT client-assertion grant at the workspace's - * configured IdP token endpoint (e.g. Entra ID for Azure Databricks), - * which is required when that IdP — not Databricks-native OIDC — is the - * authority for [`AuthMode::OAuthM2m`] / [`AuthMode::OAuthM2mJwt`]. - */ - tokenUrl?: string - /** - * U2M on-disk token-cache control (kernel path). Omitted ⇒ the kernel - * default (cache enabled, encrypted under a machine-local key, survives - * restarts). `false` disables on-disk persistence (re-login each fresh - * process); `true` keeps it enabled. Applies to [`AuthMode::OAuthU2m`]. - */ - tokenCacheEnabled?: boolean - /** - * Optional passphrase for the U2M on-disk token cache (AES-256 key). - * Omitted/blank ⇒ a machine-local derived key. Supplying one is stronger. - * A passphrase with no explicit `tokenCacheEnabled` implies enabled. - * Applies to [`AuthMode::OAuthU2m`]. - */ - tokenCachePassphrase?: string - /** - * Path to the PEM private-key file. Required for - * [`AuthMode::OAuthM2mJwt`]. - */ - jwtKeyFile?: string - /** JWT key id (`kid`). Required for [`AuthMode::OAuthM2mJwt`]. */ - jwtKid?: string - /** - * Passphrase for an encrypted PKCS#8 key. Optional for - * [`AuthMode::OAuthM2mJwt`] (omit for an unencrypted key). - */ - jwtPassphrase?: string - /** - * JWT signing algorithm (`RS256`/`384`/`512`, `PS256`/`384`/`512`, - * `ES256`, `ES384`). Optional for [`AuthMode::OAuthM2mJwt`] - * (omitted ⇒ kernel default `RS256`). - */ - jwtAlgorithm?: string - /** - * SP-wide Workload Identity Federation client id used during mandatory - * token exchange. Omitted selects BYOT / account-wide WIF. - */ - identityFederationClientId?: string - /** - * Azure Entra app-registration client id. Required for - * [`AuthMode::AzureSpM2m`]; ignored otherwise. - */ - azureClientId?: string - /** - * Azure Entra app-registration client secret. Required for - * [`AuthMode::AzureSpM2m`]. - */ - azureClientSecret?: string - /** - * Azure Entra tenant id. Optional for [`AuthMode::AzureSpM2m`]; - * omitted ⇒ the kernel auto-discovers it from the workspace's - * `/aad/auth` redirect (matching the Thrift connector). - */ - azureTenantId?: string - /** - * Azure workspace ARM resource id. Optional for [`AuthMode::AzureSpM2m`]; - * when set the kernel also sends the SP management token - * (`X-Databricks-Azure-SP-Management-Token`) + the - * `X-Databricks-Azure-Workspace-Resource-Id` header, so a service - * principal with an Azure RBAC role but no workspace membership can - * authenticate. Omitted ⇒ the data token authenticates alone. - */ - azureWorkspaceResourceId?: string - /** - * Default catalog for statements executed on this session. - * Routed through the kernel's `DefaultOpts` and onto the SEA - * `CreateSession.catalog` wire field. - */ - catalog?: string - /** - * Default schema for statements executed on this session. - * Routed through the kernel's `DefaultOpts` and onto the SEA - * `CreateSession.schema` wire field. - */ - schema?: 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. - */ - sessionConf?: Record - /** - * Select whether `GEOMETRY` / `GEOGRAPHY` results use their native Arrow - * representation. `true` (the default) requests Arrow - * `struct` values; `false` requests WKT / EWKT - * in Arrow UTF-8 values. The kernel normalizes both standard-warehouse - * text and native Arrow results locally and never sends this choice - * to SEA. - */ - enableGeoSpatialSupport?: boolean - /** - * Driver name reported in telemetry system configuration. Omitted ⇒ - * kernel default. - */ - driverName?: string - /** - * Driver version reported in telemetry system configuration. Omitted ⇒ - * kernel default. - */ - driverVersion?: string - /** - * Runtime name reported in telemetry system configuration. Omitted ⇒ - * kernel default. - */ - runtimeName?: string - /** - * Runtime version reported in telemetry system configuration. Omitted ⇒ - * kernel default. - */ - runtimeVersion?: string - /** - * Runtime vendor reported in telemetry system configuration. Omitted ⇒ - * kernel default. - */ - runtimeVendor?: string - /** - * Operating system name reported in telemetry system configuration. - * Omitted ⇒ kernel default. - */ - osName?: string - /** - * Operating system version reported in telemetry system configuration. - * Omitted ⇒ kernel default. - */ - osVersion?: string + osVersion?: string /** * Operating system architecture reported in telemetry system * configuration. Omitted ⇒ kernel default. @@ -958,7 +516,9 @@ export interface ConnectionOptions { * `User-Agent` entry here. */ customHeaders?: Array - /** Whether SEA API responses may use HTTP compression. Defaults to false. */ + /** + * Whether SEA API responses may use HTTP compression. Defaults to false. + */ seaResponseCompressionEnabled?: boolean /** * Retry/backoff tuning — all optional. An unset field keeps the kernel's @@ -989,13 +549,10 @@ export interface ConnectionOptions { */ retryOverallTimeoutSecs?: number /** - * Enable kernel telemetry export. Tri-state: an explicit `true` or `false` - * takes precedence; when omitted, export defers to the - * `enableTelemetryForKernel` workspace feature flag, falling back to - * disabled when the flag is absent. Only an explicit `false` guarantees - * telemetry stays disabled. When enabled, the kernel records operation - * telemetry below the binding layer and exports through the Databricks SQL - * driver telemetry endpoint. + * Enable kernel telemetry export. Omitted / `false` keeps telemetry + * disabled. When enabled, the kernel records operation telemetry below the + * binding layer and exports through the Databricks SQL driver telemetry + * endpoint. */ telemetryEnabled?: boolean /** @@ -1021,9 +578,9 @@ export interface ConnectionOptions { /** Enable telemetry circuit-breaker protection. Omitted ⇒ kernel default. */ telemetryCircuitBreakerEnabled?: boolean /** - * Consecutive telemetry export failures before opening the circuit. - * Omitted ⇒ kernel default. Must be greater than zero when the circuit - * breaker is enabled. + * Consecutive telemetry export failures before opening the circuit. Omitted + * ⇒ kernel default. Must be greater than zero when the circuit breaker is + * enabled. */ telemetryCircuitBreakerThreshold?: number /** @@ -1060,136 +617,41 @@ export interface ConnectionOptions { */ socketTimeoutMs?: number } - /** - * Per-statement options for `Connection.executeStatement`. + * Open a Databricks SQL session and return an opaque `Connection` + * wrapping the kernel `Session`. Authentication is selected by + * `options.auth_mode` (PAT / OAuth M2M / OAuth U2M) — see + * [`build_auth_config`]. * - * Mirrors the kernel `StatementSpec` knobs that are safe to thread - * through napi without a kernel-side change. Today this covers: - * - `statementConf` — per-statement Spark conf overlay - * (`StatementSpec.statement_conf` → SEA `parameters` / - * Thrift `confOverlay`) - * - `queryTags` — convenience wrapper over `statementConf` with - * key `query_tags`; serialised to the same comma-separated - * `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. + * The JS-visible name is `openSession` (napi-rs converts snake_case + * to camelCase for free functions). + */ +export declare function openSession(options: ConnectionOptions): Promise +/** + * One kernel log event, as handed to JS. `level` is a lower-case string + * (`error`/`warn`/`info`/`debug`/`trace`) the Node side maps onto its + * `LogLevel`; `target` is the originating `tracing` target (e.g. + * `databricks::sql::kernel`); `message` is the rendered event plus any + * structured `key=value` fields. + */ +export interface LogRecord { + level: string + target: string + message: string +} +/** + * Install (idempotently) the kernel→JS log bridge and set its level. * - * `rowLimit` (SEA `row_limit`) is exposed here and threaded onto the kernel - * `StatementSpec`. `positionalParams` (`?`) and `namedParams` (`:name`) - * carry bound query parameters, decoded via `params::parse_typed_value`. - * `rawParams` forwards pre-marshalled SEA parameters unchanged. - * (There is no `queryTimeoutSecs`: it abused the SEA `wait_timeout` inline-hold - * window and was removed — a real per-statement timeout is `STATEMENT_TIMEOUT`.) - * - * **Tag-order caveat (M4 parity note).** The napi `queryTags` field - * is a Rust `HashMap` whose iteration order is - * non-deterministic, so the serialised `query_tags` value may have - * a different key order than Thrift's `serializeQueryTags` (which - * iterates `Object.keys(...)` in insertion order) for the same - * input. The SEA server is order-insensitive on conf values, so - * the two are functionally equivalent. If a caller needs - * byte-identical Thrift parity, the JS adapter pre-serialises via - * `serializeQueryTags` and writes the result into - * `statementConf["query_tags"]` directly — see - * `KernelSessionBackend.executeStatement` in the NodeJS driver. This - * path is the one the production code uses. - */ -export interface ExecuteOptions { - /** - * Per-statement Spark conf overlay. Merged on top of the - * session-level `sessionConf` at execute time; this map wins - * on key collisions. Unknown keys are rejected by the server. - */ - statementConf?: Record - /** - * Query tags as key→value pairs. Serialised to a comma- - * separated `key:value` string (backslash-escaping `\`, `:`, - * `,`) and placed into `statementConf["query_tags"]`, matching - * NodeJS Thrift's `serializeQueryTags` wire shape. Passing - * both `queryTags` AND a `query_tags` key in `statementConf` - * raises `InvalidArgument` — the caller's intent is ambiguous - * so we refuse to silently pick one over the other. - * - * A **`null`** value emits a **bare key** (no colon) — e.g. - * `{ production: null }` → `"production"` — matching the - * connectors' `key`-only tag form. - * - * See the struct-level "Tag-order caveat" for the - * HashMap-iteration-order vs `Object.keys`-iteration-order - * divergence and the byte-identical-Thrift-parity workaround. - */ - queryTags?: Record - /** - * Server-side cap on the number of rows this statement returns - * (SEA `row_limit`), independent of any SQL `LIMIT`. Maps to - * `StatementSpec.row_limit`. Omitted ⇒ no driver-imposed cap. - */ - rowLimit?: number - /** Omit to handle instructions in the caller; an empty list denies local file access. */ - stagingAllowedLocalPaths?: Array - /** - * 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 - * string-encoded literal or `null` for SQL NULL. Mirrors - * `StatementSpec::positional_params`; decoded via [`parse_typed_value`]. - */ - positionalParams?: Array - /** - * Named parameters (`:name` placeholders). Each carries its `name` - * alongside the `{ sqlType, value? }` pair. Mapped to a kernel - * `TypedValue` via the same [`parse_typed_value`] codec and bound with - * `StatementSpec::param_named`. Named is the SEA-spec-required public - * param form (`StatementParameter.name` is `openapi_required`); - * positional is the documented-undocumented variant. The two are - * mutually exclusive at the SQL level (`?` vs `:name`). - */ - namedParams?: Array - /** - * Pre-marshalled parameters passed through `StatementSpec::param_raw`. - * Omit `name` for positional values. Raw parameters cannot be mixed with - * typed parameters or combine named and positional markers. - */ - rawParams?: Array -} - -/** - * A single extra HTTP header as an explicit `{ name, value }` pair. - * - * An ordered list of these (`ConnectionOptions.custom_headers`) mirrors - * the kernel core's `Vec<(String, String)>` and the pyo3 binding's - * `http_headers`: order is preserved and duplicate `name`s are allowed. - * A struct (rather than a raw `[name, value]` tuple) because napi-rs - * does not marshal Rust tuples through `#[napi(object)]` fields; the - * struct is the idiomatic, self-documenting equivalent and maps to a JS - * `{ name: string, value: string }`. - */ -export interface HeaderEntry { - name: string - value: string -} - -/** - * Install (idempotently) the kernel→JS log bridge and set its level. - * - * `callback` is invoked with **an array of [`LogRecord`]s** (`(err, records)`) - * for each forwarded batch. `level` is one of - * `off`/`error`/`warn`/`info`/`debug`/`trace` (case-insensitive); unknown - * values fall back to `warn`. + * `callback` is invoked with **an array of [`LogRecord`]s** (`(err, records)`) + * for each forwarded batch. `level` is one of + * `off`/`error`/`warn`/`info`/`debug`/`trace` (case-insensitive); unknown + * values fall back to `warn`. * * Safe to call more than once: the process-global subscriber is installed on * the first call only, while every call refreshes the sink + level (last * writer wins — see module docs). */ -export declare function initKernelLogging(callback: ((err: Error | null, arg: Array) => any), level: string): void - -/** - * Return the bridge's [`KernelLoggingStats`]. Safe to call before - * `initKernelLogging` (reports `installed: false`, `dropped: 0`). - */ -export declare function kernelLoggingStats(): KernelLoggingStats - +export declare function initKernelLogging(callback: (err: Error | null, arg: Array) => any, level: string): void /** * Snapshot of the bridge's runtime state for observability. * @@ -1205,81 +667,16 @@ export interface KernelLoggingStats { installed: boolean dropped: number } - -/** - * One kernel log event, as handed to JS. `level` is a lower-case string - * (`error`/`warn`/`info`/`debug`/`trace`) the Node side maps onto its - * `LogLevel`; `target` is the originating `tracing` target (e.g. - * `databricks::sql::kernel`); `message` is the rendered event plus any - * structured `key=value` fields. - */ -export interface LogRecord { - level: string - target: string - message: string -} - -/** - * A named bound parameter — a [`TypedValueInput`] plus its `:name`. Kept a - * distinct napi object (rather than an optional `name` on `TypedValueInput`) - * so the positional surface stays a clean ordered list with no name field. - */ -export interface NamedTypedValueInput { - name: string - sqlType: string - value?: string -} - -/** - * Open a Databricks SQL session and return an opaque `Connection` - * wrapping the kernel `Session`. Authentication is selected by - * `options.auth_mode` (PAT / OAuth M2M / OAuth U2M) — see - * [`build_auth_config`]. - * - * The JS-visible name is `openSession` (napi-rs converts snake_case - * to camelCase for free functions). - */ -export declare function openSession(options: ConnectionOptions): Promise - -/** - * Programmatic HTTP/HTTPS proxy configuration, mirroring the kernel's - * internal [`ProxyConfig`]. Supplied as a structured object rather than a - * flattened URL so credentials never have to be percent-encoded into the URL - * and the bypass-host list can be expressed. - * - * - `url` — proxy endpoint, e.g. `"http://proxy.corp.example.com:8080"`. Must - * use the `http://` or `https://` scheme. - * - `username` / `password` — optional proxy basic-auth, applied via - * `reqwest`'s `Proxy::basic_auth` (not embedded in the URL). - * - `bypassHosts` — optional comma-separated host/domain list that should - * bypass the proxy (e.g. `"localhost,*.internal.corp"`). - */ -export interface ProxyInput { - url: string - username?: string - password?: string - bypassHosts?: string -} - /** - * A pre-marshalled SEA parameter that preserves `sql_type` verbatim. - * Omit `name` for positional markers; the kernel assigns their ordinals. + * Return the bridge's [`KernelLoggingStats`]. Safe to call before + * `initKernelLogging` (reports `installed: false`, `dropped: 0`). */ -export interface RawParameterInput { - /** Named marker name. Omit for a positional marker. */ - name?: string - /** Databricks SQL type name sent verbatim to SEA. */ - sqlType: string - /** String-encoded value. `None` represents SQL NULL. */ - value?: string -} - +export declare function kernelLoggingStats(): KernelLoggingStats /** * Live-retarget the bridge's level (one of * `off`/`error`/`warn`/`info`/`debug`/`trace`, case-insensitive). */ export declare function setKernelLogLevel(level: string): void - /** * JS-visible binding for a single positional parameter. * @@ -1313,7 +710,41 @@ export interface TypedValueInput { */ value?: string } - +/** + * A pre-marshalled SEA parameter that preserves `sql_type` verbatim. + * Omit `name` for positional markers; the kernel assigns their ordinals. + */ +export interface RawParameterInput { + /** Named marker name. Omit for a positional marker. */ + name?: string + /** Databricks SQL type name sent verbatim to SEA. */ + sqlType: string + /** String-encoded value. `None` represents SQL NULL. */ + value?: string +} +/** + * A single Arrow IPC stream payload encoding one record batch (plus + * the schema header so the JS-side reader is stateless). + */ +export interface ArrowBatch { + /** + * Arrow IPC stream payload (schema header + 1 record-batch + * message). Decode with `apache-arrow`'s `RecordBatchReader`. + */ + ipcBytes: Buffer +} +/** + * An Arrow IPC stream payload encoding just the result schema (no + * record-batch messages). Returned by `Statement.schema()`. + */ +export interface ArrowSchema { + /** + * Arrow IPC stream payload (schema header only, no record-batch + * messages). Decode with `apache-arrow`'s `RecordBatchReader` — + * the reader will expose the schema and immediately end. + */ + ipcBytes: Buffer +} /** * Returns the native binding's crate version (`CARGO_PKG_VERSION`). * @@ -1321,3 +752,541 @@ export interface TypedValueInput { * loaded?" probe for the JS-side loader's structured diagnostics. */ export declare function version(): string +/** + * Opaque async-statement handle. + * + * Returned by `Connection.submitStatement(...)` after the kernel + * `Statement::submit()` returns (server sent `wait_timeout=0s`, so + * the response carries a `statement_id` but the statement is still + * `Pending`/`Running`). JS drives polling via `status()` / + * `awaitResult()`. + * + * Concurrency shape: `status()`, `awaitResult()`, and `close()` take + * `inner.lock()` and hold the guard across the kernel `.await` (tokio + * `Mutex` is FIFO), so `status()` / `close()` queue behind any + * in-flight `awaitResult()` until it returns naturally. `cancel()` is + * the deliberate exception: it does **not** touch `inner` — it fires + * through the detached `AsyncStatementCanceller` (session + + * statement_id, captured at construction), so an explicit + * `stmt.cancel()` interrupts an in-flight `awaitResult()` instead of + * queueing behind it. The server-side cancel flips the statement + * terminal, which the parked `awaitResult()` poll loop observes + * (`Cancelled`) and returns on. The kernel's `AwaitResultCancelGuard` + * still covers the drop-cancel case (Promise.race / timeout) + * independently — see module docs. + */ +export declare class AsyncStatement { + /** + * Server-issued statement id. Cached at construction; readable + * even after `close()` so JS-side log lines can correlate + * against kernel / server logs which key on the same id. + */ + get statementId(): string + /** + * One-shot status check. Returns a string enum matching the + * kernel `StatementStatus` shape: + * `'Pending' | 'Running' | 'Succeeded' | 'Failed' | + * 'Cancelled' | 'Closed' | 'Unknown'`. (`'Unknown'` is the + * `#[non_exhaustive]` forward-compat catch-all that + * `StatementStatus::as_str` can return — consumers switching on + * the state must handle it.) Returns + * `KernelError(InvalidStatementHandle)` if the statement has + * been explicitly `close()`d. + * + * The `Failed` variant collapses to the string `'Failed'` on + * the JS side; the underlying error envelope (sql_state / + * error_code / query_id) is surfaced by `awaitResult()`'s + * rejection, which is where callers actually need the typed + * error. `status()` is intended for polling progress UIs + * that only need the state name. + */ + status(): Promise + /** Rows modified by the statement (UPDATE / INSERT / DELETE / MERGE). */ + numModifiedRows(): Promise + /** + * Server-supplied user-facing message (may contain SQL fragments — + * redact before centralised logging). + */ + displayMessage(): Promise + /** Server-supplied diagnostic detail. */ + diagnosticInfo(): Promise + /** Server-supplied structured error detail (JSON), when enabled. */ + errorDetailsJson(): Promise + /** + * Block until the server reaches a terminal state, then return + * an `AsyncResultHandle` that wraps the materialised result + * stream. The handle exposes `fetchNextBatch()` / `schema()` + * for consuming the result, plus `statementId` for log + * correlation. + * + * Drop-cancel safety: kernel `await_result` installs + * `AwaitResultCancelGuard` which fires a fire-and-forget + * `cancel_statement` if the future is dropped mid-poll + * (timeout, tokio::select! loser, JS-side `Promise.race` + * loser). The `util::guarded` `catch_unwind` here covers the + * V8-panic-across-boundary case on top. Returns + * `KernelError(InvalidStatementHandle)` if the statement has + * been explicitly `close()`d. + */ + awaitResult(): Promise + /** + * Server-side cancel. Returns + * `KernelError(InvalidStatementHandle)` if the statement has + * been explicitly `close()`d. Idempotent against a server + * that already reached a terminal state — the kernel's + * `cancel_statement` is a no-op there. + * + * **Lock-free by design.** Unlike `status()` / `awaitResult()` / + * `close()`, this does not take `inner.lock()` — it fires through + * the detached `AsyncStatementCanceller` captured at construction. + * That lets `stmt.cancel()` interrupt an in-flight `awaitResult()` + * (which holds the mutex for the whole poll) instead of queueing + * behind it: the server-side cancel flips the statement terminal, + * the parked `awaitResult()` poll loop observes `Cancelled` and + * returns. The closed-state check reads a lock-free flag so a + * cancel after an explicit `close()` still surfaces + * `InvalidStatementHandle`. + */ + cancel(): Promise + /** + * Explicit close. Idempotent — a second call on an + * already-closed handle returns `Ok(())`. On `Err`, the napi + * inner is already `None`, so a JS-side retry sees the + * closed-handle short-circuit and returns `Ok(())` without + * re-attempting the wire call. The kernel's own `Drop` + * fire-and-forget retry runs once in the background. + */ + close(): Promise +} +/** + * Opaque result-fetch handle returned by + * `AsyncStatement.awaitResult()`. Wraps a kernel `ResultStream` + * directly; structurally analogous to the sync `Statement`'s + * fetch-side surface (`fetchNextBatch` / `schema` / + * `statementId`). + * + * `cancel()` / `close()` are not exposed: the parent + * `AsyncStatement` owns server-side lifecycle. A `close()` here + * would create dual-ownership of the same statement_id with + * inconsistent close semantics. Callers `close()` the parent + * `AsyncStatement` after they're done fetching. + * + * Schema is cached at construction so it survives the underlying + * stream being drained; mirrors the sync `Statement.schema()` + * post-close contract. + */ +export declare class AsyncResultHandle { + /** + * Server-issued statement id. Cached at construction; readable + * for log correlation. Matches the parent `AsyncStatement`'s + * `statementId`. + */ + get statementId(): string + /** + * Pull the next batch of results. Returns `null` when the + * stream is exhausted. The returned `ArrowBatch.ipcBytes` is a + * complete Arrow IPC stream (schema header + 1 record-batch + * message), suitable for handing to `apache-arrow`'s + * `RecordBatchReader`. Byte-identical to the sync + * `Statement.fetchNextBatch()` payload for the same query. + */ + fetchNextBatch(): Promise + /** + * Result schema as an Arrow IPC payload (schema header only, + * no record-batch message). Available before any batches have + * been fetched. Sync because the body has no `.await` — + * `encode_ipc_stream` is pure CPU work over the cached + * `Arc`. + */ + schema(): ArrowSchema +} +/** + * Handle returned by `Connection.executeStatementCancellable`. Owns the + * built-but-not-yet-executed kernel `Statement` plus a detached + * [`StatementCanceller`] captured before dispatch, so JS can fire a + * server-side cancel while the blocking `result()` is in flight. + * + * `pending` is `Arc>>` so `result()` can + * `.take()` the statement (the kernel `execute()` borrows it `&mut`, + * then it moves into the produced `Statement` wrapper to keep its + * `ValidityFlag` set — see `statement.rs`). A second `result()` call + * after the first resolved surfaces `InvalidStatementHandle`. + */ +export declare class CancellableExecution { + /** + * The server-issued statement id this execution targets, if the + * server has issued one yet (`null` before the initial submit + * round-trip publishes it mid-`result()`). Useful for log + * correlation while the blocking drive is in flight. + */ + get statementId(): string | null + /** + * Drive the blocking `execute()` and resolve to a `Statement` + * (identical to what `executeStatement` returns) once the kernel + * reaches a terminal state and the result stream is ready. + * + * Consumes the pending statement: a second `result()` call returns + * `KernelError(InvalidStatementHandle)`. The future is + * drop-cancel-safe — the kernel's per-execute `MidExecuteCancelState` + * guard fires a fire-and-forget `cancel_statement` if this future is + * dropped mid-flight (`Promise.race` / timeout loser), independently + * of an explicit `cancel()`. + * + * On a server-side cancel the kernel's blocking `execute()` currently + * surfaces `InvalidArgument` (a known kernel quirk — the async path + * returns `Cancelled`). When this handle's `cancel()` actually dispatched a + * server-side cancel, we normalise that into `Cancelled` here so JS callers + * can rely on a single cancelled-status code regardless of execution path. + * + * Three outcomes can race the blocking drive: (1) a natural terminal state + * → `Ok` or the genuine error; (2) an explicit `cancel()` that dispatched a + * server cancel → this `result()` rejects with a `Cancelled`-coded error + * (the normalisation above); (3) the future being **dropped** mid-flight + * (`Promise.race`/timeout loser) → the kernel's `MidExecuteCancelState` + * drop-guard fires a fire-and-forget `cancel_statement`, but there is no + * `result()` left to observe a code. Only (2) yields a `Cancelled` error. + */ + result(): Promise + /** + * Server-side cancel of the in-flight statement. + * + * Lock-free: fires the detached `StatementCanceller` captured at + * construction rather than taking the mutex `result()` holds, so it + * interrupts a still-running blocking `result()` instead of queueing + * behind it. No-op (returns `Ok`) if `result()` already finished + * successfully, or if no statement id has been observed yet (query still + * in its initial submit round-trip), and idempotent against a server + * already in a terminal state. + */ + cancel(): Promise +} +/** + * Opaque connection handle wrapping a kernel `Session`. + * + * `inner` is `Arc>>` so: + * - the Drop impl can clone the `Arc` and `.take()` the session on a + * background tokio task without holding `&mut self` (which Drop is + * forbidden from doing across an `await`), + * - `close()` can `.take()` the session to consume it for the kernel's + * move-by-value `Session::close(self)` signature. + * + * **Concurrency shape** — both `executeStatement` and + * `submitStatement` build the kernel `Statement` under `inner.lock()` + * and then RELEASE the guard before the wire call + * (`stmt.execute().await` / `stmt.submit().await`). `Session::statement()` + * is `&self`-callable and only clones the session's internal `Arc`, so + * the built statement is independent of the guard. Concurrent + * `Promise.all([executeStatement(q1), submitStatement(q2)])` therefore + * serialise only for the microsecond statement-build, not the network + * round-trip, and `close()` never blocks behind an in-flight execute or + * submit. See + * `sea-workflow/jira-candidates/2026-05-24-napi-cancel-during-fetch.md`. + */ +export declare class Connection { + /** + * Server-issued session id. Cached at construction; readable + * even after `close()` so JS-side log lines can correlate + * against kernel / server logs which key on the same id. + */ + get sessionId(): string + /** + * Execute a SQL statement and return a Statement handle that + * streams batches via `fetchNextBatch()`. + * + * Catalog / schema / sessionConf are session-level + * (`openSession`). Per-statement options on `ExecuteOptions`: + * - `statementConf` — per-statement Spark conf overlay + * - `queryTags` — serialised to a comma-separated `key:value` + * string and placed in `statement_conf["query_tags"]`, + * matching NodeJS Thrift's `serializeQueryTags` wire shape + * + * `options` is omitted/`None` for the no-options path; passing + * `{ statementConf: {} }` (an empty map) is treated the same as + * omission to keep the wire shape stable for the common case. + */ + executeStatement(sql: string, options?: ExecuteOptions | undefined | null): Promise + /** + * directResults execute — the Thrift/JDBC model. Sends ExecuteStatement + * with no `wait_timeout` field (server applies its ~10s default inline wait + * and auto-closes on success) and returns WITHOUT polling past it: + * + * - a **`Statement`** (left arm) when the query finished within the inline + * wait — terminal, result ready inline, `close()` is a clean release; + * - an **`AsyncStatement`** (right arm) when it did not — a poll/cancel + * handle the caller drives (`status()` / `awaitResult()` / `cancel()`). + * + * JS distinguishes the arms by feature-detecting `awaitResult` (present + * only on `AsyncStatement`). This is the path that gives mid-run cancel for + * long queries WITHOUT the eager-handle / close-drives workaround: the + * returned handle always corresponds to a server-owned statement. + * + * **Load-bearing contract:** the kernel's `DirectStatement::{Completed, + * Running}` discriminant cannot ride on these opaque `#[napi]` classes, so + * consumers MUST feature-detect via `awaitResult` (the only member unique to + * `AsyncStatement`). `Statement` (the Completed arm) MUST NOT gain an + * `awaitResult` member, or every consumer silently misroutes. The pyo3 + * binding makes the same `await_result`-probe assumption. + */ + executeStatementDirect(sql: string, options?: ExecuteOptions | undefined | null): Promise + /** + * Execute a SQL statement on the blocking (sync) path, but return a + * `CancellableExecution` handle so a concurrent JS task can cancel + * the query *while it is still running server-side*. + * + * `executeStatement` builds the kernel `Statement`, awaits the + * blocking `execute()`, and only then hands JS a `Statement` — so a + * query that runs for several seconds is uncancellable from JS on + * that path (there is no handle until the blocking call resolves). + * This method instead builds the statement, captures a detached + * `StatementCanceller` **before** dispatching `execute()`, and hands + * JS a `CancellableExecution` immediately. The caller drives the + * blocking execution via `result()` (resolves to the same + * `Statement` `executeStatement` returns) and can fire `cancel()` + * concurrently to interrupt a still-running query mid-COMPUTE. + * + * Option semantics are identical to `executeStatement`. + * Mirrors the pyo3 `Statement.canceller()` / `Statement.execute()` + * split (PR #121): obtain the canceller before the blocking drive. + */ + executeStatementCancellable(sql: string, options?: ExecuteOptions | undefined | null): Promise + /** + * Submit a SQL statement and return immediately with an + * `AsyncStatement` handle, without blocking until the query + * finishes. The kernel's `Statement::submit()` sends + * `wait_timeout=0s`, so the server responds as soon as it has a + * `statement_id` (state `Pending`/`Running`); JS drives polling + * via `AsyncStatement.status()` and materialises results with + * `AsyncStatement.awaitResult()`. + * + * This is the async-execution path the Thrift backend always + * 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`. + * 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 + * differs from `executeStatement`. + */ + submitStatement(sql: string, options?: ExecuteOptions | undefined | null): Promise + /** + * Explicit close. Awaits the server-side `DeleteSession` so the + * JS caller can observe failures (auth revoked mid-session, + * warehouse stopped, network error). Idempotent — a second call + * on an already-closed connection returns `Ok`. + * + * **Errors are terminal from the JS side.** The kernel session + * handle is consumed (`take()`) BEFORE the wire `DeleteSession` + * runs, because `Session::close` takes `self` by value. On `Err`, + * the napi `inner` is already `None`, so a JS-side retry sees a + * closed connection and returns `Ok(())` without re-attempting + * the wire call. The kernel's own `Drop` fire-and-forget retry + * runs once in the background — the JS caller can log the error + * but cannot drive a retry. If you need retry-on-failure + * semantics for `DeleteSession`, layer them above this method. + */ + close(): Promise + /** + * All catalogs visible to the session. + * + * JDBC `getCatalogs` shape: `TABLE_CAT: Utf8`. + */ + listCatalogs(): Promise + /** + * Schemas filtered by catalog (exact) and schema name pattern. + * + * JDBC `getSchemas` shape: `TABLE_SCHEM, TABLE_CATALOG`. + */ + listSchemas(catalog?: string | undefined | null, schemaPattern?: string | undefined | null): Promise + /** + * Tables filtered by catalog (exact), schema (pattern), table (pattern). + * + * JDBC `getTables` shape: 10 columns. `tableTypes`, when provided, + * filters rows by `TABLE_TYPE` kernel-side. + * + * `tableTypes` is an advisory filter. Databricks `SHOW TABLES` does + * NOT honour the table-type filter server-side; the kernel applies + * it client-side after the result returns. Callers expecting + * server-side rejection of off-type tables should not rely on this. + */ + listTables(catalog?: string | undefined | null, schemaPattern?: string | undefined | null, tablePattern?: string | undefined | null, tableTypes?: Array | undefined | null): Promise + /** + * Columns of tables matching the filter. + * + * JDBC `getColumns` shape: 23 columns. + */ + listColumns(catalog?: string | undefined | null, schemaPattern?: string | undefined | null, tablePattern?: string | undefined | null, columnPattern?: string | undefined | null): Promise + /** + * Functions visible to the session. `catalog` is exact; + * `schemaPattern` and `functionPattern` are SQL LIKE. + */ + listFunctions(catalog?: string | undefined | null, schemaPattern?: string | undefined | null, functionPattern?: string | undefined | null): Promise + /** + * Procedures visible to the session. `catalog` is exact; + * `schemaPattern` and `procedurePattern` are SQL LIKE. + */ + listProcedures(catalog?: string | undefined | null, schemaPattern?: string | undefined | null, procedurePattern?: string | undefined | null): Promise + /** + * All table types (`TABLE`, `VIEW`, `SYSTEM TABLE`, …). + * No wire call — static in-memory result. + */ + listTableTypes(): Promise + /** + * SQL data types supported by the workspace. + * No wire call — static in-memory result. + */ + listTypeInfo(): Promise + /** + * Primary keys for the given table. All three identifiers are + * exact — ODBC `SQLPrimaryKeys` does not support patterns. + */ + getPrimaryKeys(catalog: string | undefined | null, schema: string | undefined | null, table: string): Promise + /** + * Foreign-key relationships. The parent side is optional. When the + * foreign table is omitted, returns an empty result without issuing a + * server statement. When it is provided, its catalog and schema are + * required. All identifiers are exact — no LIKE patterns. + */ + getCrossReference(parentCatalog: string | undefined | null, parentSchema: string | undefined | null, parentTable: string | undefined | null, foreignCatalog: string | undefined | null, foreignSchema: string | undefined | null, foreignTable: string | undefined | null): Promise +} +/** + * Opaque executed-statement handle. + * + * **Current concurrency shape** — every method takes `inner.lock()` + * and holds the guard across the kernel `.await`. tokio `Mutex` is + * FIFO, so cancel/close queue behind any in-flight `fetchNextBatch` + * until it returns naturally. This is a known limitation that exists + * because the napi shape has not yet been split into an + * `Arc` (for cancel/close, which the + * kernel exposes as `&self`-callable) plus a `Mutex>` only + * for the borrowed-mut fetch path. The lock-shape refactor needs a + * small kernel-side accessor and lands in a follow-up PR — see + * `sea-workflow/jira-candidates/2026-05-24-napi-cancel-during-fetch.md`. + * + * `schema` and `statement_id` are cached at construction so they + * survive `close()` — JS callers building error reports against a + * disposed statement can still read them. + */ +export declare class Statement { + /** + * Server-issued statement id. Cached at construction; readable + * even after `close()` so JS-side log lines can correlate against + * kernel / server logs which key on the same id. + */ + get statementId(): string + /** + * Number of rows modified by the statement (UPDATE / INSERT / + * DELETE / MERGE). `null` for SELECT and on warehouses that don't + * surface the counter. Mirrors Thrift's + * `TGetOperationStatusResp.numModifiedRows`. + */ + numModifiedRows(): Promise + /** + * Server-supplied user-facing message. Mirrors Thrift's + * `TGetOperationStatusResp.displayMessage`. **PII / sensitive- + * data note:** may contain SQL fragments or parameter values — + * redact before centralised logging. + * + * Populated on `Succeeded` / `Closed` paths (incl. an empty `Closed`). + * On terminal-error states (`Failed` / `Cancelled`) the kernel returns + * an Error instead of a `Statement`, and the same field rides on the JS + * Error envelope under the same `displayMessage` key. + */ + displayMessage(): Promise + /** + * Server-supplied diagnostic detail — multi-line operator / + * stack context. Mirrors Thrift's + * `TGetOperationStatusResp.diagnosticInfo`. For support surfaces, + * not user-facing. Same reachability + PII caveats as + * `displayMessage`. + */ + diagnosticInfo(): Promise + /** + * Server-supplied JSON blob with extended error details. Mirrors + * Thrift's `TGetOperationStatusResp.errorDetailsJson`. + * Pass-through string — JS callers parse with `JSON.parse` if + * they need structured access. + * + * **Server-side gating:** populated only when the workspace has + * `spark.databricks.sql.errorDetailsJson.enabled = true` on the + * underlying SQL cluster. The flag is internal-only / default- + * false in the Databricks runtime, so for most JS callers this + * will return `null`. Admin-enabled workspaces return content + * shaped like `{"errorClass": "...", "messageTemplate": "..."}`. + * + * **Unbounded:** when populated, server can return a multi-MB + * blob; size before logging. + */ + errorDetailsJson(): Promise + /** + * Pull the next batch of results. Returns `null` when the stream + * is exhausted. The returned `ArrowBatch.ipcBytes` is a complete + * Arrow IPC stream (schema header + 1 record-batch message) + * suitable for handing to `apache-arrow`'s `RecordBatchReader`. + * + * On `Err`, the stream is in an unspecified state — call + * `close()` and discard the `Statement`. Subsequent + * `fetchNextBatch()` calls after an error are not guaranteed to + * succeed or fail consistently. + */ + fetchNextBatch(): Promise + /** + * Result schema as an Arrow IPC payload (schema header only, no + * record-batch message). Available before any batches have been + * fetched, and remains available after `close()` — the kernel + * materialises the schema eagerly so JS callers can build error + * reports against a disposed statement. + * + * Sync because the body has no `.await` — `encode_ipc_stream` is + * pure CPU work over an `Arc` already cached on the + * wrapper. Mirrors `pyo3/src/statement.rs::arrow_schema` (sync). + * napi-rs converts a panic in a sync `#[napi]` entry point into a + * thrown JS error via its own macro-expanded boundary, so the + * `util::guarded` `catch_unwind` wrapper that the `async fn` + * entry points use is not required for this method. + */ + schema(): ArrowSchema + /** + * Server-side cancel. + * + * For executed statements: short-circuits to `Ok(())` if + * `fetchNextBatch` has already returned `null` (stream + * naturally exhausted) — matches the JDBC `Statement.cancel()` + * no-op-after-completion contract, so JS callers can fire cancel + * defensively without distinguishing "real cancel" from "raced + * with natural completion." + * + * For metadata streams: no-op (the kernel has no in-flight + * cancellation surface for metadata calls today). + * + * Returns `KernelError(InvalidStatementHandle)` if the statement + * has been explicitly `close()`d. + */ + cancel(): Promise + /** + * Explicit close. + * + * For executed statements: awaits the server-side `CloseStatement` + * so the JS caller can observe failures (auth revoked mid-session, + * network error, server-side error). Idempotent — a second call + * on an already-closed statement returns `Ok`. + * + * **Errors are terminal from the JS side.** The kernel executed + * handle is taken out of `inner` BEFORE the wire `CloseStatement` + * runs (so `Drop` knows there's nothing left to clean up). On + * `Err`, the napi `inner` is already `None`, so a JS-side retry + * sees a closed statement and returns `Ok(())` without re- + * attempting the wire call. The kernel-level `ExecutedStatement` + * has been consumed at that point and the value is dropped on + * the way out of the closure — the kernel's `ExecutedStatement:: + * Drop` then fires-and-forgets a single retry on the captured + * runtime. The JS caller can log the error but cannot drive a + * further retry. If you need retry-on-failure semantics for + * `CloseStatement`, layer them above this method. + * + * For metadata streams: drops the stream (no server round-trip + * needed — metadata results have no in-flight server-side + * resource to release). + */ + close(): Promise +} diff --git a/napi/index.js b/napi/index.js index 6902ddee..ad50ecc9 100644 --- a/napi/index.js +++ b/napi/index.js @@ -1,713 +1,325 @@ -// prettier-ignore +/* tslint:disable */ /* eslint-disable */ -// @ts-nocheck +/* prettier-ignore */ + /* auto-generated by NAPI-RS */ -const { readFileSync } = require('fs') -let nativeBinding = null -const loadErrors = [] +const { existsSync, readFileSync } = require('fs') +const { join } = require('path') -const isMusl = () => { - let musl = false - if (process.platform === 'linux') { - musl = isMuslFromFilesystem() - if (musl === null) { - musl = isMuslFromReport() - } - if (musl === null) { - musl = isMuslFromChildProcess() - } - } - return musl -} +const { platform, arch } = process -const isFileMusl = (f) => f.includes('libc.musl-') || f.includes('ld-musl-') - -const isMuslFromFilesystem = () => { - try { - return readFileSync('/usr/bin/ldd', 'utf-8').includes('musl') - } catch { - return null - } -} +let nativeBinding = null +let localFileExisted = false +let loadError = null -const isMuslFromReport = () => { - let report = null - if (process.report && typeof process.report.getReport === 'function') { - process.report.excludeNetwork = true - report = process.report.getReport() - } - if (!report) { - return null - } - if (report.header && report.header.glibcVersionRuntime) { - return false - } - if (Array.isArray(report.sharedObjects)) { - if (report.sharedObjects.some(isFileMusl)) { +function isMusl() { + // For Node 10 + if (!process.report || typeof process.report.getReport !== 'function') { + try { + const lddPath = require('child_process').execSync('which ldd').toString().trim() + return readFileSync(lddPath, 'utf8').includes('musl') + } catch (e) { return true } - } - return false -} - -const isMuslFromChildProcess = () => { - try { - return require('child_process').execSync('ldd --version', { encoding: 'utf8' }).includes('musl') - } catch (e) { - // If we reach this case, we don't know if the system is musl or not, so is better to just fallback to false - return false + } else { + const { glibcVersionRuntime } = process.report.getReport().header + return !glibcVersionRuntime } } -function requireNative() { - if (process.env.NAPI_RS_NATIVE_LIBRARY_PATH) { - try { - return require(process.env.NAPI_RS_NATIVE_LIBRARY_PATH); - } catch (err) { - loadErrors.push(err) - } - } else if (process.platform === 'android') { - if (process.arch === 'arm64') { - try { - return require('./index.android-arm64.node') - } catch (e) { - loadErrors.push(e) - } - try { - const binding = require('@databricks/databricks-sql-kernel-android-arm64') - const bindingPackageVersion = require('@databricks/databricks-sql-kernel-android-arm64/package.json').version - if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) - } - return binding - } catch (e) { - loadErrors.push(e) - } - } else if (process.arch === 'arm') { - try { - return require('./index.android-arm-eabi.node') - } catch (e) { - loadErrors.push(e) - } - try { - const binding = require('@databricks/databricks-sql-kernel-android-arm-eabi') - const bindingPackageVersion = require('@databricks/databricks-sql-kernel-android-arm-eabi/package.json').version - if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) - } - return binding - } catch (e) { - loadErrors.push(e) - } - } else { - loadErrors.push(new Error(`Unsupported architecture on Android ${process.arch}`)) - } - } else if (process.platform === 'win32') { - if (process.arch === 'x64') { - if ((process.config && process.config.variables && process.config.variables.shlib_suffix === 'dll.a') || (process.config && process.config.variables && process.config.variables.node_target_type === 'shared_library')) { - try { - return require('./index.win32-x64-gnu.node') - } catch (e) { - loadErrors.push(e) - } - try { - const binding = require('@databricks/databricks-sql-kernel-win32-x64-gnu') - const bindingPackageVersion = require('@databricks/databricks-sql-kernel-win32-x64-gnu/package.json').version - if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) - } - return binding - } catch (e) { - loadErrors.push(e) - } - } else { - try { - return require('./index.win32-x64-msvc.node') - } catch (e) { - loadErrors.push(e) - } - try { - const binding = require('@databricks/databricks-sql-kernel-win32-x64-msvc') - const bindingPackageVersion = require('@databricks/databricks-sql-kernel-win32-x64-msvc/package.json').version - if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) - } - return binding - } catch (e) { - loadErrors.push(e) - } - } - } else if (process.arch === 'ia32') { - try { - return require('./index.win32-ia32-msvc.node') - } catch (e) { - loadErrors.push(e) - } - try { - const binding = require('@databricks/databricks-sql-kernel-win32-ia32-msvc') - const bindingPackageVersion = require('@databricks/databricks-sql-kernel-win32-ia32-msvc/package.json').version - if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) - } - return binding - } catch (e) { - loadErrors.push(e) - } - } else if (process.arch === 'arm64') { - try { - return require('./index.win32-arm64-msvc.node') - } catch (e) { - loadErrors.push(e) - } - try { - const binding = require('@databricks/databricks-sql-kernel-win32-arm64-msvc') - const bindingPackageVersion = require('@databricks/databricks-sql-kernel-win32-arm64-msvc/package.json').version - if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) - } - return binding - } catch (e) { - loadErrors.push(e) - } - } else { - loadErrors.push(new Error(`Unsupported architecture on Windows: ${process.arch}`)) - } - } else if (process.platform === 'darwin') { - try { - return require('./index.darwin-universal.node') - } catch (e) { - loadErrors.push(e) - } - try { - const binding = require('@databricks/databricks-sql-kernel-darwin-universal') - const bindingPackageVersion = require('@databricks/databricks-sql-kernel-darwin-universal/package.json').version - if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) - } - return binding - } catch (e) { - loadErrors.push(e) - } - if (process.arch === 'x64') { - try { - return require('./index.darwin-x64.node') - } catch (e) { - loadErrors.push(e) - } - try { - const binding = require('@databricks/databricks-sql-kernel-darwin-x64') - const bindingPackageVersion = require('@databricks/databricks-sql-kernel-darwin-x64/package.json').version - if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) - } - return binding - } catch (e) { - loadErrors.push(e) - } - } else if (process.arch === 'arm64') { - try { - return require('./index.darwin-arm64.node') - } catch (e) { - loadErrors.push(e) - } - try { - const binding = require('@databricks/databricks-sql-kernel-darwin-arm64') - const bindingPackageVersion = require('@databricks/databricks-sql-kernel-darwin-arm64/package.json').version - if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) - } - return binding - } catch (e) { - loadErrors.push(e) - } - } else { - loadErrors.push(new Error(`Unsupported architecture on macOS: ${process.arch}`)) - } - } else if (process.platform === 'freebsd') { - if (process.arch === 'x64') { - try { - return require('./index.freebsd-x64.node') - } catch (e) { - loadErrors.push(e) - } - try { - const binding = require('@databricks/databricks-sql-kernel-freebsd-x64') - const bindingPackageVersion = require('@databricks/databricks-sql-kernel-freebsd-x64/package.json').version - if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) - } - return binding - } catch (e) { - loadErrors.push(e) - } - } else if (process.arch === 'arm64') { - try { - return require('./index.freebsd-arm64.node') - } catch (e) { - loadErrors.push(e) - } - try { - const binding = require('@databricks/databricks-sql-kernel-freebsd-arm64') - const bindingPackageVersion = require('@databricks/databricks-sql-kernel-freebsd-arm64/package.json').version - if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) - } - return binding - } catch (e) { - loadErrors.push(e) - } - } else { - loadErrors.push(new Error(`Unsupported architecture on FreeBSD: ${process.arch}`)) - } - } else if (process.platform === 'linux') { - if (process.arch === 'x64') { - if (isMusl()) { +switch (platform) { + case 'android': + switch (arch) { + case 'arm64': + localFileExisted = existsSync(join(__dirname, 'index.android-arm64.node')) try { - return require('./index.linux-x64-musl.node') - } catch (e) { - loadErrors.push(e) - } - try { - const binding = require('@databricks/databricks-sql-kernel-linux-x64-musl') - const bindingPackageVersion = require('@databricks/databricks-sql-kernel-linux-x64-musl/package.json').version - if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + if (localFileExisted) { + nativeBinding = require('./index.android-arm64.node') + } else { + nativeBinding = require('@databricks/databricks-sql-kernel-android-arm64') } - return binding } catch (e) { - loadErrors.push(e) + loadError = e } - } else { + break + case 'arm': + localFileExisted = existsSync(join(__dirname, 'index.android-arm-eabi.node')) try { - return require('./index.linux-x64-gnu.node') - } catch (e) { - loadErrors.push(e) - } - try { - const binding = require('@databricks/databricks-sql-kernel-linux-x64-gnu') - const bindingPackageVersion = require('@databricks/databricks-sql-kernel-linux-x64-gnu/package.json').version - if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + if (localFileExisted) { + nativeBinding = require('./index.android-arm-eabi.node') + } else { + nativeBinding = require('@databricks/databricks-sql-kernel-android-arm-eabi') } - return binding - } catch (e) { - loadErrors.push(e) - } - } - } else if (process.arch === 'arm64') { - if (isMusl()) { - try { - return require('./index.linux-arm64-musl.node') } catch (e) { - loadErrors.push(e) + loadError = e } + break + default: + throw new Error(`Unsupported architecture on Android ${arch}`) + } + break + case 'win32': + switch (arch) { + case 'x64': + localFileExisted = existsSync( + join(__dirname, 'index.win32-x64-msvc.node') + ) try { - const binding = require('@databricks/databricks-sql-kernel-linux-arm64-musl') - const bindingPackageVersion = require('@databricks/databricks-sql-kernel-linux-arm64-musl/package.json').version - if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + if (localFileExisted) { + nativeBinding = require('./index.win32-x64-msvc.node') + } else { + nativeBinding = require('@databricks/databricks-sql-kernel-win32-x64-msvc') } - return binding - } catch (e) { - loadErrors.push(e) - } - } else { - try { - return require('./index.linux-arm64-gnu.node') } catch (e) { - loadErrors.push(e) + loadError = e } + break + case 'ia32': + localFileExisted = existsSync( + join(__dirname, 'index.win32-ia32-msvc.node') + ) try { - const binding = require('@databricks/databricks-sql-kernel-linux-arm64-gnu') - const bindingPackageVersion = require('@databricks/databricks-sql-kernel-linux-arm64-gnu/package.json').version - if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + if (localFileExisted) { + nativeBinding = require('./index.win32-ia32-msvc.node') + } else { + nativeBinding = require('@databricks/databricks-sql-kernel-win32-ia32-msvc') } - return binding } catch (e) { - loadErrors.push(e) + loadError = e } - } - } else if (process.arch === 'arm') { - if (isMusl()) { + break + case 'arm64': + localFileExisted = existsSync( + join(__dirname, 'index.win32-arm64-msvc.node') + ) try { - return require('./index.linux-arm-musleabihf.node') - } catch (e) { - loadErrors.push(e) - } - try { - const binding = require('@databricks/databricks-sql-kernel-linux-arm-musleabihf') - const bindingPackageVersion = require('@databricks/databricks-sql-kernel-linux-arm-musleabihf/package.json').version - if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + if (localFileExisted) { + nativeBinding = require('./index.win32-arm64-msvc.node') + } else { + nativeBinding = require('@databricks/databricks-sql-kernel-win32-arm64-msvc') } - return binding } catch (e) { - loadErrors.push(e) + loadError = e } + break + default: + throw new Error(`Unsupported architecture on Windows: ${arch}`) + } + break + case 'darwin': + localFileExisted = existsSync(join(__dirname, 'index.darwin-universal.node')) + try { + if (localFileExisted) { + nativeBinding = require('./index.darwin-universal.node') } else { - try { - return require('./index.linux-arm-gnueabihf.node') - } catch (e) { - loadErrors.push(e) - } - try { - const binding = require('@databricks/databricks-sql-kernel-linux-arm-gnueabihf') - const bindingPackageVersion = require('@databricks/databricks-sql-kernel-linux-arm-gnueabihf/package.json').version - if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) - } - return binding - } catch (e) { - loadErrors.push(e) - } + nativeBinding = require('@databricks/databricks-sql-kernel-darwin-universal') } - } else if (process.arch === 'loong64') { - if (isMusl()) { - try { - return require('./index.linux-loong64-musl.node') - } catch (e) { - loadErrors.push(e) - } - try { - const binding = require('@databricks/databricks-sql-kernel-linux-loong64-musl') - const bindingPackageVersion = require('@databricks/databricks-sql-kernel-linux-loong64-musl/package.json').version - if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) - } - return binding - } catch (e) { - loadErrors.push(e) - } - } else { + break + } catch {} + switch (arch) { + case 'x64': + localFileExisted = existsSync(join(__dirname, 'index.darwin-x64.node')) try { - return require('./index.linux-loong64-gnu.node') - } catch (e) { - loadErrors.push(e) - } - try { - const binding = require('@databricks/databricks-sql-kernel-linux-loong64-gnu') - const bindingPackageVersion = require('@databricks/databricks-sql-kernel-linux-loong64-gnu/package.json').version - if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + if (localFileExisted) { + nativeBinding = require('./index.darwin-x64.node') + } else { + nativeBinding = require('@databricks/databricks-sql-kernel-darwin-x64') } - return binding - } catch (e) { - loadErrors.push(e) - } - } - } else if (process.arch === 'riscv64') { - if (isMusl()) { - try { - return require('./index.linux-riscv64-musl.node') } catch (e) { - loadErrors.push(e) + loadError = e } + break + case 'arm64': + localFileExisted = existsSync( + join(__dirname, 'index.darwin-arm64.node') + ) try { - const binding = require('@databricks/databricks-sql-kernel-linux-riscv64-musl') - const bindingPackageVersion = require('@databricks/databricks-sql-kernel-linux-riscv64-musl/package.json').version - if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + if (localFileExisted) { + nativeBinding = require('./index.darwin-arm64.node') + } else { + nativeBinding = require('@databricks/databricks-sql-kernel-darwin-arm64') } - return binding } catch (e) { - loadErrors.push(e) + loadError = e } + break + default: + throw new Error(`Unsupported architecture on macOS: ${arch}`) + } + break + case 'freebsd': + if (arch !== 'x64') { + throw new Error(`Unsupported architecture on FreeBSD: ${arch}`) + } + localFileExisted = existsSync(join(__dirname, 'index.freebsd-x64.node')) + try { + if (localFileExisted) { + nativeBinding = require('./index.freebsd-x64.node') } else { - try { - return require('./index.linux-riscv64-gnu.node') - } catch (e) { - loadErrors.push(e) - } - try { - const binding = require('@databricks/databricks-sql-kernel-linux-riscv64-gnu') - const bindingPackageVersion = require('@databricks/databricks-sql-kernel-linux-riscv64-gnu/package.json').version - if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) - } - return binding - } catch (e) { - loadErrors.push(e) - } - } - } else if (process.arch === 'ppc64') { - try { - return require('./index.linux-ppc64-gnu.node') - } catch (e) { - loadErrors.push(e) + nativeBinding = require('@databricks/databricks-sql-kernel-freebsd-x64') } - try { - const binding = require('@databricks/databricks-sql-kernel-linux-ppc64-gnu') - const bindingPackageVersion = require('@databricks/databricks-sql-kernel-linux-ppc64-gnu/package.json').version - if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) - } - return binding - } catch (e) { - loadErrors.push(e) - } - } else if (process.arch === 's390x') { - try { - return require('./index.linux-s390x-gnu.node') - } catch (e) { - loadErrors.push(e) - } - try { - const binding = require('@databricks/databricks-sql-kernel-linux-s390x-gnu') - const bindingPackageVersion = require('@databricks/databricks-sql-kernel-linux-s390x-gnu/package.json').version - if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) - } - return binding - } catch (e) { - loadErrors.push(e) - } - } else { - loadErrors.push(new Error(`Unsupported architecture on Linux: ${process.arch}`)) + } catch (e) { + loadError = e } - } else if (process.platform === 'openharmony') { - if (process.arch === 'arm64') { - try { - return require('./index.openharmony-arm64.node') - } catch (e) { - loadErrors.push(e) - } - try { - const binding = require('@databricks/databricks-sql-kernel-openharmony-arm64') - const bindingPackageVersion = require('@databricks/databricks-sql-kernel-openharmony-arm64/package.json').version - if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) - } - return binding - } catch (e) { - loadErrors.push(e) - } - } else if (process.arch === 'x64') { - try { - return require('./index.openharmony-x64.node') - } catch (e) { - loadErrors.push(e) - } - try { - const binding = require('@databricks/databricks-sql-kernel-openharmony-x64') - const bindingPackageVersion = require('@databricks/databricks-sql-kernel-openharmony-x64/package.json').version - if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + break + case 'linux': + switch (arch) { + case 'x64': + if (isMusl()) { + localFileExisted = existsSync( + join(__dirname, 'index.linux-x64-musl.node') + ) + try { + if (localFileExisted) { + nativeBinding = require('./index.linux-x64-musl.node') + } else { + nativeBinding = require('@databricks/databricks-sql-kernel-linux-x64-musl') + } + } catch (e) { + loadError = e + } + } else { + localFileExisted = existsSync( + join(__dirname, 'index.linux-x64-gnu.node') + ) + try { + if (localFileExisted) { + nativeBinding = require('./index.linux-x64-gnu.node') + } else { + nativeBinding = require('@databricks/databricks-sql-kernel-linux-x64-gnu') + } + } catch (e) { + loadError = e + } } - return binding - } catch (e) { - loadErrors.push(e) - } - } else if (process.arch === 'arm') { - try { - return require('./index.openharmony-arm.node') - } catch (e) { - loadErrors.push(e) - } - try { - const binding = require('@databricks/databricks-sql-kernel-openharmony-arm') - const bindingPackageVersion = require('@databricks/databricks-sql-kernel-openharmony-arm/package.json').version - if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + break + case 'arm64': + if (isMusl()) { + localFileExisted = existsSync( + join(__dirname, 'index.linux-arm64-musl.node') + ) + try { + if (localFileExisted) { + nativeBinding = require('./index.linux-arm64-musl.node') + } else { + nativeBinding = require('@databricks/databricks-sql-kernel-linux-arm64-musl') + } + } catch (e) { + loadError = e + } + } else { + localFileExisted = existsSync( + join(__dirname, 'index.linux-arm64-gnu.node') + ) + try { + if (localFileExisted) { + nativeBinding = require('./index.linux-arm64-gnu.node') + } else { + nativeBinding = require('@databricks/databricks-sql-kernel-linux-arm64-gnu') + } + } catch (e) { + loadError = e + } } - return binding - } catch (e) { - loadErrors.push(e) - } - } else { - loadErrors.push(new Error(`Unsupported architecture on OpenHarmony: ${process.arch}`)) - } - } else { - loadErrors.push(new Error(`Unsupported OS: ${process.platform}, architecture: ${process.arch}`)) - } -} - -function createLoadErrorChain(errors) { - return errors.reduce((previous, current) => { - let message - try { - message = - current && typeof current.message === 'string' - ? current.message - : String(current) - } catch { - message = 'Unknown error' - } - const error = new Error(message) - error.cause = previous - return error - }, null) -} - -// NAPI_RS_FORCE_WASI is a tri-state flag: -// unset / any other value → native binding preferred, WASI is only a fallback -// 'true' → prefer WASI, but retain native as a lazy fallback -// 'error' → require WASI without initializing a native fallback -// Treating any non-empty string as truthy (the historical behavior) meant -// NAPI_RS_FORCE_WASI=false, NAPI_RS_FORCE_WASI=0, etc. inadvertently triggered -// the WASI path, causing ENOENT for packages shipped without a .wasi.cjs file. -// -// NAPI_RS_WASI_FLAVOR selects one exact generated flavor and implies strict -// WASI loading. It never crosses into another flavor or falls back to native. -const __napiWasiFlavors = ["wasm32-wasi"] -const __napiWasiFlavor = process.env.NAPI_RS_WASI_FLAVOR -const __napiWasiFlavorRequested = - typeof __napiWasiFlavor === 'string' && __napiWasiFlavor.length > 0 -if ( - __napiWasiFlavorRequested && - __napiWasiFlavors.indexOf(__napiWasiFlavor) === -1 -) { - throw new Error( - 'Unsupported WASI flavor "' + - __napiWasiFlavor + - '". Available flavors: ' + - __napiWasiFlavors.join(', '), - ) -} -const forceWasiError = process.env.NAPI_RS_FORCE_WASI === 'error' -const forceWasi = - process.env.NAPI_RS_FORCE_WASI === 'true' || - forceWasiError || - __napiWasiFlavorRequested - -if (!forceWasi) { - nativeBinding = requireNative() -} - -if (!nativeBinding || forceWasi) { - let wasiBinding = null - let wasiBindingLoaded = false - const wasiBindingErrors = [] - const __napiWasiResolveCandidate = (specifier, isPackage, localArtifacts) => { - try { - require.resolve(specifier) - } catch (resolveError) { - if (!resolveError || resolveError.code !== 'MODULE_NOT_FOUND') { - throw resolveError - } - if (isPackage) { - try { - require.resolve(specifier + '/package.json') - } catch (packageError) { - if (packageError && packageError.code === 'MODULE_NOT_FOUND') { - return resolveError + break + case 'arm': + if (isMusl()) { + localFileExisted = existsSync( + join(__dirname, 'index.linux-arm-musleabihf.node') + ) + try { + if (localFileExisted) { + nativeBinding = require('./index.linux-arm-musleabihf.node') + } else { + nativeBinding = require('@databricks/databricks-sql-kernel-linux-arm-musleabihf') + } + } catch (e) { + loadError = e + } + } else { + localFileExisted = existsSync( + join(__dirname, 'index.linux-arm-gnueabihf.node') + ) + try { + if (localFileExisted) { + nativeBinding = require('./index.linux-arm-gnueabihf.node') + } else { + nativeBinding = require('@databricks/databricks-sql-kernel-linux-arm-gnueabihf') + } + } catch (e) { + loadError = e } - // An exports restriction proves the package exists even when its - // package.json is not public. Preserve the root resolution failure. - throw resolveError } - // The package exists but its main/export target is broken. - throw resolveError - } - return resolveError - } - if (localArtifacts) { - let artifactError = null - for (let i = 0; i < localArtifacts.length; i++) { - try { - require.resolve(localArtifacts[i]) - return null - } catch (resolveError) { - if (!resolveError || resolveError.code !== 'MODULE_NOT_FOUND') { - throw resolveError + break + case 'riscv64': + if (isMusl()) { + localFileExisted = existsSync( + join(__dirname, 'index.linux-riscv64-musl.node') + ) + try { + if (localFileExisted) { + nativeBinding = require('./index.linux-riscv64-musl.node') + } else { + nativeBinding = require('@databricks/databricks-sql-kernel-linux-riscv64-musl') + } + } catch (e) { + loadError = e + } + } else { + localFileExisted = existsSync( + join(__dirname, 'index.linux-riscv64-gnu.node') + ) + try { + if (localFileExisted) { + nativeBinding = require('./index.linux-riscv64-gnu.node') + } else { + nativeBinding = require('@databricks/databricks-sql-kernel-linux-riscv64-gnu') + } + } catch (e) { + loadError = e } - artifactError = resolveError } - } - return artifactError - } - return null - } - if (!wasiBindingLoaded && (!__napiWasiFlavorRequested || __napiWasiFlavor === "wasm32-wasi")) { - let candidateError = null - let candidateFailed = false - try { - candidateError = __napiWasiResolveCandidate('./index.wasi.cjs', false, ["./index.wasm32-wasi.debug.wasm","./index.wasm32-wasi.wasm"]) - candidateFailed = candidateError !== null - if (!candidateFailed) { - wasiBinding = require('./index.wasi.cjs') - nativeBinding = wasiBinding - wasiBindingLoaded = true - } - } catch (err) { - candidateError = err - candidateFailed = true - } - if (candidateFailed) { - wasiBindingErrors.push(candidateError) - loadErrors.push(candidateError) - } - } - if (!wasiBindingLoaded && (!__napiWasiFlavorRequested || __napiWasiFlavor === "wasm32-wasi")) { - let candidateError = null - let candidateFailed = false - try { - candidateError = __napiWasiResolveCandidate('@databricks/databricks-sql-kernel-wasm32-wasi', true, undefined) - candidateFailed = candidateError !== null - if (!candidateFailed) { - if (process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - const bindingPackageVersion = require('@databricks/databricks-sql-kernel-wasm32-wasi/package.json').version - if (bindingPackageVersion !== '1.4.0') { - throw new Error(`WASI binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + break + case 's390x': + localFileExisted = existsSync( + join(__dirname, 'index.linux-s390x-gnu.node') + ) + try { + if (localFileExisted) { + nativeBinding = require('./index.linux-s390x-gnu.node') + } else { + nativeBinding = require('@databricks/databricks-sql-kernel-linux-s390x-gnu') } + } catch (e) { + loadError = e } - wasiBinding = require('@databricks/databricks-sql-kernel-wasm32-wasi') - nativeBinding = wasiBinding - wasiBindingLoaded = true - } - } catch (err) { - candidateError = err - candidateFailed = true + break + default: + throw new Error(`Unsupported architecture on Linux: ${arch}`) } - if (candidateFailed) { - wasiBindingErrors.push(candidateError) - loadErrors.push(candidateError) - } - } - if ( - !wasiBindingLoaded && - forceWasi && - !forceWasiError && - !__napiWasiFlavorRequested - ) { - nativeBinding = requireNative() - } - if ((forceWasiError || __napiWasiFlavorRequested) && !wasiBindingLoaded) { - const error = new Error( - __napiWasiFlavorRequested - ? 'WASI binding for flavor "' + __napiWasiFlavor + '" not found' - : 'WASI binding not found and NAPI_RS_FORCE_WASI is set to error', - ) - error.cause = createLoadErrorChain(wasiBindingErrors) - throw error - } + break + default: + throw new Error(`Unsupported OS: ${platform}, architecture: ${arch}`) } if (!nativeBinding) { - if (loadErrors.length > 0) { - const error = new Error( - `Cannot find native binding. ` + - `npm has a bug related to optional dependencies (https://github.com/npm/cli/issues/4828). ` + - 'Please try `npm i` again after removing both package-lock.json and node_modules directory.', - ) - // assign instead of the `new Error(message, { cause })` options form, - // which Node < 16.9 silently ignores - error.cause = createLoadErrorChain(loadErrors) - throw error + if (loadError) { + throw loadError } throw new Error(`Failed to load native binding`) } -module.exports = nativeBinding -module.exports.AsyncResultHandle = nativeBinding.AsyncResultHandle -module.exports.AsyncStatement = nativeBinding.AsyncStatement -module.exports.CancellableExecution = nativeBinding.CancellableExecution -module.exports.Connection = nativeBinding.Connection -module.exports.Statement = nativeBinding.Statement -module.exports.AuthMode = nativeBinding.AuthMode -module.exports.initKernelLogging = nativeBinding.initKernelLogging -module.exports.kernelLoggingStats = nativeBinding.kernelLoggingStats -module.exports.openSession = nativeBinding.openSession -module.exports.setKernelLogLevel = nativeBinding.setKernelLogLevel -module.exports.version = nativeBinding.version +const { AsyncStatement, AsyncResultHandle, CancellableExecution, Connection, AuthMode, openSession, initKernelLogging, kernelLoggingStats, setKernelLogLevel, Statement, version } = nativeBinding + +module.exports.AsyncStatement = AsyncStatement +module.exports.AsyncResultHandle = AsyncResultHandle +module.exports.CancellableExecution = CancellableExecution +module.exports.Connection = Connection +module.exports.AuthMode = AuthMode +module.exports.openSession = openSession +module.exports.initKernelLogging = initKernelLogging +module.exports.kernelLoggingStats = kernelLoggingStats +module.exports.setKernelLogLevel = setKernelLogLevel +module.exports.Statement = Statement +module.exports.version = version From ebb8204b36951b751dd837b2c41ced8c821b2d94 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Wed, 11 Nov 2026 23:08:20 +0000 Subject: [PATCH 05/39] fix(volume): preserve download destinations on transfer failure Signed-off-by: Aakash Saravanan --- Cargo.toml | 3 +- adbc/Cargo.lock | 1 + adbc/tests/live.rs | 82 +++++++++++++++++++++++++++++++++++++++++ napi/Cargo.lock | 39 ++++++++++++++++++++ pyo3/Cargo.lock | 39 ++++++++++++++++++++ src/statement/volume.rs | 73 ++++++++++++++++++++++++++++++------ 6 files changed, 225 insertions(+), 12 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 19951cdf..37414939 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -145,10 +145,11 @@ zeroize = "1.9" jsonwebtoken = { version = "9", default-features = false, features = ["use_pem"] } # JWT signing (RS256/384/512, PS256/384/512, ES256/384); use_pem = PEM key loading (adds pem + simple_asn1, no TLS) pkcs8 = { version = "0.10", features = ["encryption", "pem", "std"] } # PKCS#8 PEM parsing + PBES2 passphrase decryption +tempfile = "3" + [dev-dependencies] tokio = { version = "1", features = ["rt-multi-thread", "macros", "net", "io-util"] } wiremock = "0.6" -tempfile = "3" log = "0.4" # Generate JWT test keys in-process to avoid PEM fixtures and an external # `openssl` dependency. `ring` already backs runtime JWT signing. diff --git a/adbc/Cargo.lock b/adbc/Cargo.lock index 37956eeb..7a9bfb6b 100644 --- a/adbc/Cargo.lock +++ b/adbc/Cargo.lock @@ -678,6 +678,7 @@ dependencies = [ "serde", "serde_json", "sha2 0.11.1", + "tempfile", "thiserror 2.0.21", "tokio", "tokio-util", diff --git a/adbc/tests/live.rs b/adbc/tests/live.rs index 54f8deec..75b6054f 100644 --- a/adbc/tests/live.rs +++ b/adbc/tests/live.rs @@ -366,3 +366,85 @@ fn metadata_statement_catalog_underscore_escaping_is_configurable() { assert_eq!(actual_catalogs, expected_catalogs); } } + +#[test] +#[ignore = "requires a writable Unity Catalog catalog and live warehouse"] +fn volume_files_round_trip_and_remove() { + let catalog = env::var("DATABRICKS_VOLUME_TEST_CATALOG").unwrap_or_else(|_| "main".into()); + let unique = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos(); + let schema = format!("volume_{unique}"); + let namespace = format!("`{}`.`{schema}`", catalog.replace('`', "``")); + let directory = env::temp_dir().join(&schema); + fs::create_dir(&directory).unwrap(); + let source = directory.join("input.bin"); + let destination = directory.join("output.bin"); + let payload: Vec = (0..=255).cycle().take(1_048_576).collect(); + fs::write(&source, &payload).unwrap(); + let remote = format!("/Volumes/{catalog}/{schema}/files/input.bin"); + let literal = |value: &str| format!("'{}'", value.replace('\\', "\\\\").replace('\'', "\\'")); + let mut connection = live_connection(); + let mut statement = connection.new_statement().unwrap(); + statement + .set_sql_query(format!("CREATE SCHEMA {namespace}")) + .unwrap(); + statement.execute_update().unwrap(); + let result = (|| -> Result<(), Box> { + statement.set_sql_query(format!("CREATE VOLUME {namespace}.files"))?; + statement.execute_update()?; + let option = + OptionStatement::Other("adbc.databricks.statement.staging_allowed_local_paths".into()); + if statement + .set_option(option.clone(), OptionValue::String("null".into())) + .is_ok() + { + return Err("invalid path list was accepted".into()); + } + statement.set_option( + option, + OptionValue::String(serde_json::to_string(&vec![directory.to_str().unwrap()])?), + )?; + for sql in [ + format!( + "PUT {} INTO {} OVERWRITE", + literal(source.to_str().unwrap()), + literal(&remote) + ), + format!( + "GET {} TO {}", + literal(&remote), + literal(destination.to_str().unwrap()) + ), + ] { + statement.set_sql_query(sql)?; + let batches = statement.execute()?.collect::, _>>()?; + if batches.iter().any(|batch| batch.num_rows() != 0) { + return Err("completed transfer retained instruction rows".into()); + } + } + if fs::read(&destination)? != payload { + return Err("downloaded bytes differ".into()); + } + for _ in 0..2 { + statement.set_sql_query(format!("REMOVE {}", literal(&remote)))?; + statement.execute_update()?; + } + statement.set_sql_query(format!( + "GET {} TO {}", + literal(&remote), + literal(destination.to_str().unwrap()) + ))?; + if statement.execute().is_ok() { + return Err("download succeeded after removal".into()); + } + Ok(()) + })(); + statement + .set_sql_query(format!("DROP SCHEMA {namespace} CASCADE")) + .unwrap(); + statement.execute_update().unwrap(); + fs::remove_dir_all(directory).unwrap(); + result.unwrap(); +} diff --git a/napi/Cargo.lock b/napi/Cargo.lock index 303fb234..a7fd477a 100644 --- a/napi/Cargo.lock +++ b/napi/Cargo.lock @@ -638,6 +638,7 @@ dependencies = [ "serde", "serde_json", "sha2 0.11.0", + "tempfile", "thiserror 2.0.19", "tokio", "tokio-util", @@ -796,6 +797,12 @@ dependencies = [ "pin-project-lite", ] +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + [[package]] name = "find-msvc-tools" version = "0.1.9" @@ -1493,6 +1500,12 @@ dependencies = [ "libc", ] +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + [[package]] name = "litemap" version = "0.8.2" @@ -2200,6 +2213,19 @@ dependencies = [ "semver", ] +[[package]] +name = "rustix" +version = "1.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.61.2", +] + [[package]] name = "rustls" version = "0.23.46" @@ -2546,6 +2572,19 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7b2093cf4c8eb1e67749a6762251bc9cd836b6fc171623bd0a9d324d37af2417" +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.4.3", + "once_cell", + "rustix", + "windows-sys 0.61.2", +] + [[package]] name = "thiserror" version = "1.0.69" diff --git a/pyo3/Cargo.lock b/pyo3/Cargo.lock index 30946d3c..357cb953 100644 --- a/pyo3/Cargo.lock +++ b/pyo3/Cargo.lock @@ -634,6 +634,7 @@ dependencies = [ "serde", "serde_json", "sha2 0.11.0", + "tempfile", "thiserror 2.0.19", "tokio", "tokio-util", @@ -769,6 +770,12 @@ dependencies = [ "pin-project-lite", ] +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + [[package]] name = "find-msvc-tools" version = "0.1.9" @@ -1423,6 +1430,12 @@ dependencies = [ "libc", ] +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + [[package]] name = "litemap" version = "0.8.2" @@ -2112,6 +2125,19 @@ dependencies = [ "semver", ] +[[package]] +name = "rustix" +version = "1.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.61.2", +] + [[package]] name = "rustls" version = "0.23.46" @@ -2464,6 +2490,19 @@ version = "0.13.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "adb6935a6f5c20170eeceb1a3835a49e12e19d792f6dd344ccc76a985ca5a6ca" +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.4.3", + "once_cell", + "rustix", + "windows-sys 0.61.2", +] + [[package]] name = "thiserror" version = "1.0.69" diff --git a/src/statement/volume.rs b/src/statement/volume.rs index 9421c0e3..fc740334 100644 --- a/src/statement/volume.rs +++ b/src/statement/volume.rs @@ -205,7 +205,13 @@ async fn transfer( }; let parsed = reqwest::Url::parse(url) .map_err(|_| Error::invalid_state().message("Invalid file transfer URL"))?; - if !matches!(parsed.scheme(), "https" | "http") { + let loopback = parsed.host_str().is_some_and(|host| { + host == "localhost" + || host + .parse::() + .is_ok_and(|ip| ip.is_loopback()) + }); + if parsed.scheme() != "https" && !(parsed.scheme() == "http" && loopback) { return Err(Error::invalid_state().message("Invalid file transfer URL scheme")); } let local = if operation == "REMOVE" { @@ -225,20 +231,37 @@ async fn transfer( ); } if operation == "GET" { - let mut file = tokio::fs::File::create(local.as_ref().unwrap()) - .await - .map_err(file_error)?; + let destination = local.as_ref().unwrap(); + let temporary = + tempfile::NamedTempFile::new_in(destination.parent().unwrap()).map_err(file_error)?; + let mut file = tokio::fs::File::from_std(temporary.reopen().map_err(file_error)?); let mut body = response.bytes_stream(); while let Some(bytes) = body.next().await { - let bytes = bytes - .map_err(|_| Error::new(ErrorCode::NetworkError, "File download interrupted"))?; + let bytes = bytes.map_err(transport_error)?; file.write_all(&bytes).await.map_err(file_error)?; } file.flush().await.map_err(file_error)?; + drop(file); + temporary + .persist(destination) + .map_err(|error| file_error(error.error))?; } Ok(()) } +fn transport_error(error: reqwest::Error) -> Error { + let message = if error.is_timeout() { + "File transfer timed out" + } else if error.is_connect() { + "File transfer connection failed" + } else if error.is_body() || error.is_decode() { + "File download interrupted" + } else { + "File transfer request failed" + }; + Error::new(ErrorCode::NetworkError, message) +} + async fn send_transfer( client: &DatabricksHttpClient, method: Method, @@ -296,13 +319,11 @@ async fn send_transfer( Err(error) => (strategy.is_retryable_error(error), None), }; if !retryable || attempt == config.max_retries { - return response - .map_err(|_| Error::new(ErrorCode::NetworkError, "File transfer request failed")); + return response.map_err(transport_error); } let delay = calculate_backoff(&config, attempt, retry_after); if started.elapsed().saturating_add(delay) >= config.overall_timeout { - return response - .map_err(|_| Error::new(ErrorCode::NetworkError, "File transfer request failed")); + return response.map_err(transport_error); } tokio::time::sleep(delay).await; } @@ -521,7 +542,9 @@ mod tests { use crate::client::retry::{RequestCategory, RetryConfig}; use std::time::Duration; use tokio::io::AsyncReadExt; - for (budget, succeeds) in [(1000, true), (40, false)] { + for (budget, succeeds, existing) in + [(1000, true, false), (40, false, true), (40, false, false)] + { let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); let address = listener.local_addr().unwrap(); let server = tokio::spawn(async move { @@ -553,6 +576,9 @@ mod tests { .unwrap(); let dir = tempfile::tempdir().unwrap(); let file = dir.path().join("download"); + if existing { + std::fs::write(&file, b"original").unwrap(); + } let result = transfer( &http, "GET", @@ -567,11 +593,36 @@ mod tests { assert_eq!(std::fs::read(&file).unwrap(), b"data"); } else { assert_eq!(result.unwrap_err().code, ErrorCode::NetworkError); + if existing { + assert_eq!(std::fs::read(&file).unwrap(), b"original"); + } else { + assert!(!file.exists()); + } } + assert_eq!( + std::fs::read_dir(dir.path()).unwrap().count(), + usize::from(succeeds || existing) + ); server.await.unwrap(); } } + #[tokio::test] + async fn rejects_plaintext_storage_host() { + let error = transfer( + &client(), + "REMOVE", + "http://storage.example/file?signature=secret", + &HashMap::new(), + None, + &[], + ) + .await + .unwrap_err(); + assert!(error.message.contains("scheme")); + assert!(!error.message.contains("secret")); + } + #[test] fn unresolvable_allowed_root_does_not_hide_later_root() { let dir = tempfile::tempdir().unwrap(); From 02283500d50e1bcd61007e0cf04a7e1e3d16ea86 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Wed, 11 Nov 2026 23:21:48 +0000 Subject: [PATCH 06/39] fix(volume): preserve file modes and reject root destinations Signed-off-by: Aakash Saravanan --- Cargo.lock | 12 ++--- adbc/Cargo.lock | 10 ++--- src/statement/spec.rs | 3 +- src/statement/volume.rs | 97 +++++++++++++++++++++++++++++++++++++++-- 4 files changed, 107 insertions(+), 15 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index b47213ce..a6b0620f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -814,7 +814,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -2135,7 +2135,7 @@ dependencies = [ "once_cell", "socket2", "tracing", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -2383,15 +2383,15 @@ dependencies = [ [[package]] name = "rustix" -version = "1.1.4" +version = "1.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" dependencies = [ "bitflags", "errno", "libc", "linux-raw-sys", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -2766,7 +2766,7 @@ dependencies = [ "getrandom 0.4.3", "once_cell", "rustix", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] diff --git a/adbc/Cargo.lock b/adbc/Cargo.lock index 7a9bfb6b..3d8cbee0 100644 --- a/adbc/Cargo.lock +++ b/adbc/Cargo.lock @@ -792,7 +792,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -2170,15 +2170,15 @@ dependencies = [ [[package]] name = "rustix" -version = "1.1.5" +version = "1.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" dependencies = [ "bitflags", "errno", "libc", "linux-raw-sys", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -2508,7 +2508,7 @@ dependencies = [ "getrandom 0.4.3", "once_cell", "rustix", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] diff --git a/src/statement/spec.rs b/src/statement/spec.rs index e4f9fc2b..836e3b18 100644 --- a/src/statement/spec.rs +++ b/src/statement/spec.rs @@ -225,7 +225,8 @@ pub struct StatementSpec { /// Local paths permitted for SQL file transfers. `None` leaves transfer /// instructions available to a caller that handles them itself. An empty list - /// enables REMOVE while denying local file access. + /// enables REMOVE while denying local file access. Transfers use the storage + /// retry overall deadline, which defaults to 15 minutes. pub staging_allowed_local_paths: Option>, /// Preserve the instruction row after a successful transfer for APIs diff --git a/src/statement/volume.rs b/src/statement/volume.rs index fc740334..eb1620d4 100644 --- a/src/statement/volume.rs +++ b/src/statement/volume.rs @@ -232,8 +232,16 @@ async fn transfer( } if operation == "GET" { let destination = local.as_ref().unwrap(); - let temporary = - tempfile::NamedTempFile::new_in(destination.parent().unwrap()).map_err(file_error)?; + let parent = destination.parent().ok_or_else(|| { + Error::invalid_argument().message("Download destination must be a file") + })?; + let mut builder = tempfile::Builder::new(); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + builder.permissions(std::fs::Permissions::from_mode(0o666)); + } + let temporary = builder.tempfile_in(parent).map_err(file_error)?; let mut file = tokio::fs::File::from_std(temporary.reopen().map_err(file_error)?); let mut body = response.bytes_stream(); while let Some(bytes) = body.next().await { @@ -242,6 +250,14 @@ async fn transfer( } file.flush().await.map_err(file_error)?; drop(file); + match std::fs::metadata(destination) { + Ok(metadata) => temporary + .as_file() + .set_permissions(metadata.permissions()) + .map_err(file_error)?, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} + Err(error) => return Err(file_error(error)), + } temporary .persist(destination) .map_err(|error| file_error(error.error))?; @@ -259,7 +275,10 @@ fn transport_error(error: reqwest::Error) -> Error { } else { "File transfer request failed" }; - Error::new(ErrorCode::NetworkError, message) + Error::new(ErrorCode::NetworkError, message).with_cause(Error::new( + ErrorCode::NetworkError, + format!("{:?}", error.without_url()), + )) } async fn send_transfer( @@ -413,6 +432,62 @@ mod tests { assert_eq!(request.headers["x-file-header"], "value"); } + #[cfg(unix)] + #[tokio::test] + async fn download_preserves_file_permissions_and_rejects_root() { + use std::os::unix::fs::PermissionsExt; + let server = MockServer::start().await; + Mock::given(method("GET")) + .respond_with(ResponseTemplate::new(200).set_body_bytes(b"contents")) + .mount(&server) + .await; + let dir = tempfile::tempdir().unwrap(); + let destination = dir.path().join("download"); + let control = dir.path().join("control"); + std::fs::write(&control, b"").unwrap(); + let roots = vec![dir.path().to_str().unwrap().into()]; + for existing in [false, true] { + if existing { + std::fs::set_permissions(&destination, std::fs::Permissions::from_mode(0o640)) + .unwrap(); + } + transfer( + &client(), + "GET", + &server.uri(), + &HashMap::new(), + destination.to_str(), + &roots, + ) + .await + .unwrap(); + let expected = if existing { + 0o640 + } else { + std::fs::metadata(&control).unwrap().permissions().mode() & 0o777 + }; + assert_eq!( + std::fs::metadata(&destination) + .unwrap() + .permissions() + .mode() + & 0o777, + expected + ); + } + let error = transfer( + &client(), + "GET", + &server.uri(), + &HashMap::new(), + Some("/"), + &["/".into()], + ) + .await + .unwrap_err(); + assert_eq!(error.code, ErrorCode::InvalidArgument); + } + #[tokio::test] async fn streams_upload_and_accepts_missing_remove() { let server = MockServer::start().await; @@ -607,6 +682,22 @@ mod tests { } } + #[tokio::test] + async fn transport_cause_omits_signed_url() { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + drop(listener); + let error = reqwest::Client::new() + .get(format!("http://{address}/file?signature=secret")) + .send() + .await + .unwrap_err(); + let error = transport_error(error); + assert!(error.cause.is_some()); + assert!(!format!("{error:?}").contains("signature")); + assert!(!format!("{error:?}").contains("secret")); + } + #[tokio::test] async fn rejects_plaintext_storage_host() { let error = transfer( From 2f317d97212f00d73b89d947f5261a2145ea7a10 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Wed, 11 Nov 2026 23:35:34 +0000 Subject: [PATCH 07/39] fix(volume): validate destinations and reset reused statements Signed-off-by: Aakash Saravanan --- Cargo.lock | 6 +-- adbc/Cargo.lock | 6 +-- adbc/README.md | 1 + adbc/src/statement.rs | 17 ++++--- adbc/tests/live.rs | 26 ++++++++-- include/databricks_kernel.h | 3 +- pyo3/src/statement.rs | 6 +-- src/c_abi/statement.rs | 11 ++-- src/statement/spec.rs | 2 + src/statement/volume.rs | 40 +++++++++------ tests/v0_async_execute_wiremock.rs | 81 ++++++++++++++++++++++++++++++ 11 files changed, 157 insertions(+), 42 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index a6b0620f..ed208acb 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -814,7 +814,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -2391,7 +2391,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -2766,7 +2766,7 @@ dependencies = [ "getrandom 0.4.3", "once_cell", "rustix", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] diff --git a/adbc/Cargo.lock b/adbc/Cargo.lock index 3d8cbee0..55f52d62 100644 --- a/adbc/Cargo.lock +++ b/adbc/Cargo.lock @@ -792,7 +792,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -2178,7 +2178,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -2508,7 +2508,7 @@ dependencies = [ "getrandom 0.4.3", "once_cell", "rustix", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] diff --git a/adbc/README.md b/adbc/README.md index 3c343768..fe0717a2 100644 --- a/adbc/README.md +++ b/adbc/README.md @@ -133,6 +133,7 @@ of local paths, for example `["/tmp/transfers"]`, and enables SQL PUT, GET, and REMOVE file transfers. An empty array permits REMOVE and denies local file access. Successful transfers return no instruction rows. Without the option, results remain available to callers that handle transfers themselves. +Set the option to JSON `null` to restore that mode on a reused statement. Statement options include positional or named parameter style, query tags, the portable `adbc.apache.statement.query_timeout_s` client deadline (with `0` diff --git a/adbc/src/statement.rs b/adbc/src/statement.rs index 90defb9d..22d5b746 100644 --- a/adbc/src/statement.rs +++ b/adbc/src/statement.rs @@ -471,14 +471,15 @@ impl Statement { } match key { "adbc.databricks.statement.staging_allowed_local_paths" => { - let paths = serde_json::from_str::>(&expect_string(value, key)?) - .map_err(|_| { - adbc_error( - "Expected a JSON array of allowed local paths", - Status::InvalidArguments, - ) - })?; - self.inner()?.spec().staging_allowed_local_paths = Some(paths); + let paths = + serde_json::from_str::>>(&expect_string(value, key)?) + .map_err(|_| { + adbc_error( + "Expected a JSON array of allowed local paths or null", + Status::InvalidArguments, + ) + })?; + self.inner()?.spec().staging_allowed_local_paths = paths; Ok(()) } ENABLE_DIRECT_RESULTS_OPTION => { diff --git a/adbc/tests/live.rs b/adbc/tests/live.rs index 75b6054f..ee7d5822 100644 --- a/adbc/tests/live.rs +++ b/adbc/tests/live.rs @@ -397,15 +397,14 @@ fn volume_files_round_trip_and_remove() { let option = OptionStatement::Other("adbc.databricks.statement.staging_allowed_local_paths".into()); if statement - .set_option(option.clone(), OptionValue::String("null".into())) + .set_option(option.clone(), OptionValue::String("{}".into())) .is_ok() { return Err("invalid path list was accepted".into()); } - statement.set_option( - option, - OptionValue::String(serde_json::to_string(&vec![directory.to_str().unwrap()])?), - )?; + statement.set_option(option.clone(), OptionValue::String("null".into()))?; + let paths = serde_json::to_string(&vec![directory.to_str().unwrap()])?; + statement.set_option(option.clone(), OptionValue::String(paths.clone()))?; for sql in [ format!( "PUT {} INTO {} OVERWRITE", @@ -427,6 +426,23 @@ fn volume_files_round_trip_and_remove() { if fs::read(&destination)? != payload { return Err("downloaded bytes differ".into()); } + fs::remove_file(&destination)?; + statement.set_option(option.clone(), OptionValue::String("null".into()))?; + statement.set_sql_query(format!( + "GET {} TO {}", + literal(&remote), + literal(destination.to_str().unwrap()) + ))?; + let rows: usize = statement + .execute()? + .collect::, _>>()? + .iter() + .map(|batch| batch.num_rows()) + .sum(); + if rows != 1 || destination.exists() { + return Err("clearing the option did not restore raw instructions".into()); + } + statement.set_option(option, OptionValue::String(paths))?; for _ in 0..2 { statement.set_sql_query(format!("REMOVE {}", literal(&remote)))?; statement.execute_update()?; diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h index f1a40844..0fe272f7 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -688,7 +688,8 @@ KernelStatusCode kernel_session_rollback(kernel_session_t* session); * so a reused statement handle starts each query with a fresh parameter set. */ KernelStatusCode kernel_statement_set_sql(kernel_statement_t* stmt, const char* sql); -/** Configure allowed local paths; retain_result keeps instructions after transfer. */ +/** Configure allowed local paths; null restores caller-managed transfers. + * retain_result keeps instructions after transfer. */ KernelStatusCode kernel_statement_set_staging_allowed_local_paths( kernel_statement_t* stmt, const char* paths_json, bool retain_result); diff --git a/pyo3/src/statement.rs b/pyo3/src/statement.rs index de89668f..dc43e64a 100644 --- a/pyo3/src/statement.rs +++ b/pyo3/src/statement.rs @@ -66,10 +66,10 @@ impl Statement { Ok(()) } - /// Set the local paths permitted for SQL PUT and GET transfers. - fn set_staging_allowed_local_paths(&mut self, paths: Vec) -> PyResult<()> { + /// Set permitted local paths; ``None`` restores caller-managed transfers. + fn set_staging_allowed_local_paths(&mut self, paths: Option>) -> PyResult<()> { let inner = alive_mut!(self, "Statement"); - inner.stmt.spec().staging_allowed_local_paths = Some(paths); + inner.stmt.spec().staging_allowed_local_paths = paths; Ok(()) } diff --git a/src/c_abi/statement.rs b/src/c_abi/statement.rs index 48ac0e44..027c08df 100644 --- a/src/c_abi/statement.rs +++ b/src/c_abi/statement.rs @@ -163,7 +163,7 @@ pub enum KernelStatementStatusKind { /// `retain_result` keeps the instruction row readable after a successful transfer. /// /// # Safety -/// `stmt` must be live and `paths_json` must be a NUL-terminated UTF-8 string. +/// `stmt` must be live; non-null `paths_json` must be NUL-terminated UTF-8. #[no_mangle] pub unsafe extern "C" fn kernel_statement_set_staging_allowed_local_paths( stmt: *mut kernel_statement_t, @@ -172,15 +172,16 @@ pub unsafe extern "C" fn kernel_statement_set_staging_allowed_local_paths( ) -> KernelStatusCode { with_statement(stmt, |stmt| { if paths_json.is_null() { - return Err(Error::invalid_argument().message("paths_json must not be null")); + stmt.spec().staging_allowed_local_paths = None; + return Ok(()); } let json = CStr::from_ptr(paths_json) .to_str() .map_err(|_| Error::invalid_argument().message("paths_json must be UTF-8"))?; - let paths: Vec = serde_json::from_str(json).map_err(|_| { - Error::invalid_argument().message("paths_json must be an array of paths") + let paths: Option> = serde_json::from_str(json).map_err(|_| { + Error::invalid_argument().message("paths_json must be an array of paths or null") })?; - stmt.spec().staging_allowed_local_paths = Some(paths); + stmt.spec().staging_allowed_local_paths = paths; stmt.spec().retain_volume_operation_result = retain_result; Ok(()) }) diff --git a/src/statement/spec.rs b/src/statement/spec.rs index 836e3b18..2d2ed285 100644 --- a/src/statement/spec.rs +++ b/src/statement/spec.rs @@ -227,6 +227,8 @@ pub struct StatementSpec { /// instructions available to a caller that handles them itself. An empty list /// enables REMOVE while denying local file access. Transfers use the storage /// retry overall deadline, which defaults to 15 minutes. + /// Completion, including a failure after retries, is final and shared by all + /// readers of an execution. Re-execute the SQL to start a new transfer attempt. pub staging_allowed_local_paths: Option>, /// Preserve the instruction row after a successful transfer for APIs diff --git a/src/statement/volume.rs b/src/statement/volume.rs index eb1620d4..237a74ca 100644 --- a/src/statement/volume.rs +++ b/src/statement/volume.rs @@ -219,6 +219,13 @@ async fn transfer( } else { Some(allowed_path(local_file, paths)?) }; + if operation == "GET" + && local + .as_ref() + .is_some_and(|path| path.parent().is_none() || path.is_dir()) + { + return Err(Error::invalid_argument().message("Download destination must be a file")); + } let response = send_transfer(client, method, parsed, headers, local.as_deref()).await?; if !response.status().is_success() && !(operation == "REMOVE" && response.status().as_u16() == 404) @@ -235,12 +242,14 @@ async fn transfer( let parent = destination.parent().ok_or_else(|| { Error::invalid_argument().message("Download destination must be a file") })?; - let mut builder = tempfile::Builder::new(); + let builder = tempfile::Builder::new(); #[cfg(unix)] - { + let builder = { use std::os::unix::fs::PermissionsExt; + let mut builder = builder; builder.permissions(std::fs::Permissions::from_mode(0o666)); - } + builder + }; let temporary = builder.tempfile_in(parent).map_err(file_error)?; let mut file = tokio::fs::File::from_std(temporary.reopen().map_err(file_error)?); let mut body = response.bytes_stream(); @@ -439,6 +448,7 @@ mod tests { let server = MockServer::start().await; Mock::given(method("GET")) .respond_with(ResponseTemplate::new(200).set_body_bytes(b"contents")) + .expect(2) .mount(&server) .await; let dir = tempfile::tempdir().unwrap(); @@ -475,17 +485,19 @@ mod tests { expected ); } - let error = transfer( - &client(), - "GET", - &server.uri(), - &HashMap::new(), - Some("/"), - &["/".into()], - ) - .await - .unwrap_err(); - assert_eq!(error.code, ErrorCode::InvalidArgument); + for destination in [Path::new("/"), dir.path()] { + let error = transfer( + &client(), + "GET", + &server.uri(), + &HashMap::new(), + destination.to_str(), + &["/".into()], + ) + .await + .unwrap_err(); + assert_eq!(error.code, ErrorCode::InvalidArgument); + } } #[tokio::test] diff --git a/tests/v0_async_execute_wiremock.rs b/tests/v0_async_execute_wiremock.rs index 6900d7d7..7d8ef644 100644 --- a/tests/v0_async_execute_wiremock.rs +++ b/tests/v0_async_execute_wiremock.rs @@ -2331,3 +2331,84 @@ async fn file_transfer_completion_is_shared_by_independent_readers() { owner.close().await.unwrap(); session.close().await.unwrap(); } + +#[tokio::test] +async fn sync_and_direct_transfers_complete_and_preserve_error_context() { + use arrow_array::StringArray; + use databricks_sql_kernel::DirectStatement; + for direct in [false, true] { + for denied in [false, true] { + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_delete_session(&server).await; + mount_close_any_statement(&server).await; + Mock::given(method("GET")) + .and(path("/storage/file")) + .respond_with(ResponseTemplate::new(200).set_body_bytes(b"download")) + .expect(if denied { 0 } else { 1 }) + .mount(&server) + .await; + let directory = tempfile::tempdir().unwrap(); + let destination = directory.path().join("download"); + let batch = RecordBatch::try_from_iter(vec![ + ( + "operation", + Arc::new(StringArray::from(vec!["GET"])) as arrow_array::ArrayRef, + ), + ( + "url", + Arc::new(StringArray::from(vec![format!( + "{}/storage/file", + server.uri() + )])), + ), + ("headers", Arc::new(StringArray::from(vec!["{}"]))), + ( + "local", + Arc::new(StringArray::from(vec![destination.to_str().unwrap()])), + ), + ]) + .unwrap(); + let mut body: serde_json::Value = + serde_json::from_str(&succeeded_inline_body("transfer", &batch)).unwrap(); + body["manifest"]["is_volume_operation"] = json!(true); + mount_submit(&server, body.to_string()).await; + let session = open_session(&server).await; + let mut statement = session.statement(); + statement + .spec() + .sql("GET '/Volumes/c/s/v/file' TO '/tmp/download'"); + statement.spec().staging_allowed_local_paths = Some(if denied { + vec![] + } else { + vec![directory.path().to_str().unwrap().into()] + }); + let result = if direct { + match statement.execute_direct().await { + Ok(DirectStatement::Completed(executed)) => Ok(executed), + Ok(DirectStatement::Running(_)) => panic!("expected inline completion"), + Err(error) => Err(error), + } + } else { + statement.execute().await + }; + if denied { + let error = result.err().expect("denied transfer"); + assert_eq!(error.error_code.as_deref(), Some("FILE_TRANSFER_ERROR")); + assert_eq!(error.query_id.as_deref(), Some("transfer")); + assert!(!destination.exists()); + } else { + let mut executed = result.unwrap(); + assert!(executed + .result_stream_mut() + .next_batch() + .await + .unwrap() + .is_none()); + assert_eq!(std::fs::read(&destination).unwrap(), b"download"); + executed.close().await.unwrap(); + } + session.close().await.unwrap(); + } + } +} From 95f294c8c2c825440191af9f58a9b6071aa68408 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Wed, 11 Nov 2026 23:46:00 +0000 Subject: [PATCH 08/39] fix(volume): preserve error context and normalize option clearing Signed-off-by: Aakash Saravanan --- Cargo.lock | 2 +- src/c_abi/statement.rs | 89 +++++++++++++++++++++++++---- src/statement/spec.rs | 2 + src/statement/volume.rs | 123 +++++++++++++++++++++++++--------------- 4 files changed, 159 insertions(+), 57 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index ed208acb..682745ea 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2135,7 +2135,7 @@ dependencies = [ "once_cell", "socket2", "tracing", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] diff --git a/src/c_abi/statement.rs b/src/c_abi/statement.rs index 027c08df..dc35aafd 100644 --- a/src/c_abi/statement.rs +++ b/src/c_abi/statement.rs @@ -171,16 +171,16 @@ pub unsafe extern "C" fn kernel_statement_set_staging_allowed_local_paths( retain_result: bool, ) -> KernelStatusCode { with_statement(stmt, |stmt| { - if paths_json.is_null() { - stmt.spec().staging_allowed_local_paths = None; - return Ok(()); - } - let json = CStr::from_ptr(paths_json) - .to_str() - .map_err(|_| Error::invalid_argument().message("paths_json must be UTF-8"))?; - let paths: Option> = serde_json::from_str(json).map_err(|_| { - Error::invalid_argument().message("paths_json must be an array of paths or null") - })?; + let paths = if paths_json.is_null() { + None + } else { + let json = CStr::from_ptr(paths_json) + .to_str() + .map_err(|_| Error::invalid_argument().message("paths_json must be UTF-8"))?; + serde_json::from_str::>>(json).map_err(|_| { + Error::invalid_argument().message("paths_json must be an array of paths or null") + })? + }; stmt.spec().staging_allowed_local_paths = paths; stmt.spec().retain_volume_operation_result = retain_result; Ok(()) @@ -1271,6 +1271,75 @@ unsafe fn with_statement( mod tests { use super::*; + #[test] + fn staging_options_clear_consistently_and_reject_invalid_inputs() { + use crate::{AuthConfig, ConnectionConfig, Session}; + use wiremock::matchers::method; + use wiremock::{Mock, MockServer, ResponseTemplate}; + let runtime = tokio::runtime::Runtime::new().unwrap(); + let server = runtime.block_on(async { + let server = MockServer::start().await; + Mock::given(method("POST")) + .respond_with( + ResponseTemplate::new(200) + .set_body_string(r#"{"session_id":"session","warehouse_id":"warehouse"}"#), + ) + .mount(&server) + .await; + Mock::given(method("DELETE")) + .respond_with(ResponseTemplate::new(200).set_body_string("{}")) + .mount(&server) + .await; + server + }); + let session = runtime + .block_on( + Session::builder() + .connection( + ConnectionConfig::from_http_path( + server.uri(), + "/sql/1.0/warehouses/warehouse", + ) + .unwrap(), + ) + .auth(AuthConfig::Pat { + token: "test".into(), + identity_federation_client_id: None, + }) + .open(), + ) + .unwrap(); + let statement = into_raw_statement(session.statement()); + unsafe { + for (json, retained, expected) in [ + (c"[]".as_ptr(), true, Some(vec![])), + (std::ptr::null(), false, None), + (c"[\"/tmp\"]".as_ptr(), false, Some(vec!["/tmp".to_owned()])), + (c"null".as_ptr(), true, None), + ] { + assert_eq!( + kernel_statement_set_staging_allowed_local_paths(statement, json, retained), + KernelStatusCode::Success + ); + let spec = statement_mut(statement).unwrap().spec(); + assert_eq!(spec.staging_allowed_local_paths, expected); + assert_eq!(spec.retain_volume_operation_result, retained); + } + let invalid_utf8 = [0xff_u8, 0]; + for json in [c"{}".as_ptr(), invalid_utf8.as_ptr().cast()] { + assert_eq!( + kernel_statement_set_staging_allowed_local_paths(statement, json, false), + KernelStatusCode::InvalidArgument + ); + let spec = statement_mut(statement).unwrap().spec(); + assert!(spec.staging_allowed_local_paths.is_none()); + assert!(spec.retain_volume_operation_result); + } + assert_eq!(kernel_statement_close(statement), KernelStatusCode::Success); + } + runtime.block_on(session.close()).unwrap(); + } + // Null-pointer guards only: a bad handle yields InvalidArgument, never a // crash. The success + concurrent-cancel-during-execute paths are covered by // tests/v0_c_abi_canceller_wiremock.rs, which drives these entry points diff --git a/src/statement/spec.rs b/src/statement/spec.rs index 2d2ed285..3520e242 100644 --- a/src/statement/spec.rs +++ b/src/statement/spec.rs @@ -229,6 +229,8 @@ pub struct StatementSpec { /// retry overall deadline, which defaults to 15 minutes. /// Completion, including a failure after retries, is final and shared by all /// readers of an execution. Re-execute the SQL to start a new transfer attempt. + /// Interrupted GET bodies are not retried. Allow only trusted roots whose + /// directory components cannot be modified by untrusted users during transfer. pub staging_allowed_local_paths: Option>, /// Preserve the instruction row after a successful transfer for APIs diff --git a/src/statement/volume.rs b/src/statement/volume.rs index 237a74ca..59be0644 100644 --- a/src/statement/volume.rs +++ b/src/statement/volume.rs @@ -59,53 +59,59 @@ pub(crate) async fn complete( { return Ok(result); } - let mut stream = ResultStream::from_reader(result.reader).await?; - let schema = stream.schema(); - let batch = match stream.next_batch().await? { - Some(ResultBatch::Arrow(batch)) if batch.num_rows() == 1 => batch.clone(), - _ => return Err(Error::invalid_state().message("Expected one file transfer instruction")), - }; - let row = stream - .next_row_in_batch() - .ok_or_else(|| Error::invalid_state().message("Missing file transfer instruction"))?; - if !(3..=4).contains(&row.num_columns()) { - return Err(Error::invalid_state().message("Invalid file transfer instruction columns")); - } - let operation = row.get_str(0)?.unwrap_or_default().to_owned(); - let url = row.get_str(1)?.unwrap_or_default().to_owned(); - let headers = instruction_headers(&batch)?; - let local_file = if row.num_columns() == 4 { - row.get_str(3)?.map(str::to_owned) - } else { - None - }; - if stream.next_batch().await?.is_some() { - return Err(Error::invalid_state().message("Expected one file transfer instruction")); + let statement_id = result.statement_id.clone(); + async { + let mut stream = ResultStream::from_reader(result.reader).await?; + let schema = stream.schema(); + let batch = match stream.next_batch().await? { + Some(ResultBatch::Arrow(batch)) if batch.num_rows() == 1 => batch.clone(), + _ => { + return Err(Error::invalid_state().message("Expected one file transfer instruction")) + } + }; + let row = stream + .next_row_in_batch() + .ok_or_else(|| Error::invalid_state().message("Missing file transfer instruction"))?; + if !(3..=4).contains(&row.num_columns()) { + return Err(Error::invalid_state().message("Invalid file transfer instruction columns")); + } + let operation = row.get_str(0)?.unwrap_or_default().to_owned(); + let url = row.get_str(1)?.unwrap_or_default().to_owned(); + let headers = instruction_headers(&batch)?; + let local_file = if row.num_columns() == 4 { + row.get_str(3)?.map(str::to_owned) + } else { + None + }; + if stream.next_batch().await?.is_some() { + return Err(Error::invalid_state().message("Expected one file transfer instruction")); + } + completion + .get_or_init(|| { + transfer( + client, + &operation, + &url, + &headers, + local_file.as_deref(), + paths, + ) + }) + .await + .clone()?; + result.reader = if options.retain_result { + Box::new(InMemoryReader::new(schema, vec![batch])) + } else { + Box::new(EmptyReader::new(schema)) + }; + Ok(result) } - completion - .get_or_init(|| { - transfer( - client, - &operation, - &url, - &headers, - local_file.as_deref(), - paths, - ) - }) - .await - .clone() - .map_err(|e| { - e.with_error_code("FILE_TRANSFER_ERROR") - .with_sql_state("HY000") - .with_query_id(&result.statement_id) - })?; - result.reader = if options.retain_result { - Box::new(InMemoryReader::new(schema, vec![batch])) - } else { - Box::new(EmptyReader::new(schema)) - }; - Ok(result) + .await + .map_err(|e: Error| { + e.with_error_code("FILE_TRANSFER_ERROR") + .with_sql_state("HY000") + .with_query_id(&statement_id) + }) } fn instruction_headers(batch: &RecordBatch) -> Result> { @@ -578,6 +584,31 @@ mod tests { assert_eq!(attempts.load(Ordering::SeqCst), 2); } + #[tokio::test] + async fn malformed_instruction_keeps_transfer_error_context() { + let batch = RecordBatch::try_from_iter(vec![( + "operation", + Arc::new(StringArray::from(vec!["GET"])) as arrow_array::ArrayRef, + )]) + .unwrap(); + let error = complete( + &client(), + result(batch, true), + &VolumeOptions { + paths: Some(vec![]), + retain_result: false, + }, + &OnceCell::new(), + ) + .await + .err() + .unwrap(); + assert_eq!(error.code, ErrorCode::InvalidArgument); + assert_eq!(error.error_code.as_deref(), Some("FILE_TRANSFER_ERROR")); + assert_eq!(error.query_id.as_deref(), Some("statement")); + assert_eq!(error.sql_state.as_deref(), Some("HY000")); + } + #[tokio::test] async fn marker_and_opt_in_are_both_required() { let batch = instruction("GET", "http://127.0.0.1:1/file", "/unavailable"); From f68e4e5d1600e987187cf84f58ddf6a61e6a5ba6 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Wed, 11 Nov 2026 23:58:22 +0000 Subject: [PATCH 09/39] fix(volume): constrain storage redirects and preserve filesystem errors Signed-off-by: Aakash Saravanan --- src/client/http.rs | 12 +++++ src/session.rs | 6 ++- src/statement/volume.rs | 116 +++++++++++++++++++++++++++++++++------- 3 files changed, 115 insertions(+), 19 deletions(-) diff --git a/src/client/http.rs b/src/client/http.rs index d120f7cd..458f319f 100644 --- a/src/client/http.rs +++ b/src/client/http.rs @@ -383,6 +383,7 @@ fn build_mtls_identity(cert_pem: &[u8], key_pem: &[u8]) -> Result>, config: HttpClientConfig, auth_provider: OnceLock>, retry_configs: HashMap, @@ -499,6 +500,7 @@ impl DatabricksHttpClient { Ok(Self { client, + volume_client: OnceLock::new(), config, auth_provider: OnceLock::new(), retry_configs, @@ -736,6 +738,16 @@ impl DatabricksHttpClient { &self.client } + pub(crate) fn volume_client(&self) -> Result<&Client> { + // Transfer instructions authorize one URL; redirects must not forward their headers. + self.volume_client + .get_or_init(|| { + Self::build_reqwest_client(&self.config, reqwest::redirect::Policy::none()) + }) + .as_ref() + .map_err(Clone::clone) + } + pub(crate) fn storage_retry_config(&self) -> RetryConfig { self.retry_configs .get(&RequestCategory::CloudFetch) diff --git a/src/session.rs b/src/session.rs index c413704f..9ac51d79 100644 --- a/src/session.rs +++ b/src/session.rs @@ -1088,6 +1088,10 @@ fn validate_mtls_endpoint_scheme(config: &SessionConfig) -> Result<()> { /// / `skip_hostname_verification` and is projected onto the internal /// [`HttpTlsConfig`] via [`HttpTlsConfig::from_public`]. fn build_http_client_config(config: &SessionConfig, org_id: Option) -> HttpClientConfig { + let mut tls = HttpTlsConfig::from_public(&config.tls); + if config.connection.host.starts_with("http://") { + tls.enabled = Some(false); + } HttpClientConfig { sea_response_compression_enabled: config.http.sea_response_compression_enabled, connect_timeout: Duration::from_secs(30), @@ -1096,7 +1100,7 @@ fn build_http_client_config(config: &SessionConfig, org_id: Option) -> H read_timeout: config.http.request_timeout, max_connections_per_host: config.http.pool_max_idle_per_host, proxy: build_proxy_config(config.proxy.as_ref()), - tls: HttpTlsConfig::from_public(&config.tls), + tls, org_id, custom_headers: config.http.custom_headers.clone(), ..HttpClientConfig::default() diff --git a/src/statement/volume.rs b/src/statement/volume.rs index 59be0644..984e6236 100644 --- a/src/statement/volume.rs +++ b/src/statement/volume.rs @@ -63,8 +63,8 @@ pub(crate) async fn complete( async { let mut stream = ResultStream::from_reader(result.reader).await?; let schema = stream.schema(); - let batch = match stream.next_batch().await? { - Some(ResultBatch::Arrow(batch)) if batch.num_rows() == 1 => batch.clone(), + let batch = match next_instruction_batch(&mut stream).await? { + Some(batch) if batch.num_rows() == 1 => batch, _ => { return Err(Error::invalid_state().message("Expected one file transfer instruction")) } @@ -83,7 +83,7 @@ pub(crate) async fn complete( } else { None }; - if stream.next_batch().await?.is_some() { + if next_instruction_batch(&mut stream).await?.is_some() { return Err(Error::invalid_state().message("Expected one file transfer instruction")); } completion @@ -114,6 +114,16 @@ pub(crate) async fn complete( }) } +async fn next_instruction_batch(stream: &mut ResultStream) -> Result> { + loop { + match stream.next_batch().await? { + Some(ResultBatch::Arrow(batch)) if batch.num_rows() == 0 => continue, + Some(ResultBatch::Arrow(batch)) => return Ok(Some(batch.clone())), + None => return Ok(None), + } + } +} + fn instruction_headers(batch: &RecordBatch) -> Result> { let invalid = || Error::invalid_state().message("Invalid file transfer headers"); let column = batch.column(2); @@ -150,10 +160,13 @@ fn instruction_headers(batch: &RecordBatch) -> Result> { fn file_error(error: std::io::Error) -> Error { Error::new( - if error.kind() == std::io::ErrorKind::NotFound { - ErrorCode::NotFound - } else { - ErrorCode::InvalidArgument + match error.kind() { + std::io::ErrorKind::NotFound => ErrorCode::NotFound, + std::io::ErrorKind::PermissionDenied => ErrorCode::PermissionDenied, + std::io::ErrorKind::InvalidInput => ErrorCode::InvalidArgument, + std::io::ErrorKind::TimedOut => ErrorCode::Timeout, + std::io::ErrorKind::StorageFull => ErrorCode::ResourceExhausted, + _ => ErrorCode::Unavailable, }, format!("File transfer failed: {error}"), ) @@ -217,7 +230,9 @@ async fn transfer( .parse::() .is_ok_and(|ip| ip.is_loopback()) }); - if parsed.scheme() != "https" && !(parsed.scheme() == "http" && loopback) { + if parsed.scheme() != "https" + && !(parsed.scheme() == "http" && loopback && client.config().tls.enabled == Some(false)) + { return Err(Error::invalid_state().message("Invalid file transfer URL scheme")); } let local = if operation == "REMOVE" { @@ -316,7 +331,7 @@ async fn send_transfer( } // Large files need the storage budget rather than the SQL request timeout. let mut request = client - .inner() + .volume_client()? .request(method.clone(), url.clone()) .timeout(remaining); for (name, value) in headers { @@ -374,7 +389,9 @@ mod tests { use wiremock::{Mock, MockServer, ResponseTemplate}; fn client() -> DatabricksHttpClient { - DatabricksHttpClient::with_default_retry(HttpClientConfig::default()).unwrap() + let mut config = HttpClientConfig::default(); + config.tls.enabled = Some(false); + DatabricksHttpClient::with_default_retry(config).unwrap() } fn instruction(operation: &str, url: &str, local: &str) -> RecordBatch { @@ -434,7 +451,16 @@ mod tests { let completion = OnceCell::new(); let http = client(); for _ in 0..2 { - let completed = complete(&http, result(batch.clone(), true), &options, &completion) + let mut execution = result(batch.clone(), true); + execution.reader = Box::new(InMemoryReader::new( + batch.schema(), + vec![ + RecordBatch::new_empty(batch.schema()), + batch.clone(), + RecordBatch::new_empty(batch.schema()), + ], + )); + let completed = complete(&http, execution, &options, &completion) .await .unwrap(); let mut reader = ResultStream::from_reader(completed.reader).await.unwrap(); @@ -447,6 +473,49 @@ mod tests { assert_eq!(request.headers["x-file-header"], "value"); } + #[test] + fn file_errors_keep_their_category() { + use std::io::ErrorKind; + for (kind, code) in [ + (ErrorKind::NotFound, ErrorCode::NotFound), + (ErrorKind::PermissionDenied, ErrorCode::PermissionDenied), + (ErrorKind::InvalidInput, ErrorCode::InvalidArgument), + (ErrorKind::StorageFull, ErrorCode::ResourceExhausted), + (ErrorKind::TimedOut, ErrorCode::Timeout), + (ErrorKind::Other, ErrorCode::Unavailable), + ] { + assert_eq!(file_error(std::io::Error::from(kind)).code, code); + } + } + + #[tokio::test] + async fn storage_redirects_are_not_followed_and_plaintext_requires_opt_out() { + let server = MockServer::start().await; + Mock::given(path("/redirect")) + .respond_with( + ResponseTemplate::new(307) + .insert_header("Location", format!("{}/destination", server.uri())), + ) + .expect(1) + .mount(&server) + .await; + Mock::given(path("/destination")) + .respond_with(ResponseTemplate::new(200)) + .expect(0) + .mount(&server) + .await; + let url = format!("{}/redirect", server.uri()); + let strict = DatabricksHttpClient::with_default_retry(HttpClientConfig::default()).unwrap(); + let error = transfer(&strict, "REMOVE", &url, &HashMap::new(), None, &[]) + .await + .unwrap_err(); + assert!(error.message.contains("URL scheme")); + let error = transfer(&client(), "REMOVE", &url, &HashMap::new(), None, &[]) + .await + .unwrap_err(); + assert_eq!(error.http_status, Some(307)); + } + #[cfg(unix)] #[tokio::test] async fn download_preserves_file_permissions_and_rejects_root() { @@ -660,9 +729,11 @@ mod tests { use crate::client::retry::{RequestCategory, RetryConfig}; use std::time::Duration; use tokio::io::AsyncReadExt; - for (budget, succeeds, existing) in - [(1000, true, false), (40, false, true), (40, false, false)] - { + for (budget, succeeds, existing) in [ + (10_000, true, false), + (100, false, true), + (100, false, false), + ] { let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); let address = listener.local_addr().unwrap(); let server = tokio::spawn(async move { @@ -675,13 +746,18 @@ mod tests { .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 4\r\nConnection: close\r\n\r\n") .await .unwrap(); - tokio::time::sleep(Duration::from_millis(100)).await; - let _ = socket.write_all(b"data").await; + if succeeds { + tokio::time::sleep(Duration::from_millis(100)).await; + socket.write_all(b"data").await.unwrap(); + } else { + std::future::pending::<()>().await; + } }); - let config = HttpClientConfig { + let mut config = HttpClientConfig { read_timeout: Duration::from_millis(10), ..Default::default() }; + config.tls.enabled = Some(false); let retry = RetryConfig { overall_timeout: Duration::from_millis(budget), max_retries: 0, @@ -721,7 +797,11 @@ mod tests { std::fs::read_dir(dir.path()).unwrap().count(), usize::from(succeeds || existing) ); - server.await.unwrap(); + if succeeds { + server.await.unwrap(); + } else { + server.abort(); + } } } From c3e7cf1ba339155c7932c77e39e2821fd918cddf Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Thu, 12 Nov 2026 00:07:30 +0000 Subject: [PATCH 10/39] fix(volume): retain instruction reader error details Signed-off-by: Aakash Saravanan --- src/statement/volume.rs | 60 ++++++++++++++++++++++++++++++++++------- 1 file changed, 51 insertions(+), 9 deletions(-) diff --git a/src/statement/volume.rs b/src/statement/volume.rs index 984e6236..76875479 100644 --- a/src/statement/volume.rs +++ b/src/statement/volume.rs @@ -24,7 +24,7 @@ use futures::StreamExt; use reqwest::Method; use std::collections::HashMap; use std::path::{Path, PathBuf}; -use tokio::io::AsyncWriteExt; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio::sync::OnceCell; use tokio_util::io::ReaderStream; @@ -107,10 +107,14 @@ pub(crate) async fn complete( Ok(result) } .await - .map_err(|e: Error| { - e.with_error_code("FILE_TRANSFER_ERROR") - .with_sql_state("HY000") - .with_query_id(&statement_id) + .map_err(|mut e: Error| { + if e.error_code.is_none() { + e = e.with_error_code("FILE_TRANSFER_ERROR"); + } + if e.sql_state.is_none() { + e = e.with_sql_state("HY000"); + } + e.with_query_id(&statement_id) }) } @@ -340,15 +344,17 @@ async fn send_transfer( if method == Method::PUT { let local = local .ok_or_else(|| Error::invalid_argument().message("Missing local upload path"))?; - let metadata = tokio::fs::metadata(local).await.map_err(file_error)?; + // Each retry reopens the file so a streaming upload starts at byte zero. + let file = tokio::fs::File::open(local).await.map_err(file_error)?; + let metadata = file.metadata().await.map_err(file_error)?; if !metadata.is_file() { return Err(Error::invalid_argument().message("Local upload path must be a file")); } - // Each retry reopens the file so a streaming upload starts at byte zero. - let file = tokio::fs::File::open(local).await.map_err(file_error)?; request = request .header(reqwest::header::CONTENT_LENGTH, metadata.len()) - .body(reqwest::Body::wrap_stream(ReaderStream::new(file))); + .body(reqwest::Body::wrap_stream(ReaderStream::new( + file.take(metadata.len()), + ))); } // Presigned storage requests must omit workspace credentials and custom headers. let response = request.send().await; @@ -678,6 +684,42 @@ mod tests { assert_eq!(error.sql_state.as_deref(), Some("HY000")); } + #[tokio::test] + async fn instruction_read_failure_keeps_existing_error_context() { + struct FailedReader; + #[async_trait::async_trait] + impl crate::reader::ResultReader for FailedReader { + async fn schema(&self) -> Result { + Err( + Error::new(ErrorCode::NetworkError, "Instruction read failed") + .with_error_code("INSTRUCTION_READ_FAILED") + .with_sql_state("08S01"), + ) + } + async fn next_batch(&mut self) -> Result> { + unreachable!() + } + } + let batch = instruction("GET", "https://storage.example/file", "/download"); + let mut execution = result(batch, true); + execution.reader = Box::new(FailedReader); + let error = complete( + &client(), + execution, + &VolumeOptions { + paths: Some(vec![]), + retain_result: false, + }, + &OnceCell::new(), + ) + .await + .err() + .unwrap(); + assert_eq!(error.error_code.as_deref(), Some("INSTRUCTION_READ_FAILED")); + assert_eq!(error.sql_state.as_deref(), Some("08S01")); + assert_eq!(error.query_id.as_deref(), Some("statement")); + } + #[tokio::test] async fn marker_and_opt_in_are_both_required() { let batch = instruction("GET", "http://127.0.0.1:1/file", "/unavailable"); From 7a938104d5e9870f995926f135aa41925c044cf6 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Thu, 12 Nov 2026 00:19:03 +0000 Subject: [PATCH 11/39] fix(volume): reject special uploads and close failed transfers Signed-off-by: Aakash Saravanan --- src/statement/mutable.rs | 22 ++++++++++--- src/statement/volume.rs | 50 ++++++++++++++++++++++++++++++ tests/v0_async_execute_wiremock.rs | 10 ++++++ 3 files changed, 78 insertions(+), 4 deletions(-) diff --git a/src/statement/mutable.rs b/src/statement/mutable.rs index 8691ad9d..abf33fd2 100644 --- a/src/statement/mutable.rs +++ b/src/statement/mutable.rs @@ -409,13 +409,20 @@ impl Statement { self.last_valid = Some(valid.clone()); self.last_closed = Some(Arc::clone(&closed)); - let result = super::volume::complete( + let result = match super::volume::complete( &self.session.http_client, result, &super::volume::VolumeOptions::from(&self.spec), &tokio::sync::OnceCell::new(), ) - .await?; + .await + { + Ok(result) => result, + Err(error) => { + self.invalidate_prior().await; + return Err(error); + } + }; let mut result_stream = ResultStream::from_reader(result.reader).await?; result_stream.attach_telemetry(telemetry_for_body.clone()); // SEA puts no row count on the status envelope; for a DML it @@ -653,13 +660,20 @@ impl Statement { self.last_statement_id = Some(result.statement_id.clone()); self.last_valid = Some(valid.clone()); self.last_closed = Some(Arc::clone(&closed)); - let result = super::volume::complete( + let result = match super::volume::complete( &self.session.http_client, result, &super::volume::VolumeOptions::from(&self.spec), &tokio::sync::OnceCell::new(), ) - .await?; + .await + { + Ok(result) => result, + Err(error) => { + self.invalidate_prior().await; + return Err(error); + } + }; let mut result_stream = ResultStream::from_reader(result.reader).await?; result_stream.attach_telemetry(telemetry_for_body.clone()); let executed = ExecutedStatement::new( diff --git a/src/statement/volume.rs b/src/statement/volume.rs index 76875479..aadb2a9b 100644 --- a/src/statement/volume.rs +++ b/src/statement/volume.rs @@ -344,6 +344,13 @@ async fn send_transfer( if method == Method::PUT { let local = local .ok_or_else(|| Error::invalid_argument().message("Missing local upload path"))?; + if !tokio::fs::metadata(local) + .await + .map_err(file_error)? + .is_file() + { + return Err(Error::invalid_argument().message("Local upload path must be a file")); + } // Each retry reopens the file so a streaming upload starts at byte zero. let file = tokio::fs::File::open(local).await.map_err(file_error)?; let metadata = file.metadata().await.map_err(file_error)?; @@ -624,6 +631,49 @@ mod tests { .unwrap(); } + #[tokio::test] + #[cfg(unix)] + async fn rejects_fifo_before_opening_upload() { + let server = MockServer::start().await; + let directory = tempfile::tempdir().unwrap(); + let fifo = directory.path().join("input"); + assert!(std::process::Command::new("mkfifo") + .arg(&fifo) + .status() + .unwrap() + .success()); + let local = fifo.clone(); + let root = directory.path().to_str().unwrap().to_owned(); + let url = format!("{}/file", server.uri()); + let mut upload = tokio::spawn(async move { + transfer( + &client(), + "PUT", + &url, + &HashMap::new(), + local.to_str(), + &[root], + ) + .await + }); + let outcome = tokio::time::timeout(std::time::Duration::from_secs(1), &mut upload).await; + if outcome.is_err() { + // Unblock a regressed open so the runtime can shut down after the assertion. + let _peer = std::fs::OpenOptions::new() + .read(true) + .write(true) + .open(&fifo) + .unwrap(); + let _ = upload.await; + panic!("upload blocked while opening a FIFO"); + } + assert_eq!( + outcome.unwrap().unwrap().unwrap_err().code, + ErrorCode::InvalidArgument + ); + assert!(server.received_requests().await.unwrap().is_empty()); + } + #[tokio::test] async fn retries_upload_from_the_start() { use std::sync::atomic::{AtomicUsize, Ordering}; diff --git a/tests/v0_async_execute_wiremock.rs b/tests/v0_async_execute_wiremock.rs index 7d8ef644..5820ae44 100644 --- a/tests/v0_async_execute_wiremock.rs +++ b/tests/v0_async_execute_wiremock.rs @@ -2397,6 +2397,16 @@ async fn sync_and_direct_transfers_complete_and_preserve_error_context() { assert_eq!(error.error_code.as_deref(), Some("FILE_TRANSFER_ERROR")); assert_eq!(error.query_id.as_deref(), Some("transfer")); assert!(!destination.exists()); + assert_eq!( + wait_for_close_delete( + &server, + "transfer", + 1, + std::time::Duration::from_secs(1), + ) + .await, + 1, + ); } else { let mut executed = result.unwrap(); assert!(executed From ab10f222493fe45c645f746cdd2d762173a70fc5 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Thu, 12 Nov 2026 00:35:36 +0000 Subject: [PATCH 12/39] fix(volume): honor destination permissions and safe upload retries Signed-off-by: Aakash Saravanan --- adbc/src/statement.rs | 62 ++++++++++++++++++++ src/client/retry.rs | 14 ++++- src/statement/volume.rs | 126 ++++++++++++++++++++++++++++++++++++---- 3 files changed, 188 insertions(+), 14 deletions(-) diff --git a/adbc/src/statement.rs b/adbc/src/statement.rs index 22d5b746..625a8760 100644 --- a/adbc/src/statement.rs +++ b/adbc/src/statement.rs @@ -1474,6 +1474,68 @@ mod tests { use arrow_array::{BinaryArray, Int64Array, LargeBinaryArray, StringArray}; use arrow_schema::{DataType, Field}; + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn volume_paths_option_sets_clears_and_rejects_invalid_values() { + use adbc_core::options::OptionDatabase; + use adbc_core::{Connection as _, Database as _, Driver as _, Optionable as _}; + use wiremock::matchers::{method, path}; + use wiremock::{Mock, MockServer, ResponseTemplate}; + let server = MockServer::start().await; + Mock::given(method("POST")) + .and(path("/api/2.0/sql/warehouses/test_wh/sessions")) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "session_id": "session", "warehouse_id": "test_wh" + }))) + .mount(&server) + .await; + Mock::given(method("DELETE")) + .respond_with(ResponseTemplate::new(200).set_body_string("{}")) + .mount(&server) + .await; + let database = crate::Driver + .new_database_with_opts([ + (OptionDatabase::Uri, server.uri().into()), + ( + OptionDatabase::Other(crate::config::HTTP_PATH.into()), + "/sql/1.0/warehouses/test_wh".into(), + ), + ( + OptionDatabase::Other(crate::config::ACCESS_TOKEN.into()), + "token".into(), + ), + ]) + .unwrap(); + let mut connection = database.new_connection().unwrap(); + let mut statement = connection.new_statement().unwrap(); + let option = + OptionStatement::Other("adbc.databricks.statement.staging_allowed_local_paths".into()); + for (value, expected) in [ + (r#"["/tmp/files"]"#, Some(vec!["/tmp/files".to_owned()])), + ("[]", Some(vec![])), + ("null", None), + ] { + statement.set_option(option.clone(), value.into()).unwrap(); + assert_eq!( + statement + .inner() + .unwrap() + .spec() + .staging_allowed_local_paths, + expected + ); + } + let error = statement.set_option(option, "{}".into()).unwrap_err(); + assert_eq!(error.status, Status::InvalidArguments); + assert_eq!( + statement + .inner() + .unwrap() + .spec() + .staging_allowed_local_paths, + None + ); + } + fn batch(rows: usize) -> RecordBatch { let schema = Arc::new(Schema::new(vec![ Field::new("id", DataType::Int64, false), diff --git a/src/client/retry.rs b/src/client/retry.rs index cdd1c31b..d1f09468 100644 --- a/src/client/retry.rs +++ b/src/client/retry.rs @@ -46,6 +46,7 @@ pub enum RequestType { TelemetryExport, // CloudFetch CloudFetchDownload, + VolumeUpload, // Auth AuthTokenRequest, AuthDiscovery, @@ -83,7 +84,7 @@ impl RequestType { Self::TelemetryExport => RequestCategory::Telemetry, - Self::CloudFetchDownload => RequestCategory::CloudFetch, + Self::CloudFetchDownload | Self::VolumeUpload => RequestCategory::CloudFetch, Self::AuthTokenRequest | Self::AuthDiscovery => RequestCategory::Auth, } @@ -92,7 +93,7 @@ impl RequestType { /// Returns the idempotency classification for strategy selection. pub fn idempotency(self) -> RequestIdempotency { match self { - Self::ExecuteStatement => RequestIdempotency::NonIdempotent, + Self::ExecuteStatement | Self::VolumeUpload => RequestIdempotency::NonIdempotent, _ => RequestIdempotency::Idempotent, } } @@ -821,11 +822,18 @@ mod tests { #[test] fn test_request_type_idempotency_mapping() { - // Only ExecuteStatement is non-idempotent assert_eq!( RequestType::ExecuteStatement.idempotency(), RequestIdempotency::NonIdempotent ); + assert_eq!( + RequestType::VolumeUpload.idempotency(), + RequestIdempotency::NonIdempotent + ); + assert_eq!( + RequestType::VolumeUpload.category(), + RequestCategory::CloudFetch + ); // Everything else is idempotent let idempotent_types = [ diff --git a/src/statement/volume.rs b/src/statement/volume.rs index aadb2a9b..531973d4 100644 --- a/src/statement/volume.rs +++ b/src/statement/volume.rs @@ -129,7 +129,12 @@ async fn next_instruction_batch(stream: &mut ResultStream) -> Result Result> { - let invalid = || Error::invalid_state().message("Invalid file transfer headers"); + let invalid = || { + Error::invalid_state().message(format!( + "Invalid file transfer headers: {:?}", + batch.column(2).data_type() + )) + }; let column = batch.column(2); if column.is_null(0) { return Ok(HashMap::new()); @@ -163,7 +168,8 @@ fn instruction_headers(batch: &RecordBatch) -> Result> { } fn file_error(error: std::io::Error) -> Error { - Error::new( + let permission_denied = error.kind() == std::io::ErrorKind::PermissionDenied; + let error = Error::new( match error.kind() { std::io::ErrorKind::NotFound => ErrorCode::NotFound, std::io::ErrorKind::PermissionDenied => ErrorCode::PermissionDenied, @@ -173,7 +179,12 @@ fn file_error(error: std::io::Error) -> Error { _ => ErrorCode::Unavailable, }, format!("File transfer failed: {error}"), - ) + ); + if permission_denied { + error.with_error_code("FILE_TRANSFER_PERMISSION_ERROR") + } else { + error + } } fn resolved_path(path: &Path) -> Result { @@ -244,12 +255,27 @@ async fn transfer( } else { Some(allowed_path(local_file, paths)?) }; - if operation == "GET" - && local - .as_ref() - .is_some_and(|path| path.parent().is_none() || path.is_dir()) - { - return Err(Error::invalid_argument().message("Download destination must be a file")); + if operation == "GET" { + let destination = local.as_ref().unwrap(); + if destination.parent().is_none() { + return Err(Error::invalid_argument().message("Download destination must be a file")); + } + match tokio::fs::metadata(destination).await { + Ok(metadata) if !metadata.is_file() => { + return Err( + Error::invalid_argument().message("Download destination must be a file") + ); + } + Ok(_) => { + tokio::fs::OpenOptions::new() + .write(true) + .open(destination) + .await + .map_err(file_error)?; + } + Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} + Err(error) => return Err(file_error(error)), + } } let response = send_transfer(client, method, parsed, headers, local.as_deref()).await?; if !response.status().is_success() @@ -323,7 +349,12 @@ async fn send_transfer( local: Option<&Path>, ) -> Result { let config = client.storage_retry_config(); - let strategy = RetryStrategy::for_request(RequestType::CloudFetchDownload, &config); + let request_type = if method == Method::PUT { + RequestType::VolumeUpload + } else { + RequestType::CloudFetchDownload + }; + let strategy = RetryStrategy::for_request(request_type, &config); let started = std::time::Instant::now(); for attempt in 0..=config.max_retries { let remaining = config.overall_timeout.saturating_sub(started.elapsed()); @@ -497,7 +528,12 @@ mod tests { (ErrorKind::TimedOut, ErrorCode::Timeout), (ErrorKind::Other, ErrorCode::Unavailable), ] { - assert_eq!(file_error(std::io::Error::from(kind)).code, code); + let error = file_error(std::io::Error::from(kind)); + assert_eq!(error.code, code); + assert_eq!( + error.error_code.as_deref(), + (kind == ErrorKind::PermissionDenied).then_some("FILE_TRANSFER_PERMISSION_ERROR") + ); } } @@ -573,6 +609,30 @@ mod tests { expected ); } + std::fs::write(&destination, b"protected").unwrap(); + std::fs::set_permissions(&destination, std::fs::Permissions::from_mode(0o440)).unwrap(); + if std::fs::OpenOptions::new() + .write(true) + .open(&destination) + .is_err() + { + let error = transfer( + &client(), + "GET", + &server.uri(), + &HashMap::new(), + destination.to_str(), + &roots, + ) + .await + .unwrap_err(); + assert_eq!(error.code, ErrorCode::PermissionDenied); + assert_eq!( + error.error_code.as_deref(), + Some("FILE_TRANSFER_PERMISSION_ERROR") + ); + assert_eq!(std::fs::read(&destination).unwrap(), b"protected"); + } for destination in [Path::new("/"), dir.path()] { let error = transfer( &client(), @@ -689,6 +749,7 @@ mod tests { } else { 200 }) + .insert_header("Retry-After", "0") }) .expect(2) .mount(&server) @@ -709,6 +770,49 @@ mod tests { assert_eq!(attempts.load(Ordering::SeqCst), 2); } + #[tokio::test] + async fn does_not_retry_upload_after_response_is_lost() { + use std::sync::atomic::{AtomicUsize, Ordering}; + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}/file", listener.local_addr().unwrap()); + let attempts = Arc::new(AtomicUsize::new(0)); + let observed = Arc::clone(&attempts); + let server = tokio::spawn(async move { + for attempt in 0..2 { + let (mut socket, _) = listener.accept().await.unwrap(); + let mut received = Vec::new(); + while !received.ends_with(b"\r\n\r\nupload") { + let mut buffer = [0u8; 1024]; + let count = socket.read(&mut buffer).await.unwrap(); + assert_ne!(count, 0); + received.extend_from_slice(&buffer[..count]); + } + observed.fetch_add(1, Ordering::SeqCst); + if attempt == 1 { + socket + .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n") + .await + .unwrap(); + } + } + }); + let directory = tempfile::tempdir().unwrap(); + let local = directory.path().join("input"); + std::fs::write(&local, b"upload").unwrap(); + let outcome = transfer( + &client(), + "PUT", + &url, + &HashMap::new(), + local.to_str(), + &[directory.path().to_str().unwrap().into()], + ) + .await; + server.abort(); + assert!(outcome.is_err()); + assert_eq!(attempts.load(Ordering::SeqCst), 1); + } + #[tokio::test] async fn malformed_instruction_keeps_transfer_error_context() { let batch = RecordBatch::try_from_iter(vec![( From 6dbc9a7c721e55e535b469df446251f1fc0ccaaa Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Thu, 12 Nov 2026 00:47:08 +0000 Subject: [PATCH 13/39] fix(volume): preserve private modes during downloads Signed-off-by: Aakash Saravanan --- src/session.rs | 1 + src/statement/volume.rs | 68 ++++++++++++++++++++++++++++++++++++++++- 2 files changed, 68 insertions(+), 1 deletion(-) diff --git a/src/session.rs b/src/session.rs index 9ac51d79..f3824578 100644 --- a/src/session.rs +++ b/src/session.rs @@ -1090,6 +1090,7 @@ fn validate_mtls_endpoint_scheme(config: &SessionConfig) -> Result<()> { fn build_http_client_config(config: &SessionConfig, org_id: Option) -> HttpClientConfig { let mut tls = HttpTlsConfig::from_public(&config.tls); if config.connection.host.starts_with("http://") { + // Explicit HTTP sessions opt into loopback storage for local integrations. tls.enabled = Some(false); } HttpClientConfig { diff --git a/src/statement/volume.rs b/src/statement/volume.rs index 531973d4..2620520e 100644 --- a/src/statement/volume.rs +++ b/src/statement/volume.rs @@ -298,7 +298,14 @@ async fn transfer( let builder = { use std::os::unix::fs::PermissionsExt; let mut builder = builder; - builder.permissions(std::fs::Permissions::from_mode(0o666)); + let permissions = match std::fs::metadata(destination) { + Ok(metadata) => metadata.permissions(), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => { + std::fs::Permissions::from_mode(0o666) + } + Err(error) => return Err(file_error(error)), + }; + builder.permissions(permissions); builder }; let temporary = builder.tempfile_in(parent).map_err(file_error)?; @@ -565,6 +572,65 @@ mod tests { assert_eq!(error.http_status, Some(307)); } + #[cfg(unix)] + #[tokio::test] + async fn download_temporary_file_preserves_private_permissions() { + use std::os::unix::fs::PermissionsExt; + use std::time::Duration; + + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let (resume, wait) = tokio::sync::oneshot::channel(); + let server = tokio::spawn(async move { + let (mut socket, _) = listener.accept().await.unwrap(); + let mut request = Vec::new(); + while !request.ends_with(b"\r\n\r\n") { + request.push(socket.read_u8().await.unwrap()); + } + socket + .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 8\r\nConnection: close\r\n\r\npriv") + .await + .unwrap(); + wait.await.unwrap(); + socket.write_all(b"ate\n").await.unwrap(); + }); + let directory = tempfile::tempdir().unwrap(); + let destination = directory.path().join("download"); + std::fs::write(&destination, b"original").unwrap(); + std::fs::set_permissions(&destination, std::fs::Permissions::from_mode(0o600)).unwrap(); + let http = client(); + let url = format!("http://{address}/file"); + let headers = HashMap::new(); + let roots = vec![directory.path().to_str().unwrap().into()]; + let inspect = async { + let permissions = tokio::time::timeout(Duration::from_secs(5), async { + loop { + for entry in std::fs::read_dir(directory.path()).unwrap() { + let entry = entry.unwrap(); + if entry.path() != destination && entry.metadata().unwrap().len() > 0 { + return entry.metadata().unwrap().permissions().mode() & 0o777; + } + } + tokio::time::sleep(Duration::from_millis(5)).await; + } + }) + .await; + let original = std::fs::read(&destination).unwrap(); + resume.send(()).unwrap(); + (permissions.unwrap(), original) + }; + let (result, (permissions, original)) = tokio::join!( + transfer(&http, "GET", &url, &headers, destination.to_str(), &roots), + inspect + ); + result.unwrap(); + server.await.unwrap(); + assert_eq!(permissions, 0o600); + assert_eq!(original, b"original"); + assert_eq!(std::fs::read(&destination).unwrap(), b"private\n"); + assert_eq!(std::fs::read_dir(directory.path()).unwrap().count(), 1); + } + #[cfg(unix)] #[tokio::test] async fn download_preserves_file_permissions_and_rejects_root() { From bd8adef4f3a38cc8807e4a22b614865246ee7cc2 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Thu, 12 Nov 2026 00:57:51 +0000 Subject: [PATCH 14/39] fix(volume): isolate loopback policy and accept operation casing Signed-off-by: Aakash Saravanan --- src/client/http.rs | 2 ++ src/session.rs | 18 ++++++++---------- src/statement/volume.rs | 24 +++++++++++++----------- 3 files changed, 23 insertions(+), 21 deletions(-) diff --git a/src/client/http.rs b/src/client/http.rs index 458f319f..004b6b50 100644 --- a/src/client/http.rs +++ b/src/client/http.rs @@ -384,6 +384,7 @@ fn build_mtls_identity(cert_pem: &[u8], key_pem: &[u8]) -> Result>, + pub(crate) allow_loopback_plaintext_storage: bool, config: HttpClientConfig, auth_provider: OnceLock>, retry_configs: HashMap, @@ -501,6 +502,7 @@ impl DatabricksHttpClient { Ok(Self { client, volume_client: OnceLock::new(), + allow_loopback_plaintext_storage: false, config, auth_provider: OnceLock::new(), retry_configs, diff --git a/src/session.rs b/src/session.rs index f3824578..e96a8012 100644 --- a/src/session.rs +++ b/src/session.rs @@ -368,11 +368,14 @@ impl Session { // it for OIDC discovery / token endpoint calls. let http_client_config = build_http_client_config(&config, org_id); let retry_configs = build_retry_configs_for_session(&config); - let http_client = Arc::new( - DatabricksHttpClient::new(http_client_config, retry_configs).map_err(|e| { + let mut http_client = DatabricksHttpClient::new(http_client_config, retry_configs) + .map_err(|e| { Error::network_error().message(format!("Failed to construct HTTP client: {e}")) - })?, - ); + })?; + // Explicit HTTP sessions allow loopback storage for local integrations. + http_client.allow_loopback_plaintext_storage = + reqwest::Url::parse(&host).is_ok_and(|url| url.scheme() == "http"); + let http_client = Arc::new(http_client); // 2. Auth provider — async because OAuth flows hit the OIDC // discovery endpoint. @@ -1088,11 +1091,6 @@ fn validate_mtls_endpoint_scheme(config: &SessionConfig) -> Result<()> { /// / `skip_hostname_verification` and is projected onto the internal /// [`HttpTlsConfig`] via [`HttpTlsConfig::from_public`]. fn build_http_client_config(config: &SessionConfig, org_id: Option) -> HttpClientConfig { - let mut tls = HttpTlsConfig::from_public(&config.tls); - if config.connection.host.starts_with("http://") { - // Explicit HTTP sessions opt into loopback storage for local integrations. - tls.enabled = Some(false); - } HttpClientConfig { sea_response_compression_enabled: config.http.sea_response_compression_enabled, connect_timeout: Duration::from_secs(30), @@ -1101,7 +1099,7 @@ fn build_http_client_config(config: &SessionConfig, org_id: Option) -> H read_timeout: config.http.request_timeout, max_connections_per_host: config.http.pool_max_idle_per_host, proxy: build_proxy_config(config.proxy.as_ref()), - tls, + tls: HttpTlsConfig::from_public(&config.tls), org_id, custom_headers: config.http.custom_headers.clone(), ..HttpClientConfig::default() diff --git a/src/statement/volume.rs b/src/statement/volume.rs index 2620520e..09582714 100644 --- a/src/statement/volume.rs +++ b/src/statement/volume.rs @@ -231,7 +231,8 @@ async fn transfer( local_file: Option<&str>, paths: &[String], ) -> Result<()> { - let method = match operation { + let operation = operation.to_ascii_uppercase(); + let method = match operation.as_str() { "PUT" => Method::PUT, "GET" => Method::GET, "REMOVE" => Method::DELETE, @@ -246,7 +247,7 @@ async fn transfer( .is_ok_and(|ip| ip.is_loopback()) }); if parsed.scheme() != "https" - && !(parsed.scheme() == "http" && loopback && client.config().tls.enabled == Some(false)) + && !(parsed.scheme() == "http" && loopback && client.allow_loopback_plaintext_storage) { return Err(Error::invalid_state().message("Invalid file transfer URL scheme")); } @@ -440,9 +441,10 @@ mod tests { use wiremock::{Mock, MockServer, ResponseTemplate}; fn client() -> DatabricksHttpClient { - let mut config = HttpClientConfig::default(); - config.tls.enabled = Some(false); - DatabricksHttpClient::with_default_retry(config).unwrap() + let mut client = + DatabricksHttpClient::with_default_retry(HttpClientConfig::default()).unwrap(); + client.allow_loopback_plaintext_storage = true; + client } fn instruction(operation: &str, url: &str, local: &str) -> RecordBatch { @@ -491,7 +493,7 @@ mod tests { let dir = tempfile::tempdir().unwrap(); let local = dir.path().join("download"); let batch = instruction( - "GET", + "gEt", &format!("{}/file", server.uri()), local.to_str().unwrap(), ); @@ -737,7 +739,7 @@ mod tests { let http = client(); transfer( &http, - "PUT", + "pUt", &format!("{}/file", server.uri()), &HashMap::new(), local.to_str(), @@ -747,7 +749,7 @@ mod tests { .unwrap(); transfer( &http, - "REMOVE", + "remove", &format!("{}/file", server.uri()), &HashMap::new(), None, @@ -1015,21 +1017,21 @@ mod tests { std::future::pending::<()>().await; } }); - let mut config = HttpClientConfig { + let config = HttpClientConfig { read_timeout: Duration::from_millis(10), ..Default::default() }; - config.tls.enabled = Some(false); let retry = RetryConfig { overall_timeout: Duration::from_millis(budget), max_retries: 0, ..Default::default() }; - let http = DatabricksHttpClient::new( + let mut http = DatabricksHttpClient::new( config, HashMap::from([(RequestCategory::CloudFetch, retry)]), ) .unwrap(); + http.allow_loopback_plaintext_storage = true; let dir = tempfile::tempdir().unwrap(); let file = dir.path().join("download"); if existing { From c3300aaa17d0d1109e2579c40e6f35b3c3aeaf54 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Thu, 12 Nov 2026 01:08:27 +0000 Subject: [PATCH 15/39] fix(volume): keep cancelled transfers terminal across readers Signed-off-by: Aakash Saravanan --- src/statement/executed_async.rs | 6 +- src/statement/mutable.rs | 4 +- src/statement/spec.rs | 3 +- src/statement/volume.rs | 127 +++++++++++++++++++++++++++----- 4 files changed, 115 insertions(+), 25 deletions(-) diff --git a/src/statement/executed_async.rs b/src/statement/executed_async.rs index 3abf1fbb..1715b17a 100644 --- a/src/statement/executed_async.rs +++ b/src/statement/executed_async.rs @@ -222,7 +222,7 @@ pub struct ExecutedAsyncStatement { /// every network round-trip. latest_status: Arc>, pub(crate) volume_options: super::volume::VolumeOptions, - volume_completion: Arc>>, + volume_completion: Arc, statement_telemetry: StatementTelemetry, /// Set once result materialisation hands success finalization to /// the returned `ResultStream`. @@ -334,7 +334,7 @@ impl ExecutedAsyncStatement { session_attribution: SessionAttribution::Current, latest_status: Arc::new(std::sync::Mutex::new(initial_status)), volume_options: super::volume::VolumeOptions::default(), - volume_completion: Arc::new(tokio::sync::OnceCell::new()), + volume_completion: Arc::new(super::volume::VolumeCompletion::default()), statement_telemetry, result_stream_owns_success_telemetry: AtomicBool::new(false), client_deadline, @@ -395,7 +395,7 @@ impl ExecutedAsyncStatement { session_attribution, latest_status: Arc::new(std::sync::Mutex::new(initial_status)), volume_options: super::volume::VolumeOptions::default(), - volume_completion: Arc::new(tokio::sync::OnceCell::new()), + volume_completion: Arc::new(super::volume::VolumeCompletion::default()), statement_telemetry: StatementTelemetry::noop(), result_stream_owns_success_telemetry: AtomicBool::new(false), client_deadline: None, diff --git a/src/statement/mutable.rs b/src/statement/mutable.rs index abf33fd2..5ee16466 100644 --- a/src/statement/mutable.rs +++ b/src/statement/mutable.rs @@ -413,7 +413,7 @@ impl Statement { &self.session.http_client, result, &super::volume::VolumeOptions::from(&self.spec), - &tokio::sync::OnceCell::new(), + &super::volume::VolumeCompletion::default(), ) .await { @@ -664,7 +664,7 @@ impl Statement { &self.session.http_client, result, &super::volume::VolumeOptions::from(&self.spec), - &tokio::sync::OnceCell::new(), + &super::volume::VolumeCompletion::default(), ) .await { diff --git a/src/statement/spec.rs b/src/statement/spec.rs index 3520e242..1b6a1f56 100644 --- a/src/statement/spec.rs +++ b/src/statement/spec.rs @@ -228,7 +228,8 @@ pub struct StatementSpec { /// enables REMOVE while denying local file access. Transfers use the storage /// retry overall deadline, which defaults to 15 minutes. /// Completion, including a failure after retries, is final and shared by all - /// readers of an execution. Re-execute the SQL to start a new transfer attempt. + /// readers of an execution. Cancellation during transfer is terminal; + /// re-execute the SQL to start a new transfer attempt. /// Interrupted GET bodies are not retried. Allow only trusted roots whose /// directory components cannot be modified by untrusted users during transfer. pub staging_allowed_local_paths: Option>, diff --git a/src/statement/volume.rs b/src/statement/volume.rs index 09582714..7bf646b5 100644 --- a/src/statement/volume.rs +++ b/src/statement/volume.rs @@ -25,9 +25,11 @@ use reqwest::Method; use std::collections::HashMap; use std::path::{Path, PathBuf}; use tokio::io::{AsyncReadExt, AsyncWriteExt}; -use tokio::sync::OnceCell; +use tokio::sync::Mutex; use tokio_util::io::ReaderStream; +pub(crate) type VolumeCompletion = Mutex>>; + #[derive(Clone, Default)] pub(crate) struct VolumeOptions { paths: Option>, @@ -47,7 +49,7 @@ pub(crate) async fn complete( client: &DatabricksHttpClient, mut result: ExecuteResult, options: &VolumeOptions, - completion: &OnceCell>, + completion: &VolumeCompletion, ) -> Result { let Some(paths) = &options.paths else { return Ok(result); @@ -86,19 +88,28 @@ pub(crate) async fn complete( if next_instruction_batch(&mut stream).await?.is_some() { return Err(Error::invalid_state().message("Expected one file transfer instruction")); } - completion - .get_or_init(|| { - transfer( - client, - &operation, - &url, - &headers, - local_file.as_deref(), - paths, - ) - }) - .await - .clone()?; + { + let mut completed = completion.lock().await; + if completed.is_none() { + // Cancellation must leave a terminal result instead of replaying an upload. + *completed = Some(Err(Error::new( + ErrorCode::Cancelled, + "File transfer interrupted; re-execute the SQL to retry", + ))); + *completed = Some( + transfer( + client, + &operation, + &url, + &headers, + local_file.as_deref(), + paths, + ) + .await, + ); + } + completed.as_ref().unwrap().clone()?; + } result.reader = if options.retain_result { Box::new(InMemoryReader::new(schema, vec![batch])) } else { @@ -241,6 +252,10 @@ async fn transfer( let parsed = reqwest::Url::parse(url) .map_err(|_| Error::invalid_state().message("Invalid file transfer URL"))?; let loopback = parsed.host_str().is_some_and(|host| { + let host = host + .strip_prefix('[') + .and_then(|host| host.strip_suffix(']')) + .unwrap_or(host); host == "localhost" || host .parse::() @@ -501,7 +516,7 @@ mod tests { paths: Some(vec![dir.path().to_str().unwrap().into()]), retain_result: true, }; - let completion = OnceCell::new(); + let completion = VolumeCompletion::default(); let http = client(); for _ in 0..2 { let mut execution = result(batch.clone(), true); @@ -526,6 +541,80 @@ mod tests { assert_eq!(request.headers["x-file-header"], "value"); } + #[tokio::test] + async fn cancelled_reader_does_not_replay_upload() { + use std::time::Duration; + + let server = MockServer::start().await; + Mock::given(method("PUT")) + .respond_with(ResponseTemplate::new(200).set_delay(Duration::from_secs(5))) + .expect(1) + .mount(&server) + .await; + let directory = tempfile::tempdir().unwrap(); + let source = directory.path().join("upload"); + std::fs::write(&source, b"upload").unwrap(); + let batch = instruction("PUT", &server.uri(), source.to_str().unwrap()); + let options = VolumeOptions { + paths: Some(vec![directory.path().to_str().unwrap().into()]), + retain_result: false, + }; + let completion = VolumeCompletion::default(); + let http = client(); + let mut in_flight = Box::pin(complete( + &http, + result(batch.clone(), true), + &options, + &completion, + )); + tokio::time::timeout(Duration::from_secs(5), async { + while server.received_requests().await.unwrap().is_empty() { + tokio::select! { + _ = &mut in_flight => panic!("upload completed before cancellation"), + _ = tokio::time::sleep(Duration::from_millis(5)) => {} + } + } + }) + .await + .unwrap(); + drop(in_flight); + let error = tokio::time::timeout( + Duration::from_millis(500), + complete(&http, result(batch, true), &options, &completion), + ) + .await + .unwrap() + .err() + .unwrap(); + assert_eq!(error.code, ErrorCode::Cancelled); + assert_eq!(error.error_code.as_deref(), Some("FILE_TRANSFER_ERROR")); + assert_eq!(error.query_id.as_deref(), Some("statement")); + let requests = server.received_requests().await.unwrap(); + assert_eq!(requests.len(), 1); + assert_eq!(requests[0].body, b"upload"); + } + + #[tokio::test] + async fn explicit_plaintext_opt_in_accepts_ipv6_loopback() { + let listener = std::net::TcpListener::bind("[::1]:0").unwrap(); + let server = MockServer::builder().listener(listener).start().await; + Mock::given(method("DELETE")) + .respond_with(ResponseTemplate::new(404)) + .expect(1) + .mount(&server) + .await; + transfer( + &client(), + "REMOVE", + &server.uri(), + &HashMap::new(), + None, + &[], + ) + .await + .unwrap(); + } + #[test] fn file_errors_keep_their_category() { use std::io::ErrorKind; @@ -895,7 +984,7 @@ mod tests { paths: Some(vec![]), retain_result: false, }, - &OnceCell::new(), + &VolumeCompletion::default(), ) .await .err() @@ -932,7 +1021,7 @@ mod tests { paths: Some(vec![]), retain_result: false, }, - &OnceCell::new(), + &VolumeCompletion::default(), ) .await .err() @@ -959,7 +1048,7 @@ mod tests { &client(), result(batch.clone(), marker), &options, - &OnceCell::new(), + &VolumeCompletion::default(), ) .await .unwrap(); From ed829e8ac8b27bdb503beaf6576dc41876df9465 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Thu, 12 Nov 2026 01:27:21 +0000 Subject: [PATCH 16/39] fix(statement): preserve transfer policy and timeout diagnostics Signed-off-by: Aakash Saravanan --- src/statement/volume.rs | 113 ++++++++++++++++++++++++++++++++++++++-- 1 file changed, 109 insertions(+), 4 deletions(-) diff --git a/src/statement/volume.rs b/src/statement/volume.rs index 7bf646b5..d873cbb2 100644 --- a/src/statement/volume.rs +++ b/src/statement/volume.rs @@ -123,7 +123,12 @@ pub(crate) async fn complete( e = e.with_error_code("FILE_TRANSFER_ERROR"); } if e.sql_state.is_none() { - e = e.with_sql_state("HY000"); + let state = if e.code == ErrorCode::Timeout { + "HYT00" + } else { + "HY000" + }; + e = e.with_sql_state(state); } e.with_query_id(&statement_id) }) @@ -215,17 +220,48 @@ fn resolved_path(path: &Path) -> Result { } } +fn missing_path_for_policy(path: &Path) -> Result { + let absolute = std::path::absolute(path).map_err(file_error)?; + for ancestor in absolute.ancestors().skip(1) { + if let Ok(mut resolved) = ancestor.canonicalize() { + let suffix = absolute.strip_prefix(ancestor).unwrap(); + for component in suffix.components() { + match component { + std::path::Component::ParentDir => { + resolved.pop(); + } + std::path::Component::CurDir => {} + component => resolved.push(component.as_os_str()), + } + } + return Ok(resolved); + } + } + Err(Error::new( + ErrorCode::PermissionDenied, + "Cannot resolve local file path", + )) +} + fn allowed_path(local_file: Option<&str>, paths: &[String]) -> Result { let file = local_file.filter(|s| !s.is_empty()).ok_or_else(|| { Error::invalid_argument().message("Local file path is required for PUT and GET") })?; - let file = resolved_path(Path::new(file))?; + let resolved = resolved_path(Path::new(file)); + let policy_path = match &resolved { + Ok(file) => file.clone(), + Err(error) if error.code == ErrorCode::NotFound => { + // Missing components may classify a denial, but must never authorize file access. + missing_path_for_policy(Path::new(file))? + } + Err(error) => return Err(error.clone()), + }; for base in paths { let Ok(base) = resolved_path(Path::new(base)) else { continue; }; - if file.starts_with(base) { - return Ok(file); + if policy_path.starts_with(base) { + return resolved; } } Err(Error::new( @@ -970,6 +1006,75 @@ mod tests { assert_eq!(attempts.load(Ordering::SeqCst), 1); } + #[test] + fn missing_parent_preserves_policy_denial() { + let directory = tempfile::tempdir().unwrap(); + let allowed = directory.path().join("allowed"); + std::fs::create_dir(&allowed).unwrap(); + let paths = [allowed.to_str().unwrap().to_owned()]; + for (path, expected) in [ + (allowed.join("missing/file"), ErrorCode::NotFound), + ( + directory.path().join("outside/missing/file"), + ErrorCode::PermissionDenied, + ), + ( + allowed.join("missing/../../outside/file"), + ErrorCode::PermissionDenied, + ), + ] { + let error = allowed_path(path.to_str(), &paths).unwrap_err(); + assert_eq!(error.code, expected); + } + #[cfg(unix)] + { + let outside = directory.path().join("outside"); + std::fs::create_dir(&outside).unwrap(); + std::os::unix::fs::symlink(&outside, allowed.join("link")).unwrap(); + let error = + allowed_path(allowed.join("link/missing/file").to_str(), &paths).unwrap_err(); + assert_eq!(error.code, ErrorCode::PermissionDenied); + } + } + + #[tokio::test] + async fn storage_deadline_keeps_timeout_state_and_transfer_context() { + use crate::client::retry::{RequestCategory, RetryConfig}; + let server = MockServer::start().await; + Mock::given(method("DELETE")) + .respond_with(ResponseTemplate::new(200)) + .expect(0) + .mount(&server) + .await; + let retry = RetryConfig { + overall_timeout: std::time::Duration::ZERO, + ..Default::default() + }; + let mut http = DatabricksHttpClient::new( + HttpClientConfig::default(), + HashMap::from([(RequestCategory::CloudFetch, retry)]), + ) + .unwrap(); + http.allow_loopback_plaintext_storage = true; + let batch = instruction("REMOVE", &server.uri(), ""); + let error = complete( + &http, + result(batch, true), + &VolumeOptions { + paths: Some(vec![]), + retain_result: false, + }, + &VolumeCompletion::default(), + ) + .await + .err() + .unwrap(); + assert_eq!(error.code, ErrorCode::Timeout); + assert_eq!(error.sql_state.as_deref(), Some("HYT00")); + assert_eq!(error.error_code.as_deref(), Some("FILE_TRANSFER_ERROR")); + assert_eq!(error.query_id.as_deref(), Some("statement")); + } + #[tokio::test] async fn malformed_instruction_keeps_transfer_error_context() { let batch = RecordBatch::try_from_iter(vec![( From 2006c55d1b67903ca7b6090d0b84a2be73fcb82f Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Thu, 12 Nov 2026 01:40:10 +0000 Subject: [PATCH 17/39] fix(adbc): expose configured file transfer paths Signed-off-by: Aakash Saravanan --- adbc/src/statement.rs | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/adbc/src/statement.rs b/adbc/src/statement.rs index 625a8760..262acec3 100644 --- a/adbc/src/statement.rs +++ b/adbc/src/statement.rs @@ -596,6 +596,12 @@ impl Statement { fn get_other_string(&self, key: &str) -> Result { match key { + "adbc.databricks.statement.staging_allowed_local_paths" => { + serde_json::to_string(&self.inner()?.spec_ref().staging_allowed_local_paths) + .map_err(|_| { + adbc_error("Cannot serialize allowed local paths", Status::Internal) + }) + } ENABLE_DIRECT_RESULTS_OPTION => Ok(self.enable_direct_results.to_string()), IS_METADATA_COMMAND_OPTION => Ok(self.metadata_options.enabled.to_string()), METADATA_CATALOG_OPTION => metadata_string_option( @@ -1509,6 +1515,7 @@ mod tests { let mut statement = connection.new_statement().unwrap(); let option = OptionStatement::Other("adbc.databricks.statement.staging_allowed_local_paths".into()); + assert_eq!(statement.get_option_string(option.clone()).unwrap(), "null"); for (value, expected) in [ (r#"["/tmp/files"]"#, Some(vec!["/tmp/files".to_owned()])), ("[]", Some(vec![])), @@ -1523,8 +1530,11 @@ mod tests { .staging_allowed_local_paths, expected ); + assert_eq!(statement.get_option_string(option.clone()).unwrap(), value); } - let error = statement.set_option(option, "{}".into()).unwrap_err(); + let error = statement + .set_option(option.clone(), "{}".into()) + .unwrap_err(); assert_eq!(error.status, Status::InvalidArguments); assert_eq!( statement @@ -1534,6 +1544,7 @@ mod tests { .staging_allowed_local_paths, None ); + assert_eq!(statement.get_option_string(option).unwrap(), "null"); } fn batch(rows: usize) -> RecordBatch { From 892ee5698302b4e34db5ea926baa0354e9c229da Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Thu, 12 Nov 2026 01:49:05 +0000 Subject: [PATCH 18/39] docs(bindings): describe transfer instruction consumption Signed-off-by: Aakash Saravanan --- napi/index.d.ts | 5 ++++- napi/src/connection.rs | 1 + pyo3/src/statement.rs | 3 ++- 3 files changed, 7 insertions(+), 2 deletions(-) diff --git a/napi/index.d.ts b/napi/index.d.ts index 8ffef883..e0e82327 100644 --- a/napi/index.d.ts +++ b/napi/index.d.ts @@ -38,7 +38,10 @@ * path is the one the production code uses. */ export interface ExecuteOptions { - /** Omit to handle instructions in the caller; an empty list denies local file access. */ + /** + * Configured transfers consume instruction rows. + * Omit to handle instructions in the caller; an empty list denies local file access. + */ stagingAllowedLocalPaths?: string[] /** * Per-statement Spark conf overlay. Merged on top of the diff --git a/napi/src/connection.rs b/napi/src/connection.rs index 4b1ea4b0..8de29311 100644 --- a/napi/src/connection.rs +++ b/napi/src/connection.rs @@ -102,6 +102,7 @@ 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, + /// Configured transfers consume instruction rows. /// Omit to handle instructions in the caller; an empty list denies local file access. pub staging_allowed_local_paths: Option>, /// Positional parameters, in 1-based wire order. Index `i` in this diff --git a/pyo3/src/statement.rs b/pyo3/src/statement.rs index dc43e64a..79030e8b 100644 --- a/pyo3/src/statement.rs +++ b/pyo3/src/statement.rs @@ -66,7 +66,8 @@ impl Statement { Ok(()) } - /// Set permitted local paths; ``None`` restores caller-managed transfers. + /// Configured transfers consume instruction rows. + /// ``None`` restores caller-managed transfers. fn set_staging_allowed_local_paths(&mut self, paths: Option>) -> PyResult<()> { let inner = alive_mut!(self, "Statement"); inner.stmt.spec().staging_allowed_local_paths = paths; From 00e1701a9b14082dba9e4d4d7d8df378971e1818 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Thu, 12 Nov 2026 01:59:53 +0000 Subject: [PATCH 19/39] fix(http): limit plaintext storage to local sessions Signed-off-by: Aakash Saravanan --- src/client/http.rs | 35 +++++++++++++++++++++++++++++++++++ src/session.rs | 6 +++--- src/statement/volume.rs | 34 ++-------------------------------- 3 files changed, 40 insertions(+), 35 deletions(-) diff --git a/src/client/http.rs b/src/client/http.rs index 004b6b50..c80fb363 100644 --- a/src/client/http.rs +++ b/src/client/http.rs @@ -36,6 +36,20 @@ use std::sync::{Arc, OnceLock}; use std::time::{Duration, Instant}; use tokio::time::sleep; +pub(crate) fn is_loopback_http_url(url: &reqwest::Url) -> bool { + url.scheme() == "http" + && url.host_str().is_some_and(|host| { + let host = host + .strip_prefix('[') + .and_then(|host| host.strip_suffix(']')) + .unwrap_or(host); + host == "localhost" + || host + .parse::() + .is_ok_and(|ip| ip.is_loopback()) + }) +} + /// Build an `Error` for a transport-level non-2xx HTTP response, parsing /// the SEA error envelope out of the response body when present. /// @@ -1102,6 +1116,27 @@ mod tests { use crate::auth::PersonalAccessToken; use crate::client::retry::build_retry_configs; + #[test] + fn plaintext_storage_requires_a_loopback_http_url() { + for (url, allowed) in [ + ("http://localhost:8080", true), + ("http://127.0.0.1:8080", true), + ("http://127.1.2.3:8080", true), + ("http://[::1]:8080", true), + ("https://localhost", false), + ("http://example.com", false), + ("http://localhost.example.com", false), + ("http://192.0.2.1", false), + ("http://[2001:db8::1]", false), + ] { + assert_eq!( + is_loopback_http_url(&reqwest::Url::parse(url).unwrap()), + allowed, + "{url}" + ); + } + } + fn default_retry_configs() -> HashMap { build_retry_configs(&RetryConfig::default(), &HashMap::new()) } diff --git a/src/session.rs b/src/session.rs index e96a8012..81d9abf2 100644 --- a/src/session.rs +++ b/src/session.rs @@ -372,9 +372,9 @@ impl Session { .map_err(|e| { Error::network_error().message(format!("Failed to construct HTTP client: {e}")) })?; - // Explicit HTTP sessions allow loopback storage for local integrations. - http_client.allow_loopback_plaintext_storage = - reqwest::Url::parse(&host).is_ok_and(|url| url.scheme() == "http"); + // Local HTTP sessions allow loopback storage for local integrations. + http_client.allow_loopback_plaintext_storage = reqwest::Url::parse(&host) + .is_ok_and(|url| crate::client::http::is_loopback_http_url(&url)); let http_client = Arc::new(http_client); // 2. Auth provider — async because OAuth flows hit the OIDC diff --git a/src/statement/volume.rs b/src/statement/volume.rs index d873cbb2..8d1a2440 100644 --- a/src/statement/volume.rs +++ b/src/statement/volume.rs @@ -287,18 +287,9 @@ async fn transfer( }; let parsed = reqwest::Url::parse(url) .map_err(|_| Error::invalid_state().message("Invalid file transfer URL"))?; - let loopback = parsed.host_str().is_some_and(|host| { - let host = host - .strip_prefix('[') - .and_then(|host| host.strip_suffix(']')) - .unwrap_or(host); - host == "localhost" - || host - .parse::() - .is_ok_and(|ip| ip.is_loopback()) - }); if parsed.scheme() != "https" - && !(parsed.scheme() == "http" && loopback && client.allow_loopback_plaintext_storage) + && !(client.allow_loopback_plaintext_storage + && crate::client::http::is_loopback_http_url(&parsed)) { return Err(Error::invalid_state().message("Invalid file transfer URL scheme")); } @@ -630,27 +621,6 @@ mod tests { assert_eq!(requests[0].body, b"upload"); } - #[tokio::test] - async fn explicit_plaintext_opt_in_accepts_ipv6_loopback() { - let listener = std::net::TcpListener::bind("[::1]:0").unwrap(); - let server = MockServer::builder().listener(listener).start().await; - Mock::given(method("DELETE")) - .respond_with(ResponseTemplate::new(404)) - .expect(1) - .mount(&server) - .await; - transfer( - &client(), - "REMOVE", - &server.uri(), - &HashMap::new(), - None, - &[], - ) - .await - .unwrap(); - } - #[test] fn file_errors_keep_their_category() { use std::io::ErrorKind; From e78a4b1e58562e03a06c9166cc76bde5842f1de0 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Thu, 12 Nov 2026 02:09:49 +0000 Subject: [PATCH 20/39] fix(volume): classify permanent local IO failures Signed-off-by: Aakash Saravanan --- src/statement/volume.rs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/statement/volume.rs b/src/statement/volume.rs index 8d1a2440..2a373598 100644 --- a/src/statement/volume.rs +++ b/src/statement/volume.rs @@ -192,7 +192,7 @@ fn file_error(error: std::io::Error) -> Error { std::io::ErrorKind::InvalidInput => ErrorCode::InvalidArgument, std::io::ErrorKind::TimedOut => ErrorCode::Timeout, std::io::ErrorKind::StorageFull => ErrorCode::ResourceExhausted, - _ => ErrorCode::Unavailable, + _ => ErrorCode::Internal, }, format!("File transfer failed: {error}"), ); @@ -630,10 +630,13 @@ mod tests { (ErrorKind::InvalidInput, ErrorCode::InvalidArgument), (ErrorKind::StorageFull, ErrorCode::ResourceExhausted), (ErrorKind::TimedOut, ErrorCode::Timeout), - (ErrorKind::Other, ErrorCode::Unavailable), + (ErrorKind::IsADirectory, ErrorCode::Internal), + (ErrorKind::ReadOnlyFilesystem, ErrorCode::Internal), + (ErrorKind::Other, ErrorCode::Internal), ] { let error = file_error(std::io::Error::from(kind)); assert_eq!(error.code, code); + assert!(!error.retryable); assert_eq!( error.error_code.as_deref(), (kind == ErrorKind::PermissionDenied).then_some("FILE_TRANSFER_PERMISSION_ERROR") From f139344c9c8cf9f3224f6d3068adba08632a0c32 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Thu, 12 Nov 2026 02:39:51 +0000 Subject: [PATCH 21/39] fix(staging): preserve timeout category during storage requests Signed-off-by: Aakash Saravanan --- src/statement/volume.rs | 32 ++++++++++++++++++++++---------- 1 file changed, 22 insertions(+), 10 deletions(-) diff --git a/src/statement/volume.rs b/src/statement/volume.rs index 2a373598..92120c47 100644 --- a/src/statement/volume.rs +++ b/src/statement/volume.rs @@ -376,6 +376,11 @@ async fn transfer( } fn transport_error(error: reqwest::Error) -> Error { + let code = if error.is_timeout() { + ErrorCode::Timeout + } else { + ErrorCode::NetworkError + }; let message = if error.is_timeout() { "File transfer timed out" } else if error.is_connect() { @@ -385,10 +390,7 @@ fn transport_error(error: reqwest::Error) -> Error { } else { "File transfer request failed" }; - Error::new(ErrorCode::NetworkError, message).with_cause(Error::new( - ErrorCode::NetworkError, - format!("{:?}", error.without_url()), - )) + Error::new(code, message).with_cause(Error::new(code, format!("{:?}", error.without_url()))) } async fn send_transfer( @@ -1204,20 +1206,30 @@ mod tests { if existing { std::fs::write(&file, b"original").unwrap(); } - let result = transfer( - &http, + let batch = instruction( "GET", &format!("http://{address}/file"), - &HashMap::new(), - file.to_str(), - &[dir.path().to_str().unwrap().into()], + file.to_str().unwrap(), + ); + let result = complete( + &http, + result(batch, true), + &VolumeOptions { + paths: Some(vec![dir.path().to_str().unwrap().into()]), + retain_result: false, + }, + &VolumeCompletion::default(), ) .await; assert_eq!(result.is_ok(), succeeds); if succeeds { assert_eq!(std::fs::read(&file).unwrap(), b"data"); } else { - assert_eq!(result.unwrap_err().code, ErrorCode::NetworkError); + let error = result.err().unwrap(); + assert_eq!(error.code, ErrorCode::Timeout); + assert_eq!(error.sql_state.as_deref(), Some("HYT00")); + assert_eq!(error.error_code.as_deref(), Some("FILE_TRANSFER_ERROR")); + assert_eq!(error.query_id.as_deref(), Some("statement")); if existing { assert_eq!(std::fs::read(&file).unwrap(), b"original"); } else { From 9f7bf932aacbd76ff67c52cc1cd84082af2e5ab0 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Thu, 12 Nov 2026 03:05:45 +0000 Subject: [PATCH 22/39] fix(volume): preserve local OS error codes across Python bindings Signed-off-by: Aakash Saravanan --- pyo3/src/errors.rs | 28 ++++++++++++++++++++++++++++ src/kernel_error.rs | 5 +++++ src/statement/volume.rs | 12 +++++++++--- 3 files changed, 42 insertions(+), 3 deletions(-) diff --git a/pyo3/src/errors.rs b/pyo3/src/errors.rs index 88ff4257..25644d05 100644 --- a/pyo3/src/errors.rs +++ b/pyo3/src/errors.rs @@ -70,12 +70,14 @@ fn attach_attrs( display_message: Option<&str>, diagnostic_info: Option<&str>, error_details_json: Option<&str>, + os_error_code: Option, ) -> PyResult<()> { bound.setattr("code", code)?; bound.setattr("message", message)?; bound.setattr("sql_state", sql_state)?; bound.setattr("error_code", error_code)?; bound.setattr("vendor_code", vendor_code)?; + bound.setattr("os_error_code", os_error_code)?; bound.setattr("http_status", http_status)?; bound.setattr("retryable", retryable)?; bound.setattr("query_id", query_id)?; @@ -138,6 +140,7 @@ pub(crate) fn to_py_err(py: Python<'_>, err: KError) -> PyErr { err.display_message.as_deref(), err.diagnostic_info.as_deref(), err.error_details_json.as_deref(), + err.os_error_code, ) { // Attribute attachment is best-effort. If something goes wrong // (extremely unlikely for plain string/int setattrs — but @@ -182,9 +185,34 @@ pub(crate) fn closed_err(handle_name: &str) -> PyErr { None, None, None, + None, ) { return setattr_err; } py_err }) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn local_os_error_code_crosses_python_boundary() { + Python::initialize(); + Python::attach(|py| { + for raw in [None, Some(1), Some(2), Some(5), Some(13)] { + let mut error = KError::new(ErrorCode::NotFound, "missing file"); + error.os_error_code = raw; + let mapped = to_py_err(py, error); + let actual: Option = mapped + .value(py) + .getattr("os_error_code") + .unwrap() + .extract() + .unwrap(); + assert_eq!(actual, raw); + } + }); + } +} diff --git a/src/kernel_error.rs b/src/kernel_error.rs index ecfb7fb2..831f1d72 100644 --- a/src/kernel_error.rs +++ b/src/kernel_error.rs @@ -197,6 +197,10 @@ pub struct Error { /// the string `error_code` themselves. pub vendor_code: Option, + /// Original local OS error code for language-native filesystem errors. + /// Uses errno on Unix and the Windows system error code on Windows. + pub os_error_code: Option, + /// HTTP status for transport-layer errors. pub http_status: Option, @@ -262,6 +266,7 @@ impl Error { sql_state: None, error_code: None, vendor_code: None, + os_error_code: None, http_status: None, retryable: false, query_id: None, diff --git a/src/statement/volume.rs b/src/statement/volume.rs index 92120c47..8b8d1288 100644 --- a/src/statement/volume.rs +++ b/src/statement/volume.rs @@ -185,7 +185,7 @@ fn instruction_headers(batch: &RecordBatch) -> Result> { fn file_error(error: std::io::Error) -> Error { let permission_denied = error.kind() == std::io::ErrorKind::PermissionDenied; - let error = Error::new( + let mut mapped = Error::new( match error.kind() { std::io::ErrorKind::NotFound => ErrorCode::NotFound, std::io::ErrorKind::PermissionDenied => ErrorCode::PermissionDenied, @@ -196,10 +196,11 @@ fn file_error(error: std::io::Error) -> Error { }, format!("File transfer failed: {error}"), ); + mapped.os_error_code = error.raw_os_error(); if permission_denied { - error.with_error_code("FILE_TRANSFER_PERMISSION_ERROR") + mapped.with_error_code("FILE_TRANSFER_PERMISSION_ERROR") } else { - error + mapped } } @@ -639,11 +640,16 @@ mod tests { let error = file_error(std::io::Error::from(kind)); assert_eq!(error.code, code); assert!(!error.retryable); + assert_eq!(error.os_error_code, None); assert_eq!( error.error_code.as_deref(), (kind == ErrorKind::PermissionDenied).then_some("FILE_TRANSFER_PERMISSION_ERROR") ); } + for raw in [1, 2, 5, 13] { + let error = file_error(std::io::Error::from_raw_os_error(raw)); + assert_eq!(error.os_error_code, Some(raw)); + } } #[tokio::test] From be474276cbffa2aa89eeee593c957cacc7b43c81 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Thu, 12 Nov 2026 03:16:17 +0000 Subject: [PATCH 23/39] fix(volume): preserve requested filenames in local OS errors Signed-off-by: Aakash Saravanan --- pyo3/src/errors.rs | 21 +++++++++++++++-- src/kernel_error.rs | 16 +++++++++---- src/statement/volume.rs | 51 +++++++++++++++++++++++++++++++++++++---- 3 files changed, 77 insertions(+), 11 deletions(-) diff --git a/pyo3/src/errors.rs b/pyo3/src/errors.rs index 25644d05..01a252ce 100644 --- a/pyo3/src/errors.rs +++ b/pyo3/src/errors.rs @@ -71,6 +71,7 @@ fn attach_attrs( diagnostic_info: Option<&str>, error_details_json: Option<&str>, os_error_code: Option, + os_error_filename: Option<&str>, ) -> PyResult<()> { bound.setattr("code", code)?; bound.setattr("message", message)?; @@ -78,6 +79,7 @@ fn attach_attrs( bound.setattr("error_code", error_code)?; bound.setattr("vendor_code", vendor_code)?; bound.setattr("os_error_code", os_error_code)?; + bound.setattr("os_error_filename", os_error_filename)?; bound.setattr("http_status", http_status)?; bound.setattr("retryable", retryable)?; bound.setattr("query_id", query_id)?; @@ -140,7 +142,8 @@ pub(crate) fn to_py_err(py: Python<'_>, err: KError) -> PyErr { err.display_message.as_deref(), err.diagnostic_info.as_deref(), err.error_details_json.as_deref(), - err.os_error_code, + err.os_error.as_ref().map(|e| e.code), + err.os_error.as_ref().and_then(|e| e.filename.as_deref()), ) { // Attribute attachment is best-effort. If something goes wrong // (extremely unlikely for plain string/int setattrs — but @@ -186,6 +189,7 @@ pub(crate) fn closed_err(handle_name: &str) -> PyErr { None, None, None, + None, ) { return setattr_err; } @@ -196,6 +200,7 @@ pub(crate) fn closed_err(handle_name: &str) -> PyErr { #[cfg(test)] mod tests { use super::*; + use databricks_sql_kernel::kernel_error::OsError; #[test] fn local_os_error_code_crosses_python_boundary() { @@ -203,7 +208,12 @@ mod tests { Python::attach(|py| { for raw in [None, Some(1), Some(2), Some(5), Some(13)] { let mut error = KError::new(ErrorCode::NotFound, "missing file"); - error.os_error_code = raw; + error.os_error = raw.map(|code| { + Box::new(OsError { + code, + filename: Some("local-file.bin".to_owned()), + }) + }); let mapped = to_py_err(py, error); let actual: Option = mapped .value(py) @@ -212,6 +222,13 @@ mod tests { .extract() .unwrap(); assert_eq!(actual, raw); + let filename: Option = mapped + .value(py) + .getattr("os_error_filename") + .unwrap() + .extract() + .unwrap(); + assert_eq!(filename.as_deref(), raw.map(|_| "local-file.bin")); } }); } diff --git a/src/kernel_error.rs b/src/kernel_error.rs index 831f1d72..81e1a6bb 100644 --- a/src/kernel_error.rs +++ b/src/kernel_error.rs @@ -158,6 +158,15 @@ impl ErrorCode { } } +/// Local OS failure details for language-native filesystem exceptions. +#[derive(Debug, Clone)] +pub struct OsError { + /// Uses errno on Unix and the Windows system error code on Windows. + pub code: i32, + /// Requested local path for a file-transfer OS error. + pub filename: Option, +} + /// Typed kernel error. /// /// `cause` chains preserve the underlying provenance — a `SqlError` @@ -197,9 +206,8 @@ pub struct Error { /// the string `error_code` themselves. pub vendor_code: Option, - /// Original local OS error code for language-native filesystem errors. - /// Uses errno on Unix and the Windows system error code on Windows. - pub os_error_code: Option, + /// Local OS failure details, boxed to keep other errors small. + pub os_error: Option>, /// HTTP status for transport-layer errors. pub http_status: Option, @@ -266,7 +274,7 @@ impl Error { sql_state: None, error_code: None, vendor_code: None, - os_error_code: None, + os_error: None, http_status: None, retryable: false, query_id: None, diff --git a/src/statement/volume.rs b/src/statement/volume.rs index 8b8d1288..4117ac4a 100644 --- a/src/statement/volume.rs +++ b/src/statement/volume.rs @@ -15,7 +15,7 @@ use crate::client::retry::{calculate_backoff, RequestType, RetryStrategy}; use crate::client::transport::ExecuteResult; use crate::client::DatabricksHttpClient; -use crate::kernel_error::{Error, ErrorCode, Result}; +use crate::kernel_error::{Error, ErrorCode, OsError, Result}; use crate::reader::{EmptyReader, InMemoryReader}; use crate::result_stream::{ResultBatch, ResultStream}; use crate::statement::StatementSpec; @@ -105,7 +105,13 @@ pub(crate) async fn complete( local_file.as_deref(), paths, ) - .await, + .await + .map_err(|mut error| { + if let Some(os_error) = error.os_error.as_mut() { + os_error.filename = local_file.clone(); + } + error + }), ); } completed.as_ref().unwrap().clone()?; @@ -196,7 +202,12 @@ fn file_error(error: std::io::Error) -> Error { }, format!("File transfer failed: {error}"), ); - mapped.os_error_code = error.raw_os_error(); + mapped.os_error = error.raw_os_error().map(|code| { + Box::new(OsError { + code, + filename: None, + }) + }); if permission_denied { mapped.with_error_code("FILE_TRANSFER_PERMISSION_ERROR") } else { @@ -640,7 +651,7 @@ mod tests { let error = file_error(std::io::Error::from(kind)); assert_eq!(error.code, code); assert!(!error.retryable); - assert_eq!(error.os_error_code, None); + assert!(error.os_error.is_none()); assert_eq!( error.error_code.as_deref(), (kind == ErrorKind::PermissionDenied).then_some("FILE_TRANSFER_PERMISSION_ERROR") @@ -648,10 +659,40 @@ mod tests { } for raw in [1, 2, 5, 13] { let error = file_error(std::io::Error::from_raw_os_error(raw)); - assert_eq!(error.os_error_code, Some(raw)); + assert_eq!(error.os_error.as_ref().map(|e| e.code), Some(raw)); } } + #[tokio::test] + async fn local_os_errors_keep_requested_filename() { + let server = MockServer::start().await; + let dir = tempfile::tempdir().unwrap(); + let local = dir.path().join("absent-parent/file"); + let expected_code = std::fs::File::open(&local).unwrap_err().raw_os_error(); + let options = VolumeOptions { + paths: Some(vec![dir.path().to_str().unwrap().into()]), + retain_result: false, + }; + for operation in ["PUT", "GET"] { + let batch = instruction(operation, &server.uri(), local.to_str().unwrap()); + let error = complete( + &client(), + result(batch, true), + &options, + &VolumeCompletion::default(), + ) + .await + .err() + .unwrap(); + assert_eq!(error.code, ErrorCode::NotFound); + let os_error = error.os_error.as_ref().unwrap(); + assert_eq!(Some(os_error.code), expected_code); + assert_eq!(os_error.filename.as_deref(), local.to_str()); + assert_eq!(error.error_code.as_deref(), Some("FILE_TRANSFER_ERROR")); + } + assert!(server.received_requests().await.unwrap().is_empty()); + } + #[tokio::test] async fn storage_redirects_are_not_followed_and_plaintext_requires_opt_out() { let server = MockServer::start().await; From f8211f44018af231a31dbfa01d97e821f75c23e5 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Thu, 12 Nov 2026 03:44:13 +0000 Subject: [PATCH 24/39] fix(volume): write through the existing temporary file handle Signed-off-by: Aakash Saravanan --- src/statement/volume.rs | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/src/statement/volume.rs b/src/statement/volume.rs index 4117ac4a..4bce4255 100644 --- a/src/statement/volume.rs +++ b/src/statement/volume.rs @@ -364,7 +364,8 @@ async fn transfer( builder }; let temporary = builder.tempfile_in(parent).map_err(file_error)?; - let mut file = tokio::fs::File::from_std(temporary.reopen().map_err(file_error)?); + let mut file = + tokio::fs::File::from_std(temporary.as_file().try_clone().map_err(file_error)?); let mut body = response.bytes_stream(); while let Some(bytes) = body.next().await { let bytes = bytes.map_err(transport_error)?; @@ -787,7 +788,7 @@ mod tests { let server = MockServer::start().await; Mock::given(method("GET")) .respond_with(ResponseTemplate::new(200).set_body_bytes(b"contents")) - .expect(2) + .expect(3) .mount(&server) .await; let dir = tempfile::tempdir().unwrap(); @@ -795,9 +796,9 @@ mod tests { let control = dir.path().join("control"); std::fs::write(&control, b"").unwrap(); let roots = vec![dir.path().to_str().unwrap().into()]; - for existing in [false, true] { - if existing { - std::fs::set_permissions(&destination, std::fs::Permissions::from_mode(0o640)) + for existing in [None, Some(0o640), Some(0o200)] { + if let Some(mode) = existing { + std::fs::set_permissions(&destination, std::fs::Permissions::from_mode(mode)) .unwrap(); } transfer( @@ -810,11 +811,9 @@ mod tests { ) .await .unwrap(); - let expected = if existing { - 0o640 - } else { + let expected = existing.unwrap_or_else(|| { std::fs::metadata(&control).unwrap().permissions().mode() & 0o777 - }; + }); assert_eq!( std::fs::metadata(&destination) .unwrap() From 23cd28e82876a75d0ecbaa487018906bc0dca924 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Thu, 12 Nov 2026 03:44:14 +0000 Subject: [PATCH 25/39] fix(volume): interrupt local transfers on detached cancellation Signed-off-by: Aakash Saravanan --- src/c_abi/statement.rs | 4 +-- src/statement/mutable.rs | 70 +++++++++++++++++++++++++++------------- 2 files changed, 50 insertions(+), 24 deletions(-) diff --git a/src/c_abi/statement.rs b/src/c_abi/statement.rs index dc35aafd..b71d0f7b 100644 --- a/src/c_abi/statement.rs +++ b/src/c_abi/statement.rs @@ -651,7 +651,7 @@ pub unsafe extern "C" fn kernel_statement_canceller_new( KernelStatusCode::Success } -/// Fire a server-side cancel of the statement this canceller was created for. +/// Interrupt its local file transfer and send a server-side statement cancel. /// Idempotent and safe to call concurrently with `kernel_statement_execute` on /// the originating statement. /// @@ -697,7 +697,7 @@ pub unsafe extern "C" fn kernel_statement_canceller_cancel( let Some(handle) = (canceller as *mut CancellerHandle).as_ref() else { return store_invalid_arg("kernel_statement_canceller_cancel: handle must not be null"); }; - // Clone the canceller (two Arc bumps) so the blocking cancel RPC owns its + // Clone the canceller so the blocking cancel RPC owns its // session and id-slot handles rather than borrowing through this box. let canceller = handle.canceller.clone(); match block_on_ffi(move || Box::pin(async move { canceller.cancel().await })) { diff --git a/src/statement/mutable.rs b/src/statement/mutable.rs index 5ee16466..a0f237bf 100644 --- a/src/statement/mutable.rs +++ b/src/statement/mutable.rs @@ -54,6 +54,7 @@ //! stale handle short-circuits locally — no network round-trip. See //! `crate::statement::validity` for the flag implementation. +use crate::client::transport::ExecuteResult; use crate::client::{DirectOutcome, ExecutionTimeout}; use crate::kernel_error::{Error, Result}; use crate::klog::{debug, warn}; @@ -69,6 +70,7 @@ use crate::types::sea::{ExecuteParams, QueryTag, StatementState}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex}; use std::time::Duration; +use tokio::sync::watch; use tracing::Instrument; /// Outcome of [`Statement::execute_direct`] — the Thrift/JDBC directResults @@ -245,6 +247,7 @@ pub struct Statement { /// new `execute()` / `submit()` so a canceller never targets a /// stale prior statement. inflight_id: InflightId, + volume_cancellation: watch::Sender>, } impl Statement { @@ -258,6 +261,7 @@ impl Statement { last_valid: None, last_closed: None, inflight_id: Arc::new(Mutex::new(None)), + volume_cancellation: watch::channel(None).0, } } @@ -274,7 +278,7 @@ impl Statement { /// once the server issues the statement id mid-execute, the /// canceller's [`cancel`](StatementCanceller::cancel) reaches it. /// - /// Cheap to clone (two `Arc` bumps). If `cancel()` fires before the + /// Cheap to clone. If `cancel()` fires before the /// id is observed (query still in the initial submit round-trip) it /// is a no-op; the per-call drop guard still covers the /// future-dropped case. @@ -282,6 +286,7 @@ impl Statement { StatementCanceller { session: Arc::clone(&self.session), inflight_id: Arc::clone(&self.inflight_id), + volume_cancellation: self.volume_cancellation.clone(), } } @@ -409,14 +414,7 @@ impl Statement { self.last_valid = Some(valid.clone()); self.last_closed = Some(Arc::clone(&closed)); - let result = match super::volume::complete( - &self.session.http_client, - result, - &super::volume::VolumeOptions::from(&self.spec), - &super::volume::VolumeCompletion::default(), - ) - .await - { + let result = match self.complete_volume(result).await { Ok(result) => result, Err(error) => { self.invalidate_prior().await; @@ -660,14 +658,7 @@ impl Statement { self.last_statement_id = Some(result.statement_id.clone()); self.last_valid = Some(valid.clone()); self.last_closed = Some(Arc::clone(&closed)); - let result = match super::volume::complete( - &self.session.http_client, - result, - &super::volume::VolumeOptions::from(&self.spec), - &super::volume::VolumeCompletion::default(), - ) - .await - { + let result = match self.complete_volume(result).await { Ok(result) => result, Err(error) => { self.invalidate_prior().await; @@ -781,6 +772,35 @@ impl Statement { build_execute_params(&self.spec, wait_timeout_secs) } + async fn complete_volume(&self, result: ExecuteResult) -> Result { + let is_transfer = self.spec.staging_allowed_local_paths.is_some() + && result + .manifest + .as_ref() + .is_some_and(|manifest| manifest.is_volume_operation); + let statement_id = result.statement_id.clone(); + let options = super::volume::VolumeOptions::from(&self.spec); + let completion = super::volume::VolumeCompletion::default(); + let complete = + super::volume::complete(&self.session.http_client, result, &options, &completion); + if !is_transfer { + return complete.await; + } + // The SQL statement can finish before its local transfer starts. + let mut cancellation = self.volume_cancellation.subscribe(); + tokio::select! { + biased; + _ = cancellation.wait_for(|id| id.as_ref() == Some(&statement_id)) => { + Err(Error::cancelled() + .message("File transfer cancelled") + .with_error_code("FILE_TRANSFER_ERROR") + .with_sql_state("HY000") + .with_query_id(&statement_id)) + } + result = complete => result, + } + } + /// Clear the shared in-flight-id slot at the very start of a new /// dispatch, before any `.await`. /// @@ -950,16 +970,17 @@ impl Drop for MidExecuteCancelGuard { /// is blocked. The sync-execute analogue of /// [`AsyncStatementCanceller`](crate::statement::executed_async::AsyncStatementCanceller). /// -/// Cheap to [`Clone`] (two `Arc` bumps). +/// Cheap to [`Clone`]. #[derive(Clone)] pub struct StatementCanceller { session: Arc, inflight_id: InflightId, + volume_cancellation: watch::Sender>, } impl StatementCanceller { - /// Server-side cancel of the in-flight statement via - /// `cancel_statement(statement_id)`. + /// Interrupt a local file transfer and send the in-flight statement's + /// server-side cancel via `cancel_statement(statement_id)`. /// /// Returns `Ok(true)` if a cancel RPC was POSTed for the currently /// observed statement id, and `Ok(false)` if it was a no-op because no @@ -980,9 +1001,14 @@ impl StatementCanceller { /// Idempotent against a server already in a terminal state (the /// kernel's `cancel_statement` is a no-op there). Safe to call /// concurrently with the `execute()` it targets — the two share - /// only the id slot (behind a `Mutex`), no mutable statement state. + /// only the id slot and transfer-cancellation notification, no mutable + /// statement state. pub async fn cancel(&self) -> Result { - let id = self.inflight_id.lock().ok().and_then(|g| g.clone()); + let id = self.inflight_id.lock().ok().and_then(|slot| { + let id = slot.clone()?; + self.volume_cancellation.send_replace(Some(id.clone())); + Some(id) + }); async { // Log both outcomes at the decision point so a host debugging a // cancel can tell "raced ahead of the id" (no-op) from "wired to From 2dfbb5ce5dd73c611275b6334fad295802f23669 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Thu, 12 Nov 2026 03:58:07 +0000 Subject: [PATCH 26/39] fix(volume): cancel shared asynchronous transfers Signed-off-by: Aakash Saravanan --- src/statement/executed_async.rs | 13 ++-- src/statement/volume.rs | 61 +++++++++++----- tests/v0_async_execute_wiremock.rs | 108 +++++++++++++++++++++++++++++ 3 files changed, 158 insertions(+), 24 deletions(-) diff --git a/src/statement/executed_async.rs b/src/statement/executed_async.rs index 1715b17a..a9b3ed68 100644 --- a/src/statement/executed_async.rs +++ b/src/statement/executed_async.rs @@ -1054,6 +1054,7 @@ impl ExecutedStatementHandle for ExecutedAsyncStatement { submitted it", )); } + self.volume_completion.cancel(); self.session .transport() .cancel_statement(&self.statement_id) @@ -1139,6 +1140,7 @@ impl ExecutedAsyncStatement { session: Arc::clone(&self.session), statement_id: self.statement_id.clone(), valid: self.valid.clone(), + volume_completion: Arc::clone(&self.volume_completion), // Inherit ownership: a canceller derived from an attached // (read-only) handle must not cancel the owner's statement // either — otherwise the footgun just moves to the detached @@ -1150,19 +1152,19 @@ impl ExecutedAsyncStatement { /// Detached canceller for an in-flight async statement. /// -/// Holds only the shared session handle, the statement id, and the -/// shared [`ValidityFlag`] — **not** the [`ExecutedAsyncStatement`] -/// itself — so a binding can fire a server-side cancel while the handle +/// Holds the shared session, statement id, transfer completion, and +/// [`ValidityFlag`] so a binding can cancel while the handle /// is borrowed elsewhere (e.g. parked inside a long-running /// [`ExecutedAsyncStatement::await_result`] that a binding-side lock is /// held across). Produced by [`ExecutedAsyncStatement::canceller`]. /// -/// Cheap to [`Clone`] (one `Arc` bump plus a `String` / flag clone). +/// Cheap to [`Clone`]. #[derive(Clone)] pub struct AsyncStatementCanceller { session: Arc, statement_id: String, valid: ValidityFlag, + volume_completion: Arc, /// Inherited from the producing handle — `false` for a canceller /// derived from an attached (read-only) handle, which must not /// cancel a statement it doesn't own. See @@ -1171,7 +1173,7 @@ pub struct AsyncStatementCanceller { } impl AsyncStatementCanceller { - /// Server-side cancel via `cancel_statement(statement_id)`. + /// Interrupt its local transfer and send `cancel_statement(statement_id)`. /// /// Short-circuits to `InvalidStatementHandle` (no wire round-trip) /// if the parent handle was invalidated (re-execute / parent @@ -1191,6 +1193,7 @@ impl AsyncStatementCanceller { is owned by whoever submitted it", )); } + self.volume_completion.cancel(); self.session .transport() .cancel_statement(&self.statement_id) diff --git a/src/statement/volume.rs b/src/statement/volume.rs index 4bce4255..81cba473 100644 --- a/src/statement/volume.rs +++ b/src/statement/volume.rs @@ -25,10 +25,28 @@ use reqwest::Method; use std::collections::HashMap; use std::path::{Path, PathBuf}; use tokio::io::{AsyncReadExt, AsyncWriteExt}; -use tokio::sync::Mutex; +use tokio::sync::{watch, Mutex}; use tokio_util::io::ReaderStream; -pub(crate) type VolumeCompletion = Mutex>>; +pub(crate) struct VolumeCompletion { + result: Mutex>>, + cancelled: watch::Sender, +} + +impl Default for VolumeCompletion { + fn default() -> Self { + Self { + result: Mutex::new(None), + cancelled: watch::channel(false).0, + } + } +} + +impl VolumeCompletion { + pub(super) fn cancel(&self) { + self.cancelled.send_replace(true); + } +} #[derive(Clone, Default)] pub(crate) struct VolumeOptions { @@ -89,30 +107,35 @@ pub(crate) async fn complete( return Err(Error::invalid_state().message("Expected one file transfer instruction")); } { - let mut completed = completion.lock().await; + let mut completed = completion.result.lock().await; if completed.is_none() { // Cancellation must leave a terminal result instead of replaying an upload. *completed = Some(Err(Error::new( ErrorCode::Cancelled, "File transfer interrupted; re-execute the SQL to retry", ))); - *completed = Some( - transfer( - client, - &operation, - &url, - &headers, - local_file.as_deref(), - paths, - ) - .await - .map_err(|mut error| { - if let Some(os_error) = error.os_error.as_mut() { - os_error.filename = local_file.clone(); - } - error - }), + let mut cancelled = completion.cancelled.subscribe(); + let transfer = transfer( + client, + &operation, + &url, + &headers, + local_file.as_deref(), + paths, ); + let result = tokio::select! { + biased; + _ = cancelled.wait_for(|cancelled| *cancelled) => { + Err(Error::cancelled().message("File transfer cancelled")) + } + result = transfer => result, + }; + *completed = Some(result.map_err(|mut error| { + if let Some(os_error) = error.os_error.as_mut() { + os_error.filename = local_file.clone(); + } + error + })); } completed.as_ref().unwrap().clone()?; } diff --git a/tests/v0_async_execute_wiremock.rs b/tests/v0_async_execute_wiremock.rs index 5820ae44..f1858ea7 100644 --- a/tests/v0_async_execute_wiremock.rs +++ b/tests/v0_async_execute_wiremock.rs @@ -2422,3 +2422,111 @@ async fn sync_and_direct_transfers_complete_and_preserve_error_context() { } } } + +#[tokio::test] +async fn async_cancel_interrupts_shared_file_transfer() { + use arrow_array::StringArray; + use std::time::Duration; + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + + for operation in ["PUT", "GET"] { + for detached in [false, true] { + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_delete_session(&server).await; + mount_close_any_statement(&server).await; + Mock::given(method("POST")) + .and(path("/api/2.0/sql/statements/transfer/cancel")) + .respond_with(ResponseTemplate::new(200).set_body_string("{}")) + .expect(1) + .mount(&server) + .await; + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let (started, received) = tokio::sync::oneshot::channel(); + let storage = tokio::spawn(async move { + let (mut socket, _) = listener.accept().await.unwrap(); + let mut headers = Vec::new(); + while !headers.ends_with(b"\r\n\r\n") { + headers.push(socket.read_u8().await.unwrap()); + } + if operation == "GET" { + socket.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 100\r\nConnection: close\r\n\r\npartial").await.unwrap(); + } else { + socket.read_u8().await.unwrap(); + } + started.send(()).unwrap(); + std::future::pending::<()>().await; + }); + let directory = tempfile::tempdir().unwrap(); + let local = directory.path().join("file"); + let original = vec![b'a'; 8 * 1024 * 1024]; + std::fs::write(&local, &original).unwrap(); + let batch = RecordBatch::try_from_iter(vec![ + ( + "operation", + Arc::new(StringArray::from(vec![operation])) as arrow_array::ArrayRef, + ), + ( + "url", + Arc::new(StringArray::from(vec![format!("http://{address}/file")])), + ), + ("headers", Arc::new(StringArray::from(vec!["{}"]))), + ( + "local", + Arc::new(StringArray::from(vec![local.to_str().unwrap()])), + ), + ]) + .unwrap(); + let mut body: serde_json::Value = + serde_json::from_str(&succeeded_inline_body("transfer", &batch)).unwrap(); + body["manifest"]["is_volume_operation"] = json!(true); + mount_submit(&server, pending_body("transfer")).await; + mount_status_once(&server, "transfer", body.to_string()).await; + let session = open_session(&server).await; + let mut statement = session.statement(); + let sql = if operation == "PUT" { + format!( + "PUT '{}' INTO '/Volumes/c/s/v/file' OVERWRITE", + local.display() + ) + } else { + format!("GET '/Volumes/c/s/v/file' TO '{}'", local.display()) + }; + statement.spec().sql(sql); + statement.spec().staging_allowed_local_paths = + Some(vec![directory.path().to_str().unwrap().into()]); + let owner = statement.submit().await.unwrap(); + let first = owner.reader().unwrap(); + let second = owner.reader().unwrap(); + let first = tokio::spawn(async move { first.fetch_result().await }); + tokio::time::timeout(Duration::from_secs(5), received) + .await + .unwrap() + .unwrap(); + let second = tokio::spawn(async move { second.fetch_result().await }); + if detached { + owner.canceller().cancel().await.unwrap(); + } else { + ExecutedStatementHandle::cancel(&owner).await.unwrap(); + } + let results = tokio::time::timeout(Duration::from_secs(2), async { + (first.await.unwrap(), second.await.unwrap()) + }) + .await + .expect("async cancellation did not stop the transfer"); + for result in [results.0, results.1] { + let error = result.err().expect("cancelled transfer must fail"); + assert_eq!(error.code, ErrorCode::Cancelled); + assert_eq!(error.error_code.as_deref(), Some("FILE_TRANSFER_ERROR")); + assert_eq!(error.query_id.as_deref(), Some("transfer")); + } + if operation == "GET" { + assert_eq!(std::fs::read(&local).unwrap(), original); + } + storage.abort(); + owner.close().await.unwrap(); + session.close().await.unwrap(); + } + } +} From 4f12d122d435c03ca489f77138deebd2ebe17081 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Thu, 12 Nov 2026 04:01:38 +0000 Subject: [PATCH 27/39] fix(volume): preserve directory open errors Signed-off-by: Aakash Saravanan --- src/statement/volume.rs | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/src/statement/volume.rs b/src/statement/volume.rs index 81cba473..4c8590b2 100644 --- a/src/statement/volume.rs +++ b/src/statement/volume.rs @@ -335,11 +335,8 @@ async fn transfer( }; if operation == "GET" { let destination = local.as_ref().unwrap(); - if destination.parent().is_none() { - return Err(Error::invalid_argument().message("Download destination must be a file")); - } match tokio::fs::metadata(destination).await { - Ok(metadata) if !metadata.is_file() => { + Ok(metadata) if !metadata.is_file() && !metadata.is_dir() => { return Err( Error::invalid_argument().message("Download destination must be a file") ); @@ -881,7 +878,8 @@ mod tests { ) .await .unwrap_err(); - assert_eq!(error.code, ErrorCode::InvalidArgument); + assert_eq!(error.code, ErrorCode::Internal); + assert!(error.os_error.is_some()); } } From b92a86716b49f48f577e2299989f235c20b50ee7 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Thu, 12 Nov 2026 04:14:24 +0000 Subject: [PATCH 28/39] fix(volume): send one upload content length Signed-off-by: Aakash Saravanan --- src/statement/volume.rs | 53 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 52 insertions(+), 1 deletion(-) diff --git a/src/statement/volume.rs b/src/statement/volume.rs index 4c8590b2..f99ef58d 100644 --- a/src/statement/volume.rs +++ b/src/statement/volume.rs @@ -455,7 +455,11 @@ async fn send_transfer( .request(method.clone(), url.clone()) .timeout(remaining); for (name, value) in headers { - request = request.header(name, value); + if method != Method::PUT + || !name.eq_ignore_ascii_case(reqwest::header::CONTENT_LENGTH.as_str()) + { + request = request.header(name, value); + } } if method == Method::PUT { let local = local @@ -883,6 +887,53 @@ mod tests { } } + #[tokio::test] + async fn upload_uses_one_content_length() { + // HTTP test servers can normalize duplicate framing headers before inspection. + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let server = tokio::spawn(async move { + let (mut socket, _) = listener.accept().await.unwrap(); + let mut headers = Vec::new(); + while !headers.ends_with(b"\r\n\r\n") { + headers.push(socket.read_u8().await.unwrap()); + } + let mut body = [0; 6]; + socket.read_exact(&mut body).await.unwrap(); + assert_eq!(&body, b"upload"); + socket + .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\nConnection: close\r\n\r\n") + .await + .unwrap(); + String::from_utf8(headers).unwrap() + }); + let dir = tempfile::tempdir().unwrap(); + let local = dir.path().join("input"); + tokio::fs::write(&local, b"upload").await.unwrap(); + transfer( + &client(), + "PUT", + &format!("http://{address}/file"), + &HashMap::from([ + ("cOnTeNt-LeNgTh".into(), "6".into()), + ("x-file-header".into(), "value".into()), + ]), + local.to_str(), + &[dir.path().to_str().unwrap().into()], + ) + .await + .unwrap(); + let headers = server.await.unwrap().to_ascii_lowercase(); + assert_eq!( + headers + .lines() + .filter(|line| line.starts_with("content-length:")) + .collect::>(), + ["content-length: 6"] + ); + assert!(headers.lines().any(|line| line == "x-file-header: value")); + } + #[tokio::test] async fn streams_upload_and_accepts_missing_remove() { let server = MockServer::start().await; From 5999f829274a1dc1ef82e01f99a57578080b2760 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Thu, 12 Nov 2026 04:30:02 +0000 Subject: [PATCH 29/39] test(volume): cover sync cancellation and upload path denial Signed-off-by: Aakash Saravanan --- src/statement/volume.rs | 26 ++++----- tests/v0_async_execute_wiremock.rs | 84 +++++++++++++++++++++--------- 2 files changed, 73 insertions(+), 37 deletions(-) diff --git a/src/statement/volume.rs b/src/statement/volume.rs index f99ef58d..5c040c90 100644 --- a/src/statement/volume.rs +++ b/src/statement/volume.rs @@ -1261,18 +1261,20 @@ mod tests { let allowed = dir.path().join("allowed"); std::fs::create_dir(&allowed).unwrap(); let outside = dir.path().join("outside"); - let error = transfer( - &client(), - "GET", - "http://127.0.0.1:1/file", - &HashMap::new(), - outside.to_str(), - &[allowed.to_str().unwrap().into()], - ) - .await - .unwrap_err(); - assert_eq!(error.code, ErrorCode::PermissionDenied); - assert!(!outside.exists()); + for operation in ["PUT", "GET"] { + let error = transfer( + &client(), + operation, + "http://127.0.0.1:1/file", + &HashMap::new(), + outside.to_str(), + &[allowed.to_str().unwrap().into()], + ) + .await + .unwrap_err(); + assert_eq!(error.code, ErrorCode::PermissionDenied); + assert!(!outside.exists()); + } } #[tokio::test] diff --git a/tests/v0_async_execute_wiremock.rs b/tests/v0_async_execute_wiremock.rs index f1858ea7..f40c58e0 100644 --- a/tests/v0_async_execute_wiremock.rs +++ b/tests/v0_async_execute_wiremock.rs @@ -2424,13 +2424,14 @@ async fn sync_and_direct_transfers_complete_and_preserve_error_context() { } #[tokio::test] -async fn async_cancel_interrupts_shared_file_transfer() { +async fn cancellation_interrupts_file_transfers() { use arrow_array::StringArray; + use databricks_sql_kernel::DirectStatement; use std::time::Duration; use tokio::io::{AsyncReadExt, AsyncWriteExt}; for operation in ["PUT", "GET"] { - for detached in [false, true] { + for mode in ["sync", "direct", "async-owner", "async-detached"] { let server = MockServer::start().await; mount_create_session(&server).await; mount_delete_session(&server).await; @@ -2481,8 +2482,12 @@ async fn async_cancel_interrupts_shared_file_transfer() { let mut body: serde_json::Value = serde_json::from_str(&succeeded_inline_body("transfer", &batch)).unwrap(); body["manifest"]["is_volume_operation"] = json!(true); - mount_submit(&server, pending_body("transfer")).await; - mount_status_once(&server, "transfer", body.to_string()).await; + if mode == "sync" || mode == "direct" { + mount_submit(&server, body.to_string()).await; + } else { + mount_submit(&server, pending_body("transfer")).await; + mount_status_once(&server, "transfer", body.to_string()).await; + } let session = open_session(&server).await; let mut statement = session.statement(); let sql = if operation == "PUT" { @@ -2496,27 +2501,57 @@ async fn async_cancel_interrupts_shared_file_transfer() { statement.spec().sql(sql); statement.spec().staging_allowed_local_paths = Some(vec![directory.path().to_str().unwrap().into()]); - let owner = statement.submit().await.unwrap(); - let first = owner.reader().unwrap(); - let second = owner.reader().unwrap(); - let first = tokio::spawn(async move { first.fetch_result().await }); - tokio::time::timeout(Duration::from_secs(5), received) - .await - .unwrap() - .unwrap(); - let second = tokio::spawn(async move { second.fetch_result().await }); - if detached { - owner.canceller().cancel().await.unwrap(); + let errors = if mode == "sync" || mode == "direct" { + let canceller = statement.canceller(); + let transfer = tokio::spawn(async move { + if mode == "direct" { + match statement.execute_direct().await { + Ok(DirectStatement::Completed(executed)) => Ok(executed), + Ok(DirectStatement::Running(_)) => panic!("expected inline completion"), + Err(error) => Err(error), + } + } else { + statement.execute().await + } + }); + tokio::time::timeout(Duration::from_secs(5), received) + .await + .unwrap() + .unwrap(); + canceller.cancel().await.unwrap(); + let result = tokio::time::timeout(Duration::from_secs(2), transfer) + .await + .expect("sync/direct cancellation did not stop the transfer") + .unwrap(); + vec![result.err().expect("cancelled transfer must fail")] } else { - ExecutedStatementHandle::cancel(&owner).await.unwrap(); - } - let results = tokio::time::timeout(Duration::from_secs(2), async { - (first.await.unwrap(), second.await.unwrap()) - }) - .await - .expect("async cancellation did not stop the transfer"); - for result in [results.0, results.1] { - let error = result.err().expect("cancelled transfer must fail"); + let owner = statement.submit().await.unwrap(); + let first = owner.reader().unwrap(); + let second = owner.reader().unwrap(); + let first = tokio::spawn(async move { first.fetch_result().await }); + tokio::time::timeout(Duration::from_secs(5), received) + .await + .unwrap() + .unwrap(); + let second = tokio::spawn(async move { second.fetch_result().await }); + if mode == "async-detached" { + owner.canceller().cancel().await.unwrap(); + } else { + ExecutedStatementHandle::cancel(&owner).await.unwrap(); + } + let results = tokio::time::timeout(Duration::from_secs(2), async { + (first.await.unwrap(), second.await.unwrap()) + }) + .await + .expect("async cancellation did not stop the transfer"); + let errors = vec![ + results.0.err().expect("cancelled transfer must fail"), + results.1.err().expect("cancelled transfer must fail"), + ]; + owner.close().await.unwrap(); + errors + }; + for error in errors { assert_eq!(error.code, ErrorCode::Cancelled); assert_eq!(error.error_code.as_deref(), Some("FILE_TRANSFER_ERROR")); assert_eq!(error.query_id.as_deref(), Some("transfer")); @@ -2525,7 +2560,6 @@ async fn async_cancel_interrupts_shared_file_transfer() { assert_eq!(std::fs::read(&local).unwrap(), original); } storage.abort(); - owner.close().await.unwrap(); session.close().await.unwrap(); } } From ea26771a5122c8558066638c292cff01df1ebb82 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Thu, 12 Nov 2026 04:45:05 +0000 Subject: [PATCH 30/39] fix(volume): retry failed storage client initialization Signed-off-by: Aakash Saravanan --- src/client/http.rs | 29 ++++++++++++++++++++++------- 1 file changed, 22 insertions(+), 7 deletions(-) diff --git a/src/client/http.rs b/src/client/http.rs index c80fb363..95ba63a0 100644 --- a/src/client/http.rs +++ b/src/client/http.rs @@ -397,7 +397,7 @@ fn build_mtls_identity(cert_pem: &[u8], key_pem: &[u8]) -> Result>, + volume_client: OnceLock, pub(crate) allow_loopback_plaintext_storage: bool, config: HttpClientConfig, auth_provider: OnceLock>, @@ -756,12 +756,11 @@ impl DatabricksHttpClient { pub(crate) fn volume_client(&self) -> Result<&Client> { // Transfer instructions authorize one URL; redirects must not forward their headers. - self.volume_client - .get_or_init(|| { - Self::build_reqwest_client(&self.config, reqwest::redirect::Policy::none()) - }) - .as_ref() - .map_err(Clone::clone) + if let Some(client) = self.volume_client.get() { + return Ok(client); + } + let client = Self::build_reqwest_client(&self.config, reqwest::redirect::Policy::none())?; + Ok(self.volume_client.get_or_init(|| client)) } pub(crate) fn storage_retry_config(&self) -> RetryConfig { @@ -1616,6 +1615,22 @@ lGrv15pBcePj assert!(client.is_ok()); } + #[test] + fn volume_client_recovers_after_certificate_file_is_restored() { + let directory = tempfile::tempdir().unwrap(); + let certificate = directory.path().join("ca.pem"); + std::fs::write(&certificate, TEST_CA_CERT_PEM).unwrap(); + let mut config = HttpClientConfig::default(); + config.tls.trusted_certificate_path = Some(certificate.to_string_lossy().into_owned()); + let client = DatabricksHttpClient::new(config, default_retry_configs()).unwrap(); + + std::fs::remove_file(&certificate).unwrap(); + assert!(client.volume_client().is_err()); + std::fs::write(&certificate, TEST_CA_CERT_PEM).unwrap(); + let initialized = client.volume_client().unwrap(); + assert!(std::ptr::eq(initialized, client.volume_client().unwrap())); + } + #[test] fn test_http_client_with_invalid_cert_path() { let mut config = HttpClientConfig::default(); From 37c7a3ec1b54f4690d9325d65f2220e0bb64b83e Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Thu, 12 Nov 2026 05:16:31 +0000 Subject: [PATCH 31/39] Enforce transfer policy for unresolved paths and stream sources Signed-off-by: Aakash Saravanan --- pyo3/src/statement.rs | 9 ++++- src/statement/spec.rs | 3 ++ src/statement/volume.rs | 75 ++++++++++++++++++++++++++++++++++++++--- 3 files changed, 82 insertions(+), 5 deletions(-) diff --git a/pyo3/src/statement.rs b/pyo3/src/statement.rs index 79030e8b..795ed5ea 100644 --- a/pyo3/src/statement.rs +++ b/pyo3/src/statement.rs @@ -68,9 +68,16 @@ impl Statement { /// Configured transfers consume instruction rows. /// ``None`` restores caller-managed transfers. - fn set_staging_allowed_local_paths(&mut self, paths: Option>) -> PyResult<()> { + /// ``input_stream_token`` prevents a stream sentinel from being opened as a file. + #[pyo3(signature = (paths=None, *, input_stream_token=None))] + fn set_staging_allowed_local_paths( + &mut self, + paths: Option>, + input_stream_token: Option, + ) -> PyResult<()> { let inner = alive_mut!(self, "Statement"); inner.stmt.spec().staging_allowed_local_paths = paths; + inner.stmt.spec().staging_stream_token = input_stream_token; Ok(()) } diff --git a/src/statement/spec.rs b/src/statement/spec.rs index 1b6a1f56..3347704c 100644 --- a/src/statement/spec.rs +++ b/src/statement/spec.rs @@ -234,6 +234,9 @@ pub struct StatementSpec { /// directory components cannot be modified by untrusted users during transfer. pub staging_allowed_local_paths: Option>, + /// A connector's stream sentinel must never be opened as a local file. + pub staging_stream_token: Option, + /// Preserve the instruction row after a successful transfer for APIs /// whose existing result contract includes that row. pub retain_volume_operation_result: bool, diff --git a/src/statement/volume.rs b/src/statement/volume.rs index 5c040c90..a8137cd5 100644 --- a/src/statement/volume.rs +++ b/src/statement/volume.rs @@ -51,6 +51,7 @@ impl VolumeCompletion { #[derive(Clone, Default)] pub(crate) struct VolumeOptions { paths: Option>, + stream_token: Option, retain_result: bool, } @@ -58,6 +59,7 @@ impl From<&StatementSpec> for VolumeOptions { fn from(spec: &StatementSpec) -> Self { Self { paths: spec.staging_allowed_local_paths.clone(), + stream_token: spec.staging_stream_token.clone(), retain_result: spec.retain_volume_operation_result, } } @@ -106,6 +108,14 @@ pub(crate) async fn complete( if next_instruction_batch(&mut stream).await?.is_some() { return Err(Error::invalid_state().message("Expected one file transfer instruction")); } + if operation.eq_ignore_ascii_case("PUT") + && options.stream_token.is_some() + && local_file == options.stream_token + { + return Err(Error::invalid_argument() + .message("Streaming PUT is not supported by the kernel backend.") + .with_error_code("FILE_TRANSFER_UNSUPPORTED_STREAM")); + } { let mut completed = completion.result.lock().await; if completed.is_none() { @@ -285,11 +295,10 @@ fn allowed_path(local_file: Option<&str>, paths: &[String]) -> Result { let resolved = resolved_path(Path::new(file)); let policy_path = match &resolved { Ok(file) => file.clone(), - Err(error) if error.code == ErrorCode::NotFound => { - // Missing components may classify a denial, but must never authorize file access. + Err(_) => { + // Unresolved components may classify a denial, but must never authorize file access. missing_path_for_policy(Path::new(file))? } - Err(error) => return Err(error.clone()), }; for base in paths { let Ok(base) = resolved_path(Path::new(base)) else { @@ -581,6 +590,7 @@ mod tests { let options = VolumeOptions { paths: Some(vec![dir.path().to_str().unwrap().into()]), retain_result: true, + ..Default::default() }; let completion = VolumeCompletion::default(); let http = client(); @@ -607,6 +617,35 @@ mod tests { assert_eq!(request.headers["x-file-header"], "value"); } + #[tokio::test] + async fn decoded_stream_token_is_not_opened_as_a_file() { + let server = MockServer::start().await; + let directory = tempfile::tempdir().unwrap(); + let local = directory.path().join("stream-token"); + std::fs::write(&local, b"disk bytes").unwrap(); + let token = local.to_str().unwrap().to_owned(); + let batch = instruction("PUT", &server.uri(), &token); + let error = complete( + &client(), + result(batch, true), + &VolumeOptions { + paths: Some(vec![directory.path().to_str().unwrap().into()]), + stream_token: Some(token), + ..Default::default() + }, + &VolumeCompletion::default(), + ) + .await + .err() + .unwrap(); + assert_eq!( + error.error_code.as_deref(), + Some("FILE_TRANSFER_UNSUPPORTED_STREAM") + ); + assert_eq!(error.query_id.as_deref(), Some("statement")); + assert!(server.received_requests().await.unwrap().is_empty()); + } + #[tokio::test] async fn cancelled_reader_does_not_replay_upload() { use std::time::Duration; @@ -624,6 +663,7 @@ mod tests { let options = VolumeOptions { paths: Some(vec![directory.path().to_str().unwrap().into()]), retain_result: false, + ..Default::default() }; let completion = VolumeCompletion::default(); let http = client(); @@ -697,6 +737,7 @@ mod tests { let options = VolumeOptions { paths: Some(vec![dir.path().to_str().unwrap().into()]), retain_result: false, + ..Default::default() }; for operation in ["PUT", "GET"] { let batch = instruction(operation, &server.uri(), local.to_str().unwrap()); @@ -1119,14 +1160,35 @@ mod tests { let error = allowed_path(path.to_str(), &paths).unwrap_err(); assert_eq!(error.code, expected); } + for base in [&allowed, &directory.path().join("outside")] { + std::fs::create_dir_all(base).unwrap(); + std::fs::write(base.join("file"), b"file").unwrap(); + let error = allowed_path(base.join("file/child").to_str(), &paths).unwrap_err(); + if base == &allowed { + assert!(error.os_error.is_some()); + } else { + assert_eq!(error.code, ErrorCode::PermissionDenied); + assert!(error.os_error.is_none()); + } + } #[cfg(unix)] { let outside = directory.path().join("outside"); - std::fs::create_dir(&outside).unwrap(); std::os::unix::fs::symlink(&outside, allowed.join("link")).unwrap(); let error = allowed_path(allowed.join("link/missing/file").to_str(), &paths).unwrap_err(); assert_eq!(error.code, ErrorCode::PermissionDenied); + for base in [&allowed, &outside] { + let path = base.join("loop"); + std::os::unix::fs::symlink(&path, &path).unwrap(); + let error = allowed_path(path.to_str(), &paths).unwrap_err(); + if base == &allowed { + assert!(error.os_error.is_some()); + } else { + assert_eq!(error.code, ErrorCode::PermissionDenied); + assert!(error.os_error.is_none()); + } + } } } @@ -1156,6 +1218,7 @@ mod tests { &VolumeOptions { paths: Some(vec![]), retain_result: false, + ..Default::default() }, &VolumeCompletion::default(), ) @@ -1181,6 +1244,7 @@ mod tests { &VolumeOptions { paths: Some(vec![]), retain_result: false, + ..Default::default() }, &VolumeCompletion::default(), ) @@ -1218,6 +1282,7 @@ mod tests { &VolumeOptions { paths: Some(vec![]), retain_result: false, + ..Default::default() }, &VolumeCompletion::default(), ) @@ -1238,6 +1303,7 @@ mod tests { VolumeOptions { paths: Some(vec![]), retain_result: false, + ..Default::default() }, ), (true, VolumeOptions::default()), @@ -1337,6 +1403,7 @@ mod tests { &VolumeOptions { paths: Some(vec![dir.path().to_str().unwrap().into()]), retain_result: false, + ..Default::default() }, &VolumeCompletion::default(), ) From 572fe4901a9e86bd2f791c1998f00b31db7d8bc0 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Thu, 12 Nov 2026 06:47:20 +0000 Subject: [PATCH 32/39] Document replacement semantics of transfer options Signed-off-by: Aakash Saravanan --- pyo3/src/statement.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/pyo3/src/statement.rs b/pyo3/src/statement.rs index 795ed5ea..7e6dbdf9 100644 --- a/pyo3/src/statement.rs +++ b/pyo3/src/statement.rs @@ -69,6 +69,7 @@ impl Statement { /// Configured transfers consume instruction rows. /// ``None`` restores caller-managed transfers. /// ``input_stream_token`` prevents a stream sentinel from being opened as a file. + /// Each call replaces both settings; omitting ``input_stream_token`` clears it. #[pyo3(signature = (paths=None, *, input_stream_token=None))] fn set_staging_allowed_local_paths( &mut self, From edd340c83b04fde72f64729c2db25c44c8cefc0c Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Thu, 12 Nov 2026 19:23:14 +0000 Subject: [PATCH 33/39] test(volume): remove redundant transfer setup and cases Signed-off-by: Aakash Saravanan --- adbc/tests/live.rs | 7 -- pyo3/src/errors.rs | 2 +- src/statement/executed_async.rs | 4 +- src/statement/volume.rs | 59 +++------------- tests/v0_async_execute_wiremock.rs | 106 ++++++++++------------------- 5 files changed, 48 insertions(+), 130 deletions(-) diff --git a/adbc/tests/live.rs b/adbc/tests/live.rs index ee7d5822..e97c6039 100644 --- a/adbc/tests/live.rs +++ b/adbc/tests/live.rs @@ -396,13 +396,6 @@ fn volume_files_round_trip_and_remove() { statement.execute_update()?; let option = OptionStatement::Other("adbc.databricks.statement.staging_allowed_local_paths".into()); - if statement - .set_option(option.clone(), OptionValue::String("{}".into())) - .is_ok() - { - return Err("invalid path list was accepted".into()); - } - statement.set_option(option.clone(), OptionValue::String("null".into()))?; let paths = serde_json::to_string(&vec![directory.to_str().unwrap()])?; statement.set_option(option.clone(), OptionValue::String(paths.clone()))?; for sql in [ diff --git a/pyo3/src/errors.rs b/pyo3/src/errors.rs index 01a252ce..24db8807 100644 --- a/pyo3/src/errors.rs +++ b/pyo3/src/errors.rs @@ -206,7 +206,7 @@ mod tests { fn local_os_error_code_crosses_python_boundary() { Python::initialize(); Python::attach(|py| { - for raw in [None, Some(1), Some(2), Some(5), Some(13)] { + for raw in [None, Some(13)] { let mut error = KError::new(ErrorCode::NotFound, "missing file"); error.os_error = raw.map(|code| { Box::new(OsError { diff --git a/src/statement/executed_async.rs b/src/statement/executed_async.rs index a9b3ed68..1518cf60 100644 --- a/src/statement/executed_async.rs +++ b/src/statement/executed_async.rs @@ -1180,8 +1180,8 @@ impl AsyncStatementCanceller { /// `Statement` drop). Idempotent against a server already in a /// terminal state — the kernel's `cancel_statement` is a no-op /// there. Byte-for-byte the same operation as - /// [`ExecutedAsyncStatement::cancel`]; the two share no mutable - /// state, so this can run concurrently with an in-flight + /// [`ExecutedAsyncStatement::cancel`]; no exclusive borrow of the + /// executed handle is required, so this can run concurrently with an in-flight /// `await_result` on the same statement. pub async fn cancel(&self) -> Result<()> { async { diff --git a/src/statement/volume.rs b/src/statement/volume.rs index a8137cd5..64d22c89 100644 --- a/src/statement/volume.rs +++ b/src/statement/volume.rs @@ -709,8 +709,6 @@ mod tests { (ErrorKind::InvalidInput, ErrorCode::InvalidArgument), (ErrorKind::StorageFull, ErrorCode::ResourceExhausted), (ErrorKind::TimedOut, ErrorCode::Timeout), - (ErrorKind::IsADirectory, ErrorCode::Internal), - (ErrorKind::ReadOnlyFilesystem, ErrorCode::Internal), (ErrorKind::Other, ErrorCode::Internal), ] { let error = file_error(std::io::Error::from(kind)); @@ -722,10 +720,8 @@ mod tests { (kind == ErrorKind::PermissionDenied).then_some("FILE_TRANSFER_PERMISSION_ERROR") ); } - for raw in [1, 2, 5, 13] { - let error = file_error(std::io::Error::from_raw_os_error(raw)); - assert_eq!(error.os_error.as_ref().map(|e| e.code), Some(raw)); - } + let error = file_error(std::io::Error::from_raw_os_error(13)); + assert_eq!(error.os_error.as_ref().map(|e| e.code), Some(13)); } #[tokio::test] @@ -953,7 +949,7 @@ mod tests { tokio::fs::write(&local, b"upload").await.unwrap(); transfer( &client(), - "PUT", + "pUt", &format!("http://{address}/file"), &HashMap::from([ ("cOnTeNt-LeNgTh".into(), "6".into()), @@ -976,38 +972,16 @@ mod tests { } #[tokio::test] - async fn streams_upload_and_accepts_missing_remove() { + async fn accepts_missing_remove() { let server = MockServer::start().await; - Mock::given(method("PUT")) - .and(path("/file")) - .and(body_bytes(b"upload")) - .respond_with(ResponseTemplate::new(200)) - .expect(1) - .mount(&server) - .await; Mock::given(method("DELETE")) .and(path("/file")) .respond_with(ResponseTemplate::new(404)) .expect(1) .mount(&server) .await; - let dir = tempfile::tempdir().unwrap(); - let local = dir.path().join("input"); - tokio::fs::write(&local, b"upload").await.unwrap(); - let roots = vec![dir.path().to_str().unwrap().into()]; - let http = client(); - transfer( - &http, - "pUt", - &format!("{}/file", server.uri()), - &HashMap::new(), - local.to_str(), - &roots, - ) - .await - .unwrap(); transfer( - &http, + &client(), "remove", &format!("{}/file", server.uri()), &HashMap::new(), @@ -1175,9 +1149,10 @@ mod tests { { let outside = directory.path().join("outside"); std::os::unix::fs::symlink(&outside, allowed.join("link")).unwrap(); - let error = - allowed_path(allowed.join("link/missing/file").to_str(), &paths).unwrap_err(); - assert_eq!(error.code, ErrorCode::PermissionDenied); + for suffix in ["link/file", "link/missing/file"] { + let error = allowed_path(allowed.join(suffix).to_str(), &paths).unwrap_err(); + assert_eq!(error.code, ErrorCode::PermissionDenied); + } for base in [&allowed, &outside] { let path = base.join("loop"); std::os::unix::fs::symlink(&path, &path).unwrap(); @@ -1477,20 +1452,4 @@ mod tests { ]; assert_eq!(allowed_path(file.to_str(), &paths).unwrap(), file); } - - #[cfg(unix)] - #[test] - fn rejects_symlinks_that_escape_allowed_directory() { - let dir = tempfile::tempdir().unwrap(); - let allowed = dir.path().join("allowed"); - let outside = dir.path().join("outside"); - std::fs::create_dir(&allowed).unwrap(); - std::fs::create_dir(&outside).unwrap(); - std::os::unix::fs::symlink(&outside, allowed.join("link")).unwrap(); - assert!(allowed_path( - allowed.join("link/file").to_str(), - &[allowed.to_str().unwrap().into()] - ) - .is_err()); - } } diff --git a/tests/v0_async_execute_wiremock.rs b/tests/v0_async_execute_wiremock.rs index f40c58e0..06e6c885 100644 --- a/tests/v0_async_execute_wiremock.rs +++ b/tests/v0_async_execute_wiremock.rs @@ -141,6 +141,27 @@ fn succeeded_inline_body(statement_id: &str, batch: &RecordBatch) -> String { .to_string() } +fn file_transfer_body(operation: &str, url: &str, local: &std::path::Path) -> String { + use arrow_array::StringArray; + let batch = RecordBatch::try_from_iter(vec![ + ( + "operation", + Arc::new(StringArray::from(vec![operation])) as arrow_array::ArrayRef, + ), + ("url", Arc::new(StringArray::from(vec![url]))), + ("headers", Arc::new(StringArray::from(vec!["{}"]))), + ( + "local", + Arc::new(StringArray::from(vec![local.to_str().unwrap()])), + ), + ]) + .unwrap(); + let mut body: serde_json::Value = + serde_json::from_str(&succeeded_inline_body("transfer", &batch)).unwrap(); + body["manifest"]["is_volume_operation"] = json!(true); + body.to_string() +} + fn pending_body(statement_id: &str) -> String { json!({ "statement_id": statement_id, @@ -2277,7 +2298,6 @@ async fn await_result_succeeded_status_still_closes_statement() { #[tokio::test] async fn file_transfer_completion_is_shared_by_independent_readers() { - use arrow_array::StringArray; let server = MockServer::start().await; mount_create_session(&server).await; mount_delete_session(&server).await; @@ -2290,30 +2310,13 @@ async fn file_transfer_completion_is_shared_by_independent_readers() { .await; let dir = tempfile::tempdir().unwrap(); let destination = dir.path().join("download"); - let batch = RecordBatch::try_from_iter(vec![ - ( - "operation", - Arc::new(StringArray::from(vec!["GET"])) as arrow_array::ArrayRef, - ), - ( - "url", - Arc::new(StringArray::from(vec![format!( - "{}/storage/file", - server.uri() - )])), - ), - ("headers", Arc::new(StringArray::from(vec!["{}"]))), - ( - "local", - Arc::new(StringArray::from(vec![destination.to_str().unwrap()])), - ), - ]) - .unwrap(); - let mut body: serde_json::Value = - serde_json::from_str(&succeeded_inline_body("transfer", &batch)).unwrap(); - body["manifest"]["is_volume_operation"] = json!(true); + let body = file_transfer_body( + "GET", + &format!("{}/storage/file", server.uri()), + &destination, + ); mount_submit(&server, pending_body("transfer")).await; - mount_status_once(&server, "transfer", body.to_string()).await; + mount_status_once(&server, "transfer", body).await; let session = open_session(&server).await; let mut statement = session.statement(); statement @@ -2334,7 +2337,6 @@ async fn file_transfer_completion_is_shared_by_independent_readers() { #[tokio::test] async fn sync_and_direct_transfers_complete_and_preserve_error_context() { - use arrow_array::StringArray; use databricks_sql_kernel::DirectStatement; for direct in [false, true] { for denied in [false, true] { @@ -2350,29 +2352,12 @@ async fn sync_and_direct_transfers_complete_and_preserve_error_context() { .await; let directory = tempfile::tempdir().unwrap(); let destination = directory.path().join("download"); - let batch = RecordBatch::try_from_iter(vec![ - ( - "operation", - Arc::new(StringArray::from(vec!["GET"])) as arrow_array::ArrayRef, - ), - ( - "url", - Arc::new(StringArray::from(vec![format!( - "{}/storage/file", - server.uri() - )])), - ), - ("headers", Arc::new(StringArray::from(vec!["{}"]))), - ( - "local", - Arc::new(StringArray::from(vec![destination.to_str().unwrap()])), - ), - ]) - .unwrap(); - let mut body: serde_json::Value = - serde_json::from_str(&succeeded_inline_body("transfer", &batch)).unwrap(); - body["manifest"]["is_volume_operation"] = json!(true); - mount_submit(&server, body.to_string()).await; + let body = file_transfer_body( + "GET", + &format!("{}/storage/file", server.uri()), + &destination, + ); + mount_submit(&server, body).await; let session = open_session(&server).await; let mut statement = session.statement(); statement @@ -2425,7 +2410,6 @@ async fn sync_and_direct_transfers_complete_and_preserve_error_context() { #[tokio::test] async fn cancellation_interrupts_file_transfers() { - use arrow_array::StringArray; use databricks_sql_kernel::DirectStatement; use std::time::Duration; use tokio::io::{AsyncReadExt, AsyncWriteExt}; @@ -2463,30 +2447,12 @@ async fn cancellation_interrupts_file_transfers() { let local = directory.path().join("file"); let original = vec![b'a'; 8 * 1024 * 1024]; std::fs::write(&local, &original).unwrap(); - let batch = RecordBatch::try_from_iter(vec![ - ( - "operation", - Arc::new(StringArray::from(vec![operation])) as arrow_array::ArrayRef, - ), - ( - "url", - Arc::new(StringArray::from(vec![format!("http://{address}/file")])), - ), - ("headers", Arc::new(StringArray::from(vec!["{}"]))), - ( - "local", - Arc::new(StringArray::from(vec![local.to_str().unwrap()])), - ), - ]) - .unwrap(); - let mut body: serde_json::Value = - serde_json::from_str(&succeeded_inline_body("transfer", &batch)).unwrap(); - body["manifest"]["is_volume_operation"] = json!(true); + let body = file_transfer_body(operation, &format!("http://{address}/file"), &local); if mode == "sync" || mode == "direct" { - mount_submit(&server, body.to_string()).await; + mount_submit(&server, body).await; } else { mount_submit(&server, pending_body("transfer")).await; - mount_status_once(&server, "transfer", body.to_string()).await; + mount_status_once(&server, "transfer", body).await; } let session = open_session(&server).await; let mut statement = session.statement(); From 663d58632a4117fc45145635f202e5796b9529cf Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Thu, 12 Nov 2026 19:33:40 +0000 Subject: [PATCH 34/39] Strengthen invalid staging-option state assertions Signed-off-by: Aakash Saravanan --- adbc/src/statement.rs | 9 ++++++--- src/c_abi/statement.rs | 9 ++++++--- src/statement/volume.rs | 1 + 3 files changed, 13 insertions(+), 6 deletions(-) diff --git a/adbc/src/statement.rs b/adbc/src/statement.rs index 262acec3..b0371f59 100644 --- a/adbc/src/statement.rs +++ b/adbc/src/statement.rs @@ -1517,9 +1517,9 @@ mod tests { OptionStatement::Other("adbc.databricks.statement.staging_allowed_local_paths".into()); assert_eq!(statement.get_option_string(option.clone()).unwrap(), "null"); for (value, expected) in [ - (r#"["/tmp/files"]"#, Some(vec!["/tmp/files".to_owned()])), ("[]", Some(vec![])), ("null", None), + (r#"["/tmp/files"]"#, Some(vec!["/tmp/files".to_owned()])), ] { statement.set_option(option.clone(), value.into()).unwrap(); assert_eq!( @@ -1542,9 +1542,12 @@ mod tests { .unwrap() .spec() .staging_allowed_local_paths, - None + Some(vec!["/tmp/files".to_owned()]) + ); + assert_eq!( + statement.get_option_string(option).unwrap(), + r#"["/tmp/files"]"# ); - assert_eq!(statement.get_option_string(option).unwrap(), "null"); } fn batch(rows: usize) -> RecordBatch { diff --git a/src/c_abi/statement.rs b/src/c_abi/statement.rs index b71d0f7b..85ace551 100644 --- a/src/c_abi/statement.rs +++ b/src/c_abi/statement.rs @@ -1314,8 +1314,8 @@ mod tests { for (json, retained, expected) in [ (c"[]".as_ptr(), true, Some(vec![])), (std::ptr::null(), false, None), - (c"[\"/tmp\"]".as_ptr(), false, Some(vec!["/tmp".to_owned()])), - (c"null".as_ptr(), true, None), + (c"null".as_ptr(), false, None), + (c"[\"/tmp\"]".as_ptr(), true, Some(vec!["/tmp".to_owned()])), ] { assert_eq!( kernel_statement_set_staging_allowed_local_paths(statement, json, retained), @@ -1332,7 +1332,10 @@ mod tests { KernelStatusCode::InvalidArgument ); let spec = statement_mut(statement).unwrap().spec(); - assert!(spec.staging_allowed_local_paths.is_none()); + assert_eq!( + spec.staging_allowed_local_paths, + Some(vec!["/tmp".to_owned()]) + ); assert!(spec.retain_volume_operation_result); } assert_eq!(kernel_statement_close(statement), KernelStatusCode::Success); diff --git a/src/statement/volume.rs b/src/statement/volume.rs index 64d22c89..d02a2087 100644 --- a/src/statement/volume.rs +++ b/src/statement/volume.rs @@ -351,6 +351,7 @@ async fn transfer( ); } Ok(_) => { + // Preserve the OS error for directory destinations. tokio::fs::OpenOptions::new() .write(true) .open(destination) From 6adac39ac2f1a132508f6c77005ca93757e8a63b Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Thu, 12 Nov 2026 22:53:53 +0000 Subject: [PATCH 35/39] fix(volume): honor transfer policy and statement lifecycle Signed-off-by: Aakash Saravanan --- Cargo.lock | 1 + Cargo.toml | 1 + adbc/Cargo.lock | 1 + adbc/tests/live.rs | 2 +- napi/Cargo.lock | 1 + napi/src/error.rs | 30 +- pyo3/Cargo.lock | 1 + src/client/http.rs | 6 +- src/client/mod.rs | 2 +- src/session.rs | 6 + src/statement/executed_async.rs | 23 +- src/statement/mutable.rs | 10 + src/statement/spec.rs | 19 +- src/statement/volume.rs | 612 ++++++++++++++++++++++------- tests/v0_async_execute_wiremock.rs | 311 +++++++++++++++ 15 files changed, 873 insertions(+), 153 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 682745ea..0dff8d98 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -663,6 +663,7 @@ dependencies = [ "geo-traits", "hex", "hmac 0.13.0", + "hyper", "jsonwebtoken", "log", "lz4_flex", diff --git a/Cargo.toml b/Cargo.toml index 37414939..b5a4fc70 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -60,6 +60,7 @@ arrow-ipc = "59" # module load time and segfaults the process before any Rust code runs. # `rustls` is pure Rust + ring and avoids the conflict entirely. reqwest = { version = "0.12", default-features = false, features = ["json", "gzip", "stream"] } +hyper = { version = "1", default-features = false } native-tls = { version = "0.2", optional = true } rustls = { version = "0.23.41", optional = true, default-features = false, features = ["ring", "std", "tls12"] } # Enforce TLS dependency minimums for consumers with their own lockfiles. diff --git a/adbc/Cargo.lock b/adbc/Cargo.lock index 55f52d62..f522959b 100644 --- a/adbc/Cargo.lock +++ b/adbc/Cargo.lock @@ -665,6 +665,7 @@ dependencies = [ "geo-traits", "hex", "hmac 0.13.0", + "hyper", "jsonwebtoken", "lz4_flex", "moka", diff --git a/adbc/tests/live.rs b/adbc/tests/live.rs index e97c6039..2fd0c978 100644 --- a/adbc/tests/live.rs +++ b/adbc/tests/live.rs @@ -370,7 +370,7 @@ fn metadata_statement_catalog_underscore_escaping_is_configurable() { #[test] #[ignore = "requires a writable Unity Catalog catalog and live warehouse"] fn volume_files_round_trip_and_remove() { - let catalog = env::var("DATABRICKS_VOLUME_TEST_CATALOG").unwrap_or_else(|_| "main".into()); + let catalog = required_env("DATABRICKS_VOLUME_TEST_CATALOG"); let unique = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .unwrap() diff --git a/napi/Cargo.lock b/napi/Cargo.lock index a7fd477a..6f896e68 100644 --- a/napi/Cargo.lock +++ b/napi/Cargo.lock @@ -624,6 +624,7 @@ dependencies = [ "geo-traits", "hex", "hmac 0.13.0", + "hyper", "jsonwebtoken", "lz4_flex", "moka", diff --git a/napi/src/error.rs b/napi/src/error.rs index 70518fe3..ae95ece9 100644 --- a/napi/src/error.rs +++ b/napi/src/error.rs @@ -143,6 +143,12 @@ pub(crate) fn napi_err_from_kernel(e: KernelError) -> NapiError { if let Some(qid) = e.query_id { obj.insert("queryId".to_owned(), Value::from(qid)); } + if let Some(os_error) = e.os_error { + obj.insert("osErrorCode".to_owned(), Value::from(os_error.code)); + if let Some(filename) = os_error.filename { + obj.insert("osErrorFilename".to_owned(), Value::from(filename)); + } + } // Thrift-parity extended status fields: surfaced on the napi // envelope so a JS caller's catch-block sees the same fields the // Thrift driver's `TGetOperationStatusResp` exposes. Only @@ -195,6 +201,7 @@ fn error_code_str(code: ErrorCode) -> &'static str { #[cfg(test)] mod tests { use super::*; + use databricks_sql_kernel::kernel_error::OsError; #[test] fn envelope_carries_sentinel_and_code() { @@ -333,6 +340,10 @@ mod tests { e.http_status = Some(503); e.retryable = true; e.query_id = Some("01eedeadbeefdeadbeefdeadbeefdead".to_string()); + e.os_error = Some(Box::new(OsError { + code: 13, + filename: Some("requested/local-file".to_string()), + })); // Thrift-parity extension fields: populated too so the // superset relation is exercised in the same fixture. e.display_message = Some("Statement failed at operator Scan".to_string()); @@ -388,6 +399,8 @@ mod tests { "envelope is missing the Thrift-parity key `{k}`. payload: {payload}" ); } + assert_eq!(obj["osErrorCode"], 13); + assert_eq!(obj["osErrorFilename"], "requested/local-file"); // Intentionally-omitted fields must NOT leak into the wire // shape (the module doc and the kernel `Error` struct both @@ -404,12 +417,12 @@ mod tests { // No surprise keys: the wire shape stays the documented set. // Exact-size check (not subset) catches accidental additions. - let expected_total = pyo3_parity_keys.len() + thrift_parity_keys.len(); + let expected_total = pyo3_parity_keys.len() + thrift_parity_keys.len() + 2; assert_eq!( obj.len(), expected_total, "envelope has unexpected extra keys. expected pyo3 parity \ - {pyo3_parity_keys:?} + thrift parity {thrift_parity_keys:?}, \ + {pyo3_parity_keys:?} + thrift parity {thrift_parity_keys:?} + OS details, \ got: {:?}", obj.keys().collect::>() ); @@ -482,6 +495,8 @@ mod tests { "httpStatus", "retryable", "queryId", + "osErrorCode", + "osErrorFilename", // Thrift-parity extension fields also follow the // omit-when-None convention. "displayMessage", @@ -496,6 +511,17 @@ mod tests { } assert!(obj.contains_key("code")); assert!(obj.contains_key("message")); + + let mut e = KernelError::invalid_argument().message("hi"); + e.os_error = Some(Box::new(OsError { + code: -2, + filename: None, + })); + let napi_err = napi_err_from_kernel(e); + let payload = &napi_err.reason.to_string()[ERROR_SENTINEL.len()..]; + let v: serde_json::Value = serde_json::from_str(payload).unwrap(); + assert_eq!(v["osErrorCode"], -2); + assert!(!v.as_object().unwrap().contains_key("osErrorFilename")); } #[test] diff --git a/pyo3/Cargo.lock b/pyo3/Cargo.lock index 357cb953..9ba2c6bc 100644 --- a/pyo3/Cargo.lock +++ b/pyo3/Cargo.lock @@ -620,6 +620,7 @@ dependencies = [ "geo-traits", "hex", "hmac 0.13.0", + "hyper", "jsonwebtoken", "lz4_flex", "moka", diff --git a/src/client/http.rs b/src/client/http.rs index 95ba63a0..495d18ff 100644 --- a/src/client/http.rs +++ b/src/client/http.rs @@ -763,9 +763,11 @@ impl DatabricksHttpClient { Ok(self.volume_client.get_or_init(|| client)) } - pub(crate) fn storage_retry_config(&self) -> RetryConfig { + pub(crate) fn volume_retry_config(&self) -> RetryConfig { + // Session resolves the normalized global policy into Sea without an override. + // CloudFetch has its own outer retry loop and a separate inner policy. self.retry_configs - .get(&RequestCategory::CloudFetch) + .get(&RequestCategory::Sea) .cloned() .unwrap_or_default() } diff --git a/src/client/mod.rs b/src/client/mod.rs index af553abf..4205b276 100644 --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -36,7 +36,7 @@ pub mod retry; pub mod sea; pub(crate) mod transport; -fn error_chain<'a>( +pub(crate) fn error_chain<'a>( error: &'a (dyn std::error::Error + 'static), ) -> impl Iterator { std::iter::successors(Some(error), |error| { diff --git a/src/session.rs b/src/session.rs index 81d9abf2..4ad86984 100644 --- a/src/session.rs +++ b/src/session.rs @@ -1755,6 +1755,12 @@ mod retry_config_tests { Duration::from_secs(600), "Sea overall_timeout" ); + let client = DatabricksHttpClient::new(HttpClientConfig::default(), configs).unwrap(); + let volume = client.volume_retry_config(); + assert_eq!(volume.min_wait, Duration::from_secs(3)); + assert_eq!(volume.max_wait, Duration::from_secs(90)); + assert_eq!(volume.max_retries, 7); + assert_eq!(volume.overall_timeout, Duration::from_secs(600)); } #[test] diff --git a/src/statement/executed_async.rs b/src/statement/executed_async.rs index 1518cf60..40eead2e 100644 --- a/src/statement/executed_async.rs +++ b/src/statement/executed_async.rs @@ -222,7 +222,7 @@ pub struct ExecutedAsyncStatement { /// every network round-trip. latest_status: Arc>, pub(crate) volume_options: super::volume::VolumeOptions, - volume_completion: Arc, + pub(super) volume_completion: Arc, statement_telemetry: StatementTelemetry, /// Set once result materialisation hands success finalization to /// the returned `ResultStream`. @@ -280,7 +280,7 @@ impl ExecutedAsyncStatement { /// best-effort server cleanup when a deadline retained across /// caller-driven status polls expires. pub(crate) fn expire_client_query_timeout(&self) -> Error { - self.owner_released.store(true, Ordering::Release); + self.release_owner(); if !self.client_timeout_expired.swap(true, Ordering::AcqRel) { self.session .dispatch_timeout_cleanup(Some(self.statement_id.clone())); @@ -436,6 +436,13 @@ impl ExecutedAsyncStatement { Ok(()) } + fn release_owner(&self) { + if self.owning { + self.owner_released.store(true, Ordering::Release); + self.volume_completion.cancel(); + } + } + fn check_read_validity(&self) -> Result<()> { self.valid.check()?; if !self.owning { @@ -887,7 +894,9 @@ impl ExecutedAsyncStatement { &self.volume_options, &self.volume_completion, ) - .await?; + .await; + self.check_read_validity()?; + let result = result?; let mut stream = ResultStream::from_reader(result.reader).await?; stream.attach_telemetry(self.statement_telemetry.clone()); // SEA carries no row count on the async status either; for a @@ -1084,9 +1093,7 @@ impl ExecutedAsyncStatement { } async fn close_server_statement(&self) -> Result<()> { - if self.owning { - self.owner_released.store(true, Ordering::Release); - } + self.release_owner(); // Idempotent on success: a prior successful close sets // `closed=true` and subsequent calls short-circuit. // @@ -1211,9 +1218,7 @@ impl AsyncStatementCanceller { impl Drop for ExecutedAsyncStatement { fn drop(&mut self) { - if self.owning { - self.owner_released.store(true, Ordering::Release); - } + self.release_owner(); // Ensure submit-and-drop / status-only async statements still // emit one terminal telemetry event. Once a result stream has // been returned, that stream owns success finalization so it can diff --git a/src/statement/mutable.rs b/src/statement/mutable.rs index a0f237bf..8f93c107 100644 --- a/src/statement/mutable.rs +++ b/src/statement/mutable.rs @@ -240,6 +240,7 @@ pub struct Statement { /// skip the `CloseStatement` round-trip entirely when the server /// side is already gone. last_closed: Option>, + last_volume_completion: Option>, /// Server statement id of the in-flight (or most recent) execution, /// shared with any [`StatementCanceller`] handed out via /// [`Statement::canceller`]. Populated mid-execute as soon as the @@ -260,6 +261,7 @@ impl Statement { last_statement_id: None, last_valid: None, last_closed: None, + last_volume_completion: None, inflight_id: Arc::new(Mutex::new(None)), volume_cancellation: watch::channel(None).0, } @@ -563,6 +565,7 @@ impl Statement { timeout, ); executed.volume_options = super::volume::VolumeOptions::from(&self.spec); + self.last_volume_completion = Some(Arc::clone(&executed.volume_completion)); Ok(executed) } .instrument(span) @@ -698,6 +701,7 @@ impl Statement { ExecutionTimeout::Default, ); executed.volume_options = super::volume::VolumeOptions::from(&self.spec); + self.last_volume_completion = Some(Arc::clone(&executed.volume_completion)); Ok(DirectStatement::Running(executed)) } } @@ -855,6 +859,9 @@ impl Statement { if let Some(valid) = self.last_valid.take() { valid.invalidate(); } + if let Some(completion) = self.last_volume_completion.take() { + completion.cancel(); + } // If the shared `closed` flag is already set, the server side // is gone (server auto-closed on the inline-result fast path, // or the caller already closed the executed handle). Flip it @@ -1049,6 +1056,9 @@ impl Drop for Statement { if let Some(valid) = self.last_valid.take() { valid.invalidate(); } + if let Some(completion) = self.last_volume_completion.take() { + completion.cancel(); + } // `last_statement_id` is left as-is. By construction it is // only set immediately before `ExecutedStatement::new` // wraps it; if the caller still holds an `ExecutedStatement`, diff --git a/src/statement/spec.rs b/src/statement/spec.rs index 3347704c..a15ace44 100644 --- a/src/statement/spec.rs +++ b/src/statement/spec.rs @@ -225,11 +225,22 @@ pub struct StatementSpec { /// Local paths permitted for SQL file transfers. `None` leaves transfer /// instructions available to a caller that handles them itself. An empty list - /// enables REMOVE while denying local file access. Transfers use the storage - /// retry overall deadline, which defaults to 15 minutes. + /// enables REMOVE while denying local file access. /// Completion, including a failure after retries, is final and shared by all - /// readers of an execution. Cancellation during transfer is terminal; - /// re-execute the SQL to start a new transfer attempt. + /// readers of an execution. Cancellation or release before destination + /// replacement begins is terminal; a replacement already in progress completes. + /// Re-execute the SQL to start a new transfer attempt. + /// + /// Storage HTTP attempts and the entire GET response body, including continuous + /// progress, share the session's [`crate::HttpConfig::overall_timeout`] budget + /// (default 900 seconds), also used by SQL HTTP retries. Lowering it caps storage + /// transfers too. This is separate from the SQL query timeout; the Thrift + /// transfer path has no equivalent wall-clock cap on a progressing body. + /// Cancellation and deadlines are cooperative, not hard limits on blocked + /// filesystem calls. Temporary-file creation, replacement and cleanup run + /// inline and can stall other work sharing the runtime; the Python binding + /// performs them on the caller's thread. + /// /// Interrupted GET bodies are not retried. Allow only trusted roots whose /// directory components cannot be modified by untrusted users during transfer. pub staging_allowed_local_paths: Option>, diff --git a/src/statement/volume.rs b/src/statement/volume.rs index d02a2087..053e1ece 100644 --- a/src/statement/volume.rs +++ b/src/statement/volume.rs @@ -24,6 +24,7 @@ use futures::StreamExt; use reqwest::Method; use std::collections::HashMap; use std::path::{Path, PathBuf}; +use std::time::Instant; use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio::sync::{watch, Mutex}; use tokio_util::io::ReaderStream; @@ -125,7 +126,10 @@ pub(crate) async fn complete( "File transfer interrupted; re-execute the SQL to retry", ))); let mut cancelled = completion.cancelled.subscribe(); + let log = TransferLog::new(&statement_id, &operation); + let started = Instant::now(); let transfer = transfer( + &statement_id, client, &operation, &url, @@ -140,6 +144,7 @@ pub(crate) async fn complete( } result = transfer => result, }; + log.finish("total", started, result.as_ref().err()); *completed = Some(result.map_err(|mut error| { if let Some(os_error) = error.os_error.as_mut() { os_error.filename = local_file.clone(); @@ -314,7 +319,65 @@ fn allowed_path(local_file: Option<&str>, paths: &[String]) -> Result { )) } +struct TransferLog<'a> { + statement_id: &'a str, + operation: &'static str, +} + +impl<'a> TransferLog<'a> { + fn new(statement_id: &'a str, operation: &str) -> Self { + Self { + statement_id, + operation: if operation.eq_ignore_ascii_case("PUT") { + "PUT" + } else if operation.eq_ignore_ascii_case("GET") { + "GET" + } else if operation.eq_ignore_ascii_case("REMOVE") { + "REMOVE" + } else { + "UNKNOWN" + }, + } + } + + fn start(&self, phase: &'static str) -> Instant { + crate::klog::debug!( + statement_id = self.statement_id, + operation = self.operation, + phase, + outcome = "start", + reason = "none", + elapsed_ms = 0, + "Volume transfer" + ); + Instant::now() + } + + fn finish(&self, phase: &'static str, started: Instant, error: Option<&Error>) { + let (outcome, reason) = match error.map(|error| error.code) { + None => ("success", "none"), + Some(ErrorCode::Cancelled) => ("cancelled", "cancelled"), + Some(ErrorCode::Timeout) => ("error", "timeout"), + Some(ErrorCode::PermissionDenied) => ("error", "permission_denied"), + Some(ErrorCode::NotFound) => ("error", "not_found"), + Some(ErrorCode::InvalidArgument) => ("error", "invalid_argument"), + Some(ErrorCode::NetworkError) => ("error", "transport_error"), + Some(_) => ("error", "transfer_error"), + }; + crate::klog::debug!( + statement_id = self.statement_id, + operation = self.operation, + phase, + outcome, + reason, + elapsed_ms = started.elapsed().as_millis() as u64, + "Volume transfer" + ); + } +} + async fn transfer( + statement_id: &str, client: &DatabricksHttpClient, operation: &str, url: &str, @@ -322,8 +385,9 @@ async fn transfer( local_file: Option<&str>, paths: &[String], ) -> Result<()> { - let operation = operation.to_ascii_uppercase(); - let method = match operation.as_str() { + let log = TransferLog::new(statement_id, operation); + let operation = log.operation; + let method = match operation { "PUT" => Method::PUT, "GET" => Method::GET, "REMOVE" => Method::DELETE, @@ -340,29 +404,36 @@ async fn transfer( let local = if operation == "REMOVE" { None } else { - Some(allowed_path(local_file, paths)?) - }; - if operation == "GET" { - let destination = local.as_ref().unwrap(); - match tokio::fs::metadata(destination).await { - Ok(metadata) if !metadata.is_file() && !metadata.is_dir() => { - return Err( - Error::invalid_argument().message("Download destination must be a file") - ); - } - Ok(_) => { - // Preserve the OS error for directory destinations. - tokio::fs::OpenOptions::new() - .write(true) - .open(destination) - .await - .map_err(file_error)?; + let local_file = local_file.map(str::to_owned); + let paths = paths.to_vec(); + let started = log.start("preflight"); + let local = tokio::task::spawn_blocking(move || { + let destination = allowed_path(local_file.as_deref(), &paths)?; + if operation == "GET" { + match std::fs::metadata(&destination) { + Ok(metadata) if !metadata.is_file() && !metadata.is_dir() => { + return Err(Error::invalid_argument() + .message("Download destination must be a file")); + } + Ok(_) => { + // Preserve the OS error for directory destinations. + std::fs::OpenOptions::new() + .write(true) + .open(&destination) + .map_err(file_error)?; + } + Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} + Err(error) => return Err(file_error(error)), + } } - Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} - Err(error) => return Err(file_error(error)), - } - } - let response = send_transfer(client, method, parsed, headers, local.as_deref()).await?; + Ok(destination) + }) + .await + .unwrap_or_else(|_| Err(Error::internal().message("File transfer preflight failed"))); + log.finish("preflight", started, local.as_ref().err()); + Some(local?) + }; + let response = send_transfer(client, method, parsed, headers, local.as_deref(), &log).await?; if !response.status().is_success() && !(operation == "REMOVE" && response.status().as_u16() == 404) { @@ -378,42 +449,64 @@ async fn transfer( let parent = destination.parent().ok_or_else(|| { Error::invalid_argument().message("Download destination must be a file") })?; - let builder = tempfile::Builder::new(); - #[cfg(unix)] - let builder = { - use std::os::unix::fs::PermissionsExt; - let mut builder = builder; - let permissions = match std::fs::metadata(destination) { - Ok(metadata) => metadata.permissions(), - Err(error) if error.kind() == std::io::ErrorKind::NotFound => { - std::fs::Permissions::from_mode(0o666) - } - Err(error) => return Err(file_error(error)), + let started = log.start("temp_create"); + let temporary = (|| { + let builder = tempfile::Builder::new(); + #[cfg(unix)] + let builder = { + use std::os::unix::fs::PermissionsExt; + let mut builder = builder; + let permissions = match std::fs::metadata(destination) { + Ok(metadata) => metadata.permissions(), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => { + std::fs::Permissions::from_mode(0o666) + } + Err(error) => return Err(file_error(error)), + }; + builder.permissions(permissions); + builder }; - builder.permissions(permissions); - builder - }; - let temporary = builder.tempfile_in(parent).map_err(file_error)?; - let mut file = - tokio::fs::File::from_std(temporary.as_file().try_clone().map_err(file_error)?); - let mut body = response.bytes_stream(); - while let Some(bytes) = body.next().await { - let bytes = bytes.map_err(transport_error)?; - file.write_all(&bytes).await.map_err(file_error)?; + let temporary = builder.tempfile_in(parent).map_err(file_error)?; + let file = + tokio::fs::File::from_std(temporary.as_file().try_clone().map_err(file_error)?); + Ok((temporary, file)) + })(); + log.finish("temp_create", started, temporary.as_ref().err()); + let (temporary, mut file) = temporary?; + let started = log.start("body_write"); + let body = async { + let mut body = response.bytes_stream(); + while let Some(bytes) = body.next().await { + let bytes = bytes.map_err(transport_error)?; + file.write_all(&bytes).await.map_err(file_error)?; + } + Ok(()) } - file.flush().await.map_err(file_error)?; + .await; + log.finish("body_write", started, body.as_ref().err()); + body?; + let started = log.start("body_flush"); + let flushed = file.flush().await.map_err(file_error); + log.finish("body_flush", started, flushed.as_ref().err()); + flushed?; drop(file); - match std::fs::metadata(destination) { - Ok(metadata) => temporary - .as_file() - .set_permissions(metadata.permissions()) - .map_err(file_error)?, - Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} - Err(error) => return Err(file_error(error)), - } - temporary - .persist(destination) - .map_err(|error| file_error(error.error))?; + let started = log.start("commit"); + let committed = (|| { + match std::fs::metadata(destination) { + Ok(metadata) => temporary + .as_file() + .set_permissions(metadata.permissions()) + .map_err(file_error)?, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} + Err(error) => return Err(file_error(error)), + } + temporary + .persist(destination) + .map_err(|error| file_error(error.error))?; + Ok(()) + })(); + log.finish("commit", started, committed.as_ref().err()); + committed?; } Ok(()) } @@ -433,7 +526,62 @@ fn transport_error(error: reqwest::Error) -> Error { } else { "File transfer request failed" }; - Error::new(code, message).with_cause(Error::new(code, format!("{:?}", error.without_url()))) + let message = format!("{message}: {}", transport_reason(&error)); + Error::new(code, message.clone()).with_cause(Error::new(code, message)) +} + +fn transport_reason(error: &reqwest::Error) -> &'static str { + let mut io_reason = None; + let mut http_reason = None; + for source in crate::client::error_chain(error).take(8) { + if let Some(error) = source.downcast_ref::() { + io_reason = io_reason.or(match error.kind() { + std::io::ErrorKind::UnexpectedEof => Some("unexpected_eof"), + std::io::ErrorKind::ConnectionRefused => Some("connection_refused"), + std::io::ErrorKind::ConnectionReset => Some("connection_reset"), + std::io::ErrorKind::ConnectionAborted => Some("connection_aborted"), + std::io::ErrorKind::NotConnected => Some("not_connected"), + std::io::ErrorKind::BrokenPipe => Some("broken_pipe"), + std::io::ErrorKind::TimedOut => Some("timeout"), + std::io::ErrorKind::PermissionDenied => Some("permission_denied"), + _ => None, + }); + } + if let Some(source) = source.downcast_ref::() { + http_reason = http_reason.or(if source.is_incomplete_message() { + Some(if error.is_body() || error.is_decode() { + "unexpected_eof" + } else { + "incomplete_response" + }) + } else if source.is_closed() { + Some("connection_closed") + } else if source.is_parse() { + Some("invalid_response") + } else if source.is_canceled() { + Some("cancelled") + } else if source.is_timeout() { + Some("timeout") + } else if source.is_body_write_aborted() { + Some("body_write_aborted") + } else { + None + }); + } + } + io_reason.or(http_reason).unwrap_or(if error.is_timeout() { + "timeout" + } else if error.is_connect() { + "connection_failed" + } else if error.is_body() { + "body_error" + } else if error.is_decode() { + "decode_error" + } else if error.is_builder() { + "invalid_request" + } else { + "request_failed" + }) } async fn send_transfer( @@ -442,8 +590,9 @@ async fn send_transfer( url: reqwest::Url, headers: &HashMap, local: Option<&Path>, + log: &TransferLog<'_>, ) -> Result { - let config = client.storage_retry_config(); + let config = client.volume_retry_config(); let request_type = if method == Method::PUT { RequestType::VolumeUpload } else { @@ -451,6 +600,17 @@ async fn send_transfer( }; let strategy = RetryStrategy::for_request(request_type, &config); let started = std::time::Instant::now(); + let attempt_limit = u64::from(config.max_retries) + 1; + crate::klog::debug!( + statement_id = log.statement_id, + operation = log.operation, + phase = "retry_policy", + outcome = "resolved", + reason = "none", + attempt_limit, + budget_ms = config.overall_timeout.as_millis() as u64, + "Volume transfer" + ); for attempt in 0..=config.max_retries { let remaining = config.overall_timeout.saturating_sub(started.elapsed()); if remaining.is_zero() { @@ -474,19 +634,30 @@ async fn send_transfer( if method == Method::PUT { let local = local .ok_or_else(|| Error::invalid_argument().message("Missing local upload path"))?; - if !tokio::fs::metadata(local) - .await - .map_err(file_error)? - .is_file() - { - return Err(Error::invalid_argument().message("Local upload path must be a file")); - } - // Each retry reopens the file so a streaming upload starts at byte zero. - let file = tokio::fs::File::open(local).await.map_err(file_error)?; - let metadata = file.metadata().await.map_err(file_error)?; - if !metadata.is_file() { - return Err(Error::invalid_argument().message("Local upload path must be a file")); + let opened_at = log.start("upload_open"); + let opened = async { + if !tokio::fs::metadata(local) + .await + .map_err(file_error)? + .is_file() + { + return Err( + Error::invalid_argument().message("Local upload path must be a file") + ); + } + // Each retry reopens the file so a streaming upload starts at byte zero. + let file = tokio::fs::File::open(local).await.map_err(file_error)?; + let metadata = file.metadata().await.map_err(file_error)?; + if !metadata.is_file() { + return Err( + Error::invalid_argument().message("Local upload path must be a file") + ); + } + Ok((file, metadata)) } + .await; + log.finish("upload_open", opened_at, opened.as_ref().err()); + let (file, metadata) = opened?; request = request .header(reqwest::header::CONTENT_LENGTH, metadata.len()) .body(reqwest::Body::wrap_stream(ReaderStream::new( @@ -494,7 +665,35 @@ async fn send_transfer( ))); } // Presigned storage requests must omit workspace credentials and custom headers. + let attempt_started = Instant::now(); + crate::klog::debug!( + statement_id = log.statement_id, + operation = log.operation, + phase = "attempt", + outcome = "start", + reason = "none", + attempt = u64::from(attempt) + 1, + attempt_limit, + remaining_ms = remaining.as_millis() as u64, + "Volume transfer" + ); let response = request.send().await; + crate::klog::debug!( + statement_id = log.statement_id, + operation = log.operation, + phase = "attempt", + outcome = if response.is_ok() { "headers" } else { "error" }, + reason = response + .as_ref() + .err() + .map(transport_reason) + .unwrap_or("none"), + attempt = u64::from(attempt) + 1, + attempt_limit, + http_status = response.as_ref().ok().map(|r| r.status().as_u16()), + elapsed_ms = attempt_started.elapsed().as_millis() as u64, + "Volume transfer" + ); let (retryable, retry_after) = match &response { Ok(response) => ( strategy.is_retryable_status( @@ -510,11 +709,40 @@ async fn send_transfer( ), Err(error) => (strategy.is_retryable_error(error), None), }; - if !retryable || attempt == config.max_retries { - return response.map_err(transport_error); - } - let delay = calculate_backoff(&config, attempt, retry_after); - if started.elapsed().saturating_add(delay) >= config.overall_timeout { + let delay = if retryable && attempt < config.max_retries { + calculate_backoff(&config, attempt, retry_after) + } else { + std::time::Duration::ZERO + }; + let reason = if !retryable { + "not_retryable" + } else if attempt == config.max_retries { + "attempt_limit" + } else if started.elapsed().saturating_add(delay) >= config.overall_timeout { + "budget_exhausted" + } else { + "retryable" + }; + crate::klog::debug!( + statement_id = log.statement_id, + operation = log.operation, + phase = "retry", + outcome = if reason == "retryable" { + "scheduled" + } else { + "stop" + }, + reason, + attempt = u64::from(attempt) + 1, + attempt_limit, + remaining_ms = config + .overall_timeout + .saturating_sub(started.elapsed()) + .as_millis() as u64, + backoff_ms = delay.as_millis() as u64, + "Volume transfer" + ); + if reason != "retryable" { return response.map_err(transport_error); } tokio::time::sleep(delay).await; @@ -572,50 +800,59 @@ mod tests { } } - #[tokio::test] - async fn completes_transfer_once_and_preserves_requested_result() { - let server = MockServer::start().await; - Mock::given(method("GET")) - .and(path("/file")) - .respond_with(ResponseTemplate::new(200).set_body_bytes(b"file contents")) - .expect(1) - .mount(&server) - .await; - let dir = tempfile::tempdir().unwrap(); - let local = dir.path().join("download"); - let batch = instruction( - "gEt", - &format!("{}/file", server.uri()), - local.to_str().unwrap(), - ); - let options = VolumeOptions { - paths: Some(vec![dir.path().to_str().unwrap().into()]), - retain_result: true, - ..Default::default() - }; - let completion = VolumeCompletion::default(); - let http = client(); - for _ in 0..2 { - let mut execution = result(batch.clone(), true); - execution.reader = Box::new(InMemoryReader::new( - batch.schema(), - vec![ - RecordBatch::new_empty(batch.schema()), - batch.clone(), - RecordBatch::new_empty(batch.schema()), - ], - )); - let completed = complete(&http, execution, &options, &completion) - .await - .unwrap(); - let mut reader = ResultStream::from_reader(completed.reader).await.unwrap(); - assert!(reader.next_batch().await.unwrap().is_some()); - assert!(reader.next_batch().await.unwrap().is_none()); - } - assert_eq!(tokio::fs::read(local).await.unwrap(), b"file contents"); - let request = server.received_requests().await.unwrap().remove(0); - assert!(!request.headers.contains_key("authorization")); - assert_eq!(request.headers["x-file-header"], "value"); + #[test] + fn completes_transfer_once_and_preserves_requested_result() { + let runtime = tokio::runtime::Builder::new_multi_thread() + .worker_threads(1) + .enable_all() + .build() + .unwrap(); + tokio::task::LocalSet::new().block_on(&runtime, async { + let server = MockServer::start().await; + Mock::given(method("GET")) + .and(path("/file")) + .respond_with(ResponseTemplate::new(200).set_body_bytes(b"file contents")) + .expect(1) + .mount(&server) + .await; + let dir = tempfile::tempdir().unwrap(); + let local = dir.path().join("download"); + std::fs::write(&local, b"stale bytes").unwrap(); + let batch = instruction( + "gEt", + &format!("{}/file", server.uri()), + local.to_str().unwrap(), + ); + let options = VolumeOptions { + paths: Some(vec![dir.path().to_str().unwrap().into()]), + retain_result: true, + ..Default::default() + }; + let completion = VolumeCompletion::default(); + let http = client(); + for _ in 0..2 { + let mut execution = result(batch.clone(), true); + execution.reader = Box::new(InMemoryReader::new( + batch.schema(), + vec![ + RecordBatch::new_empty(batch.schema()), + batch.clone(), + RecordBatch::new_empty(batch.schema()), + ], + )); + let completed = complete(&http, execution, &options, &completion) + .await + .unwrap(); + let mut reader = ResultStream::from_reader(completed.reader).await.unwrap(); + assert!(reader.next_batch().await.unwrap().is_some()); + assert!(reader.next_batch().await.unwrap().is_none()); + } + assert_eq!(tokio::fs::read(&local).await.unwrap(), b"file contents"); + assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 1); + let request = server.received_requests().await.unwrap().remove(0); + assert!(!request.headers.contains_key("authorization")); + assert_eq!(request.headers["x-file-header"], "value"); + }); } #[tokio::test] @@ -774,13 +1011,29 @@ mod tests { .await; let url = format!("{}/redirect", server.uri()); let strict = DatabricksHttpClient::with_default_retry(HttpClientConfig::default()).unwrap(); - let error = transfer(&strict, "REMOVE", &url, &HashMap::new(), None, &[]) - .await - .unwrap_err(); + let error = transfer( + "statement", + &strict, + "REMOVE", + &url, + &HashMap::new(), + None, + &[], + ) + .await + .unwrap_err(); assert!(error.message.contains("URL scheme")); - let error = transfer(&client(), "REMOVE", &url, &HashMap::new(), None, &[]) - .await - .unwrap_err(); + let error = transfer( + "statement", + &client(), + "REMOVE", + &url, + &HashMap::new(), + None, + &[], + ) + .await + .unwrap_err(); assert_eq!(error.http_status, Some(307)); } @@ -832,7 +1085,15 @@ mod tests { (permissions.unwrap(), original) }; let (result, (permissions, original)) = tokio::join!( - transfer(&http, "GET", &url, &headers, destination.to_str(), &roots), + transfer( + "statement", + &http, + "GET", + &url, + &headers, + destination.to_str(), + &roots + ), inspect ); result.unwrap(); @@ -864,6 +1125,7 @@ mod tests { .unwrap(); } transfer( + "statement", &client(), "GET", &server.uri(), @@ -893,6 +1155,7 @@ mod tests { .is_err() { let error = transfer( + "statement", &client(), "GET", &server.uri(), @@ -911,6 +1174,7 @@ mod tests { } for destination in [Path::new("/"), dir.path()] { let error = transfer( + "statement", &client(), "GET", &server.uri(), @@ -949,6 +1213,7 @@ mod tests { let local = dir.path().join("input"); tokio::fs::write(&local, b"upload").await.unwrap(); transfer( + "statement", &client(), "pUt", &format!("http://{address}/file"), @@ -982,6 +1247,7 @@ mod tests { .mount(&server) .await; transfer( + "statement", &client(), "remove", &format!("{}/file", server.uri()), @@ -1009,6 +1275,7 @@ mod tests { let url = format!("{}/file", server.uri()); let mut upload = tokio::spawn(async move { transfer( + "statement", &client(), "PUT", &url, @@ -1060,6 +1327,7 @@ mod tests { let file = dir.path().join("input"); std::fs::write(&file, b"upload").unwrap(); transfer( + "statement", &client(), "PUT", &format!("{}/file", server.uri()), @@ -1102,6 +1370,7 @@ mod tests { let local = directory.path().join("input"); std::fs::write(&local, b"upload").unwrap(); let outcome = transfer( + "statement", &client(), "PUT", &url, @@ -1111,7 +1380,9 @@ mod tests { ) .await; server.abort(); - assert!(outcome.is_err()); + let error = outcome.unwrap_err(); + assert_eq!(error.code, ErrorCode::NetworkError); + assert!(error.message.contains("incomplete_response"), "{error:?}"); assert_eq!(attempts.load(Ordering::SeqCst), 1); } @@ -1183,7 +1454,7 @@ mod tests { }; let mut http = DatabricksHttpClient::new( HttpClientConfig::default(), - HashMap::from([(RequestCategory::CloudFetch, retry)]), + HashMap::from([(RequestCategory::Sea, retry)]), ) .unwrap(); http.allow_loopback_plaintext_storage = true; @@ -1305,6 +1576,7 @@ mod tests { let outside = dir.path().join("outside"); for operation in ["PUT", "GET"] { let error = transfer( + "statement", &client(), operation, "http://127.0.0.1:1/file", @@ -1357,11 +1629,9 @@ mod tests { max_retries: 0, ..Default::default() }; - let mut http = DatabricksHttpClient::new( - config, - HashMap::from([(RequestCategory::CloudFetch, retry)]), - ) - .unwrap(); + let mut http = + DatabricksHttpClient::new(config, HashMap::from([(RequestCategory::Sea, retry)])) + .unwrap(); http.allow_loopback_plaintext_storage = true; let dir = tempfile::tempdir().unwrap(); let file = dir.path().join("download"); @@ -1413,6 +1683,9 @@ mod tests { #[tokio::test] async fn transport_cause_omits_signed_url() { + use std::io::Write; + use tracing::instrument::WithSubscriber; + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); let address = listener.local_addr().unwrap(); drop(listener); @@ -1423,13 +1696,84 @@ mod tests { .unwrap_err(); let error = transport_error(error); assert!(error.cause.is_some()); + assert!(error.message.contains("connection_refused"), "{error:?}"); assert!(!format!("{error:?}").contains("signature")); assert!(!format!("{error:?}").contains("secret")); + + struct Capture(Arc>>); + impl Write for Capture { + fn write(&mut self, bytes: &[u8]) -> std::io::Result { + self.0.lock().unwrap().extend_from_slice(bytes); + Ok(bytes.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } + let captured = Arc::new(std::sync::Mutex::new(Vec::new())); + let writer = captured.clone(); + let subscriber = tracing_subscriber::fmt() + .with_env_filter("databricks::sql::kernel=debug") + .without_time() + .with_ansi(false) + .with_writer(move || Capture(writer.clone())) + .finish(); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!( + "http://{}/remote-sentinel?signature=secret-sentinel", + listener.local_addr().unwrap() + ); + let server = tokio::spawn(async move { + let (mut socket, _) = listener.accept().await.unwrap(); + let mut request = Vec::new(); + while !request.ends_with(b"\r\n\r\n") { + request.push(socket.read_u8().await.unwrap()); + } + socket.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 8\r\nX-Sentinel: header-sentinel\r\nConnection: close\r\n\r\npart").await.unwrap(); + }); + let dir = tempfile::tempdir().unwrap(); + let local = dir.path().join("local-path-sentinel"); + std::fs::write(&local, b"original").unwrap(); + let error = transfer( + "statement", + &client(), + "GET", + &url, + &HashMap::from([("x-file-header".into(), "header-sentinel".into())]), + local.to_str(), + &[dir.path().to_str().unwrap().into()], + ) + .with_subscriber(subscriber) + .await + .unwrap_err(); + server.await.unwrap(); + assert_eq!(error.code, ErrorCode::NetworkError); + assert!(error.message.contains("unexpected_eof"), "{error:?}"); + assert_eq!(std::fs::read(local).unwrap(), b"original"); + assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 1); + let logs = String::from_utf8(captured.lock().unwrap().clone()).unwrap(); + assert!(logs.contains("Volume transfer")); + assert!( + logs.contains("body_write") && logs.contains("error"), + "{logs}" + ); + let diagnostics = format!("{error:?}\n{logs}"); + for sentinel in [ + "signature", + "secret-sentinel", + "remote-sentinel", + "header-sentinel", + "local-path-sentinel", + &url, + ] { + assert!(!diagnostics.contains(sentinel), "{diagnostics}"); + } } #[tokio::test] async fn rejects_plaintext_storage_host() { let error = transfer( + "statement", &client(), "REMOVE", "http://storage.example/file?signature=secret", diff --git a/tests/v0_async_execute_wiremock.rs b/tests/v0_async_execute_wiremock.rs index 06e6c885..93633dc8 100644 --- a/tests/v0_async_execute_wiremock.rs +++ b/tests/v0_async_execute_wiremock.rs @@ -2296,6 +2296,83 @@ async fn await_result_succeeded_status_still_closes_statement() { // `_close` also verifies expect(1) when it drops at end of scope. } +#[tokio::test] +async fn file_transfer_uses_session_retry_policy() { + use databricks_sql_kernel::HttpConfig; + use std::sync::atomic::{AtomicUsize, Ordering}; + use std::time::Duration; + + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_delete_session(&server).await; + mount_close_any_statement(&server).await; + let requests = Arc::new(AtomicUsize::new(0)); + let count = requests.clone(); + Mock::given(method("GET")) + .and(path("/storage/file")) + .respond_with(move |_: &wiremock::Request| { + if count.fetch_add(1, Ordering::SeqCst) == 0 { + ResponseTemplate::new(503).insert_header("Retry-After", "0") + } else { + ResponseTemplate::new(200).set_body_bytes(b"fresh download") + } + }) + .mount(&server) + .await; + let dir = tempfile::tempdir().unwrap(); + let destination = dir.path().join("download"); + std::fs::write(&destination, b"stale bytes").unwrap(); + mount_submit( + &server, + file_transfer_body( + "GET", + &format!("{}/storage/file", server.uri()), + &destination, + ), + ) + .await; + let mut http = HttpConfig::default(); + http.retry_min_wait = Duration::from_millis(1); + http.retry_max_wait = Duration::from_millis(1); + http.retry_max_retries = 1; + http.overall_timeout = Duration::from_secs(5); + let session = Session::builder() + .connection( + ConnectionConfig::from_http_path(server.uri(), "/sql/1.0/warehouses/test_wh").unwrap(), + ) + .auth(AuthConfig::Pat { + token: "dapi_test_token".into(), + identity_federation_client_id: None, + }) + .http(http) + .open() + .await + .unwrap(); + let mut statement = session.statement(); + statement + .spec() + .sql("GET '/Volumes/c/s/v/file' TO '/tmp/download'"); + statement.spec().staging_allowed_local_paths = Some(vec![dir.path().to_str().unwrap().into()]); + let result = statement.execute().await; + assert!( + result.is_ok(), + "storage requests={}: {:?}", + requests.load(Ordering::SeqCst), + result.as_ref().err() + ); + let mut result = result.unwrap(); + assert!(result + .result_stream_mut() + .next_batch() + .await + .unwrap() + .is_none()); + assert_eq!(requests.load(Ordering::SeqCst), 2); + assert_eq!(std::fs::read(destination).unwrap(), b"fresh download"); + result.close().await.unwrap(); + session.close().await.unwrap(); +} + #[tokio::test] async fn file_transfer_completion_is_shared_by_independent_readers() { let server = MockServer::start().await; @@ -2335,6 +2412,240 @@ async fn file_transfer_completion_is_shared_by_independent_readers() { session.close().await.unwrap(); } +#[tokio::test] +async fn owner_close_interrupts_download() { + release_during_download("owner-close").await; +} + +#[tokio::test] +async fn owner_drop_interrupts_download_after_server_close() { + release_during_download("owner-drop").await; +} + +#[tokio::test] +async fn parent_close_interrupts_direct_download() { + release_during_download("parent-close").await; +} + +#[tokio::test] +async fn parent_drop_interrupts_download() { + release_during_download("parent-drop").await; +} + +#[tokio::test] +async fn parent_reuse_interrupts_download_and_allows_next_transfer() { + release_during_download("parent-reuse").await; +} + +#[tokio::test] +async fn owner_deadline_interrupts_reader_download() { + release_during_download("owner-deadline").await; +} + +#[tokio::test] +async fn idle_reader_drop_preserves_download() { + release_during_download("reader-drop").await; +} + +async fn release_during_download(mode: &str) { + use databricks_sql_kernel::DirectStatement; + use std::time::Duration; + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_delete_session(&server).await; + mount_close_any_statement(&server).await; + Mock::given(method("POST")) + .and(path("/api/2.0/sql/statements/transfer/cancel")) + .respond_with(ResponseTemplate::new(200).set_body_string("{}")) + .expect(u64::from(mode == "owner-deadline")) + .mount(&server) + .await; + if mode == "owner-drop" { + Mock::given(method("DELETE")) + .and(path("/api/2.0/sql/statements/transfer")) + .respond_with(ResponseTemplate::new(200)) + .expect(0) + .mount(&server) + .await; + } + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let (started, received) = tokio::sync::oneshot::channel(); + let (release, released) = tokio::sync::oneshot::channel(); + let storage = tokio::spawn(async move { + let (mut socket, _) = listener.accept().await.unwrap(); + let mut headers = Vec::new(); + while !headers.ends_with(b"\r\n\r\n") { + headers.push(socket.read_u8().await.unwrap()); + } + socket + .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 8\r\nConnection: close\r\n\r\nnew-") + .await + .unwrap(); + started.send(()).unwrap(); + let _ = released.await; + let _ = socket.write_all(b"data").await; + }); + let directory = tempfile::tempdir().unwrap(); + let destination = directory.path().join("download"); + std::fs::write(&destination, b"original").unwrap(); + let mut body: serde_json::Value = serde_json::from_str(&file_transfer_body( + "GET", + &format!("http://{address}/file"), + &destination, + )) + .unwrap(); + if mode == "owner-drop" { + body["status"]["state"] = json!("CLOSED"); + } + mount_status_once(&server, "transfer", body.to_string()).await; + Mock::given(method("POST")) + .and(path("/api/2.0/sql/statements")) + .respond_with(ResponseTemplate::new(200).set_body_string(pending_body("transfer"))) + .up_to_n_times(1) + .mount(&server) + .await; + let session = open_session(&server).await; + let mut statement = session.statement(); + statement + .spec() + .sql("GET '/Volumes/c/s/v/file' TO 'download'"); + statement.spec().staging_allowed_local_paths = + Some(vec![directory.path().to_str().unwrap().into()]); + let owner = if mode == "parent-close" { + match statement.execute_direct().await.unwrap() { + DirectStatement::Running(owner) => owner, + DirectStatement::Completed(_) => panic!("expected running statement"), + } + } else if mode == "owner-deadline" { + statement + .submit_with_timeout(Duration::from_secs(1)) + .await + .unwrap() + } else { + statement.submit().await.unwrap() + }; + let first = owner.reader().unwrap(); + let sibling = owner.reader().unwrap(); + let mut readers = tokio::task::JoinSet::new(); + readers.spawn(async move { first.fetch_result().await.map(|_| ()) }); + tokio::time::timeout(Duration::from_secs(5), received) + .await + .expect("download did not start") + .unwrap(); + if mode == "owner-close" { + readers.spawn(async move { sibling.fetch_result().await.map(|_| ()) }); + tokio::task::yield_now().await; + } else { + drop(sibling); + } + let mut owner = Some(owner); + let mut statement = Some(statement); + let mut next = None; + match mode { + "owner-close" => owner.as_mut().unwrap().close().await.unwrap(), + "owner-drop" => { + assert!(tokio::time::timeout( + Duration::from_millis(100), + owner.as_ref().unwrap().await_result(), + ) + .await + .is_err()); + drop(owner.take()); + } + "parent-close" => statement.take().unwrap().close().await.unwrap(), + "parent-drop" => drop(statement.take()), + "parent-reuse" => { + mount_submit(&server, pending_body("next-transfer")).await; + let mut body: serde_json::Value = serde_json::from_str(&file_transfer_body( + "GET", + &format!("{}/storage/next", server.uri()), + &destination, + )) + .unwrap(); + body["statement_id"] = json!("next-transfer"); + mount_status_once(&server, "next-transfer", body.to_string()).await; + Mock::given(method("GET")) + .and(path("/storage/next")) + .respond_with(ResponseTemplate::new(200).set_body_bytes(b"fresh")) + .expect(1) + .mount(&server) + .await; + next = Some(statement.as_mut().unwrap().submit().await.unwrap()); + } + "owner-deadline" => { + tokio::time::sleep(Duration::from_secs(1)).await; + let error = owner.as_ref().unwrap().status().await.unwrap_err(); + assert_eq!(error.code, ErrorCode::Timeout); + assert_eq!(error.sql_state.as_deref(), Some("HYT00")); + assert_eq!(error.query_id.as_deref(), Some("transfer")); + assert!(!error.retryable); + } + "reader-drop" => {} + _ => panic!("unknown release mode: {mode}"), + } + assert_eq!(std::fs::read(&destination).unwrap(), b"original"); + let mut outcomes = Vec::new(); + let stopped = if mode == "reader-drop" { + false + } else { + tokio::time::timeout(Duration::from_secs(2), async { + while let Some(result) = readers.join_next().await { + outcomes.push(result.unwrap()); + } + }) + .await + .is_ok() + }; + release.send(()).unwrap(); + storage.await.unwrap(); + tokio::time::timeout(Duration::from_secs(5), async { + while let Some(result) = readers.join_next().await { + outcomes.push(result.unwrap()); + } + }) + .await + .expect("reader did not finish after releasing storage"); + let bytes = std::fs::read(&destination).unwrap(); + if mode == "reader-drop" { + outcomes.pop().unwrap().unwrap(); + assert_eq!(bytes, b"new-data"); + } else { + for outcome in outcomes { + let error = outcome.unwrap_err(); + assert_eq!(error.code, ErrorCode::InvalidStatementHandle, "{mode}"); + assert!(error.error_code.is_none(), "{mode}: {error:?}"); + } + assert!( + stopped, + "{mode}: reader waited for storage; final bytes: {bytes:?}" + ); + assert_eq!(bytes, b"original", "{mode}"); + } + assert_eq!(std::fs::read_dir(directory.path()).unwrap().count(), 1); + if let Some(next) = next { + next.fetch_result().await.unwrap(); + assert_eq!(std::fs::read(&destination).unwrap(), b"fresh"); + next.close().await.unwrap(); + } + if mode == "owner-deadline" { + assert_eq!( + wait_for_close_delete(&server, "transfer", 1, Duration::from_secs(5)).await, + 1 + ); + } + if let Some(owner) = owner { + owner.close().await.unwrap(); + } + if let Some(statement) = statement { + statement.close().await.unwrap(); + } + session.close().await.unwrap(); + server.verify().await; +} + #[tokio::test] async fn sync_and_direct_transfers_complete_and_preserve_error_context() { use databricks_sql_kernel::DirectStatement; From 65e8e5f270a393482f0a4186c4de713501daf18d Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Fri, 13 Nov 2026 00:17:05 +0000 Subject: [PATCH 36/39] fix(c-abi): preserve native filesystem error details Signed-off-by: Aakash Saravanan --- include/databricks_kernel.h | 28 +++++--- src/c_abi/error.rs | 132 ++++++++++++++++++++++++++++++------ 2 files changed, 130 insertions(+), 30 deletions(-) diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h index 0fe272f7..8d035106 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -32,9 +32,10 @@ * Every fallible entry point returns a `KernelStatusCode`. On any * non-`Success` return, call `kernel_get_last_error` to fetch the typed * detail for the current thread. The thread-local error buffer is reset - * at the start of every kernel call, and the `char*` fields it hands - * back are valid only until the next kernel call on the same thread — - * copy them out before calling again. + * at the start of kernel calls except `kernel_get_last_error` and + * `kernel_get_last_error_os`, which leave it intact. Borrowed `char*` + * fields remain valid until a call clears or replaces that thread's + * buffer; copy them before such a call. * * ## ABI versioning * @@ -44,7 +45,7 @@ * pointers to them, never read their fields — so their Rust-side layout * is irrelevant. The one caller-*readable* struct, `KernelError`, is laid * out exactly as declared here; copy its fields out before the next - * `kernel_*` call on the thread. + * call that clears or replaces the thread's error buffer. * * ## Lifecycle & threading notes * @@ -168,9 +169,9 @@ typedef enum KernelStatementStatusKind { /* * Typed last-error detail. Populated by `kernel_get_last_error`. The * `char*` fields point into the calling thread's last-error buffer and - * are valid only until the next kernel call on that thread; a NULL - * pointer means the field was absent. `vendor_code` / `http_status` are - * `0` when absent. + * remain valid until a call clears or replaces it; both error getters + * leave it intact. A NULL pointer means the field was absent. + * `vendor_code` / `http_status` are `0` when absent. */ typedef struct KernelError { /* Discriminant value of `KernelStatusCode`. */ @@ -187,10 +188,21 @@ typedef struct KernelError { /* * Fetch the last error recorded on the calling thread. Returns `false` * (leaving `*out` untouched) if no error has been recorded since the - * last kernel call cleared the buffer. + * last kernel call cleared the buffer, or if `out` is NULL. Both error + * getters are read-only and can be called repeatedly in either order. */ bool kernel_get_last_error(KernelError* out); +/* + * Fetch optional OS details from the calling thread's last error. Returns + * `false` without writing outputs if either output pointer is NULL or OS + * details are absent. On `true`, `*code_out` is the raw native code (errno + * on Unix, system error code on Windows) and `*filename_out` is NULL when + * absent. A non-NULL filename borrows the error buffer until a call clears + * or replaces it. Both error getters leave the buffer and strings intact. + */ +bool kernel_get_last_error_os(int32_t* code_out, const char** filename_out); + /* ─── Opaque handles ────────────────────────────────────────────────── * * All handles are owned heap allocations on the Rust side; the C side diff --git a/src/c_abi/error.rs b/src/c_abi/error.rs index f5243007..1e0718bb 100644 --- a/src/c_abi/error.rs +++ b/src/c_abi/error.rs @@ -12,12 +12,11 @@ // See the License for the specific language governing permissions and // limitations under the License. -//! Thread-local last-error storage and the `kernel_get_last_error` C -//! entry point. +//! Thread-local last-error storage and read-only C error getters. //! //! Pattern borrowed from the legacy `src/adbc/ffi/error.rs`: every C -//! function clears the buffer at entry and writes to it on error; -//! callers fetch detail with `kernel_get_last_error`. +//! function except the error getters clears the buffer at entry and +//! writes to it on error; the getters leave the buffer intact. use super::KernelStatusCode; use crate::kernel_error::Error; @@ -27,9 +26,9 @@ use std::ffi::{c_char, CString}; /// Mirror of `crate::kernel_error::Error` in `repr(C)` form. /// /// String fields are owned by the kernel's thread-local buffer; the -/// caller copies them out before the next FFI call on this thread -/// clears the buffer. Pointers are nullable for fields the underlying -/// `Error` left as `None`. +/// caller copies them out before an FFI call on this thread clears or +/// replaces the buffer. Error getters leave it intact. Pointers are nullable +/// for fields the underlying `Error` left as `None`. #[repr(C)] pub struct KernelError { /// Discriminant matches `KernelStatusCode` (cast-equal). Use @@ -50,7 +49,7 @@ pub struct KernelError { /// Owned backing store for the thread-local last error. /// /// Holds the `CString`s alive so the `*const c_char` pointers handed -/// back through [`KernelError`] stay valid until the next FFI call on +/// back through the error getters stay valid until an FFI call on /// this thread clears or overwrites the buffer. `code == None` means /// "no error recorded since the last clear". #[derive(Default)] @@ -62,13 +61,14 @@ struct LastError { http_status: u16, retryable: bool, query_id: Option, + os_error: Option<(i32, Option)>, } thread_local! { /// Per-thread last-error slot. The C ABI is call-response on a /// single thread: a function clears this on entry, populates it on /// failure, and the caller reads it via `kernel_get_last_error` - /// before making the next FFI call on the same thread. + /// before making a call that clears or replaces it on the same thread. static LAST_ERROR: RefCell = RefCell::new(LastError::default()); } @@ -95,13 +95,12 @@ pub(crate) fn to_cstring_lossy(s: &str) -> CString { /// Returns `false` if no error has been recorded since the last /// [`clear_error`] (or thread start), leaving `*out` untouched. On /// `true`, `*out` is fully populated; its `*const c_char` fields point -/// into this thread's last-error buffer and are valid until the next -/// `kernel_*` call on this thread. +/// into this thread's last-error buffer and are valid until a call clears +/// or replaces it. Both error getters leave the buffer intact. /// /// # Safety /// `out` must be a valid, writable pointer to a `KernelError`. The -/// pointer fields it returns are valid until the next FFI call on -/// this thread. +/// pointer fields it returns borrow this thread's last-error buffer. #[no_mangle] pub unsafe extern "C" fn kernel_get_last_error(out: *mut KernelError) -> bool { if out.is_null() { @@ -130,6 +129,39 @@ pub unsafe extern "C" fn kernel_get_last_error(out: *mut KernelError) -> bool { }) } +/// Fetch optional raw OS details without clearing this thread's last error. +/// +/// Returns `false` without writing outputs if either pointer is null or +/// OS details are absent. On `true`, the filename pointer is null when +/// absent; otherwise it borrows the buffer until a call clears or replaces +/// it. Both error getters can be called repeatedly in either order. +/// +/// # Safety +/// Non-null outputs must be valid, writable pointers to their respective +/// types. Copy the filename before a call clears or replaces the buffer. +#[no_mangle] +pub unsafe extern "C" fn kernel_get_last_error_os( + code_out: *mut i32, + filename_out: *mut *const c_char, +) -> bool { + if code_out.is_null() || filename_out.is_null() { + return false; + } + LAST_ERROR.with(|cell| { + let last = cell.borrow(); + let Some((code, filename)) = &last.os_error else { + return false; + }; + // SAFETY: both outputs are non-null and writable per the contract. + std::ptr::write(code_out, *code); + std::ptr::write( + filename_out, + filename.as_ref().map_or(std::ptr::null(), |s| s.as_ptr()), + ); + true + }) +} + /// Crate-internal: write a typed kernel [`Error`] into the thread-local /// last-error buffer. Every FFI function that returns a non-`Success` /// status code calls this (via [`crate::c_abi::block_on_ffi`] or directly) @@ -158,13 +190,16 @@ pub(crate) fn store_error(err: Error) { http_status: err.http_status.unwrap_or(0), retryable: err.retryable, query_id: err.query_id.as_deref().map(to_cstring_lossy), + os_error: err + .os_error + .map(|os| (os.code, os.filename.as_deref().map(to_cstring_lossy))), }; }); } /// Crate-internal: clear the thread-local last-error buffer. Called at -/// the entry of every FFI function (via [`crate::c_abi::block_on_ffi`] or -/// directly) so a previous call's stale error can't leak into a +/// the entry of FFI functions other than the error getters (via +/// [`crate::c_abi::block_on_ffi`] or directly) so stale errors can't leak into a /// subsequent one that succeeds. pub(crate) fn clear_error() { LAST_ERROR.with(|cell| *cell.borrow_mut() = LastError::default()); @@ -208,19 +243,51 @@ mod tests { #[test] fn no_error_after_clear() { + let mut error = Error::internal().message("local failure"); + error.os_error = Some(Box::new(crate::kernel_error::OsError { + code: 2, + filename: Some("local-file".into()), + })); + store_error(error.clone()); clear_error(); with_last_error(|e| assert!(e.is_none())); + let mut code = -1; + let untouched = c"untouched".as_ptr(); + let mut filename = untouched; + assert!(!unsafe { kernel_get_last_error_os(&mut code, &mut filename) }); + assert_eq!(code, -1); + assert_eq!(filename, untouched); + + store_error(error); + store_error(Error::from_http_status(404).message("remote failure")); + assert!(!unsafe { kernel_get_last_error_os(&mut code, &mut filename) }); + assert_eq!(code, -1); + assert_eq!(filename, untouched); + with_last_error(|e| assert_eq!(e.unwrap().http_status, 404)); + clear_error(); } #[test] fn store_then_fetch_roundtrips_core_fields() { - store_error( - Error::sql_error() - .message("boom") - .with_sql_state("42601") - .with_http_status(400) - .with_query_id("q-123"), - ); + let mut error = Error::sql_error() + .message("boom") + .with_sql_state("42601") + .with_http_status(400) + .with_query_id("q-123"); + error.os_error = Some(Box::new(crate::kernel_error::OsError { + code: 2, + filename: Some("requested/local-file".into()), + })); + store_error(error.clone()); + let mut code = -1; + let mut filename = std::ptr::null(); + assert!(unsafe { kernel_get_last_error_os(&mut code, &mut filename) }); + assert_eq!(code, 2); + let path = filename; + assert!(!unsafe { kernel_get_last_error_os(std::ptr::null_mut(), &mut filename) }); + assert!(!unsafe { kernel_get_last_error_os(&mut code, std::ptr::null_mut()) }); + assert_eq!(code, 2); + assert_eq!(filename, path); with_last_error(|e| { let e = e.expect("error present"); assert_eq!(e.code, KernelStatusCode::SqlError as i32); @@ -238,7 +305,28 @@ mod tests { .to_str() .unwrap(); assert_eq!(qid, "q-123"); + for _ in 0..2 { + assert!(unsafe { kernel_get_last_error_os(&mut code, &mut filename) }); + assert_eq!(code, 2); + assert_eq!(filename, path); + assert_eq!( + unsafe { std::ffi::CStr::from_ptr(path) }.to_str().unwrap(), + "requested/local-file" + ); + with_last_error(|again| { + let again = again.unwrap(); + assert_eq!(again.code, e.code); + assert_eq!(again.message, e.message); + assert_eq!(again.sql_state, e.sql_state); + assert_eq!(again.query_id, e.query_id); + }); + } }); + error.os_error.as_mut().unwrap().filename = None; + store_error(error); + assert!(unsafe { kernel_get_last_error_os(&mut code, &mut filename) }); + assert_eq!(code, 2); + assert!(filename.is_null()); clear_error(); } From 81c6a9cb13311e612efe2c7ee14c0bccc2d9ce11 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Fri, 13 Nov 2026 01:55:46 +0000 Subject: [PATCH 37/39] fix(napi): preserve filesystem operations and Windows errno Signed-off-by: Aakash Saravanan --- napi/Cargo.lock | 1 + napi/Cargo.toml | 3 + napi/src/error.rs | 142 ++++++++++++++++++---------------------- pyo3/src/errors.rs | 1 + src/c_abi/error.rs | 2 + src/kernel_error.rs | 2 + src/statement/volume.rs | 87 +++++++++++++++++------- 7 files changed, 137 insertions(+), 101 deletions(-) diff --git a/napi/Cargo.lock b/napi/Cargo.lock index 6f896e68..1183feb7 100644 --- a/napi/Cargo.lock +++ b/napi/Cargo.lock @@ -661,6 +661,7 @@ dependencies = [ "chrono", "databricks-sql-kernel", "futures", + "libloading", "napi", "napi-build", "napi-derive", diff --git a/napi/Cargo.toml b/napi/Cargo.toml index d1778963..725c0526 100644 --- a/napi/Cargo.toml +++ b/napi/Cargo.toml @@ -128,6 +128,9 @@ serde_json = "1" # Version kept in lock-step with the kernel's `chrono` dep. chrono = { version = "0.4", default-features = false, features = ["clock"] } +[target.'cfg(windows)'.dependencies] +libloading = "0.9.0" + [dev-dependencies] wiremock = "0.6" diff --git a/napi/src/error.rs b/napi/src/error.rs index ae95ece9..2f06d879 100644 --- a/napi/src/error.rs +++ b/napi/src/error.rs @@ -82,22 +82,9 @@ pub(crate) const ERROR_SENTINEL: &str = "__databricks_error__:"; /// and `cause` are intentionally omitted from the v1 envelope — see /// the module-level doc for rationale. /// -/// **Wire-shape superset of pyo3 for Thrift parity:** the envelope -/// also carries `displayMessage` / `diagnosticInfo` / `errorDetailsJson` -/// — the three SEA extended-status fields that ride on the wire across -/// terminal-error states. These mirror the same-named fields on the -/// NodeJS Thrift driver's `TGetOperationStatusResp`, so JS callers -/// migrating from Thrift to the SEA-backed binding see the same field -/// set on a failed statement. The pyo3 binding does NOT (yet) attach -/// these — pyo3's `attach_attrs` stays at the original 8 fields. -/// -/// The whole JSON-envelope-on-`reason` scheme is interim. The follow-up -/// PR that lands the first `#[napi]` entry points (PR #25) is expected -/// to replace it with typed errors via `Env::create_error` + -/// `set_named_property` (mirroring pyo3's `setattr` approach in -/// `pyo3/src/errors.rs`). The sentinel + envelope vanish once that -/// lands. See `sea-workflow/jira-candidates/2026-05-23-napi-typed-error-refactor.md` -/// for the deferred-spec write-up. +/// Thirteen fields also have Python exception attributes, including the +/// three extended-status fields and raw OS code/filename. The optional +/// `osErrorOperation` and Windows `osErrorNodeErrno` are Node-specific. pub(crate) fn napi_err_from_kernel(e: KernelError) -> NapiError { let status = status_from_kernel_code(e.code); @@ -148,6 +135,13 @@ pub(crate) fn napi_err_from_kernel(e: KernelError) -> NapiError { if let Some(filename) = os_error.filename { obj.insert("osErrorFilename".to_owned(), Value::from(filename)); } + if let Some(operation) = os_error.operation { + obj.insert("osErrorOperation".to_owned(), Value::from(operation)); + } + #[cfg(windows)] + if let Some(errno) = windows_node_errno(os_error.code) { + obj.insert("osErrorNodeErrno".to_owned(), Value::from(errno)); + } } // Thrift-parity extended status fields: surfaced on the napi // envelope so a JS caller's catch-block sees the same fields the @@ -175,6 +169,31 @@ pub(crate) fn napi_err_from_kernel(e: KernelError) -> NapiError { NapiError::new(status, envelope) } +#[cfg(windows)] +fn windows_node_errno(raw: i32) -> Option { + use libloading::os::windows::Library; + + type Translate = unsafe extern "C" fn(i32) -> i32; + // The library keeps the function pointer valid for every subsequent call. + static TRANSLATOR: std::sync::OnceLock> = + std::sync::OnceLock::new(); + + if raw <= 0 { + return None; + } + let (_, translate) = TRANSLATOR + .get_or_init(|| { + let library = Library::this().ok()?; + // SAFETY: the public libuv export uses this C signature; retain its module. + let translate = unsafe { *library.get::(b"uv_translate_sys_error\0").ok()? }; + Some((library, translate)) + }) + .as_ref()?; + // SAFETY: the cached public function and module are valid for this call. + let errno = unsafe { translate(raw) }; + (errno < 0).then_some(errno) +} + /// Map kernel `ErrorCode` → napi `Status`. The status is mostly /// cosmetic on the napi side (the TS layer dispatches on `code` from /// the envelope); we pick the closest match so unwrapped errors still @@ -305,31 +324,8 @@ mod tests { ); } - /// Parity guard: the napi envelope must carry the same kernel - /// `Error` field set that pyo3's typed `KernelError` exposes via - /// `setattr`. The two bindings diverge on *wire mechanism* (typed - /// exception attrs vs JSON envelope) and on *naming convention* - /// (snake_case attrs in pyo3 vs camelCase JSON keys in napi). - /// - /// **Thrift-parity superset.** The napi envelope is a strict - /// superset of pyo3's field set: it adds `displayMessage` / - /// `diagnosticInfo` / `errorDetailsJson` so JS consumers see the - /// same fields the NodeJS Thrift driver's `TGetOperationStatusResp` - /// exposes on terminal-error states. The pyo3 binding may grow - /// these later via a separate `attach_attrs` extension; the two - /// bindings stay in sync on the *pyo3-side 8 fields*, and napi - /// extends from there for its host-language's contract. - /// - /// pyo3 attaches via `attach_attrs(...)` in `pyo3/src/errors.rs:67`: - /// `code, message, sql_state, error_code, vendor_code, http_status, - /// retryable, query_id`. Both bindings intentionally omit `location` - /// (kernel-internal `file:line` for `Internal` errors) and `cause` - /// (recursive — needs an explicit schema decision). - /// - /// Reviewer-flagged at PR #27 / error.rs:76 — see comment text - /// `pyo3 attaches kernel error fields as Python attributes…`. #[test] - fn envelope_field_set_matches_pyo3_setattr_contract() { + fn envelope_encodes_expected_fields() { // Build a kernel error with every optional field populated so // the conditional `if let Some(...)` branches in the encoder // all fire and we exercise the full key set in one shot. @@ -343,9 +339,8 @@ mod tests { e.os_error = Some(Box::new(OsError { code: 13, filename: Some("requested/local-file".to_string()), + operation: Some("stat"), })); - // Thrift-parity extension fields: populated too so the - // superset relation is exercised in the same fixture. e.display_message = Some("Statement failed at operator Scan".to_string()); e.diagnostic_info = Some("operator=Scan; stage=Compile".to_string()); e.error_details_json = Some(r#"{"errorClass":"COMPILE_FAILURE"}"#.to_string()); @@ -363,44 +358,31 @@ mod tests { .as_object() .expect("envelope payload must be a JSON object"); - // pyo3's `attach_attrs` field list, in pyo3's snake_case → - // napi's camelCase. These 8 keys must stay in lockstep across - // bindings — any divergence on these is a parity regression. - let pyo3_parity_keys: &[&str] = &[ - "code", // pyo3: "code" - "message", // pyo3: "message" - "sqlState", // pyo3: "sql_state" - "errorCode", // pyo3: "error_code" - "vendorCode", // pyo3: "vendor_code" - "httpStatus", // pyo3: "http_status" - "retryable", // pyo3: "retryable" - "queryId", // pyo3: "query_id" - ]; - for k in pyo3_parity_keys { - assert!( - obj.contains_key(*k), - "envelope is missing the `{k}` key — pyo3 sets this via \ - setattr, napi binding must keep parity. payload: {payload}" - ); - } - - // Thrift-parity superset: these 3 are napi-only today (pyo3 - // may add them later via attach_attrs). They mirror the - // same-named optional fields on the NodeJS Thrift - // `TGetOperationStatusResp`. - let thrift_parity_keys: &[&str] = &[ - "displayMessage", // Thrift: displayMessage - "diagnosticInfo", // Thrift: diagnosticInfo - "errorDetailsJson", // Thrift: errorDetailsJson + let expected_keys = [ + "code", + "message", + "sqlState", + "errorCode", + "vendorCode", + "httpStatus", + "retryable", + "queryId", + "osErrorCode", + "osErrorFilename", + "displayMessage", + "diagnosticInfo", + "errorDetailsJson", + "osErrorOperation", ]; - for k in thrift_parity_keys { + for k in expected_keys { assert!( - obj.contains_key(*k), - "envelope is missing the Thrift-parity key `{k}`. payload: {payload}" + obj.contains_key(k), + "envelope is missing key `{k}`. payload: {payload}" ); } assert_eq!(obj["osErrorCode"], 13); assert_eq!(obj["osErrorFilename"], "requested/local-file"); + assert_eq!(obj["osErrorOperation"], "stat"); // Intentionally-omitted fields must NOT leak into the wire // shape (the module doc and the kernel `Error` struct both @@ -417,13 +399,10 @@ mod tests { // No surprise keys: the wire shape stays the documented set. // Exact-size check (not subset) catches accidental additions. - let expected_total = pyo3_parity_keys.len() + thrift_parity_keys.len() + 2; assert_eq!( obj.len(), - expected_total, - "envelope has unexpected extra keys. expected pyo3 parity \ - {pyo3_parity_keys:?} + thrift parity {thrift_parity_keys:?} + OS details, \ - got: {:?}", + expected_keys.len(), + "envelope has unexpected extra keys. expected {expected_keys:?}, got: {:?}", obj.keys().collect::>() ); } @@ -497,6 +476,8 @@ mod tests { "queryId", "osErrorCode", "osErrorFilename", + "osErrorOperation", + "osErrorNodeErrno", // Thrift-parity extension fields also follow the // omit-when-None convention. "displayMessage", @@ -516,12 +497,15 @@ mod tests { e.os_error = Some(Box::new(OsError { code: -2, filename: None, + operation: None, })); let napi_err = napi_err_from_kernel(e); let payload = &napi_err.reason.to_string()[ERROR_SENTINEL.len()..]; let v: serde_json::Value = serde_json::from_str(payload).unwrap(); assert_eq!(v["osErrorCode"], -2); assert!(!v.as_object().unwrap().contains_key("osErrorFilename")); + assert!(!v.as_object().unwrap().contains_key("osErrorOperation")); + assert!(!v.as_object().unwrap().contains_key("osErrorNodeErrno")); } #[test] diff --git a/pyo3/src/errors.rs b/pyo3/src/errors.rs index 24db8807..74b8425f 100644 --- a/pyo3/src/errors.rs +++ b/pyo3/src/errors.rs @@ -212,6 +212,7 @@ mod tests { Box::new(OsError { code, filename: Some("local-file.bin".to_owned()), + operation: None, }) }); let mapped = to_py_err(py, error); diff --git a/src/c_abi/error.rs b/src/c_abi/error.rs index 1e0718bb..7ddbc596 100644 --- a/src/c_abi/error.rs +++ b/src/c_abi/error.rs @@ -247,6 +247,7 @@ mod tests { error.os_error = Some(Box::new(crate::kernel_error::OsError { code: 2, filename: Some("local-file".into()), + operation: None, })); store_error(error.clone()); clear_error(); @@ -277,6 +278,7 @@ mod tests { error.os_error = Some(Box::new(crate::kernel_error::OsError { code: 2, filename: Some("requested/local-file".into()), + operation: None, })); store_error(error.clone()); let mut code = -1; diff --git a/src/kernel_error.rs b/src/kernel_error.rs index 81e1a6bb..a71d46e9 100644 --- a/src/kernel_error.rs +++ b/src/kernel_error.rs @@ -165,6 +165,8 @@ pub struct OsError { pub code: i32, /// Requested local path for a file-transfer OS error. pub filename: Option, + /// Logical filesystem operation when the failing API identifies it. + pub operation: Option<&'static str>, } /// Typed kernel error. diff --git a/src/statement/volume.rs b/src/statement/volume.rs index 053e1ece..68cf9bee 100644 --- a/src/statement/volume.rs +++ b/src/statement/volume.rs @@ -227,7 +227,7 @@ fn instruction_headers(batch: &RecordBatch) -> Result> { } } -fn file_error(error: std::io::Error) -> Error { +fn file_error(operation: Option<&'static str>, error: std::io::Error) -> Error { let permission_denied = error.kind() == std::io::ErrorKind::PermissionDenied; let mut mapped = Error::new( match error.kind() { @@ -244,6 +244,7 @@ fn file_error(error: std::io::Error) -> Error { Box::new(OsError { code, filename: None, + operation, }) }); if permission_denied { @@ -257,21 +258,24 @@ fn resolved_path(path: &Path) -> Result { match path.canonicalize() { Ok(path) => Ok(path), Err(error) if error.kind() == std::io::ErrorKind::NotFound => { - let absolute = std::path::absolute(path).map_err(file_error)?; + let absolute = std::path::absolute(path).map_err(|error| file_error(None, error))?; let parent = absolute .parent() .ok_or_else(|| Error::invalid_argument().message("Invalid local file path"))?; let name = absolute .file_name() .ok_or_else(|| Error::invalid_argument().message("Invalid local file path"))?; - Ok(parent.canonicalize().map_err(file_error)?.join(name)) + Ok(parent + .canonicalize() + .map_err(|error| file_error(Some("realpath"), error))? + .join(name)) } - Err(error) => Err(file_error(error)), + Err(error) => Err(file_error(Some("realpath"), error)), } } fn missing_path_for_policy(path: &Path) -> Result { - let absolute = std::path::absolute(path).map_err(file_error)?; + let absolute = std::path::absolute(path).map_err(|error| file_error(None, error))?; for ancestor in absolute.ancestors().skip(1) { if let Ok(mut resolved) = ancestor.canonicalize() { let suffix = absolute.strip_prefix(ancestor).unwrap(); @@ -420,10 +424,10 @@ async fn transfer( std::fs::OpenOptions::new() .write(true) .open(&destination) - .map_err(file_error)?; + .map_err(|error| file_error(Some("open"), error))?; } Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} - Err(error) => return Err(file_error(error)), + Err(error) => return Err(file_error(Some("stat"), error)), } } Ok(destination) @@ -461,14 +465,20 @@ async fn transfer( Err(error) if error.kind() == std::io::ErrorKind::NotFound => { std::fs::Permissions::from_mode(0o666) } - Err(error) => return Err(file_error(error)), + Err(error) => return Err(file_error(Some("stat"), error)), }; builder.permissions(permissions); builder }; - let temporary = builder.tempfile_in(parent).map_err(file_error)?; - let file = - tokio::fs::File::from_std(temporary.as_file().try_clone().map_err(file_error)?); + let temporary = builder + .tempfile_in(parent) + .map_err(|error| file_error(Some("open"), error))?; + let file = tokio::fs::File::from_std( + temporary + .as_file() + .try_clone() + .map_err(|error| file_error(None, error))?, + ); Ok((temporary, file)) })(); log.finish("temp_create", started, temporary.as_ref().err()); @@ -478,7 +488,9 @@ async fn transfer( let mut body = response.bytes_stream(); while let Some(bytes) = body.next().await { let bytes = bytes.map_err(transport_error)?; - file.write_all(&bytes).await.map_err(file_error)?; + file.write_all(&bytes) + .await + .map_err(|error| file_error(Some("write"), error))?; } Ok(()) } @@ -486,7 +498,10 @@ async fn transfer( log.finish("body_write", started, body.as_ref().err()); body?; let started = log.start("body_flush"); - let flushed = file.flush().await.map_err(file_error); + let flushed = file + .flush() + .await + .map_err(|error| file_error(Some("write"), error)); log.finish("body_flush", started, flushed.as_ref().err()); flushed?; drop(file); @@ -496,13 +511,15 @@ async fn transfer( Ok(metadata) => temporary .as_file() .set_permissions(metadata.permissions()) - .map_err(file_error)?, + .map_err(|error| file_error(Some("fchmod"), error))?, Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} - Err(error) => return Err(file_error(error)), + Err(error) => return Err(file_error(Some("stat"), error)), } + // Windows persist can fail before replacement without identifying the operation. + let operation = cfg!(unix).then_some("rename"); temporary .persist(destination) - .map_err(|error| file_error(error.error))?; + .map_err(|error| file_error(operation, error.error))?; Ok(()) })(); log.finish("commit", started, committed.as_ref().err()); @@ -638,7 +655,7 @@ async fn send_transfer( let opened = async { if !tokio::fs::metadata(local) .await - .map_err(file_error)? + .map_err(|error| file_error(Some("stat"), error))? .is_file() { return Err( @@ -646,8 +663,13 @@ async fn send_transfer( ); } // Each retry reopens the file so a streaming upload starts at byte zero. - let file = tokio::fs::File::open(local).await.map_err(file_error)?; - let metadata = file.metadata().await.map_err(file_error)?; + let file = tokio::fs::File::open(local) + .await + .map_err(|error| file_error(Some("open"), error))?; + let metadata = file + .metadata() + .await + .map_err(|error| file_error(Some("fstat"), error))?; if !metadata.is_file() { return Err( Error::invalid_argument().message("Local upload path must be a file") @@ -949,7 +971,7 @@ mod tests { (ErrorKind::TimedOut, ErrorCode::Timeout), (ErrorKind::Other, ErrorCode::Internal), ] { - let error = file_error(std::io::Error::from(kind)); + let error = file_error(Some("stat"), std::io::Error::from(kind)); assert_eq!(error.code, code); assert!(!error.retryable); assert!(error.os_error.is_none()); @@ -958,8 +980,10 @@ mod tests { (kind == ErrorKind::PermissionDenied).then_some("FILE_TRANSFER_PERMISSION_ERROR") ); } - let error = file_error(std::io::Error::from_raw_os_error(13)); - assert_eq!(error.os_error.as_ref().map(|e| e.code), Some(13)); + let error = file_error(None, std::io::Error::from_raw_os_error(13)); + let os_error = error.os_error.as_ref().unwrap(); + assert_eq!(os_error.code, 13); + assert_eq!(os_error.operation, None); } #[tokio::test] @@ -988,8 +1012,27 @@ mod tests { let os_error = error.os_error.as_ref().unwrap(); assert_eq!(Some(os_error.code), expected_code); assert_eq!(os_error.filename.as_deref(), local.to_str()); + assert_eq!(os_error.operation, Some("realpath")); assert_eq!(error.error_code.as_deref(), Some("FILE_TRANSFER_ERROR")); } + let missing_leaf = dir.path().join("missing"); + let expected_code = std::fs::metadata(&missing_leaf).unwrap_err().raw_os_error(); + let batch = instruction("PUT", &server.uri(), missing_leaf.to_str().unwrap()); + let error = complete( + &client(), + result(batch, true), + &options, + &VolumeCompletion::default(), + ) + .await + .err() + .unwrap(); + assert_eq!(error.code, ErrorCode::NotFound); + let os_error = error.os_error.as_ref().unwrap(); + assert_eq!(Some(os_error.code), expected_code); + assert_eq!(os_error.filename.as_deref(), missing_leaf.to_str()); + assert_eq!(os_error.operation, Some("stat")); + assert_eq!(error.error_code.as_deref(), Some("FILE_TRANSFER_ERROR")); assert!(server.received_requests().await.unwrap().is_empty()); } From 96f629990d3553fac4cbe6df9016bed884206725 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Fri, 13 Nov 2026 03:58:15 +0000 Subject: [PATCH 38/39] perf(statement): reuse successful async terminal responses Consume a handle's observed successful response once when constructing its reader, and materialise terminal polls without another status request. Clear saved responses at fresh observations and owner release, including late replies, while retaining existing metadata and lifecycle behavior. Signed-off-by: Aakash Saravanan --- src/client/sea.rs | 11 +- src/client/transport.rs | 14 +- src/reader/cloudfetch/link_fetcher.rs | 6 +- src/reader/mod.rs | 4 +- src/session.rs | 4 +- src/statement/executed_async.rs | 121 +++++++++++----- tests/v0_async_execute_wiremock.rs | 199 +++++++++++++++++++++++--- 7 files changed, 278 insertions(+), 81 deletions(-) diff --git a/src/client/sea.rs b/src/client/sea.rs index 7003150f..b94f6d23 100644 --- a/src/client/sea.rs +++ b/src/client/sea.rs @@ -102,7 +102,7 @@ struct ExecutionRequest { /// /// Used by the shared decoder [`SeaRestTransport::terminal_outcome`] /// so the sync polling loop and the async one-shot -/// [`Transport::fetch_completed_result`] path produce identical +/// [`Transport::completed_result`] materialisation produce identical /// outcomes (and identical errors) for `FAILED` / `CANCELLED` responses. enum StatementOutcome { /// Terminal success — `Succeeded` OR `Closed` (with or without inline @@ -499,7 +499,7 @@ impl SeaRestTransport { /// Decode a single SEA `ExecuteResponse` into a terminal outcome. /// /// Shared by synchronous execution after it observes a raw terminal state and - /// [`Transport::fetch_completed_result`] (async one-shot fetch), so both paths + /// [`Transport::completed_result`] (async materialisation), so both paths /// produce identical errors for `FAILED` / `CANCELLED`. /// `CLOSED` (with or without result data) is a terminal success — JDBC /// parity; an empty `CLOSED` materialises an empty result downstream. @@ -1370,14 +1370,11 @@ impl Transport for SeaRestTransport { } } - async fn fetch_completed_result( + async fn completed_result( &self, - statement_id: &str, + response: ExecuteResponse, session_attribution: SessionAttribution, ) -> Result> { - let response = self - .get_statement_status(statement_id, session_attribution) - .await?; match Self::terminal_outcome(response) { StatementOutcome::Done(r) => { let reader_factory = self.reader_factory()?; diff --git a/src/client/transport.rs b/src/client/transport.rs index 90f91a75..019d675c 100644 --- a/src/client/transport.rs +++ b/src/client/transport.rs @@ -325,7 +325,7 @@ pub(crate) trait Transport: Send + Sync + std::fmt::Debug { /// `ExecutedAsyncStatement` immediately. Unlike /// [`Transport::execute_statement`], this never polls and never /// constructs a reader; callers fetch results later via - /// [`Transport::fetch_completed_result`]. + /// [`Transport::completed_result`]. /// /// **The implementation forces `params.wait_timeout = "0s"`** /// regardless of what the caller supplied — submit's contract @@ -339,8 +339,7 @@ pub(crate) trait Transport: Send + Sync + std::fmt::Debug { params: &ExecuteParams, ) -> Result; - /// Refresh status for an already-submitted statement and, if - /// terminal-and-succeeded, materialise the reader. + /// Materialise a reader from an observed terminal response. /// /// Returns: /// - `Ok(Some(ExecuteResult))` when the server reports @@ -348,22 +347,21 @@ pub(crate) trait Transport: Send + Sync + std::fmt::Debug { /// server emits for one-batch results). /// - `Ok(None)` when the server reports `Pending` / `Running` — /// the caller should `status()` again later. - /// - `Err(...)` on `Failed` / `Cancelled` / true `Closed`-without-data - /// with the same structured error + /// - `Err(...)` on `Failed` / `Cancelled` with the same structured error /// `Transport::execute_statement`'s polling path produces. /// /// Used by `ExecutedAsyncStatement::fetch_result` and inside the /// `await_result` poll loop. - async fn fetch_completed_result( + async fn completed_result( &self, - statement_id: &str, + response: ExecuteResponse, session_attribution: SessionAttribution, ) -> Result>; /// One-shot status check for an in-flight statement. Returns the /// full `ExecuteResponse` (status + manifest + initial result, if /// any). Used by `ExecutedAsyncStatement::status` and the - /// `await_result` poll loop. + /// `await_result` poll loop, and `fetch_result`. async fn statement_status( &self, statement_id: &str, diff --git a/src/reader/cloudfetch/link_fetcher.rs b/src/reader/cloudfetch/link_fetcher.rs index c0fcf8ac..8bbcdb6a 100644 --- a/src/reader/cloudfetch/link_fetcher.rs +++ b/src/reader/cloudfetch/link_fetcher.rs @@ -1197,12 +1197,12 @@ mod tests { unimplemented!("execute_statement_direct not used by the link-fetcher mock") } - async fn fetch_completed_result( + async fn completed_result( &self, - _statement_id: &str, + _response: crate::client::ExecuteResponse, _session_attribution: crate::client::SessionAttribution, ) -> Result> { - unimplemented!("fetch_completed_result not used by the link-fetcher mock") + unimplemented!("completed_result not used by the link-fetcher mock") } async fn statement_status( diff --git a/src/reader/mod.rs b/src/reader/mod.rs index dd8023c3..33e7816d 100644 --- a/src/reader/mod.rs +++ b/src/reader/mod.rs @@ -1975,9 +1975,9 @@ mod tests { ) -> Result { unreachable!() } - async fn fetch_completed_result( + async fn completed_result( &self, - _: &str, + _: ExecuteResponse, _: crate::client::SessionAttribution, ) -> Result> { unreachable!() diff --git a/src/session.rs b/src/session.rs index ccb3fd0d..b77305af 100644 --- a/src/session.rs +++ b/src/session.rs @@ -3049,8 +3049,8 @@ mod is_open_tests { ); assert_eq!( detail["n_operation_status_calls"].as_i64(), - Some(2), - "only owning status and await polls contribute to execution telemetry" + Some(1), + "only the owning status request contributes; await consumes its response" ); assert!( detail["operation_status_latency_millis"] diff --git a/src/statement/executed_async.rs b/src/statement/executed_async.rs index 0fc9f09a..3c91947c 100644 --- a/src/statement/executed_async.rs +++ b/src/statement/executed_async.rs @@ -221,6 +221,8 @@ pub struct ExecutedAsyncStatement { /// don't `.await` and the poll loop releases the lock before /// every network round-trip. latest_status: Arc>, + /// Take-once ownership avoids retaining raw payloads after reader construction. + pending_result: std::sync::Mutex>, statement_telemetry: StatementTelemetry, /// Set once result materialisation hands success finalization to /// the returned `ResultStream`. @@ -279,6 +281,7 @@ impl ExecutedAsyncStatement { /// caller-driven status polls expires. pub(crate) fn expire_client_query_timeout(&self) -> Error { self.owner_released.store(true, Ordering::Release); + self.clear_pending_result(); if !self.client_timeout_expired.swap(true, Ordering::AcqRel) { self.session .dispatch_timeout_cleanup(Some(self.statement_id.clone())); @@ -331,6 +334,7 @@ impl ExecutedAsyncStatement { owning: true, session_attribution: SessionAttribution::Current, latest_status: Arc::new(std::sync::Mutex::new(initial_status)), + pending_result: std::sync::Mutex::new(None), statement_telemetry, result_stream_owns_success_telemetry: AtomicBool::new(false), client_deadline, @@ -390,6 +394,7 @@ impl ExecutedAsyncStatement { owning: false, session_attribution, latest_status: Arc::new(std::sync::Mutex::new(initial_status)), + pending_result: std::sync::Mutex::new(None), statement_telemetry: StatementTelemetry::noop(), result_stream_owns_success_telemetry: AtomicBool::new(false), client_deadline: None, @@ -514,18 +519,45 @@ impl ExecutedAsyncStatement { .and_then(|s| s.error_details_json.clone()) } - /// Internal helper — overwrite the cached `StatementStatus` with - /// a fresh poll's response. Called by `status()` / - /// `await_result()` after every successful - /// `statement_status` RPC. Lock poisoning is intentionally - /// swallowed: a poisoned lock here would only happen if a panic + /// Publish observed metadata together with an optional response for reuse. + /// Lock poisoning is intentionally swallowed: a poisoned lock here + /// would only happen if a panic /// landed mid-write, and the recovery path is to keep the prior /// status visible (worse: a fresh poll's status lost; better: /// the handle's accessor surface keeps working). - fn record_latest_status(&self, fresh: crate::types::sea::StatementStatus) { + fn record_latest_status( + &self, + fresh: crate::types::sea::StatementStatus, + response: Option, + ) { + // Payload before metadata keeps concurrent publications from mixing observations. + let pending = self.pending_result.lock().ok(); if let Ok(mut guard) = self.latest_status.lock() { *guard = fresh; } + if let Some(mut pending) = pending { + *pending = response.filter(|response| { + matches!( + response.status.state, + StatementState::Succeeded | StatementState::Closed + ) && !self.owner_released.load(Ordering::Acquire) + }); + } + } + + fn clear_pending_result(&self) { + if let Ok(mut pending) = self.pending_result.lock() { + *pending = None; + } + } + + fn take_pending_result(&self) -> Option { + let mut pending = self.pending_result.lock().ok()?; + if self.owner_released.load(Ordering::Acquire) { + *pending = None; + return None; + } + pending.take() } fn cancelled_error(&self, status: &crate::types::sea::StatementStatus) -> Error { @@ -567,6 +599,7 @@ impl ExecutedAsyncStatement { let span = self.session.log_span().clone(); let result = async { self.check_read_validity()?; + self.clear_pending_result(); // The client deadline governs only the pre-terminal window // ("initial submit through observed terminal status"). Once // this handle has observed a terminal state, `status()` @@ -608,10 +641,6 @@ impl ExecutedAsyncStatement { self.check_read_validity()?; self.statement_telemetry .record_poll(status_started.elapsed()); - // Cache the wire status so the extended-field accessors - // reflect what THIS handle has observed (instead of the - // stale initial-submit snapshot). - self.record_latest_status(response.status.clone()); // Latch the terminal observation so subsequent `status()` // calls stop enforcing the client deadline against this // already-finished statement. @@ -625,6 +654,7 @@ impl ExecutedAsyncStatement { .client_deadline .is_some_and(|deadline| std::time::Instant::now() >= deadline) { + self.record_latest_status(response.status.clone(), None); return Err(self.expire_client_query_timeout()); } match &status { @@ -640,11 +670,13 @@ impl ExecutedAsyncStatement { | StatementStatus::Succeeded | StatementStatus::Closed => {} } + self.record_latest_status(response.status.clone(), Some(response)); Ok(status) } .instrument(span) .await; if let Err(error) = &result { + self.clear_pending_result(); self.statement_telemetry.finalize(Some(error)); } result @@ -671,6 +703,9 @@ impl ExecutedAsyncStatement { let span = self.session.log_span().clone(); let result = async { self.check_read_validity()?; + if let Some(response) = self.take_pending_result() { + return self.materialise_result(response).await; + } let cfg = self.session.transport().poll_config(); let start = std::time::Instant::now(); @@ -753,7 +788,7 @@ impl ExecutedAsyncStatement { // Cache the wire status so the extended-field // accessors reflect THIS poll's observation — not the // initial-submit snapshot that's now stale by minutes. - self.record_latest_status(response.status.clone()); + self.record_latest_status(response.status.clone(), None); // Latch the terminal observation so a later `status()` // call stops enforcing the client deadline against this // already-finished statement. @@ -765,7 +800,7 @@ impl ExecutedAsyncStatement { if let Some(g) = cancel_guard.take() { g.defuse(); } - return self.materialise_result().await; + return self.materialise_result(response).await; } StatementStatus::Failed(e) => { // Server already decided this is terminal — no @@ -822,6 +857,7 @@ impl ExecutedAsyncStatement { .instrument(span) .await; if let Err(error) = &result { + self.clear_pending_result(); self.statement_telemetry.finalize(Some(error)); } result @@ -835,8 +871,28 @@ impl ExecutedAsyncStatement { /// when the caller has already confirmed completion themselves. pub async fn fetch_result(&self) -> Result { let span = self.session.log_span().clone(); - let result = self.materialise_result().instrument(span).await; + let result = async { + self.check_read_validity()?; + let response = match self.take_pending_result() { + Some(response) => response, + None => { + self.clear_pending_result(); + let response = self + .session + .transport() + .statement_status(&self.statement_id, self.session_attribution) + .await?; + self.check_read_validity()?; + self.clear_pending_result(); + response + } + }; + self.materialise_result(response).await + } + .instrument(span) + .await; if let Err(error) = &result { + self.clear_pending_result(); self.statement_telemetry.finalize(Some(error)); } result @@ -847,12 +903,17 @@ impl ExecutedAsyncStatement { /// statement is still running. The error includes the observed /// status so callers don't have to re-query, and points at the /// actionable follow-up. - async fn materialise_result(&self) -> Result { + async fn materialise_result(&self, response: ExecuteResponse) -> Result { self.check_read_validity()?; + let observed = match response.status.state { + StatementState::Pending => "Pending", + StatementState::Running => "Running", + _ => "non-terminal", + }; let result = self .session .transport() - .fetch_completed_result(&self.statement_id, self.session_attribution) + .completed_result(response, self.session_attribution) .await?; self.check_read_validity()?; match result { @@ -894,32 +955,12 @@ impl ExecutedAsyncStatement { .store(true, Ordering::Release); Ok(stream) } - None => { - // Re-read the status so the error message names the - // observed state (Pending vs Running). Best-effort — - // if the status call itself fails, fall back to the - // generic non-terminal message. - let observed = match self - .session - .transport() - .statement_status(&self.statement_id, self.session_attribution) - .await - { - Ok(r) => match r.status.state { - crate::types::sea::StatementState::Pending => "Pending", - crate::types::sea::StatementState::Running => "Running", - _ => "non-terminal", - }, - Err(_) => "non-terminal", - }; - self.check_read_validity()?; - Err(Error::invalid_state().message(format!( - "Statement {} is not terminal yet (status: {}); call await_result() to \ + None => Err(Error::invalid_state().message(format!( + "Statement {} is not terminal yet (status: {}); call await_result() to \ block until done, or poll status() and re-call fetch_result() once it \ reports Succeeded / Closed", - self.statement_id, observed - ))) - } + self.statement_id, observed + ))), } } } @@ -1071,6 +1112,7 @@ impl ExecutedAsyncStatement { async fn close_server_statement(&self) -> Result<()> { if self.owning { self.owner_released.store(true, Ordering::Release); + self.clear_pending_result(); } // Idempotent on success: a prior successful close sets // `closed=true` and subsequent calls short-circuit. @@ -1196,6 +1238,7 @@ impl Drop for ExecutedAsyncStatement { fn drop(&mut self) { if self.owning { self.owner_released.store(true, Ordering::Release); + self.clear_pending_result(); } // Ensure submit-and-drop / status-only async statements still // emit one terminal telemetry event. Once a result stream has diff --git a/tests/v0_async_execute_wiremock.rs b/tests/v0_async_execute_wiremock.rs index 789a862f..b6169719 100644 --- a/tests/v0_async_execute_wiremock.rs +++ b/tests/v0_async_execute_wiremock.rs @@ -484,6 +484,18 @@ async fn await_result_polls_until_succeeded() { .value(0), 42 ); + let requests = server.received_requests().await.unwrap(); + assert_eq!( + requests + .iter() + .filter(|request| { + request.method.as_str() == "GET" + && request.url.path() == "/api/2.0/sql/statements/stmt-poll" + }) + .count(), + 2, + "materialisation must use the final poll response" + ); } #[tokio::test] @@ -1243,7 +1255,7 @@ async fn async_status_call_refreshes_cached_status() { // A status() poll returns SUCCEEDED with extended fields. The // status() call itself must overwrite the cached snapshot. - let batch = int64_batch("n", vec![1]); + let batch = int64_batch("n", vec![11, 22]); mount_status_sequence( &server, "stmt-async-refresh", @@ -1252,8 +1264,8 @@ async fn async_status_call_refreshes_cached_status() { &batch, Some(99), Some("Refreshed via status()"), - None, - None, + Some("operator=Update"), + Some(r#"{"detail":"refreshed"}"#), )], ) .await; @@ -1283,6 +1295,62 @@ async fn async_status_call_refreshes_cached_status() { async_exec.display_message().as_deref(), Some("Refreshed via status()") ); + assert_eq!( + async_exec.diagnostic_info().as_deref(), + Some("operator=Update") + ); + assert_eq!( + async_exec.error_details_json().as_deref(), + Some(r#"{"detail":"refreshed"}"#) + ); + + let mut stream = async_exec.await_result().await.expect("await_result"); + let schema = stream.schema(); + assert_eq!(schema.fields().len(), 1); + assert_eq!(schema.field(0).name(), "n"); + assert_eq!(schema.field(0).data_type(), &DataType::Int64); + assert_eq!( + schema.field(0).is_nullable(), + batch.schema().field(0).is_nullable() + ); + let batches = drain(&mut stream).await; + assert_eq!(batches.len(), 1); + assert_eq!(batches[0].num_rows(), 2); + assert_eq!( + batches[0] + .column(0) + .as_primitive::() + .values() + .as_ref(), + &[11_i64, 22] + ); + assert_eq!(async_exec.num_modified_rows(), Some(99)); + assert_eq!( + async_exec.display_message().as_deref(), + Some("Refreshed via status()") + ); + assert_eq!( + async_exec.diagnostic_info().as_deref(), + Some("operator=Update") + ); + assert_eq!( + async_exec.error_details_json().as_deref(), + Some(r#"{"detail":"refreshed"}"#) + ); + let status_requests = server + .received_requests() + .await + .unwrap() + .into_iter() + .filter(|request| { + request.method.as_str() == "GET" + && request.url.path() == "/api/2.0/sql/statements/stmt-async-refresh" + }) + .count(); + assert_eq!( + status_requests, 1, + "owner await must consume its observed response" + ); async_exec.close().await.expect("close"); } @@ -1481,7 +1549,7 @@ async fn async_readers_preserve_session_routes() { Mock::given(method("GET")) .and(path(format!("{session_prefix}/statements/stmt-result"))) .respond_with(ResponseTemplate::new(200).set_body_json(&response)) - .expect(7) + .expect(4) .mount(&server) .await; let chunk_mock = Mock::given(method("GET")).and(path(format!( @@ -1807,7 +1875,7 @@ async fn attached_statement_inline_reads_use_standard_urls() { Mock::given(method("GET")) .and(path("/api/2.0/sql/statements/stmt-attach")) .respond_with(ResponseTemplate::new(200).set_body_json(status)) - .expect(3) + .expect(2) .mount(&server) .await; Mock::given(method("GET")) @@ -2165,8 +2233,8 @@ async fn await_result_closed_status_skips_close_statement() { let batch = int64_batch("n", vec![7]); mount_submit(&server, pending_body("stmt-async-closed")).await; - // await_result polls RUNNING → CLOSED (with inline results). The final - // CLOSED body is also served to materialise_result's own status GET. + // await_result polls RUNNING → CLOSED with inline results. An independent + // reader can still fetch the same CLOSED result. mount_status_sequence( &server, "stmt-async-closed", @@ -2231,16 +2299,23 @@ async fn await_result_succeeded_status_still_closes_statement() { mount_delete_session(&server).await; let batch = int64_batch("n", vec![7]); - mount_submit(&server, pending_body("stmt-async-succ")).await; - mount_status_sequence( - &server, - "stmt-async-succ", - vec![ - running_body("stmt-async-succ"), - succeeded_inline_body("stmt-async-succ", &batch), - ], - ) - .await; + let submit = Mock::given(method("POST")) + .and(path("/api/2.0/sql/statements")) + .respond_with(ResponseTemplate::new(200).set_body_string(pending_body("stmt-async-succ"))) + .expect(1) + .mount_as_scoped(&server) + .await; + Mock::given(method("GET")) + .and(path("/api/2.0/sql/statements/stmt-async-succ")) + .respond_with( + ResponseTemplate::new(200) + .set_body_string(succeeded_inline_body("stmt-async-succ", &batch)), + ) + .up_to_n_times(1) + .expect(1) + .mount(&server) + .await; + mount_status_not_found(&server, "stmt-async-succ").await; // Scoped expectation: exactly one DELETE on the statement endpoint. let _close = Mock::given(method("DELETE")) @@ -2255,10 +2330,18 @@ async fn await_result_succeeded_status_still_closes_statement() { let mut stmt = session.statement(); stmt.spec().sql("SELECT 7 AS n"); let async_exec = stmt.submit().await.expect("submit"); - let mut stream = async_exec.await_result().await.expect("await_result"); - let _ = drain(&mut stream).await; + assert!(matches!( + async_exec.status().await.unwrap(), + StatementStatus::Succeeded + )); async_exec.close().await.expect("close"); - // async_exec drops here — the close guard must fire the DELETE. + let error = async_exec + .await_result() + .await + .err() + .expect("fresh status after close"); + assert_eq!(error.code, ErrorCode::NotFound); + // Drop must not repeat the explicit close. } let closes = wait_for_close_delete( @@ -2273,4 +2356,80 @@ async fn await_result_succeeded_status_still_closes_statement() { "SUCCEEDED status must trigger exactly one CloseStatement" ); // `_close` also verifies expect(1) when it drops at end of scope. + assert_eq!( + server + .received_requests() + .await + .unwrap() + .iter() + .filter(|request| { + request.method.as_str() == "GET" + && request.url.path() == "/api/2.0/sql/statements/stmt-async-succ" + }) + .count(), + 2 + ); + drop(submit); + + // A status reply arriving after owner release must not backfill reusable rows. + let started = Arc::new(tokio::sync::Notify::new()); + let notify = Arc::clone(&started); + let late_body = succeeded_inline_body("stmt-late-status", &batch); + mount_submit(&server, pending_body("stmt-late-status")).await; + Mock::given(method("GET")) + .and(path("/api/2.0/sql/statements/stmt-late-status")) + .respond_with(move |_: &wiremock::Request| { + notify.notify_one(); + ResponseTemplate::new(200) + .set_body_string(late_body.clone()) + .set_delay(std::time::Duration::from_secs(1)) + }) + .up_to_n_times(1) + .expect(1) + .mount(&server) + .await; + mount_status_not_found(&server, "stmt-late-status").await; + Mock::given(method("DELETE")) + .and(path("/api/2.0/sql/statements/stmt-late-status")) + .respond_with(ResponseTemplate::new(200)) + .expect(1) + .mount(&server) + .await; + let mut late_statement = session.statement(); + late_statement.spec().sql("SELECT 7 AS n"); + let late = late_statement.submit().await.unwrap(); + tokio::time::timeout(std::time::Duration::from_secs(3), async { + let status = late.status(); + tokio::pin!(status); + tokio::select! { + result = &mut status => panic!("status completed before request notification: {result:?}"), + _ = started.notified() => {} + } + ExecutedStatementHandle::close(&late).await.unwrap(); + assert!(futures::poll!(&mut status).is_pending(), "status must complete after close returns"); + assert!(matches!(status.await.unwrap(), StatementStatus::Succeeded)); + let error = late.await_result().await.err().expect("late reply must not survive close"); + assert_eq!(error.code, ErrorCode::NotFound); + }).await.expect("bounded late status reply"); + let requests = server.received_requests().await.unwrap(); + assert_eq!( + requests + .iter() + .filter(|request| { + request.method.as_str() == "GET" + && request.url.path() == "/api/2.0/sql/statements/stmt-late-status" + }) + .count(), + 2 + ); + assert_eq!( + requests + .iter() + .filter(|request| { + request.method.as_str() == "DELETE" + && request.url.path() == "/api/2.0/sql/statements/stmt-late-status" + }) + .count(), + 1 + ); } From 04a4b7309b8e0e703ff5e6322889abfe03cda394 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Fri, 13 Nov 2026 05:51:50 +0000 Subject: [PATCH 39/39] fix(async): document terminal payload retention and correct test counts Signed-off-by: Aakash Saravanan --- pyo3/tests/test_async.py | 2 +- src/statement/executed_async.rs | 5 +++++ tests/v0_async_execute_wiremock.rs | 8 +++----- 3 files changed, 9 insertions(+), 6 deletions(-) diff --git a/pyo3/tests/test_async.py b/pyo3/tests/test_async.py index e8c11f06..fa104989 100644 --- a/pyo3/tests/test_async.py +++ b/pyo3/tests/test_async.py @@ -235,7 +235,7 @@ def log_message(self, *_args): assert (state, failure) == ("Succeeded", None) streams = [reader.await_result(), reader.fetch_result()] assert all(isinstance(stream, k.ResultStream) for stream in streams) - expected_reads = 4 if failed else 5 + expected_reads = 4 if failed else 3 assert [path for method, path in requests if method == "GET"] == [statement_path] * expected_reads owner.close() with pytest.raises(k.KernelError) as error: diff --git a/src/statement/executed_async.rs b/src/statement/executed_async.rs index 3c91947c..e16dd2ff 100644 --- a/src/statement/executed_async.rs +++ b/src/statement/executed_async.rs @@ -595,6 +595,11 @@ impl ExecutedAsyncStatement { /// GetStatementStatus RPC. Returns `Err(InvalidStatementHandle)` /// locally — without hitting the wire — if the parent `Statement` /// has already invalidated this handle. + /// + /// A successful terminal check keeps one complete response, including any + /// inline rows, on this handle for its next result read. Status-only callers + /// should close or drop owning handles when finished, and drop independent + /// readers or attached handles to release their saved payload. pub async fn status(&self) -> Result { let span = self.session.log_span().clone(); let result = async { diff --git a/tests/v0_async_execute_wiremock.rs b/tests/v0_async_execute_wiremock.rs index b6169719..d8ed9400 100644 --- a/tests/v0_async_execute_wiremock.rs +++ b/tests/v0_async_execute_wiremock.rs @@ -2288,12 +2288,10 @@ async fn await_result_closed_status_skips_close_statement() { // `_no_close` also verifies expect(0) when it drops at end of scope. } -/// Regression-guard for the async CLOSED-skip fix: a SUCCEEDED async -/// result must STILL fire exactly one `CloseStatement` on close/drop — -/// the server still owns the statement. Guards against over-correcting -/// the CLOSED-skip into a server-statement leak. +/// A Succeeded statement still receives exactly one CloseStatement on owner close, +/// and close discards both a saved terminal response and a later status reply. #[tokio::test] -async fn await_result_succeeded_status_still_closes_statement() { +async fn owner_close_discards_cached_and_late_terminal_responses() { let server = MockServer::start().await; mount_create_session(&server).await; mount_delete_session(&server).await;