From 83367e2d58c7e997e6d8aa88085aff881d79eb2f Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Thu, 3 Dec 2026 02:03:42 +0000 Subject: [PATCH 1/9] feat(volume): expose Volume options through the C ABI, ADBC, NAPI and PyO3 Each binding sets StatementSpec::volume before executing, so a Volume PUT, GET or REMOVE runs its file transfer inside the execution, and the binding's existing cancel and close paths stop it. - C ABI: kernel_statement_set_volume_options, the is_volume_operation flags on executed statements and result streams, and the last-error code, OS error and local path accessors. - PyO3: Statement.set_volume_options with optional upload bytes taken without copying, is_volume_operation, and local error attributes on KernelError. - NAPI: ExecuteOptions.volume, isVolumeOperation and local error fields; socketTimeoutMs 0 keeps the kernel default, and AsyncStatement.close() cancels a call that still holds the statement. - ADBC: the staging_allowed_local_paths statement option; execute_update on a Volume statement without it fails with InvalidState. Co-authored-by: Isaac Signed-off-by: Aakash Saravanan --- NEXT_CHANGELOG.md | 6 ++ adbc/Cargo.lock | 2 + adbc/Cargo.toml | 2 + adbc/README.md | 12 +++ adbc/src/statement.rs | 199 +++++++++++++++++++++++++++++++++++- include/databricks_kernel.h | 40 +++++++- napi/NEXT_CHANGELOG.md | 10 ++ napi/index.d.ts | 29 +++++- napi/src/async_statement.rs | 30 +++++- napi/src/connection.rs | 64 +++++++++++- napi/src/database.rs | 17 ++- napi/src/error.rs | 49 +++++++++ napi/src/statement.rs | 14 +++ pyo3/Cargo.lock | 1 + pyo3/Cargo.toml | 1 + pyo3/NEXT_CHANGELOG.md | 7 ++ pyo3/src/errors.rs | 19 +++- pyo3/src/result_stream.rs | 6 ++ pyo3/src/statement.rs | 43 ++++++++ pyo3/tests/sql_api.py | 8 +- pyo3/tests/test_volume.py | 75 ++++++++++++++ src/c_abi/error.rs | 62 +++++++++++ src/c_abi/result.rs | 27 +++++ src/c_abi/statement.rs | 99 ++++++++++++++++++ tests/c/session_smoke.c | 13 +++ 25 files changed, 819 insertions(+), 16 deletions(-) create mode 100644 pyo3/tests/test_volume.py diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index 0cec5f3f..acd6162e 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -31,6 +31,12 @@ changes go in their respective binding's NEXT_CHANGELOG. - Configure the Arrow result LZ4 session default with `ResultConfig.lz4_compression_enabled` (client config key `lz4_compression_enabled`) and override it with `StatementSpec::lz4_compression`. ADBC exposes the default through `adbc.databricks.enable_query_result_lz4_compression`. +- C ABI: `kernel_statement_set_volume_options`, the + `kernel_*_is_volume_operation` flags, and `kernel_get_last_error_code` / + `_local_os_error` / `_local_path`. +- ADBC: the `adbc.databricks.statement.staging_allowed_local_paths` statement + option runs Volume transfers. The driver takes no upload bytes, so a + `PUT '__input_stream__'` fails with `InvalidArguments`. ### Changed diff --git a/adbc/Cargo.lock b/adbc/Cargo.lock index 89294293..12e0e63e 100644 --- a/adbc/Cargo.lock +++ b/adbc/Cargo.lock @@ -648,7 +648,9 @@ dependencies = [ "arrow-array", "arrow-buffer", "arrow-cast", + "arrow-ipc", "arrow-schema", + "base64 0.22.1", "databricks-sql-kernel", "serde_json", "tokio", diff --git a/adbc/Cargo.toml b/adbc/Cargo.toml index 559af9d1..5bfb6c17 100644 --- a/adbc/Cargo.toml +++ b/adbc/Cargo.toml @@ -37,6 +37,8 @@ serde_json = "1" tokio = { version = "1", features = ["rt-multi-thread"] } [dev-dependencies] +arrow-ipc = "59" +base64 = "0.22" adbc_driver_manager = "0.24" arrow-cast = "59" wiremock = "0.6" diff --git a/adbc/README.md b/adbc/README.md index 38f1385f..5374cfe9 100644 --- a/adbc/README.md +++ b/adbc/README.md @@ -77,6 +77,18 @@ optional C interface and native Rust asynchronous submission and polling. Transactions, partitioned execution, statistics, and progress reporting are not currently implemented. +## Volume file operations + +Set the statement option `adbc.databricks.statement.staging_allowed_local_paths` +to a JSON array of local directories to run the file transfer for a Volume +`PUT`, `GET` or `REMOVE` before results are returned; the instruction row stays +readable. Local paths, with symlinks resolved, must be inside one of those +directories, and `[]` allows only `REMOVE`. The option stays set until it is set +to JSON `null`. Without it, `execute` returns the server's instruction row and +moves no file, and `execute_update` fails with `InvalidState`. `REMOVE` of a +missing object succeeds. `PUT` from an input stream is not supported. +`SocketTimeout` also limits how long a transfer may go without progress. + ## Compatibility and status The current implementation targets Rust 1.89+, Rust edition 2021, ADBC 1.1, diff --git a/adbc/src/statement.rs b/adbc/src/statement.rs index 1a6b5899..8d401845 100644 --- a/adbc/src/statement.rs +++ b/adbc/src/statement.rs @@ -34,6 +34,7 @@ use crate::runtime::{RuntimeExt as _, RuntimeHandle}; const PARAMETER_STYLE_OPTION: &str = "adbc.databricks.statement.parameter_style"; const QUERY_TAGS_OPTION: &str = "adbc.databricks.statement.query_tags"; +const STAGING_ALLOWED_PATHS_OPTION: &str = "adbc.databricks.statement.staging_allowed_local_paths"; const CLIENT_TIMEOUT_OPTION: &str = "adbc.databricks.statement.client_timeout_ms"; const QUERY_TIMEOUT_OPTION: &str = "adbc.apache.statement.query_timeout_s"; const ENABLE_DIRECT_RESULTS_OPTION: &str = "adbc.databricks.enable_direct_results"; @@ -540,6 +541,19 @@ impl Statement { .row_limit(Some(expect_nonnegative_int(value, key)?)); Ok(()) } + STAGING_ALLOWED_PATHS_OPTION => { + let roots: Option> = + serde_json::from_str(&expect_string(value, key)?).map_err(|_| { + adbc_error( + format!("{key} expects a JSON array of strings or null"), + Status::InvalidArguments, + ) + })?; + self.inner()? + .spec() + .volume(roots.map(|roots| kernel::VolumeOptions::new(roots, true))); + Ok(()) + } ROWS_FETCHED_PER_BLOCK_OPTION | "adbc.databricks.rows_fetched_per_block" => { let rows = expect_nonnegative_int(value, key)?; if rows == 0 { @@ -632,6 +646,15 @@ impl Statement { .get("query_tags") .cloned() .ok_or_else(|| adbc_error("query tags are not set", Status::NotFound)), + STAGING_ALLOWED_PATHS_OPTION => self + .inner()? + .spec_ref() + .volume + .as_ref() + .map(|options| { + serde_json::to_string(&options.allowed_paths).expect("paths serialize") + }) + .ok_or_else(|| option_not_found("statement string", key)), _ if key.starts_with(STATEMENT_CONF_PREFIX) => self .inner()? .spec_ref() @@ -848,21 +871,26 @@ impl adbc_core::Statement for Statement { fn execute_update(&mut self) -> Result> { self.invalidate_results(); let _connection_operation = self.register_connection_operation()?; + let staging = self.inner()?.spec_ref().volume.is_some(); let Some(binding) = self.binding.take() else { if !self.enable_direct_results { let (executed, stream) = self.execute_async_inner()?; + let marked = stream.is_volume_operation(); let count = executed.num_modified_rows(); drop(stream); self.runtime .block_on_safe(executed.close()) .map_err(map_kernel_error)?; + require_staging_option(marked, staging)?; return Ok(count); } let executed = self.execute_inner()?; + let marked = executed.result_stream().is_volume_operation(); let count = executed.num_modified_rows(); self.runtime .block_on_safe(executed.close()) .map_err(map_kernel_error)?; + require_staging_option(marked, staging)?; return Ok(count); }; @@ -888,7 +916,11 @@ impl adbc_core::Statement for Statement { &row, self.parameter_style, self.client_timeout, - ) { + ) + .and_then(|executed| { + require_staging_option(executed.result_stream().is_volume_operation(), staging)?; + Ok(executed) + }) { Ok(executed) => executed, Err(mut error) => { row_index += 1; @@ -1116,6 +1148,18 @@ fn is_valid_named_parameter(name: &str) -> bool { && bytes.all(|byte| byte.is_ascii_alphanumeric() || byte == b'_') } +/// `execute_update` returns no rows, so a Volume statement executed without the +/// staging option, which therefore moved no file, would otherwise read as success. +fn require_staging_option(marked: bool, staging: bool) -> Result<()> { + if marked && !staging { + return Err(adbc_error( + format!("execute_update on a Volume PUT, GET or REMOVE requires {STAGING_ALLOWED_PATHS_OPTION}"), + Status::InvalidState, + )); + } + Ok(()) +} + pub(crate) fn execute_bound_row( inner: &Arc>, runtime: &Arc, @@ -1684,4 +1728,157 @@ mod tests { assert!(!is_describable_query("INSERT INTO t VALUES (1)")); assert!(!is_describable_query("DESCRIBE TABLE t")); } + + #[test] + fn staging_option_runs_volume_transfers_and_execute_update_requires_it() { + use adbc_core::options::OptionDatabase; + use adbc_core::{ + Connection as _, Database as _, Driver as _, Optionable as _, Statement as _, + }; + use base64::Engine as _; + use wiremock::matchers::{body_string_contains, method, path}; + use wiremock::{Mock, MockServer, ResponseTemplate}; + + let runtime = RuntimeHandle::create().unwrap(); + let server = runtime.block_on_safe(MockServer::start()); + let response = |operation: &str, route: &str, local_file: &str| { + let values = [ + operation.to_owned(), + format!("{}/{route}", server.uri()), + "{}".into(), + local_file.to_owned(), + ]; + let names = ["operation", "presignedUrl", "headers", "localFile"]; + let batch = + RecordBatch::try_from_iter(names.into_iter().zip(values).map(|(name, value)| { + ( + name, + Arc::new(StringArray::from(vec![value])) as arrow_array::ArrayRef, + ) + })) + .unwrap(); + let mut ipc = Vec::new(); + let mut writer = + arrow_ipc::writer::StreamWriter::try_new(&mut ipc, &batch.schema()).unwrap(); + writer.write(&batch).unwrap(); + writer.finish().unwrap(); + drop(writer); + let columns: Vec<_> = names + .iter() + .enumerate() + .map(|(position, name)| serde_json::json!({"name": name, "type_name": "STRING", "type_text": "STRING", "position": position})) + .collect(); + serde_json::json!({ + "statement_id": "stmt-volume", + "status": {"state": "SUCCEEDED"}, + "manifest": {"is_volume_operation": true, "format": "ARROW_STREAM", "schema": {"column_count": 4, "columns": columns}, "total_chunk_count": 1, "total_row_count": 1}, + "result": {"chunk_index": 0, "row_offset": 0, "row_count": 1, "attachment": base64::engine::general_purpose::STANDARD.encode(&ipc)}, + }) + .to_string() + }; + let remove = response("REMOVE", "object", ""); + let slow_remove = response("REMOVE", "slow", ""); + runtime.block_on_safe(async { + Mock::given(method("POST")) + .and(path("/api/2.0/sql/statements")) + .and(body_string_contains("files/slow")) + .respond_with(ResponseTemplate::new(200).set_body_string(slow_remove)) + .mount(&server) + .await; + for (verb, route, body) in [ + ( + "POST", + "/api/2.0/sql/warehouses/test_wh/sessions", + r#"{"session_id":"sess-test"}"#.to_owned(), + ), + ("POST", "/api/2.0/sql/statements", remove.clone()), + ( + "POST", + "/api/2.0/sql/statements/stmt-volume/cancel", + "{}".into(), + ), + ("GET", "/api/2.0/sql/statements/stmt-volume", remove), + ] { + Mock::given(method(verb)) + .and(path(route)) + .respond_with(ResponseTemplate::new(200).set_body_string(body)) + .mount(&server) + .await; + } + Mock::given(method("DELETE")) + .and(path("/object")) + .respond_with(ResponseTemplate::new(204)) + .expect(1) + .mount(&server) + .await; + Mock::given(method("DELETE")) + .and(path("/slow")) + .respond_with(ResponseTemplate::new(204).set_delay(Duration::from_secs(30))) + .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()), + "secret".into(), + ), + ]) + .unwrap(); + let mut connection = database.new_connection().unwrap(); + let mut statement = |sql: &str, staging: bool| { + let mut statement = connection.new_statement().unwrap(); + statement.set_sql_query(sql).unwrap(); + if staging { + statement + .set_option( + OptionStatement::Other(STAGING_ALLOWED_PATHS_OPTION.into()), + "[]".into(), + ) + .unwrap(); + } + statement + }; + let remove = "REMOVE '/Volumes/main/default/files/file'"; + // With the option, execute_update runs the transfer. + statement(remove, true).execute_update().unwrap(); + // Without it, execute returns the instruction row and moves no file, and + // execute_update, which returns no rows, refuses the statement. + let mut reader = statement(remove, false).execute().unwrap(); + assert_eq!(reader.next().unwrap().unwrap().num_rows(), 1); + let error = statement(remove, false).execute_update().unwrap_err(); + assert_eq!(error.status, Status::InvalidState); + + // The cancellation handle stops a running transfer. + let mut slow = statement("REMOVE '/Volumes/main/default/files/slow'", true); + let cancellation = slow.cancellation_handle(); + let started = std::time::Instant::now(); + std::thread::scope(|scope| { + scope.spawn(|| { + while !runtime + .block_on_safe(server.received_requests()) + .unwrap() + .iter() + .any(|request| request.url.path() == "/slow") + { + assert!(started.elapsed() < Duration::from_secs(10)); + std::thread::sleep(Duration::from_millis(10)); + } + cancellation.cancel().unwrap(); + }); + let error = slow.execute_update().unwrap_err(); + assert_eq!(error.status, Status::Cancelled); + }); + assert!(started.elapsed() < Duration::from_secs(10)); + runtime.block_on_safe(server.verify()); + } } diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h index c8aae2de..762a92fc 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -191,6 +191,18 @@ typedef struct KernelError { */ bool kernel_get_last_error(KernelError* out); +/* + * Details of the last error recorded on the calling thread. Strings are NULL + * when absent and valid until the next kernel call on that thread. + * - `_code`: string code such as `VOLUME_PATH_NOT_ALLOWED`. + * - `_local_os_error`: OS error number behind a local file error (errno, or + * a Windows error code on Windows), or 0. + * - `_local_path`: local path of a local file error. + */ +const char* kernel_get_last_error_code(void); +int32_t kernel_get_last_error_local_os_error(void); +const char* kernel_get_last_error_local_path(void); + /* ─── Opaque handles ────────────────────────────────────────────────── * * All handles are owned heap allocations on the Rust side; the C side @@ -387,10 +399,13 @@ KernelStatusCode kernel_session_config_set_sea_response_compression_enabled( /* Configure the total timeout for one HTTP request, from connection start * through response-body completion. A separate 30s connection timeout also * applies, so connection establishment is bounded by the shorter limit. - * `request_timeout_ms == 0` keeps the kernel default (120s). */ + * `request_timeout_ms == 0` keeps the kernel default (120s). For Volume file + * transfers it is an idle limit: a transfer fails after this long without + * progress. */ KernelStatusCode kernel_session_config_set_request_timeout(KernelSessionConfig* config, uint64_t request_timeout_ms); + /* Configure the maximum number of idle HTTP connections retained per host. * `max_connections` must be greater than zero. Omitting this setter keeps the * kernel default (100). */ @@ -803,6 +818,21 @@ KernelStatusCode kernel_statement_bind_parameter(kernel_statement_t* stmt, KernelStatusCode kernel_statement_set_query_tags(kernel_statement_t* stmt, const char* query_tags); +/* + * Set the Volume transfer options for later executions of `stmt`. With them, + * executing a Volume PUT, GET or REMOVE also runs its file transfer, and the + * execution fails if the transfer does. `allowed_paths_json`: JSON array of + * local directories a transfer may use; the local path, with symlinks + * resolved, must be inside one of them. NULL clears the options, so a Volume + * statement returns its instruction row without transferring. + * `remove_not_found_is_success`: report success when REMOVE targets a missing + * object. The options survive kernel_statement_set_sql. This API takes no upload + * bytes, so `PUT '__input_stream__'` fails. + */ +KernelStatusCode kernel_statement_set_volume_options(kernel_statement_t* stmt, + const char* allowed_paths_json, + bool remove_not_found_is_success); + /* * Wait-for-result execution without an overall client polling deadline. * On success, release `*out` with @@ -960,6 +990,10 @@ KernelStatusCode kernel_executed_statement_get_result_stream(kernel_executed_sta */ int64_t kernel_executed_statement_num_modified_rows(const kernel_executed_statement_t* exec); +/* Whether the server marked the statement as a Volume PUT, GET or REMOVE. */ +KernelStatusCode kernel_executed_statement_is_volume_operation( + const kernel_executed_statement_t* exec, bool* out); + /* * Server statement (query) id of a successfully executed statement, as a * NUL-terminated C string — the success-path counterpart to the query id on @@ -1069,6 +1103,10 @@ KernelStatusCode kernel_result_stream_canceller_cancel( KernelStatusCode kernel_result_stream_canceller_free( kernel_result_stream_canceller_t* canceller); +/* Whether the server marked this result as a Volume PUT, GET or REMOVE. */ +KernelStatusCode kernel_result_stream_is_volume_operation(const kernel_result_stream_t* stream, + bool* out); + /* ─── Metadata ──────────────────────────────────────────────────────── * * Each returns a self-contained result stream (released via diff --git a/napi/NEXT_CHANGELOG.md b/napi/NEXT_CHANGELOG.md index 516adfe8..f97bd253 100644 --- a/napi/NEXT_CHANGELOG.md +++ b/napi/NEXT_CHANGELOG.md @@ -18,9 +18,19 @@ layout, or npm publishing. Pure-kernel changes go in the root `0..=65535`, or a host the kernel can't combine with the port, gives `InvalidArgument`. - `ExecuteOptions.lz4Compression` overrides Arrow result LZ4 compression per statement. +- `ExecuteOptions.volume` (`{ allowedPaths, removeNotFoundIsSuccess? }`): with + it, executing a Volume `PUT`, `GET` or `REMOVE` also runs its file transfer. + `Statement` and `AsyncResultHandle` expose `isVolumeOperation`. Local file + errors carry `localOsError`, `localErrorKind` and `localPath`. + `socketTimeoutMs` is also the transfer idle limit. ### Changed +- `socketTimeoutMs: 0` keeps the kernel default instead of setting a zero + request timeout. +- `AsyncStatement.close()` cancels the statement first when another call on it, + such as `awaitResult()`, is still running, instead of waiting for it. + ### Updated - Bundle the kernel's SOCKS proxy support. diff --git a/napi/index.d.ts b/napi/index.d.ts index 574f639b..ca7dedfe 100644 --- a/napi/index.d.ts +++ b/napi/index.d.ts @@ -95,6 +95,24 @@ export interface ExecuteOptions { * typed parameters or combine named and positional markers. */ rawParams?: Array + /** + * Volume transfer settings. With them, executing a Volume PUT, GET or + * REMOVE also runs its file transfer, and a failed transfer fails the + * execution. Omitted ⇒ a Volume statement returns its instruction row + * and moves no file. Maps to `StatementSpec.volume`. No upload bytes + * can be passed, so `PUT '__input_stream__'` fails. + */ + volume?: VolumeExecuteOptions +} +/** Volume transfer settings for one execution. */ +export interface VolumeExecuteOptions { + /** + * Local directories a PUT may read from and a GET may write to. The + * local path, with symlinks resolved, must be inside one of them. + */ + allowedPaths: Array + /** Report success when REMOVE targets an object that does not exist. */ + removeNotFoundIsSuccess?: boolean } /** * A named bound parameter — a [`TypedValueInput`] plus its `:name`. Kept a @@ -621,7 +639,8 @@ export interface ConnectionOptions { * long a single HTTP round-trip may block waiting on the server * before the request errors out. Maps onto the kernel * [`HttpConfig::request_timeout`] (the internal reqwest - * `Client::timeout`). + * `Client::timeout`), which is also the idle limit for Volume file + * transfers. `0` keeps the kernel default. * * Omitted ⇒ kernel default (120 000 ms / 120 s). Napi-rs * serialises `u32` as JS `number`; the largest representable value @@ -870,7 +889,9 @@ export declare class AsyncStatement { * * Also invalidates the handles `awaitResult()` returned: their * `fetchNextBatch()` then rejects with `InvalidStatementHandle`, - * unless a fetch was in progress when `close()` ran. + * unless a fetch was in progress when `close()` ran. If another call on + * the statement is still running, such as an `awaitResult()` and its + * Volume transfer, the statement is cancelled first. */ close(): Promise } @@ -892,6 +913,8 @@ export declare class AsyncStatement { * post-close contract. */ export declare class AsyncResultHandle { + /** True when the server marked this result as a Volume PUT, GET or REMOVE. */ + get isVolumeOperation(): boolean /** * Server-issued statement id. Cached at construction; readable * for log correlation. Matches the parent `AsyncStatement`'s @@ -1264,6 +1287,8 @@ export declare class Statement { * entry points use is not required for this method. */ schema(): ArrowSchema + /** True when the server marked this result as a Volume PUT, GET or REMOVE. */ + get isVolumeOperation(): boolean /** * Server-side cancel. * diff --git a/napi/src/async_statement.rs b/napi/src/async_statement.rs index df416254..078ed52b 100644 --- a/napi/src/async_statement.rs +++ b/napi/src/async_statement.rs @@ -320,6 +320,7 @@ impl AsyncStatement { .map_err(napi_err_from_kernel)?; let statement_id = inner_state.executed_async.statement_id().to_owned(); let schema = stream.schema(); + let is_volume_operation = stream.is_volume_operation(); let stream = Arc::new(Mutex::new(Some(stream))); // Registered while `inner` is held, so a queued `close()` sees it. results @@ -330,6 +331,7 @@ impl AsyncStatement { inner: stream, schema, statement_id, + is_volume_operation, }) }) .await @@ -376,7 +378,9 @@ impl AsyncStatement { /// /// Also invalidates the handles `awaitResult()` returned: their /// `fetchNextBatch()` then rejects with `InvalidStatementHandle`, - /// unless a fetch was in progress when `close()` ran. + /// unless a fetch was in progress when `close()` ran. If another call on + /// the statement is still running, such as an `awaitResult()` and its + /// Volume transfer, the statement is cancelled first. #[napi] pub async fn close(&self) -> napi::Result<()> { let inner = Arc::clone(&self.inner); @@ -384,9 +388,20 @@ impl AsyncStatement { let canceller = Arc::clone(&self.canceller); let results = Arc::clone(&self.results); guarded(async move { - let taken = { - let mut guard = inner.lock().await; - guard.take() + let taken = match inner.try_lock() { + Ok(mut guard) => guard.take(), + // A call still running holds `inner` until it returns, such as an + // `awaitResult()` and its Volume transfer, so cancel it first. + Err(_) => { + let in_flight = canceller + .lock() + .unwrap_or_else(PoisonError::into_inner) + .clone(); + if let Some(in_flight) = in_flight { + let _ = in_flight.cancel().await; + } + inner.lock().await.take() + } }; let Some(mut inner_state) = taken else { return Ok(()); @@ -459,6 +474,7 @@ pub struct AsyncResultHandle { inner: Arc, schema: SchemaRef, statement_id: String, + is_volume_operation: bool, } #[napi] @@ -471,6 +487,12 @@ impl AsyncResultHandle { &self.statement_id } + /// True when the server marked this result as a Volume PUT, GET or REMOVE. + #[napi(getter)] + pub fn is_volume_operation(&self) -> bool { + self.is_volume_operation + } + /// 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 diff --git a/napi/src/connection.rs b/napi/src/connection.rs index c340bacb..876e9465 100644 --- a/napi/src/connection.rs +++ b/napi/src/connection.rs @@ -123,6 +123,26 @@ pub struct ExecuteOptions { /// Omit `name` for positional values. Raw parameters cannot be mixed with /// typed parameters or combine named and positional markers. pub raw_params: Option>, + /// Volume transfer settings. With them, executing a Volume PUT, GET or + /// REMOVE also runs its file transfer, and a failed transfer fails the + /// execution. Omitted ⇒ a Volume statement returns its instruction row + /// and moves no file. Maps to `StatementSpec.volume`. No upload bytes + /// can be passed, so `PUT '__input_stream__'` fails. + pub volume: Option, +} + +/// Volume transfer settings for one execution. +#[allow( + dead_code, + reason = "exported via napi macro codegen; not called from Rust" +)] +#[napi(object)] +pub struct VolumeExecuteOptions { + /// Local directories a PUT may read from and a GET may write to. The + /// local path, with symlinks resolved, must be inside one of them. + pub allowed_paths: Vec, + /// Report success when REMOVE targets an object that does not exist. + pub remove_not_found_is_success: Option, } /// A named bound parameter — a [`TypedValueInput`] plus its `:name`. Kept a @@ -197,6 +217,7 @@ fn build_statement( positional_params: Vec, named_params: Vec<(String, TypedValue)>, raw_params: Vec, + volume: Option, ) -> napi::Result { // Positional/named mutual-exclusivity is enforced in the kernel's // `build_execute_params` (StatementSpec dispatch), so every binding @@ -236,6 +257,12 @@ fn build_statement( for raw in raw_params { stmt.spec().param_raw(raw.name, raw.sql_type, raw.value); } + stmt.spec().volume(volume.map(|volume| { + databricks_sql_kernel::VolumeOptions::new( + volume.allowed_paths.into_iter().map(Into::into).collect(), + volume.remove_not_found_is_success.unwrap_or(false), + ) + })); Ok(stmt) } @@ -326,6 +353,7 @@ 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 volume = options.as_mut().and_then(|o| o.volume.take()); guarded(async move { // Build the kernel `Statement` while holding the session lock, // then RELEASE the lock before `execute().await`. `Session::statement()` @@ -350,6 +378,7 @@ impl Connection { positional_params, named_params, raw_params, + volume, )? // session lock released here }; @@ -411,6 +440,7 @@ 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 volume = options.as_mut().and_then(|o| o.volume.take()); guarded(async move { let mut stmt = { let guard = inner.lock().await; @@ -425,6 +455,7 @@ impl Connection { positional_params, named_params, raw_params, + volume, )? }; @@ -486,6 +517,7 @@ 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 volume = options.as_mut().and_then(|o| o.volume.take()); guarded(async move { // Build the kernel `Statement` under the session lock, release // the lock, then hand the built statement to the @@ -507,6 +539,7 @@ impl Connection { positional_params, named_params, raw_params, + volume, )? // session lock released here }; @@ -563,6 +596,7 @@ 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 volume = options.as_mut().and_then(|o| o.volume.take()); guarded(async move { // Build the kernel `Statement` while holding the session lock, // then RELEASE the lock before `submit().await` — same shape as @@ -587,6 +621,7 @@ impl Connection { positional_params, named_params, raw_params, + volume, )? // session lock released here }; @@ -714,7 +749,7 @@ mod tests { } #[tokio::test] - async fn build_statement_forwards_raw_params_and_rejects_mixed_binding() { + async fn build_statement_forwards_options_and_rejects_mixed_binding() { let server = MockServer::start().await; Mock::given(method("POST")) .and(path("/api/2.0/sql/warehouses/test_wh/sessions")) @@ -756,6 +791,31 @@ mod tests { .await .expect("session opens against mock server"); + let volume = VolumeExecuteOptions { + allowed_paths: vec!["/data".into()], + remove_not_found_is_success: Some(true), + }; + let volume_stmt = build_statement( + &session, + "GET".into(), + None, + None, + None, + None, + vec![], + vec![], + vec![], + Some(volume), + ) + .expect("volume statement builds"); + let options = volume_stmt + .spec_ref() + .volume + .as_ref() + .expect("volume options set"); + assert_eq!(options.allowed_paths, [std::path::PathBuf::from("/data")]); + assert!(options.remove_not_found_is_success); + let raw = || RawParameterInput { name: None, sql_type: "INTERVAL MONTH".into(), @@ -771,6 +831,7 @@ mod tests { vec![], vec![], vec![raw()], + None, ) .expect("raw statement builds"); let dispatched_err = raw_stmt @@ -806,6 +867,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/napi/src/database.rs b/napi/src/database.rs index 27897403..634142c9 100644 --- a/napi/src/database.rs +++ b/napi/src/database.rs @@ -467,7 +467,8 @@ pub struct ConnectionOptions { /// long a single HTTP round-trip may block waiting on the server /// before the request errors out. Maps onto the kernel /// [`HttpConfig::request_timeout`] (the internal reqwest - /// `Client::timeout`). + /// `Client::timeout`), which is also the idle limit for Volume file + /// transfers. `0` keeps the kernel default. /// /// Omitted ⇒ kernel default (120 000 ms / 120 s). Napi-rs /// serialises `u32` as JS `number`; the largest representable value @@ -680,8 +681,8 @@ fn build_http_config(options: &mut ConnectionOptions) -> HttpConfig { } // Per-connection socket read timeout. Maps onto the kernel's // `request_timeout` (the reqwest `Client::timeout`). Omitted ⇒ kernel - // default (120 s). - if let Some(ms) = options.socket_timeout_ms { + // default (120 s), and so does `0`. + if let Some(ms) = options.socket_timeout_ms.filter(|&ms| ms != 0) { http.request_timeout = std::time::Duration::from_millis(u64::from(ms)); } http @@ -930,6 +931,16 @@ pub async fn open_session(mut options: ConnectionOptions) -> napi::Result ConnectionOptions { diff --git a/napi/src/error.rs b/napi/src/error.rs index 70518fe3..976c5bdb 100644 --- a/napi/src/error.rs +++ b/napi/src/error.rs @@ -158,6 +158,18 @@ pub(crate) fn napi_err_from_kernel(e: KernelError) -> NapiError { if let Some(ej) = e.error_details_json { obj.insert("errorDetailsJson".to_owned(), Value::from(ej)); } + // A local file error carries what a Node `fs` error needs: the OS error + // number, an error kind for when there is none, and the path. + if let Some(local) = e.local_error { + if let Some(errno) = local.raw_os_error { + obj.insert("localOsError".to_owned(), Value::from(errno)); + } + obj.insert( + "localErrorKind".to_owned(), + Value::from(local_error_kind(local.kind)), + ); + obj.insert("localPath".to_owned(), Value::from(local.path)); + } // `to_string` on a JSON object is infallible: every field above is // a `String` / `i64` / `u16` / `bool` whose serialization can't fail. @@ -169,6 +181,18 @@ pub(crate) fn napi_err_from_kernel(e: KernelError) -> NapiError { NapiError::new(status, envelope) } +fn local_error_kind(kind: std::io::ErrorKind) -> &'static str { + use std::io::ErrorKind; + match kind { + ErrorKind::NotFound => "NotFound", + ErrorKind::PermissionDenied => "PermissionDenied", + ErrorKind::AlreadyExists => "AlreadyExists", + ErrorKind::NotADirectory => "NotADirectory", + ErrorKind::IsADirectory => "IsADirectory", + _ => "Other", + } +} + /// 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 @@ -196,6 +220,31 @@ fn error_code_str(code: ErrorCode) -> &'static str { mod tests { use super::*; + #[test] + fn local_file_errors_carry_os_error_kind_and_path() { + let error = + KernelError::not_found().with_local_error(databricks_sql_kernel::LocalFileError::new( + Some(2), + std::io::ErrorKind::NotFound, + "local-file", + )); + let encoded = napi_err_from_kernel(error); + let value: Value = serde_json::from_str(&encoded.reason[ERROR_SENTINEL.len()..]).unwrap(); + assert_eq!(value["localOsError"], 2); + assert_eq!(value["localErrorKind"], "NotFound"); + assert_eq!(value["localPath"], "local-file"); + + let error = KernelError::io().with_local_error(databricks_sql_kernel::LocalFileError::new( + None, + std::io::ErrorKind::UnexpectedEof, + "local-file", + )); + let encoded = napi_err_from_kernel(error); + let value: Value = serde_json::from_str(&encoded.reason[ERROR_SENTINEL.len()..]).unwrap(); + assert!(value.get("localOsError").is_none()); + assert_eq!(value["localErrorKind"], "Other"); + } + #[test] fn envelope_carries_sentinel_and_code() { let e = KernelError::invalid_argument().message("hi"); diff --git a/napi/src/statement.rs b/napi/src/statement.rs index 40d682d2..484737cd 100644 --- a/napi/src/statement.rs +++ b/napi/src/statement.rs @@ -139,6 +139,7 @@ pub struct Statement { /// (Irrelevant for the `Metadata` variant where cancel is already /// a no-op kernel-side; harmless to carry the field regardless.) finished: Arc, + is_volume_operation: bool, } impl Statement { @@ -153,6 +154,7 @@ impl Statement { pub(crate) fn from_executed(parent: KernelStatement, executed: ExecutedStatement) -> Self { let schema = executed.schema(); let statement_id = executed.statement_id().to_owned(); + let is_volume_operation = executed.result_stream().is_volume_operation(); Self { inner: Arc::new(Mutex::new(Some(AnyInner::Executed(Box::new( StatementInner { @@ -163,6 +165,7 @@ impl Statement { schema, statement_id, finished: Arc::new(AtomicBool::new(false)), + is_volume_operation, } } @@ -183,6 +186,7 @@ impl Statement { schema, statement_id: String::new(), finished: Arc::new(AtomicBool::new(false)), + is_volume_operation: false, } } } @@ -197,6 +201,12 @@ impl Statement { &self.statement_id } + /// True when the server marked this result as a Volume PUT, GET or REMOVE. + #[napi(getter)] + pub fn is_volume_operation(&self) -> bool { + self.is_volume_operation + } + // ─── SEA extended status accessors (Thrift parity) ───────────────── // // Mirror the same-named optional fields on the NodeJS Thrift @@ -625,6 +635,7 @@ mod tests { schema: make_schema(), statement_id: "stmt-survives-close".to_owned(), finished: Arc::new(AtomicBool::new(false)), + is_volume_operation: false, }; assert_eq!(stmt.statement_id(), "stmt-survives-close"); } @@ -640,6 +651,7 @@ mod tests { schema: schema.clone(), statement_id: "x".to_owned(), finished: Arc::new(AtomicBool::new(false)), + is_volume_operation: false, }; // Two refs alive: the local + the stmt field. assert!(Arc::strong_count(&stmt.schema) >= 2); @@ -659,6 +671,7 @@ mod tests { schema: make_schema(), statement_id: "x".to_owned(), finished: Arc::new(AtomicBool::new(false)), + is_volume_operation: false, }; assert!(!stmt.finished.load(Ordering::Acquire)); stmt.finished.store(true, Ordering::Release); @@ -675,6 +688,7 @@ mod tests { schema: make_schema(), statement_id: "x".to_owned(), finished: Arc::new(AtomicBool::new(true)), + is_volume_operation: false, }; assert!(stmt.cancel().await.is_ok()); } diff --git a/pyo3/Cargo.lock b/pyo3/Cargo.lock index 205684e9..9267dee8 100644 --- a/pyo3/Cargo.lock +++ b/pyo3/Cargo.lock @@ -669,6 +669,7 @@ dependencies = [ "pyo3", "pyo3-log", "tokio", + "tokio-util", "tracing", ] diff --git a/pyo3/Cargo.toml b/pyo3/Cargo.toml index 7b6270f2..30ad072a 100644 --- a/pyo3/Cargo.toml +++ b/pyo3/Cargo.toml @@ -83,6 +83,7 @@ pyo3 = { version = "0.29", features = ["abi3-py39"] } # Multi-thread runtime — one per Session, owned on the Rust side. tokio = { version = "1", features = ["rt-multi-thread"] } +tokio-util = "0.7" # Arrow handoff. Pinned to 59 to match the kernel's arrow-* deps so we # share the same RecordBatch / Schema types and never have to convert. diff --git a/pyo3/NEXT_CHANGELOG.md b/pyo3/NEXT_CHANGELOG.md index 95eb2ce8..e86cf6a9 100644 --- a/pyo3/NEXT_CHANGELOG.md +++ b/pyo3/NEXT_CHANGELOG.md @@ -17,6 +17,13 @@ changes go in the root `NEXT_CHANGELOG.md`. `0..=65535` raises `ValueError`; a host the kernel can't combine with the port raises `KernelError` (`InvalidArgument`). - `Statement.set_lz4_compression` overrides Arrow result LZ4 compression per statement. +- `Statement.set_volume_options(allowed_paths, remove_not_found_is_success=False, + input_bytes=None)`: with it, executing a Volume `PUT`, `GET` or `REMOVE` also + runs its file transfer; `input_bytes` is the upload for + `PUT '__input_stream__'`. `ExecutedStatement` and `ResultStream` expose + `is_volume_operation`. `KernelError` carries `local_os_error` and `local_path` for local + file failures. A positive `request_timeout_secs` also sets the transfer idle + limit. ### Changed - Allow pyarrow 24.x through 26.x on Python 3.10+ (`pyarrow>=23.0.1,<27`), diff --git a/pyo3/src/errors.rs b/pyo3/src/errors.rs index 88ff4257..b010875c 100644 --- a/pyo3/src/errors.rs +++ b/pyo3/src/errors.rs @@ -105,6 +105,17 @@ fn attach_attrs( Ok(()) } +/// A local file error also carries the OS error number (errno, or a Windows +/// error code on Windows) and path, so the +/// connector can raise the matching `OSError`; both are `None` otherwise. +fn attach_local_error( + bound: &Bound<'_, PyAny>, + local: Option<&databricks_sql_kernel::LocalFileError>, +) -> PyResult<()> { + bound.setattr("local_os_error", local.and_then(|local| local.raw_os_error))?; + bound.setattr("local_path", local.map(|local| local.path.as_str())) +} + /// Convert a kernel `Error` into a `KernelError` Python exception /// with the structured fields attached as attributes. Python sees /// `err.code`, `err.message`, `err.sql_state`, etc.; `str(err)` is @@ -138,7 +149,9 @@ 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(), - ) { + ) + .and_then(|()| attach_local_error(bound.as_any(), err.local_error.as_deref())) + { // Attribute attachment is best-effort. If something goes wrong // (extremely unlikely for plain string/int setattrs — but // marginally less so now that `error_details_json` can be a @@ -182,7 +195,9 @@ pub(crate) fn closed_err(handle_name: &str) -> PyErr { None, None, None, - ) { + ) + .and_then(|()| attach_local_error(bound.as_any(), None)) + { return setattr_err; } py_err diff --git a/pyo3/src/result_stream.rs b/pyo3/src/result_stream.rs index 1b5fc590..7b2a6334 100644 --- a/pyo3/src/result_stream.rs +++ b/pyo3/src/result_stream.rs @@ -61,6 +61,12 @@ impl ResultStream { self.schema.as_ref().to_pyarrow(py) } + /// True when the server marked this result as a Volume PUT, GET or REMOVE. + #[getter] + fn is_volume_operation(&self) -> PyResult { + Ok(alive!(self, "ResultStream").stream.is_volume_operation()) + } + /// Pull the next batch as a `pyarrow.RecordBatch`, or `None` when /// exhausted. fn fetch_next_batch<'py>(&mut self, py: Python<'py>) -> PyResult>> { diff --git a/pyo3/src/statement.rs b/pyo3/src/statement.rs index b8f78f2c..3a0904a4 100644 --- a/pyo3/src/statement.rs +++ b/pyo3/src/statement.rs @@ -31,8 +31,10 @@ use databricks_sql_kernel::{ Statement as KStatement, StatementCanceller as KStatementCanceller, }; use pyo3::prelude::*; +use pyo3::pybacked::PyBackedBytes; use std::collections::HashMap; use std::sync::Arc; +use tokio_util::bytes::Bytes; /// Python-facing mutable statement. /// @@ -84,6 +86,38 @@ impl Statement { Ok(()) } + /// Set the Volume transfer options. With them, executing a Volume PUT, GET + /// or REMOVE also runs its file transfer, and a failed transfer raises. + /// ``allowed_paths=None`` clears them, so a Volume statement returns its + /// instruction row without transferring. ``input_bytes`` is the upload for + /// ``PUT '__input_stream__'``; the next execution takes it. Passing it + /// without ``allowed_paths`` raises ``ValueError``. + #[pyo3(signature = (allowed_paths, remove_not_found_is_success=false, input_bytes=None))] + fn set_volume_options( + &mut self, + allowed_paths: Option>, + remove_not_found_is_success: bool, + input_bytes: Option, + ) -> PyResult<()> { + let inner = alive_mut!(self, "Statement"); + if allowed_paths.is_none() && input_bytes.is_some() { + return Err(pyo3::exceptions::PyValueError::new_err( + "input_bytes needs allowed_paths", + )); + } + let options = allowed_paths.map(|paths| { + let options = + databricks_sql_kernel::VolumeOptions::new(paths, remove_not_found_is_success); + // The kernel reads the Python buffer in place instead of copying it. + match input_bytes { + Some(bytes) => options.with_input_bytes(Bytes::from_owner(bytes)), + None => options, + } + }); + inner.stmt.spec().volume(options); + Ok(()) + } + /// Set per-statement query tags. /// /// ``tags`` is a ``dict[str, str | None]`` — a ``None`` value emits @@ -346,6 +380,15 @@ impl ExecutedStatement { self.num_modified_rows } + /// True when the server marked this result as a Volume PUT, GET or REMOVE. + #[getter] + fn is_volume_operation(&self) -> PyResult { + Ok(alive!(self, "ExecutedStatement") + .exec + .result_stream() + .is_volume_operation()) + } + /// Result schema as a `pyarrow.Schema`. Available even after /// `close()`. fn arrow_schema<'py>(&self, py: Python<'py>) -> PyResult> { diff --git a/pyo3/tests/sql_api.py b/pyo3/tests/sql_api.py index 21c3d175..c66ff4bc 100644 --- a/pyo3/tests/sql_api.py +++ b/pyo3/tests/sql_api.py @@ -23,7 +23,7 @@ @contextmanager -def sql_api(session_type, arrow_bytes=None): +def sql_api(session_type, arrow_bytes=None, statement_response=None): state = SimpleNamespace( batches=[[1, 2]] if arrow_bytes else [], mode="buffered", @@ -44,6 +44,10 @@ def reply(self): status, response = 200, {} if self.command == "POST" and path.endswith("/sessions"): response = {"session_id": "00000000-0000-0000-0000-000000000001"} + elif self.command == "POST" and path.endswith("/statements") and statement_response: + response = state.response = statement_response(state.host) + elif self.command == "PUT" and path == "/storage/volume": + state.uploaded = body elif self.command == "POST" and path.endswith("/statements"): state.statement_bodies.append(json.loads(body)) pending = state.mode != "buffered" @@ -134,7 +138,7 @@ def link(self, index): "expiration": "2099-01-01T00:00:00Z", } - do_POST = do_GET = do_DELETE = reply + do_POST = do_GET = do_PUT = do_DELETE = reply def log_message(self, *args): pass diff --git a/pyo3/tests/test_volume.py b/pyo3/tests/test_volume.py new file mode 100644 index 00000000..3e15f86a --- /dev/null +++ b/pyo3/tests/test_volume.py @@ -0,0 +1,75 @@ +"""Volume options over the loopback SQL API.""" + +import base64 +import errno + +import pyarrow as pa +import pytest + +import databricks_sql_kernel as k +from sql_api import sql_api + + +def instruction(operation, local_file): + """A server answer carrying one Volume instruction for `local_file`.""" + + def response(host): + names = ["operation", "presignedUrl", "headers", "localFile"] + values = [operation, f"{host}/storage/volume", "{}", local_file] + batch = pa.record_batch([pa.array([value]) for value in values], names=names) + sink = pa.BufferOutputStream() + with pa.ipc.new_stream(sink, batch.schema) as writer: + writer.write_batch(batch) + columns = [ + {"name": name, "type_name": "STRING", "type_text": "STRING", "position": i} + for i, name in enumerate(names) + ] + return { + "statement_id": "00000001-0000-0000-0000-000000000001", + "status": {"state": "SUCCEEDED"}, + "manifest": { + "is_volume_operation": True, + "format": "ARROW_STREAM", + "schema": {"column_count": len(names), "columns": columns}, + "total_chunk_count": 1, + "total_row_count": 1, + }, + "result": { + "chunk_index": 0, + "row_offset": 0, + "row_count": 1, + "attachment": base64.b64encode(sink.getvalue().to_pybytes()).decode(), + }, + } + + return response + + +def test_volume_options_and_input_bytes_reach_the_transfer(): + with sql_api(k.Session, statement_response=instruction("PUT", "__input_stream__")) as api: + statement = api.session.statement() + statement.set_sql("PUT '__input_stream__' INTO '/Volumes/main/default/files/file'") + with pytest.raises(ValueError): + statement.set_volume_options(None, input_bytes=b"\x00\xffdata") + statement.set_volume_options([], input_bytes=b"\x00\xffdata") + executed = statement.execute() + assert executed.is_volume_operation + assert api.uploaded == b"\x00\xffdata" + + +def test_local_file_errors_carry_the_os_error_and_path(tmp_path): + missing = tmp_path / "missing" + with sql_api(k.Session, statement_response=instruction("PUT", str(missing))) as api: + statement = api.session.statement() + statement.set_sql("PUT 'missing' INTO '/Volumes/main/default/files/file'") + statement.set_volume_options([tmp_path]) + with pytest.raises(k.KernelError) as raised: + statement.execute() + assert raised.value.error_code == "VOLUME_LOCAL_FILE_ERROR" + assert raised.value.local_os_error == errno.ENOENT + assert raised.value.local_path == str(missing) + statement.close() + with pytest.raises(k.KernelError) as closed: + statement.execute() + assert closed.value.local_os_error is None + assert closed.value.local_path is None diff --git a/src/c_abi/error.rs b/src/c_abi/error.rs index f5243007..55d741cf 100644 --- a/src/c_abi/error.rs +++ b/src/c_abi/error.rs @@ -62,6 +62,9 @@ struct LastError { http_status: u16, retryable: bool, query_id: Option, + error_code: Option, + local_os_error: i32, + local_path: Option, } thread_local! { @@ -150,6 +153,7 @@ pub(crate) fn store_error(err: Error) { message.push_str("error_code="); message.push_str(ec); } + let local = err.local_error.as_deref(); *last = LastError { code: Some(err.code), message: Some(to_cstring_lossy(&message)), @@ -158,10 +162,44 @@ 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), + error_code: err.error_code.as_deref().map(to_cstring_lossy), + local_os_error: local.and_then(|local| local.raw_os_error).unwrap_or(0), + local_path: local.map(|local| to_cstring_lossy(&local.path)), }; }); } +/// The last error's string code, such as `VOLUME_PATH_NOT_ALLOWED`, or NULL. +/// Valid until the next call that clears the error. +#[no_mangle] +pub extern "C" fn kernel_get_last_error_code() -> *const c_char { + LAST_ERROR.with(|cell| { + cell.borrow() + .error_code + .as_ref() + .map_or(std::ptr::null(), |code| code.as_ptr()) + }) +} + +/// The OS error number behind the last local file error (errno, or a Windows +/// error code on Windows), or zero. +#[no_mangle] +pub extern "C" fn kernel_get_last_error_local_os_error() -> i32 { + LAST_ERROR.with(|cell| cell.borrow().local_os_error) +} + +/// The local path of the last local file error, or NULL. Valid until the next +/// call that clears the error. +#[no_mangle] +pub extern "C" fn kernel_get_last_error_local_path() -> *const c_char { + LAST_ERROR.with(|cell| { + cell.borrow() + .local_path + .as_ref() + .map_or(std::ptr::null(), |path| path.as_ptr()) + }) +} + /// 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 @@ -192,6 +230,30 @@ pub(crate) fn store_invalid_arg(msg: &str) -> KernelStatusCode { mod tests { use super::*; + #[test] + fn last_error_exposes_error_code_and_local_file_details() { + store_error( + Error::not_found() + .with_error_code("VOLUME_LOCAL_FILE_ERROR") + .with_local_error(crate::LocalFileError::new( + Some(2), + std::io::ErrorKind::NotFound, + "local-file", + )), + ); + let text = |ptr| unsafe { std::ffi::CStr::from_ptr(ptr) }.to_str().unwrap(); + assert_eq!( + text(kernel_get_last_error_code()), + "VOLUME_LOCAL_FILE_ERROR" + ); + assert_eq!(kernel_get_last_error_local_os_error(), 2); + assert_eq!(text(kernel_get_last_error_local_path()), "local-file"); + clear_error(); + assert!(kernel_get_last_error_code().is_null()); + assert_eq!(kernel_get_last_error_local_os_error(), 0); + assert!(kernel_get_last_error_local_path().is_null()); + } + /// Helper: read the thread-local error into a `KernelError` and run /// `f` with the borrowed C strings still alive. fn with_last_error(f: impl FnOnce(Option) -> R) -> R { diff --git a/src/c_abi/result.rs b/src/c_abi/result.rs index 1c66a033..2ad60a91 100644 --- a/src/c_abi/result.rs +++ b/src/c_abi/result.rs @@ -623,6 +623,33 @@ pub unsafe extern "C" fn kernel_result_stream_canceller_cancel( }) } +/// Whether the server marked this result as a Volume PUT, GET or REMOVE. +/// +/// # Safety +/// `stream` must be a live handle with no other call in flight on it, and +/// `out` must be writable. +#[no_mangle] +pub unsafe extern "C" fn kernel_result_stream_is_volume_operation( + stream: *const kernel_result_stream_t, + out: *mut bool, +) -> KernelStatusCode { + catch_ffi(|| { + if stream.is_null() || out.is_null() { + return store_invalid_arg("kernel_result_stream_is_volume_operation: null pointer"); + } + let p = stream as *const ResultStreamInner; + let marked = match &*std::ptr::addr_of!((*p).shape) { + ResultStreamShape::Owned { stream, .. } => stream.is_volume_operation(), + ResultStreamShape::Executed { exec, valid } => match executed_ref(*exec, valid) { + Ok(exec) => exec.result_stream().is_volume_operation(), + Err(code) => return code, + }, + }; + std::ptr::write(out, marked); + KernelStatusCode::Success + }) +} + /// Free a result-stream canceller handle. Does not touch the originating stream. /// Drives no RPC (only drops the box), so its order relative to /// `kernel_result_stream_close` is free. diff --git a/src/c_abi/statement.rs b/src/c_abi/statement.rs index f90bc436..3a81c5a2 100644 --- a/src/c_abi/statement.rs +++ b/src/c_abi/statement.rs @@ -446,6 +446,51 @@ pub unsafe extern "C" fn kernel_statement_set_query_tags( }) } +/// Set the Volume transfer options for later executions of `stmt`; see +/// `StatementSpec::volume`. With them, executing a Volume PUT, GET or REMOVE +/// also runs its file transfer, and the execution fails if the transfer does. +/// `allowed_paths_json` is a JSON array of the local directories a transfer may +/// use; NULL clears the options, so a Volume statement returns its instruction +/// row without transferring. The options survive [`kernel_statement_set_sql`]. +/// This API takes no upload bytes, so `PUT '__input_stream__'` fails. +/// +/// # Safety +/// `stmt` must be a live statement handle; `allowed_paths_json` must be NULL or +/// a NUL-terminated UTF-8 C string. +#[no_mangle] +pub unsafe extern "C" fn kernel_statement_set_volume_options( + stmt: *mut kernel_statement_t, + allowed_paths_json: *const c_char, + remove_not_found_is_success: bool, +) -> KernelStatusCode { + with_statement(stmt, |stmt| { + let json = (!allowed_paths_json.is_null()).then(|| CStr::from_ptr(allowed_paths_json)); + let options = volume_options(json, remove_not_found_is_success)?; + stmt.spec().volume(options); + Ok(()) + }) +} + +fn volume_options( + allowed_paths_json: Option<&CStr>, + remove_not_found_is_success: bool, +) -> Result, Error> { + let Some(json) = allowed_paths_json else { + return Ok(None); + }; + let roots = json + .to_str() + .ok() + .and_then(|text| serde_json::from_str::>(text).ok()) + .ok_or_else(|| { + Error::invalid_argument().message("allowed_paths_json must be a JSON array of strings") + })?; + Ok(Some(crate::VolumeOptions::new( + roots, + remove_not_found_is_success, + ))) +} + // ─── Execute (sync) ────────────────────────────────────────────────────────── /// Wait-for-result execution. Auto-cancels + closes any prior executed @@ -818,6 +863,37 @@ pub unsafe extern "C" fn kernel_executed_statement_num_modified_rows( handle.exec.num_modified_rows().unwrap_or(-1) } +/// Whether the server marked the statement as a Volume PUT, GET or REMOVE. +/// +/// # Safety +/// `exec` must be a live executed handle and `out` must be writable. +#[no_mangle] +pub unsafe extern "C" fn kernel_executed_statement_is_volume_operation( + exec: *const kernel_executed_statement_t, + out: *mut bool, +) -> KernelStatusCode { + catch_ffi(|| { + let Some(handle) = (exec as *const ExecutedHandle).as_ref() else { + return store_invalid_arg( + "kernel_executed_statement_is_volume_operation: exec must not be null", + ); + }; + if out.is_null() { + return store_invalid_arg( + "kernel_executed_statement_is_volume_operation: out must not be null", + ); + } + if !handle.exec.is_valid() { + return store_and_code(Error::new( + crate::kernel_error::ErrorCode::InvalidStatementHandle, + "executed statement was invalidated by a re-execute or close on its parent statement", + )); + } + std::ptr::write(out, handle.exec.result_stream().is_volume_operation()); + KernelStatusCode::Success + }) +} + /// The server statement (query) id of a successfully executed statement, as a /// NUL-terminated C string. This is the success-path counterpart to the query id /// on `KernelError` (which crosses only on failure): a host driver uses it for @@ -1274,6 +1350,29 @@ mod tests { assert_eq!(rc, KernelStatusCode::InvalidArgument); } + #[test] + fn volume_options_parse_a_json_array_of_directories() { + let options = volume_options(Some(cr#"["/data","/tmp"]"#), true) + .unwrap() + .unwrap(); + assert_eq!( + options.allowed_paths, + ["/data", "/tmp"].map(std::path::PathBuf::from) + ); + assert!(options.remove_not_found_is_success); + assert!(volume_options(None, false).unwrap().is_none()); + for invalid in [c"/data", cr#"{"path":"/data"}"#] { + assert_eq!( + volume_options(Some(invalid), false).unwrap_err().code, + crate::ErrorCode::InvalidArgument + ); + } + let rc = unsafe { + kernel_statement_set_volume_options(std::ptr::null_mut(), c"[]".as_ptr(), false) + }; + assert_eq!(rc, KernelStatusCode::InvalidArgument); + } + #[test] fn canceller_null_guards_return_invalid_argument() { let mut out: *mut kernel_statement_canceller_t = std::ptr::null_mut(); diff --git a/tests/c/session_smoke.c b/tests/c/session_smoke.c index 730a216f..4aed59b2 100644 --- a/tests/c/session_smoke.c +++ b/tests/c/session_smoke.c @@ -77,6 +77,19 @@ static void test_null_guards(void) { rc = kernel_statement_set_query_tags(NULL, "team:eng"); CHECK(rc == KernelStatusCode_InvalidArgument, "statement_set_query_tags(NULL) → InvalidArgument"); + rc = kernel_statement_set_volume_options(NULL, "[]", false); + CHECK(rc == KernelStatusCode_InvalidArgument, + "statement_set_volume_options(NULL) → InvalidArgument"); + CHECK(kernel_get_last_error_code() == NULL && kernel_get_last_error_local_os_error() == 0 && + kernel_get_last_error_local_path() == NULL, + "last error without a code or local file carries none"); + bool marked = true; + rc = kernel_executed_statement_is_volume_operation(NULL, &marked); + CHECK(rc == KernelStatusCode_InvalidArgument, + "executed_statement_is_volume_operation(NULL) → InvalidArgument"); + rc = kernel_result_stream_is_volume_operation(NULL, &marked); + CHECK(rc == KernelStatusCode_InvalidArgument, + "result_stream_is_volume_operation(NULL) → InvalidArgument"); kernel_executed_statement_t* exec = (kernel_executed_statement_t*)0x1; rc = kernel_statement_execute_with_timeout_ms(NULL, 1, &exec); CHECK(rc == KernelStatusCode_InvalidArgument, From ede575538fe32ab8f8ecdcf00d8f8048e9715469 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Thu, 3 Dec 2026 02:15:16 +0000 Subject: [PATCH 2/9] test(napi): cover close cancelling an awaitResult that runs a transfer The test parks awaitResult() on a stalled Volume GET and checks that close() cancels it and returns. Also drops a blank line left in the C header. Co-authored-by: Isaac Signed-off-by: Aakash Saravanan --- include/databricks_kernel.h | 1 - napi/Cargo.lock | 1 + napi/Cargo.toml | 1 + napi/src/async_statement.rs | 108 ++++++++++++++++++++++++++++++++++++ 4 files changed, 110 insertions(+), 1 deletion(-) diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h index 762a92fc..abcbad67 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -405,7 +405,6 @@ KernelStatusCode kernel_session_config_set_sea_response_compression_enabled( KernelStatusCode kernel_session_config_set_request_timeout(KernelSessionConfig* config, uint64_t request_timeout_ms); - /* Configure the maximum number of idle HTTP connections retained per host. * `max_connections` must be greater than zero. Omitting this setter keeps the * kernel default (100). */ diff --git a/napi/Cargo.lock b/napi/Cargo.lock index c2eec113..63f0e4ab 100644 --- a/napi/Cargo.lock +++ b/napi/Cargo.lock @@ -667,6 +667,7 @@ dependencies = [ "arrow-array", "arrow-ipc", "arrow-schema", + "base64 0.22.1", "chrono", "databricks-sql-kernel", "futures", diff --git a/napi/Cargo.toml b/napi/Cargo.toml index 78326e4d..a55dab43 100644 --- a/napi/Cargo.toml +++ b/napi/Cargo.toml @@ -129,6 +129,7 @@ serde_json = "1" chrono = { version = "0.4", default-features = false, features = ["clock"] } [dev-dependencies] +base64 = "0.22" wiremock = "0.6" [build-dependencies] diff --git a/napi/src/async_statement.rs b/napi/src/async_statement.rs index 078ed52b..ce45bc0a 100644 --- a/napi/src/async_statement.rs +++ b/napi/src/async_statement.rs @@ -768,6 +768,114 @@ mod tests { connection.close().await.expect("close session"); } + /// A finished statement whose result is a Volume GET of `/object` into `local`. + fn volume_get_result(server: &MockServer, local: &str) -> serde_json::Value { + use arrow_array::{ArrayRef, RecordBatch, StringArray}; + use base64::Engine; + let names = ["operation", "presignedUrl", "headers", "localFile"]; + let url = format!("{}/object", server.uri()); + let values = ["GET", url.as_str(), "{}", local]; + let batch = + RecordBatch::try_from_iter(names.iter().zip(values).map(|(name, value)| { + (*name, Arc::new(StringArray::from(vec![value])) as ArrayRef) + })) + .unwrap(); + let mut writer = + arrow_ipc::writer::StreamWriter::try_new(Vec::new(), &batch.schema()).unwrap(); + writer.write(&batch).unwrap(); + writer.finish().unwrap(); + let columns: Vec<_> = names + .iter() + .enumerate() + .map(|(position, name)| { + json!({"name": name, "type_name": "STRING", "type_text": "STRING", "position": position}) + }) + .collect(); + json!({ + "statement_id": STATEMENT, + "status": { "state": "SUCCEEDED" }, + "manifest": { + "is_volume_operation": true, + "format": "ARROW_STREAM", + "schema": { "column_count": names.len(), "columns": columns }, + "total_chunk_count": 1, + "total_row_count": 1, + }, + "result": { + "chunk_index": 0, + "row_offset": 0, + "row_count": 1, + "attachment": base64::engine::general_purpose::STANDARD + .encode(writer.into_inner().unwrap()), + }, + }) + } + + #[tokio::test] + async fn close_cancels_an_await_result_still_running_a_transfer() { + let server = lease_server().await; + let dir = std::env::temp_dir().join(format!("napi-close-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let local = dir.join("download"); + Mock::given(method("GET")) + .and(path(format!("/api/2.0/sql/statements/{STATEMENT}"))) + .respond_with( + ResponseTemplate::new(200) + .set_body_json(volume_get_result(&server, local.to_str().unwrap())), + ) + .with_priority(1) + .mount(&server) + .await; + Mock::given(method("GET")) + .and(path("/object")) + .respond_with( + ResponseTemplate::new(200) + .set_body_string("data") + .set_delay(Duration::from_secs(60)), + ) + .mount(&server) + .await; + let connection = telemetry_connection(&server, 1_000, Duration::from_secs(300)).await; + let options = crate::connection::ExecuteOptions { + statement_conf: None, + query_tags: None, + row_limit: None, + lz4_compression: None, + positional_params: None, + named_params: None, + raw_params: None, + volume: Some(crate::connection::VolumeExecuteOptions { + allowed_paths: vec![dir.to_string_lossy().into_owned()], + remove_not_found_is_success: None, + }), + }; + let statement = connection + .submit_statement("GET".into(), Some(options)) + .await + .expect("submit"); + let closing = async { + while !server + .received_requests() + .await + .unwrap_or_default() + .iter() + .any(|request| request.url.path() == "/object") + { + tokio::time::sleep(Duration::from_millis(10)).await; + } + statement.close().await + }; + let (waited, closed) = tokio::time::timeout(Duration::from_secs(10), async { + tokio::join!(statement.await_result(), closing) + }) + .await + .expect("close must stop a running transfer instead of waiting for it"); + closed.expect("close statement"); + assert!(waited.is_err()); + connection.close().await.expect("close session"); + let _ = std::fs::remove_dir_all(&dir); + } + #[tokio::test] async fn close_releases_session_when_the_close_rpc_fails() { let server = lease_server().await; From 61d3bd64f40bbd494a72639fe009ccb702172414 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Thu, 3 Dec 2026 06:58:46 +0000 Subject: [PATCH 3/9] feat(c_abi): report the Volume marker on an async statement kernel_executed_async_statement_is_volume_operation reports whether the last status poll succeeded for a statement the server marks as a Volume PUT, GET or REMOVE. Reading its result stream runs the file transfer, so a host that polls an async statement can run only that read off its polling thread and return any other result on the same poll. The get_result_stream doc now says it runs the transfer. Co-authored-by: Isaac Signed-off-by: Aakash Saravanan --- include/databricks_kernel.h | 9 ++- src/c_abi/statement.rs | 26 +++++++++ src/statement/executed_async.rs | 11 ++++ tests/c/session_smoke.c | 3 + tests/v0_c_abi_canceller_wiremock.rs | 83 ++++++++++++++++++++++++++++ 5 files changed, 131 insertions(+), 1 deletion(-) diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h index abcbad67..062ec808 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -1022,10 +1022,17 @@ KernelStatusCode kernel_executed_async_statement_status( * state returns KernelStatusCode_InvalidArgument rather than blocking (v0 * collapses invalid-state into that code). This is single-consumption: * a second successful take is rejected. Close the stream with - * kernel_result_stream_close. */ + * kernel_result_stream_close. For a statement the server marks as a Volume + * PUT, GET or REMOVE, it runs the file transfer before returning. */ KernelStatusCode kernel_executed_async_statement_get_result_stream( kernel_executed_async_statement_t* exec, kernel_result_stream_t** out); +/* Whether the last status poll reported success for a statement the server + * marks as a Volume PUT, GET or REMOVE. False before that poll and once the + * result stream is taken. */ +KernelStatusCode kernel_executed_async_statement_is_volume_operation( + const kernel_executed_async_statement_t* exec, bool* out); + /* Most recently observed DML count, or -1 when unavailable. */ int64_t kernel_executed_async_statement_num_modified_rows( const kernel_executed_async_statement_t* exec); diff --git a/src/c_abi/statement.rs b/src/c_abi/statement.rs index 3a81c5a2..bdaba027 100644 --- a/src/c_abi/statement.rs +++ b/src/c_abi/statement.rs @@ -1158,6 +1158,32 @@ pub unsafe extern "C" fn kernel_executed_async_statement_get_result_stream( }) } +/// Whether the last status poll reported success for a statement the server +/// marks as a Volume PUT, GET or REMOVE, whose result read runs the transfer. +/// +/// # Safety +/// `exec` must be a valid pointer and `out` must be writable. +#[no_mangle] +pub unsafe extern "C" fn kernel_executed_async_statement_is_volume_operation( + exec: *const kernel_executed_async_statement_t, + out: *mut bool, +) -> KernelStatusCode { + catch_ffi(|| { + let Some(handle) = (exec as *const ExecutedAsyncHandle).as_ref() else { + return store_invalid_arg( + "kernel_executed_async_statement_is_volume_operation: exec must not be null", + ); + }; + if out.is_null() { + return store_invalid_arg( + "kernel_executed_async_statement_is_volume_operation: out must not be null", + ); + } + std::ptr::write(out, handle.exec.is_volume_operation()); + KernelStatusCode::Success + }) +} + /// Rows modified by the statement, or `-1` if unavailable / on error. /// /// # Safety diff --git a/src/statement/executed_async.rs b/src/statement/executed_async.rs index 9173f2f7..8977a2a6 100644 --- a/src/statement/executed_async.rs +++ b/src/statement/executed_async.rs @@ -579,6 +579,17 @@ impl ExecutedAsyncStatement { } } + /// Whether the last status poll reported success for a statement the server + /// marks as a Volume PUT, GET or REMOVE. False once the result is read. + pub(crate) fn is_volume_operation(&self) -> bool { + self.pending_result.lock().is_ok_and(|pending| { + pending + .as_ref() + .and_then(|response| response.manifest.as_ref()) + .is_some_and(|manifest| manifest.is_volume_operation) + }) + } + fn take_pending_result(&self) -> Option { let mut pending = self.pending_result.lock().ok()?; if self.owner_released.load(Ordering::Acquire) { diff --git a/tests/c/session_smoke.c b/tests/c/session_smoke.c index 4aed59b2..34b80cb6 100644 --- a/tests/c/session_smoke.c +++ b/tests/c/session_smoke.c @@ -90,6 +90,9 @@ static void test_null_guards(void) { rc = kernel_result_stream_is_volume_operation(NULL, &marked); CHECK(rc == KernelStatusCode_InvalidArgument, "result_stream_is_volume_operation(NULL) → InvalidArgument"); + rc = kernel_executed_async_statement_is_volume_operation(NULL, &marked); + CHECK(rc == KernelStatusCode_InvalidArgument, + "executed_async_statement_is_volume_operation(NULL) → InvalidArgument"); kernel_executed_statement_t* exec = (kernel_executed_statement_t*)0x1; rc = kernel_statement_execute_with_timeout_ms(NULL, 1, &exec); CHECK(rc == KernelStatusCode_InvalidArgument, diff --git a/tests/v0_c_abi_canceller_wiremock.rs b/tests/v0_c_abi_canceller_wiremock.rs index 4d3df1ee..94455999 100644 --- a/tests/v0_c_abi_canceller_wiremock.rs +++ b/tests/v0_c_abi_canceller_wiremock.rs @@ -63,6 +63,7 @@ use databricks_sql_kernel::c_abi::statement::{ kernel_executed_async_statement_canceller_free, kernel_executed_async_statement_canceller_new, kernel_executed_async_statement_canceller_t, kernel_executed_async_statement_close, kernel_executed_async_statement_get_result_stream, + kernel_executed_async_statement_is_volume_operation, kernel_executed_async_statement_num_modified_rows, kernel_executed_async_statement_query_id, kernel_executed_async_statement_status, kernel_executed_async_statement_t, kernel_executed_statement_close, kernel_executed_statement_get_result_stream, @@ -169,6 +170,88 @@ fn async_c_abi_submit_poll_and_materialise() { } } +#[test] +fn async_c_abi_reports_the_volume_marker_from_the_successful_status_poll() { + let rt = tokio::runtime::Runtime::new().unwrap(); + let server = rt.block_on(async { + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_close_any(&server).await; + Mock::given(method("POST")) + .and(path("/api/2.0/sql/statements")) + .respond_with(ResponseTemplate::new(200).set_body_string(running_body("stmt-volume"))) + .mount(&server) + .await; + let mut marked: serde_json::Value = + serde_json::from_str(&succeeded_empty_body("stmt-volume")).unwrap(); + marked["manifest"]["is_volume_operation"] = json!(true); + Mock::given(method("GET")) + .and(path("/api/2.0/sql/statements/stmt-volume")) + .respond_with(ResponseTemplate::new(200).set_body_string(marked.to_string())) + .mount(&server) + .await; + server + }); + + unsafe { + let session = open_session_c_abi(&server.uri()); + let mut stmt = std::ptr::null_mut(); + assert_eq!( + kernel_session_new_statement(session, &mut stmt), + KernelStatusCode::Success + ); + let sql = CString::new("GET '/Volumes/c/s/v/f' TO '/tmp/f'").unwrap(); + assert_eq!( + kernel_statement_set_sql(stmt, sql.as_ptr()), + KernelStatusCode::Success + ); + let mut exec: *mut kernel_executed_async_statement_t = std::ptr::null_mut(); + assert_eq!( + kernel_statement_submit(stmt, &mut exec), + KernelStatusCode::Success + ); + let mut volume = true; + assert_eq!( + kernel_executed_async_statement_is_volume_operation(exec, &mut volume), + KernelStatusCode::Success + ); + assert!(!volume, "the RUNNING submit response carries no result"); + + let mut status = KernelStatementStatusKind::Pending; + assert_eq!( + kernel_executed_async_statement_status(exec, &mut status), + KernelStatusCode::Success + ); + assert_eq!(status, KernelStatementStatusKind::Succeeded); + assert_eq!( + kernel_executed_async_statement_is_volume_operation(exec, &mut volume), + KernelStatusCode::Success + ); + assert!(volume); + + let mut stream: *mut kernel_result_stream_t = std::ptr::null_mut(); + assert_eq!( + kernel_executed_async_statement_get_result_stream(exec, &mut stream), + KernelStatusCode::Success + ); + assert_eq!( + kernel_executed_async_statement_is_volume_operation(exec, &mut volume), + KernelStatusCode::Success + ); + assert!(!volume, "reading the result consumes the status response"); + assert_eq!( + kernel_result_stream_close(stream), + KernelStatusCode::Success + ); + assert_eq!( + kernel_executed_async_statement_close(exec), + KernelStatusCode::Success + ); + assert_eq!(kernel_statement_close(stmt), KernelStatusCode::Success); + assert_eq!(kernel_session_close(session), KernelStatusCode::Success); + } +} + #[test] fn async_c_abi_query_timeout_expires_across_status_polls() { let rt = tokio::runtime::Runtime::new().unwrap(); From 6b7ab90791515d5cffd6eef34473514951382312 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Thu, 3 Dec 2026 16:39:15 +0000 Subject: [PATCH 4/9] fix(statement): report no Volume marker once the async owner is released is_volume_operation now checks owner_released, as take_pending_result does, so it cannot report a status response the released owner no longer serves. Co-authored-by: Isaac Signed-off-by: Aakash Saravanan --- src/statement/executed_async.rs | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/src/statement/executed_async.rs b/src/statement/executed_async.rs index 8977a2a6..22d3e60f 100644 --- a/src/statement/executed_async.rs +++ b/src/statement/executed_async.rs @@ -580,14 +580,16 @@ impl ExecutedAsyncStatement { } /// Whether the last status poll reported success for a statement the server - /// marks as a Volume PUT, GET or REMOVE. False once the result is read. + /// marks as a Volume PUT, GET or REMOVE. False once the result is read or + /// the owning handle is released. pub(crate) fn is_volume_operation(&self) -> bool { - self.pending_result.lock().is_ok_and(|pending| { - pending - .as_ref() - .and_then(|response| response.manifest.as_ref()) - .is_some_and(|manifest| manifest.is_volume_operation) - }) + !self.owner_released.load(Ordering::Acquire) + && self.pending_result.lock().is_ok_and(|pending| { + pending + .as_ref() + .and_then(|response| response.manifest.as_ref()) + .is_some_and(|manifest| manifest.is_volume_operation) + }) } fn take_pending_result(&self) -> Option { From d10b9f021801c2a6aaff4d9d905d6f77d63c33bb Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Thu, 3 Dec 2026 16:51:24 +0000 Subject: [PATCH 5/9] test(volume): cover the C ABI transfer path and the ADBC option round trip A C ABI test sets the Volume options on a live statement, checks that a GET writes the file, and checks that a missing PUT source reports its error code, OS error and path to the calling thread. The ADBC test now reads the option back, clears it with JSON null and rejects other JSON, as the README says. Co-authored-by: Isaac Signed-off-by: Aakash Saravanan --- adbc/src/statement.rs | 18 ++++ tests/v0_c_abi_canceller_wiremock.rs | 130 ++++++++++++++++++++++++++- 2 files changed, 144 insertions(+), 4 deletions(-) diff --git a/adbc/src/statement.rs b/adbc/src/statement.rs index 8d401845..a4f6fa5d 100644 --- a/adbc/src/statement.rs +++ b/adbc/src/statement.rs @@ -1835,6 +1835,24 @@ mod tests { ]) .unwrap(); let mut connection = database.new_connection().unwrap(); + // The option reads back as set, clears with JSON null and rejects other JSON. + let mut options = connection.new_statement().unwrap(); + let key = || OptionStatement::Other(STAGING_ALLOWED_PATHS_OPTION.into()); + options + .set_option(key(), r#"["/tmp/files"]"#.into()) + .unwrap(); + assert_eq!( + options.get_option_string(key()).unwrap(), + r#"["/tmp/files"]"# + ); + options.set_option(key(), "null".into()).unwrap(); + assert_eq!( + options.get_option_string(key()).unwrap_err().status, + Status::NotFound + ); + let error = options.set_option(key(), "{}".into()).unwrap_err(); + assert_eq!(error.status, Status::InvalidArguments); + drop(options); let mut statement = |sql: &str, staging: bool| { let mut statement = connection.new_statement().unwrap(); statement.set_sql_query(sql).unwrap(); diff --git a/tests/v0_c_abi_canceller_wiremock.rs b/tests/v0_c_abi_canceller_wiremock.rs index 94455999..df55e4bf 100644 --- a/tests/v0_c_abi_canceller_wiremock.rs +++ b/tests/v0_c_abi_canceller_wiremock.rs @@ -44,12 +44,15 @@ use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::sync::Arc; use std::time::{Duration, Instant}; -use arrow_array::{Int64Array, RecordBatch}; +use arrow_array::{Int64Array, RecordBatch, StringArray}; use arrow_ipc::writer::StreamWriter; use arrow_schema::{DataType, Field, Schema}; use base64::{engine::general_purpose::STANDARD, Engine}; -use databricks_sql_kernel::c_abi::error::{kernel_get_last_error, KernelError}; +use databricks_sql_kernel::c_abi::error::{ + kernel_get_last_error, kernel_get_last_error_code, kernel_get_last_error_local_os_error, + kernel_get_last_error_local_path, KernelError, +}; use databricks_sql_kernel::c_abi::result::{ kernel_result_stream_close, kernel_result_stream_t, kernel_result_stream_try_next_batch, }; @@ -71,8 +74,9 @@ use databricks_sql_kernel::c_abi::statement::{ kernel_statement_bind_parameter, kernel_statement_canceller_cancel, kernel_statement_canceller_free, kernel_statement_canceller_new, kernel_statement_canceller_t, kernel_statement_close, kernel_statement_execute, kernel_statement_execute_with_timeout_ms, - kernel_statement_set_sql, kernel_statement_submit, kernel_statement_submit_with_timeout_ms, - kernel_statement_t, KernelStatementStatusKind, MAX_CLIENT_QUERY_TIMEOUT_MS, + kernel_statement_set_sql, kernel_statement_set_volume_options, kernel_statement_submit, + kernel_statement_submit_with_timeout_ms, kernel_statement_t, KernelStatementStatusKind, + MAX_CLIENT_QUERY_TIMEOUT_MS, }; use databricks_sql_kernel::c_abi::KernelStatusCode; use serde_json::json; @@ -252,6 +256,78 @@ fn async_c_abi_reports_the_volume_marker_from_the_successful_status_poll() { } } +#[test] +fn volume_options_run_the_transfer_and_local_errors_reach_the_caller() { + let dir = tempfile::tempdir().unwrap(); + let download = dir.path().join("download"); + let missing = dir.path().join("missing"); + let allowed = CString::new(serde_json::to_string(&[dir.path()]).unwrap()).unwrap(); + for (operation, local) in [("GET", &download), ("PUT", &missing)] { + let rt = tokio::runtime::Runtime::new().unwrap(); + let server = rt.block_on(async { + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_close_any(&server).await; + let body = + volume_instruction_body(operation, &format!("{}/object", server.uri()), local); + Mock::given(method("POST")) + .and(path("/api/2.0/sql/statements")) + .respond_with(ResponseTemplate::new(200).set_body_string(body)) + .mount(&server) + .await; + Mock::given(method("GET")) + .and(path("/object")) + .respond_with(ResponseTemplate::new(200).set_body_string("data")) + .mount(&server) + .await; + server + }); + + unsafe { + let session = open_session_c_abi(&server.uri()); + let mut stmt = std::ptr::null_mut(); + assert_eq!( + kernel_session_new_statement(session, &mut stmt), + KernelStatusCode::Success + ); + let sql = CString::new(format!("{operation} '/Volumes/c/s/v/f'")).unwrap(); + assert_eq!( + kernel_statement_set_sql(stmt, sql.as_ptr()), + KernelStatusCode::Success + ); + assert_eq!( + kernel_statement_set_volume_options(stmt, allowed.as_ptr(), false), + KernelStatusCode::Success + ); + let mut exec: *mut kernel_executed_statement_t = std::ptr::null_mut(); + let rc = kernel_statement_execute(stmt, &mut exec); + if operation == "GET" { + assert_eq!(rc, KernelStatusCode::Success); + assert_eq!(std::fs::read(&download).unwrap(), b"data"); + assert_eq!( + kernel_executed_statement_close(exec), + KernelStatusCode::Success + ); + } else { + assert_ne!(rc, KernelStatusCode::Success); + assert_eq!( + std::ffi::CStr::from_ptr(kernel_get_last_error_code()).to_str(), + Ok("VOLUME_LOCAL_FILE_ERROR") + ); + assert_eq!( + std::io::Error::from_raw_os_error(kernel_get_last_error_local_os_error()) + .kind(), + std::io::ErrorKind::NotFound + ); + let reported = std::ffi::CStr::from_ptr(kernel_get_last_error_local_path()); + assert!(reported.to_str().unwrap().ends_with("missing")); + } + assert_eq!(kernel_statement_close(stmt), KernelStatusCode::Success); + assert_eq!(kernel_session_close(session), KernelStatusCode::Success); + } + } +} + #[test] fn async_c_abi_query_timeout_expires_across_status_polls() { let rt = tokio::runtime::Runtime::new().unwrap(); @@ -882,6 +958,52 @@ fn arrow_ipc_bytes(batch: &RecordBatch) -> Vec { buf } +/// A SUCCEEDED body the server marks as a Volume operation, with one +/// `operation` instruction row for `local`. +fn volume_instruction_body(operation: &str, url: &str, local: &std::path::Path) -> String { + let names = ["operation", "presignedUrl", "headers", "localFile"]; + let values = [operation, url, "{}", local.to_str().unwrap()]; + let schema = Arc::new(Schema::new( + names + .iter() + .map(|name| Field::new(*name, DataType::Utf8, true)) + .collect::>(), + )); + let columns = values + .iter() + .map(|value| Arc::new(StringArray::from(vec![*value])) as _) + .collect(); + let ipc = arrow_ipc_bytes(&RecordBatch::try_new(schema, columns).unwrap()); + let columns: Vec<_> = names + .iter() + .enumerate() + .map(|(position, name)| { + json!({"name": name, "type_name": "STRING", "type_text": "STRING", "position": position}) + }) + .collect(); + json!({ + "statement_id": "stmt-volume", + "status": { "state": "SUCCEEDED" }, + "manifest": { + "is_volume_operation": true, + "format": "ARROW_STREAM", + "schema": { "column_count": 4, "columns": columns }, + "total_chunk_count": 1, + "total_row_count": 1, + "total_byte_count": ipc.len() as i64, + "truncated": false, + }, + "result": { + "chunk_index": 0, + "row_offset": 0, + "row_count": 1, + "byte_count": ipc.len() as i64, + "attachment": STANDARD.encode(&ipc), + }, + }) + .to_string() +} + /// A terminal SUCCEEDED body whose result set is a single-row SEA DML count /// (`num_affected_rows`, …). The SEA status envelope carries NO row count for /// DML — the count rides in the result set and is derived on materialisation — From 9943c8b4fc6076c623a8a4e7b6055745550e4efc Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Thu, 3 Dec 2026 17:00:56 +0000 Subject: [PATCH 6/9] fix(c_abi): report InvalidStatementHandle for a stale async Volume marker kernel_executed_async_statement_is_volume_operation now checks the handle's validity, as kernel_executed_statement_is_volume_operation does, so after the parent statement is re-executed or closed it reports InvalidStatementHandle instead of a cached marker. Co-authored-by: Isaac Signed-off-by: Aakash Saravanan --- include/databricks_kernel.h | 3 ++- src/c_abi/statement.rs | 9 +++++++-- src/statement/executed_async.rs | 10 ++++++---- tests/v0_c_abi_canceller_wiremock.rs | 14 ++++++++++++++ 4 files changed, 29 insertions(+), 7 deletions(-) diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h index 062ec808..35fc9c4e 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -1029,7 +1029,8 @@ KernelStatusCode kernel_executed_async_statement_get_result_stream( /* Whether the last status poll reported success for a statement the server * marks as a Volume PUT, GET or REMOVE. False before that poll and once the - * result stream is taken. */ + * result stream is taken. Returns KernelStatusCode_InvalidStatementHandle + * after the parent statement is re-executed or closed. */ KernelStatusCode kernel_executed_async_statement_is_volume_operation( const kernel_executed_async_statement_t* exec, bool* out); diff --git a/src/c_abi/statement.rs b/src/c_abi/statement.rs index bdaba027..3dd9f7a1 100644 --- a/src/c_abi/statement.rs +++ b/src/c_abi/statement.rs @@ -1179,8 +1179,13 @@ pub unsafe extern "C" fn kernel_executed_async_statement_is_volume_operation( "kernel_executed_async_statement_is_volume_operation: out must not be null", ); } - std::ptr::write(out, handle.exec.is_volume_operation()); - KernelStatusCode::Success + match handle.exec.is_volume_operation() { + Ok(volume) => { + std::ptr::write(out, volume); + KernelStatusCode::Success + } + Err(error) => store_and_code(error), + } }) } diff --git a/src/statement/executed_async.rs b/src/statement/executed_async.rs index 22d3e60f..5321f053 100644 --- a/src/statement/executed_async.rs +++ b/src/statement/executed_async.rs @@ -581,15 +581,17 @@ impl ExecutedAsyncStatement { /// Whether the last status poll reported success for a statement the server /// marks as a Volume PUT, GET or REMOVE. False once the result is read or - /// the owning handle is released. - pub(crate) fn is_volume_operation(&self) -> bool { - !self.owner_released.load(Ordering::Acquire) + /// the owning handle is released, and `InvalidStatementHandle` once the + /// parent statement is re-executed or closed. + pub(crate) fn is_volume_operation(&self) -> Result { + self.valid.check()?; + Ok(!self.owner_released.load(Ordering::Acquire) && self.pending_result.lock().is_ok_and(|pending| { pending .as_ref() .and_then(|response| response.manifest.as_ref()) .is_some_and(|manifest| manifest.is_volume_operation) - }) + })) } fn take_pending_result(&self) -> Option { diff --git a/tests/v0_c_abi_canceller_wiremock.rs b/tests/v0_c_abi_canceller_wiremock.rs index df55e4bf..d333d457 100644 --- a/tests/v0_c_abi_canceller_wiremock.rs +++ b/tests/v0_c_abi_canceller_wiremock.rs @@ -247,6 +247,20 @@ fn async_c_abi_reports_the_volume_marker_from_the_successful_status_poll() { kernel_result_stream_close(stream), KernelStatusCode::Success ); + let mut next: *mut kernel_executed_async_statement_t = std::ptr::null_mut(); + assert_eq!( + kernel_statement_submit(stmt, &mut next), + KernelStatusCode::Success + ); + assert_eq!( + kernel_executed_async_statement_is_volume_operation(exec, &mut volume), + KernelStatusCode::InvalidStatementHandle, + "a re-execute invalidates the earlier handle" + ); + assert_eq!( + kernel_executed_async_statement_close(next), + KernelStatusCode::Success + ); assert_eq!( kernel_executed_async_statement_close(exec), KernelStatusCode::Success From 5d5bd541058097cf62317b3fb8f0472875e86738 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Thu, 3 Dec 2026 19:42:45 +0000 Subject: [PATCH 7/9] test(c_abi): pin NotFound for a missing PUT source Co-authored-by: Isaac Signed-off-by: Aakash Saravanan --- tests/v0_c_abi_canceller_wiremock.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/v0_c_abi_canceller_wiremock.rs b/tests/v0_c_abi_canceller_wiremock.rs index d333d457..661565db 100644 --- a/tests/v0_c_abi_canceller_wiremock.rs +++ b/tests/v0_c_abi_canceller_wiremock.rs @@ -323,7 +323,7 @@ fn volume_options_run_the_transfer_and_local_errors_reach_the_caller() { KernelStatusCode::Success ); } else { - assert_ne!(rc, KernelStatusCode::Success); + assert_eq!(rc, KernelStatusCode::NotFound); assert_eq!( std::ffi::CStr::from_ptr(kernel_get_last_error_code()).to_str(), Ok("VOLUME_LOCAL_FILE_ERROR") From 0049af3d8689206fc17e535ee83864794548a6df Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Thu, 3 Dec 2026 19:53:00 +0000 Subject: [PATCH 8/9] fix(napi): let close() stop a running call without waiting on its cancel close() awaited the server cancel request before taking the statement, so a slow or retrying cancel endpoint held it after the transfer had already stopped locally. The cancel now runs as its own task. The C ABI is_volume_operation accessors also write false to out before reporting an error, as get_result_stream writes null. Co-authored-by: Isaac Signed-off-by: Aakash Saravanan --- napi/src/async_statement.rs | 8 ++++++-- src/c_abi/result.rs | 1 + src/c_abi/statement.rs | 2 ++ tests/v0_c_abi_canceller_wiremock.rs | 2 ++ 4 files changed, 11 insertions(+), 2 deletions(-) diff --git a/napi/src/async_statement.rs b/napi/src/async_statement.rs index ce45bc0a..7135d33b 100644 --- a/napi/src/async_statement.rs +++ b/napi/src/async_statement.rs @@ -391,14 +391,18 @@ impl AsyncStatement { let taken = match inner.try_lock() { Ok(mut guard) => guard.take(), // A call still running holds `inner` until it returns, such as an - // `awaitResult()` and its Volume transfer, so cancel it first. + // `awaitResult()` and its Volume transfer, so cancel it first. The + // cancel stops a transfer at once, and close does not wait for its + // server request. Err(_) => { let in_flight = canceller .lock() .unwrap_or_else(PoisonError::into_inner) .clone(); if let Some(in_flight) = in_flight { - let _ = in_flight.cancel().await; + tokio::spawn(async move { + let _ = in_flight.cancel().await; + }); } inner.lock().await.take() } diff --git a/src/c_abi/result.rs b/src/c_abi/result.rs index 2ad60a91..af31947b 100644 --- a/src/c_abi/result.rs +++ b/src/c_abi/result.rs @@ -637,6 +637,7 @@ pub unsafe extern "C" fn kernel_result_stream_is_volume_operation( if stream.is_null() || out.is_null() { return store_invalid_arg("kernel_result_stream_is_volume_operation: null pointer"); } + std::ptr::write(out, false); let p = stream as *const ResultStreamInner; let marked = match &*std::ptr::addr_of!((*p).shape) { ResultStreamShape::Owned { stream, .. } => stream.is_volume_operation(), diff --git a/src/c_abi/statement.rs b/src/c_abi/statement.rs index 3dd9f7a1..cf469f4d 100644 --- a/src/c_abi/statement.rs +++ b/src/c_abi/statement.rs @@ -883,6 +883,7 @@ pub unsafe extern "C" fn kernel_executed_statement_is_volume_operation( "kernel_executed_statement_is_volume_operation: out must not be null", ); } + std::ptr::write(out, false); if !handle.exec.is_valid() { return store_and_code(Error::new( crate::kernel_error::ErrorCode::InvalidStatementHandle, @@ -1179,6 +1180,7 @@ pub unsafe extern "C" fn kernel_executed_async_statement_is_volume_operation( "kernel_executed_async_statement_is_volume_operation: out must not be null", ); } + std::ptr::write(out, false); match handle.exec.is_volume_operation() { Ok(volume) => { std::ptr::write(out, volume); diff --git a/tests/v0_c_abi_canceller_wiremock.rs b/tests/v0_c_abi_canceller_wiremock.rs index 661565db..a4f70879 100644 --- a/tests/v0_c_abi_canceller_wiremock.rs +++ b/tests/v0_c_abi_canceller_wiremock.rs @@ -252,11 +252,13 @@ fn async_c_abi_reports_the_volume_marker_from_the_successful_status_poll() { kernel_statement_submit(stmt, &mut next), KernelStatusCode::Success ); + volume = true; assert_eq!( kernel_executed_async_statement_is_volume_operation(exec, &mut volume), KernelStatusCode::InvalidStatementHandle, "a re-execute invalidates the earlier handle" ); + assert!(!volume, "an error still writes false"); assert_eq!( kernel_executed_async_statement_close(next), KernelStatusCode::Success From 7a5f9f710d23e053b6386ed4360b429915017245 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Thu, 3 Dec 2026 21:10:50 +0000 Subject: [PATCH 9/9] test(c_abi): check the Volume marker on live executed handles and streams The live GET now reads kernel_executed_statement_is_volume_operation and kernel_result_stream_is_volume_operation on the stream borrowed from the executed handle, and the async test reads it on the stream the async read owns, so both stream shapes are covered. Co-authored-by: Isaac Signed-off-by: Aakash Saravanan --- tests/v0_c_abi_canceller_wiremock.rs | 40 +++++++++++++++++++++++----- 1 file changed, 34 insertions(+), 6 deletions(-) diff --git a/tests/v0_c_abi_canceller_wiremock.rs b/tests/v0_c_abi_canceller_wiremock.rs index a4f70879..7682587d 100644 --- a/tests/v0_c_abi_canceller_wiremock.rs +++ b/tests/v0_c_abi_canceller_wiremock.rs @@ -54,7 +54,8 @@ use databricks_sql_kernel::c_abi::error::{ kernel_get_last_error_local_path, KernelError, }; use databricks_sql_kernel::c_abi::result::{ - kernel_result_stream_close, kernel_result_stream_t, kernel_result_stream_try_next_batch, + kernel_result_stream_close, kernel_result_stream_is_volume_operation, kernel_result_stream_t, + kernel_result_stream_try_next_batch, }; use databricks_sql_kernel::c_abi::session::{ kernel_session_close, kernel_session_config_new, kernel_session_config_set_auth_pat, @@ -70,11 +71,12 @@ use databricks_sql_kernel::c_abi::statement::{ kernel_executed_async_statement_num_modified_rows, kernel_executed_async_statement_query_id, kernel_executed_async_statement_status, kernel_executed_async_statement_t, kernel_executed_statement_close, kernel_executed_statement_get_result_stream, - kernel_executed_statement_query_id, kernel_executed_statement_t, - kernel_statement_bind_parameter, kernel_statement_canceller_cancel, - kernel_statement_canceller_free, kernel_statement_canceller_new, kernel_statement_canceller_t, - kernel_statement_close, kernel_statement_execute, kernel_statement_execute_with_timeout_ms, - kernel_statement_set_sql, kernel_statement_set_volume_options, kernel_statement_submit, + kernel_executed_statement_is_volume_operation, kernel_executed_statement_query_id, + kernel_executed_statement_t, kernel_statement_bind_parameter, + kernel_statement_canceller_cancel, kernel_statement_canceller_free, + kernel_statement_canceller_new, kernel_statement_canceller_t, kernel_statement_close, + kernel_statement_execute, kernel_statement_execute_with_timeout_ms, kernel_statement_set_sql, + kernel_statement_set_volume_options, kernel_statement_submit, kernel_statement_submit_with_timeout_ms, kernel_statement_t, KernelStatementStatusKind, MAX_CLIENT_QUERY_TIMEOUT_MS, }; @@ -243,6 +245,11 @@ fn async_c_abi_reports_the_volume_marker_from_the_successful_status_poll() { KernelStatusCode::Success ); assert!(!volume, "reading the result consumes the status response"); + assert_eq!( + kernel_result_stream_is_volume_operation(stream, &mut volume), + KernelStatusCode::Success + ); + assert!(volume, "a stream the async read owns"); assert_eq!( kernel_result_stream_close(stream), KernelStatusCode::Success @@ -320,6 +327,27 @@ fn volume_options_run_the_transfer_and_local_errors_reach_the_caller() { if operation == "GET" { assert_eq!(rc, KernelStatusCode::Success); assert_eq!(std::fs::read(&download).unwrap(), b"data"); + let mut marked = false; + assert_eq!( + kernel_executed_statement_is_volume_operation(exec, &mut marked), + KernelStatusCode::Success + ); + assert!(marked); + let mut stream: *mut kernel_result_stream_t = std::ptr::null_mut(); + assert_eq!( + kernel_executed_statement_get_result_stream(exec, &mut stream), + KernelStatusCode::Success + ); + marked = false; + assert_eq!( + kernel_result_stream_is_volume_operation(stream, &mut marked), + KernelStatusCode::Success + ); + assert!(marked, "a stream borrowed from the executed handle"); + assert_eq!( + kernel_result_stream_close(stream), + KernelStatusCode::Success + ); assert_eq!( kernel_executed_statement_close(exec), KernelStatusCode::Success