diff --git a/Cargo.lock b/Cargo.lock index b47213ce..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", @@ -2383,9 +2384,9 @@ 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", diff --git a/Cargo.toml b/Cargo.toml index f428c382..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. @@ -91,7 +92,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 @@ -145,10 +146,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..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", @@ -678,6 +679,7 @@ dependencies = [ "serde", "serde_json", "sha2 0.11.1", + "tempfile", "thiserror 2.0.21", "tokio", "tokio-util", @@ -2169,9 +2171,9 @@ 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", diff --git a/adbc/README.md b/adbc/README.md index 7b5bac0f..58b1993e 100644 --- a/adbc/README.md +++ b/adbc/README.md @@ -128,6 +128,13 @@ 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. 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` meaning unlimited), a millisecond Databricks client-timeout alias, server diff --git a/adbc/src/statement.rs b/adbc/src/statement.rs index 1a6b5899..b0371f59 100644 --- a/adbc/src/statement.rs +++ b/adbc/src/statement.rs @@ -470,6 +470,18 @@ 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 or null", + Status::InvalidArguments, + ) + })?; + self.inner()?.spec().staging_allowed_local_paths = paths; + Ok(()) + } ENABLE_DIRECT_RESULTS_OPTION => { self.enable_direct_results = expect_bool_string(value, key)?; Ok(()) @@ -584,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( @@ -1462,6 +1480,76 @@ 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()); + assert_eq!(statement.get_option_string(option.clone()).unwrap(), "null"); + for (value, expected) in [ + ("[]", Some(vec![])), + ("null", None), + (r#"["/tmp/files"]"#, Some(vec!["/tmp/files".to_owned()])), + ] { + statement.set_option(option.clone(), value.into()).unwrap(); + assert_eq!( + statement + .inner() + .unwrap() + .spec() + .staging_allowed_local_paths, + expected + ); + assert_eq!(statement.get_option_string(option.clone()).unwrap(), value); + } + let error = statement + .set_option(option.clone(), "{}".into()) + .unwrap_err(); + assert_eq!(error.status, Status::InvalidArguments); + assert_eq!( + statement + .inner() + .unwrap() + .spec() + .staging_allowed_local_paths, + Some(vec!["/tmp/files".to_owned()]) + ); + assert_eq!( + statement.get_option_string(option).unwrap(), + r#"["/tmp/files"]"# + ); + } + fn batch(rows: usize) -> RecordBatch { let schema = Arc::new(Schema::new(vec![ Field::new("id", DataType::Int64, false), diff --git a/adbc/tests/live.rs b/adbc/tests/live.rs index 54f8deec..2fd0c978 100644 --- a/adbc/tests/live.rs +++ b/adbc/tests/live.rs @@ -366,3 +366,94 @@ 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 = required_env("DATABRICKS_VOLUME_TEST_CATALOG"); + 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()); + 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", + 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()); + } + 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()?; + } + 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/include/databricks_kernel.h b/include/databricks_kernel.h index e167f181..74645d59 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 @@ -688,6 +700,11 @@ 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; 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); + /* 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/Cargo.lock b/napi/Cargo.lock index 303fb234..1183feb7 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", @@ -638,6 +639,7 @@ dependencies = [ "serde", "serde_json", "sha2 0.11.0", + "tempfile", "thiserror 2.0.19", "tokio", "tokio-util", @@ -659,6 +661,7 @@ dependencies = [ "chrono", "databricks-sql-kernel", "futures", + "libloading", "napi", "napi-build", "napi-derive", @@ -796,6 +799,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 +1502,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 +2215,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 +2574,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/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/index.d.ts b/napi/index.d.ts index bcb54502..e0e82327 100644 --- a/napi/index.d.ts +++ b/napi/index.d.ts @@ -38,6 +38,11 @@ * path is the one the production code uses. */ export interface ExecuteOptions { + /** + * 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 * session-level `sessionConf` at execute time; this map wins diff --git a/napi/src/connection.rs b/napi/src/connection.rs index 7aba91ff..8de29311 100644 --- a/napi/src/connection.rs +++ b/napi/src/connection.rs @@ -102,6 +102,9 @@ 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 /// Vec corresponds to the `i+1`-th `?` placeholder in the SQL. /// Each entry is a `{ sqlType, value }` pair — `value` is the @@ -193,6 +196,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 +204,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 +327,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 +353,7 @@ impl Connection { positional_params, named_params, raw_params, + staging_allowed_local_paths, )? // session lock released here }; @@ -405,6 +414,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 +430,7 @@ impl Connection { positional_params, named_params, raw_params, + staging_allowed_local_paths, )? }; @@ -478,6 +491,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 +514,7 @@ impl Connection { positional_params, named_params, raw_params, + staging_allowed_local_paths, )? // session lock released here }; @@ -553,6 +570,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 +596,7 @@ impl Connection { positional_params, named_params, raw_params, + staging_allowed_local_paths, )? // session lock released here }; @@ -759,6 +780,7 @@ mod tests { vec![], vec![], vec![raw()], + None, ) .expect("raw statement builds"); let dispatched_err = raw_stmt @@ -792,6 +814,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 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 ⇒ diff --git a/napi/src/error.rs b/napi/src/error.rs index 70518fe3..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); @@ -143,6 +130,19 @@ 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)); + } + 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 // Thrift driver's `TGetOperationStatusResp` exposes. Only @@ -169,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 @@ -195,6 +220,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() { @@ -298,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. @@ -333,8 +336,11 @@ mod tests { e.http_status = Some(503); e.retryable = true; e.query_id = Some("01eedeadbeefdeadbeefdeadbeefdead".to_string()); - // Thrift-parity extension fields: populated too so the - // superset relation is exercised in the same fixture. + e.os_error = Some(Box::new(OsError { + code: 13, + filename: Some("requested/local-file".to_string()), + operation: Some("stat"), + })); 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()); @@ -352,42 +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 @@ -404,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(); assert_eq!( obj.len(), - expected_total, - "envelope has unexpected extra keys. expected pyo3 parity \ - {pyo3_parity_keys:?} + thrift parity {thrift_parity_keys:?}, \ - got: {:?}", + expected_keys.len(), + "envelope has unexpected extra keys. expected {expected_keys:?}, got: {:?}", obj.keys().collect::>() ); } @@ -482,6 +474,10 @@ mod tests { "httpStatus", "retryable", "queryId", + "osErrorCode", + "osErrorFilename", + "osErrorOperation", + "osErrorNodeErrno", // Thrift-parity extension fields also follow the // omit-when-None convention. "displayMessage", @@ -496,6 +492,20 @@ 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, + 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/Cargo.lock b/pyo3/Cargo.lock index 30946d3c..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", @@ -634,6 +635,7 @@ dependencies = [ "serde", "serde_json", "sha2 0.11.0", + "tempfile", "thiserror 2.0.19", "tokio", "tokio-util", @@ -769,6 +771,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 +1431,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 +2126,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 +2491,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/pyo3/src/errors.rs b/pyo3/src/errors.rs index 88ff4257..74b8425f 100644 --- a/pyo3/src/errors.rs +++ b/pyo3/src/errors.rs @@ -70,12 +70,16 @@ fn attach_attrs( display_message: Option<&str>, 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)?; 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("os_error_filename", os_error_filename)?; bound.setattr("http_status", http_status)?; bound.setattr("retryable", retryable)?; bound.setattr("query_id", query_id)?; @@ -138,6 +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.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 @@ -182,9 +188,49 @@ pub(crate) fn closed_err(handle_name: &str) -> PyErr { None, None, None, + None, + None, ) { return setattr_err; } py_err }) } + +#[cfg(test)] +mod tests { + use super::*; + use databricks_sql_kernel::kernel_error::OsError; + + #[test] + fn local_os_error_code_crosses_python_boundary() { + Python::initialize(); + Python::attach(|py| { + for raw in [None, Some(13)] { + let mut error = KError::new(ErrorCode::NotFound, "missing file"); + error.os_error = raw.map(|code| { + Box::new(OsError { + code, + filename: Some("local-file.bin".to_owned()), + operation: None, + }) + }); + let mapped = to_py_err(py, error); + let actual: Option = mapped + .value(py) + .getattr("os_error_code") + .unwrap() + .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/pyo3/src/statement.rs b/pyo3/src/statement.rs index 7f2dc3e8..7e6dbdf9 100644 --- a/pyo3/src/statement.rs +++ b/pyo3/src/statement.rs @@ -66,6 +66,22 @@ impl Statement { Ok(()) } + /// 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, + 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(()) + } + /// 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/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/c_abi/error.rs b/src/c_abi/error.rs index f5243007..7ddbc596 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,53 @@ 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()), + operation: None, + })); + 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()), + operation: None, + })); + 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 +307,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(); } diff --git a/src/c_abi/statement.rs b/src/c_abi/statement.rs index 5f10c9dd..85ace551 100644 --- a/src/c_abi/statement.rs +++ b/src/c_abi/statement.rs @@ -159,6 +159,34 @@ pub enum KernelStatementStatusKind { Closed = 5, } +/// 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; 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, + paths_json: *const c_char, + retain_result: bool, +) -> KernelStatusCode { + with_statement(stmt, |stmt| { + 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(()) + }) +} + // ─── Crate-internal raw-handle helpers ─────────────────────────────────────── /// Box a [`Statement`] and erase it to the opaque C handle type. @@ -623,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. /// @@ -669,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 })) { @@ -1243,6 +1271,78 @@ 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"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), + 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_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); + } + 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/client/http.rs b/src/client/http.rs index e5f9ad0b..495d18ff 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. /// @@ -383,6 +397,8 @@ 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, @@ -499,6 +515,8 @@ impl DatabricksHttpClient { Ok(Self { client, + volume_client: OnceLock::new(), + allow_loopback_plaintext_storage: false, config, auth_provider: OnceLock::new(), retry_configs, @@ -736,6 +754,24 @@ impl DatabricksHttpClient { &self.client } + pub(crate) fn volume_client(&self) -> Result<&Client> { + // Transfer instructions authorize one URL; redirects must not forward their headers. + 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 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::Sea) + .cloned() + .unwrap_or_default() + } + /// Get the authorization header value. /// /// Returns an error if the auth provider has not been set via `set_auth_provider()`. @@ -1081,6 +1117,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()) } @@ -1560,6 +1617,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(); 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/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/client/sea.rs b/src/client/sea.rs index 7003150f..4a5e03fd 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()?; @@ -2404,6 +2401,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/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/kernel_error.rs b/src/kernel_error.rs index ecfb7fb2..a71d46e9 100644 --- a/src/kernel_error.rs +++ b/src/kernel_error.rs @@ -158,6 +158,17 @@ 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, + /// Logical filesystem operation when the failing API identifies it. + pub operation: Option<&'static str>, +} + /// Typed kernel error. /// /// `cause` chains preserve the underlying provenance — a `SqlError` @@ -197,6 +208,9 @@ pub struct Error { /// the string `error_code` themselves. pub vendor_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, @@ -262,6 +276,7 @@ impl Error { sql_state: None, error_code: None, vendor_code: None, + os_error: None, http_status: None, retryable: false, query_id: None, 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..e08ac229 100644 --- a/src/reader/mod.rs +++ b/src/reader/mod.rs @@ -1460,6 +1460,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, @@ -1975,9 +1976,9 @@ mod tests { ) -> Result { unreachable!() } - async fn fetch_completed_result( + async fn completed_result( &self, - _: &str, + _: ExecuteResponse, _: crate::client::SessionAttribution, ) -> Result> { unreachable!() @@ -2134,6 +2135,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 ccb3fd0d..c60609eb 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, @@ -367,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}")) - })?, - ); + })?; + // 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 // discovery endpoint. @@ -453,7 +457,7 @@ impl Session { &config.connection, &config.auth, config.driver_system_configuration.clone(), - http_client, + http_client.clone(), session_info.session_id.clone(), )); telemetry @@ -473,6 +477,7 @@ impl Session { Ok(Session { inner: Arc::new(SessionInner { transport, + http_client, session_id: session_info.session_id, config, runtime_handle, @@ -1751,6 +1756,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] @@ -3049,8 +3060,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..f5d6cbf5 100644 --- a/src/statement/executed_async.rs +++ b/src/statement/executed_async.rs @@ -221,6 +221,10 @@ 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>, + pub(crate) volume_options: super::volume::VolumeOptions, + pub(super) volume_completion: Arc, statement_telemetry: StatementTelemetry, /// Set once result materialisation hands success finalization to /// the returned `ResultStream`. @@ -278,7 +282,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())); @@ -331,6 +335,9 @@ 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), + volume_options: super::volume::VolumeOptions::default(), + volume_completion: Arc::new(super::volume::VolumeCompletion::default()), statement_telemetry, result_stream_owns_success_telemetry: AtomicBool::new(false), client_deadline, @@ -390,6 +397,9 @@ impl ExecutedAsyncStatement { owning: false, session_attribution, latest_status: Arc::new(std::sync::Mutex::new(initial_status)), + pending_result: std::sync::Mutex::new(None), + volume_options: super::volume::VolumeOptions::default(), + volume_completion: Arc::new(super::volume::VolumeCompletion::default()), statement_telemetry: StatementTelemetry::noop(), result_stream_owns_success_telemetry: AtomicBool::new(false), client_deadline: None, @@ -408,16 +418,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<()> { @@ -429,6 +440,14 @@ impl ExecutedAsyncStatement { Ok(()) } + fn release_owner(&self) { + if self.owning { + self.owner_released.store(true, Ordering::Release); + self.clear_pending_result(); + self.volume_completion.cancel(); + } + } + fn check_read_validity(&self) -> Result<()> { self.valid.check()?; if !self.owning { @@ -514,18 +533,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 { @@ -563,10 +609,16 @@ 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 { 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 +660,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 +673,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 +689,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 +722,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 +807,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 +819,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 +876,7 @@ impl ExecutedAsyncStatement { .instrument(span) .await; if let Err(error) = &result { + self.clear_pending_result(); self.statement_telemetry.finalize(Some(error)); } result @@ -835,8 +890,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 +922,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 { @@ -874,6 +954,15 @@ 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; + 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 @@ -894,32 +983,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 + ))), } } } @@ -1040,6 +1109,7 @@ impl ExecutedStatementHandle for ExecutedAsyncStatement { submitted it", )); } + self.volume_completion.cancel(); self.session .transport() .cancel_statement(&self.statement_id) @@ -1069,9 +1139,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. // @@ -1125,6 +1193,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 @@ -1136,19 +1205,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 @@ -1157,15 +1226,15 @@ 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 /// `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 { @@ -1177,6 +1246,7 @@ impl AsyncStatementCanceller { is owned by whoever submitted it", )); } + self.volume_completion.cancel(); self.session .transport() .cancel_statement(&self.statement_id) @@ -1194,9 +1264,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/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..8f93c107 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 @@ -238,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 @@ -245,6 +248,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 { @@ -257,7 +261,9 @@ 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, } } @@ -274,7 +280,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 +288,7 @@ impl Statement { StatementCanceller { session: Arc::clone(&self.session), inflight_id: Arc::clone(&self.inflight_id), + volume_cancellation: self.volume_cancellation.clone(), } } @@ -409,6 +416,13 @@ impl Statement { self.last_valid = Some(valid.clone()); self.last_closed = Some(Arc::clone(&closed)); + let result = match self.complete_volume(result).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 @@ -535,7 +549,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 +563,10 @@ impl Statement { response.status, telemetry_for_body, timeout, - )) + ); + executed.volume_options = super::volume::VolumeOptions::from(&self.spec); + self.last_volume_completion = Some(Arc::clone(&executed.volume_completion)); + Ok(executed) } .instrument(span) .await; @@ -644,6 +661,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 = match self.complete_volume(result).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( @@ -667,7 +691,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 +699,10 @@ impl Statement { resp.status, telemetry_for_body, 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)) } } } @@ -749,6 +776,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`. /// @@ -803,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 @@ -918,16 +977,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 @@ -948,9 +1008,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 @@ -991,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 288bb0ae..a15ace44 100644 --- a/src/statement/spec.rs +++ b/src/statement/spec.rs @@ -222,6 +222,35 @@ 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. + /// Completion, including a failure after retries, is final and shared by all + /// 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>, + + /// 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, } impl StatementSpec { diff --git a/src/statement/volume.rs b/src/statement/volume.rs new file mode 100644 index 00000000..68cf9bee --- /dev/null +++ b/src/statement/volume.rs @@ -0,0 +1,1843 @@ +// 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, OsError, 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 std::time::Instant; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::sync::{watch, Mutex}; +use tokio_util::io::ReaderStream; + +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 { + paths: Option>, + stream_token: Option, + retain_result: bool, +} + +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, + } + } +} + +pub(crate) async fn complete( + client: &DatabricksHttpClient, + mut result: ExecuteResult, + options: &VolumeOptions, + completion: &VolumeCompletion, +) -> 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 statement_id = result.statement_id.clone(); + async { + let mut stream = ResultStream::from_reader(result.reader).await?; + let schema = stream.schema(); + 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")) + } + }; + 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 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() { + // 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", + ))); + 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, + &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, + }; + 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(); + } + error + })); + } + completed.as_ref().unwrap().clone()?; + } + result.reader = if options.retain_result { + Box::new(InMemoryReader::new(schema, vec![batch])) + } else { + Box::new(EmptyReader::new(schema)) + }; + Ok(result) + } + .await + .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() { + let state = if e.code == ErrorCode::Timeout { + "HYT00" + } else { + "HY000" + }; + e = e.with_sql_state(state); + } + e.with_query_id(&statement_id) + }) +} + +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(format!( + "Invalid file transfer headers: {:?}", + batch.column(2).data_type() + )) + }; + 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(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() { + 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::Internal, + }, + format!("File transfer failed: {error}"), + ); + mapped.os_error = error.raw_os_error().map(|code| { + Box::new(OsError { + code, + filename: None, + operation, + }) + }); + if permission_denied { + mapped.with_error_code("FILE_TRANSFER_PERMISSION_ERROR") + } else { + mapped + } +} + +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(|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(|error| file_error(Some("realpath"), error))? + .join(name)) + } + Err(error) => Err(file_error(Some("realpath"), error)), + } +} + +fn missing_path_for_policy(path: &Path) -> Result { + 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(); + 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 resolved = resolved_path(Path::new(file)); + let policy_path = match &resolved { + Ok(file) => file.clone(), + Err(_) => { + // Unresolved components may classify a denial, but must never authorize file access. + missing_path_for_policy(Path::new(file))? + } + }; + for base in paths { + let Ok(base) = resolved_path(Path::new(base)) else { + continue; + }; + if policy_path.starts_with(base) { + return resolved; + } + } + Err(Error::new( + ErrorCode::PermissionDenied, + "Local file operations are restricted to the configured allowed paths", + )) +} + +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, + headers: &HashMap, + local_file: Option<&str>, + paths: &[String], +) -> Result<()> { + let log = TransferLog::new(statement_id, operation); + let operation = log.operation; + 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 parsed.scheme() != "https" + && !(client.allow_loopback_plaintext_storage + && crate::client::http::is_loopback_http_url(&parsed)) + { + return Err(Error::invalid_state().message("Invalid file transfer URL scheme")); + } + let local = if operation == "REMOVE" { + None + } else { + 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(|error| file_error(Some("open"), error))?; + } + Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} + Err(error) => return Err(file_error(Some("stat"), error)), + } + } + 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) + { + 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 destination = local.as_ref().unwrap(); + let parent = destination.parent().ok_or_else(|| { + Error::invalid_argument().message("Download destination must be a file") + })?; + 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(Some("stat"), error)), + }; + builder.permissions(permissions); + builder + }; + 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()); + 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(|error| file_error(Some("write"), error))?; + } + Ok(()) + } + .await; + log.finish("body_write", started, body.as_ref().err()); + body?; + let started = log.start("body_flush"); + 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); + let started = log.start("commit"); + let committed = (|| { + match std::fs::metadata(destination) { + Ok(metadata) => temporary + .as_file() + .set_permissions(metadata.permissions()) + .map_err(|error| file_error(Some("fchmod"), error))?, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} + 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(operation, error.error))?; + Ok(()) + })(); + log.finish("commit", started, committed.as_ref().err()); + committed?; + } + Ok(()) +} + +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() { + "File transfer connection failed" + } else if error.is_body() || error.is_decode() { + "File download interrupted" + } else { + "File transfer request failed" + }; + 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( + client: &DatabricksHttpClient, + method: Method, + url: reqwest::Url, + headers: &HashMap, + local: Option<&Path>, + log: &TransferLog<'_>, +) -> Result { + let config = client.volume_retry_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(); + 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() { + 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 + .volume_client()? + .request(method.clone(), url.clone()) + .timeout(remaining); + for (name, value) in headers { + 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 + .ok_or_else(|| Error::invalid_argument().message("Missing local upload path"))?; + let opened_at = log.start("upload_open"); + let opened = async { + if !tokio::fs::metadata(local) + .await + .map_err(|error| file_error(Some("stat"), 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(|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") + ); + } + 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( + file.take(metadata.len()), + ))); + } + // 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( + 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), + }; + 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; + } + 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 { + 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 { + 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(), + } + } + + #[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] + 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; + + 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, + ..Default::default() + }; + 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"); + } + + #[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::Internal), + ] { + 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()); + assert_eq!( + error.error_code.as_deref(), + (kind == ErrorKind::PermissionDenied).then_some("FILE_TRANSFER_PERMISSION_ERROR") + ); + } + 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] + 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, + ..Default::default() + }; + 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!(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()); + } + + #[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( + "statement", + &strict, + "REMOVE", + &url, + &HashMap::new(), + None, + &[], + ) + .await + .unwrap_err(); + assert!(error.message.contains("URL scheme")); + let error = transfer( + "statement", + &client(), + "REMOVE", + &url, + &HashMap::new(), + None, + &[], + ) + .await + .unwrap_err(); + 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( + "statement", + &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() { + 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")) + .expect(3) + .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 [None, Some(0o640), Some(0o200)] { + if let Some(mode) = existing { + std::fs::set_permissions(&destination, std::fs::Permissions::from_mode(mode)) + .unwrap(); + } + transfer( + "statement", + &client(), + "GET", + &server.uri(), + &HashMap::new(), + destination.to_str(), + &roots, + ) + .await + .unwrap(); + let expected = existing.unwrap_or_else(|| { + std::fs::metadata(&control).unwrap().permissions().mode() & 0o777 + }); + assert_eq!( + std::fs::metadata(&destination) + .unwrap() + .permissions() + .mode() + & 0o777, + 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( + "statement", + &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( + "statement", + &client(), + "GET", + &server.uri(), + &HashMap::new(), + destination.to_str(), + &["/".into()], + ) + .await + .unwrap_err(); + assert_eq!(error.code, ErrorCode::Internal); + assert!(error.os_error.is_some()); + } + } + + #[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( + "statement", + &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 accepts_missing_remove() { + let server = MockServer::start().await; + Mock::given(method("DELETE")) + .and(path("/file")) + .respond_with(ResponseTemplate::new(404)) + .expect(1) + .mount(&server) + .await; + transfer( + "statement", + &client(), + "remove", + &format!("{}/file", server.uri()), + &HashMap::new(), + None, + &[], + ) + .await + .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( + "statement", + &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}; + 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 + }) + .insert_header("Retry-After", "0") + }) + .expect(2) + .mount(&server) + .await; + let dir = tempfile::tempdir().unwrap(); + let file = dir.path().join("input"); + std::fs::write(&file, b"upload").unwrap(); + transfer( + "statement", + &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 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( + "statement", + &client(), + "PUT", + &url, + &HashMap::new(), + local.to_str(), + &[directory.path().to_str().unwrap().into()], + ) + .await; + server.abort(); + 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); + } + + #[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); + } + 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::os::unix::fs::symlink(&outside, allowed.join("link")).unwrap(); + 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(); + 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()); + } + } + } + } + + #[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::Sea, 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, + ..Default::default() + }, + &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![( + "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, + ..Default::default() + }, + &VolumeCompletion::default(), + ) + .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 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, + ..Default::default() + }, + &VolumeCompletion::default(), + ) + .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"); + for (marker, options) in [ + ( + false, + VolumeOptions { + paths: Some(vec![]), + retain_result: false, + ..Default::default() + }, + ), + (true, VolumeOptions::default()), + ] { + let completed = complete( + &client(), + result(batch.clone(), marker), + &options, + &VolumeCompletion::default(), + ) + .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"); + for operation in ["PUT", "GET"] { + let error = transfer( + "statement", + &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] + async fn download_body_uses_storage_deadline() { + use crate::client::retry::{RequestCategory, RetryConfig}; + use std::time::Duration; + use tokio::io::AsyncReadExt; + 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 { + 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(); + 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 { + read_timeout: Duration::from_millis(10), + ..Default::default() + }; + let retry = RetryConfig { + overall_timeout: Duration::from_millis(budget), + max_retries: 0, + ..Default::default() + }; + 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"); + if existing { + std::fs::write(&file, b"original").unwrap(); + } + let batch = instruction( + "GET", + &format!("http://{address}/file"), + file.to_str().unwrap(), + ); + let result = complete( + &http, + result(batch, true), + &VolumeOptions { + paths: Some(vec![dir.path().to_str().unwrap().into()]), + retain_result: false, + ..Default::default() + }, + &VolumeCompletion::default(), + ) + .await; + assert_eq!(result.is_ok(), succeeds); + if succeeds { + assert_eq!(std::fs::read(&file).unwrap(), b"data"); + } else { + 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 { + assert!(!file.exists()); + } + } + assert_eq!( + std::fs::read_dir(dir.path()).unwrap().count(), + usize::from(succeeds || existing) + ); + if succeeds { + server.await.unwrap(); + } else { + server.abort(); + } + } + } + + #[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); + 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!(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", + &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(); + 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); + } +} diff --git a/src/types/sea.rs b/src/types/sea.rs index 8d988dad..62f674ea 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..b41df37b 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, @@ -484,6 +505,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 +1276,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 +1285,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 +1316,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 +1570,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 +1896,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 +2254,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", @@ -2220,27 +2309,32 @@ 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; 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 +2349,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 +2375,626 @@ 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 + ); +} + +#[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; + 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 body = file_transfer_body( + "GET", + &format!("{}/storage/file", server.uri()), + &destination, + ); + mount_submit(&server, pending_body("transfer")).await; + mount_status_once(&server, "transfer", body).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(); +} + +#[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; + 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 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 + .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()); + 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 + .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(); + } + } +} + +#[tokio::test] +async fn cancellation_interrupts_file_transfers() { + use databricks_sql_kernel::DirectStatement; + use std::time::Duration; + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + + for operation in ["PUT", "GET"] { + for mode in ["sync", "direct", "async-owner", "async-detached"] { + 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 body = file_transfer_body(operation, &format!("http://{address}/file"), &local); + if mode == "sync" || mode == "direct" { + mount_submit(&server, body).await; + } else { + mount_submit(&server, pending_body("transfer")).await; + mount_status_once(&server, "transfer", body).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 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 { + 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")); + } + if operation == "GET" { + assert_eq!(std::fs::read(&local).unwrap(), original); + } + storage.abort(); + session.close().await.unwrap(); + } + } }