Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
42 commits
Select commit Hold shift + click to select a range
d41cc36
feat(volume): complete SQL file transfers in the shared kernel
aakash-saravanan-db Nov 11, 2026
87e4ea4
fix(volume): honor storage deadlines and independent allowed paths
aakash-saravanan-db Nov 11, 2026
9c4ab90
docs(napi): synchronize generated public binding declarations
aakash-saravanan-db Nov 11, 2026
bc39c79
docs(napi): keep transfer declarations focused
aakash-saravanan-db Nov 11, 2026
ebb8204
fix(volume): preserve download destinations on transfer failure
aakash-saravanan-db Nov 11, 2026
0228350
fix(volume): preserve file modes and reject root destinations
aakash-saravanan-db Nov 11, 2026
2f317d9
fix(volume): validate destinations and reset reused statements
aakash-saravanan-db Nov 11, 2026
95f294c
fix(volume): preserve error context and normalize option clearing
aakash-saravanan-db Nov 11, 2026
f68e4e5
fix(volume): constrain storage redirects and preserve filesystem errors
aakash-saravanan-db Nov 11, 2026
c3e7cf1
fix(volume): retain instruction reader error details
aakash-saravanan-db Nov 12, 2026
7a93810
fix(volume): reject special uploads and close failed transfers
aakash-saravanan-db Nov 12, 2026
ab10f22
fix(volume): honor destination permissions and safe upload retries
aakash-saravanan-db Nov 12, 2026
6dbc9a7
fix(volume): preserve private modes during downloads
aakash-saravanan-db Nov 12, 2026
bd8adef
fix(volume): isolate loopback policy and accept operation casing
aakash-saravanan-db Nov 12, 2026
c3300aa
fix(volume): keep cancelled transfers terminal across readers
aakash-saravanan-db Nov 12, 2026
ed829e8
fix(statement): preserve transfer policy and timeout diagnostics
aakash-saravanan-db Nov 12, 2026
2006c55
fix(adbc): expose configured file transfer paths
aakash-saravanan-db Nov 12, 2026
892ee56
docs(bindings): describe transfer instruction consumption
aakash-saravanan-db Nov 12, 2026
00e1701
fix(http): limit plaintext storage to local sessions
aakash-saravanan-db Nov 12, 2026
e78a4b1
fix(volume): classify permanent local IO failures
aakash-saravanan-db Nov 12, 2026
f139344
fix(staging): preserve timeout category during storage requests
aakash-saravanan-db Nov 12, 2026
9f7bf93
fix(volume): preserve local OS error codes across Python bindings
aakash-saravanan-db Nov 12, 2026
be47427
fix(volume): preserve requested filenames in local OS errors
aakash-saravanan-db Nov 12, 2026
f8211f4
fix(volume): write through the existing temporary file handle
aakash-saravanan-db Nov 12, 2026
23cd28e
fix(volume): interrupt local transfers on detached cancellation
aakash-saravanan-db Nov 12, 2026
2dfbb5c
fix(volume): cancel shared asynchronous transfers
aakash-saravanan-db Nov 12, 2026
4f12d12
fix(volume): preserve directory open errors
aakash-saravanan-db Nov 12, 2026
b92a867
fix(volume): send one upload content length
aakash-saravanan-db Nov 12, 2026
5999f82
test(volume): cover sync cancellation and upload path denial
aakash-saravanan-db Nov 12, 2026
ea26771
fix(volume): retry failed storage client initialization
aakash-saravanan-db Nov 12, 2026
37c7a3e
Enforce transfer policy for unresolved paths and stream sources
aakash-saravanan-db Nov 12, 2026
572fe49
Document replacement semantics of transfer options
aakash-saravanan-db Nov 12, 2026
edd340c
test(volume): remove redundant transfer setup and cases
aakash-saravanan-db Nov 12, 2026
663d586
Strengthen invalid staging-option state assertions
aakash-saravanan-db Nov 12, 2026
6adac39
fix(volume): honor transfer policy and statement lifecycle
aakash-saravanan-db Nov 12, 2026
65e8e5f
fix(c-abi): preserve native filesystem error details
aakash-saravanan-db Nov 13, 2026
81c6a9c
fix(napi): preserve filesystem operations and Windows errno
aakash-saravanan-db Nov 13, 2026
7b4191f
chore: merge main into volume operations
aakash-saravanan-db Nov 13, 2026
96f6299
perf(statement): reuse successful async terminal responses
aakash-saravanan-db Nov 13, 2026
7c98f1c
perf(statement): reuse terminal responses during volume execution
aakash-saravanan-db Nov 13, 2026
04a4b73
fix(async): document terminal payload retention and correct test counts
aakash-saravanan-db Nov 13, 2026
69b2998
Merge async terminal response documentation and test corrections
aakash-saravanan-db Nov 13, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 4 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand Down
6 changes: 4 additions & 2 deletions adbc/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 7 additions & 0 deletions adbc/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
88 changes: 88 additions & 0 deletions adbc/src/statement.rs
Original file line number Diff line number Diff line change
Expand Up @@ -470,6 +470,18 @@ impl Statement {
return Ok(());
}
match key {
"adbc.databricks.statement.staging_allowed_local_paths" => {
Comment thread
oss-reviewer-bot[bot] marked this conversation as resolved.
Resolved
Comment thread
oss-reviewer-bot[bot] marked this conversation as resolved.
Resolved
let paths =
serde_json::from_str::<Option<Vec<String>>>(&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(())
Expand Down Expand Up @@ -584,6 +596,12 @@ impl Statement {

fn get_other_string(&self, key: &str) -> Result<String> {
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(
Expand Down Expand Up @@ -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),
Expand Down
91 changes: 91 additions & 0 deletions adbc/tests/live.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<u8> = (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<dyn std::error::Error>> {
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::<Result<Vec<_>, _>>()?;
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::<Result<Vec<_>, _>>()?
.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();
}
33 changes: 25 additions & 8 deletions include/databricks_kernel.h
Original file line number Diff line number Diff line change
Expand Up @@ -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
*
Expand All @@ -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
*
Expand Down Expand Up @@ -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`. */
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down
Loading
Loading