From aede51fb9cd36fd486ca5e2dab99ff835ec2f229 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Fri, 13 Nov 2026 21:40:35 +0000 Subject: [PATCH 01/63] feat: add explicit Volume transfer completion Signed-off-by: Aakash Saravanan --- Cargo.toml | 4 +- NEXT_CHANGELOG.md | 5 + README.md | 23 + pyo3/Cargo.lock | 39 ++ pyo3/NEXT_CHANGELOG.md | 4 + pyo3/src/errors.rs | 9 + pyo3/src/result_stream.rs | 29 ++ pyo3/src/statement.rs | 29 ++ src/client/sea.rs | 1 + src/kernel_error.rs | 12 + src/lib.rs | 4 +- src/reader/mod.rs | 2 + src/reader/post_processor/mod.rs | 1 + src/result_stream.rs | 51 ++ src/session.rs | 36 +- src/statement/executed.rs | 3 + src/statement/executed_async.rs | 49 +- src/statement/mutable.rs | 34 ++ src/types/sea.rs | 2 + src/volume.rs | 823 +++++++++++++++++++++++++++++++ tests/v0_volume_wiremock.rs | 298 +++++++++++ 21 files changed, 1444 insertions(+), 14 deletions(-) create mode 100644 src/volume.rs create mode 100644 tests/v0_volume_wiremock.rs diff --git a/Cargo.toml b/Cargo.toml index 5a53e72c..67ae5bd3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -105,7 +105,8 @@ moka = { version = "0.12.16", features = ["future"] } # Async utilities futures = "0.3" -tokio-util = "0.7" +tokio-util = { version = "0.7", features = ["io"] } +tempfile = "3" async-trait = "0.1" # Error handling @@ -162,7 +163,6 @@ pkcs8 = { version = "0.10", features = ["encryption", "pem", "std"] } [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/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index 2ebce050..5721d60b 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -11,6 +11,11 @@ changes go in their respective binding's NEXT_CHANGELOG. ### Added +- Explicit, execution-scoped completion of server-marked Volume PUT/GET/REMOVE + instructions, with allowed-root checks, resumable owned-byte PUT input, safe GET + replacement and cached completion outcomes. Resolved symlink targets must remain + within the configured roots. + ### Changed ### Updated diff --git a/README.md b/README.md index ba83c9f1..735ec0bf 100644 --- a/README.md +++ b/README.md @@ -66,6 +66,29 @@ and security vulnerabilities should be reported according to [SECURITY.md](SECURITY.md). For other project questions, contact [eng-oss-sql-driver@databricks.com](mailto:eng-oss-sql-driver@databricks.com). +## Volume file operations + +`ResultStream::complete_volume_operation` completes server-marked SQL PUT, GET, +and REMOVE instructions. Pass `VolumeOptions` with the local roots authorized for +PUT and GET. Completion preserves the instruction rows; callers that want the raw +result can omit completion. The PyO3 `ExecutedStatement` and `ResultStream` +classes expose `is_volume_operation` and `complete_volume_operation`. + +A PUT instruction with `localFile == "__input_stream__"` returns +`NeedsInputStream` until owned input bytes are supplied. An empty byte buffer is a +valid upload. Other statements do not request or consume input bytes. + +Local paths must satisfy both the lexical allowed-root check and a resolved-target +check. Symlinks within the configured roots are permitted, including links between +two authorized roots. Symlinks that resolve outside all authorized roots are +rejected. This is stricter than the lexical-only checks in existing Python and +Node.js Thrift transfer paths. An allowed root's symlink alias does not authorize +additional lexical paths. + +GET replaces the destination only after a complete download. Transfer failures +and cancellation before publication preserve the destination's existing bytes. +Repeated completion on the same execution reuses its outcome, including errors. + ## License Apache 2.0. See [LICENSE](LICENSE) and [NOTICE](NOTICE). diff --git a/pyo3/Cargo.lock b/pyo3/Cargo.lock index fa59876f..6d9c3e25 100644 --- a/pyo3/Cargo.lock +++ b/pyo3/Cargo.lock @@ -634,6 +634,7 @@ dependencies = [ "serde", "serde_json", "sha2 0.11.0", + "tempfile", "thiserror 2.0.19", "tokio", "tokio-util", @@ -769,6 +770,12 @@ dependencies = [ "pin-project-lite", ] +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + [[package]] name = "find-msvc-tools" version = "0.1.9" @@ -1423,6 +1430,12 @@ dependencies = [ "libc", ] +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + [[package]] name = "litemap" version = "0.8.2" @@ -2112,6 +2125,19 @@ dependencies = [ "semver", ] +[[package]] +name = "rustix" +version = "1.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.61.2", +] + [[package]] name = "rustls" version = "0.23.46" @@ -2464,6 +2490,19 @@ version = "0.13.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "adb6935a6f5c20170eeceb1a3835a49e12e19d792f6dd344ccc76a985ca5a6ca" +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.4.3", + "once_cell", + "rustix", + "windows-sys 0.61.2", +] + [[package]] name = "thiserror" version = "1.0.69" diff --git a/pyo3/NEXT_CHANGELOG.md b/pyo3/NEXT_CHANGELOG.md index e0881e54..b10c0fa0 100644 --- a/pyo3/NEXT_CHANGELOG.md +++ b/pyo3/NEXT_CHANGELOG.md @@ -13,6 +13,10 @@ changes go in the root `NEXT_CHANGELOG.md`. ### Added +- `ExecutedStatement` and `ResultStream` expose `is_volume_operation` and + `complete_volume_operation` for explicit Volume transfers, including owned-byte + stream uploads. Filesystem errors retain their OS code, kind and requested path. + ### Changed ### Updated diff --git a/pyo3/src/errors.rs b/pyo3/src/errors.rs index 88ff4257..0c14b9f2 100644 --- a/pyo3/src/errors.rs +++ b/pyo3/src/errors.rs @@ -154,6 +154,15 @@ pub(crate) fn to_py_err(py: Python<'_>, err: KError) -> PyErr { chained.set_cause(py, Some(setattr_err)); return chained; } + let local = err.local_error.as_ref(); + if let Err(error) = (|| -> PyResult<()> { + bound.setattr("local_os_error", local.and_then(|e| e.raw_os_error))?; + bound.setattr("local_error_kind", local.map(|e| e.kind.as_str()))?; + bound.setattr("local_path", local.map(|e| e.path.as_str()))?; + Ok(()) + })() { + return error; + } py_err } diff --git a/pyo3/src/result_stream.rs b/pyo3/src/result_stream.rs index 1b5fc590..aaf5888d 100644 --- a/pyo3/src/result_stream.rs +++ b/pyo3/src/result_stream.rs @@ -56,6 +56,35 @@ impl ResultStream { #[pymethods] impl ResultStream { + #[getter] + fn is_volume_operation(&self) -> PyResult { + let inner = alive!(self, "ResultStream"); + Ok(inner.stream.is_volume_operation()) + } + + #[pyo3(signature = (allowed_paths, remove_not_found_is_success=false, input_bytes=None))] + fn complete_volume_operation( + &mut self, + py: Python<'_>, + allowed_paths: Vec, + remove_not_found_is_success: bool, + input_bytes: Option>, + ) -> PyResult<&'static str> { + let inner = alive_mut!(self, "ResultStream"); + let runtime = inner.runtime.clone(); + let options = databricks_sql_kernel::VolumeOptions { + allowed_paths: allowed_paths.into_iter().map(Into::into).collect(), + remove_not_found_is_success, + }; + let stream = &mut inner.stream; + let outcome = run_kernel_interruptible!( + py, + &runtime, + stream.complete_volume_operation(&options, input_bytes) + )?; + Ok(outcome.as_str()) + } + /// Result schema as a `pyarrow.Schema`. Available even after `close()`. fn arrow_schema<'py>(&self, py: Python<'py>) -> PyResult> { self.schema.as_ref().to_pyarrow(py) diff --git a/pyo3/src/statement.rs b/pyo3/src/statement.rs index 2777b114..321f5386 100644 --- a/pyo3/src/statement.rs +++ b/pyo3/src/statement.rs @@ -321,6 +321,35 @@ impl ExecutedStatement { #[pymethods] impl ExecutedStatement { + #[getter] + fn is_volume_operation(&self) -> PyResult { + let inner = alive!(self, "ExecutedStatement"); + Ok(inner.exec.result_stream().is_volume_operation()) + } + + #[pyo3(signature = (allowed_paths, remove_not_found_is_success=false, input_bytes=None))] + fn complete_volume_operation( + &mut self, + py: Python<'_>, + allowed_paths: Vec, + remove_not_found_is_success: bool, + input_bytes: Option>, + ) -> PyResult<&'static str> { + let inner = alive_mut!(self, "ExecutedStatement"); + let runtime = inner.runtime.clone(); + let options = databricks_sql_kernel::VolumeOptions { + allowed_paths: allowed_paths.into_iter().map(Into::into).collect(), + remove_not_found_is_success, + }; + let stream = inner.exec.result_stream_mut(); + let outcome = run_kernel_interruptible!( + py, + &runtime, + stream.complete_volume_operation(&options, input_bytes) + )?; + Ok(outcome.as_str()) + } + #[getter] fn statement_id(&self) -> &str { &self.statement_id diff --git a/src/client/sea.rs b/src/client/sea.rs index a5aa3563..f0163cb0 100644 --- a/src/client/sea.rs +++ b/src/client/sea.rs @@ -2400,6 +2400,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/kernel_error.rs b/src/kernel_error.rs index ecfb7fb2..14f2030e 100644 --- a/src/kernel_error.rs +++ b/src/kernel_error.rs @@ -248,6 +248,17 @@ pub struct Error { /// Underlying cause. Boxed to keep the struct stack-friendly. pub cause: Option>, + + /// Original local filesystem failure, for host-language OS error mapping. + pub local_error: Option>, +} + +/// Local filesystem error details retained across language boundaries. +#[derive(Debug, Clone)] +pub struct LocalFileError { + pub raw_os_error: Option, + pub kind: String, + pub path: String, } impl Error { @@ -270,6 +281,7 @@ impl Error { diagnostic_info: None, error_details_json: None, cause: None, + local_error: None, } } diff --git a/src/lib.rs b/src/lib.rs index 00340e94..4a189d3f 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -127,6 +127,7 @@ pub mod metadata_v0; pub mod result_stream; pub mod session; pub(crate) mod util; +mod volume; // Custom C ABI for ODBC / Go consumers (lives in the core crate; see // `c_abi` module docs for why it is not a separate crate like pyo3 / napi). @@ -138,7 +139,7 @@ pub use config::{ LoggingConfig, ProxyConfig, ResultConfig, SessionConfig, TelemetryConfig, TlsConfig, TokenCacheConfig, TransportMode, }; -pub use kernel_error::{Error, ErrorCode, Result}; +pub use kernel_error::{Error, ErrorCode, LocalFileError, Result}; /// The `tracing` target string stamped on every kernel log event. /// Binding crates (pyo3, napi) reference this constant directly so the /// logger name they expose to users can never drift from what the @@ -157,6 +158,7 @@ pub use statement::params_codec::parse_typed_value; pub use statement::spec::{ResultFormat, StatementSpec, TypedValue}; pub use statement::{MAX_CLIENT_QUERY_TIMEOUT, MAX_CLIENT_QUERY_TIMEOUT_MS}; pub use telemetry::DriverSystemConfiguration; +pub use volume::{VolumeCompletion, VolumeOptions}; // === Compile-time guarantees on auto-traits === // diff --git a/src/reader/mod.rs b/src/reader/mod.rs index fd616540..b89a31e9 100644 --- a/src/reader/mod.rs +++ b/src/reader/mod.rs @@ -1472,6 +1472,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, @@ -2149,6 +2150,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 4c5c82ce..cc3f80cf 100644 --- a/src/reader/post_processor/mod.rs +++ b/src/reader/post_processor/mod.rs @@ -469,6 +469,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/result_stream.rs b/src/result_stream.rs index 721424e1..1b6e9844 100644 --- a/src/result_stream.rs +++ b/src/result_stream.rs @@ -493,6 +493,7 @@ pub struct ResultStream { close_guard: Option, telemetry: Option, + volume: Option<(Arc, reqwest::Client)>, } struct ResultStreamTelemetry { @@ -608,6 +609,7 @@ impl ResultStream { exhausted: false, close_guard: None, telemetry: None, + volume: None, }) } @@ -638,6 +640,54 @@ impl ResultStream { Ok(stream) } + pub(crate) fn attach_volume( + &mut self, + marked: bool, + state: Arc, + client: reqwest::Client, + ) { + if marked { + self.volume = Some((state, client)); + } + } + + /// Whether this execution has server-authorized Volume completion. + pub fn is_volume_operation(&self) -> bool { + self.volume.is_some() + } + + /// Complete a marked instruction without consuming its result row. + /// + /// Ordinary results and read-only attachments have no transfer authority. + /// `NeedsInputStream` requests owned bytes for the server's stream sentinel; + /// supplying an empty buffer is a valid upload. + pub async fn complete_volume_operation( + &mut self, + options: &crate::volume::VolumeOptions, + input_bytes: Option>, + ) -> Result { + let Some((state, client)) = self.volume.clone() else { + return Ok(crate::volume::VolumeCompletion::NotVolume); + }; + if let Some(result) = state.cached() { + return result; + } + let batch = self + .peek_first_batch() + .await + .map_err(|error| state.fail(error))? + .ok_or_else(|| { + state.fail(Error::invalid_argument().message("Missing Volume instruction row")) + })?; + state.complete(batch, &client, options, input_bytes).await + } + + pub(crate) fn cancel_volume(&self) { + if let Some((state, _)) = &self.volume { + state.cancel(); + } + } + pub(crate) fn attach_telemetry(&mut self, telemetry: StatementTelemetry) { self.telemetry = Some(ResultStreamTelemetry::new(telemetry)); } @@ -887,6 +937,7 @@ impl ResultStream { /// `Drop` performs the same cleanup (including the metadata guard's /// close) if `close` was never called explicitly. pub fn close(self) { + self.cancel_volume(); // Drops `self` (and the wrapped reader / current batch / any // metadata close-guard). Background tasks owned by the reader // stop on `Drop`. diff --git a/src/session.rs b/src/session.rs index ac2f462f..36422d5d 100644 --- a/src/session.rs +++ b/src/session.rs @@ -97,6 +97,8 @@ pub(crate) struct SessionInner { /// behind the trait object; future variants slot in via /// `TransportMode`. transport: Arc, + storage_client: reqwest::Client, + volume_states: std::sync::Mutex>>>, /// Server-issued session identifier. session_id: String, @@ -158,6 +160,34 @@ pub(crate) struct SessionInner { } impl SessionInner { + pub(crate) fn new_volume_state(&self) -> Arc { + let state = crate::volume::VolumeState::new(); + let mut states = self.volume_states.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(states) = states.as_mut() { + states.retain(|state| state.strong_count() != 0); + states.push(Arc::downgrade(&state)); + } else { + state.cancel(); + } + state + } + + fn cancel_volume_operations(&self) { + let states = self + .volume_states + .lock() + .unwrap_or_else(|e| e.into_inner()) + .take() + .unwrap_or_default(); + for state in states.into_iter().filter_map(|state| state.upgrade()) { + state.cancel(); + } + } + + pub(crate) fn storage_client(&self) -> reqwest::Client { + self.storage_client.clone() + } + /// Crate-internal accessor for the session's transport. Used by /// `Metadata` (and PR 4's `Statement`) to drive RPCs without /// reaching into private fields. @@ -226,6 +256,7 @@ impl SessionInner { /// explicit close genuinely *initiates* the delete rather than /// deferring it to an idle-timeout. pub(crate) fn initiate_delete(&self) { + self.cancel_volume_operations(); if self .closed .compare_exchange( @@ -452,7 +483,7 @@ impl Session { &config.connection, &config.auth, config.driver_system_configuration.clone(), - http_client, + http_client.clone(), session_info.session_id.clone(), )); telemetry @@ -472,6 +503,8 @@ impl Session { Ok(Session { inner: Arc::new(SessionInner { transport, + storage_client: http_client.inner().clone(), + volume_states: std::sync::Mutex::new(Some(Vec::new())), session_id: session_info.session_id, config, runtime_handle, @@ -778,6 +811,7 @@ impl Session { /// race): flag stays false, [`Drop`] picks up the slack. /// - On `Ok`: flag flips, [`Drop`] is a no-op. pub async fn close(self) -> Result<()> { + self.inner.cancel_volume_operations(); // Bail early if a concurrent caller already finished a // successful close — no point hitting the wire twice. if self.inner.closed.load(std::sync::atomic::Ordering::Acquire) { diff --git a/src/statement/executed.rs b/src/statement/executed.rs index 025db78e..ee852c5c 100644 --- a/src/statement/executed.rs +++ b/src/statement/executed.rs @@ -189,6 +189,7 @@ impl ExecutedStatement { } async fn close_server_statement(&self) -> Result<()> { + self.result_stream.cancel_volume(); // Idempotent on success: a prior successful close sets // `closed=true` and subsequent calls short-circuit. // @@ -348,6 +349,7 @@ impl ExecutedStatementHandle for ExecutedStatement { } async fn cancel(&self) -> Result<()> { + self.result_stream.cancel_volume(); // Local validity short-circuits a wire call against an // already-closed/superseded handle. `instrument` (rather // than `.entered()`) so the future stays `Send` per the @@ -370,6 +372,7 @@ impl ExecutedStatementHandle for ExecutedStatement { impl Drop for ExecutedStatement { fn drop(&mut self) { + self.result_stream.cancel_volume(); // Backstop for the not-fully-drained case (partial fetch / // abandoned result / early error): if the stream was drained, // `next_batch`'s auto-close already fired and flipped `closed`, diff --git a/src/statement/executed_async.rs b/src/statement/executed_async.rs index f9dfc2ac..036f3739 100644 --- a/src/statement/executed_async.rs +++ b/src/statement/executed_async.rs @@ -172,6 +172,7 @@ impl StatementStatus { /// Async-consumption executed handle. pub struct ExecutedAsyncStatement { + volume: Option>, session: Arc, statement_id: String, /// Shared with the parent `Statement`; flipped on re-execute or @@ -280,6 +281,9 @@ 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 { + if let Some(volume) = &self.volume { + volume.cancel(); + } self.owner_released.store(true, Ordering::Release); self.clear_pending_result(); if !self.client_timeout_expired.swap(true, Ordering::AcqRel) { @@ -313,6 +317,7 @@ impl ExecutedAsyncStatement { /// deadline and the transport's default `poll_timeout` ceiling; /// `Default` keeps the `poll_timeout` ceiling with no client /// deadline. + #[allow(clippy::too_many_arguments)] pub(crate) fn new( session: Arc, statement_id: String, @@ -321,6 +326,7 @@ impl ExecutedAsyncStatement { initial_status: crate::types::sea::StatementStatus, statement_telemetry: StatementTelemetry, timeout: ExecutionTimeout, + volume: Arc, ) -> Self { let (client_deadline, poll_timeout_disabled) = deadline_policy(timeout); let initial_terminal = initial_status.state.is_terminal(); @@ -330,6 +336,7 @@ impl ExecutedAsyncStatement { valid, closed, owner_released: Arc::new(AtomicBool::new(false)), + volume: Some(volume), // The submitting handle owns the statement lifecycle. owning: true, session_attribution: SessionAttribution::Current, @@ -391,6 +398,7 @@ impl ExecutedAsyncStatement { valid, closed: Arc::new(AtomicBool::new(true)), owner_released, + volume: None, owning: false, session_attribution, latest_status: Arc::new(std::sync::Mutex::new(initial_status)), @@ -413,16 +421,16 @@ 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 = self.volume.clone(); + Ok(AsyncStatementReader { inner }) } fn check_owner_available(&self) -> Result<()> { @@ -940,7 +948,14 @@ impl ExecutedAsyncStatement { if result.status.state == crate::types::sea::StatementState::Closed { self.closed.store(true, Ordering::Release); } + let marked = result + .manifest + .as_ref() + .is_some_and(|m| m.is_volume_operation); let mut stream = ResultStream::from_reader(result.reader).await?; + if let Some(volume) = &self.volume { + stream.attach_volume(marked, Arc::clone(volume), self.session.storage_client()); + } stream.attach_telemetry(self.statement_telemetry.clone()); // SEA carries no row count on the async status either; for a // DML the count rides in the result set. Derive it once @@ -1086,6 +1101,9 @@ impl ExecutedStatementHandle for ExecutedAsyncStatement { submitted it", )); } + if let Some(volume) = &self.volume { + volume.cancel(); + } self.session .transport() .cancel_statement(&self.statement_id) @@ -1116,6 +1134,9 @@ impl ExecutedAsyncStatement { async fn close_server_statement(&self) -> Result<()> { if self.owning { + if let Some(volume) = &self.volume { + volume.cancel(); + } self.owner_released.store(true, Ordering::Release); self.clear_pending_result(); } @@ -1176,6 +1197,7 @@ impl ExecutedAsyncStatement { // either — otherwise the footgun just moves to the detached // canceller. owning: self.owning, + volume: self.volume.clone(), } } } @@ -1192,6 +1214,7 @@ impl ExecutedAsyncStatement { /// Cheap to [`Clone`] (one `Arc` bump plus a `String` / flag clone). #[derive(Clone)] pub struct AsyncStatementCanceller { + volume: Option>, session: Arc, statement_id: String, valid: ValidityFlag, @@ -1223,6 +1246,9 @@ impl AsyncStatementCanceller { is owned by whoever submitted it", )); } + if let Some(volume) = &self.volume { + volume.cancel(); + } self.session .transport() .cancel_statement(&self.statement_id) @@ -1241,6 +1267,9 @@ impl AsyncStatementCanceller { impl Drop for ExecutedAsyncStatement { fn drop(&mut self) { if self.owning { + if let Some(volume) = &self.volume { + volume.cancel(); + } self.owner_released.store(true, Ordering::Release); self.clear_pending_result(); } diff --git a/src/statement/mutable.rs b/src/statement/mutable.rs index 34baf1d1..bfda144d 100644 --- a/src/statement/mutable.rs +++ b/src/statement/mutable.rs @@ -245,12 +245,14 @@ pub struct Statement { /// new `execute()` / `submit()` so a canceller never targets a /// stale prior statement. inflight_id: InflightId, + volume: Arc>>, } impl Statement { /// Construct a new statement bound to `session`. Crate-private — /// wrappers obtain a `Statement` via `Session::statement()`. pub(crate) fn new(session: Arc) -> Self { + let volume = session.new_volume_state(); Self { session, spec: StatementSpec::new(), @@ -258,6 +260,7 @@ impl Statement { last_valid: None, last_closed: None, inflight_id: Arc::new(Mutex::new(None)), + volume: Arc::new(Mutex::new(volume)), } } @@ -282,6 +285,7 @@ impl Statement { StatementCanceller { session: Arc::clone(&self.session), inflight_id: Arc::clone(&self.inflight_id), + volume: Arc::clone(&self.volume), } } @@ -409,7 +413,12 @@ impl Statement { self.last_valid = Some(valid.clone()); self.last_closed = Some(Arc::clone(&closed)); + let marked = result + .manifest + .as_ref() + .is_some_and(|m| m.is_volume_operation); let mut result_stream = ResultStream::from_reader(result.reader).await?; + result_stream.attach_volume(marked, self.volume_state(), self.session.storage_client()); result_stream.attach_telemetry(telemetry_for_body.clone()); // SEA puts no row count on the status envelope; for a DML it // returns the count as the result set. If the server didn't @@ -549,6 +558,7 @@ impl Statement { response.status, telemetry_for_body, timeout, + self.volume_state(), )) } .instrument(span) @@ -644,7 +654,16 @@ 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 marked = result + .manifest + .as_ref() + .is_some_and(|m| m.is_volume_operation); let mut result_stream = ResultStream::from_reader(result.reader).await?; + result_stream.attach_volume( + marked, + self.volume_state(), + self.session.storage_client(), + ); result_stream.attach_telemetry(telemetry_for_body.clone()); let mut status = result.status; if status.num_modified_rows.is_none() { @@ -685,6 +704,7 @@ impl Statement { resp.status, telemetry_for_body, ExecutionTimeout::Default, + self.volume_state(), ))) } } @@ -697,6 +717,10 @@ impl Statement { result } + fn volume_state(&self) -> Arc { + Arc::clone(&self.volume.lock().unwrap_or_else(|e| e.into_inner())) + } + fn statement_telemetry(&self, operation_type: OperationType) -> StatementTelemetry { self.session .statement_telemetry_observer(StatementType::Sql, operation_type) @@ -729,6 +753,7 @@ impl Statement { /// for callers that forget to call `close()` explicitly, but /// the explicit path is the supported one. pub async fn close(mut self) -> Result<()> { + self.volume_state().cancel(); let span = self.session.log_span().clone(); async { self.invalidate_prior().await; @@ -780,6 +805,9 @@ impl Statement { /// canceller can still dispatch against the just-closed statement (its /// cloned session `Arc` keeps the client side alive). fn reset_inflight_slot(&self) { + let mut volume = self.volume.lock().unwrap_or_else(|e| e.into_inner()); + volume.cancel(); + *volume = self.session.new_volume_state(); if let Ok(mut slot) = self.inflight_id.lock() { *slot = None; } @@ -933,6 +961,7 @@ impl Drop for MidExecuteCancelGuard { pub struct StatementCanceller { session: Arc, inflight_id: InflightId, + volume: Arc>>, } impl StatementCanceller { @@ -960,6 +989,10 @@ impl StatementCanceller { /// concurrently with the `execute()` it targets — the two share /// only the id slot (behind a `Mutex`), no mutable statement state. pub async fn cancel(&self) -> Result { + self.volume + .lock() + .unwrap_or_else(|e| e.into_inner()) + .cancel(); let id = self.inflight_id.lock().ok().and_then(|g| g.clone()); async { // Log both outcomes at the decision point so a host debugging a @@ -991,6 +1024,7 @@ impl StatementCanceller { impl Drop for Statement { fn drop(&mut self) { + self.volume_state().cancel(); // Flip the validity flag so any executed handle the caller // still holds short-circuits to InvalidStatementHandle on its // next call without a network round-trip. Server-side cleanup 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/src/volume.rs b/src/volume.rs new file mode 100644 index 00000000..68b3341f --- /dev/null +++ b/src/volume.rs @@ -0,0 +1,823 @@ +// 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. + +//! Explicit completion of server-authorized Volume file transfers. + +use crate::kernel_error::{Error, LocalFileError, Result}; +use crate::result_stream::ResultBatch; +use arrow_array::{Array, LargeStringArray, MapArray, StringArray, StringViewArray}; +use reqwest::{header::HeaderMap, Client, Method}; +use std::path::{Component, Path, PathBuf}; +use std::sync::{Arc, Mutex}; +use tokio::io::AsyncWriteExt; +use tokio::sync::Notify; +use tokio_util::io::ReaderStream; + +/// Local file authorization and driver-specific storage response policy. +#[derive(Debug, Clone, Default)] +pub struct VolumeOptions { + pub allowed_paths: Vec, + pub remove_not_found_is_success: bool, +} + +/// Result of explicitly completing a server-marked Volume instruction. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum VolumeCompletion { + NotVolume, + NeedsInputStream, + Completed, +} + +impl VolumeCompletion { + pub fn as_str(self) -> &'static str { + match self { + Self::NotVolume => "not_volume", + Self::NeedsInputStream => "needs_input_stream", + Self::Completed => "completed", + } + } +} + +#[derive(Default)] +enum CommitState { + #[default] + Ready, + Running, + Finished(Box>), +} + +/// The synchronous gate makes cancellation and local publication mutually exclusive. +#[derive(Default)] +pub(crate) struct VolumeState { + serial: tokio::sync::Mutex<()>, + commit: Mutex, + changed: Notify, +} + +fn cancelled() -> Error { + Error::cancelled().message("Volume transfer was cancelled") +} + +impl VolumeState { + pub(crate) fn new() -> Arc { + Arc::new(Self::default()) + } + + pub(crate) fn cached(&self) -> Option> { + match &*self.commit.lock().unwrap_or_else(|e| e.into_inner()) { + CommitState::Finished(result) => Some(result.as_ref().clone()), + CommitState::Ready | CommitState::Running => None, + } + } + + pub(crate) fn fail(&self, error: Error) -> Error { + let mut gate = self.commit.lock().unwrap_or_else(|e| e.into_inner()); + match &*gate { + CommitState::Finished(result) => { + if let Err(existing) = result.as_ref() { + return existing.clone(); + } + } + CommitState::Ready => *gate = CommitState::Finished(Box::new(Err(error.clone()))), + CommitState::Running => {} + } + error + } + + pub(crate) fn cancel(&self) { + let mut gate = self.commit.lock().unwrap_or_else(|e| e.into_inner()); + if !matches!(*gate, CommitState::Finished(_)) { + *gate = CommitState::Finished(Box::new(Err(cancelled()))); + self.changed.notify_waiters(); + } + } + + async fn cancellation(&self) { + loop { + let notified = self.changed.notified(); + tokio::pin!(notified); + notified.as_mut().enable(); + if matches!(self.cached(), Some(Err(error)) if error.code == crate::ErrorCode::Cancelled) + { + return; + } + notified.await; + } + } + + pub(crate) async fn complete( + &self, + batch: &ResultBatch, + client: &Client, + options: &VolumeOptions, + input_bytes: Option>, + ) -> Result { + let _serial = self.serial.lock().await; + { + let mut gate = self.commit.lock().unwrap_or_else(|e| e.into_inner()); + match &*gate { + CommitState::Finished(result) => return result.as_ref().clone(), + // Holding serialization proves that the previous initializer was dropped. + CommitState::Running => { + *gate = CommitState::Finished(Box::new(Err(cancelled()))); + return Err(cancelled()); + } + CommitState::Ready => {} + } + } + let instruction = Instruction::decode(batch); + let result = match instruction { + Ok(instruction) => { + if instruction.operation == "PUT" + && instruction.local_file == "__input_stream__" + && input_bytes.is_none() + { + return Ok(VolumeCompletion::NeedsInputStream); + } + { + let mut gate = self.commit.lock().unwrap_or_else(|e| e.into_inner()); + if let CommitState::Finished(result) = &*gate { + return result.as_ref().clone(); + } + // Running is a cancellation tombstone if this future is abandoned. + *gate = CommitState::Running; + } + tokio::select! { + biased; + result = self.transfer(instruction, client, options, input_bytes) => result, + _ = self.cancellation() => Err(cancelled()), + } + } + Err(error) => Err(error), + }; + let mut gate = self.commit.lock().unwrap_or_else(|e| e.into_inner()); + if let CommitState::Finished(result) = &*gate { + return result.as_ref().clone(); + } + *gate = CommitState::Finished(Box::new(result.clone())); + result + } + + async fn transfer( + &self, + instruction: Instruction, + client: &Client, + options: &VolumeOptions, + input_bytes: Option>, + ) -> Result { + let method = match instruction.operation.as_str() { + "PUT" => Method::PUT, + "GET" => Method::GET, + "REMOVE" => Method::DELETE, + _ => return Err(invalid("Unsupported Volume operation")), + }; + let mut request = client + .request(method, &instruction.url) + .headers(instruction.headers); + let local_path = if instruction.operation == "REMOVE" { + None + } else if instruction.operation == "PUT" && instruction.local_file == "__input_stream__" { + request = request.body(input_bytes.ok_or_else(|| invalid("Missing input stream"))?); + None + } else { + let path = allowed_path(&instruction.local_file, &options.allowed_paths)?; + if instruction.operation == "PUT" { + let file = std::fs::File::open(&path) + .map_err(|e| local_error(e, &instruction.local_file))?; + let size = file + .metadata() + .map_err(|e| local_error(e, &instruction.local_file))? + .len(); + request = request.header(reqwest::header::CONTENT_LENGTH, size).body( + reqwest::Body::wrap_stream(ReaderStream::new(tokio::fs::File::from_std(file))), + ); + } + Some(path) + }; + let mut destination = if instruction.operation == "GET" { + let path = local_path.as_ref().expect("GET path was checked"); + // Match normal write permissions even though publication uses replacement. + let permissions = match std::fs::OpenOptions::new().write(true).open(path) { + Ok(file) => Some( + file.metadata() + .map_err(|e| local_error(e, &instruction.local_file))? + .permissions(), + ), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => None, + Err(error) => return Err(local_error(error, &instruction.local_file)), + }; + let mut builder = tempfile::Builder::new(); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + builder.permissions(std::fs::Permissions::from_mode(0o666)); + } + let temp = builder + .tempfile_in( + path.parent() + .ok_or_else(|| invalid("Missing destination parent"))?, + ) + .map_err(|e| local_error(e, &instruction.local_file))?; + if let Some(permissions) = permissions { + temp.as_file() + .set_permissions(permissions) + .map_err(|e| local_error(e, &instruction.local_file))?; + } + let writer = tokio::fs::File::from_std( + temp.reopen() + .map_err(|e| local_error(e, &instruction.local_file))?, + ); + Some((temp, writer)) + } else { + None + }; + + // This client has workspace TLS/proxy/timeouts, but no workspace auth headers. + // A single attempt avoids replaying an upload after an ambiguous response. + let mut response = request.send().await.map_err(storage_error)?; + let status = response.status(); + if !status.is_success() + && !(instruction.operation == "REMOVE" + && status.as_u16() == 404 + && options.remove_not_found_is_success) + { + return Err(Error::from_http_status(status.as_u16()).message(format!( + "Volume storage request failed: HTTP {}", + status.as_u16() + ))); + } + if let Some((temp, mut writer)) = destination.take() { + while let Some(bytes) = response.chunk().await.map_err(storage_error)? { + writer + .write_all(&bytes) + .await + .map_err(|e| local_error(e, &instruction.local_file))?; + } + writer + .flush() + .await + .map_err(|e| local_error(e, &instruction.local_file))?; + drop(writer); + let mut gate = self.commit.lock().unwrap_or_else(|e| e.into_inner()); + if let CommitState::Finished(result) = &*gate { + return result.as_ref().clone(); + } + temp.persist(local_path.as_ref().expect("GET destination")) + .map_err(|e| local_error(e.error, &instruction.local_file))?; + *gate = CommitState::Finished(Box::new(Ok(VolumeCompletion::Completed))); + } + Ok(VolumeCompletion::Completed) + } +} + +fn invalid(message: &str) -> Error { + Error::invalid_argument().message(message) +} + +fn storage_error(error: reqwest::Error) -> Error { + Error::network_error() + .with_retryable(false) + .message(format!( + "Volume storage request failed: {}", + error.without_url() + )) +} + +fn local_error(error: std::io::Error, path: &str) -> Error { + let mut result = Error::io().message(format!("{error}: {path}")); + result.local_error = Some(Box::new(LocalFileError { + raw_os_error: error.raw_os_error(), + kind: format!("{:?}", error.kind()), + path: path.to_owned(), + })); + result +} + +fn normalize(path: &Path) -> Result { + let absolute = + std::path::absolute(path).map_err(|e| local_error(e, &path.to_string_lossy()))?; + let mut normalized = PathBuf::new(); + for component in absolute.components() { + match component { + Component::ParentDir => { + normalized.pop(); + } + Component::CurDir => {} + _ => normalized.push(component.as_os_str()), + } + } + Ok(normalized) +} + +fn resolve_existing_parent(path: &Path, requested: &str) -> Result { + match path.canonicalize() { + Ok(path) => Ok(path), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => { + if std::fs::symlink_metadata(path).is_ok_and(|m| m.file_type().is_symlink()) { + let target = std::fs::read_link(path).map_err(|e| local_error(e, requested))?; + let target = if target.is_absolute() { + target + } else { + path.parent() + .ok_or_else(|| invalid("Invalid local path"))? + .join(target) + }; + return resolve_existing_parent(&normalize(&target)?, requested); + } + let parent = path.parent().ok_or_else(|| local_error(error, requested))?; + let name = path + .file_name() + .ok_or_else(|| invalid("Invalid local path"))?; + Ok(resolve_existing_parent(parent, requested)?.join(name)) + } + Err(error) => Err(local_error(error, requested)), + } +} + +fn within_root(path: &Path, root: &Path) -> bool { + #[cfg(windows)] + { + let mut path = path.components(); + root.components().all(|root| { + path.next().is_some_and(|part| { + part.as_os_str().to_string_lossy().to_lowercase() + == root.as_os_str().to_string_lossy().to_lowercase() + }) + }) + } + #[cfg(not(windows))] + { + path.starts_with(root) + } +} + +fn allowed_path(requested: &str, roots: &[PathBuf]) -> Result { + if requested.is_empty() { + return Err(invalid("Local file path is empty")); + } + let path = normalize(Path::new(requested))?; + let roots = roots + .iter() + .filter(|root| !root.as_os_str().is_empty()) + .map(|root| normalize(root)) + .collect::>>()?; + if !roots.iter().any(|root| within_root(&path, root)) { + return Err(invalid( + "Local file path is outside the configured allowed roots", + )); + } + let resolved = resolve_existing_parent(&path, requested)?; + for root in roots { + let root = resolve_existing_parent(&root, requested)?; + if within_root(&resolved, &root) { + return Ok(resolved); + } + } + Err(invalid( + "Resolved local file path is outside the configured allowed roots", + )) +} + +struct Instruction { + operation: String, + url: String, + headers: HeaderMap, + local_file: String, +} + +fn string_at(array: &dyn Array, row: usize) -> Result<&str> { + if array.is_null(row) { + return Err(invalid("Null Volume instruction field")); + } + if let Some(values) = array.as_any().downcast_ref::() { + return Ok(values.value(row)); + } + if let Some(values) = array.as_any().downcast_ref::() { + return Ok(values.value(row)); + } + if let Some(values) = array.as_any().downcast_ref::() { + return Ok(values.value(row)); + } + Err(invalid("Invalid Volume instruction column type")) +} + +impl Instruction { + fn decode(batch: &ResultBatch) -> Result { + let ResultBatch::Arrow(batch) = batch; + if batch.num_rows() != 1 { + return Err(invalid("Expected one Volume instruction row")); + } + let schema = batch.schema(); + let column = |name: &str| -> Result<&dyn Array> { + let index = schema + .fields() + .iter() + .position(|f| f.name() == name) + .ok_or_else(|| invalid("Missing Volume instruction column"))?; + Ok(batch.column(index).as_ref()) + }; + let operation = string_at(column("operation")?, 0)?.to_owned(); + let headers = column("headers")?; + let mut parsed_headers = HeaderMap::new(); + let mut add_header = |name: &str, value: &str| -> Result<()> { + parsed_headers.insert( + reqwest::header::HeaderName::from_bytes(name.as_bytes()) + .map_err(|_| invalid("Invalid Volume storage header name"))?, + value + .parse() + .map_err(|_| invalid("Invalid Volume storage header value"))?, + ); + Ok(()) + }; + if !headers.is_null(0) { + if let Some(map) = headers.as_any().downcast_ref::() { + let entries = map.value(0); + for row in 0..entries.len() { + add_header( + string_at(entries.column(0).as_ref(), row)?, + string_at(entries.column(1).as_ref(), row)?, + )?; + } + } else { + let headers: std::collections::HashMap = + serde_json::from_str(string_at(headers, 0)?) + .map_err(|_| invalid("Invalid Volume storage headers"))?; + for (name, value) in headers { + add_header(&name, &value)?; + } + } + } + let local_file = if operation == "REMOVE" { + String::new() + } else { + string_at(column("localFile")?, 0)?.to_owned() + }; + Ok(Self { + operation, + url: string_at(column("presignedUrl")?, 0)?.to_owned(), + headers: parsed_headers, + local_file, + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use arrow_array::builder::{MapBuilder, StringBuilder}; + use arrow_array::{ArrayRef, RecordBatch}; + use arrow_schema::{DataType, Field, Schema}; + use std::time::Duration; + use wiremock::matchers::{body_bytes, header, method, path}; + use wiremock::{Mock, MockServer, ResponseTemplate}; + + fn instruction(operation: &str, url: &str, local: &Path) -> ResultBatch { + let mut headers = MapBuilder::new(None, StringBuilder::new(), StringBuilder::new()); + headers.keys().append_value("x-storage-token"); + headers.values().append_value("server-token"); + headers.append(true).unwrap(); + let arrays: Vec = vec![ + Arc::new(StringArray::from(vec![operation])), + Arc::new(StringArray::from(vec![url])), + Arc::new(headers.finish()), + Arc::new(StringArray::from(vec![local.to_str().unwrap()])), + ]; + let schema = Schema::new( + ["operation", "presignedUrl", "headers", "localFile"] + .iter() + .zip(&arrays) + .map(|(name, values)| Field::new(*name, values.data_type().clone(), true)) + .collect::>(), + ); + ResultBatch::Arrow(RecordBatch::try_new(Arc::new(schema), arrays).unwrap()) + } + + fn options(root: &Path) -> VolumeOptions { + VolumeOptions { + allowed_paths: vec![root.to_owned()], + ..Default::default() + } + } + + #[tokio::test] + async fn stream_handshake_accepts_empty_bytes_once_and_keeps_success_after_cancel() { + let server = MockServer::start().await; + Mock::given(method("PUT")) + .and(path("/object")) + .and(body_bytes(Vec::::new())) + .and(header("x-storage-token", "server-token")) + .respond_with(ResponseTemplate::new(200)) + .expect(1) + .mount(&server) + .await; + let batch = instruction( + "PUT", + &format!("{}/object", server.uri()), + Path::new("__input_stream__"), + ); + let state = VolumeState::new(); + let client = Client::new(); + assert_eq!( + state + .complete(&batch, &client, &VolumeOptions::default(), None) + .await + .unwrap(), + VolumeCompletion::NeedsInputStream + ); + assert!(server.received_requests().await.unwrap().is_empty()); + assert_eq!( + state + .complete(&batch, &client, &VolumeOptions::default(), Some(vec![])) + .await + .unwrap(), + VolumeCompletion::Completed + ); + state.cancel(); + assert_eq!( + state + .complete(&batch, &client, &VolumeOptions::default(), Some(vec![1])) + .await + .unwrap(), + VolumeCompletion::Completed + ); + } + + #[tokio::test] + async fn file_put_preserves_streamed_body_and_server_headers() { + let server = MockServer::start().await; + let dir = tempfile::tempdir().unwrap(); + let source = dir.path().join("source"); + let bytes = vec![42; 128 * 1024]; + std::fs::write(&source, &bytes).unwrap(); + Mock::given(method("PUT")) + .and(body_bytes(bytes)) + .and(header("x-storage-token", "server-token")) + .respond_with(ResponseTemplate::new(200)) + .expect(1) + .mount(&server) + .await; + let batch = instruction("PUT", &server.uri(), &source); + VolumeState::new() + .complete(&batch, &Client::new(), &options(dir.path()), None) + .await + .unwrap(); + assert!(!server.received_requests().await.unwrap()[0] + .headers + .contains_key("authorization")); + } + + #[tokio::test] + async fn get_replaces_destination_and_caches_error_without_replay() { + let server = MockServer::start().await; + Mock::given(method("GET")) + .and(path("/ok")) + .respond_with(ResponseTemplate::new(200).set_body_bytes(b"new bytes")) + .expect(1) + .mount(&server) + .await; + Mock::given(method("GET")) + .and(path("/fail")) + .respond_with(ResponseTemplate::new(403)) + .expect(1) + .mount(&server) + .await; + let dir = tempfile::tempdir().unwrap(); + let dest = dir.path().join("download"); + std::fs::write(&dest, b"old bytes").unwrap(); + let batch = instruction("GET", &format!("{}/ok", server.uri()), &dest); + let completed = VolumeState::new(); + completed + .complete(&batch, &Client::new(), &options(dir.path()), None) + .await + .unwrap(); + completed.cancel(); + assert_eq!( + completed + .complete(&batch, &Client::new(), &options(dir.path()), None) + .await + .unwrap(), + VolumeCompletion::Completed + ); + assert_eq!(std::fs::read(&dest).unwrap(), b"new bytes"); + let state = VolumeState::new(); + let batch = instruction( + "GET", + &format!("{}/fail?secret=hidden", server.uri()), + &dest, + ); + let error = state + .complete(&batch, &Client::new(), &options(dir.path()), None) + .await + .unwrap_err(); + assert_eq!(error.http_status, Some(403)); + assert!(!error.message.contains("hidden")); + state.cancel(); + assert_eq!( + state + .complete(&batch, &Client::new(), &options(dir.path()), None) + .await + .unwrap_err() + .http_status, + Some(403) + ); + assert_eq!(std::fs::read(&dest).unwrap(), b"new bytes"); + assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 1); + } + + #[tokio::test] + async fn remove_has_narrow_missing_status_policy_and_no_local_path_requirement() { + let server = MockServer::start().await; + Mock::given(method("DELETE")) + .respond_with(ResponseTemplate::new(404)) + .expect(2) + .mount(&server) + .await; + let batch = instruction("REMOVE", &server.uri(), Path::new("")); + let strict = VolumeOptions::default(); + assert_eq!( + VolumeState::new() + .complete(&batch, &Client::new(), &strict, None) + .await + .unwrap_err() + .http_status, + Some(404) + ); + let permissive = VolumeOptions { + remove_not_found_is_success: true, + ..strict + }; + assert_eq!( + VolumeState::new() + .complete(&batch, &Client::new(), &permissive, None) + .await + .unwrap(), + VolumeCompletion::Completed + ); + } + + #[tokio::test] + async fn abandoned_or_cancelled_get_cannot_publish_or_restart() { + let server = MockServer::start().await; + Mock::given(method("GET")) + .respond_with( + ResponseTemplate::new(200) + .set_body_bytes(b"new") + .set_delay(Duration::from_millis(300)), + ) + .expect(2) + .mount(&server) + .await; + let dir = tempfile::tempdir().unwrap(); + let dest = dir.path().join("download"); + std::fs::write(&dest, b"old").unwrap(); + let batch = instruction("GET", &server.uri(), &dest); + let options = options(dir.path()); + let client = Client::new(); + for cancel in [false, true] { + let state = VolumeState::new(); + let mut future = Box::pin(state.complete(&batch, &client, &options, None)); + tokio::select! { + result = &mut future => panic!("unexpected early completion: {result:?}"), + _ = async { + loop { + if server.received_requests().await.unwrap().len() >= if cancel { 2 } else { 1 } { break; } + tokio::task::yield_now().await; + } + } => {} + } + if cancel { + state.cancel(); + assert_eq!( + future.as_mut().await.unwrap_err().code, + crate::ErrorCode::Cancelled + ); + } + drop(future); + assert_eq!( + state + .complete(&batch, &client, &options, None) + .await + .unwrap_err() + .code, + crate::ErrorCode::Cancelled + ); + assert_eq!(std::fs::read(&dest).unwrap(), b"old"); + } + assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 1); + } + + #[tokio::test] + async fn truncated_get_preserves_destination() { + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}", listener.local_addr().unwrap()); + let peer = tokio::spawn(async move { + let (mut socket, _) = listener.accept().await.unwrap(); + let mut request = [0; 2048]; + assert!(socket.read(&mut request).await.unwrap() > 0); + socket + .write_all( + b"HTTP/1.1 200 OK\r\nContent-Length: 20\r\nConnection: close\r\n\r\nshort", + ) + .await + .unwrap(); + }); + let dir = tempfile::tempdir().unwrap(); + let dest = dir.path().join("download"); + std::fs::write(&dest, b"old").unwrap(); + let batch = instruction("GET", &url, &dest); + let error = VolumeState::new() + .complete(&batch, &Client::new(), &options(dir.path()), None) + .await + .unwrap_err(); + assert_eq!(error.code, crate::ErrorCode::NetworkError); + assert_eq!(std::fs::read(&dest).unwrap(), b"old"); + assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 1); + peer.await.unwrap(); + } + + #[cfg(unix)] + #[test] + fn symlinks_require_lexical_authority_and_resolved_target_in_any_allowed_root() { + use std::os::unix::fs::symlink; + let dir = tempfile::tempdir().unwrap(); + let root = dir.path().join("root"); + let other = dir.path().join("other"); + std::fs::create_dir(&root).unwrap(); + std::fs::create_dir(&other).unwrap(); + std::fs::write(root.join("file"), b"ok").unwrap(); + symlink(root.join("file"), root.join("inside")).unwrap(); + symlink(other.join("missing"), root.join("escape")).unwrap(); + symlink(&root, dir.path().join("alias")).unwrap(); + assert_eq!( + allowed_path( + root.join("inside").to_str().unwrap(), + std::slice::from_ref(&root) + ) + .unwrap(), + root.join("file") + ); + assert!(allowed_path( + root.join("escape").to_str().unwrap(), + std::slice::from_ref(&root) + ) + .is_err()); + assert_eq!( + allowed_path( + root.join("escape").to_str().unwrap(), + &[root.clone(), other.clone()] + ) + .unwrap(), + other.join("missing") + ); + assert!(allowed_path( + dir.path().join("alias/file").to_str().unwrap(), + std::slice::from_ref(&root) + ) + .is_err()); + assert!(allowed_path(root.join("../other/missing").to_str().unwrap(), &[root]).is_err()); + } + + #[tokio::test] + async fn local_errors_retain_os_code_and_requested_filename() { + let dir = tempfile::tempdir().unwrap(); + let source = dir.path().join("missing"); + let batch = instruction("PUT", "http://127.0.0.1:1?secret=hidden", &source); + let error = VolumeState::new() + .complete(&batch, &Client::new(), &options(dir.path()), None) + .await + .unwrap_err(); + let local = error.local_error.unwrap(); + assert_eq!(local.kind, "NotFound"); + assert!(local.raw_os_error.is_some()); + assert_eq!(local.path, source.to_str().unwrap()); + assert!(!error.message.contains("hidden")); + } + + #[test] + fn malformed_instruction_is_rejected() { + let schema = Arc::new(Schema::new(vec![Field::new( + "operation", + DataType::Utf8, + true, + )])); + let batch = ResultBatch::Arrow( + RecordBatch::try_new(schema, vec![Arc::new(StringArray::from(vec!["PUT"]))]).unwrap(), + ); + assert_eq!( + Instruction::decode(&batch).err().unwrap().code, + crate::ErrorCode::InvalidArgument + ); + } +} diff --git a/tests/v0_volume_wiremock.rs b/tests/v0_volume_wiremock.rs new file mode 100644 index 00000000..20b93e33 --- /dev/null +++ b/tests/v0_volume_wiremock.rs @@ -0,0 +1,298 @@ +// 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. + +//! Volume completion authority and lifecycle through public execution handles. + +use arrow_array::{RecordBatch, StringArray}; +use arrow_ipc::writer::StreamWriter; +use arrow_schema::{DataType, Field, Schema}; +use base64::{engine::general_purpose::STANDARD, Engine}; +use databricks_sql_kernel::{ + AuthConfig, ConnectionConfig, DirectStatement, ErrorCode, ExecutedStatementHandle, Session, + VolumeCompletion, VolumeOptions, +}; +use serde_json::json; +use std::sync::Arc; +use std::time::Duration; +use wiremock::matchers::{method, path}; +use wiremock::{Mock, MockServer, ResponseTemplate}; + +fn response(server: &MockServer, marked: bool, local: &str) -> serde_json::Value { + let names = ["operation", "presignedUrl", "headers", "localFile"]; + let schema = Arc::new(Schema::new( + names + .iter() + .map(|name| Field::new(*name, DataType::Utf8, true)) + .collect::>(), + )); + let values = [ + "GET".to_owned(), + format!("{}/object", server.uri()), + "{}".to_owned(), + local.to_owned(), + ]; + let batch = RecordBatch::try_new( + schema, + values + .iter() + .map(|value| Arc::new(StringArray::from(vec![value.as_str()])) as _) + .collect(), + ) + .unwrap(); + let mut ipc = Vec::new(); + { + let mut writer = StreamWriter::try_new(&mut ipc, &batch.schema()).unwrap(); + writer.write(&batch).unwrap(); + writer.finish().unwrap(); + } + json!({ + "statement_id": "volume-stmt", "status": {"state": "CLOSED"}, + "manifest": { + "format": "ARROW_STREAM", "is_volume_operation": marked, + "schema": {"column_count":4,"columns": names.iter().enumerate().map(|(i,name)| json!({"name":name,"type_name":"STRING","type_text":"STRING","position":i})).collect::>()}, + "total_row_count":1,"total_chunk_count":1 + }, + "result": {"chunk_index":0,"row_offset":0,"row_count":1,"attachment":STANDARD.encode(&ipc)} + }) +} + +async fn session(server: &MockServer, body: serde_json::Value) -> Session { + Mock::given(method("POST")) + .and(path("/api/2.0/sql/warehouses/wh/sessions")) + .respond_with( + ResponseTemplate::new(200) + .set_body_json(json!({"session_id":"sess","warehouse_id":"wh"})), + ) + .mount(server) + .await; + Mock::given(method("POST")) + .and(path("/api/2.0/sql/statements")) + .respond_with(ResponseTemplate::new(200).set_body_json(body.clone())) + .mount(server) + .await; + Mock::given(method("GET")) + .and(path("/api/2.0/sql/statements/volume-stmt")) + .respond_with(ResponseTemplate::new(200).set_body_json(body)) + .mount(server) + .await; + Mock::given(method("DELETE")) + .respond_with(ResponseTemplate::new(200)) + .mount(server) + .await; + Mock::given(method("POST")) + .and(path("/api/2.0/sql/statements/volume-stmt/cancel")) + .respond_with(ResponseTemplate::new(200)) + .mount(server) + .await; + Session::builder() + .connection( + ConnectionConfig::from_http_path(server.uri(), "/sql/1.0/warehouses/wh").unwrap(), + ) + .auth(AuthConfig::Pat { + token: "workspace-token".into(), + identity_federation_client_id: None, + }) + .open() + .await + .unwrap() +} + +#[tokio::test] +async fn sync_and_direct_closed_results_complete_explicitly_and_keep_raw_rows() { + for direct in [false, true] { + let server = MockServer::start().await; + let dir = tempfile::tempdir().unwrap(); + let dest = dir.path().join("download"); + let session = session(&server, response(&server, true, dest.to_str().unwrap())).await; + Mock::given(method("GET")) + .and(path("/object")) + .respond_with(ResponseTemplate::new(200).set_body_bytes(b"data")) + .expect(1) + .mount(&server) + .await; + let mut stmt = session.statement(); + stmt.spec().sql("server decides the operation"); + let mut exec = if direct { + match stmt.execute_direct().await.unwrap() { + DirectStatement::Completed(exec) => exec, + _ => panic!("expected inline completion"), + } + } else { + stmt.execute().await.unwrap() + }; + assert!(!dest.exists()); + let stream = exec.result_stream_mut(); + assert!(stream.is_volume_operation()); + let options = VolumeOptions { + allowed_paths: vec![dir.path().to_owned()], + ..Default::default() + }; + assert_eq!( + stream + .complete_volume_operation(&options, None) + .await + .unwrap(), + VolumeCompletion::Completed + ); + assert_eq!(std::fs::read(&dest).unwrap(), b"data"); + let requests = server.received_requests().await.unwrap(); + let storage = requests + .iter() + .find(|request| request.url.path() == "/object") + .unwrap(); + assert!(!storage.headers.contains_key("authorization")); + assert!(exec.next_batch().await.unwrap().is_some()); + assert_eq!( + exec.result_stream_mut() + .complete_volume_operation(&options, None) + .await + .unwrap(), + VolumeCompletion::Completed + ); + exec.close().await.unwrap(); + session.close().await.unwrap(); + } +} + +#[tokio::test] +async fn marker_false_and_id_attachment_cannot_initiate_transfer() { + for marked in [false, true] { + let server = MockServer::start().await; + let session = session(&server, response(&server, marked, "/never-created")).await; + Mock::given(method("GET")) + .and(path("/object")) + .respond_with(ResponseTemplate::new(200)) + .expect(0) + .mount(&server) + .await; + let attached = session.attach_async_statement("volume-stmt").await.unwrap(); + let mut stream = attached.fetch_result().await.unwrap(); + assert_eq!( + stream + .complete_volume_operation(&VolumeOptions::default(), None) + .await + .unwrap(), + VolumeCompletion::NotVolume + ); + assert!(stream.next_batch().await.unwrap().is_some()); + if !marked { + let mut stmt = session.statement(); + stmt.spec().sql("PUT does not authorize local effects"); + let mut exec = stmt.execute().await.unwrap(); + assert!(!exec.result_stream().is_volume_operation()); + assert_eq!( + exec.result_stream_mut() + .complete_volume_operation(&VolumeOptions::default(), None) + .await + .unwrap(), + VolumeCompletion::NotVolume + ); + } + session.close().await.unwrap(); + } +} + +#[tokio::test] +async fn owner_reader_and_repeated_materialization_share_one_completion() { + let server = MockServer::start().await; + let dir = tempfile::tempdir().unwrap(); + let dest = dir.path().join("download"); + let session = session(&server, response(&server, true, dest.to_str().unwrap())).await; + Mock::given(method("GET")) + .and(path("/object")) + .respond_with(ResponseTemplate::new(200).set_body_bytes(b"data")) + .expect(1) + .mount(&server) + .await; + let mut stmt = session.statement(); + stmt.spec().sql("operation"); + let owner = stmt.submit().await.unwrap(); + let reader = owner.reader().unwrap(); + let mut first = reader.fetch_result().await.unwrap(); + let mut second = owner.fetch_result().await.unwrap(); + let options = VolumeOptions { + allowed_paths: vec![dir.path().to_owned()], + ..Default::default() + }; + let (a, b) = tokio::join!( + first.complete_volume_operation(&options, None), + second.complete_volume_operation(&options, None) + ); + assert_eq!(a.unwrap(), VolumeCompletion::Completed); + assert_eq!(b.unwrap(), VolumeCompletion::Completed); + drop(reader); + assert_eq!(std::fs::read(&dest).unwrap(), b"data"); + session.close().await.unwrap(); +} + +#[tokio::test] +async fn cancellation_and_session_close_interrupt_transfer_after_sql_closed() { + for close_session in [false, true] { + let server = MockServer::start().await; + let dir = tempfile::tempdir().unwrap(); + let dest = dir.path().join("download"); + std::fs::write(&dest, b"old").unwrap(); + let mut session = + Some(session(&server, response(&server, true, dest.to_str().unwrap())).await); + Mock::given(method("GET")) + .and(path("/object")) + .respond_with( + ResponseTemplate::new(200) + .set_delay(Duration::from_secs(3)) + .set_body_bytes(b"new"), + ) + .mount(&server) + .await; + let mut stmt = session.as_ref().unwrap().statement(); + let canceller = stmt.canceller(); + stmt.spec().sql("operation"); + let mut exec = stmt.execute().await.unwrap(); + let options = VolumeOptions { + allowed_paths: vec![dir.path().to_owned()], + ..Default::default() + }; + let complete = exec + .result_stream_mut() + .complete_volume_operation(&options, None); + let cancel = async { + loop { + if server + .received_requests() + .await + .unwrap() + .iter() + .any(|req| req.url.path() == "/object") + { + break; + } + tokio::task::yield_now().await; + } + if close_session { + session.take().unwrap().close().await.unwrap(); + } else { + canceller.cancel().await.unwrap(); + } + }; + let (result, _) = tokio::time::timeout(Duration::from_secs(1), async { + tokio::join!(complete, cancel) + }) + .await + .unwrap(); + assert_eq!(result.unwrap_err().code, ErrorCode::Cancelled); + assert_eq!(std::fs::read(&dest).unwrap(), b"old"); + if let Some(session) = session { + session.close().await.unwrap(); + } + } +} From d6706e52dd92b1bb216d1d8baec1a6b0796e614c Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Fri, 13 Nov 2026 22:36:54 +0000 Subject: [PATCH 02/63] feat: expose Volume completion through native driver adapters Signed-off-by: Aakash Saravanan --- adbc/Cargo.lock | 1 + adbc/src/error.rs | 14 +++ adbc/src/reader.rs | 4 + adbc/src/statement.rs | 89 +++++++++++++-- include/databricks_kernel.h | 16 +++ napi/Cargo.lock | 39 +++++++ napi/NEXT_CHANGELOG.md | 3 + napi/README.md | 7 ++ napi/index.d.ts | 6 + napi/src/async_statement.rs | 38 ++++++- napi/src/error.rs | 25 +++++ napi/src/statement.rs | 59 +++++++++- src/c_abi/error.rs | 67 ++++++++++++ src/c_abi/result.rs | 188 +++++++++++++++++++++++++++++++- src/c_abi/statement.rs | 25 +++++ src/result_stream.rs | 4 + src/statement/executed_async.rs | 9 ++ src/statement/mutable.rs | 8 ++ 18 files changed, 590 insertions(+), 12 deletions(-) diff --git a/adbc/Cargo.lock b/adbc/Cargo.lock index dcaa4b65..6c65d761 100644 --- a/adbc/Cargo.lock +++ b/adbc/Cargo.lock @@ -678,6 +678,7 @@ dependencies = [ "serde", "serde_json", "sha2 0.11.1", + "tempfile", "thiserror 2.0.21", "tokio", "tokio-util", diff --git a/adbc/src/error.rs b/adbc/src/error.rs index 54cbe4a9..17584693 100644 --- a/adbc/src/error.rs +++ b/adbc/src/error.rs @@ -60,6 +60,20 @@ pub(crate) fn map_kernel_error(source: kernel::Error) -> Error { mapped.details = source .error_code .map(|code| vec![("databricks.error_code".to_string(), code.into_bytes())]); + if let Some(local) = source.local_error { + let details = mapped.details.get_or_insert_default(); + details.push(( + "databricks.local_error_kind".into(), + local.kind.into_bytes(), + )); + details.push(("databricks.local_path".into(), local.path.into_bytes())); + if let Some(errno) = local.raw_os_error { + details.push(( + "databricks.local_os_error".into(), + errno.to_string().into_bytes(), + )); + } + } mapped } diff --git a/adbc/src/reader.rs b/adbc/src/reader.rs index d4288904..f6930d22 100644 --- a/adbc/src/reader.rs +++ b/adbc/src/reader.rs @@ -461,6 +461,7 @@ pub(crate) struct SequenceReader { base_spec: kernel::StatementSpec, parameter_style: ParameterStyle, client_timeout: Option, + volume_options: Option, rows: BoundRows, current: Option, schema: SchemaRef, @@ -476,6 +477,7 @@ impl SequenceReader { base_spec: kernel::StatementSpec, parameter_style: ParameterStyle, client_timeout: Option, + volume_options: Option, rows: BoundRows, executed: kernel::ExecutedStatement, connection_operation: OperationGuard, @@ -489,6 +491,7 @@ impl SequenceReader { base_spec, parameter_style, client_timeout, + volume_options, rows, current: Some(executed), schema, @@ -582,6 +585,7 @@ impl Iterator for SequenceReader { &row, self.parameter_style, self.client_timeout, + self.volume_options.as_ref(), ) { Ok(executed) => executed, Err(source) => return self.fail(ArrowError::ExternalError(Box::new(source))), diff --git a/adbc/src/statement.rs b/adbc/src/statement.rs index 1a6b5899..2a986acc 100644 --- a/adbc/src/statement.rs +++ b/adbc/src/statement.rs @@ -32,6 +32,7 @@ use crate::error::{adbc_error, map_kernel_error, option_not_found, unsupported}; use crate::reader::{AsyncKernelReader, BoundRows, KernelReader, SequenceReader, SlicingReader}; use crate::runtime::{RuntimeExt as _, RuntimeHandle}; +const STAGING_ALLOWED_PATHS_OPTION: &str = "adbc.databricks.statement.staging_allowed_local_paths"; const PARAMETER_STYLE_OPTION: &str = "adbc.databricks.statement.parameter_style"; const QUERY_TAGS_OPTION: &str = "adbc.databricks.statement.query_tags"; const CLIENT_TIMEOUT_OPTION: &str = "adbc.databricks.statement.client_timeout_ms"; @@ -84,6 +85,7 @@ pub struct Statement { cancellation_notify: Arc, connection_cancellation: Arc, metadata_options: MetadataCommandOptions, + volume_options: Option, } #[derive(Debug, Default)] @@ -161,11 +163,16 @@ impl SubmittedStatement<'_> { .executed .take() .ok_or_else(|| adbc_error("submitted statement was consumed", Status::InvalidState))?; - let stream = self + let mut stream = self .statement .runtime .block_on_safe(executed.await_result()) .map_err(map_kernel_error)?; + complete_volume( + &self.statement.runtime, + &mut stream, + self.statement.volume_options.as_ref(), + )?; let reader: Box = Box::new(AsyncKernelReader::new( Arc::clone(&self.statement.runtime), executed, @@ -188,11 +195,16 @@ impl SubmittedStatement<'_> { .executed .take() .ok_or_else(|| adbc_error("submitted statement was consumed", Status::InvalidState))?; - let stream = self + let mut stream = self .statement .runtime .block_on_safe(executed.fetch_result()) .map_err(map_kernel_error)?; + complete_volume( + &self.statement.runtime, + &mut stream, + self.statement.volume_options.as_ref(), + )?; let reader: Box = Box::new(AsyncKernelReader::new( Arc::clone(&self.statement.runtime), executed, @@ -234,6 +246,7 @@ pub struct StatementCancellationHandle { impl StatementCancellationHandle { pub fn cancel(&self) -> Result<()> { + self.canceller.cancel_volume_operation(); if self.current_cancellation.load(Ordering::Acquire) { return Ok(()); } @@ -335,6 +348,7 @@ impl Statement { canceller, runtime, binding: None, + volume_options: None, parameter_style: ParameterStyle::default(), prepared: false, client_timeout: None, @@ -392,10 +406,17 @@ impl Statement { )), }; self.blocking_execute.store(false, Ordering::Release); - match result { - Some(result) => result.map_err(map_kernel_error), - None => Err(adbc_error("operation was cancelled", Status::Cancelled)), - } + drop(inner); + let mut executed = match result { + Some(result) => result.map_err(map_kernel_error)?, + None => return Err(adbc_error("operation was cancelled", Status::Cancelled)), + }; + complete_volume( + &self.runtime, + executed.result_stream_mut(), + self.volume_options.as_ref(), + )?; + Ok(executed) } fn execute_async_inner( @@ -444,7 +465,9 @@ impl Statement { None => Err(adbc_error("operation was cancelled", Status::Cancelled)), }; self.blocking_execute.store(false, Ordering::Release); - result + let (executed, mut stream) = result?; + complete_volume(&self.runtime, &mut stream, self.volume_options.as_ref())?; + Ok((executed, stream)) } fn invalidate_results(&self) { @@ -470,6 +493,20 @@ impl Statement { return Ok(()); } match key { + STAGING_ALLOWED_PATHS_OPTION => { + let text = expect_string(value, key)?; + let roots: Vec = serde_json::from_str(&text).map_err(|_| { + adbc_error( + format!("{key} expects a JSON array of strings"), + Status::InvalidArguments, + ) + })?; + self.volume_options = Some(kernel::VolumeOptions { + allowed_paths: roots.into_iter().map(Into::into).collect(), + remove_not_found_is_success: false, + }); + Ok(()) + } ENABLE_DIRECT_RESULTS_OPTION => { self.enable_direct_results = expect_bool_string(value, key)?; Ok(()) @@ -584,6 +621,14 @@ impl Statement { fn get_other_string(&self, key: &str) -> Result { match key { + STAGING_ALLOWED_PATHS_OPTION => self + .volume_options + .as_ref() + .map(|options| { + serde_json::to_string(&options.allowed_paths) + .expect("paths serialize as strings") + }) + .ok_or_else(|| option_not_found("statement string", key)), 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( @@ -825,6 +870,7 @@ impl adbc_core::Statement for Statement { &row, self.parameter_style, self.client_timeout, + self.volume_options.as_ref(), )?; let expected_generation = self.generation.load(Ordering::Acquire); let reader: Box = Box::new(SequenceReader::new( @@ -835,6 +881,7 @@ impl adbc_core::Statement for Statement { base_spec, self.parameter_style, self.client_timeout, + self.volume_options.clone(), rows, executed, connection_operation, @@ -888,6 +935,7 @@ impl adbc_core::Statement for Statement { &row, self.parameter_style, self.client_timeout, + self.volume_options.as_ref(), ) { Ok(executed) => executed, Err(mut error) => { @@ -1123,6 +1171,7 @@ pub(crate) fn execute_bound_row( row: &RecordBatch, style: ParameterStyle, client_timeout: Option, + volume_options: Option<&kernel::VolumeOptions>, ) -> Result { let parameters = convert_binding(row, style)?; let mut inner = inner @@ -1164,11 +1213,33 @@ pub(crate) fn execute_bound_row( .spec() .param_raw(parameter.name, parameter.param_type, parameter.value); } - match client_timeout { + let mut executed = match client_timeout { Some(timeout) => runtime.block_on_safe(inner.execute_with_timeout(timeout)), None => runtime.block_on_safe(inner.execute()), } - .map_err(map_kernel_error) + .map_err(map_kernel_error)?; + drop(inner); + complete_volume(runtime, executed.result_stream_mut(), volume_options)?; + Ok(executed) +} + +fn complete_volume( + runtime: &RuntimeHandle, + stream: &mut kernel::ResultStream, + options: Option<&kernel::VolumeOptions>, +) -> Result<()> { + let Some(options) = options else { + return Ok(()); + }; + match runtime + .block_on_safe(stream.complete_volume_operation(options, None)) + .map_err(map_kernel_error)? + { + kernel::VolumeCompletion::NeedsInputStream => { + Err(unsupported("Volume PUT with input streams")) + } + kernel::VolumeCompletion::Completed | kernel::VolumeCompletion::NotVolume => Ok(()), + } } #[derive(Clone, Copy, PartialEq, Eq)] diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h index e167f181..fe88926b 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -190,6 +190,11 @@ typedef struct KernelError { * last kernel call cleared the buffer. */ bool kernel_get_last_error(KernelError* out); +/* These accessors preserve the last error. Strings are borrowed until the next + * error-clearing kernel call; absent strings are NULL, absent OS code is zero. */ +int32_t kernel_get_last_error_local_os_error(void); +const char* kernel_get_last_error_local_kind(void); +const char* kernel_get_last_error_local_path(void); /* ─── Opaque handles ────────────────────────────────────────────────── * @@ -966,6 +971,17 @@ KernelStatusCode kernel_executed_async_statement_close( */ KernelStatusCode kernel_result_stream_get_schema(kernel_result_stream_t* stream, struct ArrowSchema* out); +/* Volume completion preserves raw rows. Roots are a JSON array of strings; + * out_status is 0=ordinary result, 1=input bytes required, 2=completed. + * The detached result-stream canceller can interrupt completion. */ +KernelStatusCode kernel_executed_statement_is_volume_operation( + const kernel_executed_statement_t* exec, bool* out); +KernelStatusCode kernel_result_stream_is_volume_operation( + const kernel_result_stream_t* stream, bool* out); +KernelStatusCode kernel_result_stream_complete_volume_operation( + kernel_result_stream_t* stream, const char* allowed_paths_json, + bool remove_not_found_is_success, int32_t* out_status); + KernelStatusCode kernel_result_stream_next_batch(kernel_result_stream_t* stream, struct ArrowArray* out_array, struct ArrowSchema* out_schema); diff --git a/napi/Cargo.lock b/napi/Cargo.lock index b3b4c36e..e37a5a25 100644 --- a/napi/Cargo.lock +++ b/napi/Cargo.lock @@ -638,6 +638,7 @@ dependencies = [ "serde", "serde_json", "sha2 0.11.0", + "tempfile", "thiserror 2.0.19", "tokio", "tokio-util", @@ -796,6 +797,12 @@ dependencies = [ "pin-project-lite", ] +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + [[package]] name = "find-msvc-tools" version = "0.1.9" @@ -1493,6 +1500,12 @@ dependencies = [ "libc", ] +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + [[package]] name = "litemap" version = "0.8.2" @@ -2200,6 +2213,19 @@ dependencies = [ "semver", ] +[[package]] +name = "rustix" +version = "1.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.61.2", +] + [[package]] name = "rustls" version = "0.23.46" @@ -2546,6 +2572,19 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7b2093cf4c8eb1e67749a6762251bc9cd836b6fc171623bd0a9d324d37af2417" +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.4.3", + "once_cell", + "rustix", + "windows-sys 0.61.2", +] + [[package]] name = "thiserror" version = "1.0.69" diff --git a/napi/NEXT_CHANGELOG.md b/napi/NEXT_CHANGELOG.md index 8597f31e..38d38821 100644 --- a/napi/NEXT_CHANGELOG.md +++ b/napi/NEXT_CHANGELOG.md @@ -14,6 +14,9 @@ layout, or npm publishing. Pure-kernel changes go in the root ### Added +- Explicit Volume completion and marker access on synchronous and asynchronous + result handles, with structured local filesystem error details. + ### Changed ### Updated diff --git a/napi/README.md b/napi/README.md index 91f28adf..b7d6cdc4 100644 --- a/napi/README.md +++ b/napi/README.md @@ -7,6 +7,13 @@ the umbrella loader that re-exports the per-platform native packages. The binding itself lives under `src/`; its public TypeScript surface is declared in `index.d.ts`. +`Statement` and `AsyncResultHandle` expose `isVolumeOperation` and +`completeVolumeOperation(allowedPaths, removeNotFoundIsSuccess?)`. Completion +returns `not_volume`, `needs_input_stream` or `completed` and preserves the +instruction rows. The caller opts into transfer by supplying allowed local +roots; both lexical paths and resolved symlink targets must stay inside them. +The Node binding does not supply stream-upload bytes. + --- ## Building diff --git a/napi/index.d.ts b/napi/index.d.ts index 064f856d..83d8e032 100644 --- a/napi/index.d.ts +++ b/napi/index.d.ts @@ -878,6 +878,9 @@ export declare class AsyncStatement { * post-close contract. */ export declare class AsyncResultHandle { + get isVolumeOperation(): boolean + /** Completes marked file transfers and retains the instruction rows. */ + completeVolumeOperation(allowedPaths: Array, removeNotFoundIsSuccess?: boolean | undefined | null): Promise /** * Server-issued statement id. Cached at construction; readable * for log correlation. Matches the parent `AsyncStatement`'s @@ -1172,6 +1175,9 @@ export declare class Connection { * disposed statement can still read them. */ export declare class Statement { + get isVolumeOperation(): boolean + /** Completes marked file transfers and retains the instruction rows. */ + completeVolumeOperation(allowedPaths: Array, removeNotFoundIsSuccess?: boolean | undefined | null): Promise /** * Server-issued statement id. Cached at construction; readable * even after `close()` so JS-side log lines can correlate against diff --git a/napi/src/async_statement.rs b/napi/src/async_statement.rs index df416254..12d9f570 100644 --- a/napi/src/async_statement.rs +++ b/napi/src/async_statement.rs @@ -60,7 +60,7 @@ use tokio::sync::Mutex; use arrow_schema::SchemaRef; use databricks_sql_kernel::{ AsyncStatementCanceller, Error as KernelError, ExecutedAsyncStatement, ExecutedStatementHandle, - ResultBatch, ResultStream, Statement as KernelStatement, + ResultBatch, ResultStream, Statement as KernelStatement, VolumeOptions, }; use crate::error::napi_err_from_kernel; @@ -320,6 +320,7 @@ impl AsyncStatement { .map_err(napi_err_from_kernel)?; let statement_id = inner_state.executed_async.statement_id().to_owned(); let schema = stream.schema(); + let is_volume_operation = stream.is_volume_operation(); let stream = Arc::new(Mutex::new(Some(stream))); // Registered while `inner` is held, so a queued `close()` sees it. results @@ -330,6 +331,7 @@ impl AsyncStatement { inner: stream, schema, statement_id, + is_volume_operation, }) }) .await @@ -353,6 +355,7 @@ impl AsyncStatement { /// `InvalidStatementHandle`. #[napi] pub async fn cancel(&self) -> napi::Result<()> { + self.canceller.cancel_volume_operation(); if self.closed.load(Ordering::Acquire) { return Err(closed_err("AsyncStatement")); } @@ -379,6 +382,7 @@ impl AsyncStatement { /// unless a fetch was in progress when `close()` ran. #[napi] pub async fn close(&self) -> napi::Result<()> { + self.canceller.cancel_volume_operation(); let inner = Arc::clone(&self.inner); let closed = Arc::clone(&self.closed); let canceller = Arc::clone(&self.canceller); @@ -420,6 +424,7 @@ impl AsyncStatement { impl Drop for AsyncStatement { fn drop(&mut self) { + self.canceller.cancel_volume_operation(); // Best-effort cleanup — same shape as `Connection::Drop`. // JS callers needing a guaranteed close-with-error-surface // call `close()` explicitly. @@ -459,10 +464,41 @@ pub struct AsyncResultHandle { inner: Arc, schema: SchemaRef, statement_id: String, + is_volume_operation: bool, } #[napi] impl AsyncResultHandle { + #[napi(getter)] + pub fn is_volume_operation(&self) -> bool { + self.is_volume_operation + } + + /// Complete a server-marked file transfer while retaining its instruction rows. + #[napi] + pub async fn complete_volume_operation( + &self, + allowed_paths: Vec, + remove_not_found_is_success: Option, + ) -> napi::Result { + let options = VolumeOptions { + allowed_paths: allowed_paths.into_iter().map(Into::into).collect(), + remove_not_found_is_success: remove_not_found_is_success.unwrap_or(false), + }; + let inner = Arc::clone(&self.inner); + guarded(async move { + let mut guard = inner.lock().await; + guard + .as_mut() + .ok_or_else(|| closed_err("AsyncResultHandle"))? + .complete_volume_operation(&options, None) + .await + .map(|status| status.as_str().to_owned()) + .map_err(napi_err_from_kernel) + }) + .await + } + /// Server-issued statement id. Cached at construction; readable /// for log correlation. Matches the parent `AsyncStatement`'s /// `statementId`. diff --git a/napi/src/error.rs b/napi/src/error.rs index 70518fe3..7f52d897 100644 --- a/napi/src/error.rs +++ b/napi/src/error.rs @@ -143,6 +143,13 @@ 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(local) = e.local_error { + if let Some(errno) = local.raw_os_error { + obj.insert("localOsError".to_owned(), Value::from(errno)); + } + obj.insert("localErrorKind".to_owned(), Value::from(local.kind)); + obj.insert("localPath".to_owned(), Value::from(local.path)); + } // 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 @@ -196,6 +203,24 @@ fn error_code_str(code: ErrorCode) -> &'static str { mod tests { use super::*; + #[test] + fn local_error_metadata_is_optional_and_preserved() { + let mut error = KernelError::not_found().message("missing local file"); + error.local_error = Some(Box::new(databricks_sql_kernel::LocalFileError { + raw_os_error: Some(2), + kind: "NotFound".into(), + path: "local-file".into(), + })); + let encoded = napi_err_from_kernel(error); + let value: Value = serde_json::from_str(&encoded.reason[ERROR_SENTINEL.len()..]).unwrap(); + assert_eq!(value["localOsError"], 2); + assert_eq!(value["localErrorKind"], "NotFound"); + assert_eq!(value["localPath"], "local-file"); + let encoded = napi_err_from_kernel(KernelError::internal()); + let value: Value = serde_json::from_str(&encoded.reason[ERROR_SENTINEL.len()..]).unwrap(); + assert!(value.get("localErrorKind").is_none()); + } + #[test] fn envelope_carries_sentinel_and_code() { let e = KernelError::invalid_argument().message("hi"); diff --git a/napi/src/statement.rs b/napi/src/statement.rs index 40d682d2..f4bc66cb 100644 --- a/napi/src/statement.rs +++ b/napi/src/statement.rs @@ -36,7 +36,7 @@ use tokio::sync::Mutex; use arrow_schema::SchemaRef; use databricks_sql_kernel::{ Error as KernelError, ExecutedStatement, ExecutedStatementHandle, ResultBatch, ResultStream, - Statement as KernelStatement, + Statement as KernelStatement, StatementCanceller, VolumeOptions, }; use crate::error::napi_err_from_kernel; @@ -131,6 +131,8 @@ pub struct Statement { /// does not emit a statement id for SHOW/information_schema /// queries driven through `Metadata`). statement_id: String, + is_volume_operation: bool, + canceller: Option, /// Set to `true` when `fetchNextBatch` observes the natural end of /// the stream (`None`). `cancel()` short-circuits to `Ok(())` when /// this is set, matching the JDBC `Statement.cancel()` no-op-after- @@ -153,6 +155,8 @@ impl Statement { pub(crate) fn from_executed(parent: KernelStatement, executed: ExecutedStatement) -> Self { let schema = executed.schema(); let statement_id = executed.statement_id().to_owned(); + let is_volume_operation = executed.result_stream().is_volume_operation(); + let canceller = Some(parent.canceller()); Self { inner: Arc::new(Mutex::new(Some(AnyInner::Executed(Box::new( StatementInner { @@ -162,6 +166,8 @@ impl Statement { ))))), schema, statement_id, + is_volume_operation, + canceller, finished: Arc::new(AtomicBool::new(false)), } } @@ -182,6 +188,8 @@ impl Statement { inner: Arc::new(Mutex::new(Some(AnyInner::Metadata(stream)))), schema, statement_id: String::new(), + is_volume_operation: false, + canceller: None, finished: Arc::new(AtomicBool::new(false)), } } @@ -189,6 +197,38 @@ impl Statement { #[napi] impl Statement { + #[napi(getter)] + pub fn is_volume_operation(&self) -> bool { + self.is_volume_operation + } + + /// Complete a server-marked file transfer while retaining its instruction rows. + #[napi] + pub async fn complete_volume_operation( + &self, + allowed_paths: Vec, + remove_not_found_is_success: Option, + ) -> napi::Result { + let options = VolumeOptions { + allowed_paths: allowed_paths.into_iter().map(Into::into).collect(), + remove_not_found_is_success: remove_not_found_is_success.unwrap_or(false), + }; + let inner = Arc::clone(&self.inner); + guarded(async move { + let mut guard = inner.lock().await; + let stream = match guard.as_mut().ok_or_else(statement_closed_err)? { + AnyInner::Executed(s) => s.executed.result_stream_mut(), + AnyInner::Metadata(stream) => stream, + }; + stream + .complete_volume_operation(&options, None) + .await + .map(|status| status.as_str().to_owned()) + .map_err(napi_err_from_kernel) + }) + .await + } + /// Server-issued statement id. Cached at construction; readable /// even after `close()` so JS-side log lines can correlate against /// kernel / server logs which key on the same id. @@ -418,6 +458,9 @@ impl Statement { /// has been explicitly `close()`d. #[napi] pub async fn cancel(&self) -> napi::Result<()> { + if let Some(canceller) = &self.canceller { + canceller.cancel_volume_operation(); + } // Idempotent against natural completion. if self.finished.load(Ordering::Acquire) { return Ok(()); @@ -477,6 +520,9 @@ impl Statement { /// resource to release). #[napi] pub async fn close(&self) -> napi::Result<()> { + if let Some(canceller) = &self.canceller { + canceller.cancel_volume_operation(); + } let inner = Arc::clone(&self.inner); guarded(async move { // Take the inner state out so `Drop` knows there's nothing @@ -503,6 +549,9 @@ impl Statement { impl Drop for Statement { fn drop(&mut self) { + if let Some(canceller) = &self.canceller { + canceller.cancel_volume_operation(); + } // Best-effort cleanup: schedule a drop of the kernel handle on // the captured tokio runtime. JS callers who need a // guaranteed `close_statement` round-trip must call `close()` @@ -623,6 +672,8 @@ mod tests { let stmt = Statement { inner: Arc::new(Mutex::new(None)), // "already closed" schema: make_schema(), + is_volume_operation: false, + canceller: None, statement_id: "stmt-survives-close".to_owned(), finished: Arc::new(AtomicBool::new(false)), }; @@ -638,6 +689,8 @@ mod tests { let stmt = Statement { inner: Arc::new(Mutex::new(None)), schema: schema.clone(), + is_volume_operation: false, + canceller: None, statement_id: "x".to_owned(), finished: Arc::new(AtomicBool::new(false)), }; @@ -657,6 +710,8 @@ mod tests { let stmt = Statement { inner: Arc::new(Mutex::new(None)), schema: make_schema(), + is_volume_operation: false, + canceller: None, statement_id: "x".to_owned(), finished: Arc::new(AtomicBool::new(false)), }; @@ -673,6 +728,8 @@ mod tests { let stmt = Statement { inner: Arc::new(Mutex::new(None)), // closed schema: make_schema(), + is_volume_operation: false, + canceller: None, statement_id: "x".to_owned(), finished: Arc::new(AtomicBool::new(true)), }; diff --git a/src/c_abi/error.rs b/src/c_abi/error.rs index f5243007..0ea0d233 100644 --- a/src/c_abi/error.rs +++ b/src/c_abi/error.rs @@ -55,6 +55,9 @@ pub struct KernelError { /// "no error recorded since the last clear". #[derive(Default)] struct LastError { + local_os_error: i32, + local_kind: Option, + local_path: Option, code: Option, message: Option, sql_state: Option, @@ -130,6 +133,34 @@ pub unsafe extern "C" fn kernel_get_last_error(out: *mut KernelError) -> bool { }) } +/// Original local OS error number, or zero when unavailable. Does not clear the error. +#[no_mangle] +pub extern "C" fn kernel_get_last_error_local_os_error() -> i32 { + LAST_ERROR.with(|last| last.borrow().local_os_error) +} + +/// Borrowed local error kind, or null. Valid until the next error-clearing call. +#[no_mangle] +pub extern "C" fn kernel_get_last_error_local_kind() -> *const c_char { + LAST_ERROR.with(|last| { + last.borrow() + .local_kind + .as_ref() + .map_or(std::ptr::null(), |s| s.as_ptr()) + }) +} + +/// Borrowed requested local path, or null. Valid until the next error-clearing call. +#[no_mangle] +pub extern "C" fn kernel_get_last_error_local_path() -> *const c_char { + LAST_ERROR.with(|last| { + last.borrow() + .local_path + .as_ref() + .map_or(std::ptr::null(), |s| s.as_ptr()) + }) +} + /// 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) @@ -151,6 +182,13 @@ pub(crate) fn store_error(err: Error) { message.push_str(ec); } *last = LastError { + local_os_error: err + .local_error + .as_ref() + .and_then(|e| e.raw_os_error) + .unwrap_or(0), + local_kind: err.local_error.as_ref().map(|e| to_cstring_lossy(&e.kind)), + local_path: err.local_error.as_ref().map(|e| to_cstring_lossy(&e.path)), code: Some(err.code), message: Some(to_cstring_lossy(&message)), sql_state: err.sql_state.as_deref().map(to_cstring_lossy), @@ -192,6 +230,35 @@ pub(crate) fn store_invalid_arg(msg: &str) -> KernelStatusCode { mod tests { use super::*; + #[test] + fn local_error_getters_preserve_error_until_clear() { + let mut error = Error::not_found().message("missing local file"); + error.local_error = Some(Box::new(crate::kernel_error::LocalFileError { + raw_os_error: Some(2), + kind: "NotFound".into(), + path: "local-file".into(), + })); + store_error(error); + assert_eq!(kernel_get_last_error_local_os_error(), 2); + assert_eq!( + unsafe { std::ffi::CStr::from_ptr(kernel_get_last_error_local_kind()) } + .to_str() + .unwrap(), + "NotFound" + ); + assert_eq!( + unsafe { std::ffi::CStr::from_ptr(kernel_get_last_error_local_path()) } + .to_str() + .unwrap(), + "local-file" + ); + with_last_error(|error| assert!(error.is_some())); + clear_error(); + assert_eq!(kernel_get_last_error_local_os_error(), 0); + assert!(kernel_get_last_error_local_kind().is_null()); + assert!(kernel_get_last_error_local_path().is_null()); + } + /// Helper: read the thread-local error into a `KernelError` and run /// `f` with the borrowed C strings still alive. fn with_last_error(f: impl FnOnce(Option) -> R) -> R { diff --git a/src/c_abi/result.rs b/src/c_abi/result.rs index 1c66a033..5a87edec 100644 --- a/src/c_abi/result.rs +++ b/src/c_abi/result.rs @@ -86,6 +86,7 @@ pub struct kernel_result_stream_canceller_t { /// download — close the stream (and, for a sync-executed statement, the executed /// handle) to release those on their own completion. struct ResultStreamInner { + volume: Option>, /// Fired by a cloned [`ResultStreamCanceller`] to interrupt an in-flight /// `next_batch`. Once fired the stream is permanently aborted: `next_batch` /// returns `Cancelled` on every subsequent call rather than re-driving a @@ -127,6 +128,7 @@ enum ResultStreamShape { /// reference to the stream's `&mut` state, so it is safe to `cancel()` from any /// thread concurrently with `next_batch`/`close` on the owning thread. struct ResultStreamCanceller { + volume: Option>, cancel: CancellationToken, } @@ -139,6 +141,7 @@ pub(crate) fn into_raw_result_stream( stream: crate::result_stream::ResultStream, ) -> *mut kernel_result_stream_t { Box::into_raw(Box::new(ResultStreamInner { + volume: stream.volume_state(), cancel: CancellationToken::new(), shape: ResultStreamShape::Owned { schema, stream }, })) as *mut kernel_result_stream_t @@ -156,6 +159,7 @@ pub(crate) unsafe fn into_raw_executed_stream( valid: ValidityFlag, ) -> *mut kernel_result_stream_t { Box::into_raw(Box::new(ResultStreamInner { + volume: (*exec).result_stream().volume_state(), cancel: CancellationToken::new(), shape: ResultStreamShape::Executed { exec, valid }, })) as *mut kernel_result_stream_t @@ -531,7 +535,11 @@ pub unsafe extern "C" fn kernel_result_stream_close( if stream.is_null() { return store_invalid_arg("kernel_result_stream_close: stream must not be null"); } - drop(Box::from_raw(stream as *mut ResultStreamInner)); + let inner = Box::from_raw(stream as *mut ResultStreamInner); + if let Some(volume) = &inner.volume { + volume.cancel(); + } + drop(inner); KernelStatusCode::Success } @@ -584,6 +592,7 @@ pub unsafe extern "C" fn kernel_result_stream_canceller_new( // is a `Sync` atomic). SAFETY: `stream` is a live box (non-null checked). let p = stream as *mut ResultStreamInner; let handle = ResultStreamCanceller { + volume: (*std::ptr::addr_of!((*p).volume)).clone(), cancel: (*std::ptr::addr_of!((*p).cancel)).clone(), }; std::ptr::write( @@ -618,6 +627,9 @@ pub unsafe extern "C" fn kernel_result_stream_canceller_cancel( "kernel_result_stream_canceller_cancel: handle must not be null", ); }; + if let Some(volume) = &handle.volume { + volume.cancel(); + } handle.cancel.cancel(); KernelStatusCode::Success }) @@ -646,6 +658,89 @@ pub unsafe extern "C" fn kernel_result_stream_canceller_free( }) } +/// Read whether this stream has authority to complete a Volume instruction. +/// # Safety +/// `stream` must be live and `out` must be writable. +#[no_mangle] +pub unsafe extern "C" fn kernel_result_stream_is_volume_operation( + stream: *const kernel_result_stream_t, + out: *mut bool, +) -> KernelStatusCode { + catch_ffi(|| { + if stream.is_null() || out.is_null() { + return store_invalid_arg("Volume marker: null pointer"); + } + let p = stream as *const ResultStreamInner; + std::ptr::write(out, (*std::ptr::addr_of!((*p).volume)).is_some()); + KernelStatusCode::Success + }) +} + +/// Complete a marked instruction while preserving its result rows. +/// `allowed_paths_json` is a JSON array of strings. Status is 0 (ordinary result), +/// 1 (owned input bytes required) or 2 (completed). This API supplies no input bytes. +/// # Safety +/// `stream` must be live with exclusive fetch access, `allowed_paths_json` must +/// be NUL-terminated UTF-8, and `out_status` must be writable. +#[no_mangle] +pub unsafe extern "C" fn kernel_result_stream_complete_volume_operation( + stream: *mut kernel_result_stream_t, + allowed_paths_json: *const std::ffi::c_char, + remove_not_found_is_success: bool, + out_status: *mut i32, +) -> KernelStatusCode { + catch_ffi(|| { + if stream.is_null() || allowed_paths_json.is_null() || out_status.is_null() { + return store_invalid_arg("Volume completion: null pointer"); + } + let roots = match std::ffi::CStr::from_ptr(allowed_paths_json) + .to_str() + .ok() + .and_then(|text| serde_json::from_str::>(text).ok()) + { + Some(roots) => roots, + None => { + return store_invalid_arg("Volume allowed paths must be a JSON array of strings") + } + }; + let options = crate::VolumeOptions { + allowed_paths: roots.into_iter().map(Into::into).collect(), + remove_not_found_is_success, + }; + let p = stream as *mut ResultStreamInner; + let shape = &mut *std::ptr::addr_of_mut!((*p).shape); + let result = match shape { + ResultStreamShape::Owned { stream, .. } => { + block_on_ffi(|| stream.complete_volume_operation(&options, None)) + } + ResultStreamShape::Executed { exec, valid } => { + let exec = match executed_ref(*exec, valid) { + Ok(exec) => exec, + Err(code) => return code, + }; + block_on_ffi(|| { + exec.result_stream_mut() + .complete_volume_operation(&options, None) + }) + } + }; + match result { + Ok(status) => { + std::ptr::write( + out_status, + match status { + crate::VolumeCompletion::NotVolume => 0, + crate::VolumeCompletion::NeedsInputStream => 1, + crate::VolumeCompletion::Completed => 2, + }, + ); + KernelStatusCode::Success + } + Err(code) => code, + } + }) +} + #[cfg(test)] mod tests { use super::*; @@ -678,6 +773,97 @@ mod tests { into_raw_result_stream(schema, stream) } + #[test] + fn volume_completion_keeps_raw_rows_and_observes_detached_cancel() { + use crate::reader::test_utils::MockReader; + use crate::result_stream::ResultStream; + use arrow_array::StringArray; + use std::ffi::CString; + + let schema = Arc::new(Schema::new( + ["operation", "presignedUrl", "headers", "localFile"] + .map(|name| Field::new(name, DataType::Utf8, false)) + .to_vec(), + )); + let batch = RecordBatch::try_new( + schema.clone(), + ["REMOVE", "http://unused.invalid/object", "{}", ""] + .into_iter() + .map(|value| Arc::new(StringArray::from(vec![value])) as _) + .collect(), + ) + .unwrap(); + let rt = tokio::runtime::Runtime::new().unwrap(); + for marked in [false, true] { + let stream = rt.block_on(async { + let mut stream = + ResultStream::from_reader(Box::new(MockReader::new(vec![batch.clone()]))) + .await + .unwrap(); + stream.attach_volume( + marked, + crate::volume::VolumeState::new(), + reqwest::Client::new(), + ); + into_raw_result_stream(schema.clone(), stream) + }); + let mut is_volume = !marked; + assert_eq!( + unsafe { kernel_result_stream_is_volume_operation(stream, &mut is_volume) }, + KernelStatusCode::Success + ); + assert_eq!(is_volume, marked); + let roots = CString::new("[]").unwrap(); + let mut status = -1; + if marked { + let mut canceller = std::ptr::null_mut(); + assert_eq!( + unsafe { kernel_result_stream_canceller_new(stream, &mut canceller) }, + KernelStatusCode::Success + ); + assert_eq!( + unsafe { kernel_result_stream_canceller_cancel(canceller) }, + KernelStatusCode::Success + ); + for _ in 0..2 { + assert_eq!( + unsafe { + kernel_result_stream_complete_volume_operation( + stream, + roots.as_ptr(), + false, + &mut status, + ) + }, + KernelStatusCode::Cancelled + ); + } + unsafe { kernel_result_stream_canceller_free(canceller) }; + } else { + assert_eq!( + unsafe { + kernel_result_stream_complete_volume_operation( + stream, + roots.as_ptr(), + false, + &mut status, + ) + }, + KernelStatusCode::Success + ); + assert_eq!(status, 0); + let mut array = FFI_ArrowArray::empty(); + let mut schema = FFI_ArrowSchema::empty(); + assert_eq!( + unsafe { kernel_result_stream_next_batch(stream, &mut array, &mut schema) }, + KernelStatusCode::Success + ); + assert!(!array.is_released()); + } + unsafe { kernel_result_stream_close(stream) }; + } + } + /// End-of-stream on an Owned stream returns `Success` with a /// **released** array (`release == null`) — the sentinel ODBC / Go /// consumers loop on. A regression that returned a non-released empty diff --git a/src/c_abi/statement.rs b/src/c_abi/statement.rs index 5f10c9dd..84ab0106 100644 --- a/src/c_abi/statement.rs +++ b/src/c_abi/statement.rs @@ -1239,6 +1239,31 @@ unsafe fn with_statement( }) } +/// Read the server-authorized Volume marker before taking a result stream. +/// # Safety +/// `exec` must be live and `out` must be writable; no fetch may be in flight. +#[no_mangle] +pub unsafe extern "C" fn kernel_executed_statement_is_volume_operation( + exec: *const kernel_executed_statement_t, + out: *mut bool, +) -> KernelStatusCode { + catch_ffi(|| { + let Some(handle) = (exec as *const ExecutedHandle).as_ref() else { + return store_invalid_arg("Volume marker: null executed statement"); + }; + if out.is_null() { + return store_invalid_arg("Volume marker: null out pointer"); + } + if !handle.exec.is_valid() { + return store_and_code( + Error::invalid_statement_handle().message("executed statement is invalid"), + ); + } + std::ptr::write(out, handle.exec.result_stream().is_volume_operation()); + KernelStatusCode::Success + }) +} + #[cfg(test)] mod tests { use super::*; diff --git a/src/result_stream.rs b/src/result_stream.rs index 1b6e9844..51b494a7 100644 --- a/src/result_stream.rs +++ b/src/result_stream.rs @@ -682,6 +682,10 @@ impl ResultStream { state.complete(batch, &client, options, input_bytes).await } + pub(crate) fn volume_state(&self) -> Option> { + self.volume.as_ref().map(|(state, _)| Arc::clone(state)) + } + pub(crate) fn cancel_volume(&self) { if let Some((state, _)) = &self.volume { state.cancel(); diff --git a/src/statement/executed_async.rs b/src/statement/executed_async.rs index 036f3739..af71f96b 100644 --- a/src/statement/executed_async.rs +++ b/src/statement/executed_async.rs @@ -1226,6 +1226,15 @@ pub struct AsyncStatementCanceller { } impl AsyncStatementCanceller { + /// Cancel local Volume completion without waiting for a server request. + pub fn cancel_volume_operation(&self) { + if self.owning { + if let Some(volume) = &self.volume { + volume.cancel(); + } + } + } + /// Server-side cancel via `cancel_statement(statement_id)`. /// /// Short-circuits to `InvalidStatementHandle` (no wire round-trip) diff --git a/src/statement/mutable.rs b/src/statement/mutable.rs index bfda144d..684a693e 100644 --- a/src/statement/mutable.rs +++ b/src/statement/mutable.rs @@ -965,6 +965,14 @@ pub struct StatementCanceller { } impl StatementCanceller { + /// Cancel local Volume completion without waiting for a server request. + pub fn cancel_volume_operation(&self) { + self.volume + .lock() + .unwrap_or_else(|e| e.into_inner()) + .cancel(); + } + /// Server-side cancel of the in-flight statement via /// `cancel_statement(statement_id)`. /// From b5a9060d1e55a79d31ea6fe15daa613f014e92e0 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Fri, 13 Nov 2026 23:00:23 +0000 Subject: [PATCH 03/63] fix: validate all Volume instruction rows before transfer Signed-off-by: Aakash Saravanan --- adbc/Cargo.lock | 2 + adbc/Cargo.toml | 2 + adbc/src/statement.rs | 163 ++++++++++++++++++++++++++++++++++ napi/Cargo.lock | 1 + napi/Cargo.toml | 1 + napi/src/statement.rs | 168 ++++++++++++++++++++++++++++++++++++ src/result_stream.rs | 24 +++++- tests/v0_volume_wiremock.rs | 55 +++++++++++- 8 files changed, 412 insertions(+), 4 deletions(-) diff --git a/adbc/Cargo.lock b/adbc/Cargo.lock index 6c65d761..2ba2ff78 100644 --- a/adbc/Cargo.lock +++ b/adbc/Cargo.lock @@ -636,7 +636,9 @@ dependencies = [ "adbc_ffi", "arrow-array", "arrow-buffer", + "arrow-ipc", "arrow-schema", + "base64 0.22.1", "databricks-sql-kernel", "serde_json", "tokio", diff --git a/adbc/Cargo.toml b/adbc/Cargo.toml index 69380384..8f88645e 100644 --- a/adbc/Cargo.toml +++ b/adbc/Cargo.toml @@ -37,6 +37,8 @@ serde_json = "1" tokio = { version = "1", features = ["rt-multi-thread"] } [dev-dependencies] +arrow-ipc = "59" +base64 = "0.22" adbc_driver_manager = "0.24" wiremock = "0.6" diff --git a/adbc/src/statement.rs b/adbc/src/statement.rs index 2a986acc..3b688c87 100644 --- a/adbc/src/statement.rs +++ b/adbc/src/statement.rs @@ -1530,8 +1530,171 @@ fn parse_client_timeout_option(key: &str, value: OptionValue) -> Option>()}}, + "result":{"chunk_index":0,"row_offset":0,"row_count":1,"attachment":STANDARD.encode(&ipc)} + }); + runtime.block_on_safe(async { + for verb in ["POST", "GET"] { + Mock::given(method(verb)) + .and(path(if verb == "POST" { + "/api/2.0/sql/statements" + } else { + "/api/2.0/sql/statements/volume" + })) + .respond_with(ResponseTemplate::new(200).set_body_json(response.clone())) + .mount(&server) + .await; + } + Mock::given(method("POST")) + .and(path("/api/2.0/sql/warehouses/wh/sessions")) + .respond_with( + ResponseTemplate::new(200).set_body_json(json!({"session_id":"session"})), + ) + .mount(&server) + .await; + Mock::given(method("DELETE")) + .respond_with(ResponseTemplate::new(200)) + .mount(&server) + .await; + Mock::given(method("DELETE")) + .and(path("/object")) + .respond_with(ResponseTemplate::new(200)) + .with_priority(1) + .expect(7) + .mount(&server) + .await; + }); + let session = runtime + .block_on_safe( + kernel::Session::builder() + .http_path(server.uri(), "/sql/1.0/warehouses/wh") + .auth(kernel::AuthConfig::Pat { + token: "test-token".into(), + identity_federation_client_id: None, + }) + .open(), + ) + .unwrap(); + let mut transfers = 0; + for mode in ["raw", "sync", "async", "await", "fetch", "bound", "update"] { + let mut statement = Statement::new( + session.statement(), + session.metadata(), + Arc::clone(&runtime), + Arc::new(CancellationRegistry::default()), + false, + ); + statement.set_sql_query("operation ?, ?").unwrap(); + let key = OptionStatement::Other(STAGING_ALLOWED_PATHS_OPTION.into()); + assert_eq!( + statement.get_option_string(key.clone()).unwrap_err().status, + Status::NotFound + ); + for value in [OptionValue::Int(1), OptionValue::String("[1]".into())] { + assert_eq!( + statement.set_option(key.clone(), value).unwrap_err().status, + Status::InvalidArguments + ); + } + if mode != "raw" { + statement.set_option(key.clone(), "[]".into()).unwrap(); + assert_eq!(statement.get_option_string(key).unwrap(), "[]"); + } + if mode == "async" { + statement + .set_option( + OptionStatement::Other(ENABLE_DIRECT_RESULTS_OPTION.into()), + "false".into(), + ) + .unwrap(); + } + if mode == "bound" { + statement.bind(batch(2)).unwrap(); + } + let reader = match mode { + "await" => statement.submit().unwrap().await_result().unwrap(), + "fetch" => statement.submit().unwrap().fetch_result().unwrap(), + "update" => { + assert_eq!(statement.execute_update().unwrap(), None); + transfers += 1; + continue; + } + _ => statement.execute().unwrap(), + }; + let batches = reader.collect::, _>>().unwrap(); + assert_eq!(batches.len(), if mode == "bound" { 2 } else { 1 }, "{mode}"); + for batch in batches { + assert_eq!( + batch + .column(0) + .as_any() + .downcast_ref::() + .unwrap() + .value(0), + "REMOVE" + ); + } + transfers += match mode { + "raw" => 0, + "bound" => 2, + _ => 1, + }; + assert_eq!( + runtime + .block_on_safe(server.received_requests()) + .unwrap() + .iter() + .filter(|request| request.url.path() == "/object") + .count(), + transfers, + "{mode}" + ); + } + assert_eq!(transfers, 7); + runtime.block_on_safe(session.close()).unwrap(); + } fn batch(rows: usize) -> RecordBatch { let schema = Arc::new(Schema::new(vec![ diff --git a/napi/Cargo.lock b/napi/Cargo.lock index e37a5a25..e3e9f50d 100644 --- a/napi/Cargo.lock +++ b/napi/Cargo.lock @@ -657,6 +657,7 @@ dependencies = [ "arrow-array", "arrow-ipc", "arrow-schema", + "base64", "chrono", "databricks-sql-kernel", "futures", diff --git a/napi/Cargo.toml b/napi/Cargo.toml index 78326e4d..a55dab43 100644 --- a/napi/Cargo.toml +++ b/napi/Cargo.toml @@ -129,6 +129,7 @@ serde_json = "1" chrono = { version = "0.4", default-features = false, features = ["clock"] } [dev-dependencies] +base64 = "0.22" wiremock = "0.6" [build-dependencies] diff --git a/napi/src/statement.rs b/napi/src/statement.rs index f4bc66cb..c2bd9805 100644 --- a/napi/src/statement.rs +++ b/napi/src/statement.rs @@ -600,7 +600,175 @@ pub(crate) fn statement_closed_err() -> napi::Error { #[cfg(test)] mod tests { use super::*; + use arrow_array::{RecordBatch, StringArray}; + use arrow_ipc::reader::StreamReader; use arrow_schema::{DataType, Field, Schema}; + use base64::{engine::general_purpose::STANDARD, Engine}; + use databricks_sql_kernel::{AuthConfig, Session}; + use serde_json::json; + use std::time::Duration; + use wiremock::matchers::{method, path}; + use wiremock::{Mock, MockServer, ResponseTemplate}; + + async fn volume_session() -> (MockServer, Session) { + let server = MockServer::start().await; + let names = ["operation", "presignedUrl", "headers", "localFile"]; + let schema = Arc::new(Schema::new( + names + .map(|name| Field::new(name, DataType::Utf8, false)) + .to_vec(), + )); + let values = [ + "REMOVE".to_owned(), + format!("{}/object", server.uri()), + "{}".into(), + "".into(), + ]; + let batch = RecordBatch::try_new( + schema.clone(), + values + .iter() + .map(|value| Arc::new(StringArray::from(vec![value.as_str()])) as _) + .collect(), + ) + .unwrap(); + let response = json!({ + "statement_id":"volume", "status":{"state":"CLOSED"}, + "manifest":{"format":"ARROW_STREAM", "is_volume_operation":true, "total_row_count":1, "total_chunk_count":1, + "schema":{"column_count":4,"columns":names.iter().enumerate().map(|(i,name)| json!({"name":name,"type_name":"STRING","type_text":"STRING","position":i})).collect::>()}}, + "result":{"chunk_index":0,"row_offset":0,"row_count":1,"attachment":STANDARD.encode(crate::result::encode_ipc_stream(&schema, Some(&batch)).unwrap())} + }); + for verb in ["POST", "GET"] { + Mock::given(method(verb)) + .and(path(if verb == "POST" { + "/api/2.0/sql/statements" + } else { + "/api/2.0/sql/statements/volume" + })) + .respond_with(ResponseTemplate::new(200).set_body_json(response.clone())) + .mount(&server) + .await; + } + Mock::given(method("POST")) + .and(path("/api/2.0/sql/warehouses/wh/sessions")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({"session_id":"session"}))) + .mount(&server) + .await; + Mock::given(method("DELETE")) + .respond_with(ResponseTemplate::new(200)) + .mount(&server) + .await; + let session = Session::builder() + .http_path(server.uri(), "/sql/1.0/warehouses/wh") + .auth(AuthConfig::Pat { + token: "test-token".into(), + identity_federation_client_id: None, + }) + .open() + .await + .unwrap(); + (server, session) + } + + #[tokio::test] + async fn sync_and_async_volume_completion_preserves_instruction_ipc() { + for asynchronous in [false, true] { + let (server, session) = volume_session().await; + Mock::given(method("DELETE")) + .and(path("/object")) + .respond_with(ResponseTemplate::new(200)) + .with_priority(1) + .expect(1) + .mount(&server) + .await; + let mut parent = session.statement(); + parent.spec().sql("operation"); + let batch = if asynchronous { + let executed = parent.submit().await.unwrap(); + let owner = + crate::async_statement::AsyncStatement::from_executed_async(parent, executed); + let result = owner.await_result().await.unwrap(); + assert!(result.is_volume_operation()); + assert_eq!( + result + .complete_volume_operation(vec![], None) + .await + .unwrap(), + "completed" + ); + let batch = result.fetch_next_batch().await.unwrap().unwrap(); + owner.close().await.unwrap(); + batch + } else { + let executed = parent.execute().await.unwrap(); + let result = Statement::from_executed(parent, executed); + assert!(result.is_volume_operation()); + assert_eq!( + result + .complete_volume_operation(vec![], None) + .await + .unwrap(), + "completed" + ); + let batch = result.fetch_next_batch().await.unwrap().unwrap(); + result.close().await.unwrap(); + batch + }; + let decoded = + StreamReader::try_new(std::io::Cursor::new(batch.ipc_bytes.as_ref()), None) + .unwrap() + .next() + .unwrap() + .unwrap(); + assert_eq!( + decoded + .column(0) + .as_any() + .downcast_ref::() + .unwrap() + .value(0), + "REMOVE" + ); + session.close().await.unwrap(); + } + } + + #[tokio::test] + async fn close_interrupts_volume_completion_before_waiting_for_its_lock() { + let (server, session) = volume_session().await; + Mock::given(method("DELETE")) + .and(path("/object")) + .respond_with(ResponseTemplate::new(200).set_delay(Duration::from_secs(5))) + .with_priority(1) + .expect(1) + .mount(&server) + .await; + let mut parent = session.statement(); + parent.spec().sql("operation"); + let executed = parent.execute().await.unwrap(); + let result = Statement::from_executed(parent, executed); + let completion = result.complete_volume_operation(vec![], None); + tokio::pin!(completion); + tokio::select! { + finished = &mut completion => panic!("completion finished before close: {finished:?}"), + _ = async { + while !server.received_requests().await.unwrap().iter().any(|request| request.url.path() == "/object") { + tokio::task::yield_now().await; + } + } => {} + } + let (closed, completed) = tokio::time::timeout(Duration::from_secs(1), async { + tokio::join!(result.close(), &mut completion) + }) + .await + .expect("close must signal before waiting for the completion lock"); + closed.unwrap(); + assert!(completed + .unwrap_err() + .reason + .contains(r#""code":"Cancelled""#)); + session.close().await.unwrap(); + } fn make_schema() -> Arc { Arc::new(Schema::new(vec![Field::new("a", DataType::Int32, false)])) diff --git a/src/result_stream.rs b/src/result_stream.rs index 51b494a7..1031f502 100644 --- a/src/result_stream.rs +++ b/src/result_stream.rs @@ -679,7 +679,29 @@ impl ResultStream { .ok_or_else(|| { state.fail(Error::invalid_argument().message("Missing Volume instruction row")) })?; - state.complete(batch, &client, options, input_bytes).await + let ResultBatch::Arrow(batch) = batch; + let batch = ResultBatch::Arrow(batch.clone()); + // The first batch stays buffered for callers; later batches must not + // authorize a partial transfer of a multi-row instruction result. + while !self.exhausted { + match self + .reader + .as_mut() + .expect("Volume completion retains its reader") + .next_batch() + .await + .map_err(|error| state.fail(error))? + { + Some(batch) if batch.num_rows() != 0 => { + return Err(state.fail( + Error::invalid_argument().message("Expected one Volume instruction row"), + )); + } + Some(_) => {} + None => self.exhausted = true, + } + } + state.complete(&batch, &client, options, input_bytes).await } pub(crate) fn volume_state(&self) -> Option> { diff --git a/tests/v0_volume_wiremock.rs b/tests/v0_volume_wiremock.rs index 20b93e33..b25f2fd2 100644 --- a/tests/v0_volume_wiremock.rs +++ b/tests/v0_volume_wiremock.rs @@ -29,6 +29,15 @@ use wiremock::matchers::{method, path}; use wiremock::{Mock, MockServer, ResponseTemplate}; fn response(server: &MockServer, marked: bool, local: &str) -> serde_json::Value { + response_with_batches(server, marked, local, 1) +} + +fn response_with_batches( + server: &MockServer, + marked: bool, + local: &str, + count: usize, +) -> serde_json::Value { let names = ["operation", "presignedUrl", "headers", "localFile"]; let schema = Arc::new(Schema::new( names @@ -53,7 +62,9 @@ fn response(server: &MockServer, marked: bool, local: &str) -> serde_json::Value let mut ipc = Vec::new(); { let mut writer = StreamWriter::try_new(&mut ipc, &batch.schema()).unwrap(); - writer.write(&batch).unwrap(); + for _ in 0..count { + writer.write(&batch).unwrap(); + } writer.finish().unwrap(); } json!({ @@ -61,12 +72,50 @@ fn response(server: &MockServer, marked: bool, local: &str) -> serde_json::Value "manifest": { "format": "ARROW_STREAM", "is_volume_operation": marked, "schema": {"column_count":4,"columns": names.iter().enumerate().map(|(i,name)| json!({"name":name,"type_name":"STRING","type_text":"STRING","position":i})).collect::>()}, - "total_row_count":1,"total_chunk_count":1 + "total_row_count":count,"total_chunk_count":1 }, - "result": {"chunk_index":0,"row_offset":0,"row_count":1,"attachment":STANDARD.encode(&ipc)} + "result": {"chunk_index":0,"row_offset":0,"row_count":count,"attachment":STANDARD.encode(&ipc)} }) } +#[tokio::test] +async fn multiple_instruction_batches_fail_before_any_storage_request() { + let server = MockServer::start().await; + let dir = tempfile::tempdir().unwrap(); + let dest = dir.path().join("download"); + std::fs::write(&dest, b"original").unwrap(); + let session = session( + &server, + response_with_batches(&server, true, dest.to_str().unwrap(), 2), + ) + .await; + Mock::given(method("GET")) + .and(path("/object")) + .respond_with(ResponseTemplate::new(200).set_body_bytes(b"replacement")) + .expect(0) + .mount(&server) + .await; + let mut statement = session.statement(); + statement.spec().sql("operation"); + let mut executed = statement.execute().await.unwrap(); + let options = VolumeOptions { + allowed_paths: vec![dir.path().to_owned()], + ..Default::default() + }; + for _ in 0..2 { + let error = executed + .result_stream_mut() + .complete_volume_operation(&options, None) + .await + .unwrap_err(); + assert_eq!(error.code, ErrorCode::InvalidArgument); + assert_eq!(error.message, "Expected one Volume instruction row"); + } + assert_eq!(std::fs::read(&dest).unwrap(), b"original"); + executed.close().await.unwrap(); + session.close().await.unwrap(); +} + async fn session(server: &MockServer, body: serde_json::Value) -> Session { Mock::given(method("POST")) .and(path("/api/2.0/sql/warehouses/wh/sessions")) From 845c118a62915540e4460f52f0fa1225aa14ca79 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Fri, 13 Nov 2026 23:09:57 +0000 Subject: [PATCH 04/63] Set the content length of byte uploads Signed-off-by: Aakash Saravanan --- src/volume.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/volume.rs b/src/volume.rs index 68b3341f..a2a54abb 100644 --- a/src/volume.rs +++ b/src/volume.rs @@ -188,7 +188,10 @@ impl VolumeState { let local_path = if instruction.operation == "REMOVE" { None } else if instruction.operation == "PUT" && instruction.local_file == "__input_stream__" { - request = request.body(input_bytes.ok_or_else(|| invalid("Missing input stream"))?); + let bytes = input_bytes.ok_or_else(|| invalid("Missing input stream"))?; + request = request + .header(reqwest::header::CONTENT_LENGTH, bytes.len()) + .body(bytes); None } else { let path = allowed_path(&instruction.local_file, &options.allowed_paths)?; @@ -516,6 +519,7 @@ mod tests { Mock::given(method("PUT")) .and(path("/object")) .and(body_bytes(Vec::::new())) + .and(header("content-length", "0")) .and(header("x-storage-token", "server-token")) .respond_with(ResponseTemplate::new(200)) .expect(1) From 3089e1dac3e8e2ada13bbb90a1d2971e59724274 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Sat, 14 Nov 2026 00:07:08 +0000 Subject: [PATCH 05/63] Exercise Volume transfer safety on Windows Signed-off-by: Aakash Saravanan --- .github/workflows/release-debuginfo.yml | 4 ++++ src/volume.rs | 17 ++++++++++------- 2 files changed, 14 insertions(+), 7 deletions(-) diff --git a/.github/workflows/release-debuginfo.yml b/.github/workflows/release-debuginfo.yml index afdae1a4..2b9aefa2 100644 --- a/.github/workflows/release-debuginfo.yml +++ b/.github/workflows/release-debuginfo.yml @@ -132,6 +132,10 @@ jobs: with: arch: x64 + - name: Volume file and cancellation tests + shell: pwsh + run: cargo test --locked --lib volume::tests + - name: Verify linker PDB shell: pwsh run: ./.github/scripts/check-release-debuginfo.ps1 diff --git a/src/volume.rs b/src/volume.rs index a2a54abb..d3f2b473 100644 --- a/src/volume.rs +++ b/src/volume.rs @@ -751,26 +751,29 @@ mod tests { peer.await.unwrap(); } - #[cfg(unix)] + #[cfg(any(unix, windows))] #[test] fn symlinks_require_lexical_authority_and_resolved_target_in_any_allowed_root() { - use std::os::unix::fs::symlink; + #[cfg(unix)] + use std::os::unix::fs::{symlink as symlink_dir, symlink as symlink_file}; + #[cfg(windows)] + use std::os::windows::fs::{symlink_dir, symlink_file}; let dir = tempfile::tempdir().unwrap(); let root = dir.path().join("root"); let other = dir.path().join("other"); std::fs::create_dir(&root).unwrap(); std::fs::create_dir(&other).unwrap(); std::fs::write(root.join("file"), b"ok").unwrap(); - symlink(root.join("file"), root.join("inside")).unwrap(); - symlink(other.join("missing"), root.join("escape")).unwrap(); - symlink(&root, dir.path().join("alias")).unwrap(); + symlink_file(root.join("file"), root.join("inside")).unwrap(); + symlink_file(other.join("missing"), root.join("escape")).unwrap(); + symlink_dir(&root, dir.path().join("alias")).unwrap(); assert_eq!( allowed_path( root.join("inside").to_str().unwrap(), std::slice::from_ref(&root) ) .unwrap(), - root.join("file") + root.join("file").canonicalize().unwrap() ); assert!(allowed_path( root.join("escape").to_str().unwrap(), @@ -783,7 +786,7 @@ mod tests { &[root.clone(), other.clone()] ) .unwrap(), - other.join("missing") + other.canonicalize().unwrap().join("missing") ); assert!(allowed_path( dir.path().join("alias/file").to_str().unwrap(), From ebf148d15886cc13b61ed6cd6f1c5d5c0d354b22 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Sat, 14 Nov 2026 00:14:01 +0000 Subject: [PATCH 06/63] Limit temporary-file builder mutability to Unix Signed-off-by: Aakash Saravanan --- src/volume.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/volume.rs b/src/volume.rs index d3f2b473..710f400b 100644 --- a/src/volume.rs +++ b/src/volume.rs @@ -220,7 +220,10 @@ impl VolumeState { Err(error) if error.kind() == std::io::ErrorKind::NotFound => None, Err(error) => return Err(local_error(error, &instruction.local_file)), }; + #[cfg(unix)] let mut builder = tempfile::Builder::new(); + #[cfg(not(unix))] + let builder = tempfile::Builder::new(); #[cfg(unix)] { use std::os::unix::fs::PermissionsExt; From 861bb6976c1792135f3a4f8ad65ebeda1f71783c Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Sat, 14 Nov 2026 02:34:04 +0000 Subject: [PATCH 07/63] Preserve Volume transfer timeout and error behavior Build the storage client from the configured connection settings without a SQL RPC deadline. Keep populated Python kernel errors when local metadata attachment fails. Signed-off-by: Aakash Saravanan --- pyo3/src/errors.rs | 3 +- src/client/http.rs | 24 ++++++++--- src/session.rs | 3 +- tests/v0_volume_wiremock.rs | 83 ++++++++++++++++++++++++++++++++++--- 4 files changed, 101 insertions(+), 12 deletions(-) diff --git a/pyo3/src/errors.rs b/pyo3/src/errors.rs index 0c14b9f2..7229ced3 100644 --- a/pyo3/src/errors.rs +++ b/pyo3/src/errors.rs @@ -161,7 +161,8 @@ pub(crate) fn to_py_err(py: Python<'_>, err: KError) -> PyErr { bound.setattr("local_path", local.map(|e| e.path.as_str()))?; Ok(()) })() { - return error; + py_err.set_cause(py, Some(error)); + return py_err; } py_err } diff --git a/src/client/http.rs b/src/client/http.rs index cac2243b..e96aac3d 100644 --- a/src/client/http.rs +++ b/src/client/http.rs @@ -479,7 +479,11 @@ impl DatabricksHttpClient { } // Follow redirects for normal traffic (reqwest's default policy). - let client = Self::build_reqwest_client(&config, reqwest::redirect::Policy::default())?; + let client = Self::build_reqwest_client( + &config, + reqwest::redirect::Policy::default(), + Some(config.read_timeout), + )?; // Surface which TLS backend was compiled in so oncall debugging // a handshake / unknown-CA report can tell at a glance whether @@ -514,15 +518,16 @@ impl DatabricksHttpClient { fn build_reqwest_client( config: &HttpClientConfig, redirect: reqwest::redirect::Policy, + request_timeout: Option, ) -> Result { let mut builder = Client::builder() .connect_timeout(config.connect_timeout) - // `read_timeout` is a historical name; reqwest applies this as - // the total deadline from connect through response-body completion. - .timeout(config.read_timeout) .pool_max_idle_per_host(config.max_connections_per_host) .user_agent(&config.user_agent) .redirect(redirect); + if let Some(timeout) = request_timeout { + builder = builder.timeout(timeout); + } // Apply TLS configuration if config.tls.enabled == Some(false) { @@ -736,6 +741,11 @@ impl DatabricksHttpClient { &self.client } + /// Storage transfers can outlive SQL RPCs, so retain connection settings without their deadline. + pub(crate) fn storage_client(&self) -> Result { + Self::build_reqwest_client(&self.config, reqwest::redirect::Policy::default(), None) + } + /// Get the authorization header value. /// /// Returns an error if the auth provider has not been set via `set_auth_provider()`. @@ -805,7 +815,11 @@ impl DatabricksHttpClient { /// `azure_tenant_id` (which skips discovery entirely). A single hop is /// sufficient for discovery, so no retry is attempted here. pub async fn first_redirect_location(&self, url: &str) -> Result> { - let client = Self::build_reqwest_client(&self.config, reqwest::redirect::Policy::none())?; + let client = Self::build_reqwest_client( + &self.config, + reqwest::redirect::Policy::none(), + Some(self.config.read_timeout), + )?; let response = client.get(url).send().await.map_err(|e| { Error::network_error().message(format!("Redirect-probe request to {url} failed: {e}")) })?; diff --git a/src/session.rs b/src/session.rs index 36422d5d..c8f8395a 100644 --- a/src/session.rs +++ b/src/session.rs @@ -403,6 +403,7 @@ impl Session { Error::network_error().message(format!("Failed to construct HTTP client: {e}")) })?, ); + let storage_client = http_client.storage_client()?; // 2. Auth provider — async because OAuth flows hit the OIDC // discovery endpoint. @@ -503,7 +504,7 @@ impl Session { Ok(Session { inner: Arc::new(SessionInner { transport, - storage_client: http_client.inner().clone(), + storage_client, volume_states: std::sync::Mutex::new(Some(Vec::new())), session_id: session_info.session_id, config, diff --git a/tests/v0_volume_wiremock.rs b/tests/v0_volume_wiremock.rs index b25f2fd2..c259bc98 100644 --- a/tests/v0_volume_wiremock.rs +++ b/tests/v0_volume_wiremock.rs @@ -19,8 +19,8 @@ use arrow_ipc::writer::StreamWriter; use arrow_schema::{DataType, Field, Schema}; use base64::{engine::general_purpose::STANDARD, Engine}; use databricks_sql_kernel::{ - AuthConfig, ConnectionConfig, DirectStatement, ErrorCode, ExecutedStatementHandle, Session, - VolumeCompletion, VolumeOptions, + AuthConfig, ConnectionConfig, DirectStatement, ErrorCode, ExecutedStatementHandle, HttpConfig, + Session, VolumeCompletion, VolumeOptions, }; use serde_json::json; use std::sync::Arc; @@ -29,13 +29,14 @@ use wiremock::matchers::{method, path}; use wiremock::{Mock, MockServer, ResponseTemplate}; fn response(server: &MockServer, marked: bool, local: &str) -> serde_json::Value { - response_with_batches(server, marked, local, 1) + response_with_batches(server, marked, local, "GET", 1) } fn response_with_batches( server: &MockServer, marked: bool, local: &str, + operation: &str, count: usize, ) -> serde_json::Value { let names = ["operation", "presignedUrl", "headers", "localFile"]; @@ -46,7 +47,7 @@ fn response_with_batches( .collect::>(), )); let values = [ - "GET".to_owned(), + operation.to_owned(), format!("{}/object", server.uri()), "{}".to_owned(), local.to_owned(), @@ -86,7 +87,7 @@ async fn multiple_instruction_batches_fail_before_any_storage_request() { std::fs::write(&dest, b"original").unwrap(); let session = session( &server, - response_with_batches(&server, true, dest.to_str().unwrap(), 2), + response_with_batches(&server, true, dest.to_str().unwrap(), "GET", 2), ) .await; Mock::given(method("GET")) @@ -117,6 +118,14 @@ async fn multiple_instruction_batches_fail_before_any_storage_request() { } async fn session(server: &MockServer, body: serde_json::Value) -> Session { + session_with_http(server, body, HttpConfig::default()).await +} + +async fn session_with_http( + server: &MockServer, + body: serde_json::Value, + http: HttpConfig, +) -> Session { Mock::given(method("POST")) .and(path("/api/2.0/sql/warehouses/wh/sessions")) .respond_with( @@ -152,11 +161,75 @@ async fn session(server: &MockServer, body: serde_json::Value) -> Session { token: "workspace-token".into(), identity_federation_client_id: None, }) + .http(http) .open() .await .unwrap() } +#[tokio::test] +async fn storage_transfers_outlive_rpc_deadline_while_sql_requests_still_time_out() { + for operation in ["PUT", "GET"] { + let server = MockServer::start().await; + let dir = tempfile::tempdir().unwrap(); + let local = dir.path().join("file"); + std::fs::write(&local, b"original").unwrap(); + let mut http = HttpConfig::default(); + http.request_timeout = Duration::from_millis(100); + let session = session_with_http( + &server, + response_with_batches(&server, true, local.to_str().unwrap(), operation, 1), + http, + ) + .await; + Mock::given(method(operation)) + .and(path("/object")) + .respond_with( + ResponseTemplate::new(200) + .set_delay(Duration::from_millis(300)) + .set_body_bytes(b"downloaded"), + ) + .expect(1) + .mount(&server) + .await; + let mut statement = session.statement(); + statement.spec().sql("operation"); + let mut executed = statement.execute().await.unwrap(); + assert_eq!( + executed + .result_stream_mut() + .complete_volume_operation( + &VolumeOptions { + allowed_paths: vec![dir.path().to_owned()], + ..Default::default() + }, + None, + ) + .await + .unwrap(), + VolumeCompletion::Completed + ); + if operation == "PUT" { + let requests = server.received_requests().await.unwrap(); + let upload = requests.iter().find(|r| r.url.path() == "/object").unwrap(); + assert_eq!(upload.body, b"original"); + } else { + assert_eq!(std::fs::read(&local).unwrap(), b"downloaded"); + } + executed.close().await.unwrap(); + Mock::given(method("POST")) + .and(path("/api/2.0/sql/statements")) + .respond_with(ResponseTemplate::new(200).set_delay(Duration::from_millis(300))) + .with_priority(1) + .mount(&server) + .await; + let error = statement.execute().await.err().expect("RPC deadline"); + assert_eq!(error.code, ErrorCode::NetworkError); + assert!(error.message.contains("timed out"), "{error}"); + session.close().await.unwrap(); + } +} + #[tokio::test] async fn sync_and_direct_closed_results_complete_explicitly_and_keep_raw_rows() { for direct in [false, true] { From cc5bac624412f206583a53c921959fe14e9cd01b Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Sat, 14 Nov 2026 02:45:32 +0000 Subject: [PATCH 08/63] Retry transient Volume storage failures safely Signed-off-by: Aakash Saravanan --- src/c_abi/result.rs | 2 +- src/session.rs | 5 +- src/volume.rs | 380 ++++++++++++++++++++++++++++++------ tests/v0_volume_wiremock.rs | 1 + 4 files changed, 331 insertions(+), 57 deletions(-) diff --git a/src/c_abi/result.rs b/src/c_abi/result.rs index 5a87edec..0328ad37 100644 --- a/src/c_abi/result.rs +++ b/src/c_abi/result.rs @@ -802,7 +802,7 @@ mod tests { .unwrap(); stream.attach_volume( marked, - crate::volume::VolumeState::new(), + crate::volume::VolumeState::new(Default::default()), reqwest::Client::new(), ); into_raw_result_stream(schema.clone(), stream) diff --git a/src/session.rs b/src/session.rs index c8f8395a..7069ef06 100644 --- a/src/session.rs +++ b/src/session.rs @@ -98,6 +98,7 @@ pub(crate) struct SessionInner { /// `TransportMode`. transport: Arc, storage_client: reqwest::Client, + storage_retry: RetryConfig, volume_states: std::sync::Mutex>>>, /// Server-issued session identifier. @@ -161,7 +162,7 @@ pub(crate) struct SessionInner { impl SessionInner { pub(crate) fn new_volume_state(&self) -> Arc { - let state = crate::volume::VolumeState::new(); + let state = crate::volume::VolumeState::new(self.storage_retry.clone()); let mut states = self.volume_states.lock().unwrap_or_else(|e| e.into_inner()); if let Some(states) = states.as_mut() { states.retain(|state| state.strong_count() != 0); @@ -398,6 +399,7 @@ 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 storage_retry = retry_configs[&RequestCategory::Sea].clone(); let http_client = Arc::new( DatabricksHttpClient::new(http_client_config, retry_configs).map_err(|e| { Error::network_error().message(format!("Failed to construct HTTP client: {e}")) @@ -505,6 +507,7 @@ impl Session { inner: Arc::new(SessionInner { transport, storage_client, + storage_retry, volume_states: std::sync::Mutex::new(Some(Vec::new())), session_id: session_info.session_id, config, diff --git a/src/volume.rs b/src/volume.rs index 710f400b..9067b311 100644 --- a/src/volume.rs +++ b/src/volume.rs @@ -14,6 +14,7 @@ //! Explicit completion of server-authorized Volume file transfers. +use crate::client::retry::{calculate_backoff, RequestType, RetryConfig, RetryStrategy}; use crate::kernel_error::{Error, LocalFileError, Result}; use crate::result_stream::ResultBatch; use arrow_array::{Array, LargeStringArray, MapArray, StringArray, StringViewArray}; @@ -60,6 +61,7 @@ enum CommitState { /// The synchronous gate makes cancellation and local publication mutually exclusive. #[derive(Default)] pub(crate) struct VolumeState { + retry: RetryConfig, serial: tokio::sync::Mutex<()>, commit: Mutex, changed: Notify, @@ -70,8 +72,11 @@ fn cancelled() -> Error { } impl VolumeState { - pub(crate) fn new() -> Arc { - Arc::new(Self::default()) + pub(crate) fn new(retry: RetryConfig) -> Arc { + Arc::new(Self { + retry, + ..Self::default() + }) } pub(crate) fn cached(&self) -> Option> { @@ -175,6 +180,57 @@ impl VolumeState { client: &Client, options: &VolumeOptions, input_bytes: Option>, + ) -> Result { + let input_request = + if instruction.operation == "PUT" && instruction.local_file == "__input_stream__" { + let bytes = input_bytes.ok_or_else(|| invalid("Missing input stream"))?; + Some( + client + .put(&instruction.url) + .headers(instruction.headers.clone()) + .header(reqwest::header::CONTENT_LENGTH, bytes.len()) + .body(bytes), + ) + } else { + None + }; + let started = std::time::Instant::now(); + let mut attempt = 0; + loop { + let mut retry_after = None; + let error = match self + .transfer_once( + &instruction, + client, + options, + input_request.as_ref(), + &mut retry_after, + ) + .await + { + Ok(completion) => return Ok(completion), + Err(error) => error, + }; + if !error.retryable || attempt >= self.retry.max_retries { + return Err(error.with_retryable(false)); + } + let wait = calculate_backoff(&self.retry, attempt, retry_after.as_deref()); + // Retry budgets govern recovery, not the duration of a healthy transfer. + if started.elapsed().saturating_add(wait) >= self.retry.overall_timeout { + return Err(error.with_retryable(false)); + } + tokio::time::sleep(wait).await; + attempt += 1; + } + } + + async fn transfer_once( + &self, + instruction: &Instruction, + client: &Client, + options: &VolumeOptions, + input_request: Option<&reqwest::RequestBuilder>, + retry_after: &mut Option, ) -> Result { let method = match instruction.operation.as_str() { "PUT" => Method::PUT, @@ -182,16 +238,17 @@ impl VolumeState { "REMOVE" => Method::DELETE, _ => return Err(invalid("Unsupported Volume operation")), }; - let mut request = client - .request(method, &instruction.url) - .headers(instruction.headers); - let local_path = if instruction.operation == "REMOVE" { - None - } else if instruction.operation == "PUT" && instruction.local_file == "__input_stream__" { - let bytes = input_bytes.ok_or_else(|| invalid("Missing input stream"))?; - request = request - .header(reqwest::header::CONTENT_LENGTH, bytes.len()) - .body(bytes); + let mut request = match input_request { + Some(request) => request + .try_clone() + .ok_or_else(|| invalid("Input bytes cannot be replayed"))?, + None => client + .request(method, &instruction.url) + .headers(instruction.headers.clone()), + }; + let local_path = if instruction.operation == "REMOVE" + || (instruction.operation == "PUT" && instruction.local_file == "__input_stream__") + { None } else { let path = allowed_path(&instruction.local_file, &options.allowed_paths)?; @@ -249,8 +306,6 @@ impl VolumeState { None }; - // This client has workspace TLS/proxy/timeouts, but no workspace auth headers. - // A single attempt avoids replaying an upload after an ambiguous response. let mut response = request.send().await.map_err(storage_error)?; let status = response.status(); if !status.is_success() @@ -258,18 +313,27 @@ impl VolumeState { && status.as_u16() == 404 && options.remove_not_found_is_success) { - return Err(Error::from_http_status(status.as_u16()).message(format!( - "Volume storage request failed: HTTP {}", - status.as_u16() - ))); + *retry_after = response + .headers() + .get(reqwest::header::RETRY_AFTER) + .and_then(|value| value.to_str().ok()) + .map(str::to_owned); + return Err(Error::from_http_status(status.as_u16()) + .with_retryable(matches!(status.as_u16(), 408 | 429 | 500 | 502 | 503 | 504)) + .message(format!( + "Volume storage request failed: HTTP {}", + status.as_u16() + ))); } - if let Some((temp, mut writer)) = destination.take() { - while let Some(bytes) = response.chunk().await.map_err(storage_error)? { + while let Some(bytes) = response.chunk().await.map_err(response_body_error)? { + if let Some((_, writer)) = destination.as_mut() { writer .write_all(&bytes) .await .map_err(|e| local_error(e, &instruction.local_file))?; } + } + if let Some((temp, mut writer)) = destination.take() { writer .flush() .await @@ -292,14 +356,34 @@ fn invalid(message: &str) -> Error { } fn storage_error(error: reqwest::Error) -> Error { + // A file reader's failure is wrapped in a request error by the HTTP stack. + let source_body_failed = std::iter::successors( + Some(&error as &(dyn std::error::Error + 'static)), + |cause| cause.source(), + ) + .any(|cause| { + cause + .downcast_ref::() + .is_some_and(reqwest::Error::is_body) + }); + let retryable = !source_body_failed + && RetryStrategy::for_request(RequestType::CloudFetchDownload, &RetryConfig::default()) + .is_retryable_error(&error); Error::network_error() - .with_retryable(false) + .with_retryable(retryable) .message(format!( "Volume storage request failed: {}", error.without_url() )) } +fn response_body_error(error: reqwest::Error) -> Error { + let retryable = error.is_body() || error.is_decode(); + let mut error = storage_error(error); + error.retryable |= retryable; + error +} + fn local_error(error: std::io::Error, path: &str) -> Error { let mut result = Error::io().message(format!("{error}: {path}")); result.local_error = Some(Box::new(LocalFileError { @@ -516,6 +600,183 @@ mod tests { } } + fn transfer_state(max_retries: u32) -> Arc { + VolumeState::new(RetryConfig { + max_retries, + min_wait: Duration::ZERO, + max_wait: Duration::ZERO, + ..Default::default() + }) + } + + #[tokio::test] + async fn local_upload_read_errors_wrapped_as_request_errors_are_not_retried() { + let server = MockServer::start().await; + let body = reqwest::Body::wrap_stream(futures::stream::iter([Err::, _>( + std::io::Error::from(std::io::ErrorKind::PermissionDenied), + )])); + let error = Client::new() + .put(server.uri()) + .body(body) + .send() + .await + .unwrap_err(); + assert!(!storage_error(error).retryable); + } + + #[tokio::test] + async fn transient_storage_statuses_replay_full_inputs_and_cache_completion() { + use std::sync::atomic::{AtomicUsize, Ordering}; + for (operation, stream) in [ + ("PUT", false), + ("PUT", true), + ("GET", false), + ("REMOVE", false), + ] { + let server = MockServer::start().await; + let attempts = Arc::new(AtomicUsize::new(0)); + let count = Arc::clone(&attempts); + Mock::given(method(if operation == "REMOVE" { + "DELETE" + } else { + operation + })) + .and(path("/object")) + .and(header("x-storage-token", "server-token")) + .respond_with(move |request: &wiremock::Request| { + if operation == "PUT" { + assert_eq!(request.body, b"payload"); + } + if let Some(status) = + [408, 429, 500, 502, 503, 504].get(count.fetch_add(1, Ordering::SeqCst)) + { + ResponseTemplate::new(*status).insert_header("retry-after", "0") + } else { + ResponseTemplate::new(200).set_body_bytes(b"payload") + } + }) + .expect(7) + .mount(&server) + .await; + let dir = tempfile::tempdir().unwrap(); + let file = dir.path().join("file"); + std::fs::write( + &file, + if operation == "GET" { + b"old".as_slice() + } else { + b"payload" + }, + ) + .unwrap(); + let local = if stream { + Path::new("__input_stream__") + } else { + &file + }; + let batch = instruction(operation, &format!("{}/object", server.uri()), local); + let state = transfer_state(6); + let client = Client::new(); + let options = options(dir.path()); + assert_eq!( + state + .complete( + &batch, + &client, + &options, + stream.then(|| b"payload".to_vec()) + ) + .await + .unwrap(), + VolumeCompletion::Completed + ); + assert_eq!( + state + .complete(&batch, &client, &options, None) + .await + .unwrap(), + VolumeCompletion::Completed + ); + assert_eq!(attempts.load(Ordering::SeqCst), 7); + assert_eq!(std::fs::read(file).unwrap(), b"payload"); + assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 1); + } + } + + #[tokio::test] + async fn permanent_statuses_and_retry_limits_preserve_terminal_errors() { + for (status, retries, budget, requests) in [ + (400, 2, Duration::from_secs(10), 1), + (401, 2, Duration::from_secs(10), 1), + (403, 2, Duration::from_secs(10), 1), + (404, 2, Duration::from_secs(10), 1), + (501, 2, Duration::from_secs(10), 1), + (503, 0, Duration::from_secs(10), 1), + (503, 2, Duration::ZERO, 1), + (503, 2, Duration::from_secs(10), 3), + ] { + let server = MockServer::start().await; + Mock::given(method("DELETE")) + .respond_with(ResponseTemplate::new(status).insert_header("retry-after", "0")) + .expect(requests) + .mount(&server) + .await; + let state = VolumeState::new(RetryConfig { + max_retries: retries, + overall_timeout: budget, + min_wait: Duration::ZERO, + max_wait: Duration::ZERO, + ..Default::default() + }); + let batch = instruction( + "REMOVE", + &format!("{}?secret=hidden", server.uri()), + Path::new(""), + ); + for _ in 0..2 { + let error = state + .complete(&batch, &Client::new(), &VolumeOptions::default(), None) + .await + .unwrap_err(); + assert_eq!(error.http_status, Some(status)); + assert!(!error.retryable); + assert!(!error.message.contains("secret")); + } + } + } + + #[tokio::test] + async fn cancellation_interrupts_retry_backoff_without_another_request() { + let server = MockServer::start().await; + Mock::given(method("DELETE")) + .respond_with(ResponseTemplate::new(503).insert_header("retry-after", "30")) + .expect(1) + .mount(&server) + .await; + let state = VolumeState::new(RetryConfig { + min_wait: Duration::from_secs(30), + max_wait: Duration::from_secs(30), + ..Default::default() + }); + let batch = instruction("REMOVE", &server.uri(), Path::new("")); + let client = Client::new(); + let options = VolumeOptions::default(); + let complete = state.complete(&batch, &client, &options, None); + let cancel = async { + while server.received_requests().await.unwrap().is_empty() { + tokio::task::yield_now().await; + } + tokio::time::sleep(Duration::from_millis(50)).await; + state.cancel(); + }; + let (result, _) = tokio::time::timeout(Duration::from_secs(1), async { + tokio::join!(complete, cancel) + }) + .await + .unwrap(); + assert_eq!(result.unwrap_err().code, crate::ErrorCode::Cancelled); + } + #[tokio::test] async fn stream_handshake_accepts_empty_bytes_once_and_keeps_success_after_cancel() { let server = MockServer::start().await; @@ -533,7 +794,7 @@ mod tests { &format!("{}/object", server.uri()), Path::new("__input_stream__"), ); - let state = VolumeState::new(); + let state = transfer_state(0); let client = Client::new(); assert_eq!( state @@ -575,7 +836,7 @@ mod tests { .mount(&server) .await; let batch = instruction("PUT", &server.uri(), &source); - VolumeState::new() + transfer_state(0) .complete(&batch, &Client::new(), &options(dir.path()), None) .await .unwrap(); @@ -603,7 +864,7 @@ mod tests { let dest = dir.path().join("download"); std::fs::write(&dest, b"old bytes").unwrap(); let batch = instruction("GET", &format!("{}/ok", server.uri()), &dest); - let completed = VolumeState::new(); + let completed = transfer_state(0); completed .complete(&batch, &Client::new(), &options(dir.path()), None) .await @@ -617,7 +878,7 @@ mod tests { VolumeCompletion::Completed ); assert_eq!(std::fs::read(&dest).unwrap(), b"new bytes"); - let state = VolumeState::new(); + let state = transfer_state(0); let batch = instruction( "GET", &format!("{}/fail?secret=hidden", server.uri()), @@ -653,7 +914,7 @@ mod tests { let batch = instruction("REMOVE", &server.uri(), Path::new("")); let strict = VolumeOptions::default(); assert_eq!( - VolumeState::new() + transfer_state(0) .complete(&batch, &Client::new(), &strict, None) .await .unwrap_err() @@ -665,7 +926,7 @@ mod tests { ..strict }; assert_eq!( - VolumeState::new() + transfer_state(0) .complete(&batch, &Client::new(), &permissive, None) .await .unwrap(), @@ -692,7 +953,7 @@ mod tests { let options = options(dir.path()); let client = Client::new(); for cancel in [false, true] { - let state = VolumeState::new(); + let state = transfer_state(0); let mut future = Box::pin(state.complete(&batch, &client, &options, None)); tokio::select! { result = &mut future => panic!("unexpected early completion: {result:?}"), @@ -725,33 +986,42 @@ mod tests { } #[tokio::test] - async fn truncated_get_preserves_destination() { + async fn truncated_get_retries_from_clean_temp_and_preserves_destination_on_failure() { use tokio::io::{AsyncReadExt, AsyncWriteExt}; - let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); - let url = format!("http://{}", listener.local_addr().unwrap()); - let peer = tokio::spawn(async move { - let (mut socket, _) = listener.accept().await.unwrap(); - let mut request = [0; 2048]; - assert!(socket.read(&mut request).await.unwrap() > 0); - socket - .write_all( - b"HTTP/1.1 200 OK\r\nContent-Length: 20\r\nConnection: close\r\n\r\nshort", - ) - .await - .unwrap(); - }); - let dir = tempfile::tempdir().unwrap(); - let dest = dir.path().join("download"); - std::fs::write(&dest, b"old").unwrap(); - let batch = instruction("GET", &url, &dest); - let error = VolumeState::new() - .complete(&batch, &Client::new(), &options(dir.path()), None) - .await - .unwrap_err(); - assert_eq!(error.code, crate::ErrorCode::NetworkError); - assert_eq!(std::fs::read(&dest).unwrap(), b"old"); - assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 1); - peer.await.unwrap(); + for retries in [0, 1] { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}", listener.local_addr().unwrap()); + let peer = tokio::spawn(async move { + for attempt in 0..=retries { + let (mut socket, _) = listener.accept().await.unwrap(); + let mut request = [0; 2048]; + assert!(socket.read(&mut request).await.unwrap() > 0); + let response = if attempt == 0 { + b"HTTP/1.1 200 OK\r\nContent-Length: 20\r\nConnection: close\r\n\r\nshort" + .as_slice() + } else { + b"HTTP/1.1 200 OK\r\nContent-Length: 7\r\nConnection: close\r\n\r\ncorrect" + }; + socket.write_all(response).await.unwrap(); + } + }); + let dir = tempfile::tempdir().unwrap(); + let dest = dir.path().join("download"); + std::fs::write(&dest, b"old").unwrap(); + let batch = instruction("GET", &url, &dest); + let result = transfer_state(retries) + .complete(&batch, &Client::new(), &options(dir.path()), None) + .await; + if retries == 0 { + assert_eq!(result.unwrap_err().code, crate::ErrorCode::NetworkError); + assert_eq!(std::fs::read(&dest).unwrap(), b"old"); + } else { + assert_eq!(result.unwrap(), VolumeCompletion::Completed); + assert_eq!(std::fs::read(&dest).unwrap(), b"correct"); + } + assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 1); + peer.await.unwrap(); + } } #[cfg(any(unix, windows))] @@ -804,7 +1074,7 @@ mod tests { let dir = tempfile::tempdir().unwrap(); let source = dir.path().join("missing"); let batch = instruction("PUT", "http://127.0.0.1:1?secret=hidden", &source); - let error = VolumeState::new() + let error = transfer_state(0) .complete(&batch, &Client::new(), &options(dir.path()), None) .await .unwrap_err(); diff --git a/tests/v0_volume_wiremock.rs b/tests/v0_volume_wiremock.rs index c259bc98..43574539 100644 --- a/tests/v0_volume_wiremock.rs +++ b/tests/v0_volume_wiremock.rs @@ -176,6 +176,7 @@ async fn storage_transfers_outlive_rpc_deadline_while_sql_requests_still_time_ou std::fs::write(&local, b"original").unwrap(); let mut http = HttpConfig::default(); http.request_timeout = Duration::from_millis(100); + http.overall_timeout = Duration::from_millis(200); let session = session_with_http( &server, response_with_batches(&server, true, local.to_str().unwrap(), operation, 1), From 4f0b3da714091753f1610833dd7cac6204b25fd3 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Sat, 14 Nov 2026 03:28:21 +0000 Subject: [PATCH 09/63] Identify Volume storage HTTP errors Signed-off-by: Aakash Saravanan --- src/kernel_error.rs | 4 ++-- src/volume.rs | 5 +++++ 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/src/kernel_error.rs b/src/kernel_error.rs index 14f2030e..6ec47e88 100644 --- a/src/kernel_error.rs +++ b/src/kernel_error.rs @@ -180,8 +180,8 @@ pub struct Error { /// 5-character SQLSTATE if the server returned one. pub sql_state: Option, - /// Databricks-specific error identifier from the SEA - /// `ServiceError.error_code` envelope — a stable string slug like + /// Stable error identifier from the kernel or the SEA + /// `ServiceError.error_code` envelope, such as /// `STATEMENT_NOT_FOUND` or `WAREHOUSE_STOPPED` that wrappers can /// branch on to map to host-language exceptions (PySQL's /// `OperationalError` taxonomy, JDBC's `SQLException` subclasses). diff --git a/src/volume.rs b/src/volume.rs index 9067b311..bd0408dc 100644 --- a/src/volume.rs +++ b/src/volume.rs @@ -319,6 +319,7 @@ impl VolumeState { .and_then(|value| value.to_str().ok()) .map(str::to_owned); return Err(Error::from_http_status(status.as_u16()) + .with_error_code("VOLUME_STORAGE_HTTP_ERROR") .with_retryable(matches!(status.as_u16(), 408 | 429 | 500 | 502 | 503 | 504)) .message(format!( "Volume storage request failed: HTTP {}", @@ -739,6 +740,10 @@ mod tests { .await .unwrap_err(); assert_eq!(error.http_status, Some(status)); + assert_eq!( + error.error_code.as_deref(), + Some("VOLUME_STORAGE_HTTP_ERROR") + ); assert!(!error.retryable); assert!(!error.message.contains("secret")); } From 072bc2481b0a20e5b2721289f8f4c2705be0441d Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Sat, 14 Nov 2026 05:17:35 +0000 Subject: [PATCH 10/63] Preserve Volume download inactivity limits and storage error origin Signed-off-by: Aakash Saravanan --- include/databricks_kernel.h | 1 + pyo3/src/session.rs | 9 +- src/c_abi/error.rs | 20 ++++ src/c_abi/result.rs | 2 +- src/config.rs | 5 + src/session.rs | 5 +- src/volume.rs | 193 ++++++++++++++++++++++++++++++++---- 7 files changed, 211 insertions(+), 24 deletions(-) diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h index fe88926b..a88286dc 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -193,6 +193,7 @@ bool kernel_get_last_error(KernelError* out); /* These accessors preserve the last error. Strings are borrowed until the next * error-clearing kernel call; absent strings are NULL, absent OS code is zero. */ int32_t kernel_get_last_error_local_os_error(void); +const char* kernel_get_last_error_code(void); const char* kernel_get_last_error_local_kind(void); const char* kernel_get_last_error_local_path(void); diff --git a/pyo3/src/session.rs b/pyo3/src/session.rs index c626ee89..78b34e3e 100644 --- a/pyo3/src/session.rs +++ b/pyo3/src/session.rs @@ -207,6 +207,7 @@ fn build_http_config( http.sea_response_compression_enabled = sea_response_compression_enabled; if let Some(timeout) = request_timeout { http.request_timeout = timeout; + http.storage_download_read_timeout = Some(timeout); } if let Some(max) = max_connections { http.pool_max_idle_per_host = max; @@ -317,11 +318,13 @@ impl Session { /// CloudFetch requests; token-endpoint (auth) calls keep a fixed /// fast-fail policy. /// - /// `request_timeout_secs` sets the total timeout for one HTTP request, + /// `request_timeout_secs` sets the total timeout for one SQL HTTP request, /// from connection start through response-body completion. A separate /// 30-second connection timeout also applies, so connection establishment /// is bounded by the shorter limit. Unset or `0` keeps the kernel default /// (120 seconds). + /// For Volume GET, a positive configured value instead bounds inactivity + /// while waiting for response headers or the next body chunk. /// /// `max_connections` sets the maximum idle connections retained per host. /// Unset keeps the kernel default (100); zero is rejected. @@ -869,6 +872,10 @@ mod send_sync_tests { .unwrap() .expect("positive request timeout should build an HTTP config"); assert_eq!(http.request_timeout, std::time::Duration::from_millis(500)); + assert_eq!( + http.storage_download_read_timeout, + Some(std::time::Duration::from_millis(500)) + ); assert_eq!(http.retry_min_wait, default.retry_min_wait); assert_eq!(http.overall_timeout, default.overall_timeout); diff --git a/src/c_abi/error.rs b/src/c_abi/error.rs index 0ea0d233..7d1bab5c 100644 --- a/src/c_abi/error.rs +++ b/src/c_abi/error.rs @@ -65,6 +65,7 @@ struct LastError { http_status: u16, retryable: bool, query_id: Option, + error_code: Option, } thread_local! { @@ -139,6 +140,17 @@ pub extern "C" fn kernel_get_last_error_local_os_error() -> i32 { LAST_ERROR.with(|last| last.borrow().local_os_error) } +/// Borrowed structured error identifier, or null. Valid until the next error-clearing call. +#[no_mangle] +pub extern "C" fn kernel_get_last_error_code() -> *const c_char { + LAST_ERROR.with(|last| { + last.borrow() + .error_code + .as_ref() + .map_or(std::ptr::null(), |s| s.as_ptr()) + }) +} + /// Borrowed local error kind, or null. Valid until the next error-clearing call. #[no_mangle] pub extern "C" fn kernel_get_last_error_local_kind() -> *const c_char { @@ -196,6 +208,7 @@ pub(crate) fn store_error(err: Error) { http_status: err.http_status.unwrap_or(0), retryable: err.retryable, query_id: err.query_id.as_deref().map(to_cstring_lossy), + error_code: err.error_code.as_deref().map(to_cstring_lossy), }; }); } @@ -323,8 +336,15 @@ mod tests { .unwrap(); assert!(msg.contains("statement gone")); assert!(msg.contains("STATEMENT_NOT_FOUND")); + assert_eq!( + unsafe { std::ffi::CStr::from_ptr(kernel_get_last_error_code()) } + .to_str() + .unwrap(), + "STATEMENT_NOT_FOUND" + ); }); clear_error(); + assert!(kernel_get_last_error_code().is_null()); } #[test] diff --git a/src/c_abi/result.rs b/src/c_abi/result.rs index 0328ad37..3e92da95 100644 --- a/src/c_abi/result.rs +++ b/src/c_abi/result.rs @@ -802,7 +802,7 @@ mod tests { .unwrap(); stream.attach_volume( marked, - crate::volume::VolumeState::new(Default::default()), + crate::volume::VolumeState::new(Default::default(), None), reqwest::Client::new(), ); into_raw_result_stream(schema.clone(), stream) diff --git a/src/config.rs b/src/config.rs index 9c1eb0a9..4c3660e8 100644 --- a/src/config.rs +++ b/src/config.rs @@ -757,6 +757,10 @@ pub struct HttpConfig { /// applies, so connection establishment is bounded by the shorter limit. pub request_timeout: Duration, + /// Inactivity limit for Volume GET response headers and each body read. + /// Separate from the SQL request deadline so progressing transfers can finish. + pub storage_download_read_timeout: Option, + /// Maximum total time across retries for a single logical RPC. /// Retrying stops once cumulative elapsed time exceeds this. pub overall_timeout: Duration, @@ -836,6 +840,7 @@ impl Default for HttpConfig { Self { sea_response_compression_enabled: false, request_timeout: Duration::from_secs(120), + storage_download_read_timeout: None, overall_timeout: Duration::from_secs(900), pool_max_idle_per_host: 100, // Mirror `RetryConfig::default()` so a stock `HttpConfig` diff --git a/src/session.rs b/src/session.rs index 7069ef06..b9005d69 100644 --- a/src/session.rs +++ b/src/session.rs @@ -162,7 +162,10 @@ pub(crate) struct SessionInner { impl SessionInner { pub(crate) fn new_volume_state(&self) -> Arc { - let state = crate::volume::VolumeState::new(self.storage_retry.clone()); + let state = crate::volume::VolumeState::new( + self.storage_retry.clone(), + self.config.http.storage_download_read_timeout, + ); let mut states = self.volume_states.lock().unwrap_or_else(|e| e.into_inner()); if let Some(states) = states.as_mut() { states.retain(|state| state.strong_count() != 0); diff --git a/src/volume.rs b/src/volume.rs index bd0408dc..c2262522 100644 --- a/src/volume.rs +++ b/src/volume.rs @@ -62,6 +62,7 @@ enum CommitState { #[derive(Default)] pub(crate) struct VolumeState { retry: RetryConfig, + download_read_timeout: Option, serial: tokio::sync::Mutex<()>, commit: Mutex, changed: Notify, @@ -72,9 +73,13 @@ fn cancelled() -> Error { } impl VolumeState { - pub(crate) fn new(retry: RetryConfig) -> Arc { + pub(crate) fn new( + retry: RetryConfig, + download_read_timeout: Option, + ) -> Arc { Arc::new(Self { retry, + download_read_timeout, ..Self::default() }) } @@ -306,7 +311,15 @@ impl VolumeState { None }; - let mut response = request.send().await.map_err(storage_error)?; + let read_timeout = if instruction.operation == "GET" { + self.download_read_timeout + } else { + None + }; + let mut response = storage_read(read_timeout, async { + request.send().await.map_err(storage_error) + }) + .await?; let status = response.status(); if !status.is_success() && !(instruction.operation == "REMOVE" @@ -326,7 +339,11 @@ impl VolumeState { status.as_u16() ))); } - while let Some(bytes) = response.chunk().await.map_err(response_body_error)? { + while let Some(bytes) = storage_read(read_timeout, async { + response.chunk().await.map_err(response_body_error) + }) + .await? + { if let Some((_, writer)) = destination.as_mut() { writer .write_all(&bytes) @@ -356,6 +373,23 @@ fn invalid(message: &str) -> Error { Error::invalid_argument().message(message) } +async fn storage_read( + timeout: Option, + read: impl std::future::Future>, +) -> Result { + match timeout { + Some(timeout) => tokio::time::timeout(timeout, read) + .await + .unwrap_or_else(|_| { + Err(Error::network_error() + .with_error_code("VOLUME_STORAGE_NETWORK_ERROR") + .with_retryable(true) + .message("Volume storage download read timed out")) + }), + None => read.await, + } +} + fn storage_error(error: reqwest::Error) -> Error { // A file reader's failure is wrapped in a request error by the HTTP stack. let source_body_failed = std::iter::successors( @@ -371,6 +405,7 @@ fn storage_error(error: reqwest::Error) -> Error { && RetryStrategy::for_request(RequestType::CloudFetchDownload, &RetryConfig::default()) .is_retryable_error(&error); Error::network_error() + .with_error_code("VOLUME_STORAGE_NETWORK_ERROR") .with_retryable(retryable) .message(format!( "Volume storage request failed: {}", @@ -602,12 +637,15 @@ mod tests { } fn transfer_state(max_retries: u32) -> Arc { - VolumeState::new(RetryConfig { - max_retries, - min_wait: Duration::ZERO, - max_wait: Duration::ZERO, - ..Default::default() - }) + VolumeState::new( + RetryConfig { + max_retries, + min_wait: Duration::ZERO, + max_wait: Duration::ZERO, + ..Default::default() + }, + None, + ) } #[tokio::test] @@ -722,13 +760,16 @@ mod tests { .expect(requests) .mount(&server) .await; - let state = VolumeState::new(RetryConfig { - max_retries: retries, - overall_timeout: budget, - min_wait: Duration::ZERO, - max_wait: Duration::ZERO, - ..Default::default() - }); + let state = VolumeState::new( + RetryConfig { + max_retries: retries, + overall_timeout: budget, + min_wait: Duration::ZERO, + max_wait: Duration::ZERO, + ..Default::default() + }, + None, + ); let batch = instruction( "REMOVE", &format!("{}?secret=hidden", server.uri()), @@ -758,11 +799,14 @@ mod tests { .expect(1) .mount(&server) .await; - let state = VolumeState::new(RetryConfig { - min_wait: Duration::from_secs(30), - max_wait: Duration::from_secs(30), - ..Default::default() - }); + let state = VolumeState::new( + RetryConfig { + min_wait: Duration::from_secs(30), + max_wait: Duration::from_secs(30), + ..Default::default() + }, + None, + ); let batch = instruction("REMOVE", &server.uri(), Path::new("")); let client = Client::new(); let options = VolumeOptions::default(); @@ -990,6 +1034,113 @@ mod tests { assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 1); } + #[tokio::test] + async fn download_inactivity_bounds_headers_and_body_without_publishing() { + use tokio::io::AsyncReadExt; + for headers_sent in [false, true] { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}", listener.local_addr().unwrap()); + let peer = tokio::spawn(async move { + let (mut socket, _) = listener.accept().await.unwrap(); + let mut request = [0; 2048]; + assert!(socket.read(&mut request).await.unwrap() > 0); + if headers_sent { + socket + .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 20\r\n\r\nshort") + .await + .unwrap(); + } + tokio::time::sleep(Duration::from_secs(5)).await; + }); + let dir = tempfile::tempdir().unwrap(); + let dest = dir.path().join("download"); + std::fs::write(&dest, b"old").unwrap(); + let state = VolumeState::new( + transfer_state(0).retry.clone(), + Some(Duration::from_millis(150)), + ); + let error = tokio::time::timeout( + Duration::from_secs(2), + state.complete( + &instruction("GET", &url, &dest), + &Client::new(), + &options(dir.path()), + None, + ), + ) + .await + .unwrap() + .unwrap_err(); + assert_eq!(error.code, crate::ErrorCode::NetworkError); + assert_eq!( + error.error_code.as_deref(), + Some("VOLUME_STORAGE_NETWORK_ERROR") + ); + assert!(error.message.contains("read timed out")); + assert_eq!(std::fs::read(&dest).unwrap(), b"old"); + assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 1); + peer.abort(); + } + } + + #[tokio::test] + async fn download_inactivity_resets_on_progress_and_does_not_limit_put() { + use tokio::io::AsyncReadExt; + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}", listener.local_addr().unwrap()); + let peer = tokio::spawn(async move { + let (mut socket, _) = listener.accept().await.unwrap(); + let mut request = [0; 2048]; + assert!(socket.read(&mut request).await.unwrap() > 0); + socket + .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\n") + .await + .unwrap(); + for _ in 0..5 { + tokio::time::sleep(Duration::from_millis(60)).await; + socket.write_all(b"x").await.unwrap(); + } + }); + let dir = tempfile::tempdir().unwrap(); + let dest = dir.path().join("download"); + let state = VolumeState::new( + transfer_state(0).retry.clone(), + Some(Duration::from_millis(150)), + ); + state + .complete( + &instruction("GET", &url, &dest), + &Client::new(), + &options(dir.path()), + None, + ) + .await + .unwrap(); + assert_eq!(std::fs::read(&dest).unwrap(), b"xxxxx"); + peer.await.unwrap(); + + let server = MockServer::start().await; + Mock::given(method("PUT")) + .and(body_bytes(b"xxxxx")) + .respond_with(ResponseTemplate::new(200).set_delay(Duration::from_millis(300))) + .expect(1) + .mount(&server) + .await; + let state = VolumeState::new( + transfer_state(0).retry.clone(), + Some(Duration::from_millis(150)), + ); + state + .complete( + &instruction("PUT", &server.uri(), &dest), + &Client::new(), + &options(dir.path()), + None, + ) + .await + .unwrap(); + } + #[tokio::test] async fn truncated_get_retries_from_clean_temp_and_preserves_destination_on_failure() { use tokio::io::{AsyncReadExt, AsyncWriteExt}; From 243858afae723aefdceee38434d7f77bf57a3016 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Sat, 14 Nov 2026 23:45:54 +0000 Subject: [PATCH 11/63] fix(volume): preserve cancellation and storage error contracts Signed-off-by: Aakash Saravanan --- pyo3/src/session.rs | 8 +- src/config.rs | 6 +- src/result_stream.rs | 62 +++---- src/session.rs | 2 +- src/volume.rs | 318 ++++++++++++++++++++++++++---------- tests/v0_volume_wiremock.rs | 51 +++++- 6 files changed, 321 insertions(+), 126 deletions(-) diff --git a/pyo3/src/session.rs b/pyo3/src/session.rs index 78b34e3e..6126b263 100644 --- a/pyo3/src/session.rs +++ b/pyo3/src/session.rs @@ -207,7 +207,7 @@ fn build_http_config( http.sea_response_compression_enabled = sea_response_compression_enabled; if let Some(timeout) = request_timeout { http.request_timeout = timeout; - http.storage_download_read_timeout = Some(timeout); + http.storage_read_timeout = Some(timeout); } if let Some(max) = max_connections { http.pool_max_idle_per_host = max; @@ -323,8 +323,8 @@ impl Session { /// 30-second connection timeout also applies, so connection establishment /// is bounded by the shorter limit. Unset or `0` keeps the kernel default /// (120 seconds). - /// For Volume GET, a positive configured value instead bounds inactivity - /// while waiting for response headers or the next body chunk. + /// For Volume transfers, a positive configured value bounds response + /// inactivity after upload and between body chunks, without a total deadline. /// /// `max_connections` sets the maximum idle connections retained per host. /// Unset keeps the kernel default (100); zero is rejected. @@ -873,7 +873,7 @@ mod send_sync_tests { .expect("positive request timeout should build an HTTP config"); assert_eq!(http.request_timeout, std::time::Duration::from_millis(500)); assert_eq!( - http.storage_download_read_timeout, + http.storage_read_timeout, Some(std::time::Duration::from_millis(500)) ); assert_eq!(http.retry_min_wait, default.retry_min_wait); diff --git a/src/config.rs b/src/config.rs index 4c3660e8..d3621c7e 100644 --- a/src/config.rs +++ b/src/config.rs @@ -757,9 +757,9 @@ pub struct HttpConfig { /// applies, so connection establishment is bounded by the shorter limit. pub request_timeout: Duration, - /// Inactivity limit for Volume GET response headers and each body read. + /// Inactivity limit for Volume response headers after upload and each body read. /// Separate from the SQL request deadline so progressing transfers can finish. - pub storage_download_read_timeout: Option, + pub storage_read_timeout: Option, /// Maximum total time across retries for a single logical RPC. /// Retrying stops once cumulative elapsed time exceeds this. @@ -840,7 +840,7 @@ impl Default for HttpConfig { Self { sea_response_compression_enabled: false, request_timeout: Duration::from_secs(120), - storage_download_read_timeout: None, + storage_read_timeout: None, overall_timeout: Duration::from_secs(900), pool_max_idle_per_host: 100, // Mirror `RetryConfig::default()` so a stock `HttpConfig` diff --git a/src/result_stream.rs b/src/result_stream.rs index 1031f502..627c6d5c 100644 --- a/src/result_stream.rs +++ b/src/result_stream.rs @@ -672,36 +672,42 @@ impl ResultStream { if let Some(result) = state.cached() { return result; } - let batch = self - .peek_first_batch() - .await - .map_err(|error| state.fail(error))? - .ok_or_else(|| { - state.fail(Error::invalid_argument().message("Missing Volume instruction row")) - })?; - let ResultBatch::Arrow(batch) = batch; - let batch = ResultBatch::Arrow(batch.clone()); - // The first batch stays buffered for callers; later batches must not - // authorize a partial transfer of a multi-row instruction result. - while !self.exhausted { - match self - .reader - .as_mut() - .expect("Volume completion retains its reader") - .next_batch() - .await - .map_err(|error| state.fail(error))? - { - Some(batch) if batch.num_rows() != 0 => { - return Err(state.fail( - Error::invalid_argument().message("Expected one Volume instruction row"), - )); + tokio::select! { + biased; + error = state.cancellation() => Err(error), + result = async { + let batch = self + .peek_first_batch() + .await + .map_err(|error| state.fail(error))? + .ok_or_else(|| { + state.fail(Error::invalid_argument().message("Missing Volume instruction row")) + })?; + let ResultBatch::Arrow(batch) = batch; + let batch = ResultBatch::Arrow(batch.clone()); + // The first batch stays buffered for callers; later batches must not + // authorize a partial transfer of a multi-row instruction result. + while !self.exhausted { + match self + .reader + .as_mut() + .expect("Volume completion retains its reader") + .next_batch() + .await + .map_err(|error| state.fail(error))? + { + Some(batch) if batch.num_rows() != 0 => { + return Err(state.fail( + Error::invalid_argument().message("Expected one Volume instruction row"), + )); + } + Some(_) => {} + None => self.exhausted = true, + } } - Some(_) => {} - None => self.exhausted = true, - } + state.complete(&batch, &client, options, input_bytes).await + } => result, } - state.complete(&batch, &client, options, input_bytes).await } pub(crate) fn volume_state(&self) -> Option> { diff --git a/src/session.rs b/src/session.rs index b9005d69..e332a2c0 100644 --- a/src/session.rs +++ b/src/session.rs @@ -164,7 +164,7 @@ impl SessionInner { pub(crate) fn new_volume_state(&self) -> Arc { let state = crate::volume::VolumeState::new( self.storage_retry.clone(), - self.config.http.storage_download_read_timeout, + self.config.http.storage_read_timeout, ); let mut states = self.volume_states.lock().unwrap_or_else(|e| e.into_inner()); if let Some(states) = states.as_mut() { diff --git a/src/volume.rs b/src/volume.rs index c2262522..8bdc7a9e 100644 --- a/src/volume.rs +++ b/src/volume.rs @@ -18,11 +18,12 @@ use crate::client::retry::{calculate_backoff, RequestType, RetryConfig, RetryStr use crate::kernel_error::{Error, LocalFileError, Result}; use crate::result_stream::ResultBatch; use arrow_array::{Array, LargeStringArray, MapArray, StringArray, StringViewArray}; +use futures::TryStreamExt; use reqwest::{header::HeaderMap, Client, Method}; use std::path::{Component, Path, PathBuf}; use std::sync::{Arc, Mutex}; use tokio::io::AsyncWriteExt; -use tokio::sync::Notify; +use tokio::sync::{oneshot, Notify}; use tokio_util::io::ReaderStream; /// Local file authorization and driver-specific storage response policy. @@ -62,7 +63,7 @@ enum CommitState { #[derive(Default)] pub(crate) struct VolumeState { retry: RetryConfig, - download_read_timeout: Option, + read_timeout: Option, serial: tokio::sync::Mutex<()>, commit: Mutex, changed: Notify, @@ -73,13 +74,10 @@ fn cancelled() -> Error { } impl VolumeState { - pub(crate) fn new( - retry: RetryConfig, - download_read_timeout: Option, - ) -> Arc { + pub(crate) fn new(retry: RetryConfig, read_timeout: Option) -> Arc { Arc::new(Self { retry, - download_read_timeout, + read_timeout, ..Self::default() }) } @@ -113,14 +111,14 @@ impl VolumeState { } } - async fn cancellation(&self) { + pub(crate) async fn cancellation(&self) -> Error { loop { let notified = self.changed.notified(); tokio::pin!(notified); notified.as_mut().enable(); if matches!(self.cached(), Some(Err(error)) if error.code == crate::ErrorCode::Cancelled) { - return; + return cancelled(); } notified.await; } @@ -186,16 +184,10 @@ impl VolumeState { options: &VolumeOptions, input_bytes: Option>, ) -> Result { - let input_request = + let input = if instruction.operation == "PUT" && instruction.local_file == "__input_stream__" { let bytes = input_bytes.ok_or_else(|| invalid("Missing input stream"))?; - Some( - client - .put(&instruction.url) - .headers(instruction.headers.clone()) - .header(reqwest::header::CONTENT_LENGTH, bytes.len()) - .body(bytes), - ) + Some(Arc::<[u8]>::from(bytes)) } else { None }; @@ -208,7 +200,7 @@ impl VolumeState { &instruction, client, options, - input_request.as_ref(), + input.as_ref(), &mut retry_after, ) .await @@ -234,7 +226,7 @@ impl VolumeState { instruction: &Instruction, client: &Client, options: &VolumeOptions, - input_request: Option<&reqwest::RequestBuilder>, + input: Option<&Arc<[u8]>>, retry_after: &mut Option, ) -> Result { let method = match instruction.operation.as_str() { @@ -243,14 +235,23 @@ impl VolumeState { "REMOVE" => Method::DELETE, _ => return Err(invalid("Unsupported Volume operation")), }; - let mut request = match input_request { - Some(request) => request - .try_clone() - .ok_or_else(|| invalid("Input bytes cannot be replayed"))?, - None => client - .request(method, &instruction.url) - .headers(instruction.headers.clone()), - }; + let mut request = client + .request(method, &instruction.url) + .headers(instruction.headers.clone()); + let upload_error = Arc::new(Mutex::new(None)); + let (uploaded, upload_complete) = oneshot::channel(); + let mut uploaded = Some(uploaded); + if let Some(bytes) = input { + request = request + .header(reqwest::header::CONTENT_LENGTH, bytes.len()) + .body(upload_body( + std::io::Cursor::new(Arc::clone(bytes)), + bytes.len() as u64, + instruction.local_file.clone(), + uploaded.take().unwrap(), + Arc::clone(&upload_error), + )); + } let local_path = if instruction.operation == "REMOVE" || (instruction.operation == "PUT" && instruction.local_file == "__input_stream__") { @@ -258,15 +259,27 @@ impl VolumeState { } else { let path = allowed_path(&instruction.local_file, &options.allowed_paths)?; if instruction.operation == "PUT" { - let file = std::fs::File::open(&path) + let mut file = std::fs::File::open(&path) .map_err(|e| local_error(e, &instruction.local_file))?; - let size = file + let metadata = file .metadata() - .map_err(|e| local_error(e, &instruction.local_file))? - .len(); - request = request.header(reqwest::header::CONTENT_LENGTH, size).body( - reqwest::Body::wrap_stream(ReaderStream::new(tokio::fs::File::from_std(file))), - ); + .map_err(|e| local_error(e, &instruction.local_file))?; + if metadata.is_dir() { + // Reading the opened directory retains the platform's filesystem cause. + let error = std::io::Read::read(&mut file, &mut [0]) + .err() + .unwrap_or_else(|| std::io::ErrorKind::IsADirectory.into()); + return Err(local_error(error, &instruction.local_file)); + } + request = request + .header(reqwest::header::CONTENT_LENGTH, metadata.len()) + .body(upload_body( + tokio::fs::File::from_std(file), + metadata.len(), + instruction.local_file.clone(), + uploaded.take().unwrap(), + Arc::clone(&upload_error), + )); } Some(path) }; @@ -311,15 +324,11 @@ impl VolumeState { None }; - let read_timeout = if instruction.operation == "GET" { - self.download_read_timeout - } else { - None - }; - let mut response = storage_read(read_timeout, async { - request.send().await.map_err(storage_error) - }) - .await?; + if let Some(uploaded) = uploaded { + let _ = uploaded.send(()); + } + let mut response = + storage_send(request, self.read_timeout, upload_complete, upload_error).await?; let status = response.status(); if !status.is_success() && !(instruction.operation == "REMOVE" @@ -339,7 +348,7 @@ impl VolumeState { status.as_u16() ))); } - while let Some(bytes) = storage_read(read_timeout, async { + while let Some(bytes) = storage_read(self.read_timeout, async { response.chunk().await.map_err(response_body_error) }) .await? @@ -369,10 +378,63 @@ impl VolumeState { } } +fn upload_body( + reader: impl tokio::io::AsyncRead + Unpin + Send + 'static, + mut remaining: u64, + path: String, + uploaded: oneshot::Sender<()>, + error: Arc>>, +) -> reqwest::Body { + let mut uploaded = Some(uploaded); + if remaining == 0 { + let _ = uploaded.take().unwrap().send(()); + } + reqwest::Body::wrap_stream( + ReaderStream::new(reader) + .inspect_ok(move |bytes| { + remaining = remaining.saturating_sub(bytes.len() as u64); + if remaining == 0 { + if let Some(uploaded) = uploaded.take() { + let _ = uploaded.send(()); + } + } + }) + .map_err(move |cause| { + *error.lock().unwrap_or_else(|e| e.into_inner()) = Some(local_error(cause, &path)); + std::io::Error::other("Volume upload source could not be read") + }), + ) +} + fn invalid(message: &str) -> Error { Error::invalid_argument().message(message) } +async fn storage_send( + request: reqwest::RequestBuilder, + timeout: Option, + upload_complete: oneshot::Receiver<()>, + upload_error: Arc>>, +) -> Result { + let send = request.send(); + tokio::pin!(send); + // Response inactivity starts after the upload, without a total transfer deadline. + let response = tokio::select! { + result = &mut send => result.map_err(storage_error), + _ = upload_complete => storage_read(timeout, async { + send.await.map_err(storage_error) + }).await, + }; + if let Some(error) = upload_error + .lock() + .unwrap_or_else(|e| e.into_inner()) + .take() + { + return Err(error); + } + response +} + async fn storage_read( timeout: Option, read: impl std::future::Future>, @@ -384,7 +446,7 @@ async fn storage_read( Err(Error::network_error() .with_error_code("VOLUME_STORAGE_NETWORK_ERROR") .with_retryable(true) - .message("Volume storage download read timed out")) + .message("Volume storage read timed out")) }), None => read.await, } @@ -651,16 +713,45 @@ mod tests { #[tokio::test] async fn local_upload_read_errors_wrapped_as_request_errors_are_not_retried() { let server = MockServer::start().await; - let body = reqwest::Body::wrap_stream(futures::stream::iter([Err::, _>( - std::io::Error::from(std::io::ErrorKind::PermissionDenied), - )])); - let error = Client::new() - .put(server.uri()) - .body(body) - .send() - .await - .unwrap_err(); - assert!(!storage_error(error).retryable); + struct FailedRead(Option); + impl tokio::io::AsyncRead for FailedRead { + fn poll_read( + mut self: std::pin::Pin<&mut Self>, + _: &mut std::task::Context<'_>, + _: &mut tokio::io::ReadBuf<'_>, + ) -> std::task::Poll> { + std::task::Poll::Ready(Err(self.0.take().unwrap())) + } + } + let dir = tempfile::tempdir().unwrap(); + let source = dir.path().join("missing"); + let cause = std::fs::File::open(&source).unwrap_err(); + let os_code = cause.raw_os_error(); + let captured = Arc::new(Mutex::new(None)); + let (uploaded, complete) = oneshot::channel(); + let body = upload_body( + FailedRead(Some(cause)), + 1, + source.to_str().unwrap().into(), + uploaded, + Arc::clone(&captured), + ); + let error = storage_send( + Client::new() + .put(format!("{}/object?secret=hidden", server.uri())) + .body(body), + None, + complete, + captured, + ) + .await + .unwrap_err(); + assert!(!error.retryable); + assert_eq!(error.code, crate::ErrorCode::Internal); + let local = error.local_error.unwrap(); + assert_eq!(local.raw_os_error, os_code); + assert_eq!(local.path, source.to_str().unwrap()); + assert!(!error.message.contains("hidden")); } #[tokio::test] @@ -1035,15 +1126,34 @@ mod tests { } #[tokio::test] - async fn download_inactivity_bounds_headers_and_body_without_publishing() { + async fn response_inactivity_bounds_headers_and_body_without_publishing() { use tokio::io::AsyncReadExt; - for headers_sent in [false, true] { + for (operation, headers_sent) in [ + ("GET", false), + ("GET", true), + ("PUT", false), + ("REMOVE", false), + ] { let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); let url = format!("http://{}", listener.local_addr().unwrap()); let peer = tokio::spawn(async move { let (mut socket, _) = listener.accept().await.unwrap(); - let mut request = [0; 2048]; - assert!(socket.read(&mut request).await.unwrap() > 0); + let mut request = Vec::new(); + let mut byte = [0]; + while !request.ends_with(b"\r\n\r\n") { + socket.read_exact(&mut byte).await.unwrap(); + request.push(byte[0]); + } + let size = String::from_utf8(request) + .unwrap() + .lines() + .find_map(|line| { + line.to_lowercase() + .strip_prefix("content-length:") + .map(|size| size.trim().parse::().unwrap()) + }) + .unwrap_or(0); + socket.read_exact(&mut vec![0; size]).await.unwrap(); if headers_sent { socket .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 20\r\n\r\nshort") @@ -1062,7 +1172,7 @@ mod tests { let error = tokio::time::timeout( Duration::from_secs(2), state.complete( - &instruction("GET", &url, &dest), + &instruction(operation, &url, &dest), &Client::new(), &options(dir.path()), None, @@ -1084,7 +1194,7 @@ mod tests { } #[tokio::test] - async fn download_inactivity_resets_on_progress_and_does_not_limit_put() { + async fn response_inactivity_resets_on_progress_and_allows_progressing_uploads() { use tokio::io::AsyncReadExt; let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); let url = format!("http://{}", listener.local_addr().unwrap()); @@ -1122,23 +1232,32 @@ mod tests { let server = MockServer::start().await; Mock::given(method("PUT")) .and(body_bytes(b"xxxxx")) - .respond_with(ResponseTemplate::new(200).set_delay(Duration::from_millis(300))) + .respond_with(ResponseTemplate::new(200)) .expect(1) .mount(&server) .await; - let state = VolumeState::new( - transfer_state(0).retry.clone(), + let (mut writer, reader) = tokio::io::duplex(1); + let producer = tokio::spawn(async move { + for _ in 0..5 { + tokio::time::sleep(Duration::from_millis(60)).await; + writer.write_all(b"x").await.unwrap(); + } + }); + let (uploaded, complete) = oneshot::channel(); + let error = Arc::new(Mutex::new(None)); + let body = upload_body(reader, 5, "input".into(), uploaded, Arc::clone(&error)); + storage_send( + Client::new() + .put(server.uri()) + .header(reqwest::header::CONTENT_LENGTH, 5) + .body(body), Some(Duration::from_millis(150)), - ); - state - .complete( - &instruction("PUT", &server.uri(), &dest), - &Client::new(), - &options(dir.path()), - None, - ) - .await - .unwrap(); + complete, + error, + ) + .await + .unwrap(); + producer.await.unwrap(); } #[tokio::test] @@ -1228,17 +1347,46 @@ mod tests { #[tokio::test] async fn local_errors_retain_os_code_and_requested_filename() { let dir = tempfile::tempdir().unwrap(); - let source = dir.path().join("missing"); - let batch = instruction("PUT", "http://127.0.0.1:1?secret=hidden", &source); - let error = transfer_state(0) - .complete(&batch, &Client::new(), &options(dir.path()), None) - .await - .unwrap_err(); - let local = error.local_error.unwrap(); - assert_eq!(local.kind, "NotFound"); - assert!(local.raw_os_error.is_some()); - assert_eq!(local.path, source.to_str().unwrap()); - assert!(!error.message.contains("hidden")); + let server = MockServer::start().await; + for (source, kind) in [ + (dir.path().join("missing"), "NotFound"), + ( + dir.path().to_owned(), + if cfg!(windows) { + "PermissionDenied" + } else { + "IsADirectory" + }, + ), + ] { + let batch = instruction( + "PUT", + &format!("{}/object?secret=hidden", server.uri()), + &source, + ); + let state = transfer_state(1); + let error = state + .complete(&batch, &Client::new(), &options(dir.path()), None) + .await + .unwrap_err(); + let local = error.local_error.as_ref().unwrap(); + assert_eq!(local.kind, kind); + assert!(local.raw_os_error.is_some()); + assert_eq!(local.path, source.to_str().unwrap()); + assert!(!error.message.contains("hidden")); + assert_eq!( + state + .complete(&batch, &Client::new(), &options(dir.path()), None) + .await + .unwrap_err() + .local_error + .as_ref() + .unwrap() + .raw_os_error, + local.raw_os_error + ); + } + assert!(server.received_requests().await.unwrap().is_empty()); } #[test] diff --git a/tests/v0_volume_wiremock.rs b/tests/v0_volume_wiremock.rs index 43574539..15ada130 100644 --- a/tests/v0_volume_wiremock.rs +++ b/tests/v0_volume_wiremock.rs @@ -360,14 +360,36 @@ async fn owner_reader_and_repeated_materialization_share_one_completion() { } #[tokio::test] -async fn cancellation_and_session_close_interrupt_transfer_after_sql_closed() { - for close_session in [false, true] { +async fn cancellation_and_session_close_interrupt_instruction_or_storage_after_sql_closed() { + for (instruction_page, close_session) in + [(false, false), (false, true), (true, false), (true, true)] + { let server = MockServer::start().await; let dir = tempfile::tempdir().unwrap(); let dest = dir.path().join("download"); std::fs::write(&dest, b"old").unwrap(); - let mut session = - Some(session(&server, response(&server, true, dest.to_str().unwrap())).await); + let mut body = response(&server, true, dest.to_str().unwrap()); + let held_path = if instruction_page { + body["manifest"]["total_chunk_count"] = json!(2); + body["result"]["next_chunk_index"] = json!(1); + let mut next = response_with_batches(&server, true, dest.to_str().unwrap(), "GET", 0) + ["result"] + .clone(); + next["chunk_index"] = json!(1); + Mock::given(method("GET")) + .and(path("/api/2.0/sql/statements/volume-stmt/result/chunks/1")) + .respond_with( + ResponseTemplate::new(200) + .set_delay(Duration::from_secs(3)) + .set_body_json(next), + ) + .mount(&server) + .await; + "/api/2.0/sql/statements/volume-stmt/result/chunks/1" + } else { + "/object" + }; + let mut session = Some(session(&server, body).await); Mock::given(method("GET")) .and(path("/object")) .respond_with( @@ -375,6 +397,7 @@ async fn cancellation_and_session_close_interrupt_transfer_after_sql_closed() { .set_delay(Duration::from_secs(3)) .set_body_bytes(b"new"), ) + .expect(if instruction_page { 0 } else { 1 }) .mount(&server) .await; let mut stmt = session.as_ref().unwrap().statement(); @@ -395,7 +418,7 @@ async fn cancellation_and_session_close_interrupt_transfer_after_sql_closed() { .await .unwrap() .iter() - .any(|req| req.url.path() == "/object") + .any(|req| req.url.path() == held_path) { break; } @@ -413,6 +436,24 @@ async fn cancellation_and_session_close_interrupt_transfer_after_sql_closed() { .await .unwrap(); assert_eq!(result.unwrap_err().code, ErrorCode::Cancelled); + assert_eq!( + exec.result_stream_mut() + .complete_volume_operation(&options, None) + .await + .unwrap_err() + .code, + ErrorCode::Cancelled + ); + assert_eq!( + server + .received_requests() + .await + .unwrap() + .iter() + .filter(|req| req.url.path() == held_path) + .count(), + 1 + ); assert_eq!(std::fs::read(&dest).unwrap(), b"old"); if let Some(session) = session { session.close().await.unwrap(); From 9a4ec13a5ecf571043afbc8d85afc4ba1908bb8e Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Sat, 14 Nov 2026 23:48:37 +0000 Subject: [PATCH 12/63] fix(volume): avoid replaying timed out uploads Signed-off-by: Aakash Saravanan --- src/volume.rs | 93 ++++++++++++++++++++++++++++++++------------------- 1 file changed, 58 insertions(+), 35 deletions(-) diff --git a/src/volume.rs b/src/volume.rs index 8bdc7a9e..675521e4 100644 --- a/src/volume.rs +++ b/src/volume.rs @@ -327,8 +327,15 @@ impl VolumeState { if let Some(uploaded) = uploaded { let _ = uploaded.send(()); } - let mut response = - storage_send(request, self.read_timeout, upload_complete, upload_error).await?; + let retry_timeout = instruction.operation != "PUT"; + let mut response = storage_send( + request, + self.read_timeout, + retry_timeout, + upload_complete, + upload_error, + ) + .await?; let status = response.status(); if !status.is_success() && !(instruction.operation == "REMOVE" @@ -348,7 +355,7 @@ impl VolumeState { status.as_u16() ))); } - while let Some(bytes) = storage_read(self.read_timeout, async { + while let Some(bytes) = storage_read(self.read_timeout, retry_timeout, async { response.chunk().await.map_err(response_body_error) }) .await? @@ -413,6 +420,7 @@ fn invalid(message: &str) -> Error { async fn storage_send( request: reqwest::RequestBuilder, timeout: Option, + retry_timeout: bool, upload_complete: oneshot::Receiver<()>, upload_error: Arc>>, ) -> Result { @@ -421,7 +429,7 @@ async fn storage_send( // Response inactivity starts after the upload, without a total transfer deadline. let response = tokio::select! { result = &mut send => result.map_err(storage_error), - _ = upload_complete => storage_read(timeout, async { + _ = upload_complete => storage_read(timeout, retry_timeout, async { send.await.map_err(storage_error) }).await, }; @@ -437,6 +445,7 @@ async fn storage_send( async fn storage_read( timeout: Option, + retry_timeout: bool, read: impl std::future::Future>, ) -> Result { match timeout { @@ -445,7 +454,7 @@ async fn storage_read( .unwrap_or_else(|_| { Err(Error::network_error() .with_error_code("VOLUME_STORAGE_NETWORK_ERROR") - .with_retryable(true) + .with_retryable(retry_timeout) .message("Volume storage read timed out")) }), None => read.await, @@ -741,6 +750,7 @@ mod tests { .put(format!("{}/object?secret=hidden", server.uri())) .body(body), None, + false, complete, captured, ) @@ -1132,51 +1142,57 @@ mod tests { ("GET", false), ("GET", true), ("PUT", false), + ("PUT", true), ("REMOVE", false), ] { let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); let url = format!("http://{}", listener.local_addr().unwrap()); + let requests = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let received = Arc::clone(&requests); let peer = tokio::spawn(async move { - let (mut socket, _) = listener.accept().await.unwrap(); - let mut request = Vec::new(); - let mut byte = [0]; - while !request.ends_with(b"\r\n\r\n") { - socket.read_exact(&mut byte).await.unwrap(); - request.push(byte[0]); - } - let size = String::from_utf8(request) - .unwrap() - .lines() - .find_map(|line| { - line.to_lowercase() - .strip_prefix("content-length:") - .map(|size| size.trim().parse::().unwrap()) - }) - .unwrap_or(0); - socket.read_exact(&mut vec![0; size]).await.unwrap(); - if headers_sent { - socket - .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 20\r\n\r\nshort") - .await - .unwrap(); + loop { + let (mut socket, _) = listener.accept().await.unwrap(); + received.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + tokio::spawn(async move { + let mut request = Vec::new(); + let mut byte = [0]; + while !request.ends_with(b"\r\n\r\n") { + socket.read_exact(&mut byte).await.unwrap(); + request.push(byte[0]); + } + let size = String::from_utf8(request) + .unwrap() + .lines() + .find_map(|line| { + line.to_lowercase() + .strip_prefix("content-length:") + .map(|size| size.trim().parse::().unwrap()) + }) + .unwrap_or(0); + socket.read_exact(&mut vec![0; size]).await.unwrap(); + if headers_sent { + socket + .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 20\r\n\r\nshort") + .await + .unwrap(); + } + tokio::time::sleep(Duration::from_secs(5)).await; + }); } - tokio::time::sleep(Duration::from_secs(5)).await; }); let dir = tempfile::tempdir().unwrap(); let dest = dir.path().join("download"); std::fs::write(&dest, b"old").unwrap(); let state = VolumeState::new( - transfer_state(0).retry.clone(), + transfer_state(if operation == "PUT" { 1 } else { 0 }) + .retry + .clone(), Some(Duration::from_millis(150)), ); + let batch = instruction(operation, &url, &dest); let error = tokio::time::timeout( Duration::from_secs(2), - state.complete( - &instruction(operation, &url, &dest), - &Client::new(), - &options(dir.path()), - None, - ), + state.complete(&batch, &Client::new(), &options(dir.path()), None), ) .await .unwrap() @@ -1187,6 +1203,12 @@ mod tests { Some("VOLUME_STORAGE_NETWORK_ERROR") ); assert!(error.message.contains("read timed out")); + let repeated = state + .complete(&batch, &Client::new(), &options(dir.path()), None) + .await + .unwrap_err(); + assert_eq!(repeated.message, error.message); + assert_eq!(requests.load(std::sync::atomic::Ordering::SeqCst), 1); assert_eq!(std::fs::read(&dest).unwrap(), b"old"); assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 1); peer.abort(); @@ -1252,6 +1274,7 @@ mod tests { .header(reqwest::header::CONTENT_LENGTH, 5) .body(body), Some(Duration::from_millis(150)), + false, complete, error, ) From 0ad177d4a7b9890c1ce8444c1200062b10a42e90 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Sun, 15 Nov 2026 01:04:45 +0000 Subject: [PATCH 13/63] fix(volume): apply configured storage connection timeout Signed-off-by: Aakash Saravanan --- src/client/http.rs | 8 ++++-- src/client/http_tls_tests.rs | 48 ++++++++++++++++++++++++++++++++++++ src/config.rs | 1 + src/session.rs | 2 +- 4 files changed, 56 insertions(+), 3 deletions(-) diff --git a/src/client/http.rs b/src/client/http.rs index e96aac3d..616d52be 100644 --- a/src/client/http.rs +++ b/src/client/http.rs @@ -742,8 +742,12 @@ impl DatabricksHttpClient { } /// Storage transfers can outlive SQL RPCs, so retain connection settings without their deadline. - pub(crate) fn storage_client(&self) -> Result { - Self::build_reqwest_client(&self.config, reqwest::redirect::Policy::default(), None) + pub(crate) fn storage_client(&self, connect_timeout: Option) -> Result { + let mut config = self.config.clone(); + if let Some(timeout) = connect_timeout { + config.connect_timeout = config.connect_timeout.min(timeout); + } + Self::build_reqwest_client(&config, reqwest::redirect::Policy::default(), None) } /// Get the authorization header value. diff --git a/src/client/http_tls_tests.rs b/src/client/http_tls_tests.rs index b4b2d8c3..60e41b43 100644 --- a/src/client/http_tls_tests.rs +++ b/src/client/http_tls_tests.rs @@ -288,6 +288,54 @@ async fn expired_certificate_fails_once_with_certificate_cause() { assert_certificate_failure(CertificateFailure::Expired).await; } +#[tokio::test] +async fn storage_connection_timeout_preserves_unconfigured_limits() { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let (shutdown, mut stopped) = oneshot::channel(); + let server = tokio::spawn(async move { + let mut sockets = Vec::new(); + loop { + tokio::select! { + _ = &mut stopped => return sockets.len(), + accepted = listener.accept() => sockets.push(accepted.unwrap().0), + } + } + }); + let client = test_client( + HttpClientConfig { + connect_timeout: Duration::from_secs(2), + read_timeout: Duration::from_millis(10), + ..Default::default() + }, + Duration::from_secs(10), + ); + for timeout in [None, Some(Duration::from_millis(100))] { + let storage = client.storage_client(timeout).unwrap(); + let result = tokio::time::timeout( + Duration::from_millis(500), + storage + .put(format!("https://{address}/object")) + .body("bytes") + .send(), + ) + .await; + if timeout.is_some() { + let error = result + .expect("configured connection timeout must finish") + .unwrap_err(); + assert!(error.is_connect() && error.is_timeout(), "{error}"); + } else { + assert!( + result.is_err(), + "unconfigured storage must retain its limits" + ); + } + } + shutdown.send(()).unwrap(); + assert_eq!(server.await.unwrap(), 2); +} + #[tokio::test] async fn tls_handshake_timeout_still_retries() { for request_type in [RequestType::CreateSession, RequestType::ExecuteStatement] { diff --git a/src/config.rs b/src/config.rs index d3621c7e..96d42e21 100644 --- a/src/config.rs +++ b/src/config.rs @@ -759,6 +759,7 @@ pub struct HttpConfig { /// Inactivity limit for Volume response headers after upload and each body read. /// Separate from the SQL request deadline so progressing transfers can finish. + /// Also caps connection establishment. pub storage_read_timeout: Option, /// Maximum total time across retries for a single logical RPC. diff --git a/src/session.rs b/src/session.rs index e332a2c0..516ea575 100644 --- a/src/session.rs +++ b/src/session.rs @@ -408,7 +408,7 @@ impl Session { Error::network_error().message(format!("Failed to construct HTTP client: {e}")) })?, ); - let storage_client = http_client.storage_client()?; + let storage_client = http_client.storage_client(config.http.storage_read_timeout)?; // 2. Auth provider — async because OAuth flows hit the OIDC // discovery endpoint. From c0c4b680051e1dfe10e096ad324598f3b1559010 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Sun, 15 Nov 2026 01:46:23 +0000 Subject: [PATCH 14/63] fix(volume): avoid premature upload response timeouts Signed-off-by: Aakash Saravanan --- pyo3/src/session.rs | 5 ++-- src/config.rs | 4 +-- src/volume.rs | 73 +++++++++++---------------------------------- 3 files changed, 23 insertions(+), 59 deletions(-) diff --git a/pyo3/src/session.rs b/pyo3/src/session.rs index 6126b263..b6afec53 100644 --- a/pyo3/src/session.rs +++ b/pyo3/src/session.rs @@ -323,8 +323,9 @@ impl Session { /// 30-second connection timeout also applies, so connection establishment /// is bounded by the shorter limit. Unset or `0` keeps the kernel default /// (120 seconds). - /// For Volume transfers, a positive configured value bounds response - /// inactivity after upload and between body chunks, without a total deadline. + /// For Volume transfers, a positive value bounds connection establishment, + /// GET/REMOVE response-header waits and all response-body reads. PUT header + /// waits have no deadline, allowing progressing uploads to finish. /// /// `max_connections` sets the maximum idle connections retained per host. /// Unset keeps the kernel default (100); zero is rejected. diff --git a/src/config.rs b/src/config.rs index 96d42e21..5c75e532 100644 --- a/src/config.rs +++ b/src/config.rs @@ -757,9 +757,9 @@ pub struct HttpConfig { /// applies, so connection establishment is bounded by the shorter limit. pub request_timeout: Duration, - /// Inactivity limit for Volume response headers after upload and each body read. + /// Inactivity limit for Volume GET/REMOVE response headers and each response-body read. /// Separate from the SQL request deadline so progressing transfers can finish. - /// Also caps connection establishment. + /// Also caps connection establishment; PUT response headers have no deadline. pub storage_read_timeout: Option, /// Maximum total time across retries for a single logical RPC. diff --git a/src/volume.rs b/src/volume.rs index 675521e4..1ec3aabd 100644 --- a/src/volume.rs +++ b/src/volume.rs @@ -23,7 +23,7 @@ use reqwest::{header::HeaderMap, Client, Method}; use std::path::{Component, Path, PathBuf}; use std::sync::{Arc, Mutex}; use tokio::io::AsyncWriteExt; -use tokio::sync::{oneshot, Notify}; +use tokio::sync::Notify; use tokio_util::io::ReaderStream; /// Local file authorization and driver-specific storage response policy. @@ -239,16 +239,12 @@ impl VolumeState { .request(method, &instruction.url) .headers(instruction.headers.clone()); let upload_error = Arc::new(Mutex::new(None)); - let (uploaded, upload_complete) = oneshot::channel(); - let mut uploaded = Some(uploaded); if let Some(bytes) = input { request = request .header(reqwest::header::CONTENT_LENGTH, bytes.len()) .body(upload_body( std::io::Cursor::new(Arc::clone(bytes)), - bytes.len() as u64, instruction.local_file.clone(), - uploaded.take().unwrap(), Arc::clone(&upload_error), )); } @@ -275,9 +271,7 @@ impl VolumeState { .header(reqwest::header::CONTENT_LENGTH, metadata.len()) .body(upload_body( tokio::fs::File::from_std(file), - metadata.len(), instruction.local_file.clone(), - uploaded.take().unwrap(), Arc::clone(&upload_error), )); } @@ -324,15 +318,11 @@ impl VolumeState { None }; - if let Some(uploaded) = uploaded { - let _ = uploaded.send(()); - } let retry_timeout = instruction.operation != "PUT"; let mut response = storage_send( request, self.read_timeout, - retry_timeout, - upload_complete, + instruction.operation == "PUT", upload_error, ) .await?; @@ -387,30 +377,13 @@ impl VolumeState { fn upload_body( reader: impl tokio::io::AsyncRead + Unpin + Send + 'static, - mut remaining: u64, path: String, - uploaded: oneshot::Sender<()>, error: Arc>>, ) -> reqwest::Body { - let mut uploaded = Some(uploaded); - if remaining == 0 { - let _ = uploaded.take().unwrap().send(()); - } - reqwest::Body::wrap_stream( - ReaderStream::new(reader) - .inspect_ok(move |bytes| { - remaining = remaining.saturating_sub(bytes.len() as u64); - if remaining == 0 { - if let Some(uploaded) = uploaded.take() { - let _ = uploaded.send(()); - } - } - }) - .map_err(move |cause| { - *error.lock().unwrap_or_else(|e| e.into_inner()) = Some(local_error(cause, &path)); - std::io::Error::other("Volume upload source could not be read") - }), - ) + reqwest::Body::wrap_stream(ReaderStream::new(reader).map_err(move |cause| { + *error.lock().unwrap_or_else(|e| e.into_inner()) = Some(local_error(cause, &path)); + std::io::Error::other("Volume upload source could not be read") + })) } fn invalid(message: &str) -> Error { @@ -420,18 +393,15 @@ fn invalid(message: &str) -> Error { async fn storage_send( request: reqwest::RequestBuilder, timeout: Option, - retry_timeout: bool, - upload_complete: oneshot::Receiver<()>, + upload: bool, upload_error: Arc>>, ) -> Result { - let send = request.send(); - tokio::pin!(send); - // Response inactivity starts after the upload, without a total transfer deadline. - let response = tokio::select! { - result = &mut send => result.map_err(storage_error), - _ = upload_complete => storage_read(timeout, retry_timeout, async { - send.await.map_err(storage_error) - }).await, + let send = async { request.send().await.map_err(storage_error) }; + let response = if upload { + // Request-body production does not establish that transport buffers have flushed. + send.await + } else { + storage_read(timeout, true, send).await }; if let Some(error) = upload_error .lock() @@ -737,12 +707,9 @@ mod tests { let cause = std::fs::File::open(&source).unwrap_err(); let os_code = cause.raw_os_error(); let captured = Arc::new(Mutex::new(None)); - let (uploaded, complete) = oneshot::channel(); let body = upload_body( FailedRead(Some(cause)), - 1, source.to_str().unwrap().into(), - uploaded, Arc::clone(&captured), ); let error = storage_send( @@ -750,8 +717,7 @@ mod tests { .put(format!("{}/object?secret=hidden", server.uri())) .body(body), None, - false, - complete, + true, captured, ) .await @@ -1141,7 +1107,6 @@ mod tests { for (operation, headers_sent) in [ ("GET", false), ("GET", true), - ("PUT", false), ("PUT", true), ("REMOVE", false), ] { @@ -1216,7 +1181,7 @@ mod tests { } #[tokio::test] - async fn response_inactivity_resets_on_progress_and_allows_progressing_uploads() { + async fn get_inactivity_resets_on_progress_and_put_has_no_header_deadline() { use tokio::io::AsyncReadExt; let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); let url = format!("http://{}", listener.local_addr().unwrap()); @@ -1254,7 +1219,7 @@ mod tests { let server = MockServer::start().await; Mock::given(method("PUT")) .and(body_bytes(b"xxxxx")) - .respond_with(ResponseTemplate::new(200)) + .respond_with(ResponseTemplate::new(200).set_delay(Duration::from_millis(300))) .expect(1) .mount(&server) .await; @@ -1265,17 +1230,15 @@ mod tests { writer.write_all(b"x").await.unwrap(); } }); - let (uploaded, complete) = oneshot::channel(); let error = Arc::new(Mutex::new(None)); - let body = upload_body(reader, 5, "input".into(), uploaded, Arc::clone(&error)); + let body = upload_body(reader, "input".into(), Arc::clone(&error)); storage_send( Client::new() .put(server.uri()) .header(reqwest::header::CONTENT_LENGTH, 5) .body(body), Some(Duration::from_millis(150)), - false, - complete, + true, error, ) .await From 7e90c32fec74ef5fea23f1cf56cedb297a60d930 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Sun, 15 Nov 2026 02:13:48 +0000 Subject: [PATCH 15/63] docs(volume): clarify timeout scope Signed-off-by: Aakash Saravanan --- include/databricks_kernel.h | 1 + napi/index.d.ts | 8 ++++---- napi/src/database.rs | 10 +++++----- src/c_abi/session.rs | 1 + src/config.rs | 1 + 5 files changed, 12 insertions(+), 9 deletions(-) diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h index a88286dc..b6e2ded7 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -375,6 +375,7 @@ KernelStatusCode kernel_session_config_set_sea_response_compression_enabled( /* Configure the total timeout for one HTTP request, from connection start * through response-body completion. A separate 30s connection timeout also * applies, so connection establishment is bounded by the shorter limit. + * Does not bound Volume storage requests or configure their inactivity limit. * `request_timeout_ms == 0` keeps the kernel default (120s). */ KernelStatusCode kernel_session_config_set_request_timeout(KernelSessionConfig* config, uint64_t request_timeout_ms); diff --git a/napi/index.d.ts b/napi/index.d.ts index 83d8e032..3ddac0f5 100644 --- a/napi/index.d.ts +++ b/napi/index.d.ts @@ -603,11 +603,11 @@ export interface ConnectionOptions { */ proxy?: ProxyInput /** - * Per-connection socket read timeout, in milliseconds. Caps how - * long a single HTTP round-trip may block waiting on the server - * before the request errors out. Maps onto the kernel + * Per-connection HTTP request deadline, in milliseconds. Caps a single + * request through response-body completion. Maps onto the kernel * [`HttpConfig::request_timeout`] (the internal reqwest - * `Client::timeout`). + * `Client::timeout`). Does not bound Volume storage requests or configure + * their inactivity limit. Storage connection setup has a separate timeout. * * Omitted ⇒ kernel default (120 000 ms / 120 s). Napi-rs * serialises `u32` as JS `number`; the largest representable value diff --git a/napi/src/database.rs b/napi/src/database.rs index 4a8fbe3f..3cb14629 100644 --- a/napi/src/database.rs +++ b/napi/src/database.rs @@ -453,11 +453,11 @@ pub struct ConnectionOptions { /// server) can now route a single connection through a proxy /// programmatically. pub proxy: Option, - /// Per-connection socket read timeout, in milliseconds. Caps how - /// long a single HTTP round-trip may block waiting on the server - /// before the request errors out. Maps onto the kernel + /// Per-connection HTTP request deadline, in milliseconds. Caps a single + /// request through response-body completion. Maps onto the kernel /// [`HttpConfig::request_timeout`] (the internal reqwest - /// `Client::timeout`). + /// `Client::timeout`). Does not bound Volume storage requests or configure + /// their inactivity limit. Storage connection setup has a separate timeout. /// /// Omitted ⇒ kernel default (120 000 ms / 120 s). Napi-rs /// serialises `u32` as JS `number`; the largest representable value @@ -653,7 +653,7 @@ fn build_http_config(options: &mut ConnectionOptions) -> HttpConfig { if let Some(s) = options.retry_overall_timeout_secs { http.overall_timeout = std::time::Duration::from_secs(u64::from(s)); } - // Per-connection socket read timeout. Maps onto the kernel's + // Per-connection request deadline. Maps onto the kernel's // `request_timeout` (the reqwest `Client::timeout`). Omitted ⇒ kernel // default (120 s). if let Some(ms) = options.socket_timeout_ms { diff --git a/src/c_abi/session.rs b/src/c_abi/session.rs index b3365f49..10978a55 100644 --- a/src/c_abi/session.rs +++ b/src/c_abi/session.rs @@ -629,6 +629,7 @@ pub unsafe extern "C" fn kernel_session_config_set_sea_response_compression_enab /// Configure the total timeout for one HTTP request, from connection start /// through response-body completion. A separate 30-second connection timeout /// also applies, so connection establishment is bounded by the shorter limit. +/// Does not bound Volume storage requests or configure their inactivity limit. /// `request_timeout_ms == 0` clears an earlier override and keeps the kernel /// default (120 seconds); a positive value overrides it. /// diff --git a/src/config.rs b/src/config.rs index 5c75e532..bf61d50d 100644 --- a/src/config.rs +++ b/src/config.rs @@ -755,6 +755,7 @@ pub struct HttpConfig { /// Total timeout for one HTTP request, from connection start through /// response-body completion. A separate 30-second connection timeout also /// applies, so connection establishment is bounded by the shorter limit. + /// Does not bound Volume storage requests; use `storage_read_timeout` for inactivity. pub request_timeout: Duration, /// Inactivity limit for Volume GET/REMOVE response headers and each response-body read. From f7fec30385c3040f436d3755cb8b316859192633 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Sun, 15 Nov 2026 05:35:00 +0000 Subject: [PATCH 16/63] fix(volume): authorize across independently resolved roots Signed-off-by: Aakash Saravanan --- src/volume.rs | 32 +++++++++++++++++++++++++++++++- 1 file changed, 31 insertions(+), 1 deletion(-) diff --git a/src/volume.rs b/src/volume.rs index 1ec3aabd..6ea25b02 100644 --- a/src/volume.rs +++ b/src/volume.rs @@ -545,12 +545,22 @@ fn allowed_path(requested: &str, roots: &[PathBuf]) -> Result { )); } let resolved = resolve_existing_parent(&path, requested)?; + let mut root_error = None; for root in roots { - let root = resolve_existing_parent(&root, requested)?; + let root = match resolve_existing_parent(&root, &root.to_string_lossy()) { + Ok(root) => root, + Err(error) => { + root_error.get_or_insert(error); + continue; + } + }; if within_root(&resolved, &root) { return Ok(resolved); } } + if let Some(error) = root_error { + return Err(error); + } Err(invalid( "Resolved local file path is outside the configured allowed roots", )) @@ -1327,6 +1337,26 @@ mod tests { std::slice::from_ref(&root) ) .is_err()); + let looping_root = dir.path().join("loop"); + symlink_dir(&looping_root, &looping_root).unwrap(); + for roots in [ + [looping_root.clone(), root.clone()], + [root.clone(), looping_root.clone()], + ] { + assert_eq!( + allowed_path(root.join("file").to_str().unwrap(), &roots).unwrap(), + root.join("file").canonicalize().unwrap() + ); + } + let error = allowed_path( + root.join("escape").to_str().unwrap(), + &[looping_root.clone(), root.clone()], + ) + .unwrap_err(); + assert_eq!( + error.local_error.unwrap().path, + looping_root.to_string_lossy() + ); assert!(allowed_path(root.join("../other/missing").to_str().unwrap(), &[root]).is_err()); } From 54182af8856e6e861b4c47846981208384956135 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Sun, 15 Nov 2026 07:56:17 +0000 Subject: [PATCH 17/63] fix(volume): replay owned upload bytes across redirects Signed-off-by: Aakash Saravanan --- src/volume.rs | 51 ++++++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 46 insertions(+), 5 deletions(-) diff --git a/src/volume.rs b/src/volume.rs index 6ea25b02..20e29558 100644 --- a/src/volume.rs +++ b/src/volume.rs @@ -242,11 +242,7 @@ impl VolumeState { if let Some(bytes) = input { request = request .header(reqwest::header::CONTENT_LENGTH, bytes.len()) - .body(upload_body( - std::io::Cursor::new(Arc::clone(bytes)), - instruction.local_file.clone(), - Arc::clone(&upload_error), - )); + .body(bytes.to_vec()); } let local_path = if instruction.operation == "REMOVE" || (instruction.operation == "PUT" && instruction.local_file == "__input_stream__") @@ -740,6 +736,51 @@ mod tests { assert!(!error.message.contains("hidden")); } + #[tokio::test] + async fn stream_put_replays_owned_bytes_on_redirect() { + for status in [307, 308] { + for payload in [b"".as_slice(), b"payload"] { + let server = MockServer::start().await; + Mock::given(method("PUT")) + .and(path("/object")) + .and(header("x-storage-token", "server-token")) + .and(body_bytes(payload)) + .respond_with( + ResponseTemplate::new(status) + .insert_header("location", format!("{}/redirected", server.uri())), + ) + .expect(1) + .mount(&server) + .await; + Mock::given(method("PUT")) + .and(path("/redirected")) + .and(header("x-storage-token", "server-token")) + .and(body_bytes(payload)) + .respond_with(ResponseTemplate::new(200)) + .expect(1) + .mount(&server) + .await; + let batch = instruction( + "PUT", + &format!("{}/object", server.uri()), + Path::new("__input_stream__"), + ); + assert_eq!( + transfer_state(0) + .complete( + &batch, + &Client::new(), + &VolumeOptions::default(), + Some(payload.to_vec()), + ) + .await + .unwrap(), + VolumeCompletion::Completed + ); + } + } + } + #[tokio::test] async fn transient_storage_statuses_replay_full_inputs_and_cache_completion() { use std::sync::atomic::{AtomicUsize, Ordering}; From 499ae02c0397fe814671eafc7ac30e21a37a5296 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Sun, 15 Nov 2026 08:19:37 +0000 Subject: [PATCH 18/63] fix(volume): keep result stream close local Signed-off-by: Aakash Saravanan --- src/c_abi/result.rs | 17 ++++++++--------- src/result_stream.rs | 1 - tests/v0_volume_wiremock.rs | 1 + 3 files changed, 9 insertions(+), 10 deletions(-) diff --git a/src/c_abi/result.rs b/src/c_abi/result.rs index 3e92da95..f5029efa 100644 --- a/src/c_abi/result.rs +++ b/src/c_abi/result.rs @@ -536,9 +536,6 @@ pub unsafe extern "C" fn kernel_result_stream_close( return store_invalid_arg("kernel_result_stream_close: stream must not be null"); } let inner = Box::from_raw(stream as *mut ResultStreamInner); - if let Some(volume) = &inner.volume { - volume.cancel(); - } drop(inner); KernelStatusCode::Success } @@ -794,17 +791,14 @@ mod tests { ) .unwrap(); let rt = tokio::runtime::Runtime::new().unwrap(); - for marked in [false, true] { + for (marked, cancel) in [(false, false), (true, false), (true, true)] { + let volume = crate::volume::VolumeState::new(Default::default(), None); let stream = rt.block_on(async { let mut stream = ResultStream::from_reader(Box::new(MockReader::new(vec![batch.clone()]))) .await .unwrap(); - stream.attach_volume( - marked, - crate::volume::VolumeState::new(Default::default(), None), - reqwest::Client::new(), - ); + stream.attach_volume(marked, Arc::clone(&volume), reqwest::Client::new()); into_raw_result_stream(schema.clone(), stream) }); let mut is_volume = !marked; @@ -813,6 +807,11 @@ mod tests { KernelStatusCode::Success ); assert_eq!(is_volume, marked); + if marked && !cancel { + unsafe { kernel_result_stream_close(stream) }; + assert!(volume.cached().is_none()); + continue; + } let roots = CString::new("[]").unwrap(); let mut status = -1; if marked { diff --git a/src/result_stream.rs b/src/result_stream.rs index 627c6d5c..c24983a5 100644 --- a/src/result_stream.rs +++ b/src/result_stream.rs @@ -969,7 +969,6 @@ impl ResultStream { /// `Drop` performs the same cleanup (including the metadata guard's /// close) if `close` was never called explicitly. pub fn close(self) { - self.cancel_volume(); // Drops `self` (and the wrapped reader / current batch / any // metadata close-guard). Background tasks owned by the reader // stop on `Drop`. diff --git a/tests/v0_volume_wiremock.rs b/tests/v0_volume_wiremock.rs index 15ada130..de6b9f3e 100644 --- a/tests/v0_volume_wiremock.rs +++ b/tests/v0_volume_wiremock.rs @@ -342,6 +342,7 @@ async fn owner_reader_and_repeated_materialization_share_one_completion() { stmt.spec().sql("operation"); let owner = stmt.submit().await.unwrap(); let reader = owner.reader().unwrap(); + reader.fetch_result().await.unwrap().close(); let mut first = reader.fetch_result().await.unwrap(); let mut second = owner.fetch_result().await.unwrap(); let options = VolumeOptions { From 67e1bffef3fa0a84e2f6038fb774b14b5a7a79e8 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Sun, 15 Nov 2026 23:38:28 +0000 Subject: [PATCH 19/63] fix(volume): replay file bodies across storage redirects Signed-off-by: Aakash Saravanan --- adbc/src/statement.rs | 32 ++-- src/client/http.rs | 3 +- src/volume.rs | 340 ++++++++++++++++++++++++++++++------------ 3 files changed, 270 insertions(+), 105 deletions(-) diff --git a/adbc/src/statement.rs b/adbc/src/statement.rs index 3b688c87..33fd2a79 100644 --- a/adbc/src/statement.rs +++ b/adbc/src/statement.rs @@ -1617,6 +1617,26 @@ mod tests { .open(), ) .unwrap(); + let mut statement = Statement::new( + session.statement(), + session.metadata(), + Arc::clone(&runtime), + Arc::new(CancellationRegistry::default()), + false, + ); + let key = OptionStatement::Other(STAGING_ALLOWED_PATHS_OPTION.into()); + assert_eq!( + statement.get_option_string(key.clone()).unwrap_err().status, + Status::NotFound + ); + for value in [OptionValue::Int(1), OptionValue::String("[1]".into())] { + assert_eq!( + statement.set_option(key.clone(), value).unwrap_err().status, + Status::InvalidArguments + ); + } + statement.set_option(key.clone(), "[]".into()).unwrap(); + assert_eq!(statement.get_option_string(key.clone()).unwrap(), "[]"); let mut transfers = 0; for mode in ["raw", "sync", "async", "await", "fetch", "bound", "update"] { let mut statement = Statement::new( @@ -1627,20 +1647,8 @@ mod tests { false, ); statement.set_sql_query("operation ?, ?").unwrap(); - let key = OptionStatement::Other(STAGING_ALLOWED_PATHS_OPTION.into()); - assert_eq!( - statement.get_option_string(key.clone()).unwrap_err().status, - Status::NotFound - ); - for value in [OptionValue::Int(1), OptionValue::String("[1]".into())] { - assert_eq!( - statement.set_option(key.clone(), value).unwrap_err().status, - Status::InvalidArguments - ); - } if mode != "raw" { statement.set_option(key.clone(), "[]".into()).unwrap(); - assert_eq!(statement.get_option_string(key).unwrap(), "[]"); } if mode == "async" { statement diff --git a/src/client/http.rs b/src/client/http.rs index 616d52be..92df7acf 100644 --- a/src/client/http.rs +++ b/src/client/http.rs @@ -747,7 +747,8 @@ impl DatabricksHttpClient { if let Some(timeout) = connect_timeout { config.connect_timeout = config.connect_timeout.min(timeout); } - Self::build_reqwest_client(&config, reqwest::redirect::Policy::default(), None) + // Volume completion reopens file bodies and applies one redirect budget across all hops. + Self::build_reqwest_client(&config, reqwest::redirect::Policy::none(), None) } /// Get the authorization header value. diff --git a/src/volume.rs b/src/volume.rs index 20e29558..a6ee03e0 100644 --- a/src/volume.rs +++ b/src/volume.rs @@ -238,7 +238,6 @@ impl VolumeState { let mut request = client .request(method, &instruction.url) .headers(instruction.headers.clone()); - let upload_error = Arc::new(Mutex::new(None)); if let Some(bytes) = input { request = request .header(reqwest::header::CONTENT_LENGTH, bytes.len()) @@ -249,29 +248,10 @@ impl VolumeState { { None } else { - let path = allowed_path(&instruction.local_file, &options.allowed_paths)?; - if instruction.operation == "PUT" { - let mut file = std::fs::File::open(&path) - .map_err(|e| local_error(e, &instruction.local_file))?; - let metadata = file - .metadata() - .map_err(|e| local_error(e, &instruction.local_file))?; - if metadata.is_dir() { - // Reading the opened directory retains the platform's filesystem cause. - let error = std::io::Read::read(&mut file, &mut [0]) - .err() - .unwrap_or_else(|| std::io::ErrorKind::IsADirectory.into()); - return Err(local_error(error, &instruction.local_file)); - } - request = request - .header(reqwest::header::CONTENT_LENGTH, metadata.len()) - .body(upload_body( - tokio::fs::File::from_std(file), - instruction.local_file.clone(), - Arc::clone(&upload_error), - )); - } - Some(path) + Some(allowed_path( + &instruction.local_file, + &options.allowed_paths, + )?) }; let mut destination = if instruction.operation == "GET" { let path = local_path.as_ref().expect("GET path was checked"); @@ -315,13 +295,105 @@ impl VolumeState { }; let retry_timeout = instruction.operation != "PUT"; - let mut response = storage_send( - request, - self.read_timeout, - instruction.operation == "PUT", - upload_error, - ) - .await?; + // File bodies must be reopened for redirects; reqwest can only clone owned bytes. + let mut request = request.build().map_err(storage_error)?; + let mut redirects = 0; + let mut response = loop { + let mut next = reqwest::RequestBuilder::from_parts( + client.clone(), + request.try_clone().expect("replayable request template"), + ); + let upload_error = Arc::new(Mutex::new(None)); + if request.method() == Method::PUT && input.is_none() { + let path = local_path.as_ref().expect("PUT path was checked"); + let mut file = std::fs::File::open(path) + .map_err(|e| local_error(e, &instruction.local_file))?; + let metadata = file + .metadata() + .map_err(|e| local_error(e, &instruction.local_file))?; + if metadata.is_dir() { + // Reading the opened directory retains the platform's filesystem cause. + let error = std::io::Read::read(&mut file, &mut [0]) + .err() + .unwrap_or_else(|| std::io::ErrorKind::IsADirectory.into()); + return Err(local_error(error, &instruction.local_file)); + } + next = next + .header(reqwest::header::CONTENT_LENGTH, metadata.len()) + .body(upload_body( + tokio::fs::File::from_std(file), + instruction.local_file.clone(), + Arc::clone(&upload_error), + )); + } + let response = storage_send( + next, + self.read_timeout, + request.method() == Method::PUT, + upload_error, + ) + .await?; + if !matches!(response.status().as_u16(), 301 | 302 | 303 | 307 | 308) { + break response; + } + let Some(url) = response + .headers() + .get(reqwest::header::LOCATION) + .and_then(|location| location.to_str().ok()) + .and_then(|location| response.url().join(location).ok()) + else { + break response; + }; + if redirects == 10 || !matches!(url.scheme(), "http" | "https") { + return Err(Error::network_error() + .with_error_code("VOLUME_STORAGE_NETWORK_ERROR") + .with_retryable(false) + .message(if redirects == 10 { + "Volume storage redirect limit exceeded" + } else { + "Volume storage redirect URL must use HTTP or HTTPS" + })); + } + redirects += 1; + let previous = response.url(); + if url.host_str() != previous.host_str() + || url.port_or_known_default() != previous.port_or_known_default() + { + for name in [ + "authorization", + "cookie", + "cookie2", + "proxy-authorization", + "www-authenticate", + ] { + request.headers_mut().remove(name); + } + } + if !(previous.scheme() == "https" && url.scheme() == "http") { + let mut referer = previous.clone(); + let _ = referer.set_username(""); + let _ = referer.set_password(None); + referer.set_fragment(None); + if let Ok(value) = referer.as_str().parse() { + request + .headers_mut() + .insert(reqwest::header::REFERER, value); + } + } + if response.status() == reqwest::StatusCode::SEE_OTHER { + *request.method_mut() = Method::GET; + *request.body_mut() = None; + for name in [ + "content-type", + "content-length", + "content-encoding", + "transfer-encoding", + ] { + request.headers_mut().remove(name); + } + } + *request.url_mut() = url; + }; let status = response.status(); if !status.is_success() && !(instruction.operation == "REMOVE" @@ -737,48 +809,152 @@ mod tests { } #[tokio::test] - async fn stream_put_replays_owned_bytes_on_redirect() { - for status in [307, 308] { - for payload in [b"".as_slice(), b"payload"] { - let server = MockServer::start().await; - Mock::given(method("PUT")) - .and(path("/object")) - .and(header("x-storage-token", "server-token")) - .and(body_bytes(payload)) - .respond_with( - ResponseTemplate::new(status) - .insert_header("location", format!("{}/redirected", server.uri())), - ) - .expect(1) - .mount(&server) - .await; + async fn put_replays_file_and_owned_bytes_on_redirect() { + let dir = tempfile::tempdir().unwrap(); + let source = dir.path().join("source"); + for (status, stream, payload) in [ + (200, false, vec![42; 128 * 1024]), + (307, false, vec![42; 128 * 1024]), + (308, false, vec![42; 128 * 1024]), + (307, true, vec![]), + (308, true, vec![]), + (307, true, b"payload".to_vec()), + (308, true, b"payload".to_vec()), + ] { + let server = MockServer::start().await; + Mock::given(method("PUT")) + .and(path("/object")) + .and(header("x-storage-token", "server-token")) + .and(body_bytes(payload.clone())) + .respond_with( + ResponseTemplate::new(status).insert_header("location", "/redirected"), + ) + .expect(1) + .mount(&server) + .await; + if status != 200 { Mock::given(method("PUT")) .and(path("/redirected")) .and(header("x-storage-token", "server-token")) - .and(body_bytes(payload)) + .and(body_bytes(payload.clone())) .respond_with(ResponseTemplate::new(200)) .expect(1) .mount(&server) .await; - let batch = instruction( - "PUT", - &format!("{}/object", server.uri()), - Path::new("__input_stream__"), - ); + } + std::fs::write(&source, &payload).unwrap(); + let batch = instruction( + "PUT", + &format!("{}/object", server.uri()), + if stream { + Path::new("__input_stream__") + } else { + &source + }, + ); + assert_eq!( + transfer_state(0) + .complete( + &batch, + &Client::builder() + .redirect(reqwest::redirect::Policy::none()) + .build() + .unwrap(), + &options(dir.path()), + stream.then_some(payload), + ) + .await + .unwrap(), + VolumeCompletion::Completed + ); + assert!(server + .received_requests() + .await + .unwrap() + .iter() + .all(|request| !request.headers.contains_key("authorization"))); + } + } + + #[tokio::test] + async fn redirects_strip_cross_host_credentials_and_share_a_hop_limit() { + use std::sync::atomic::{AtomicUsize, Ordering}; + let server = MockServer::start().await; + let redirected = MockServer::start().await; + let dir = tempfile::tempdir().unwrap(); + let source = dir.path().join("source"); + std::fs::write(&source, b"payload").unwrap(); + Mock::given(method("PUT")) + .and(body_bytes(b"payload")) + .and(header("authorization", "storage-secret")) + .respond_with(ResponseTemplate::new(307).insert_header("location", redirected.uri())) + .expect(1) + .mount(&server) + .await; + let count = Arc::new(AtomicUsize::new(0)); + let attempts = Arc::clone(&count); + Mock::given(header("x-storage-token", "server-token")) + .respond_with(move |request: &wiremock::Request| { + for name in [ + "authorization", + "cookie", + "cookie2", + "proxy-authorization", + "www-authenticate", + ] { + assert!(!request.headers.contains_key(name)); + } + let first = attempts.fetch_add(1, Ordering::SeqCst) == 0; + assert_eq!(request.method.as_str(), if first { "PUT" } else { "GET" }); assert_eq!( - transfer_state(0) - .complete( - &batch, - &Client::new(), - &VolumeOptions::default(), - Some(payload.to_vec()), - ) - .await - .unwrap(), - VolumeCompletion::Completed + request.body, + if first { b"payload".as_slice() } else { b"" } ); - } + if !first { + assert!(!request.headers.contains_key("content-type")); + } + ResponseTemplate::new(if first { 303 } else { 308 }).insert_header("location", "/") + }) + .expect(10) + .mount(&redirected) + .await; + let batch = instruction("PUT", &server.uri(), &source); + let mut instruction = Instruction::decode(&batch).unwrap(); + for name in [ + "authorization", + "cookie", + "cookie2", + "proxy-authorization", + "www-authenticate", + ] { + instruction.headers.insert( + reqwest::header::HeaderName::from_static(name), + "storage-secret".parse().unwrap(), + ); } + instruction.headers.insert( + reqwest::header::CONTENT_TYPE, + "application/octet-stream".parse().unwrap(), + ); + let error = transfer_state(2) + .transfer( + instruction, + &Client::builder() + .redirect(reqwest::redirect::Policy::none()) + .build() + .unwrap(), + &options(dir.path()), + None, + ) + .await + .unwrap_err(); + assert_eq!( + error.error_code.as_deref(), + Some("VOLUME_STORAGE_NETWORK_ERROR") + ); + assert!(!error.retryable); + assert_eq!(count.load(Ordering::SeqCst), 10); + assert!(!error.message.contains("storage-secret")); } #[tokio::test] @@ -790,6 +966,12 @@ mod tests { ("GET", false), ("REMOVE", false), ] { + let statuses: &[u16] = if operation == "PUT" && !stream { + &[408, 429, 500, 502, 503, 504] + } else { + &[503] + }; + let requests = statuses.len() as u64 + 1; let server = MockServer::start().await; let attempts = Arc::new(AtomicUsize::new(0)); let count = Arc::clone(&attempts); @@ -804,15 +986,13 @@ mod tests { if operation == "PUT" { assert_eq!(request.body, b"payload"); } - if let Some(status) = - [408, 429, 500, 502, 503, 504].get(count.fetch_add(1, Ordering::SeqCst)) - { + if let Some(status) = statuses.get(count.fetch_add(1, Ordering::SeqCst)) { ResponseTemplate::new(*status).insert_header("retry-after", "0") } else { ResponseTemplate::new(200).set_body_bytes(b"payload") } }) - .expect(7) + .expect(requests) .mount(&server) .await; let dir = tempfile::tempdir().unwrap(); @@ -854,7 +1034,7 @@ mod tests { .unwrap(), VolumeCompletion::Completed ); - assert_eq!(attempts.load(Ordering::SeqCst), 7); + assert_eq!(attempts.load(Ordering::SeqCst), requests as usize); assert_eq!(std::fs::read(file).unwrap(), b"payload"); assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 1); } @@ -988,30 +1168,6 @@ mod tests { ); } - #[tokio::test] - async fn file_put_preserves_streamed_body_and_server_headers() { - let server = MockServer::start().await; - let dir = tempfile::tempdir().unwrap(); - let source = dir.path().join("source"); - let bytes = vec![42; 128 * 1024]; - std::fs::write(&source, &bytes).unwrap(); - Mock::given(method("PUT")) - .and(body_bytes(bytes)) - .and(header("x-storage-token", "server-token")) - .respond_with(ResponseTemplate::new(200)) - .expect(1) - .mount(&server) - .await; - let batch = instruction("PUT", &server.uri(), &source); - transfer_state(0) - .complete(&batch, &Client::new(), &options(dir.path()), None) - .await - .unwrap(); - assert!(!server.received_requests().await.unwrap()[0] - .headers - .contains_key("authorization")); - } - #[tokio::test] async fn get_replaces_destination_and_caches_error_without_replay() { let server = MockServer::start().await; From de55bbc321940d51b3abfa385ed99da281df1567 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Sun, 15 Nov 2026 23:41:57 +0000 Subject: [PATCH 20/63] fix(volume): clear redirect referer on HTTPS downgrade Signed-off-by: Aakash Saravanan --- src/volume.rs | 64 ++++++++++++++++++++++++++++++++++++--------------- 1 file changed, 46 insertions(+), 18 deletions(-) diff --git a/src/volume.rs b/src/volume.rs index a6ee03e0..91509460 100644 --- a/src/volume.rs +++ b/src/volume.rs @@ -369,7 +369,9 @@ impl VolumeState { request.headers_mut().remove(name); } } - if !(previous.scheme() == "https" && url.scheme() == "http") { + if previous.scheme() == "https" && url.scheme() == "http" { + request.headers_mut().remove(reqwest::header::REFERER); + } else { let mut referer = previous.clone(); let _ = referer.set_username(""); let _ = referer.set_password(None); @@ -809,23 +811,34 @@ mod tests { } #[tokio::test] - async fn put_replays_file_and_owned_bytes_on_redirect() { + async fn transfers_follow_redirects_and_replay_file_and_owned_inputs() { let dir = tempfile::tempdir().unwrap(); let source = dir.path().join("source"); - for (status, stream, payload) in [ - (200, false, vec![42; 128 * 1024]), - (307, false, vec![42; 128 * 1024]), - (308, false, vec![42; 128 * 1024]), - (307, true, vec![]), - (308, true, vec![]), - (307, true, b"payload".to_vec()), - (308, true, b"payload".to_vec()), + for (operation, status, stream, payload) in [ + ("PUT", 200, false, vec![42; 128 * 1024]), + ("PUT", 307, false, vec![42; 128 * 1024]), + ("PUT", 308, false, vec![42; 128 * 1024]), + ("PUT", 307, true, vec![]), + ("PUT", 308, true, vec![]), + ("PUT", 307, true, b"payload".to_vec()), + ("PUT", 308, true, b"payload".to_vec()), + ("GET", 307, false, b"downloaded".to_vec()), + ("REMOVE", 302, false, vec![]), ] { let server = MockServer::start().await; - Mock::given(method("PUT")) + let verb = if operation == "REMOVE" { + "DELETE" + } else { + operation + }; + Mock::given(method(verb)) .and(path("/object")) .and(header("x-storage-token", "server-token")) - .and(body_bytes(payload.clone())) + .and(body_bytes(if operation == "PUT" { + payload.clone() + } else { + vec![] + })) .respond_with( ResponseTemplate::new(status).insert_header("location", "/redirected"), ) @@ -833,18 +846,30 @@ mod tests { .mount(&server) .await; if status != 200 { - Mock::given(method("PUT")) + Mock::given(method(verb)) .and(path("/redirected")) .and(header("x-storage-token", "server-token")) - .and(body_bytes(payload.clone())) - .respond_with(ResponseTemplate::new(200)) + .and(body_bytes(if operation == "PUT" { + payload.clone() + } else { + vec![] + })) + .respond_with(ResponseTemplate::new(200).set_body_bytes(payload.clone())) .expect(1) .mount(&server) .await; } - std::fs::write(&source, &payload).unwrap(); + std::fs::write( + &source, + if operation == "GET" { + b"old".as_slice() + } else { + &payload + }, + ) + .unwrap(); let batch = instruction( - "PUT", + operation, &format!("{}/object", server.uri()), if stream { Path::new("__input_stream__") @@ -861,12 +886,15 @@ mod tests { .build() .unwrap(), &options(dir.path()), - stream.then_some(payload), + stream.then(|| payload.clone()), ) .await .unwrap(), VolumeCompletion::Completed ); + if operation == "GET" { + assert_eq!(std::fs::read(&source).unwrap(), payload); + } assert!(server .received_requests() .await From 9500d2d3fcf02bbe952eee323dd205660e07eb59 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Mon, 16 Nov 2026 00:48:48 +0000 Subject: [PATCH 21/63] fix(volume): preserve write-only download destinations Signed-off-by: Aakash Saravanan --- src/volume.rs | 32 +++++++++++++++++++++++++++++++- 1 file changed, 31 insertions(+), 1 deletion(-) diff --git a/src/volume.rs b/src/volume.rs index 91509460..3a7adb17 100644 --- a/src/volume.rs +++ b/src/volume.rs @@ -286,7 +286,8 @@ impl VolumeState { .map_err(|e| local_error(e, &instruction.local_file))?; } let writer = tokio::fs::File::from_std( - temp.reopen() + temp.as_file() + .try_clone() .map_err(|e| local_error(e, &instruction.local_file))?, ); Some((temp, writer)) @@ -725,6 +726,8 @@ mod tests { use arrow_array::builder::{MapBuilder, StringBuilder}; use arrow_array::{ArrayRef, RecordBatch}; use arrow_schema::{DataType, Field, Schema}; + #[cfg(unix)] + use std::os::unix::fs::PermissionsExt; use std::time::Duration; use wiremock::matchers::{body_bytes, header, method, path}; use wiremock::{Mock, MockServer, ResponseTemplate}; @@ -1214,6 +1217,8 @@ mod tests { let dir = tempfile::tempdir().unwrap(); let dest = dir.path().join("download"); std::fs::write(&dest, b"old bytes").unwrap(); + #[cfg(unix)] + std::fs::set_permissions(&dest, std::fs::Permissions::from_mode(0o200)).unwrap(); let batch = instruction("GET", &format!("{}/ok", server.uri()), &dest); let completed = transfer_state(0); completed @@ -1228,6 +1233,14 @@ mod tests { .unwrap(), VolumeCompletion::Completed ); + #[cfg(unix)] + { + assert_eq!( + std::fs::metadata(&dest).unwrap().permissions().mode() & 0o777, + 0o200 + ); + std::fs::set_permissions(&dest, std::fs::Permissions::from_mode(0o600)).unwrap(); + } assert_eq!(std::fs::read(&dest).unwrap(), b"new bytes"); let state = transfer_state(0); let batch = instruction( @@ -1251,6 +1264,23 @@ mod tests { Some(403) ); assert_eq!(std::fs::read(&dest).unwrap(), b"new bytes"); + #[cfg(unix)] + { + std::fs::set_permissions(&dest, std::fs::Permissions::from_mode(0o400)).unwrap(); + if std::fs::OpenOptions::new().write(true).open(&dest).is_err() { + let batch = instruction("GET", &format!("{}/ok", server.uri()), &dest); + let error = transfer_state(0) + .complete(&batch, &Client::new(), &options(dir.path()), None) + .await + .unwrap_err(); + let local = error.local_error.unwrap(); + assert_eq!(local.kind, "PermissionDenied"); + assert_eq!(local.path, dest.to_string_lossy()); + assert_eq!(std::fs::read(&dest).unwrap(), b"new bytes"); + assert_eq!(server.received_requests().await.unwrap().len(), 2); + } + std::fs::set_permissions(&dest, std::fs::Permissions::from_mode(0o600)).unwrap(); + } assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 1); } From f81eb196da57652639c3aaea026ada5ab05e0e9f Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Mon, 16 Nov 2026 01:04:53 +0000 Subject: [PATCH 22/63] fix(volume): omit signed queries from redirect referers Signed-off-by: Aakash Saravanan --- src/volume.rs | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/src/volume.rs b/src/volume.rs index 3a7adb17..35dcbd2f 100644 --- a/src/volume.rs +++ b/src/volume.rs @@ -376,6 +376,7 @@ impl VolumeState { let mut referer = previous.clone(); let _ = referer.set_username(""); let _ = referer.set_password(None); + referer.set_query(None); referer.set_fragment(None); if let Ok(value) = referer.as_str().parse() { request @@ -918,7 +919,10 @@ mod tests { Mock::given(method("PUT")) .and(body_bytes(b"payload")) .and(header("authorization", "storage-secret")) - .respond_with(ResponseTemplate::new(307).insert_header("location", redirected.uri())) + .respond_with(ResponseTemplate::new(307).insert_header( + "location", + format!("{}/?signature=redirect-secret", redirected.uri()), + )) .expect(1) .mount(&server) .await; @@ -935,6 +939,10 @@ mod tests { ] { assert!(!request.headers.contains_key(name)); } + let referer = + reqwest::Url::parse(request.headers.get("referer").unwrap().to_str().unwrap()) + .unwrap(); + assert!(referer.query().is_none()); let first = attempts.fetch_add(1, Ordering::SeqCst) == 0; assert_eq!(request.method.as_str(), if first { "PUT" } else { "GET" }); assert_eq!( @@ -949,7 +957,11 @@ mod tests { .expect(10) .mount(&redirected) .await; - let batch = instruction("PUT", &server.uri(), &source); + let batch = instruction( + "PUT", + &format!("{}/?signature=source-secret", server.uri()), + &source, + ); let mut instruction = Instruction::decode(&batch).unwrap(); for name in [ "authorization", From 614d2b929f3cdda218cc6d82a0f0a28d38fb1be6 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Mon, 16 Nov 2026 06:54:00 +0000 Subject: [PATCH 23/63] Clarify Volume completion ordering Signed-off-by: Aakash Saravanan --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 735ec0bf..f8dbfa33 100644 --- a/README.md +++ b/README.md @@ -71,8 +71,9 @@ and security vulnerabilities should be reported according to `ResultStream::complete_volume_operation` completes server-marked SQL PUT, GET, and REMOVE instructions. Pass `VolumeOptions` with the local roots authorized for PUT and GET. Completion preserves the instruction rows; callers that want the raw -result can omit completion. The PyO3 `ExecutedStatement` and `ResultStream` -classes expose `is_volume_operation` and `complete_volume_operation`. +result can omit completion. Complete the operation before reading its instruction +rows. The PyO3 `ExecutedStatement` and `ResultStream` classes expose +`is_volume_operation` and `complete_volume_operation`. A PUT instruction with `localFile == "__input_stream__"` returns `NeedsInputStream` until owned input bytes are supplied. An empty byte buffer is a From 91b8df0c09db67216778eb5c55d3188d695fce5f Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Mon, 16 Nov 2026 19:28:21 +0000 Subject: [PATCH 24/63] Release session resources when sync NAPI statements close Signed-off-by: Aakash Saravanan --- napi/src/async_statement.rs | 35 ++++++++++++++++++++++++++++++----- napi/src/statement.rs | 37 ++++++++++++++++++++++++++----------- src/volume.rs | 13 ++----------- 3 files changed, 58 insertions(+), 27 deletions(-) diff --git a/napi/src/async_statement.rs b/napi/src/async_statement.rs index 12d9f570..e523c9fb 100644 --- a/napi/src/async_statement.rs +++ b/napi/src/async_statement.rs @@ -712,7 +712,7 @@ mod tests { /// their statements are closed, even while JS still references the closed /// handles. Otherwise the next session on the host reuses it and ignores /// its own telemetry settings. - async fn next_session_gets_its_own_telemetry_client(fetch_result: bool) { + async fn next_session_gets_its_own_telemetry_client(fetch_result: bool, sync_statement: bool) { let server = lease_server().await; // Batch size 1: this client exports every event at once. let first = telemetry_connection(&server, 1, Duration::from_millis(100)).await; @@ -726,6 +726,16 @@ mod tests { None }; statement.close().await.expect("close statement"); + let sync_statement = if sync_statement { + let statement = first + .execute_statement("SELECT 1 AS n".into(), None) + .await + .expect("execute"); + statement.close().await.expect("close sync statement"); + Some(statement) + } else { + None + }; first.close().await.expect("close first session"); let second = telemetry_connection(&server, 1_000, Duration::from_secs(300)).await; @@ -750,17 +760,18 @@ mod tests { assert!(err.reason.contains("AsyncResultHandle already closed")); } // Dropped only now, as JS GC would. - drop((statement, result)); + drop((statement, result, sync_statement)); } #[tokio::test] async fn close_releases_session_held_by_canceller() { - next_session_gets_its_own_telemetry_client(false).await; + next_session_gets_its_own_telemetry_client(false, false).await; + next_session_gets_its_own_telemetry_client(false, true).await; } #[tokio::test] async fn close_releases_session_held_by_result_handles() { - next_session_gets_its_own_telemetry_client(true).await; + next_session_gets_its_own_telemetry_client(true, false).await; } #[tokio::test] @@ -794,7 +805,7 @@ mod tests { .with_priority(1) .mount(&server) .await; - let connection = telemetry_connection(&server, 1_000, Duration::from_secs(300)).await; + let connection = telemetry_connection(&server, 1, Duration::from_millis(100)).await; let statement = connection .submit_statement("SELECT 1 AS n".into(), None) .await @@ -806,6 +817,20 @@ mod tests { .expect_err("the close RPC must fail"); assert!(statement.canceller.lock().unwrap().is_none()); assert!(result.inner.lock().await.is_none()); + let sync_statement = connection + .execute_statement("SELECT 1 AS n".into(), None) + .await + .expect("execute"); + sync_statement + .close() + .await + .expect_err("the close RPC must fail"); + sync_statement.close().await.expect("close is terminal"); connection.close().await.expect("close session"); + let second = telemetry_connection(&server, 1_000, Duration::from_secs(300)).await; + tokio::time::sleep(Duration::from_millis(500)).await; + assert_eq!(exports_for(&server, SECOND_SESSION).await, 0); + second.close().await.expect("close second session"); + drop(sync_statement); } } diff --git a/napi/src/statement.rs b/napi/src/statement.rs index c2bd9805..c8056a9f 100644 --- a/napi/src/statement.rs +++ b/napi/src/statement.rs @@ -30,7 +30,7 @@ //! server logs which key on the same id. use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::Arc; +use std::sync::{Arc, Mutex as StdMutex, PoisonError}; use tokio::sync::Mutex; use arrow_schema::SchemaRef; @@ -132,7 +132,7 @@ pub struct Statement { /// queries driven through `Metadata`). statement_id: String, is_volume_operation: bool, - canceller: Option, + canceller: StdMutex>, /// Set to `true` when `fetchNextBatch` observes the natural end of /// the stream (`None`). `cancel()` short-circuits to `Ok(())` when /// this is set, matching the JDBC `Statement.cancel()` no-op-after- @@ -156,7 +156,7 @@ impl Statement { let schema = executed.schema(); let statement_id = executed.statement_id().to_owned(); let is_volume_operation = executed.result_stream().is_volume_operation(); - let canceller = Some(parent.canceller()); + let canceller = StdMutex::new(Some(parent.canceller())); Self { inner: Arc::new(Mutex::new(Some(AnyInner::Executed(Box::new( StatementInner { @@ -189,7 +189,7 @@ impl Statement { schema, statement_id: String::new(), is_volume_operation: false, - canceller: None, + canceller: StdMutex::new(None), finished: Arc::new(AtomicBool::new(false)), } } @@ -458,7 +458,12 @@ impl Statement { /// has been explicitly `close()`d. #[napi] pub async fn cancel(&self) -> napi::Result<()> { - if let Some(canceller) = &self.canceller { + if let Some(canceller) = self + .canceller + .lock() + .unwrap_or_else(PoisonError::into_inner) + .as_ref() + { canceller.cancel_volume_operation(); } // Idempotent against natural completion. @@ -520,7 +525,12 @@ impl Statement { /// resource to release). #[napi] pub async fn close(&self) -> napi::Result<()> { - if let Some(canceller) = &self.canceller { + if let Some(canceller) = self + .canceller + .lock() + .unwrap_or_else(PoisonError::into_inner) + .take() + { canceller.cancel_volume_operation(); } let inner = Arc::clone(&self.inner); @@ -549,7 +559,12 @@ impl Statement { impl Drop for Statement { fn drop(&mut self) { - if let Some(canceller) = &self.canceller { + if let Some(canceller) = self + .canceller + .get_mut() + .unwrap_or_else(PoisonError::into_inner) + .take() + { canceller.cancel_volume_operation(); } // Best-effort cleanup: schedule a drop of the kernel handle on @@ -841,7 +856,7 @@ mod tests { inner: Arc::new(Mutex::new(None)), // "already closed" schema: make_schema(), is_volume_operation: false, - canceller: None, + canceller: StdMutex::new(None), statement_id: "stmt-survives-close".to_owned(), finished: Arc::new(AtomicBool::new(false)), }; @@ -858,7 +873,7 @@ mod tests { inner: Arc::new(Mutex::new(None)), schema: schema.clone(), is_volume_operation: false, - canceller: None, + canceller: StdMutex::new(None), statement_id: "x".to_owned(), finished: Arc::new(AtomicBool::new(false)), }; @@ -879,7 +894,7 @@ mod tests { inner: Arc::new(Mutex::new(None)), schema: make_schema(), is_volume_operation: false, - canceller: None, + canceller: StdMutex::new(None), statement_id: "x".to_owned(), finished: Arc::new(AtomicBool::new(false)), }; @@ -897,7 +912,7 @@ mod tests { inner: Arc::new(Mutex::new(None)), // closed schema: make_schema(), is_volume_operation: false, - canceller: None, + canceller: StdMutex::new(None), statement_id: "x".to_owned(), finished: Arc::new(AtomicBool::new(true)), }; diff --git a/src/volume.rs b/src/volume.rs index 35dcbd2f..535f8783 100644 --- a/src/volume.rs +++ b/src/volume.rs @@ -1301,22 +1301,13 @@ mod tests { let server = MockServer::start().await; Mock::given(method("DELETE")) .respond_with(ResponseTemplate::new(404)) - .expect(2) + .expect(1) .mount(&server) .await; let batch = instruction("REMOVE", &server.uri(), Path::new("")); - let strict = VolumeOptions::default(); - assert_eq!( - transfer_state(0) - .complete(&batch, &Client::new(), &strict, None) - .await - .unwrap_err() - .http_status, - Some(404) - ); let permissive = VolumeOptions { remove_not_found_is_success: true, - ..strict + ..VolumeOptions::default() }; assert_eq!( transfer_state(0) From b23abde9dec892d4a8204a41e2a853c5e22598ff Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Mon, 16 Nov 2026 21:16:27 +0000 Subject: [PATCH 25/63] fix(napi): release busy results after async owner close Signed-off-by: Aakash Saravanan --- napi/index.d.ts | 5 ++--- napi/src/async_statement.rs | 34 ++++++++++++++++++++++++++-------- 2 files changed, 28 insertions(+), 11 deletions(-) diff --git a/napi/index.d.ts b/napi/index.d.ts index 3ddac0f5..9037702f 100644 --- a/napi/index.d.ts +++ b/napi/index.d.ts @@ -854,9 +854,8 @@ export declare class AsyncStatement { * re-attempting the wire call. The kernel's own `Drop` * fire-and-forget retry runs once in the background. * - * Also invalidates the handles `awaitResult()` returned: their - * `fetchNextBatch()` then rejects with `InvalidStatementHandle`, - * unless a fetch was in progress when `close()` ran. + * Also invalidates the handles `awaitResult()` returned. An operation + * already in flight may finish before its handle is cleared. */ close(): Promise } diff --git a/napi/src/async_statement.rs b/napi/src/async_statement.rs index e523c9fb..37100eee 100644 --- a/napi/src/async_statement.rs +++ b/napi/src/async_statement.rs @@ -377,9 +377,8 @@ impl AsyncStatement { /// re-attempting the wire call. The kernel's own `Drop` /// fire-and-forget retry runs once in the background. /// - /// Also invalidates the handles `awaitResult()` returned: their - /// `fetchNextBatch()` then rejects with `InvalidStatementHandle`, - /// unless a fetch was in progress when `close()` ran. + /// Also invalidates the handles `awaitResult()` returned. An operation + /// already in flight may finish before its handle is cleared. #[napi] pub async fn close(&self) -> napi::Result<()> { self.canceller.cancel_volume_operation(); @@ -404,7 +403,7 @@ impl AsyncStatement { .map_err(napi_err_from_kernel); // Release what holds the session, so JS references to closed // handles don't keep it (and the host's telemetry client) alive. - // A stream held by an in-flight fetch is left; close doesn't wait. + // Queue busy slots so close need not wait for an in-flight operation. canceller .lock() .unwrap_or_else(PoisonError::into_inner) @@ -414,6 +413,11 @@ impl AsyncStatement { for slot in slots.iter().filter_map(Weak::upgrade) { if let Ok(mut stream) = slot.try_lock() { stream.take(); + } else { + let slot = Arc::clone(&slot); + tokio::spawn(async move { + slot.lock().await.take(); + }); } } outcome @@ -460,7 +464,7 @@ impl Drop for AsyncStatement { /// post-close contract. #[napi] pub struct AsyncResultHandle { - /// Emptied by the parent's `close()`, unless a fetch holds it then. + /// Emptied after parent close once any in-flight operation releases it. inner: Arc, schema: SchemaRef, statement_id: String, @@ -775,15 +779,15 @@ mod tests { } #[tokio::test] - async fn close_does_not_wait_for_an_in_flight_fetch() { + async fn close_releases_session_after_an_in_flight_result() { let server = lease_server().await; - let connection = telemetry_connection(&server, 1_000, Duration::from_secs(300)).await; + let connection = telemetry_connection(&server, 1, Duration::from_millis(100)).await; let statement = connection .submit_statement("SELECT 1 AS n".into(), None) .await .expect("submit"); let result = statement.await_result().await.expect("await result"); - // Hold the stream the way an in-flight `fetchNextBatch()` does. + // Both fetching and Volume completion hold the result slot throughout I/O. let in_flight = result.inner.lock().await; tokio::time::timeout(Duration::from_secs(5), statement.close()) .await @@ -791,6 +795,20 @@ mod tests { .expect("close statement"); drop(in_flight); connection.close().await.expect("close session"); + tokio::time::timeout(Duration::from_secs(5), async { + while result.inner.lock().await.is_some() { + tokio::task::yield_now().await; + } + }) + .await + .expect("closed result must release its session after the operation finishes"); + + let second = telemetry_connection(&server, 1_000, Duration::from_secs(300)).await; + tokio::time::sleep(Duration::from_millis(500)).await; + assert_eq!(exports_for(&server, SECOND_SESSION).await, 0); + second.close().await.expect("close second session"); + assert!(exports_for(&server, SECOND_SESSION).await > 0); + drop((statement, result)); } #[tokio::test] From ff89c478c3282069a82a4618d228eb01ced1df99 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Mon, 16 Nov 2026 21:51:05 +0000 Subject: [PATCH 26/63] fix(volume): record instruction reader failures in telemetry Signed-off-by: Aakash Saravanan --- src/result_stream.rs | 6 +- src/telemetry/statement.rs | 119 +++++++++++++++++++++++++------------ src/volume.rs | 6 +- 3 files changed, 88 insertions(+), 43 deletions(-) diff --git a/src/result_stream.rs b/src/result_stream.rs index c24983a5..705efb02 100644 --- a/src/result_stream.rs +++ b/src/result_stream.rs @@ -694,7 +694,11 @@ impl ResultStream { .expect("Volume completion retains its reader") .next_batch() .await - .map_err(|error| state.fail(error))? + .map_err(|error| { + let error = state.fail(error); + self.finalize_telemetry(Some(&error)); + error + })? { Some(batch) if batch.num_rows() != 0 => { return Err(state.fail( diff --git a/src/telemetry/statement.rs b/src/telemetry/statement.rs index 42505bc7..171926ae 100644 --- a/src/telemetry/statement.rs +++ b/src/telemetry/statement.rs @@ -292,12 +292,12 @@ fn duration_millis(duration: Duration) -> i64 { mod tests { use super::*; use crate::kernel_error::ErrorCode; - use crate::reader::test_utils::ErrorReader; + use crate::reader::test_utils::{BatchThenErrorReader, ErrorReader}; use crate::reader::{ResultReader, ResultReaderMetrics}; use crate::result_stream::ResultStream; use crate::telemetry::models::OperationType; use crate::telemetry::runtime::{ConnectionTelemetry, TelemetrySessionContext}; - use arrow_array::RecordBatch; + use arrow_array::{RecordBatch, RecordBatchOptions}; use arrow_schema::Schema; use async_trait::async_trait; use std::future::Future; @@ -368,43 +368,84 @@ mod tests { } #[tokio::test] - async fn peek_first_batch_error_finalizes_statement_with_error_before_drop() { - let connection = Arc::new(CapturingConnectionTelemetry::default()); - let telemetry = StatementTelemetry::new( - connection.clone(), - StatementType::Sql, - OperationType::ExecuteStatement, - ); - let reader = ErrorReader { - schema: Arc::new(Schema::empty()), - }; - let mut stream = ResultStream::from_reader(Box::new(reader)) - .await - .expect("schema succeeds"); - stream.attach_telemetry(telemetry); - - let error = match stream.peek_first_batch().await { - Ok(_) => panic!("peek should surface reader error"), - Err(error) => error, - }; - assert_eq!(error.code, ErrorCode::Internal); - - drop(stream); - - let events = connection.statement_events.lock().expect("events mutex"); - assert_eq!( - events.len(), - 1, - "peek error should finalize once; Drop must not overwrite it with success" - ); - let event = &events[0]; - assert_eq!(event.context.statement_type, StatementType::Sql); - assert_eq!(event.error_code, Some(ErrorCode::Internal)); - assert_eq!(event.error_message.as_deref(), Some("simulated read error")); - assert!( - event.context.consumption_latency.is_some(), - "failed consumption should still record result-consumption latency" - ); + async fn reader_errors_finalize_statement_with_error_before_drop() { + for (volume, message) in [ + (false, "simulated read error"), + (true, "simulated read error after first batch"), + ] { + let connection = Arc::new(CapturingConnectionTelemetry::default()); + let telemetry = StatementTelemetry::new( + connection.clone(), + StatementType::Sql, + OperationType::ExecuteStatement, + ); + let schema = Arc::new(Schema::empty()); + let reader: Box = if volume { + Box::new(BatchThenErrorReader { + batch: Some( + RecordBatch::try_new_with_options( + schema.clone(), + vec![], + &RecordBatchOptions::new().with_row_count(Some(1)), + ) + .expect("one-row batch"), + ), + schema, + }) + } else { + Box::new(ErrorReader { schema }) + }; + let mut stream = ResultStream::from_reader(reader) + .await + .expect("schema succeeds"); + stream.attach_telemetry(telemetry); + + let error = if volume { + stream.attach_volume( + true, + crate::volume::VolumeState::new(Default::default(), None), + reqwest::Client::new(), + ); + stream + .complete_volume_operation(&Default::default(), None) + .await + .expect_err("instruction drain should surface reader error") + } else { + stream + .peek_first_batch() + .await + .map(|_| ()) + .expect_err("peek should surface reader error") + }; + assert_eq!(error.code, ErrorCode::Internal); + assert_eq!(error.message, message); + let events_before_drop = connection + .statement_events + .lock() + .expect("events mutex") + .len(); + assert_eq!( + events_before_drop, 1, + "reader error must finalize before Drop" + ); + + drop(stream); + + let events = connection.statement_events.lock().expect("events mutex"); + assert_eq!( + events.len(), + 1, + "reader error should finalize once; Drop must not overwrite it with success" + ); + let event = &events[0]; + assert_eq!(event.context.statement_type, StatementType::Sql); + assert_eq!(event.error_code, Some(ErrorCode::Internal)); + assert_eq!(event.error_message.as_deref(), Some(message)); + assert!( + event.context.consumption_latency.is_some(), + "failed consumption should still record result-consumption latency" + ); + } } #[tokio::test] diff --git a/src/volume.rs b/src/volume.rs index 535f8783..b5117530 100644 --- a/src/volume.rs +++ b/src/volume.rs @@ -399,10 +399,10 @@ impl VolumeState { *request.url_mut() = url; }; let status = response.status(); - if !status.is_success() - && !(instruction.operation == "REMOVE" + if !(status.is_success() + || (instruction.operation == "REMOVE" && status.as_u16() == 404 - && options.remove_not_found_is_success) + && options.remove_not_found_is_success)) { *retry_after = response .headers() From 215cd6be6726eb3422b9f981cd11c473ac1f658f Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Mon, 16 Nov 2026 22:14:15 +0000 Subject: [PATCH 27/63] test(volume): verify default and overridden storage deadlines Signed-off-by: Aakash Saravanan --- README.md | 4 ++++ src/client/http_tls_tests.rs | 22 ++++++++++------------ 2 files changed, 14 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index f8dbfa33..aaba729f 100644 --- a/README.md +++ b/README.md @@ -75,6 +75,10 @@ result can omit completion. Complete the operation before reading its instructio rows. The PyO3 `ExecutedStatement` and `ResultStream` classes expose `is_volume_operation` and `complete_volume_operation`. +Local filesystem setup and download publication are synchronous. Cancellation +cannot interrupt a blocked filesystem call and can wait for the atomic rename +that publishes a completed GET. + A PUT instruction with `localFile == "__input_stream__"` returns `NeedsInputStream` until owned input bytes are supplied. An empty byte buffer is a valid upload. Other statements do not request or consume input bytes. diff --git a/src/client/http_tls_tests.rs b/src/client/http_tls_tests.rs index 60e41b43..1684598f 100644 --- a/src/client/http_tls_tests.rs +++ b/src/client/http_tls_tests.rs @@ -312,25 +312,23 @@ async fn storage_connection_timeout_preserves_unconfigured_limits() { ); for timeout in [None, Some(Duration::from_millis(100))] { let storage = client.storage_client(timeout).unwrap(); + let deadline = if timeout.is_some() { + Duration::from_millis(500) + } else { + Duration::from_secs(3) + }; let result = tokio::time::timeout( - Duration::from_millis(500), + deadline, storage .put(format!("https://{address}/object")) .body("bytes") .send(), ) .await; - if timeout.is_some() { - let error = result - .expect("configured connection timeout must finish") - .unwrap_err(); - assert!(error.is_connect() && error.is_timeout(), "{error}"); - } else { - assert!( - result.is_err(), - "unconfigured storage must retain its limits" - ); - } + let error = result + .expect("storage connection timeout must finish") + .unwrap_err(); + assert!(error.is_connect() && error.is_timeout(), "{error}"); } shutdown.send(()).unwrap(); assert_eq!(server.await.unwrap(), 2); From 6f13979bbedd1bafd0df8bc9f1a2254ee25907c6 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Mon, 16 Nov 2026 23:56:39 +0000 Subject: [PATCH 28/63] fix(volume): skip leading empty instruction batches Signed-off-by: Aakash Saravanan --- src/result_stream.rs | 36 +++++++------ src/volume.rs | 28 +++++----- tests/v0_volume_wiremock.rs | 101 ++++++++++++++++++++++-------------- 3 files changed, 92 insertions(+), 73 deletions(-) diff --git a/src/result_stream.rs b/src/result_stream.rs index 705efb02..53eb0cc3 100644 --- a/src/result_stream.rs +++ b/src/result_stream.rs @@ -676,16 +676,21 @@ impl ResultStream { biased; error = state.cancellation() => Err(error), result = async { - let batch = self - .peek_first_batch() - .await - .map_err(|error| state.fail(error))? - .ok_or_else(|| { - state.fail(Error::invalid_argument().message("Missing Volume instruction row")) - })?; - let ResultBatch::Arrow(batch) = batch; - let batch = ResultBatch::Arrow(batch.clone()); - // The first batch stays buffered for callers; later batches must not + let batch = loop { + let batch = self + .peek_first_batch() + .await + .map_err(|error| state.fail(error))? + .ok_or_else(|| { + state.fail(Error::invalid_argument().message("Missing Volume instruction row")) + })?; + let ResultBatch::Arrow(batch) = batch; + if batch.num_rows() != 0 { + break ResultBatch::Arrow(batch.clone()); + } + self.prefetched = None; + }; + // The instruction stays buffered for callers; later batches must not // authorize a partial transfer of a multi-row instruction result. while !self.exhausted { match self @@ -870,14 +875,11 @@ impl ResultStream { } } - /// Non-consuming peek at the **first** batch of the stream. + /// Non-consuming peek at the next buffered batch. /// - /// Buffers the first batch or error so the caller's next read observes - /// the same outcome. Returns `None` for an empty - /// stream. Only valid before any `next_batch`/`peek_first_batch` has - /// run (it no-ops if a batch is already current or buffered), which is - /// the only context it's used in: deriving a DML row-count off the - /// terminal result at statement-construction time. + /// Pulls a batch or error when none is current or buffered and the reader is not + /// exhausted. A subsequent [`next_batch`](Self::next_batch) still returns + /// the buffered outcome. pub(crate) async fn peek_first_batch(&mut self) -> Result> { if self.prefetched.is_none() && self.current.is_none() && !self.exhausted { let reader = self diff --git a/src/volume.rs b/src/volume.rs index b5117530..bbd84353 100644 --- a/src/volume.rs +++ b/src/volume.rs @@ -819,11 +819,9 @@ mod tests { let dir = tempfile::tempdir().unwrap(); let source = dir.path().join("source"); for (operation, status, stream, payload) in [ - ("PUT", 200, false, vec![42; 128 * 1024]), ("PUT", 307, false, vec![42; 128 * 1024]), ("PUT", 308, false, vec![42; 128 * 1024]), ("PUT", 307, true, vec![]), - ("PUT", 308, true, vec![]), ("PUT", 307, true, b"payload".to_vec()), ("PUT", 308, true, b"payload".to_vec()), ("GET", 307, false, b"downloaded".to_vec()), @@ -849,20 +847,18 @@ mod tests { .expect(1) .mount(&server) .await; - if status != 200 { - Mock::given(method(verb)) - .and(path("/redirected")) - .and(header("x-storage-token", "server-token")) - .and(body_bytes(if operation == "PUT" { - payload.clone() - } else { - vec![] - })) - .respond_with(ResponseTemplate::new(200).set_body_bytes(payload.clone())) - .expect(1) - .mount(&server) - .await; - } + Mock::given(method(verb)) + .and(path("/redirected")) + .and(header("x-storage-token", "server-token")) + .and(body_bytes(if operation == "PUT" { + payload.clone() + } else { + vec![] + })) + .respond_with(ResponseTemplate::new(200).set_body_bytes(payload.clone())) + .expect(1) + .mount(&server) + .await; std::fs::write( &source, if operation == "GET" { diff --git a/tests/v0_volume_wiremock.rs b/tests/v0_volume_wiremock.rs index de6b9f3e..da4db59e 100644 --- a/tests/v0_volume_wiremock.rs +++ b/tests/v0_volume_wiremock.rs @@ -20,7 +20,7 @@ use arrow_schema::{DataType, Field, Schema}; use base64::{engine::general_purpose::STANDARD, Engine}; use databricks_sql_kernel::{ AuthConfig, ConnectionConfig, DirectStatement, ErrorCode, ExecutedStatementHandle, HttpConfig, - Session, VolumeCompletion, VolumeOptions, + ResultBatch, Session, VolumeCompletion, VolumeOptions, }; use serde_json::json; use std::sync::Arc; @@ -29,7 +29,7 @@ use wiremock::matchers::{method, path}; use wiremock::{Mock, MockServer, ResponseTemplate}; fn response(server: &MockServer, marked: bool, local: &str) -> serde_json::Value { - response_with_batches(server, marked, local, "GET", 1) + response_with_batches(server, marked, local, "GET", &[1]) } fn response_with_batches( @@ -37,7 +37,7 @@ fn response_with_batches( marked: bool, local: &str, operation: &str, - count: usize, + batch_rows: &[usize], ) -> serde_json::Value { let names = ["operation", "presignedUrl", "headers", "localFile"]; let schema = Arc::new(Schema::new( @@ -63,11 +63,12 @@ fn response_with_batches( let mut ipc = Vec::new(); { let mut writer = StreamWriter::try_new(&mut ipc, &batch.schema()).unwrap(); - for _ in 0..count { - writer.write(&batch).unwrap(); + for &rows in batch_rows { + writer.write(&batch.slice(0, rows)).unwrap(); } writer.finish().unwrap(); } + let count: usize = batch_rows.iter().sum(); json!({ "statement_id": "volume-stmt", "status": {"state": "CLOSED"}, "manifest": { @@ -80,41 +81,61 @@ fn response_with_batches( } #[tokio::test] -async fn multiple_instruction_batches_fail_before_any_storage_request() { - let server = MockServer::start().await; - let dir = tempfile::tempdir().unwrap(); - let dest = dir.path().join("download"); - std::fs::write(&dest, b"original").unwrap(); - let session = session( - &server, - response_with_batches(&server, true, dest.to_str().unwrap(), "GET", 2), - ) - .await; - Mock::given(method("GET")) - .and(path("/object")) - .respond_with(ResponseTemplate::new(200).set_body_bytes(b"replacement")) - .expect(0) - .mount(&server) +async fn instruction_batches_preserve_one_row_and_reject_extra_rows() { + for (batch_rows, valid) in [(&[1, 1][..], false), (&[0, 0, 1, 0][..], true)] { + let server = MockServer::start().await; + let dir = tempfile::tempdir().unwrap(); + let dest = dir.path().join("download"); + std::fs::write(&dest, b"original").unwrap(); + let session = session( + &server, + response_with_batches(&server, true, dest.to_str().unwrap(), "GET", batch_rows), + ) .await; - let mut statement = session.statement(); - statement.spec().sql("operation"); - let mut executed = statement.execute().await.unwrap(); - let options = VolumeOptions { - allowed_paths: vec![dir.path().to_owned()], - ..Default::default() - }; - for _ in 0..2 { - let error = executed - .result_stream_mut() - .complete_volume_operation(&options, None) - .await - .unwrap_err(); - assert_eq!(error.code, ErrorCode::InvalidArgument); - assert_eq!(error.message, "Expected one Volume instruction row"); + Mock::given(method("GET")) + .and(path("/object")) + .respond_with(ResponseTemplate::new(200).set_body_bytes(b"replacement")) + .expect(if valid { 1 } else { 0 }) + .mount(&server) + .await; + let mut statement = session.statement(); + statement.spec().sql("operation"); + let mut executed = statement.execute().await.unwrap(); + let options = VolumeOptions { + allowed_paths: vec![dir.path().to_owned()], + ..Default::default() + }; + for _ in 0..2 { + let result = executed + .result_stream_mut() + .complete_volume_operation(&options, None) + .await; + if valid { + assert_eq!(result.unwrap(), VolumeCompletion::Completed); + } else { + let error = result.unwrap_err(); + assert_eq!(error.code, ErrorCode::InvalidArgument); + assert_eq!(error.message, "Expected one Volume instruction row"); + } + } + assert_eq!( + std::fs::read(&dest).unwrap(), + if valid { + b"replacement".as_slice() + } else { + b"original".as_slice() + } + ); + if valid { + let ResultBatch::Arrow(batch) = executed.next_batch().await.unwrap().unwrap() else { + panic!("expected Arrow instruction batch"); + }; + assert_eq!(batch.num_rows(), 1); + assert!(executed.next_batch().await.unwrap().is_none()); + } + executed.close().await.unwrap(); + session.close().await.unwrap(); } - assert_eq!(std::fs::read(&dest).unwrap(), b"original"); - executed.close().await.unwrap(); - session.close().await.unwrap(); } async fn session(server: &MockServer, body: serde_json::Value) -> Session { @@ -179,7 +200,7 @@ async fn storage_transfers_outlive_rpc_deadline_while_sql_requests_still_time_ou http.overall_timeout = Duration::from_millis(200); let session = session_with_http( &server, - response_with_batches(&server, true, local.to_str().unwrap(), operation, 1), + response_with_batches(&server, true, local.to_str().unwrap(), operation, &[1]), http, ) .await; @@ -373,7 +394,7 @@ async fn cancellation_and_session_close_interrupt_instruction_or_storage_after_s let held_path = if instruction_page { body["manifest"]["total_chunk_count"] = json!(2); body["result"]["next_chunk_index"] = json!(1); - let mut next = response_with_batches(&server, true, dest.to_str().unwrap(), "GET", 0) + let mut next = response_with_batches(&server, true, dest.to_str().unwrap(), "GET", &[]) ["result"] .clone(); next["chunk_index"] = json!(1); From 36b2e69e308fcb6a3fd8092f6e95365024341e4c Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Tue, 17 Nov 2026 06:50:17 +0000 Subject: [PATCH 29/63] perf(volume): retain owned upload bytes across retries Signed-off-by: Aakash Saravanan --- src/volume.rs | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/volume.rs b/src/volume.rs index bbd84353..aabd248e 100644 --- a/src/volume.rs +++ b/src/volume.rs @@ -186,8 +186,7 @@ impl VolumeState { ) -> Result { let input = if instruction.operation == "PUT" && instruction.local_file == "__input_stream__" { - let bytes = input_bytes.ok_or_else(|| invalid("Missing input stream"))?; - Some(Arc::<[u8]>::from(bytes)) + Some(input_bytes.ok_or_else(|| invalid("Missing input stream"))?) } else { None }; @@ -200,7 +199,7 @@ impl VolumeState { &instruction, client, options, - input.as_ref(), + input.as_deref(), &mut retry_after, ) .await @@ -226,7 +225,7 @@ impl VolumeState { instruction: &Instruction, client: &Client, options: &VolumeOptions, - input: Option<&Arc<[u8]>>, + input: Option<&[u8]>, retry_after: &mut Option, ) -> Result { let method = match instruction.operation.as_str() { From 8a6edebb1a9fdf2ca132226840670e6396a72dd2 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Tue, 17 Nov 2026 19:28:11 +0000 Subject: [PATCH 30/63] fix(volume): preserve storage errors and instruction batches Classify common local file failures and retain transport causes. Defer storage client construction until completion, use bounded upload buffers and keep rejected instruction batches available for callers. Signed-off-by: Aakash Saravanan --- napi/src/async_statement.rs | 20 ++++++- src/c_abi/result.rs | 10 +++- src/client/http.rs | 44 ++++++++++++-- src/client/http_tls_tests.rs | 3 +- src/client/mod.rs | 2 +- src/result_stream.rs | 67 +++++++++++++--------- src/session.rs | 8 +-- src/telemetry/statement.rs | 6 +- src/volume.rs | 108 +++++++++++++++++++++++++++++++---- tests/v0_volume_wiremock.rs | 14 +++-- 10 files changed, 223 insertions(+), 59 deletions(-) diff --git a/napi/src/async_statement.rs b/napi/src/async_statement.rs index 37100eee..b5c953e3 100644 --- a/napi/src/async_statement.rs +++ b/napi/src/async_statement.rs @@ -355,7 +355,6 @@ impl AsyncStatement { /// `InvalidStatementHandle`. #[napi] pub async fn cancel(&self) -> napi::Result<()> { - self.canceller.cancel_volume_operation(); if self.closed.load(Ordering::Acquire) { return Err(closed_err("AsyncStatement")); } @@ -367,6 +366,7 @@ impl AsyncStatement { let Some(canceller) = canceller else { return Err(closed_err("AsyncStatement")); }; + canceller.cancel_volume_operation(); guarded(async move { canceller.cancel().await.map_err(napi_err_from_kernel) }).await } @@ -381,7 +381,14 @@ impl AsyncStatement { /// already in flight may finish before its handle is cleared. #[napi] pub async fn close(&self) -> napi::Result<()> { - self.canceller.cancel_volume_operation(); + if let Some(canceller) = self + .canceller + .lock() + .unwrap_or_else(PoisonError::into_inner) + .as_ref() + { + canceller.cancel_volume_operation(); + } let inner = Arc::clone(&self.inner); let closed = Arc::clone(&self.closed); let canceller = Arc::clone(&self.canceller); @@ -428,7 +435,14 @@ impl AsyncStatement { impl Drop for AsyncStatement { fn drop(&mut self) { - self.canceller.cancel_volume_operation(); + if let Some(canceller) = self + .canceller + .lock() + .unwrap_or_else(PoisonError::into_inner) + .as_ref() + { + canceller.cancel_volume_operation(); + } // Best-effort cleanup — same shape as `Connection::Drop`. // JS callers needing a guaranteed close-with-error-surface // call `close()` explicitly. diff --git a/src/c_abi/result.rs b/src/c_abi/result.rs index f5029efa..a7189ffc 100644 --- a/src/c_abi/result.rs +++ b/src/c_abi/result.rs @@ -798,7 +798,15 @@ mod tests { ResultStream::from_reader(Box::new(MockReader::new(vec![batch.clone()]))) .await .unwrap(); - stream.attach_volume(marked, Arc::clone(&volume), reqwest::Client::new()); + stream.attach_volume( + marked, + Arc::clone(&volume), + Arc::new( + crate::client::DatabricksHttpClient::with_default_retry(Default::default()) + .unwrap() + .storage_client(None), + ), + ); into_raw_result_stream(schema.clone(), stream) }); let mut is_volume = !marked; diff --git a/src/client/http.rs b/src/client/http.rs index 92df7acf..4a3edba4 100644 --- a/src/client/http.rs +++ b/src/client/http.rs @@ -388,6 +388,27 @@ pub struct DatabricksHttpClient { retry_configs: HashMap, } +pub(crate) struct StorageClient { + config: HttpClientConfig, + client: OnceLock>, +} + +impl StorageClient { + pub(crate) fn get(&self) -> Result<&Client> { + self.client + .get_or_init(|| { + // File replay uses one redirect budget across all hops. + DatabricksHttpClient::build_reqwest_client( + &self.config, + reqwest::redirect::Policy::none(), + None, + ) + }) + .as_ref() + .map_err(Clone::clone) + } +} + impl DatabricksHttpClient { /// Creates a new HTTP client with the given configuration and per-category retry configs. /// @@ -742,13 +763,15 @@ impl DatabricksHttpClient { } /// Storage transfers can outlive SQL RPCs, so retain connection settings without their deadline. - pub(crate) fn storage_client(&self, connect_timeout: Option) -> Result { + pub(crate) fn storage_client(&self, connect_timeout: Option) -> StorageClient { let mut config = self.config.clone(); if let Some(timeout) = connect_timeout { config.connect_timeout = config.connect_timeout.min(timeout); } - // Volume completion reopens file bodies and applies one redirect budget across all hops. - Self::build_reqwest_client(&config, reqwest::redirect::Policy::none(), None) + StorageClient { + config, + client: OnceLock::new(), + } } /// Get the authorization header value. @@ -1583,8 +1606,19 @@ lGrv15pBcePj let mut config = HttpClientConfig::default(); config.tls.trusted_certificate_path = Some(tmp.path().to_string_lossy().to_string()); - let client = DatabricksHttpClient::new(config, default_retry_configs()); - assert!(client.is_ok()); + let client = DatabricksHttpClient::new(config, default_retry_configs()).unwrap(); + let storage = client.storage_client(None); + assert!(storage.client.get().is_none()); + std::fs::write(tmp.path(), "not a certificate").unwrap(); + let error = storage.get().unwrap_err(); + assert!(error.message.contains("Invalid PEM certificate"), "{error}"); + std::fs::write(tmp.path(), TEST_CA_CERT_PEM).unwrap(); + assert_eq!(storage.get().unwrap_err().message, error.message); + + let storage = client.storage_client(None); + let first = storage.get().unwrap(); + std::fs::write(tmp.path(), "not a certificate").unwrap(); + assert!(std::ptr::eq(first, storage.get().unwrap())); } #[test] diff --git a/src/client/http_tls_tests.rs b/src/client/http_tls_tests.rs index 1684598f..a24d6d07 100644 --- a/src/client/http_tls_tests.rs +++ b/src/client/http_tls_tests.rs @@ -311,7 +311,8 @@ async fn storage_connection_timeout_preserves_unconfigured_limits() { Duration::from_secs(10), ); for timeout in [None, Some(Duration::from_millis(100))] { - let storage = client.storage_client(timeout).unwrap(); + let storage = client.storage_client(timeout); + let storage = storage.get().unwrap(); let deadline = if timeout.is_some() { Duration::from_millis(500) } else { 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/result_stream.rs b/src/result_stream.rs index 53eb0cc3..9ab56da0 100644 --- a/src/result_stream.rs +++ b/src/result_stream.rs @@ -58,6 +58,7 @@ use arrow_array::types::{ use arrow_array::{Array, RecordBatch}; use arrow_schema::{DataType, Schema, TimeUnit}; use chrono::{NaiveDate, NaiveDateTime}; +use std::collections::VecDeque; use std::sync::Arc; /// Cheap-clone reference to a result schema. The kernel hands one @@ -90,7 +91,7 @@ pub enum TryNextBatch<'a> { End, } -type Prefetched = Option>>; +type Prefetched = VecDeque>>; // `ResultBatch::into_arrow()` was deliberately removed: the // `#[non_exhaustive]` envelope is the right escape hatch already. @@ -466,7 +467,7 @@ pub struct ResultStream { /// until the next call to `next_batch` replaces it. current: Option, - /// A peek must preserve both data and read errors for the caller's fetch. + /// DML inspection and Volume validation must preserve rows and read errors for callers. prefetched: Prefetched, /// Row cursor inside [`current`](Self::current). Reset to `0` @@ -493,7 +494,10 @@ pub struct ResultStream { close_guard: Option, telemetry: Option, - volume: Option<(Arc, reqwest::Client)>, + volume: Option<( + Arc, + Arc, + )>, } struct ResultStreamTelemetry { @@ -604,7 +608,7 @@ impl ResultStream { reader: Some(reader), schema, current: None, - prefetched: None, + prefetched: VecDeque::new(), current_row_idx: 0, exhausted: false, close_guard: None, @@ -644,7 +648,7 @@ impl ResultStream { &mut self, marked: bool, state: Arc, - client: reqwest::Client, + client: Arc, ) { if marked { self.volume = Some((state, client)); @@ -688,7 +692,7 @@ impl ResultStream { if batch.num_rows() != 0 { break ResultBatch::Arrow(batch.clone()); } - self.prefetched = None; + self.prefetched.pop_front(); }; // The instruction stays buffered for callers; later batches must not // authorize a partial transfer of a multi-row instruction result. @@ -706,6 +710,7 @@ impl ResultStream { })? { Some(batch) if batch.num_rows() != 0 => { + self.prefetched.push_back(Ok(ResultBatch::Arrow(batch))); return Err(state.fail( Error::invalid_argument().message("Expected one Volume instruction row"), )); @@ -714,7 +719,8 @@ impl ResultStream { None => self.exhausted = true, } } - state.complete(&batch, &client, options, input_bytes).await + let client = client.get().map_err(|error| state.fail(error))?; + state.complete(&batch, client, options, input_bytes).await } => result, } } @@ -802,9 +808,9 @@ impl ResultStream { /// performed on this path, so calling from a tokio runtime /// (napi-rs, PyO3 async) is safe. pub async fn next_batch(&mut self) -> Result> { - // A batch buffered by `peek_first_batch` is replayed here first, - // so a non-consuming peek doesn't steal it from the caller. - if let Some(batch) = self.prefetched.take() { + // Replay inspected batches first so DML counts and Volume validation + // do not consume callers' result rows. + if let Some(batch) = self.prefetched.pop_front() { self.set_current_batch(batch.map_err(|error| *error)?); return Ok(self.current.as_ref()); } @@ -838,7 +844,7 @@ impl ResultStream { /// Return the next batch if it is already available without waiting for /// network or background-prefetch progress. pub fn try_next_batch(&mut self) -> Result> { - if let Some(batch) = self.prefetched.take() { + if let Some(batch) = self.prefetched.pop_front() { self.set_current_batch(batch.map_err(|error| *error)?); return Ok(TryNextBatch::Ready( self.current.as_ref().expect("batch was just installed"), @@ -881,14 +887,14 @@ impl ResultStream { /// exhausted. A subsequent [`next_batch`](Self::next_batch) still returns /// the buffered outcome. pub(crate) async fn peek_first_batch(&mut self) -> Result> { - if self.prefetched.is_none() && self.current.is_none() && !self.exhausted { + if self.prefetched.is_empty() && self.current.is_none() && !self.exhausted { let reader = self .reader .as_mut() .expect("ResultStream reader is present until into_owned_batches consumes it"); match reader.next_batch().await { Ok(Some(rb)) => { - self.prefetched = Some(Ok(ResultBatch::Arrow(rb))); + self.prefetched.push_back(Ok(ResultBatch::Arrow(rb))); // Stamp first-batch (result-set-ready) latency at fetch // time, not when the caller later consumes the prefetched // batch via `next_batch`. `record_result_batch` is @@ -898,7 +904,7 @@ impl ResultStream { // result set became ready rather than the caller's // think-time before the first `next_batch` pull. if let (Some(telemetry), Some(Ok(batch))) = - (&self.telemetry, self.prefetched.as_ref()) + (&self.telemetry, self.prefetched.front()) { telemetry.record_batch(batch); } @@ -906,12 +912,12 @@ impl ResultStream { Ok(None) => self.exhausted = true, Err(e) => { self.finalize_telemetry(Some(&e)); - self.prefetched = Some(Err(Box::new(e.clone()))); + self.prefetched.push_back(Err(Box::new(e.clone()))); return Err(e); } } } - match self.prefetched.as_ref() { + match self.prefetched.front() { Some(Ok(batch)) => Ok(Some(batch)), Some(Err(error)) => Err((**error).clone()), None => Ok(None), @@ -1004,13 +1010,11 @@ impl ResultStream { /// runtime at all. Errors are surfaced once; subsequent calls /// after an `Err` keep returning `None`. pub fn into_owned_batches(mut self) -> OwnedBatchIter { - // Preserve a peeked-but-not-yet-consumed first batch: it was - // pulled from the reader, so it must be yielded ahead of the - // reader's remaining batches or it would be silently dropped. - let prefetched = self - .prefetched - .take() - .map(|outcome| outcome.map(|ResultBatch::Arrow(rb)| rb)); + // Inspected batches were pulled from the reader; yield them first to preserve row order. + let prefetched = std::mem::take(&mut self.prefetched) + .into_iter() + .map(|outcome| outcome.map(|ResultBatch::Arrow(rb)| rb)) + .collect(); OwnedBatchIter { reader: self .reader @@ -1045,6 +1049,7 @@ impl Drop for ResultStream { /// reader's natural end-of-stream the same way. pub struct OwnedBatchIter { reader: Box, + /// Inspected batches must precede the reader's remaining rows. prefetched: Prefetched, telemetry: Option, done: bool, @@ -1057,7 +1062,7 @@ impl Iterator for OwnedBatchIter { if self.done { return None; } - if let Some(outcome) = self.prefetched.take() { + if let Some(outcome) = self.prefetched.pop_front() { return match outcome { Ok(batch) => { if let Some(telemetry) = &self.telemetry { @@ -1489,16 +1494,22 @@ mod tests { let schema = schema_for(vec![Field::new("a", DataType::Int32, false)]); let b1 = RecordBatch::try_new(schema.clone(), vec![Arc::new(Int32Array::from(vec![1, 2]))]) .unwrap(); - let b2 = RecordBatch::try_new(schema, vec![Arc::new(Int32Array::from(vec![3]))]).unwrap(); - let reader = InMemoryReader::new(b1.schema(), vec![b1.clone(), b2.clone()]); + let b2 = RecordBatch::try_new(schema.clone(), vec![Arc::new(Int32Array::from(vec![3]))]) + .unwrap(); + let b3 = RecordBatch::try_new(schema, vec![Arc::new(Int32Array::from(vec![4]))]).unwrap(); + let reader = InMemoryReader::new(b1.schema(), vec![b1.clone(), b3.clone()]); let mut stream = ResultStream::from_reader(Box::new(reader)).await.unwrap(); assert!(stream.peek_first_batch().await.unwrap().is_some()); + stream + .prefetched + .push_back(Ok(ResultBatch::Arrow(b2.clone()))); let mut iter = stream.into_owned_batches(); let first = iter.next().unwrap().unwrap(); - assert_eq!(first.num_rows(), 2); + assert_eq!(first, b1); let second = iter.next().unwrap().unwrap(); - assert_eq!(second.num_rows(), 1); + assert_eq!(second, b2); + assert_eq!(iter.next().unwrap().unwrap(), b3); assert!(iter.next().is_none(), "exhausted iterator returns None"); assert!(iter.next().is_none(), "still None on subsequent calls"); } diff --git a/src/session.rs b/src/session.rs index 516ea575..c52e6d4e 100644 --- a/src/session.rs +++ b/src/session.rs @@ -97,7 +97,7 @@ pub(crate) struct SessionInner { /// behind the trait object; future variants slot in via /// `TransportMode`. transport: Arc, - storage_client: reqwest::Client, + storage_client: Arc, storage_retry: RetryConfig, volume_states: std::sync::Mutex>>>, @@ -188,8 +188,8 @@ impl SessionInner { } } - pub(crate) fn storage_client(&self) -> reqwest::Client { - self.storage_client.clone() + pub(crate) fn storage_client(&self) -> Arc { + Arc::clone(&self.storage_client) } /// Crate-internal accessor for the session's transport. Used by @@ -408,7 +408,7 @@ impl Session { Error::network_error().message(format!("Failed to construct HTTP client: {e}")) })?, ); - let storage_client = http_client.storage_client(config.http.storage_read_timeout)?; + let storage_client = Arc::new(http_client.storage_client(config.http.storage_read_timeout)); // 2. Auth provider — async because OAuth flows hit the OIDC // discovery endpoint. diff --git a/src/telemetry/statement.rs b/src/telemetry/statement.rs index 171926ae..b56de1ca 100644 --- a/src/telemetry/statement.rs +++ b/src/telemetry/statement.rs @@ -404,7 +404,11 @@ mod tests { stream.attach_volume( true, crate::volume::VolumeState::new(Default::default(), None), - reqwest::Client::new(), + Arc::new( + crate::client::DatabricksHttpClient::with_default_retry(Default::default()) + .unwrap() + .storage_client(None), + ), ); stream .complete_volume_operation(&Default::default(), None) diff --git a/src/volume.rs b/src/volume.rs index aabd248e..8a429266 100644 --- a/src/volume.rs +++ b/src/volume.rs @@ -451,10 +451,12 @@ fn upload_body( path: String, error: Arc>>, ) -> reqwest::Body { - reqwest::Body::wrap_stream(ReaderStream::new(reader).map_err(move |cause| { - *error.lock().unwrap_or_else(|e| e.into_inner()) = Some(local_error(cause, &path)); - std::io::Error::other("Volume upload source could not be read") - })) + reqwest::Body::wrap_stream(ReaderStream::with_capacity(reader, 256 * 1024).map_err( + move |cause| { + *error.lock().unwrap_or_else(|e| e.into_inner()) = Some(local_error(cause, &path)); + std::io::Error::other("Volume upload source could not be read") + }, + )) } fn invalid(message: &str) -> Error { @@ -516,12 +518,17 @@ fn storage_error(error: reqwest::Error) -> Error { let retryable = !source_body_failed && RetryStrategy::for_request(RequestType::CloudFetchDownload, &RetryConfig::default()) .is_retryable_error(&error); + let error = error.without_url(); + let mut causes = crate::client::error_chain(&error) + .map(ToString::to_string) + .collect::>(); + causes.dedup(); Error::network_error() .with_error_code("VOLUME_STORAGE_NETWORK_ERROR") .with_retryable(retryable) .message(format!( "Volume storage request failed: {}", - error.without_url() + causes.join(": ") )) } @@ -533,7 +540,17 @@ fn response_body_error(error: reqwest::Error) -> Error { } fn local_error(error: std::io::Error, path: &str) -> Error { - let mut result = Error::io().message(format!("{error}: {path}")); + let mut result = match error.kind() { + std::io::ErrorKind::NotFound => Error::not_found(), + std::io::ErrorKind::PermissionDenied => Error::permission_denied(), + std::io::ErrorKind::InvalidInput + | std::io::ErrorKind::IsADirectory + | std::io::ErrorKind::NotADirectory => Error::invalid_argument(), + _ => Error::io(), + } + .with_error_code("VOLUME_LOCAL_FILE_ERROR") + .with_sql_state("HY000") + .message(format!("{error}: {path}")); result.local_error = Some(Box::new(LocalFileError { raw_os_error: error.raw_os_error(), kind: format!("{:?}", error.kind()), @@ -806,7 +823,8 @@ mod tests { .await .unwrap_err(); assert!(!error.retryable); - assert_eq!(error.code, crate::ErrorCode::Internal); + assert_eq!(error.code, crate::ErrorCode::NotFound); + assert_eq!(error.error_code.as_deref(), Some("VOLUME_LOCAL_FILE_ERROR")); let local = error.local_error.unwrap(); assert_eq!(local.raw_os_error, os_code); assert_eq!(local.path, source.to_str().unwrap()); @@ -818,8 +836,8 @@ mod tests { let dir = tempfile::tempdir().unwrap(); let source = dir.path().join("source"); for (operation, status, stream, payload) in [ - ("PUT", 307, false, vec![42; 128 * 1024]), - ("PUT", 308, false, vec![42; 128 * 1024]), + ("PUT", 307, false, vec![42; 512 * 1024 + 17]), + ("PUT", 308, false, vec![42; 512 * 1024 + 17]), ("PUT", 307, true, vec![]), ("PUT", 307, true, b"payload".to_vec()), ("PUT", 308, true, b"payload".to_vec()), @@ -1280,6 +1298,8 @@ mod tests { .complete(&batch, &Client::new(), &options(dir.path()), None) .await .unwrap_err(); + assert_eq!(error.code, crate::ErrorCode::PermissionDenied); + assert_eq!(error.error_code.as_deref(), Some("VOLUME_LOCAL_FILE_ERROR")); let local = error.local_error.unwrap(); assert_eq!(local.kind, "PermissionDenied"); assert_eq!(local.path, dest.to_string_lossy()); @@ -1617,8 +1637,12 @@ mod tests { async fn local_errors_retain_os_code_and_requested_filename() { let dir = tempfile::tempdir().unwrap(); let server = MockServer::start().await; - for (source, kind) in [ - (dir.path().join("missing"), "NotFound"), + for (source, kind, code) in [ + ( + dir.path().join("missing"), + "NotFound", + crate::ErrorCode::NotFound, + ), ( dir.path().to_owned(), if cfg!(windows) { @@ -1626,6 +1650,11 @@ mod tests { } else { "IsADirectory" }, + if cfg!(windows) { + crate::ErrorCode::PermissionDenied + } else { + crate::ErrorCode::InvalidArgument + }, ), ] { let batch = instruction( @@ -1638,6 +1667,10 @@ mod tests { .complete(&batch, &Client::new(), &options(dir.path()), None) .await .unwrap_err(); + assert_eq!(error.code, code); + assert_eq!(error.error_code.as_deref(), Some("VOLUME_LOCAL_FILE_ERROR")); + assert_eq!(error.sql_state.as_deref(), Some("HY000")); + assert!(!error.retryable); let local = error.local_error.as_ref().unwrap(); assert_eq!(local.kind, kind); assert!(local.raw_os_error.is_some()); @@ -1656,6 +1689,59 @@ mod tests { ); } assert!(server.received_requests().await.unwrap().is_empty()); + for (kind, code) in [ + ( + std::io::ErrorKind::PermissionDenied, + crate::ErrorCode::PermissionDenied, + ), + ( + std::io::ErrorKind::InvalidInput, + crate::ErrorCode::InvalidArgument, + ), + ( + std::io::ErrorKind::NotADirectory, + crate::ErrorCode::InvalidArgument, + ), + (std::io::ErrorKind::Other, crate::ErrorCode::Internal), + ] { + let error = local_error(std::io::Error::from(kind), "requested"); + assert_eq!(error.code, code); + assert_eq!(error.error_code.as_deref(), Some("VOLUME_LOCAL_FILE_ERROR")); + assert_eq!(error.sql_state.as_deref(), Some("HY000")); + assert!(!error.retryable); + let local = error.local_error.unwrap(); + assert_eq!(local.kind, format!("{kind:?}")); + assert_eq!(local.path, "requested"); + } + } + + #[tokio::test] + async fn storage_network_errors_preserve_causes_without_signed_urls() { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + drop(listener); + let url = format!("http://{address}/object?secret=hidden"); + let error = Client::builder() + .no_proxy() + .build() + .unwrap() + .get(&url) + .send() + .await + .unwrap_err(); + let mapped = storage_error(error); + assert_eq!(mapped.code, crate::ErrorCode::NetworkError); + assert_eq!( + mapped.error_code.as_deref(), + Some("VOLUME_STORAGE_NETWORK_ERROR") + ); + assert!(mapped.retryable); + assert!( + mapped.message.to_ascii_lowercase().contains("refused"), + "{mapped}" + ); + assert!(!mapped.message.contains(&address.to_string()), "{mapped}"); + assert!(!mapped.message.contains("hidden"), "{mapped}"); } #[test] diff --git a/tests/v0_volume_wiremock.rs b/tests/v0_volume_wiremock.rs index da4db59e..2031738d 100644 --- a/tests/v0_volume_wiremock.rs +++ b/tests/v0_volume_wiremock.rs @@ -20,7 +20,7 @@ use arrow_schema::{DataType, Field, Schema}; use base64::{engine::general_purpose::STANDARD, Engine}; use databricks_sql_kernel::{ AuthConfig, ConnectionConfig, DirectStatement, ErrorCode, ExecutedStatementHandle, HttpConfig, - ResultBatch, Session, VolumeCompletion, VolumeOptions, + ResultBatch, Session, TryNextBatch, VolumeCompletion, VolumeOptions, }; use serde_json::json; use std::sync::Arc; @@ -126,13 +126,19 @@ async fn instruction_batches_preserve_one_row_and_reject_extra_rows() { b"original".as_slice() } ); - if valid { + let TryNextBatch::Ready(ResultBatch::Arrow(batch)) = + executed.result_stream_mut().try_next_batch().unwrap() + else { + panic!("expected buffered instruction batch"); + }; + assert_eq!(batch.num_rows(), 1); + if !valid { let ResultBatch::Arrow(batch) = executed.next_batch().await.unwrap().unwrap() else { - panic!("expected Arrow instruction batch"); + panic!("expected retained extra instruction batch"); }; assert_eq!(batch.num_rows(), 1); - assert!(executed.next_batch().await.unwrap().is_none()); } + assert!(executed.next_batch().await.unwrap().is_none()); executed.close().await.unwrap(); session.close().await.unwrap(); } From 6f1b2da08edee534848251caa0cc893e67077d87 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Tue, 17 Nov 2026 21:34:30 +0000 Subject: [PATCH 31/63] docs: clarify Volume path and API contracts Signed-off-by: Aakash Saravanan --- README.md | 3 +++ src/kernel_error.rs | 15 ++++++--------- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index aaba729f..1f6842fe 100644 --- a/README.md +++ b/README.md @@ -90,6 +90,9 @@ rejected. This is stricter than the lexical-only checks in existing Python and Node.js Thrift transfer paths. An allowed root's symlink alias does not authorize additional lexical paths. +Paths are normalized lexically before symlink resolution. Allowed-root validation +assumes path components remain unchanged between validation and file access. + GET replaces the destination only after a complete download. Transfer failures and cancellation before publication preserve the destination's existing bytes. Repeated completion on the same execution reuses its outcome, including errors. diff --git a/src/kernel_error.rs b/src/kernel_error.rs index 6ec47e88..4ff419a8 100644 --- a/src/kernel_error.rs +++ b/src/kernel_error.rs @@ -41,12 +41,10 @@ //! Aborted, Unimplemented, …) lands in a follow-on PR. External //! `match` arms get a forced `_ =>` fallback — they keep compiling //! when the enum grows. -//! - `Error` **is not** `#[non_exhaustive]`: wrappers want to -//! pattern-match (`let Error { code, message, sql_state, .. }`) for -//! logging and host-language exception mapping. New fields go -//! through `Error::new(...).with_*(...)`, so adding a field is -//! non-breaking without the marker. Keeping the marker would block -//! useful pattern-matches for no real benefit. +//! - `Error` **is not** `#[non_exhaustive]`, so adding public fields +//! breaks callers using struct literals or exhaustive patterns. Prefer +//! `Error::new(...).with_*(...)` and patterns with `..` to keep callers +//! independent of additional fields. #![allow(dead_code)] @@ -169,9 +167,8 @@ impl ErrorCode { /// chain `with_*` setters. **Pattern-matching is supported** — /// wrappers writing a comprehensive logger or host-language exception /// adapter can do `let Error { code, message, sql_state, .. } = err;`. -/// New fields land through additive setters, so the type does not -/// need `#[non_exhaustive]` (and the marker would block the -/// pattern-matching wrappers actually want). +/// Adding public fields breaks callers using struct literals or exhaustive +/// patterns; constructors and patterns with `..` avoid that coupling. #[derive(Debug, Clone)] pub struct Error { pub code: ErrorCode, From f371b0067eabde3628dcbc52f849405926a22065 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Tue, 17 Nov 2026 21:57:59 +0000 Subject: [PATCH 32/63] fix(volume): strip credentials when redirect schemes differ Signed-off-by: Aakash Saravanan --- src/volume.rs | 108 ++++++++++++++++++++++++++++++-------------------- 1 file changed, 66 insertions(+), 42 deletions(-) diff --git a/src/volume.rs b/src/volume.rs index 8a429266..d504d32d 100644 --- a/src/volume.rs +++ b/src/volume.rs @@ -356,33 +356,7 @@ impl VolumeState { } redirects += 1; let previous = response.url(); - if url.host_str() != previous.host_str() - || url.port_or_known_default() != previous.port_or_known_default() - { - for name in [ - "authorization", - "cookie", - "cookie2", - "proxy-authorization", - "www-authenticate", - ] { - request.headers_mut().remove(name); - } - } - if previous.scheme() == "https" && url.scheme() == "http" { - request.headers_mut().remove(reqwest::header::REFERER); - } else { - let mut referer = previous.clone(); - let _ = referer.set_username(""); - let _ = referer.set_password(None); - referer.set_query(None); - referer.set_fragment(None); - if let Ok(value) = referer.as_str().parse() { - request - .headers_mut() - .insert(reqwest::header::REFERER, value); - } - } + redirect_headers(request.headers_mut(), previous, &url); if response.status() == reqwest::StatusCode::SEE_OTHER { *request.method_mut() = Method::GET; *request.body_mut() = None; @@ -446,6 +420,35 @@ impl VolumeState { } } +fn redirect_headers(headers: &mut HeaderMap, previous: &reqwest::Url, next: &reqwest::Url) { + if next.scheme() != previous.scheme() + || next.host_str() != previous.host_str() + || next.port_or_known_default() != previous.port_or_known_default() + { + for name in [ + "authorization", + "cookie", + "cookie2", + "proxy-authorization", + "www-authenticate", + ] { + headers.remove(name); + } + } + if previous.scheme() == "https" && next.scheme() == "http" { + headers.remove(reqwest::header::REFERER); + } else { + let mut referer = previous.clone(); + let _ = referer.set_username(""); + let _ = referer.set_password(None); + referer.set_query(None); + referer.set_fragment(None); + if let Ok(value) = referer.as_str().parse() { + headers.insert(reqwest::header::REFERER, value); + } + } +} + fn upload_body( reader: impl tokio::io::AsyncRead + Unpin + Send + 'static, path: String, @@ -922,8 +925,41 @@ mod tests { } #[tokio::test] - async fn redirects_strip_cross_host_credentials_and_share_a_hop_limit() { + async fn redirects_strip_cross_origin_credentials_and_share_a_hop_limit() { use std::sync::atomic::{AtomicUsize, Ordering}; + let sensitive = [ + "authorization", + "cookie", + "cookie2", + "proxy-authorization", + "www-authenticate", + ]; + let previous = + reqwest::Url::parse("https://storage.invalid:8443/a?signature=secret").unwrap(); + for scheme in ["https", "http"] { + let next = reqwest::Url::parse(&format!("{scheme}://storage.invalid:8443/b")).unwrap(); + let mut headers = HeaderMap::new(); + for name in sensitive { + headers.insert( + reqwest::header::HeaderName::from_static(name), + "storage-secret".parse().unwrap(), + ); + } + headers.insert("x-storage-token", "server-token".parse().unwrap()); + redirect_headers(&mut headers, &previous, &next); + let same_origin = scheme == "https"; + for name in sensitive { + assert_eq!(headers.contains_key(name), same_origin, "{scheme}: {name}"); + } + assert_eq!(headers["x-storage-token"], "server-token"); + assert_eq!(headers.contains_key(reqwest::header::REFERER), same_origin); + if same_origin { + assert_eq!( + headers[reqwest::header::REFERER], + "https://storage.invalid:8443/a" + ); + } + } let server = MockServer::start().await; let redirected = MockServer::start().await; let dir = tempfile::tempdir().unwrap(); @@ -943,13 +979,7 @@ mod tests { let attempts = Arc::clone(&count); Mock::given(header("x-storage-token", "server-token")) .respond_with(move |request: &wiremock::Request| { - for name in [ - "authorization", - "cookie", - "cookie2", - "proxy-authorization", - "www-authenticate", - ] { + for name in sensitive { assert!(!request.headers.contains_key(name)); } let referer = @@ -976,13 +1006,7 @@ mod tests { &source, ); let mut instruction = Instruction::decode(&batch).unwrap(); - for name in [ - "authorization", - "cookie", - "cookie2", - "proxy-authorization", - "www-authenticate", - ] { + for name in sensitive { instruction.headers.insert( reqwest::header::HeaderName::from_static(name), "storage-secret".parse().unwrap(), From 0263b1e8adf11bb3342134a0322268a6df3a6653 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Tue, 17 Nov 2026 22:28:53 +0000 Subject: [PATCH 33/63] fix(volume): replace computed upload lengths Signed-off-by: Aakash Saravanan --- src/volume.rs | 83 +++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 81 insertions(+), 2 deletions(-) diff --git a/src/volume.rs b/src/volume.rs index d504d32d..0e8e9512 100644 --- a/src/volume.rs +++ b/src/volume.rs @@ -239,7 +239,10 @@ impl VolumeState { .headers(instruction.headers.clone()); if let Some(bytes) = input { request = request - .header(reqwest::header::CONTENT_LENGTH, bytes.len()) + .headers(HeaderMap::from_iter([( + reqwest::header::CONTENT_LENGTH, + bytes.len().into(), + )])) .body(bytes.to_vec()); } let local_path = if instruction.operation == "REMOVE" @@ -319,7 +322,10 @@ impl VolumeState { return Err(local_error(error, &instruction.local_file)); } next = next - .header(reqwest::header::CONTENT_LENGTH, metadata.len()) + .headers(HeaderMap::from_iter([( + reqwest::header::CONTENT_LENGTH, + metadata.len().into(), + )])) .body(upload_body( tokio::fs::File::from_std(file), instruction.local_file.clone(), @@ -922,6 +928,79 @@ mod tests { .iter() .all(|request| !request.headers.contains_key("authorization"))); } + + // Hyper normalizes duplicate lengths before Wiremock can inspect them. + use tokio::io::AsyncReadExt; + for stream in [false, true] { + let payload = b"payload"; + std::fs::write(&source, payload).unwrap(); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}/object", listener.local_addr().unwrap()); + let peer = tokio::spawn(async move { + for hop in 0..2 { + let (mut socket, _) = listener.accept().await.unwrap(); + let mut request = Vec::new(); + let mut byte = [0]; + while !request.ends_with(b"\r\n\r\n") { + socket.read_exact(&mut byte).await.unwrap(); + request.push(byte[0]); + } + let lengths = String::from_utf8(request) + .unwrap() + .lines() + .filter_map(|line| { + line.to_ascii_lowercase() + .strip_prefix("content-length:") + .map(|value| value.trim().to_owned()) + }) + .collect::>(); + assert_eq!(lengths, [payload.len().to_string()]); + let mut body = vec![0; payload.len()]; + socket.read_exact(&mut body).await.unwrap(); + assert_eq!(body, payload); + let response = if hop == 0 { + b"HTTP/1.1 307 Temporary Redirect\r\nLocation: /redirected\r\nContent-Length: 0\r\nConnection: close\r\n\r\n".as_slice() + } else { + b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\nConnection: close\r\n\r\n" + }; + socket.write_all(response).await.unwrap(); + } + }); + let batch = instruction( + "PUT", + &url, + if stream { + Path::new("__input_stream__") + } else { + &source + }, + ); + let mut upload = Instruction::decode(&batch).unwrap(); + upload + .headers + .insert(reqwest::header::CONTENT_LENGTH, payload.len().into()); + let client = Client::builder() + .redirect(reqwest::redirect::Policy::none()) + .build() + .unwrap(); + assert_eq!( + tokio::time::timeout( + Duration::from_secs(2), + transfer_state(0).transfer_once( + &upload, + &client, + &options(dir.path()), + stream.then_some(payload.as_slice()), + &mut None + ), + ) + .await + .unwrap() + .unwrap(), + VolumeCompletion::Completed, + ); + peer.await.unwrap(); + } } #[tokio::test] From 2eefa41e176a69f7727eec2610092af5f7fc79ae Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Tue, 17 Nov 2026 22:51:15 +0000 Subject: [PATCH 34/63] docs: clarify cached Volume marker lifetime Signed-off-by: Aakash Saravanan --- include/databricks_kernel.h | 6 ++++-- src/c_abi/result.rs | 3 ++- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h index b6e2ded7..2312c24e 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -54,8 +54,9 @@ * `KernelStatusCode_InvalidStatementHandle`. Don't hold two live * executed handles from one statement. * - **A result stream borrows its executed handle.** Closing the executed - * handle invalidates any stream obtained from it: subsequent stream - * calls return `InvalidStatementHandle` (a defined error, not UB). + * handle invalidates any stream obtained from it: schema access, fetching + * and Volume completion return `InvalidStatementHandle` (a defined error, + * not UB). The cached Volume marker remains readable until stream close. * - **Close is awaited.** `kernel_session_close` waits for the server-side * delete to complete and flushes close-session telemetry before returning. * If close fails, the kernel still schedules best-effort cleanup when the @@ -978,6 +979,7 @@ KernelStatusCode kernel_result_stream_get_schema(kernel_result_stream_t* stream, * The detached result-stream canceller can interrupt completion. */ KernelStatusCode kernel_executed_statement_is_volume_operation( const kernel_executed_statement_t* exec, bool* out); +/* The cached marker does not establish whether the executed owner is valid. */ KernelStatusCode kernel_result_stream_is_volume_operation( const kernel_result_stream_t* stream, bool* out); KernelStatusCode kernel_result_stream_complete_volume_operation( diff --git a/src/c_abi/result.rs b/src/c_abi/result.rs index a7189ffc..67a1a614 100644 --- a/src/c_abi/result.rs +++ b/src/c_abi/result.rs @@ -655,7 +655,8 @@ pub unsafe extern "C" fn kernel_result_stream_canceller_free( }) } -/// Read whether this stream has authority to complete a Volume instruction. +/// Read the Volume marker captured when this stream was created. +/// Success does not establish whether the executed owner is valid. /// # Safety /// `stream` must be live and `out` must be writable. #[no_mangle] From 22b948bb6c417620ce8d67f070156c09109c2441 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Tue, 17 Nov 2026 23:25:45 +0000 Subject: [PATCH 35/63] docs: describe buffered result outcomes precisely Signed-off-by: Aakash Saravanan --- src/result_stream.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/result_stream.rs b/src/result_stream.rs index 9ab56da0..3a0470a7 100644 --- a/src/result_stream.rs +++ b/src/result_stream.rs @@ -467,7 +467,7 @@ pub struct ResultStream { /// until the next call to `next_batch` replaces it. current: Option, - /// DML inspection and Volume validation must preserve rows and read errors for callers. + /// Buffered outcomes retained for subsequent reads after inspection. prefetched: Prefetched, /// Row cursor inside [`current`](Self::current). Reset to `0` From ae98958357640c6ce3e3b86620d2fe0f11f8f1a3 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Tue, 17 Nov 2026 23:55:36 +0000 Subject: [PATCH 36/63] fix(volume): finalize terminal completion error telemetry Signed-off-by: Aakash Saravanan --- src/result_stream.rs | 95 ++++++++++++++--------------- src/telemetry/statement.rs | 118 ++++++++++++++++++++++++++++--------- 2 files changed, 138 insertions(+), 75 deletions(-) diff --git a/src/result_stream.rs b/src/result_stream.rs index 3a0470a7..c21f852f 100644 --- a/src/result_stream.rs +++ b/src/result_stream.rs @@ -673,56 +673,57 @@ impl ResultStream { let Some((state, client)) = self.volume.clone() else { return Ok(crate::volume::VolumeCompletion::NotVolume); }; - if let Some(result) = state.cached() { - return result; - } - tokio::select! { - biased; - error = state.cancellation() => Err(error), - result = async { - let batch = loop { - let batch = self - .peek_first_batch() - .await - .map_err(|error| state.fail(error))? - .ok_or_else(|| { - state.fail(Error::invalid_argument().message("Missing Volume instruction row")) - })?; - let ResultBatch::Arrow(batch) = batch; - if batch.num_rows() != 0 { - break ResultBatch::Arrow(batch.clone()); - } - self.prefetched.pop_front(); - }; - // The instruction stays buffered for callers; later batches must not - // authorize a partial transfer of a multi-row instruction result. - while !self.exhausted { - match self - .reader - .as_mut() - .expect("Volume completion retains its reader") - .next_batch() - .await - .map_err(|error| { - let error = state.fail(error); - self.finalize_telemetry(Some(&error)); - error - })? - { - Some(batch) if batch.num_rows() != 0 => { - self.prefetched.push_back(Ok(ResultBatch::Arrow(batch))); - return Err(state.fail( - Error::invalid_argument().message("Expected one Volume instruction row"), - )); + let result = if let Some(result) = state.cached() { + result + } else { + tokio::select! { + biased; + error = state.cancellation() => Err(error), + result = async { + let batch = loop { + let batch = self + .peek_first_batch() + .await + .map_err(|error| state.fail(error))? + .ok_or_else(|| { + state.fail(Error::invalid_argument().message("Missing Volume instruction row")) + })?; + let ResultBatch::Arrow(batch) = batch; + if batch.num_rows() != 0 { + break ResultBatch::Arrow(batch.clone()); + } + self.prefetched.pop_front(); + }; + // The instruction stays buffered for callers; later batches must not + // authorize a partial transfer of a multi-row instruction result. + while !self.exhausted { + match self + .reader + .as_mut() + .expect("Volume completion retains its reader") + .next_batch() + .await + .map_err(|error| state.fail(error))? + { + Some(batch) if batch.num_rows() != 0 => { + self.prefetched.push_back(Ok(ResultBatch::Arrow(batch))); + return Err(state.fail( + Error::invalid_argument().message("Expected one Volume instruction row"), + )); + } + Some(_) => {} + None => self.exhausted = true, } - Some(_) => {} - None => self.exhausted = true, } - } - let client = client.get().map_err(|error| state.fail(error))?; - state.complete(&batch, client, options, input_bytes).await - } => result, + let client = client.get().map_err(|error| state.fail(error))?; + state.complete(&batch, client, options, input_bytes).await + } => result, + } + }; + if let Err(error) = &result { + self.finalize_telemetry(Some(error)); } + result } pub(crate) fn volume_state(&self) -> Option> { diff --git a/src/telemetry/statement.rs b/src/telemetry/statement.rs index b56de1ca..07443d07 100644 --- a/src/telemetry/statement.rs +++ b/src/telemetry/statement.rs @@ -292,7 +292,9 @@ fn duration_millis(duration: Duration) -> i64 { mod tests { use super::*; use crate::kernel_error::ErrorCode; - use crate::reader::test_utils::{BatchThenErrorReader, ErrorReader}; + use crate::reader::test_utils::{ + BatchThenErrorReader, BlockingReader, ErrorReader, MockReader, + }; use crate::reader::{ResultReader, ResultReaderMetrics}; use crate::result_stream::ResultStream; use crate::telemetry::models::OperationType; @@ -368,10 +370,20 @@ mod tests { } #[tokio::test] - async fn reader_errors_finalize_statement_with_error_before_drop() { - for (volume, message) in [ - (false, "simulated read error"), - (true, "simulated read error after first batch"), + async fn result_errors_finalize_statement_with_error_before_drop() { + enum Case { + Reader, + VolumeReader, + Instruction, + Cancellation, + CachedCancellation, + } + for case in [ + Case::Reader, + Case::VolumeReader, + Case::Instruction, + Case::Cancellation, + Case::CachedCancellation, ] { let connection = Arc::new(CapturingConnectionTelemetry::default()); let telemetry = StatementTelemetry::new( @@ -380,40 +392,90 @@ mod tests { OperationType::ExecuteStatement, ); let schema = Arc::new(Schema::empty()); - let reader: Box = if volume { - Box::new(BatchThenErrorReader { - batch: Some( - RecordBatch::try_new_with_options( - schema.clone(), - vec![], - &RecordBatchOptions::new().with_row_count(Some(1)), - ) - .expect("one-row batch"), - ), - schema, - }) - } else { - Box::new(ErrorReader { schema }) + let batch = RecordBatch::try_new_with_options( + schema.clone(), + vec![], + &RecordBatchOptions::new().with_row_count(Some(1)), + ) + .expect("one-row batch"); + let entered = Arc::new(tokio::sync::Notify::new()); + let (reader, code, message): (Box, _, _) = match case { + Case::Reader => ( + Box::new(ErrorReader { schema }), + ErrorCode::Internal, + "simulated read error", + ), + Case::VolumeReader => ( + Box::new(BatchThenErrorReader { + batch: Some(batch), + schema, + }), + ErrorCode::Internal, + "simulated read error after first batch", + ), + Case::Instruction => ( + Box::new(MockReader::new(vec![batch])), + ErrorCode::InvalidArgument, + "Missing Volume instruction column", + ), + Case::Cancellation => ( + Box::new(BlockingReader { + schema, + entered: entered.clone(), + release: Arc::new(tokio::sync::Notify::new()), + }), + ErrorCode::Cancelled, + "Volume transfer was cancelled", + ), + Case::CachedCancellation => ( + Box::new(MockReader::new(vec![batch])), + ErrorCode::Cancelled, + "Volume transfer was cancelled", + ), }; let mut stream = ResultStream::from_reader(reader) .await .expect("schema succeeds"); stream.attach_telemetry(telemetry); - let error = if volume { + let error = if !matches!(case, Case::Reader) { + let state = crate::volume::VolumeState::new(Default::default(), None); stream.attach_volume( true, - crate::volume::VolumeState::new(Default::default(), None), + state.clone(), Arc::new( crate::client::DatabricksHttpClient::with_default_retry(Default::default()) .unwrap() .storage_client(None), ), ); - stream - .complete_volume_operation(&Default::default(), None) + if matches!(case, Case::CachedCancellation) { + state.cancel(); + } + let options = Default::default(); + let completion = stream.complete_volume_operation(&options, None); + let result = if matches!(case, Case::Cancellation) { + tokio::time::timeout(Duration::from_secs(5), async { + tokio::join!(completion, async { + entered.notified().await; + state.cancel(); + }) + .0 + }) + .await + .expect("cancellation must interrupt the blocked reader") + } else { + completion.await + }; + let error = + result.expect_err("Volume completion should surface the terminal error"); + let cached = stream + .complete_volume_operation(&options, None) .await - .expect_err("instruction drain should surface reader error") + .unwrap_err(); + assert_eq!(cached.code, error.code); + assert_eq!(cached.message, error.message); + error } else { stream .peek_first_batch() @@ -421,7 +483,7 @@ mod tests { .map(|_| ()) .expect_err("peek should surface reader error") }; - assert_eq!(error.code, ErrorCode::Internal); + assert_eq!(error.code, code); assert_eq!(error.message, message); let events_before_drop = connection .statement_events @@ -430,7 +492,7 @@ mod tests { .len(); assert_eq!( events_before_drop, 1, - "reader error must finalize before Drop" + "terminal error must finalize before Drop" ); drop(stream); @@ -439,11 +501,11 @@ mod tests { assert_eq!( events.len(), 1, - "reader error should finalize once; Drop must not overwrite it with success" + "terminal error should finalize once; Drop must not overwrite it with success" ); let event = &events[0]; assert_eq!(event.context.statement_type, StatementType::Sql); - assert_eq!(event.error_code, Some(ErrorCode::Internal)); + assert_eq!(event.error_code, Some(code)); assert_eq!(event.error_message.as_deref(), Some(message)); assert!( event.context.consumption_latency.is_some(), From 973e4bb836173f5c92ac68210dbf2a9effa4b455 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Wed, 18 Nov 2026 03:32:58 +0000 Subject: [PATCH 37/63] fix(volume): overwrite writable files in restricted directories Signed-off-by: Aakash Saravanan --- README.md | 10 +++-- src/volume.rs | 106 ++++++++++++++++++++++++++++++++++++++------------ 2 files changed, 89 insertions(+), 27 deletions(-) diff --git a/README.md b/README.md index 1f6842fe..2f2d3245 100644 --- a/README.md +++ b/README.md @@ -76,8 +76,8 @@ rows. The PyO3 `ExecutedStatement` and `ResultStream` classes expose `is_volume_operation` and `complete_volume_operation`. Local filesystem setup and download publication are synchronous. Cancellation -cannot interrupt a blocked filesystem call and can wait for the atomic rename -that publishes a completed GET. +cannot interrupt a blocked filesystem call and can wait for publication of a +completed GET. A PUT instruction with `localFile == "__input_stream__"` returns `NeedsInputStream` until owned input bytes are supplied. An empty byte buffer is a @@ -93,7 +93,11 @@ additional lexical paths. Paths are normalized lexically before symlink resolution. Allowed-root validation assumes path components remain unchanged between validation and file access. -GET replaces the destination only after a complete download. Transfer failures +GET stages the complete download before publishing it. When the destination +directory permits temporary-file creation, publication atomically replaces the +destination. Otherwise, an existing writable file can be updated in place using +private storage in the system temporary directory. That final write is not +atomic and a local write failure can leave partial contents. Download failures and cancellation before publication preserve the destination's existing bytes. Repeated completion on the same execution reuses its outcome, including errors. diff --git a/src/volume.rs b/src/volume.rs index 0e8e9512..4cfa4e40 100644 --- a/src/volume.rs +++ b/src/volume.rs @@ -257,13 +257,9 @@ impl VolumeState { }; let mut destination = if instruction.operation == "GET" { let path = local_path.as_ref().expect("GET path was checked"); - // Match normal write permissions even though publication uses replacement. - let permissions = match std::fs::OpenOptions::new().write(true).open(path) { - Ok(file) => Some( - file.metadata() - .map_err(|e| local_error(e, &instruction.local_file))? - .permissions(), - ), + // Replacement must still honor the destination's write permissions. + let existing = match std::fs::OpenOptions::new().write(true).open(path) { + Ok(file) => Some(file), Err(error) if error.kind() == std::io::ErrorKind::NotFound => None, Err(error) => return Err(local_error(error, &instruction.local_file)), }; @@ -276,23 +272,39 @@ impl VolumeState { use std::os::unix::fs::PermissionsExt; builder.permissions(std::fs::Permissions::from_mode(0o666)); } - let temp = builder - .tempfile_in( - path.parent() - .ok_or_else(|| invalid("Missing destination parent"))?, - ) - .map_err(|e| local_error(e, &instruction.local_file))?; - if let Some(permissions) = permissions { - temp.as_file() - .set_permissions(permissions) - .map_err(|e| local_error(e, &instruction.local_file))?; - } + let (temp, in_place) = match builder.tempfile_in( + path.parent() + .ok_or_else(|| invalid("Missing destination parent"))?, + ) { + Ok(temp) => { + if let Some(file) = existing { + temp.as_file() + .set_permissions( + file.metadata() + .map_err(|e| local_error(e, &instruction.local_file))? + .permissions(), + ) + .map_err(|e| local_error(e, &instruction.local_file))?; + } + (temp, None) + } + Err(error) + if error.kind() == std::io::ErrorKind::PermissionDenied + && existing.is_some() => + { + // An existing file may be writable without permission to replace its entry. + let temp = tempfile::NamedTempFile::new() + .map_err(|e| local_error(e, &instruction.local_file))?; + (temp, existing) + } + Err(error) => return Err(local_error(error, &instruction.local_file)), + }; let writer = tokio::fs::File::from_std( temp.as_file() .try_clone() .map_err(|e| local_error(e, &instruction.local_file))?, ); - Some((temp, writer)) + Some((temp, writer, in_place)) } else { None }; @@ -401,14 +413,14 @@ impl VolumeState { }) .await? { - if let Some((_, writer)) = destination.as_mut() { + if let Some((_, writer, _)) = destination.as_mut() { writer .write_all(&bytes) .await .map_err(|e| local_error(e, &instruction.local_file))?; } } - if let Some((temp, mut writer)) = destination.take() { + if let Some((mut temp, mut writer, in_place)) = destination.take() { writer .flush() .await @@ -418,8 +430,17 @@ impl VolumeState { if let CommitState::Finished(result) = &*gate { return result.as_ref().clone(); } - temp.persist(local_path.as_ref().expect("GET destination")) - .map_err(|e| local_error(e.error, &instruction.local_file))?; + if let Some(mut file) = in_place { + std::io::Seek::rewind(temp.as_file_mut()) + .map_err(|e| local_error(e, &instruction.local_file))?; + let length = std::io::copy(temp.as_file_mut(), &mut file) + .map_err(|e| local_error(e, &instruction.local_file))?; + file.set_len(length) + .map_err(|e| local_error(e, &instruction.local_file))?; + } else { + temp.persist(local_path.as_ref().expect("GET destination")) + .map_err(|e| local_error(e.error, &instruction.local_file))?; + } *gate = CommitState::Finished(Box::new(Ok(VolumeCompletion::Completed))); } Ok(VolumeCompletion::Completed) @@ -1370,6 +1391,39 @@ mod tests { std::fs::set_permissions(&dest, std::fs::Permissions::from_mode(0o600)).unwrap(); } assert_eq!(std::fs::read(&dest).unwrap(), b"new bytes"); + #[cfg(unix)] + { + std::fs::set_permissions(dir.path(), std::fs::Permissions::from_mode(0o500)).unwrap(); + if tempfile::tempfile_in(dir.path()) + .is_err_and(|error| error.kind() == std::io::ErrorKind::PermissionDenied) + { + std::fs::write(&dest, b"old bytes with a longer tail").unwrap(); + std::fs::set_permissions(&dest, std::fs::Permissions::from_mode(0o200)).unwrap(); + Mock::given(method("GET")) + .and(path("/in-place")) + .respond_with(ResponseTemplate::new(200).set_body_bytes(b"new bytes")) + .expect(1) + .mount(&server) + .await; + let batch = instruction("GET", &format!("{}/in-place", server.uri()), &dest); + let state = transfer_state(0); + assert_eq!( + state + .complete(&batch, &Client::new(), &options(dir.path()), None) + .await + .unwrap(), + VolumeCompletion::Completed + ); + assert_eq!( + std::fs::metadata(&dest).unwrap().permissions().mode() & 0o777, + 0o200 + ); + std::fs::set_permissions(&dest, std::fs::Permissions::from_mode(0o600)).unwrap(); + assert_eq!(std::fs::read(&dest).unwrap(), b"new bytes"); + } + } + #[cfg(unix)] + let requests = server.received_requests().await.unwrap().len(); let state = transfer_state(0); let batch = instruction( "GET", @@ -1407,9 +1461,13 @@ mod tests { assert_eq!(local.kind, "PermissionDenied"); assert_eq!(local.path, dest.to_string_lossy()); assert_eq!(std::fs::read(&dest).unwrap(), b"new bytes"); - assert_eq!(server.received_requests().await.unwrap().len(), 2); + assert_eq!( + server.received_requests().await.unwrap().len(), + requests + 1 + ); } std::fs::set_permissions(&dest, std::fs::Permissions::from_mode(0o600)).unwrap(); + std::fs::set_permissions(dir.path(), std::fs::Permissions::from_mode(0o700)).unwrap(); } assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 1); } From 7df0f4da92378d13a5ddbbf7c6b23061032a342f Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Wed, 18 Nov 2026 22:14:39 +0000 Subject: [PATCH 38/63] fix(volume): bound normalized symlink resolution Signed-off-by: Aakash Saravanan --- src/volume.rs | 43 ++++++++++++++++++++++++++++++++++++++----- 1 file changed, 38 insertions(+), 5 deletions(-) diff --git a/src/volume.rs b/src/volume.rs index 4cfa4e40..4b39dd64 100644 --- a/src/volume.rs +++ b/src/volume.rs @@ -605,11 +605,20 @@ fn normalize(path: &Path) -> Result { Ok(normalized) } -fn resolve_existing_parent(path: &Path, requested: &str) -> Result { +const MAX_SYMLINK_RESOLUTIONS: u8 = 40; + +fn resolve_existing_parent( + path: &Path, + requested: &str, + remaining_symlinks: u8, +) -> Result { match path.canonicalize() { Ok(path) => Ok(path), Err(error) if error.kind() == std::io::ErrorKind::NotFound => { if std::fs::symlink_metadata(path).is_ok_and(|m| m.file_type().is_symlink()) { + if remaining_symlinks == 0 { + return Err(local_error(error, requested)); + } let target = std::fs::read_link(path).map_err(|e| local_error(e, requested))?; let target = if target.is_absolute() { target @@ -618,13 +627,17 @@ fn resolve_existing_parent(path: &Path, requested: &str) -> Result { .ok_or_else(|| invalid("Invalid local path"))? .join(target) }; - return resolve_existing_parent(&normalize(&target)?, requested); + return resolve_existing_parent( + &normalize(&target)?, + requested, + remaining_symlinks - 1, + ); } let parent = path.parent().ok_or_else(|| local_error(error, requested))?; let name = path .file_name() .ok_or_else(|| invalid("Invalid local path"))?; - Ok(resolve_existing_parent(parent, requested)?.join(name)) + Ok(resolve_existing_parent(parent, requested, remaining_symlinks)?.join(name)) } Err(error) => Err(local_error(error, requested)), } @@ -662,10 +675,14 @@ fn allowed_path(requested: &str, roots: &[PathBuf]) -> Result { "Local file path is outside the configured allowed roots", )); } - let resolved = resolve_existing_parent(&path, requested)?; + let resolved = resolve_existing_parent(&path, requested, MAX_SYMLINK_RESOLUTIONS)?; let mut root_error = None; for root in roots { - let root = match resolve_existing_parent(&root, &root.to_string_lossy()) { + let root = match resolve_existing_parent( + &root, + &root.to_string_lossy(), + MAX_SYMLINK_RESOLUTIONS, + ) { Ok(root) => root, Err(error) => { root_error.get_or_insert(error); @@ -1791,6 +1808,22 @@ mod tests { error.local_error.unwrap().path, looping_root.to_string_lossy() ); + symlink_dir(&other, root.join("link")).unwrap(); + for (name, suffix) in [("cycle", ""), ("nested", "missing")] { + let cycle = root.join(name); + let target = Path::new("link").join("..").join(name).join(suffix); + symlink_file(target, &cycle).unwrap(); + let requested = cycle.to_str().unwrap(); + let error = allowed_path(requested, std::slice::from_ref(&root)).unwrap_err(); + let local = error.local_error.unwrap(); + assert_eq!(local.path, requested); + #[cfg(unix)] + { + assert_eq!(error.code, crate::ErrorCode::NotFound); + assert_eq!(local.kind, "NotFound"); + assert_eq!(local.raw_os_error, Some(2)); + } + } assert!(allowed_path(root.join("../other/missing").to_str().unwrap(), &[root]).is_err()); } From 0d8395dcf5729d97063bac1fb841e1c81b3087bb Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Thu, 19 Nov 2026 04:00:37 +0000 Subject: [PATCH 39/63] refactor(volume): use typed completion and cancellation tokens Signed-off-by: Aakash Saravanan --- README.md | 39 +- adbc/src/error.rs | 2 +- include/databricks_kernel.h | 12 +- napi/index.d.ts | 10 +- napi/index.js | 3 +- napi/src/async_statement.rs | 4 +- napi/src/error.rs | 7 +- napi/src/result.rs | 18 + napi/src/statement.rs | 8 +- pyo3/src/errors.rs | 2 +- pyo3/src/lib.rs | 1 + pyo3/src/result_stream.rs | 22 +- pyo3/src/statement.rs | 4 +- src/c_abi/error.rs | 22 +- src/c_abi/result.rs | 142 ++--- src/client/http.rs | 35 +- src/client/http_tls_tests.rs | 2 +- src/kernel_error.rs | 10 +- src/result_stream.rs | 81 ++- src/session.rs | 32 +- src/telemetry/statement.rs | 105 +--- src/volume.rs | 996 ++++++++++------------------------- tests/v0_volume_wiremock.rs | 16 +- 23 files changed, 514 insertions(+), 1059 deletions(-) diff --git a/README.md b/README.md index 2f2d3245..4ef32a2a 100644 --- a/README.md +++ b/README.md @@ -68,38 +68,13 @@ and security vulnerabilities should be reported according to ## Volume file operations -`ResultStream::complete_volume_operation` completes server-marked SQL PUT, GET, -and REMOVE instructions. Pass `VolumeOptions` with the local roots authorized for -PUT and GET. Completion preserves the instruction rows; callers that want the raw -result can omit completion. Complete the operation before reading its instruction -rows. The PyO3 `ExecutedStatement` and `ResultStream` classes expose -`is_volume_operation` and `complete_volume_operation`. - -Local filesystem setup and download publication are synchronous. Cancellation -cannot interrupt a blocked filesystem call and can wait for publication of a -completed GET. - -A PUT instruction with `localFile == "__input_stream__"` returns -`NeedsInputStream` until owned input bytes are supplied. An empty byte buffer is a -valid upload. Other statements do not request or consume input bytes. - -Local paths must satisfy both the lexical allowed-root check and a resolved-target -check. Symlinks within the configured roots are permitted, including links between -two authorized roots. Symlinks that resolve outside all authorized roots are -rejected. This is stricter than the lexical-only checks in existing Python and -Node.js Thrift transfer paths. An allowed root's symlink alias does not authorize -additional lexical paths. - -Paths are normalized lexically before symlink resolution. Allowed-root validation -assumes path components remain unchanged between validation and file access. - -GET stages the complete download before publishing it. When the destination -directory permits temporary-file creation, publication atomically replaces the -destination. Otherwise, an existing writable file can be updated in place using -private storage in the system temporary directory. That final write is not -atomic and a local write failure can leave partial contents. Download failures -and cancellation before publication preserve the destination's existing bytes. -Repeated completion on the same execution reuses its outcome, including errors. +Call `ResultStream::complete_volume_operation` with `VolumeOptions` to complete +server-marked PUT, GET and REMOVE instructions before reading their rows. Omit +completion for raw results. File paths must satisfy the configured lexical and +resolved roots. Stream PUT returns `NeedsInputStream` until owned bytes are supplied. +Completion caches its outcome, including errors; owner/session close cancels pending +work. See [`VolumeOptions`](https://docs.rs/databricks-sql-kernel/latest/databricks_sql_kernel/struct.VolumeOptions.html) +for local file and transfer behavior. ## License diff --git a/adbc/src/error.rs b/adbc/src/error.rs index 17584693..81c96097 100644 --- a/adbc/src/error.rs +++ b/adbc/src/error.rs @@ -64,7 +64,7 @@ pub(crate) fn map_kernel_error(source: kernel::Error) -> Error { let details = mapped.details.get_or_insert_default(); details.push(( "databricks.local_error_kind".into(), - local.kind.into_bytes(), + format!("{:?}", local.kind).into_bytes(), )); details.push(("databricks.local_path".into(), local.path.into_bytes())); if let Some(errno) = local.raw_os_error { diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h index 2312c24e..6dc7380f 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -195,7 +195,6 @@ bool kernel_get_last_error(KernelError* out); * error-clearing kernel call; absent strings are NULL, absent OS code is zero. */ int32_t kernel_get_last_error_local_os_error(void); const char* kernel_get_last_error_code(void); -const char* kernel_get_last_error_local_kind(void); const char* kernel_get_last_error_local_path(void); /* ─── Opaque handles ────────────────────────────────────────────────── @@ -974,8 +973,13 @@ KernelStatusCode kernel_executed_async_statement_close( */ KernelStatusCode kernel_result_stream_get_schema(kernel_result_stream_t* stream, struct ArrowSchema* out); -/* Volume completion preserves raw rows. Roots are a JSON array of strings; - * out_status is 0=ordinary result, 1=input bytes required, 2=completed. +typedef enum KernelVolumeCompletion { + KernelVolumeCompletion_NotVolume = 0, + KernelVolumeCompletion_NeedsInputStream = 1, + KernelVolumeCompletion_Completed = 2 +} KernelVolumeCompletion; + +/* Volume completion preserves raw rows. Roots are a JSON array of strings. * The detached result-stream canceller can interrupt completion. */ KernelStatusCode kernel_executed_statement_is_volume_operation( const kernel_executed_statement_t* exec, bool* out); @@ -984,7 +988,7 @@ KernelStatusCode kernel_result_stream_is_volume_operation( const kernel_result_stream_t* stream, bool* out); KernelStatusCode kernel_result_stream_complete_volume_operation( kernel_result_stream_t* stream, const char* allowed_paths_json, - bool remove_not_found_is_success, int32_t* out_status); + bool remove_not_found_is_success, KernelVolumeCompletion* out_status); KernelStatusCode kernel_result_stream_next_batch(kernel_result_stream_t* stream, struct ArrowArray* out_array, diff --git a/napi/index.d.ts b/napi/index.d.ts index 9037702f..4e29856a 100644 --- a/napi/index.d.ts +++ b/napi/index.d.ts @@ -879,7 +879,7 @@ export declare class AsyncStatement { export declare class AsyncResultHandle { get isVolumeOperation(): boolean /** Completes marked file transfers and retains the instruction rows. */ - completeVolumeOperation(allowedPaths: Array, removeNotFoundIsSuccess?: boolean | undefined | null): Promise + completeVolumeOperation(allowedPaths: Array, removeNotFoundIsSuccess?: boolean | undefined | null): Promise /** * Server-issued statement id. Cached at construction; readable * for log correlation. Matches the parent `AsyncStatement`'s @@ -1176,7 +1176,7 @@ export declare class Connection { export declare class Statement { get isVolumeOperation(): boolean /** Completes marked file transfers and retains the instruction rows. */ - completeVolumeOperation(allowedPaths: Array, removeNotFoundIsSuccess?: boolean | undefined | null): Promise + completeVolumeOperation(allowedPaths: Array, removeNotFoundIsSuccess?: boolean | undefined | null): Promise /** * Server-issued statement id. Cached at construction; readable * even after `close()` so JS-side log lines can correlate against @@ -1299,3 +1299,9 @@ export declare class Statement { */ close(): Promise } + +export const enum VolumeCompletion { + NotVolume = 'not_volume', + NeedsInputStream = 'needs_input_stream', + Completed = 'completed' +} diff --git a/napi/index.js b/napi/index.js index ad50ecc9..104cb552 100644 --- a/napi/index.js +++ b/napi/index.js @@ -310,7 +310,7 @@ if (!nativeBinding) { throw new Error(`Failed to load native binding`) } -const { AsyncStatement, AsyncResultHandle, CancellableExecution, Connection, AuthMode, openSession, initKernelLogging, kernelLoggingStats, setKernelLogLevel, Statement, version } = nativeBinding +const { AsyncStatement, AsyncResultHandle, CancellableExecution, Connection, AuthMode, openSession, initKernelLogging, kernelLoggingStats, setKernelLogLevel, Statement, VolumeCompletion, version } = nativeBinding module.exports.AsyncStatement = AsyncStatement module.exports.AsyncResultHandle = AsyncResultHandle @@ -323,3 +323,4 @@ module.exports.kernelLoggingStats = kernelLoggingStats module.exports.setKernelLogLevel = setKernelLogLevel module.exports.Statement = Statement module.exports.version = version +module.exports.VolumeCompletion = VolumeCompletion diff --git a/napi/src/async_statement.rs b/napi/src/async_statement.rs index b5c953e3..5f0a8a6d 100644 --- a/napi/src/async_statement.rs +++ b/napi/src/async_statement.rs @@ -498,7 +498,7 @@ impl AsyncResultHandle { &self, allowed_paths: Vec, remove_not_found_is_success: Option, - ) -> napi::Result { + ) -> napi::Result { let options = VolumeOptions { allowed_paths: allowed_paths.into_iter().map(Into::into).collect(), remove_not_found_is_success: remove_not_found_is_success.unwrap_or(false), @@ -511,7 +511,7 @@ impl AsyncResultHandle { .ok_or_else(|| closed_err("AsyncResultHandle"))? .complete_volume_operation(&options, None) .await - .map(|status| status.as_str().to_owned()) + .map(crate::result::VolumeCompletion::from) .map_err(napi_err_from_kernel) }) .await diff --git a/napi/src/error.rs b/napi/src/error.rs index 7f52d897..a12070f9 100644 --- a/napi/src/error.rs +++ b/napi/src/error.rs @@ -147,7 +147,10 @@ pub(crate) fn napi_err_from_kernel(e: KernelError) -> NapiError { if let Some(errno) = local.raw_os_error { obj.insert("localOsError".to_owned(), Value::from(errno)); } - obj.insert("localErrorKind".to_owned(), Value::from(local.kind)); + obj.insert( + "localErrorKind".to_owned(), + Value::from(format!("{:?}", local.kind)), + ); obj.insert("localPath".to_owned(), Value::from(local.path)); } // Thrift-parity extended status fields: surfaced on the napi @@ -208,7 +211,7 @@ mod tests { let mut error = KernelError::not_found().message("missing local file"); error.local_error = Some(Box::new(databricks_sql_kernel::LocalFileError { raw_os_error: Some(2), - kind: "NotFound".into(), + kind: std::io::ErrorKind::NotFound, path: "local-file".into(), })); let encoded = napi_err_from_kernel(error); diff --git a/napi/src/result.rs b/napi/src/result.rs index 2573bb84..80907046 100644 --- a/napi/src/result.rs +++ b/napi/src/result.rs @@ -94,6 +94,24 @@ pub(crate) fn encode_ipc_stream( Ok(buf) } +#[napi(string_enum = "snake_case")] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum VolumeCompletion { + NotVolume, + NeedsInputStream, + Completed, +} + +impl From for VolumeCompletion { + fn from(value: databricks_sql_kernel::VolumeCompletion) -> Self { + match value { + databricks_sql_kernel::VolumeCompletion::NotVolume => Self::NotVolume, + databricks_sql_kernel::VolumeCompletion::NeedsInputStream => Self::NeedsInputStream, + databricks_sql_kernel::VolumeCompletion::Completed => Self::Completed, + } + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/napi/src/statement.rs b/napi/src/statement.rs index c8056a9f..112bd683 100644 --- a/napi/src/statement.rs +++ b/napi/src/statement.rs @@ -208,7 +208,7 @@ impl Statement { &self, allowed_paths: Vec, remove_not_found_is_success: Option, - ) -> napi::Result { + ) -> napi::Result { let options = VolumeOptions { allowed_paths: allowed_paths.into_iter().map(Into::into).collect(), remove_not_found_is_success: remove_not_found_is_success.unwrap_or(false), @@ -223,7 +223,7 @@ impl Statement { stream .complete_volume_operation(&options, None) .await - .map(|status| status.as_str().to_owned()) + .map(crate::result::VolumeCompletion::from) .map_err(napi_err_from_kernel) }) .await @@ -709,7 +709,7 @@ mod tests { .complete_volume_operation(vec![], None) .await .unwrap(), - "completed" + crate::result::VolumeCompletion::Completed ); let batch = result.fetch_next_batch().await.unwrap().unwrap(); owner.close().await.unwrap(); @@ -723,7 +723,7 @@ mod tests { .complete_volume_operation(vec![], None) .await .unwrap(), - "completed" + crate::result::VolumeCompletion::Completed ); let batch = result.fetch_next_batch().await.unwrap().unwrap(); result.close().await.unwrap(); diff --git a/pyo3/src/errors.rs b/pyo3/src/errors.rs index 7229ced3..fc11becd 100644 --- a/pyo3/src/errors.rs +++ b/pyo3/src/errors.rs @@ -157,7 +157,7 @@ pub(crate) fn to_py_err(py: Python<'_>, err: KError) -> PyErr { let local = err.local_error.as_ref(); if let Err(error) = (|| -> PyResult<()> { bound.setattr("local_os_error", local.and_then(|e| e.raw_os_error))?; - bound.setattr("local_error_kind", local.map(|e| e.kind.as_str()))?; + bound.setattr("local_error_kind", local.map(|e| format!("{:?}", e.kind)))?; bound.setattr("local_path", local.map(|e| e.path.as_str()))?; Ok(()) })() { diff --git a/pyo3/src/lib.rs b/pyo3/src/lib.rs index 9ce1afb1..7220654d 100644 --- a/pyo3/src/lib.rs +++ b/pyo3/src/lib.rs @@ -84,6 +84,7 @@ fn databricks_sql_kernel(m: &Bound<'_, PyModule>) -> PyResult<()> { m.add_class::()?; m.add_class::()?; m.add_class::()?; + m.add_class::()?; m.add_function(wrap_pyfunction!(init_logging, m)?)?; m.add_function(wrap_pyfunction!(reset_logging, m)?)?; diff --git a/pyo3/src/result_stream.rs b/pyo3/src/result_stream.rs index aaf5888d..1f9a62ad 100644 --- a/pyo3/src/result_stream.rs +++ b/pyo3/src/result_stream.rs @@ -54,6 +54,24 @@ impl ResultStream { } } +#[pyclass(eq, skip_from_py_object)] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum VolumeCompletion { + NotVolume, + NeedsInputStream, + Completed, +} + +impl From for VolumeCompletion { + fn from(value: databricks_sql_kernel::VolumeCompletion) -> Self { + match value { + databricks_sql_kernel::VolumeCompletion::NotVolume => Self::NotVolume, + databricks_sql_kernel::VolumeCompletion::NeedsInputStream => Self::NeedsInputStream, + databricks_sql_kernel::VolumeCompletion::Completed => Self::Completed, + } + } +} + #[pymethods] impl ResultStream { #[getter] @@ -69,7 +87,7 @@ impl ResultStream { allowed_paths: Vec, remove_not_found_is_success: bool, input_bytes: Option>, - ) -> PyResult<&'static str> { + ) -> PyResult { let inner = alive_mut!(self, "ResultStream"); let runtime = inner.runtime.clone(); let options = databricks_sql_kernel::VolumeOptions { @@ -82,7 +100,7 @@ impl ResultStream { &runtime, stream.complete_volume_operation(&options, input_bytes) )?; - Ok(outcome.as_str()) + Ok(outcome.into()) } /// Result schema as a `pyarrow.Schema`. Available even after `close()`. diff --git a/pyo3/src/statement.rs b/pyo3/src/statement.rs index 321f5386..61072e10 100644 --- a/pyo3/src/statement.rs +++ b/pyo3/src/statement.rs @@ -334,7 +334,7 @@ impl ExecutedStatement { allowed_paths: Vec, remove_not_found_is_success: bool, input_bytes: Option>, - ) -> PyResult<&'static str> { + ) -> PyResult { let inner = alive_mut!(self, "ExecutedStatement"); let runtime = inner.runtime.clone(); let options = databricks_sql_kernel::VolumeOptions { @@ -347,7 +347,7 @@ impl ExecutedStatement { &runtime, stream.complete_volume_operation(&options, input_bytes) )?; - Ok(outcome.as_str()) + Ok(outcome.into()) } #[getter] diff --git a/src/c_abi/error.rs b/src/c_abi/error.rs index 7d1bab5c..92581035 100644 --- a/src/c_abi/error.rs +++ b/src/c_abi/error.rs @@ -56,7 +56,6 @@ pub struct KernelError { #[derive(Default)] struct LastError { local_os_error: i32, - local_kind: Option, local_path: Option, code: Option, message: Option, @@ -151,17 +150,6 @@ pub extern "C" fn kernel_get_last_error_code() -> *const c_char { }) } -/// Borrowed local error kind, or null. Valid until the next error-clearing call. -#[no_mangle] -pub extern "C" fn kernel_get_last_error_local_kind() -> *const c_char { - LAST_ERROR.with(|last| { - last.borrow() - .local_kind - .as_ref() - .map_or(std::ptr::null(), |s| s.as_ptr()) - }) -} - /// Borrowed requested local path, or null. Valid until the next error-clearing call. #[no_mangle] pub extern "C" fn kernel_get_last_error_local_path() -> *const c_char { @@ -199,7 +187,6 @@ pub(crate) fn store_error(err: Error) { .as_ref() .and_then(|e| e.raw_os_error) .unwrap_or(0), - local_kind: err.local_error.as_ref().map(|e| to_cstring_lossy(&e.kind)), local_path: err.local_error.as_ref().map(|e| to_cstring_lossy(&e.path)), code: Some(err.code), message: Some(to_cstring_lossy(&message)), @@ -248,17 +235,11 @@ mod tests { let mut error = Error::not_found().message("missing local file"); error.local_error = Some(Box::new(crate::kernel_error::LocalFileError { raw_os_error: Some(2), - kind: "NotFound".into(), + kind: std::io::ErrorKind::NotFound, path: "local-file".into(), })); store_error(error); assert_eq!(kernel_get_last_error_local_os_error(), 2); - assert_eq!( - unsafe { std::ffi::CStr::from_ptr(kernel_get_last_error_local_kind()) } - .to_str() - .unwrap(), - "NotFound" - ); assert_eq!( unsafe { std::ffi::CStr::from_ptr(kernel_get_last_error_local_path()) } .to_str() @@ -268,7 +249,6 @@ mod tests { with_last_error(|error| assert!(error.is_some())); clear_error(); assert_eq!(kernel_get_last_error_local_os_error(), 0); - assert!(kernel_get_last_error_local_kind().is_null()); assert!(kernel_get_last_error_local_path().is_null()); } diff --git a/src/c_abi/result.rs b/src/c_abi/result.rs index 67a1a614..dc25ec30 100644 --- a/src/c_abi/result.rs +++ b/src/c_abi/result.rs @@ -675,8 +675,7 @@ pub unsafe extern "C" fn kernel_result_stream_is_volume_operation( } /// Complete a marked instruction while preserving its result rows. -/// `allowed_paths_json` is a JSON array of strings. Status is 0 (ordinary result), -/// 1 (owned input bytes required) or 2 (completed). This API supplies no input bytes. +/// `allowed_paths_json` is a JSON array of strings. This API supplies no input bytes. /// # Safety /// `stream` must be live with exclusive fetch access, `allowed_paths_json` must /// be NUL-terminated UTF-8, and `out_status` must be writable. @@ -685,7 +684,7 @@ pub unsafe extern "C" fn kernel_result_stream_complete_volume_operation( stream: *mut kernel_result_stream_t, allowed_paths_json: *const std::ffi::c_char, remove_not_found_is_success: bool, - out_status: *mut i32, + out_status: *mut crate::VolumeCompletion, ) -> KernelStatusCode { catch_ffi(|| { if stream.is_null() || allowed_paths_json.is_null() || out_status.is_null() { @@ -724,14 +723,7 @@ pub unsafe extern "C" fn kernel_result_stream_complete_volume_operation( }; match result { Ok(status) => { - std::ptr::write( - out_status, - match status { - crate::VolumeCompletion::NotVolume => 0, - crate::VolumeCompletion::NeedsInputStream => 1, - crate::VolumeCompletion::Completed => 2, - }, - ); + std::ptr::write(out_status, status); KernelStatusCode::Success } Err(code) => code, @@ -772,7 +764,7 @@ mod tests { } #[test] - fn volume_completion_keeps_raw_rows_and_observes_detached_cancel() { + fn volume_completion_observes_detached_cancel() { use crate::reader::test_utils::MockReader; use crate::result_stream::ResultStream; use arrow_array::StringArray; @@ -792,84 +784,60 @@ mod tests { ) .unwrap(); let rt = tokio::runtime::Runtime::new().unwrap(); - for (marked, cancel) in [(false, false), (true, false), (true, true)] { - let volume = crate::volume::VolumeState::new(Default::default(), None); - let stream = rt.block_on(async { - let mut stream = - ResultStream::from_reader(Box::new(MockReader::new(vec![batch.clone()]))) - .await - .unwrap(); - stream.attach_volume( - marked, - Arc::clone(&volume), - Arc::new( - crate::client::DatabricksHttpClient::with_default_retry(Default::default()) - .unwrap() - .storage_client(None), - ), - ); - into_raw_result_stream(schema.clone(), stream) - }); - let mut is_volume = !marked; + let volume = crate::volume::VolumeState::new( + Default::default(), + None, + Default::default(), + Default::default(), + ); + let stream = rt.block_on(async { + let mut stream = + ResultStream::from_reader(Box::new(MockReader::new(vec![batch.clone()]))) + .await + .unwrap(); + stream.attach_volume( + true, + Arc::clone(&volume), + Arc::new( + crate::client::DatabricksHttpClient::with_default_retry(Default::default()) + .unwrap() + .storage_client(None), + ), + ); + into_raw_result_stream(schema.clone(), stream) + }); + let mut is_volume = false; + assert_eq!( + unsafe { kernel_result_stream_is_volume_operation(stream, &mut is_volume) }, + KernelStatusCode::Success + ); + assert!(is_volume); + let roots = CString::new("[]").unwrap(); + let mut status = crate::VolumeCompletion::NotVolume; + let mut canceller = std::ptr::null_mut(); + assert_eq!( + unsafe { kernel_result_stream_canceller_new(stream, &mut canceller) }, + KernelStatusCode::Success + ); + assert_eq!( + unsafe { kernel_result_stream_canceller_cancel(canceller) }, + KernelStatusCode::Success + ); + for _ in 0..2 { assert_eq!( - unsafe { kernel_result_stream_is_volume_operation(stream, &mut is_volume) }, - KernelStatusCode::Success + unsafe { + kernel_result_stream_complete_volume_operation( + stream, + roots.as_ptr(), + false, + &mut status, + ) + }, + KernelStatusCode::Cancelled ); - assert_eq!(is_volume, marked); - if marked && !cancel { - unsafe { kernel_result_stream_close(stream) }; - assert!(volume.cached().is_none()); - continue; - } - let roots = CString::new("[]").unwrap(); - let mut status = -1; - if marked { - let mut canceller = std::ptr::null_mut(); - assert_eq!( - unsafe { kernel_result_stream_canceller_new(stream, &mut canceller) }, - KernelStatusCode::Success - ); - assert_eq!( - unsafe { kernel_result_stream_canceller_cancel(canceller) }, - KernelStatusCode::Success - ); - for _ in 0..2 { - assert_eq!( - unsafe { - kernel_result_stream_complete_volume_operation( - stream, - roots.as_ptr(), - false, - &mut status, - ) - }, - KernelStatusCode::Cancelled - ); - } - unsafe { kernel_result_stream_canceller_free(canceller) }; - } else { - assert_eq!( - unsafe { - kernel_result_stream_complete_volume_operation( - stream, - roots.as_ptr(), - false, - &mut status, - ) - }, - KernelStatusCode::Success - ); - assert_eq!(status, 0); - let mut array = FFI_ArrowArray::empty(); - let mut schema = FFI_ArrowSchema::empty(); - assert_eq!( - unsafe { kernel_result_stream_next_batch(stream, &mut array, &mut schema) }, - KernelStatusCode::Success - ); - assert!(!array.is_released()); - } - unsafe { kernel_result_stream_close(stream) }; } + unsafe { kernel_result_stream_canceller_free(canceller) }; + unsafe { kernel_result_stream_close(stream) }; } /// End-of-stream on an Owned stream returns `Success` with a diff --git a/src/client/http.rs b/src/client/http.rs index 4a3edba4..de3d9bc4 100644 --- a/src/client/http.rs +++ b/src/client/http.rs @@ -390,22 +390,21 @@ pub struct DatabricksHttpClient { pub(crate) struct StorageClient { config: HttpClientConfig, - client: OnceLock>, + client: tokio::sync::OnceCell, } impl StorageClient { - pub(crate) fn get(&self) -> Result<&Client> { + pub(crate) async fn get(&self) -> Result<&Client> { self.client - .get_or_init(|| { - // File replay uses one redirect budget across all hops. + .get_or_try_init(|| async { DatabricksHttpClient::build_reqwest_client( &self.config, - reqwest::redirect::Policy::none(), + reqwest::redirect::Policy::default(), None, + false, ) }) - .as_ref() - .map_err(Clone::clone) + .await } } @@ -504,6 +503,7 @@ impl DatabricksHttpClient { &config, reqwest::redirect::Policy::default(), Some(config.read_timeout), + true, )?; // Surface which TLS backend was compiled in so oncall debugging @@ -540,12 +540,14 @@ impl DatabricksHttpClient { config: &HttpClientConfig, redirect: reqwest::redirect::Policy, request_timeout: Option, + referer: bool, ) -> Result { let mut builder = Client::builder() .connect_timeout(config.connect_timeout) .pool_max_idle_per_host(config.max_connections_per_host) .user_agent(&config.user_agent) - .redirect(redirect); + .redirect(redirect) + .referer(referer); if let Some(timeout) = request_timeout { builder = builder.timeout(timeout); } @@ -770,7 +772,7 @@ impl DatabricksHttpClient { } StorageClient { config, - client: OnceLock::new(), + client: tokio::sync::OnceCell::new(), } } @@ -847,6 +849,7 @@ impl DatabricksHttpClient { &self.config, reqwest::redirect::Policy::none(), Some(self.config.read_timeout), + true, )?; let response = client.get(url).send().await.map_err(|e| { Error::network_error().message(format!("Redirect-probe request to {url} failed: {e}")) @@ -1606,19 +1609,7 @@ lGrv15pBcePj let mut config = HttpClientConfig::default(); config.tls.trusted_certificate_path = Some(tmp.path().to_string_lossy().to_string()); - let client = DatabricksHttpClient::new(config, default_retry_configs()).unwrap(); - let storage = client.storage_client(None); - assert!(storage.client.get().is_none()); - std::fs::write(tmp.path(), "not a certificate").unwrap(); - let error = storage.get().unwrap_err(); - assert!(error.message.contains("Invalid PEM certificate"), "{error}"); - std::fs::write(tmp.path(), TEST_CA_CERT_PEM).unwrap(); - assert_eq!(storage.get().unwrap_err().message, error.message); - - let storage = client.storage_client(None); - let first = storage.get().unwrap(); - std::fs::write(tmp.path(), "not a certificate").unwrap(); - assert!(std::ptr::eq(first, storage.get().unwrap())); + assert!(DatabricksHttpClient::new(config, default_retry_configs()).is_ok()); } #[test] diff --git a/src/client/http_tls_tests.rs b/src/client/http_tls_tests.rs index a24d6d07..42355567 100644 --- a/src/client/http_tls_tests.rs +++ b/src/client/http_tls_tests.rs @@ -312,7 +312,7 @@ async fn storage_connection_timeout_preserves_unconfigured_limits() { ); for timeout in [None, Some(Duration::from_millis(100))] { let storage = client.storage_client(timeout); - let storage = storage.get().unwrap(); + let storage = storage.get().await.unwrap(); let deadline = if timeout.is_some() { Duration::from_millis(500) } else { diff --git a/src/kernel_error.rs b/src/kernel_error.rs index 4ff419a8..0de63179 100644 --- a/src/kernel_error.rs +++ b/src/kernel_error.rs @@ -41,10 +41,8 @@ //! Aborted, Unimplemented, …) lands in a follow-on PR. External //! `match` arms get a forced `_ =>` fallback — they keep compiling //! when the enum grows. -//! - `Error` **is not** `#[non_exhaustive]`, so adding public fields -//! breaks callers using struct literals or exhaustive patterns. Prefer -//! `Error::new(...).with_*(...)` and patterns with `..` to keep callers -//! independent of additional fields. +//! - `Error` **is not** `#[non_exhaustive]`: wrappers use struct patterns +//! with `..` for logging and host-language exception mapping. #![allow(dead_code)] @@ -167,8 +165,6 @@ impl ErrorCode { /// chain `with_*` setters. **Pattern-matching is supported** — /// wrappers writing a comprehensive logger or host-language exception /// adapter can do `let Error { code, message, sql_state, .. } = err;`. -/// Adding public fields breaks callers using struct literals or exhaustive -/// patterns; constructors and patterns with `..` avoid that coupling. #[derive(Debug, Clone)] pub struct Error { pub code: ErrorCode, @@ -254,7 +250,7 @@ pub struct Error { #[derive(Debug, Clone)] pub struct LocalFileError { pub raw_os_error: Option, - pub kind: String, + pub kind: std::io::ErrorKind, pub path: String, } diff --git a/src/result_stream.rs b/src/result_stream.rs index c21f852f..2b5171d1 100644 --- a/src/result_stream.rs +++ b/src/result_stream.rs @@ -58,7 +58,6 @@ use arrow_array::types::{ use arrow_array::{Array, RecordBatch}; use arrow_schema::{DataType, Schema, TimeUnit}; use chrono::{NaiveDate, NaiveDateTime}; -use std::collections::VecDeque; use std::sync::Arc; /// Cheap-clone reference to a result schema. The kernel hands one @@ -91,7 +90,7 @@ pub enum TryNextBatch<'a> { End, } -type Prefetched = VecDeque>>; +type Prefetched = Option>>; // `ResultBatch::into_arrow()` was deliberately removed: the // `#[non_exhaustive]` envelope is the right escape hatch already. @@ -608,7 +607,7 @@ impl ResultStream { reader: Some(reader), schema, current: None, - prefetched: VecDeque::new(), + prefetched: None, current_row_idx: 0, exhausted: false, close_guard: None, @@ -673,53 +672,42 @@ impl ResultStream { let Some((state, client)) = self.volume.clone() else { return Ok(crate::volume::VolumeCompletion::NotVolume); }; - let result = if let Some(result) = state.cached() { - result - } else { - tokio::select! { - biased; - error = state.cancellation() => Err(error), - result = async { + let result = state + .complete( + async { let batch = loop { - let batch = self - .peek_first_batch() - .await - .map_err(|error| state.fail(error))? - .ok_or_else(|| { - state.fail(Error::invalid_argument().message("Missing Volume instruction row")) - })?; + let batch = self.peek_first_batch().await?.ok_or_else(|| { + Error::invalid_argument().message("Missing Volume instruction row") + })?; let ResultBatch::Arrow(batch) = batch; if batch.num_rows() != 0 { - break ResultBatch::Arrow(batch.clone()); + break batch.clone(); } - self.prefetched.pop_front(); + self.prefetched.take(); }; - // The instruction stays buffered for callers; later batches must not - // authorize a partial transfer of a multi-row instruction result. + // Later batches cannot authorize a partial transfer of a multi-row result. while !self.exhausted { match self .reader .as_mut() .expect("Volume completion retains its reader") .next_batch() - .await - .map_err(|error| state.fail(error))? + .await? { Some(batch) if batch.num_rows() != 0 => { - self.prefetched.push_back(Ok(ResultBatch::Arrow(batch))); - return Err(state.fail( - Error::invalid_argument().message("Expected one Volume instruction row"), - )); + return Err(Error::invalid_argument() + .message("Expected one Volume instruction row")); } Some(_) => {} None => self.exhausted = true, } } - let client = client.get().map_err(|error| state.fail(error))?; - state.complete(&batch, client, options, input_bytes).await - } => result, - } - }; + Ok((batch, client.get().await?.clone())) + }, + options, + input_bytes, + ) + .await; if let Err(error) = &result { self.finalize_telemetry(Some(error)); } @@ -811,7 +799,7 @@ impl ResultStream { pub async fn next_batch(&mut self) -> Result> { // Replay inspected batches first so DML counts and Volume validation // do not consume callers' result rows. - if let Some(batch) = self.prefetched.pop_front() { + if let Some(batch) = self.prefetched.take() { self.set_current_batch(batch.map_err(|error| *error)?); return Ok(self.current.as_ref()); } @@ -845,7 +833,7 @@ impl ResultStream { /// Return the next batch if it is already available without waiting for /// network or background-prefetch progress. pub fn try_next_batch(&mut self) -> Result> { - if let Some(batch) = self.prefetched.pop_front() { + if let Some(batch) = self.prefetched.take() { self.set_current_batch(batch.map_err(|error| *error)?); return Ok(TryNextBatch::Ready( self.current.as_ref().expect("batch was just installed"), @@ -888,14 +876,14 @@ impl ResultStream { /// exhausted. A subsequent [`next_batch`](Self::next_batch) still returns /// the buffered outcome. pub(crate) async fn peek_first_batch(&mut self) -> Result> { - if self.prefetched.is_empty() && self.current.is_none() && !self.exhausted { + if self.prefetched.is_none() && self.current.is_none() && !self.exhausted { let reader = self .reader .as_mut() .expect("ResultStream reader is present until into_owned_batches consumes it"); match reader.next_batch().await { Ok(Some(rb)) => { - self.prefetched.push_back(Ok(ResultBatch::Arrow(rb))); + self.prefetched = Some(Ok(ResultBatch::Arrow(rb))); // Stamp first-batch (result-set-ready) latency at fetch // time, not when the caller later consumes the prefetched // batch via `next_batch`. `record_result_batch` is @@ -905,7 +893,7 @@ impl ResultStream { // result set became ready rather than the caller's // think-time before the first `next_batch` pull. if let (Some(telemetry), Some(Ok(batch))) = - (&self.telemetry, self.prefetched.front()) + (&self.telemetry, self.prefetched.as_ref()) { telemetry.record_batch(batch); } @@ -913,12 +901,12 @@ impl ResultStream { Ok(None) => self.exhausted = true, Err(e) => { self.finalize_telemetry(Some(&e)); - self.prefetched.push_back(Err(Box::new(e.clone()))); + self.prefetched = Some(Err(Box::new(e.clone()))); return Err(e); } } } - match self.prefetched.front() { + match self.prefetched.as_ref() { Some(Ok(batch)) => Ok(Some(batch)), Some(Err(error)) => Err((**error).clone()), None => Ok(None), @@ -1012,10 +1000,10 @@ impl ResultStream { /// after an `Err` keep returning `None`. pub fn into_owned_batches(mut self) -> OwnedBatchIter { // Inspected batches were pulled from the reader; yield them first to preserve row order. - let prefetched = std::mem::take(&mut self.prefetched) - .into_iter() - .map(|outcome| outcome.map(|ResultBatch::Arrow(rb)| rb)) - .collect(); + let prefetched = self + .prefetched + .take() + .map(|outcome| outcome.map(|ResultBatch::Arrow(rb)| rb)); OwnedBatchIter { reader: self .reader @@ -1063,7 +1051,7 @@ impl Iterator for OwnedBatchIter { if self.done { return None; } - if let Some(outcome) = self.prefetched.pop_front() { + if let Some(outcome) = self.prefetched.take() { return match outcome { Ok(batch) => { if let Some(telemetry) = &self.telemetry { @@ -1498,12 +1486,9 @@ mod tests { let b2 = RecordBatch::try_new(schema.clone(), vec![Arc::new(Int32Array::from(vec![3]))]) .unwrap(); let b3 = RecordBatch::try_new(schema, vec![Arc::new(Int32Array::from(vec![4]))]).unwrap(); - let reader = InMemoryReader::new(b1.schema(), vec![b1.clone(), b3.clone()]); + let reader = InMemoryReader::new(b1.schema(), vec![b1.clone(), b2.clone(), b3.clone()]); let mut stream = ResultStream::from_reader(Box::new(reader)).await.unwrap(); assert!(stream.peek_first_batch().await.unwrap().is_some()); - stream - .prefetched - .push_back(Ok(ResultBatch::Arrow(b2.clone()))); let mut iter = stream.into_owned_batches(); let first = iter.next().unwrap().unwrap(); diff --git a/src/session.rs b/src/session.rs index c52e6d4e..bbbea3eb 100644 --- a/src/session.rs +++ b/src/session.rs @@ -99,7 +99,8 @@ pub(crate) struct SessionInner { transport: Arc, storage_client: Arc, storage_retry: RetryConfig, - volume_states: std::sync::Mutex>>>, + volume_cancellation: tokio_util::sync::CancellationToken, + volume_publish: Arc>, /// Server-issued session identifier. session_id: String, @@ -162,30 +163,20 @@ pub(crate) struct SessionInner { impl SessionInner { pub(crate) fn new_volume_state(&self) -> Arc { - let state = crate::volume::VolumeState::new( + crate::volume::VolumeState::new( self.storage_retry.clone(), self.config.http.storage_read_timeout, - ); - let mut states = self.volume_states.lock().unwrap_or_else(|e| e.into_inner()); - if let Some(states) = states.as_mut() { - states.retain(|state| state.strong_count() != 0); - states.push(Arc::downgrade(&state)); - } else { - state.cancel(); - } - state + self.volume_cancellation.child_token(), + Arc::clone(&self.volume_publish), + ) } fn cancel_volume_operations(&self) { - let states = self - .volume_states + let _publish = self + .volume_publish .lock() - .unwrap_or_else(|e| e.into_inner()) - .take() - .unwrap_or_default(); - for state in states.into_iter().filter_map(|state| state.upgrade()) { - state.cancel(); - } + .unwrap_or_else(|e| e.into_inner()); + self.volume_cancellation.cancel(); } pub(crate) fn storage_client(&self) -> Arc { @@ -511,7 +502,8 @@ impl Session { transport, storage_client, storage_retry, - volume_states: std::sync::Mutex::new(Some(Vec::new())), + volume_cancellation: tokio_util::sync::CancellationToken::new(), + volume_publish: Default::default(), session_id: session_info.session_id, config, runtime_handle, diff --git a/src/telemetry/statement.rs b/src/telemetry/statement.rs index 07443d07..30951b45 100644 --- a/src/telemetry/statement.rs +++ b/src/telemetry/statement.rs @@ -292,9 +292,7 @@ fn duration_millis(duration: Duration) -> i64 { mod tests { use super::*; use crate::kernel_error::ErrorCode; - use crate::reader::test_utils::{ - BatchThenErrorReader, BlockingReader, ErrorReader, MockReader, - }; + use crate::reader::test_utils::{BatchThenErrorReader, MockReader}; use crate::reader::{ResultReader, ResultReaderMetrics}; use crate::result_stream::ResultStream; use crate::telemetry::models::OperationType; @@ -372,19 +370,10 @@ mod tests { #[tokio::test] async fn result_errors_finalize_statement_with_error_before_drop() { enum Case { - Reader, VolumeReader, Instruction, - Cancellation, - CachedCancellation, } - for case in [ - Case::Reader, - Case::VolumeReader, - Case::Instruction, - Case::Cancellation, - Case::CachedCancellation, - ] { + for case in [Case::VolumeReader, Case::Instruction] { let connection = Arc::new(CapturingConnectionTelemetry::default()); let telemetry = StatementTelemetry::new( connection.clone(), @@ -398,13 +387,7 @@ mod tests { &RecordBatchOptions::new().with_row_count(Some(1)), ) .expect("one-row batch"); - let entered = Arc::new(tokio::sync::Notify::new()); let (reader, code, message): (Box, _, _) = match case { - Case::Reader => ( - Box::new(ErrorReader { schema }), - ErrorCode::Internal, - "simulated read error", - ), Case::VolumeReader => ( Box::new(BatchThenErrorReader { batch: Some(batch), @@ -418,71 +401,37 @@ mod tests { ErrorCode::InvalidArgument, "Missing Volume instruction column", ), - Case::Cancellation => ( - Box::new(BlockingReader { - schema, - entered: entered.clone(), - release: Arc::new(tokio::sync::Notify::new()), - }), - ErrorCode::Cancelled, - "Volume transfer was cancelled", - ), - Case::CachedCancellation => ( - Box::new(MockReader::new(vec![batch])), - ErrorCode::Cancelled, - "Volume transfer was cancelled", - ), }; let mut stream = ResultStream::from_reader(reader) .await .expect("schema succeeds"); stream.attach_telemetry(telemetry); - let error = if !matches!(case, Case::Reader) { - let state = crate::volume::VolumeState::new(Default::default(), None); - stream.attach_volume( - true, - state.clone(), - Arc::new( - crate::client::DatabricksHttpClient::with_default_retry(Default::default()) - .unwrap() - .storage_client(None), - ), - ); - if matches!(case, Case::CachedCancellation) { - state.cancel(); - } - let options = Default::default(); - let completion = stream.complete_volume_operation(&options, None); - let result = if matches!(case, Case::Cancellation) { - tokio::time::timeout(Duration::from_secs(5), async { - tokio::join!(completion, async { - entered.notified().await; - state.cancel(); - }) - .0 - }) - .await - .expect("cancellation must interrupt the blocked reader") - } else { - completion.await - }; - let error = - result.expect_err("Volume completion should surface the terminal error"); - let cached = stream - .complete_volume_operation(&options, None) - .await - .unwrap_err(); - assert_eq!(cached.code, error.code); - assert_eq!(cached.message, error.message); - error - } else { - stream - .peek_first_batch() - .await - .map(|_| ()) - .expect_err("peek should surface reader error") - }; + stream.attach_volume( + true, + crate::volume::VolumeState::new( + Default::default(), + None, + Default::default(), + Default::default(), + ), + Arc::new( + crate::client::DatabricksHttpClient::with_default_retry(Default::default()) + .unwrap() + .storage_client(None), + ), + ); + let options = Default::default(); + let error = stream + .complete_volume_operation(&options, None) + .await + .unwrap_err(); + let cached = stream + .complete_volume_operation(&options, None) + .await + .unwrap_err(); + assert_eq!(cached.code, error.code); + assert_eq!(cached.message, error.message); assert_eq!(error.code, code); assert_eq!(error.message, message); let events_before_drop = connection diff --git a/src/volume.rs b/src/volume.rs index 4b39dd64..6e7d5272 100644 --- a/src/volume.rs +++ b/src/volume.rs @@ -16,17 +16,27 @@ use crate::client::retry::{calculate_backoff, RequestType, RetryConfig, RetryStrategy}; use crate::kernel_error::{Error, LocalFileError, Result}; -use crate::result_stream::ResultBatch; -use arrow_array::{Array, LargeStringArray, MapArray, StringArray, StringViewArray}; +use arrow_array::{Array, LargeStringArray, MapArray, RecordBatch, StringArray, StringViewArray}; use futures::TryStreamExt; use reqwest::{header::HeaderMap, Client, Method}; use std::path::{Component, Path, PathBuf}; +use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex}; use tokio::io::AsyncWriteExt; -use tokio::sync::Notify; +use tokio::sync::OnceCell; +use tokio_util::bytes::Bytes; use tokio_util::io::ReaderStream; +use tokio_util::sync::CancellationToken; /// Local file authorization and driver-specific storage response policy. +/// +/// Requested and resolved paths must be within allowed roots. Symlinks between +/// authorized roots work; path components must remain stable during file access. +/// GET stages downloads before publication. Sibling staging permits atomic +/// replacement; an existing writable file in a restricted directory uses private +/// temporary storage followed by a non-atomic copy, which can fail partially. +/// Download failure or cancellation before publication preserves existing bytes. +/// Filesystem setup and publication are synchronous and can delay cancellation. #[derive(Debug, Clone, Default)] pub struct VolumeOptions { pub allowed_paths: Vec, @@ -35,38 +45,22 @@ pub struct VolumeOptions { /// Result of explicitly completing a server-marked Volume instruction. #[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[repr(C)] pub enum VolumeCompletion { NotVolume, NeedsInputStream, Completed, } -impl VolumeCompletion { - pub fn as_str(self) -> &'static str { - match self { - Self::NotVolume => "not_volume", - Self::NeedsInputStream => "needs_input_stream", - Self::Completed => "completed", - } - } -} - -#[derive(Default)] -enum CommitState { - #[default] - Ready, - Running, - Finished(Box>), -} - /// The synchronous gate makes cancellation and local publication mutually exclusive. #[derive(Default)] pub(crate) struct VolumeState { retry: RetryConfig, read_timeout: Option, - serial: tokio::sync::Mutex<()>, - commit: Mutex, - changed: Notify, + completion: OnceCell>, + cancellation: CancellationToken, + publish: Arc>, + started: AtomicBool, } fn cancelled() -> Error { @@ -74,107 +68,67 @@ fn cancelled() -> Error { } impl VolumeState { - pub(crate) fn new(retry: RetryConfig, read_timeout: Option) -> Arc { + pub(crate) fn new( + retry: RetryConfig, + read_timeout: Option, + cancellation: CancellationToken, + publish: Arc>, + ) -> Arc { Arc::new(Self { retry, read_timeout, + cancellation, + publish, ..Self::default() }) } - pub(crate) fn cached(&self) -> Option> { - match &*self.commit.lock().unwrap_or_else(|e| e.into_inner()) { - CommitState::Finished(result) => Some(result.as_ref().clone()), - CommitState::Ready | CommitState::Running => None, - } - } - - pub(crate) fn fail(&self, error: Error) -> Error { - let mut gate = self.commit.lock().unwrap_or_else(|e| e.into_inner()); - match &*gate { - CommitState::Finished(result) => { - if let Err(existing) = result.as_ref() { - return existing.clone(); - } - } - CommitState::Ready => *gate = CommitState::Finished(Box::new(Err(error.clone()))), - CommitState::Running => {} - } - error - } - pub(crate) fn cancel(&self) { - let mut gate = self.commit.lock().unwrap_or_else(|e| e.into_inner()); - if !matches!(*gate, CommitState::Finished(_)) { - *gate = CommitState::Finished(Box::new(Err(cancelled()))); - self.changed.notify_waiters(); - } - } - - pub(crate) async fn cancellation(&self) -> Error { - loop { - let notified = self.changed.notified(); - tokio::pin!(notified); - notified.as_mut().enable(); - if matches!(self.cached(), Some(Err(error)) if error.code == crate::ErrorCode::Cancelled) - { - return cancelled(); - } - notified.await; - } + let _publish = self.publish.lock().unwrap_or_else(|e| e.into_inner()); + self.cancellation.cancel(); } pub(crate) async fn complete( &self, - batch: &ResultBatch, - client: &Client, + prepare: impl std::future::Future>, options: &VolumeOptions, input_bytes: Option>, ) -> Result { - let _serial = self.serial.lock().await; - { - let mut gate = self.commit.lock().unwrap_or_else(|e| e.into_inner()); - match &*gate { - CommitState::Finished(result) => return result.as_ref().clone(), - // Holding serialization proves that the previous initializer was dropped. - CommitState::Running => { - *gate = CommitState::Finished(Box::new(Err(cancelled()))); - return Err(cancelled()); - } - CommitState::Ready => {} - } - } - let instruction = Instruction::decode(batch); - let result = match instruction { - Ok(instruction) => { - if instruction.operation == "PUT" - && instruction.local_file == "__input_stream__" - && input_bytes.is_none() - { - return Ok(VolumeCompletion::NeedsInputStream); + match self + .completion + .get_or_try_init(|| async { + // An abandoned initializer must not replay an already-dispatched transfer. + if self.started.swap(true, Ordering::AcqRel) || self.cancellation.is_cancelled() { + return Ok(Err(cancelled())); } - { - let mut gate = self.commit.lock().unwrap_or_else(|e| e.into_inner()); - if let CommitState::Finished(result) = &*gate { - return result.as_ref().clone(); + let complete = async { + let (batch, client) = prepare.await?; + let instruction = Instruction::decode(&batch)?; + if matches!(instruction.operation, Operation::Put(Source::Stream)) + && input_bytes.is_none() + { + return Ok(VolumeCompletion::NeedsInputStream); } - // Running is a cancellation tombstone if this future is abandoned. - *gate = CommitState::Running; - } - tokio::select! { + self.transfer(instruction, &client, options, input_bytes) + .await + }; + let result = tokio::select! { biased; - result = self.transfer(instruction, client, options, input_bytes) => result, - _ = self.cancellation() => Err(cancelled()), + result = complete => result, + _ = self.cancellation.cancelled() => Err(cancelled()), + }; + if matches!(result, Ok(VolumeCompletion::NeedsInputStream)) { + self.started.store(false, Ordering::Release); + Err(VolumeCompletion::NeedsInputStream) + } else { + Ok(result) } - } - Err(error) => Err(error), - }; - let mut gate = self.commit.lock().unwrap_or_else(|e| e.into_inner()); - if let CommitState::Finished(result) = &*gate { - return result.as_ref().clone(); + }) + .await + { + Ok(result) => result.clone(), + Err(outcome) => Ok(outcome), } - *gate = CommitState::Finished(Box::new(result.clone())); - result } async fn transfer( @@ -184,12 +138,13 @@ impl VolumeState { options: &VolumeOptions, input_bytes: Option>, ) -> Result { - let input = - if instruction.operation == "PUT" && instruction.local_file == "__input_stream__" { - Some(input_bytes.ok_or_else(|| invalid("Missing input stream"))?) - } else { - None - }; + let input = if matches!(instruction.operation, Operation::Put(Source::Stream)) { + Some(Bytes::from( + input_bytes.ok_or_else(|| invalid("Missing input stream"))?, + )) + } else { + None + }; let started = std::time::Instant::now(); let mut attempt = 0; loop { @@ -199,7 +154,7 @@ impl VolumeState { &instruction, client, options, - input.as_deref(), + input.as_ref(), &mut retry_after, ) .await @@ -225,14 +180,14 @@ impl VolumeState { instruction: &Instruction, client: &Client, options: &VolumeOptions, - input: Option<&[u8]>, + input: Option<&Bytes>, retry_after: &mut Option, ) -> Result { - let method = match instruction.operation.as_str() { - "PUT" => Method::PUT, - "GET" => Method::GET, - "REMOVE" => Method::DELETE, - _ => return Err(invalid("Unsupported Volume operation")), + let (method, local_file) = match &instruction.operation { + Operation::Put(Source::File(path)) => (Method::PUT, path.to_string_lossy()), + Operation::Get(path) => (Method::GET, path.to_string_lossy()), + Operation::Put(Source::Stream) => (Method::PUT, std::borrow::Cow::Borrowed("")), + Operation::Remove => (Method::DELETE, std::borrow::Cow::Borrowed("")), }; let mut request = client .request(method, &instruction.url) @@ -243,25 +198,23 @@ impl VolumeState { reqwest::header::CONTENT_LENGTH, bytes.len().into(), )])) - .body(bytes.to_vec()); + .body(bytes.clone()); } - let local_path = if instruction.operation == "REMOVE" - || (instruction.operation == "PUT" && instruction.local_file == "__input_stream__") - { - None - } else { - Some(allowed_path( - &instruction.local_file, + let operation = match &instruction.operation { + Operation::Put(Source::File(_)) => Operation::Put(Source::File(allowed_path( + &local_file, &options.allowed_paths, - )?) + )?)), + Operation::Get(_) => Operation::Get(allowed_path(&local_file, &options.allowed_paths)?), + Operation::Put(Source::Stream) => Operation::Put(Source::Stream), + Operation::Remove => Operation::Remove, }; - let mut destination = if instruction.operation == "GET" { - let path = local_path.as_ref().expect("GET path was checked"); + let mut destination = if let Operation::Get(path) = &operation { // Replacement must still honor the destination's write permissions. let existing = match std::fs::OpenOptions::new().write(true).open(path) { Ok(file) => Some(file), Err(error) if error.kind() == std::io::ErrorKind::NotFound => None, - Err(error) => return Err(local_error(error, &instruction.local_file)), + Err(error) => return Err(local_error(error, &local_file)), }; #[cfg(unix)] let mut builder = tempfile::Builder::new(); @@ -281,10 +234,10 @@ impl VolumeState { temp.as_file() .set_permissions( file.metadata() - .map_err(|e| local_error(e, &instruction.local_file))? + .map_err(|e| local_error(e, &local_file))? .permissions(), ) - .map_err(|e| local_error(e, &instruction.local_file))?; + .map_err(|e| local_error(e, &local_file))?; } (temp, None) } @@ -293,105 +246,55 @@ impl VolumeState { && existing.is_some() => { // An existing file may be writable without permission to replace its entry. - let temp = tempfile::NamedTempFile::new() - .map_err(|e| local_error(e, &instruction.local_file))?; + let temp = + tempfile::NamedTempFile::new().map_err(|e| local_error(e, &local_file))?; (temp, existing) } - Err(error) => return Err(local_error(error, &instruction.local_file)), + Err(error) => return Err(local_error(error, &local_file)), }; let writer = tokio::fs::File::from_std( temp.as_file() .try_clone() - .map_err(|e| local_error(e, &instruction.local_file))?, + .map_err(|e| local_error(e, &local_file))?, ); - Some((temp, writer, in_place)) + Some((temp, writer, in_place, path)) } else { None }; - let retry_timeout = instruction.operation != "PUT"; - // File bodies must be reopened for redirects; reqwest can only clone owned bytes. - let mut request = request.build().map_err(storage_error)?; - let mut redirects = 0; - let mut response = loop { - let mut next = reqwest::RequestBuilder::from_parts( - client.clone(), - request.try_clone().expect("replayable request template"), - ); - let upload_error = Arc::new(Mutex::new(None)); - if request.method() == Method::PUT && input.is_none() { - let path = local_path.as_ref().expect("PUT path was checked"); - let mut file = std::fs::File::open(path) - .map_err(|e| local_error(e, &instruction.local_file))?; - let metadata = file - .metadata() - .map_err(|e| local_error(e, &instruction.local_file))?; - if metadata.is_dir() { - // Reading the opened directory retains the platform's filesystem cause. - let error = std::io::Read::read(&mut file, &mut [0]) - .err() - .unwrap_or_else(|| std::io::ErrorKind::IsADirectory.into()); - return Err(local_error(error, &instruction.local_file)); - } - next = next - .headers(HeaderMap::from_iter([( - reqwest::header::CONTENT_LENGTH, - metadata.len().into(), - )])) - .body(upload_body( - tokio::fs::File::from_std(file), - instruction.local_file.clone(), - Arc::clone(&upload_error), - )); - } - let response = storage_send( - next, - self.read_timeout, - request.method() == Method::PUT, - upload_error, - ) - .await?; - if !matches!(response.status().as_u16(), 301 | 302 | 303 | 307 | 308) { - break response; + let retry_timeout = !matches!(operation, Operation::Put(_)); + let upload_error = Arc::new(Mutex::new(None)); + if let Operation::Put(Source::File(path)) = &operation { + let mut file = std::fs::File::open(path).map_err(|e| local_error(e, &local_file))?; + let metadata = file.metadata().map_err(|e| local_error(e, &local_file))?; + if metadata.is_dir() { + // Reading the opened directory retains the platform's filesystem cause. + let error = std::io::Read::read(&mut file, &mut [0]) + .err() + .unwrap_or_else(|| std::io::ErrorKind::IsADirectory.into()); + return Err(local_error(error, &local_file)); } - let Some(url) = response - .headers() - .get(reqwest::header::LOCATION) - .and_then(|location| location.to_str().ok()) - .and_then(|location| response.url().join(location).ok()) - else { - break response; - }; - if redirects == 10 || !matches!(url.scheme(), "http" | "https") { - return Err(Error::network_error() - .with_error_code("VOLUME_STORAGE_NETWORK_ERROR") - .with_retryable(false) - .message(if redirects == 10 { - "Volume storage redirect limit exceeded" - } else { - "Volume storage redirect URL must use HTTP or HTTPS" - })); - } - redirects += 1; - let previous = response.url(); - redirect_headers(request.headers_mut(), previous, &url); - if response.status() == reqwest::StatusCode::SEE_OTHER { - *request.method_mut() = Method::GET; - *request.body_mut() = None; - for name in [ - "content-type", - "content-length", - "content-encoding", - "transfer-encoding", - ] { - request.headers_mut().remove(name); - } - } - *request.url_mut() = url; - }; + request = request + .headers(HeaderMap::from_iter([( + reqwest::header::CONTENT_LENGTH, + metadata.len().into(), + )])) + .body(upload_body( + tokio::fs::File::from_std(file), + local_file.to_string(), + Arc::clone(&upload_error), + )); + } + let mut response = storage_send( + request, + self.read_timeout, + matches!(operation, Operation::Put(_)), + upload_error, + ) + .await?; let status = response.status(); if !(status.is_success() - || (instruction.operation == "REMOVE" + || (matches!(operation, Operation::Remove) && status.as_u16() == 404 && options.remove_not_found_is_success)) { @@ -413,69 +316,39 @@ impl VolumeState { }) .await? { - if let Some((_, writer, _)) = destination.as_mut() { + if let Some((_, writer, _, _)) = destination.as_mut() { writer .write_all(&bytes) .await - .map_err(|e| local_error(e, &instruction.local_file))?; + .map_err(|e| local_error(e, &local_file))?; } } - if let Some((mut temp, mut writer, in_place)) = destination.take() { + if let Some((mut temp, mut writer, in_place, path)) = destination.take() { writer .flush() .await - .map_err(|e| local_error(e, &instruction.local_file))?; + .map_err(|e| local_error(e, &local_file))?; drop(writer); - let mut gate = self.commit.lock().unwrap_or_else(|e| e.into_inner()); - if let CommitState::Finished(result) = &*gate { - return result.as_ref().clone(); + let _publish = self.publish.lock().unwrap_or_else(|e| e.into_inner()); + if self.cancellation.is_cancelled() { + return Err(cancelled()); } if let Some(mut file) = in_place { std::io::Seek::rewind(temp.as_file_mut()) - .map_err(|e| local_error(e, &instruction.local_file))?; + .map_err(|e| local_error(e, &local_file))?; let length = std::io::copy(temp.as_file_mut(), &mut file) - .map_err(|e| local_error(e, &instruction.local_file))?; + .map_err(|e| local_error(e, &local_file))?; file.set_len(length) - .map_err(|e| local_error(e, &instruction.local_file))?; + .map_err(|e| local_error(e, &local_file))?; } else { - temp.persist(local_path.as_ref().expect("GET destination")) - .map_err(|e| local_error(e.error, &instruction.local_file))?; + temp.persist(path) + .map_err(|e| local_error(e.error, &local_file))?; } - *gate = CommitState::Finished(Box::new(Ok(VolumeCompletion::Completed))); } Ok(VolumeCompletion::Completed) } } -fn redirect_headers(headers: &mut HeaderMap, previous: &reqwest::Url, next: &reqwest::Url) { - if next.scheme() != previous.scheme() - || next.host_str() != previous.host_str() - || next.port_or_known_default() != previous.port_or_known_default() - { - for name in [ - "authorization", - "cookie", - "cookie2", - "proxy-authorization", - "www-authenticate", - ] { - headers.remove(name); - } - } - if previous.scheme() == "https" && next.scheme() == "http" { - headers.remove(reqwest::header::REFERER); - } else { - let mut referer = previous.clone(); - let _ = referer.set_username(""); - let _ = referer.set_password(None); - referer.set_query(None); - referer.set_fragment(None); - if let Ok(value) = referer.as_str().parse() { - headers.insert(reqwest::header::REFERER, value); - } - } -} - fn upload_body( reader: impl tokio::io::AsyncRead + Unpin + Send + 'static, path: String, @@ -535,18 +408,8 @@ async fn storage_read( } fn storage_error(error: reqwest::Error) -> Error { - // A file reader's failure is wrapped in a request error by the HTTP stack. - let source_body_failed = std::iter::successors( - Some(&error as &(dyn std::error::Error + 'static)), - |cause| cause.source(), - ) - .any(|cause| { - cause - .downcast_ref::() - .is_some_and(reqwest::Error::is_body) - }); - let retryable = !source_body_failed - && RetryStrategy::for_request(RequestType::CloudFetchDownload, &RetryConfig::default()) + let retryable = + RetryStrategy::for_request(RequestType::CloudFetchDownload, &RetryConfig::default()) .is_retryable_error(&error); let error = error.without_url(); let mut causes = crate::client::error_chain(&error) @@ -583,7 +446,7 @@ fn local_error(error: std::io::Error, path: &str) -> Error { .message(format!("{error}: {path}")); result.local_error = Some(Box::new(LocalFileError { raw_os_error: error.raw_os_error(), - kind: format!("{:?}", error.kind()), + kind: error.kind(), path: path.to_owned(), })); result @@ -701,11 +564,21 @@ fn allowed_path(requested: &str, roots: &[PathBuf]) -> Result { )) } +enum Source { + File(PathBuf), + Stream, +} + +enum Operation { + Put(Source), + Get(PathBuf), + Remove, +} + struct Instruction { - operation: String, + operation: Operation, url: String, headers: HeaderMap, - local_file: String, } fn string_at(array: &dyn Array, row: usize) -> Result<&str> { @@ -725,8 +598,7 @@ fn string_at(array: &dyn Array, row: usize) -> Result<&str> { } impl Instruction { - fn decode(batch: &ResultBatch) -> Result { - let ResultBatch::Arrow(batch) = batch; + fn decode(batch: &RecordBatch) -> Result { if batch.num_rows() != 1 { return Err(invalid("Expected one Volume instruction row")); } @@ -739,7 +611,7 @@ impl Instruction { .ok_or_else(|| invalid("Missing Volume instruction column"))?; Ok(batch.column(index).as_ref()) }; - let operation = string_at(column("operation")?, 0)?.to_owned(); + let operation = string_at(column("operation")?, 0)?; let headers = column("headers")?; let mut parsed_headers = HeaderMap::new(); let mut add_header = |name: &str, value: &str| -> Result<()> { @@ -770,16 +642,19 @@ impl Instruction { } } } - let local_file = if operation == "REMOVE" { - String::new() - } else { - string_at(column("localFile")?, 0)?.to_owned() + let operation = match operation { + "PUT" => match string_at(column("localFile")?, 0)? { + "__input_stream__" => Operation::Put(Source::Stream), + path => Operation::Put(Source::File(path.into())), + }, + "GET" => Operation::Get(string_at(column("localFile")?, 0)?.into()), + "REMOVE" => Operation::Remove, + _ => return Err(invalid("Unsupported Volume operation")), }; Ok(Self { operation, url: string_at(column("presignedUrl")?, 0)?.to_owned(), headers: parsed_headers, - local_file, }) } } @@ -796,7 +671,7 @@ mod tests { use wiremock::matchers::{body_bytes, header, method, path}; use wiremock::{Mock, MockServer, ResponseTemplate}; - fn instruction(operation: &str, url: &str, local: &Path) -> ResultBatch { + fn instruction(operation: &str, url: &str, local: &Path) -> RecordBatch { let mut headers = MapBuilder::new(None, StringBuilder::new(), StringBuilder::new()); headers.keys().append_value("x-storage-token"); headers.values().append_value("server-token"); @@ -814,7 +689,7 @@ mod tests { .map(|(name, values)| Field::new(*name, values.data_type().clone(), true)) .collect::>(), ); - ResultBatch::Arrow(RecordBatch::try_new(Arc::new(schema), arrays).unwrap()) + RecordBatch::try_new(Arc::new(schema), arrays).unwrap() } fn options(root: &Path) -> VolumeOptions { @@ -833,6 +708,8 @@ mod tests { ..Default::default() }, None, + Default::default(), + Default::default(), ) } @@ -878,296 +755,11 @@ mod tests { assert!(!error.message.contains("hidden")); } - #[tokio::test] - async fn transfers_follow_redirects_and_replay_file_and_owned_inputs() { - let dir = tempfile::tempdir().unwrap(); - let source = dir.path().join("source"); - for (operation, status, stream, payload) in [ - ("PUT", 307, false, vec![42; 512 * 1024 + 17]), - ("PUT", 308, false, vec![42; 512 * 1024 + 17]), - ("PUT", 307, true, vec![]), - ("PUT", 307, true, b"payload".to_vec()), - ("PUT", 308, true, b"payload".to_vec()), - ("GET", 307, false, b"downloaded".to_vec()), - ("REMOVE", 302, false, vec![]), - ] { - let server = MockServer::start().await; - let verb = if operation == "REMOVE" { - "DELETE" - } else { - operation - }; - Mock::given(method(verb)) - .and(path("/object")) - .and(header("x-storage-token", "server-token")) - .and(body_bytes(if operation == "PUT" { - payload.clone() - } else { - vec![] - })) - .respond_with( - ResponseTemplate::new(status).insert_header("location", "/redirected"), - ) - .expect(1) - .mount(&server) - .await; - Mock::given(method(verb)) - .and(path("/redirected")) - .and(header("x-storage-token", "server-token")) - .and(body_bytes(if operation == "PUT" { - payload.clone() - } else { - vec![] - })) - .respond_with(ResponseTemplate::new(200).set_body_bytes(payload.clone())) - .expect(1) - .mount(&server) - .await; - std::fs::write( - &source, - if operation == "GET" { - b"old".as_slice() - } else { - &payload - }, - ) - .unwrap(); - let batch = instruction( - operation, - &format!("{}/object", server.uri()), - if stream { - Path::new("__input_stream__") - } else { - &source - }, - ); - assert_eq!( - transfer_state(0) - .complete( - &batch, - &Client::builder() - .redirect(reqwest::redirect::Policy::none()) - .build() - .unwrap(), - &options(dir.path()), - stream.then(|| payload.clone()), - ) - .await - .unwrap(), - VolumeCompletion::Completed - ); - if operation == "GET" { - assert_eq!(std::fs::read(&source).unwrap(), payload); - } - assert!(server - .received_requests() - .await - .unwrap() - .iter() - .all(|request| !request.headers.contains_key("authorization"))); - } - - // Hyper normalizes duplicate lengths before Wiremock can inspect them. - use tokio::io::AsyncReadExt; - for stream in [false, true] { - let payload = b"payload"; - std::fs::write(&source, payload).unwrap(); - let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); - let url = format!("http://{}/object", listener.local_addr().unwrap()); - let peer = tokio::spawn(async move { - for hop in 0..2 { - let (mut socket, _) = listener.accept().await.unwrap(); - let mut request = Vec::new(); - let mut byte = [0]; - while !request.ends_with(b"\r\n\r\n") { - socket.read_exact(&mut byte).await.unwrap(); - request.push(byte[0]); - } - let lengths = String::from_utf8(request) - .unwrap() - .lines() - .filter_map(|line| { - line.to_ascii_lowercase() - .strip_prefix("content-length:") - .map(|value| value.trim().to_owned()) - }) - .collect::>(); - assert_eq!(lengths, [payload.len().to_string()]); - let mut body = vec![0; payload.len()]; - socket.read_exact(&mut body).await.unwrap(); - assert_eq!(body, payload); - let response = if hop == 0 { - b"HTTP/1.1 307 Temporary Redirect\r\nLocation: /redirected\r\nContent-Length: 0\r\nConnection: close\r\n\r\n".as_slice() - } else { - b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\nConnection: close\r\n\r\n" - }; - socket.write_all(response).await.unwrap(); - } - }); - let batch = instruction( - "PUT", - &url, - if stream { - Path::new("__input_stream__") - } else { - &source - }, - ); - let mut upload = Instruction::decode(&batch).unwrap(); - upload - .headers - .insert(reqwest::header::CONTENT_LENGTH, payload.len().into()); - let client = Client::builder() - .redirect(reqwest::redirect::Policy::none()) - .build() - .unwrap(); - assert_eq!( - tokio::time::timeout( - Duration::from_secs(2), - transfer_state(0).transfer_once( - &upload, - &client, - &options(dir.path()), - stream.then_some(payload.as_slice()), - &mut None - ), - ) - .await - .unwrap() - .unwrap(), - VolumeCompletion::Completed, - ); - peer.await.unwrap(); - } - } - - #[tokio::test] - async fn redirects_strip_cross_origin_credentials_and_share_a_hop_limit() { - use std::sync::atomic::{AtomicUsize, Ordering}; - let sensitive = [ - "authorization", - "cookie", - "cookie2", - "proxy-authorization", - "www-authenticate", - ]; - let previous = - reqwest::Url::parse("https://storage.invalid:8443/a?signature=secret").unwrap(); - for scheme in ["https", "http"] { - let next = reqwest::Url::parse(&format!("{scheme}://storage.invalid:8443/b")).unwrap(); - let mut headers = HeaderMap::new(); - for name in sensitive { - headers.insert( - reqwest::header::HeaderName::from_static(name), - "storage-secret".parse().unwrap(), - ); - } - headers.insert("x-storage-token", "server-token".parse().unwrap()); - redirect_headers(&mut headers, &previous, &next); - let same_origin = scheme == "https"; - for name in sensitive { - assert_eq!(headers.contains_key(name), same_origin, "{scheme}: {name}"); - } - assert_eq!(headers["x-storage-token"], "server-token"); - assert_eq!(headers.contains_key(reqwest::header::REFERER), same_origin); - if same_origin { - assert_eq!( - headers[reqwest::header::REFERER], - "https://storage.invalid:8443/a" - ); - } - } - let server = MockServer::start().await; - let redirected = MockServer::start().await; - let dir = tempfile::tempdir().unwrap(); - let source = dir.path().join("source"); - std::fs::write(&source, b"payload").unwrap(); - Mock::given(method("PUT")) - .and(body_bytes(b"payload")) - .and(header("authorization", "storage-secret")) - .respond_with(ResponseTemplate::new(307).insert_header( - "location", - format!("{}/?signature=redirect-secret", redirected.uri()), - )) - .expect(1) - .mount(&server) - .await; - let count = Arc::new(AtomicUsize::new(0)); - let attempts = Arc::clone(&count); - Mock::given(header("x-storage-token", "server-token")) - .respond_with(move |request: &wiremock::Request| { - for name in sensitive { - assert!(!request.headers.contains_key(name)); - } - let referer = - reqwest::Url::parse(request.headers.get("referer").unwrap().to_str().unwrap()) - .unwrap(); - assert!(referer.query().is_none()); - let first = attempts.fetch_add(1, Ordering::SeqCst) == 0; - assert_eq!(request.method.as_str(), if first { "PUT" } else { "GET" }); - assert_eq!( - request.body, - if first { b"payload".as_slice() } else { b"" } - ); - if !first { - assert!(!request.headers.contains_key("content-type")); - } - ResponseTemplate::new(if first { 303 } else { 308 }).insert_header("location", "/") - }) - .expect(10) - .mount(&redirected) - .await; - let batch = instruction( - "PUT", - &format!("{}/?signature=source-secret", server.uri()), - &source, - ); - let mut instruction = Instruction::decode(&batch).unwrap(); - for name in sensitive { - instruction.headers.insert( - reqwest::header::HeaderName::from_static(name), - "storage-secret".parse().unwrap(), - ); - } - instruction.headers.insert( - reqwest::header::CONTENT_TYPE, - "application/octet-stream".parse().unwrap(), - ); - let error = transfer_state(2) - .transfer( - instruction, - &Client::builder() - .redirect(reqwest::redirect::Policy::none()) - .build() - .unwrap(), - &options(dir.path()), - None, - ) - .await - .unwrap_err(); - assert_eq!( - error.error_code.as_deref(), - Some("VOLUME_STORAGE_NETWORK_ERROR") - ); - assert!(!error.retryable); - assert_eq!(count.load(Ordering::SeqCst), 10); - assert!(!error.message.contains("storage-secret")); - } - #[tokio::test] async fn transient_storage_statuses_replay_full_inputs_and_cache_completion() { use std::sync::atomic::{AtomicUsize, Ordering}; - for (operation, stream) in [ - ("PUT", false), - ("PUT", true), - ("GET", false), - ("REMOVE", false), - ] { - let statuses: &[u16] = if operation == "PUT" && !stream { - &[408, 429, 500, 502, 503, 504] - } else { - &[503] - }; + for (operation, stream) in [("PUT", false), ("PUT", true), ("GET", false)] { + let statuses: &[u16] = &[503]; let requests = statuses.len() as u64 + 1; let server = MockServer::start().await; let attempts = Arc::new(AtomicUsize::new(0)); @@ -1215,8 +807,7 @@ mod tests { assert_eq!( state .complete( - &batch, - &client, + async { Ok((batch.clone(), client.clone())) }, &options, stream.then(|| b"payload".to_vec()) ) @@ -1226,7 +817,11 @@ mod tests { ); assert_eq!( state - .complete(&batch, &client, &options, None) + .complete( + async { Ok((batch.clone(), client.clone())) }, + &options, + None + ) .await .unwrap(), VolumeCompletion::Completed @@ -1239,22 +834,32 @@ mod tests { #[tokio::test] async fn permanent_statuses_and_retry_limits_preserve_terminal_errors() { - for (status, retries, budget, requests) in [ - (400, 2, Duration::from_secs(10), 1), - (401, 2, Duration::from_secs(10), 1), - (403, 2, Duration::from_secs(10), 1), - (404, 2, Duration::from_secs(10), 1), - (501, 2, Duration::from_secs(10), 1), - (503, 0, Duration::from_secs(10), 1), - (503, 2, Duration::ZERO, 1), - (503, 2, Duration::from_secs(10), 3), + for (operation, status, retries, budget, requests) in [ + ("PUT", 307, 2, Duration::from_secs(10), 1), + ("REMOVE", 403, 2, Duration::from_secs(10), 1), + ("REMOVE", 404, 2, Duration::from_secs(10), 1), + ("REMOVE", 503, 0, Duration::from_secs(10), 1), + ("REMOVE", 503, 2, Duration::ZERO, 1), + ("REMOVE", 503, 2, Duration::from_secs(10), 3), ] { let server = MockServer::start().await; - Mock::given(method("DELETE")) - .respond_with(ResponseTemplate::new(status).insert_header("retry-after", "0")) + Mock::given(method(if operation == "PUT" { "PUT" } else { "DELETE" })) + .and(path("/object")) + .respond_with( + ResponseTemplate::new(status) + .insert_header("retry-after", "0") + .insert_header("location", "/redirected"), + ) .expect(requests) .mount(&server) .await; + let directory = tempfile::tempdir().unwrap(); + let file = directory.path().join("source"); + std::fs::write(&file, b"payload").unwrap(); + let options = VolumeOptions { + allowed_paths: vec![directory.path().to_owned()], + remove_not_found_is_success: true, + }; let state = VolumeState::new( RetryConfig { max_retries: retries, @@ -1264,17 +869,23 @@ mod tests { ..Default::default() }, None, + Default::default(), + Default::default(), ); let batch = instruction( - "REMOVE", - &format!("{}?secret=hidden", server.uri()), - Path::new(""), + operation, + &format!("{}/object?secret=hidden", server.uri()), + &file, ); for _ in 0..2 { - let error = state - .complete(&batch, &Client::new(), &VolumeOptions::default(), None) - .await - .unwrap_err(); + let result = state + .complete(async { Ok((batch.clone(), Client::new())) }, &options, None) + .await; + if status == 404 { + assert_eq!(result.unwrap(), VolumeCompletion::Completed); + continue; + } + let error = result.unwrap_err(); assert_eq!(error.http_status, Some(status)); assert_eq!( error.error_code.as_deref(), @@ -1301,11 +912,17 @@ mod tests { ..Default::default() }, None, + Default::default(), + Default::default(), ); let batch = instruction("REMOVE", &server.uri(), Path::new("")); let client = Client::new(); let options = VolumeOptions::default(); - let complete = state.complete(&batch, &client, &options, None); + let complete = state.complete( + async { Ok((batch.clone(), client.clone())) }, + &options, + None, + ); let cancel = async { while server.received_requests().await.unwrap().is_empty() { tokio::task::yield_now().await; @@ -1342,7 +959,11 @@ mod tests { let client = Client::new(); assert_eq!( state - .complete(&batch, &client, &VolumeOptions::default(), None) + .complete( + async { Ok((batch.clone(), client.clone())) }, + &VolumeOptions::default(), + None + ) .await .unwrap(), VolumeCompletion::NeedsInputStream @@ -1350,7 +971,11 @@ mod tests { assert!(server.received_requests().await.unwrap().is_empty()); assert_eq!( state - .complete(&batch, &client, &VolumeOptions::default(), Some(vec![])) + .complete( + async { Ok((batch.clone(), client.clone())) }, + &VolumeOptions::default(), + Some(vec![]) + ) .await .unwrap(), VolumeCompletion::Completed @@ -1358,7 +983,11 @@ mod tests { state.cancel(); assert_eq!( state - .complete(&batch, &client, &VolumeOptions::default(), Some(vec![1])) + .complete( + async { Ok((batch.clone(), client.clone())) }, + &VolumeOptions::default(), + Some(vec![1]) + ) .await .unwrap(), VolumeCompletion::Completed @@ -1388,17 +1017,13 @@ mod tests { let batch = instruction("GET", &format!("{}/ok", server.uri()), &dest); let completed = transfer_state(0); completed - .complete(&batch, &Client::new(), &options(dir.path()), None) + .complete( + async { Ok((batch.clone(), Client::new())) }, + &options(dir.path()), + None, + ) .await .unwrap(); - completed.cancel(); - assert_eq!( - completed - .complete(&batch, &Client::new(), &options(dir.path()), None) - .await - .unwrap(), - VolumeCompletion::Completed - ); #[cfg(unix)] { assert_eq!( @@ -1426,7 +1051,11 @@ mod tests { let state = transfer_state(0); assert_eq!( state - .complete(&batch, &Client::new(), &options(dir.path()), None) + .complete( + async { Ok((batch.clone(), Client::new())) }, + &options(dir.path()), + None + ) .await .unwrap(), VolumeCompletion::Completed @@ -1439,8 +1068,6 @@ mod tests { assert_eq!(std::fs::read(&dest).unwrap(), b"new bytes"); } } - #[cfg(unix)] - let requests = server.received_requests().await.unwrap().len(); let state = transfer_state(0); let batch = instruction( "GET", @@ -1448,69 +1075,21 @@ mod tests { &dest, ); let error = state - .complete(&batch, &Client::new(), &options(dir.path()), None) + .complete( + async { Ok((batch.clone(), Client::new())) }, + &options(dir.path()), + None, + ) .await .unwrap_err(); assert_eq!(error.http_status, Some(403)); assert!(!error.message.contains("hidden")); - state.cancel(); - assert_eq!( - state - .complete(&batch, &Client::new(), &options(dir.path()), None) - .await - .unwrap_err() - .http_status, - Some(403) - ); assert_eq!(std::fs::read(&dest).unwrap(), b"new bytes"); #[cfg(unix)] - { - std::fs::set_permissions(&dest, std::fs::Permissions::from_mode(0o400)).unwrap(); - if std::fs::OpenOptions::new().write(true).open(&dest).is_err() { - let batch = instruction("GET", &format!("{}/ok", server.uri()), &dest); - let error = transfer_state(0) - .complete(&batch, &Client::new(), &options(dir.path()), None) - .await - .unwrap_err(); - assert_eq!(error.code, crate::ErrorCode::PermissionDenied); - assert_eq!(error.error_code.as_deref(), Some("VOLUME_LOCAL_FILE_ERROR")); - let local = error.local_error.unwrap(); - assert_eq!(local.kind, "PermissionDenied"); - assert_eq!(local.path, dest.to_string_lossy()); - assert_eq!(std::fs::read(&dest).unwrap(), b"new bytes"); - assert_eq!( - server.received_requests().await.unwrap().len(), - requests + 1 - ); - } - std::fs::set_permissions(&dest, std::fs::Permissions::from_mode(0o600)).unwrap(); - std::fs::set_permissions(dir.path(), std::fs::Permissions::from_mode(0o700)).unwrap(); - } + std::fs::set_permissions(dir.path(), std::fs::Permissions::from_mode(0o700)).unwrap(); assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 1); } - #[tokio::test] - async fn remove_has_narrow_missing_status_policy_and_no_local_path_requirement() { - let server = MockServer::start().await; - Mock::given(method("DELETE")) - .respond_with(ResponseTemplate::new(404)) - .expect(1) - .mount(&server) - .await; - let batch = instruction("REMOVE", &server.uri(), Path::new("")); - let permissive = VolumeOptions { - remove_not_found_is_success: true, - ..VolumeOptions::default() - }; - assert_eq!( - transfer_state(0) - .complete(&batch, &Client::new(), &permissive, None) - .await - .unwrap(), - VolumeCompletion::Completed - ); - } - #[tokio::test] async fn abandoned_or_cancelled_get_cannot_publish_or_restart() { let server = MockServer::start().await; @@ -1531,7 +1110,11 @@ mod tests { let client = Client::new(); for cancel in [false, true] { let state = transfer_state(0); - let mut future = Box::pin(state.complete(&batch, &client, &options, None)); + let mut future = Box::pin(state.complete( + async { Ok((batch.clone(), client.clone())) }, + &options, + None, + )); tokio::select! { result = &mut future => panic!("unexpected early completion: {result:?}"), _ = async { @@ -1551,7 +1134,11 @@ mod tests { drop(future); assert_eq!( state - .complete(&batch, &client, &options, None) + .complete( + async { Ok((batch.clone(), client.clone())) }, + &options, + None + ) .await .unwrap_err() .code, @@ -1565,12 +1152,7 @@ mod tests { #[tokio::test] async fn response_inactivity_bounds_headers_and_body_without_publishing() { use tokio::io::AsyncReadExt; - for (operation, headers_sent) in [ - ("GET", false), - ("GET", true), - ("PUT", true), - ("REMOVE", false), - ] { + for (operation, headers_sent) in [("GET", false), ("GET", true), ("PUT", true)] { let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); let url = format!("http://{}", listener.local_addr().unwrap()); let requests = Arc::new(std::sync::atomic::AtomicUsize::new(0)); @@ -1614,11 +1196,17 @@ mod tests { .retry .clone(), Some(Duration::from_millis(150)), + Default::default(), + Default::default(), ); let batch = instruction(operation, &url, &dest); let error = tokio::time::timeout( Duration::from_secs(2), - state.complete(&batch, &Client::new(), &options(dir.path()), None), + state.complete( + async { Ok((batch.clone(), Client::new())) }, + &options(dir.path()), + None, + ), ) .await .unwrap() @@ -1630,7 +1218,11 @@ mod tests { ); assert!(error.message.contains("read timed out")); let repeated = state - .complete(&batch, &Client::new(), &options(dir.path()), None) + .complete( + async { Ok((batch.clone(), Client::new())) }, + &options(dir.path()), + None, + ) .await .unwrap_err(); assert_eq!(repeated.message, error.message); @@ -1664,11 +1256,12 @@ mod tests { let state = VolumeState::new( transfer_state(0).retry.clone(), Some(Duration::from_millis(150)), + Default::default(), + Default::default(), ); state .complete( - &instruction("GET", &url, &dest), - &Client::new(), + async { Ok((instruction("GET", &url, &dest), Client::new())) }, &options(dir.path()), None, ) @@ -1732,7 +1325,11 @@ mod tests { std::fs::write(&dest, b"old").unwrap(); let batch = instruction("GET", &url, &dest); let result = transfer_state(retries) - .complete(&batch, &Client::new(), &options(dir.path()), None) + .complete( + async { Ok((batch.clone(), Client::new())) }, + &options(dir.path()), + None, + ) .await; if retries == 0 { assert_eq!(result.unwrap_err().code, crate::ErrorCode::NetworkError); @@ -1820,7 +1417,7 @@ mod tests { #[cfg(unix)] { assert_eq!(error.code, crate::ErrorCode::NotFound); - assert_eq!(local.kind, "NotFound"); + assert_eq!(local.kind, std::io::ErrorKind::NotFound); assert_eq!(local.raw_os_error, Some(2)); } } @@ -1834,15 +1431,15 @@ mod tests { for (source, kind, code) in [ ( dir.path().join("missing"), - "NotFound", + std::io::ErrorKind::NotFound, crate::ErrorCode::NotFound, ), ( dir.path().to_owned(), if cfg!(windows) { - "PermissionDenied" + std::io::ErrorKind::PermissionDenied } else { - "IsADirectory" + std::io::ErrorKind::IsADirectory }, if cfg!(windows) { crate::ErrorCode::PermissionDenied @@ -1858,7 +1455,11 @@ mod tests { ); let state = transfer_state(1); let error = state - .complete(&batch, &Client::new(), &options(dir.path()), None) + .complete( + async { Ok((batch.clone(), Client::new())) }, + &options(dir.path()), + None, + ) .await .unwrap_err(); assert_eq!(error.code, code); @@ -1872,7 +1473,11 @@ mod tests { assert!(!error.message.contains("hidden")); assert_eq!( state - .complete(&batch, &Client::new(), &options(dir.path()), None) + .complete( + async { Ok((batch.clone(), Client::new())) }, + &options(dir.path()), + None + ) .await .unwrap_err() .local_error @@ -1883,30 +1488,6 @@ mod tests { ); } assert!(server.received_requests().await.unwrap().is_empty()); - for (kind, code) in [ - ( - std::io::ErrorKind::PermissionDenied, - crate::ErrorCode::PermissionDenied, - ), - ( - std::io::ErrorKind::InvalidInput, - crate::ErrorCode::InvalidArgument, - ), - ( - std::io::ErrorKind::NotADirectory, - crate::ErrorCode::InvalidArgument, - ), - (std::io::ErrorKind::Other, crate::ErrorCode::Internal), - ] { - let error = local_error(std::io::Error::from(kind), "requested"); - assert_eq!(error.code, code); - assert_eq!(error.error_code.as_deref(), Some("VOLUME_LOCAL_FILE_ERROR")); - assert_eq!(error.sql_state.as_deref(), Some("HY000")); - assert!(!error.retryable); - let local = error.local_error.unwrap(); - assert_eq!(local.kind, format!("{kind:?}")); - assert_eq!(local.path, "requested"); - } } #[tokio::test] @@ -1945,9 +1526,8 @@ mod tests { DataType::Utf8, true, )])); - let batch = ResultBatch::Arrow( - RecordBatch::try_new(schema, vec![Arc::new(StringArray::from(vec!["PUT"]))]).unwrap(), - ); + let batch = + RecordBatch::try_new(schema, vec![Arc::new(StringArray::from(vec!["PUT"]))]).unwrap(); assert_eq!( Instruction::decode(&batch).err().unwrap().code, crate::ErrorCode::InvalidArgument diff --git a/tests/v0_volume_wiremock.rs b/tests/v0_volume_wiremock.rs index 2031738d..a4544953 100644 --- a/tests/v0_volume_wiremock.rs +++ b/tests/v0_volume_wiremock.rs @@ -132,12 +132,6 @@ async fn instruction_batches_preserve_one_row_and_reject_extra_rows() { panic!("expected buffered instruction batch"); }; assert_eq!(batch.num_rows(), 1); - if !valid { - let ResultBatch::Arrow(batch) = executed.next_batch().await.unwrap().unwrap() else { - panic!("expected retained extra instruction batch"); - }; - assert_eq!(batch.num_rows(), 1); - } assert!(executed.next_batch().await.unwrap().is_none()); executed.close().await.unwrap(); session.close().await.unwrap(); @@ -196,7 +190,7 @@ async fn session_with_http( #[tokio::test] async fn storage_transfers_outlive_rpc_deadline_while_sql_requests_still_time_out() { - for operation in ["PUT", "GET"] { + for operation in ["GET"] { let server = MockServer::start().await; let dir = tempfile::tempdir().unwrap(); let local = dir.path().join("file"); @@ -237,13 +231,7 @@ async fn storage_transfers_outlive_rpc_deadline_while_sql_requests_still_time_ou .unwrap(), VolumeCompletion::Completed ); - if operation == "PUT" { - let requests = server.received_requests().await.unwrap(); - let upload = requests.iter().find(|r| r.url.path() == "/object").unwrap(); - assert_eq!(upload.body, b"original"); - } else { - assert_eq!(std::fs::read(&local).unwrap(), b"downloaded"); - } + assert_eq!(std::fs::read(&local).unwrap(), b"downloaded"); executed.close().await.unwrap(); Mock::given(method("POST")) .and(path("/api/2.0/sql/statements")) From 6121e877d67b49ec21996a6bf75ae3a88dd8ad8e Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Thu, 19 Nov 2026 07:48:58 +0000 Subject: [PATCH 40/63] docs(volume): clarify publication and input handshakes Signed-off-by: Aakash Saravanan --- src/volume.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/volume.rs b/src/volume.rs index 6e7d5272..dd75ddb8 100644 --- a/src/volume.rs +++ b/src/volume.rs @@ -37,6 +37,8 @@ use tokio_util::sync::CancellationToken; /// temporary storage followed by a non-atomic copy, which can fail partially. /// Download failure or cancellation before publication preserves existing bytes. /// Filesystem setup and publication are synchronous and can delay cancellation. +/// Cancellation and close can also wait for another statement's GET publication +/// in the same session. #[derive(Debug, Clone, Default)] pub struct VolumeOptions { pub allowed_paths: Vec, @@ -119,6 +121,7 @@ impl VolumeState { }; if matches!(result, Ok(VolumeCompletion::NeedsInputStream)) { self.started.store(false, Ordering::Release); + // Leave the cell uninitialized so completion can resume with input bytes. Err(VolumeCompletion::NeedsInputStream) } else { Ok(result) From 85c7446546316f583d89d982a6d29b2d6f6318a2 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Thu, 19 Nov 2026 17:04:31 +0000 Subject: [PATCH 41/63] fix(volume): preserve rows and reject redirect downgrades Signed-off-by: Aakash Saravanan --- include/databricks_kernel.h | 1 + src/client/http.rs | 13 ++++++- src/client/http_tls_tests.rs | 68 ++++++++++++++++++++++++++++++++++++ src/result_stream.rs | 32 +++++++++-------- src/volume.rs | 1 + tests/v0_volume_wiremock.rs | 6 ++++ 6 files changed, 105 insertions(+), 16 deletions(-) diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h index 6dc7380f..b41b99f5 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -986,6 +986,7 @@ KernelStatusCode kernel_executed_statement_is_volume_operation( /* The cached marker does not establish whether the executed owner is valid. */ KernelStatusCode kernel_result_stream_is_volume_operation( const kernel_result_stream_t* stream, bool* out); +/* out_status is written only on success. */ KernelStatusCode kernel_result_stream_complete_volume_operation( kernel_result_stream_t* stream, const char* allowed_paths_json, bool remove_not_found_is_success, KernelVolumeCompletion* out_status); diff --git a/src/client/http.rs b/src/client/http.rs index de3d9bc4..4513f1db 100644 --- a/src/client/http.rs +++ b/src/client/http.rs @@ -399,7 +399,18 @@ impl StorageClient { .get_or_try_init(|| async { DatabricksHttpClient::build_reqwest_client( &self.config, - reqwest::redirect::Policy::default(), + reqwest::redirect::Policy::custom(|attempt| { + if attempt.url().scheme() == "http" + && attempt + .previous() + .last() + .is_some_and(|url| url.scheme() == "https") + { + attempt.error("Volume storage redirect cannot downgrade HTTPS to HTTP") + } else { + reqwest::redirect::Policy::default().redirect(attempt) + } + }), None, false, ) diff --git a/src/client/http_tls_tests.rs b/src/client/http_tls_tests.rs index 42355567..ee67a03e 100644 --- a/src/client/http_tls_tests.rs +++ b/src/client/http_tls_tests.rs @@ -288,6 +288,74 @@ async fn expired_certificate_fails_once_with_certificate_cause() { assert_certificate_failure(CertificateFailure::Expired).await; } +#[tokio::test] +async fn storage_redirect_rejects_https_to_http_on_the_same_port() { + let key = KeyPair::generate().unwrap(); + let certificate = CertificateParams::new(vec!["127.0.0.1".to_string()]) + .unwrap() + .self_signed(&key) + .unwrap(); + let tls = rustls::ServerConfig::builder_with_provider(Arc::new( + rustls::crypto::ring::default_provider(), + )) + .with_safe_default_protocol_versions() + .unwrap() + .with_no_client_auth() + .with_single_cert( + vec![certificate.der().clone()], + PrivatePkcs8KeyDer::from(key.serialize_der()).into(), + ) + .unwrap(); + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let server = tokio::spawn(async move { + let socket = listener.accept().await.unwrap().0; + let mut stream = TlsAcceptor::from(Arc::new(tls)) + .accept(socket) + .await + .unwrap(); + let mut request = [0; 4096]; + assert!(stream.read(&mut request).await.unwrap() > 0); + stream + .write_all( + format!( + "HTTP/1.1 302 Found\r\nLocation: http://{address}/plain\r\nContent-Length: 0\r\nConnection: close\r\n\r\n" + ) + .as_bytes(), + ) + .await + .unwrap(); + assert!( + tokio::time::timeout(Duration::from_millis(150), listener.accept()) + .await + .is_err() + ); + }); + let client = test_client( + HttpClientConfig { + tls: TlsConfig { + allow_self_signed: Some(true), + ..Default::default() + }, + ..Default::default() + }, + Duration::from_secs(2), + ); + let storage = client.storage_client(None); + let error = storage + .get() + .await + .unwrap() + .get(format!("https://{address}/object")) + .header("authorization", "storage-secret") + .header("cookie", "storage-cookie") + .send() + .await + .unwrap_err(); + assert!(error.is_redirect(), "{error}"); + server.await.unwrap(); +} + #[tokio::test] async fn storage_connection_timeout_preserves_unconfigured_limits() { let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); diff --git a/src/result_stream.rs b/src/result_stream.rs index 2b5171d1..bd1f0f4b 100644 --- a/src/result_stream.rs +++ b/src/result_stream.rs @@ -58,6 +58,7 @@ use arrow_array::types::{ use arrow_array::{Array, RecordBatch}; use arrow_schema::{DataType, Schema, TimeUnit}; use chrono::{NaiveDate, NaiveDateTime}; +use std::collections::VecDeque; use std::sync::Arc; /// Cheap-clone reference to a result schema. The kernel hands one @@ -90,7 +91,7 @@ pub enum TryNextBatch<'a> { End, } -type Prefetched = Option>>; +type Prefetched = VecDeque>>; // `ResultBatch::into_arrow()` was deliberately removed: the // `#[non_exhaustive]` envelope is the right escape hatch already. @@ -607,7 +608,7 @@ impl ResultStream { reader: Some(reader), schema, current: None, - prefetched: None, + prefetched: VecDeque::new(), current_row_idx: 0, exhausted: false, close_guard: None, @@ -683,7 +684,7 @@ impl ResultStream { if batch.num_rows() != 0 { break batch.clone(); } - self.prefetched.take(); + self.prefetched.pop_front(); }; // Later batches cannot authorize a partial transfer of a multi-row result. while !self.exhausted { @@ -695,6 +696,7 @@ impl ResultStream { .await? { Some(batch) if batch.num_rows() != 0 => { + self.prefetched.push_back(Ok(ResultBatch::Arrow(batch))); return Err(Error::invalid_argument() .message("Expected one Volume instruction row")); } @@ -799,7 +801,7 @@ impl ResultStream { pub async fn next_batch(&mut self) -> Result> { // Replay inspected batches first so DML counts and Volume validation // do not consume callers' result rows. - if let Some(batch) = self.prefetched.take() { + if let Some(batch) = self.prefetched.pop_front() { self.set_current_batch(batch.map_err(|error| *error)?); return Ok(self.current.as_ref()); } @@ -833,7 +835,7 @@ impl ResultStream { /// Return the next batch if it is already available without waiting for /// network or background-prefetch progress. pub fn try_next_batch(&mut self) -> Result> { - if let Some(batch) = self.prefetched.take() { + if let Some(batch) = self.prefetched.pop_front() { self.set_current_batch(batch.map_err(|error| *error)?); return Ok(TryNextBatch::Ready( self.current.as_ref().expect("batch was just installed"), @@ -876,14 +878,14 @@ impl ResultStream { /// exhausted. A subsequent [`next_batch`](Self::next_batch) still returns /// the buffered outcome. pub(crate) async fn peek_first_batch(&mut self) -> Result> { - if self.prefetched.is_none() && self.current.is_none() && !self.exhausted { + if self.prefetched.is_empty() && self.current.is_none() && !self.exhausted { let reader = self .reader .as_mut() .expect("ResultStream reader is present until into_owned_batches consumes it"); match reader.next_batch().await { Ok(Some(rb)) => { - self.prefetched = Some(Ok(ResultBatch::Arrow(rb))); + self.prefetched.push_back(Ok(ResultBatch::Arrow(rb))); // Stamp first-batch (result-set-ready) latency at fetch // time, not when the caller later consumes the prefetched // batch via `next_batch`. `record_result_batch` is @@ -893,7 +895,7 @@ impl ResultStream { // result set became ready rather than the caller's // think-time before the first `next_batch` pull. if let (Some(telemetry), Some(Ok(batch))) = - (&self.telemetry, self.prefetched.as_ref()) + (&self.telemetry, self.prefetched.front()) { telemetry.record_batch(batch); } @@ -901,12 +903,12 @@ impl ResultStream { Ok(None) => self.exhausted = true, Err(e) => { self.finalize_telemetry(Some(&e)); - self.prefetched = Some(Err(Box::new(e.clone()))); + self.prefetched.push_back(Err(Box::new(e.clone()))); return Err(e); } } } - match self.prefetched.as_ref() { + match self.prefetched.front() { Some(Ok(batch)) => Ok(Some(batch)), Some(Err(error)) => Err((**error).clone()), None => Ok(None), @@ -1000,10 +1002,10 @@ impl ResultStream { /// after an `Err` keep returning `None`. pub fn into_owned_batches(mut self) -> OwnedBatchIter { // Inspected batches were pulled from the reader; yield them first to preserve row order. - let prefetched = self - .prefetched - .take() - .map(|outcome| outcome.map(|ResultBatch::Arrow(rb)| rb)); + let prefetched = std::mem::take(&mut self.prefetched) + .into_iter() + .map(|outcome| outcome.map(|ResultBatch::Arrow(rb)| rb)) + .collect(); OwnedBatchIter { reader: self .reader @@ -1051,7 +1053,7 @@ impl Iterator for OwnedBatchIter { if self.done { return None; } - if let Some(outcome) = self.prefetched.take() { + if let Some(outcome) = self.prefetched.pop_front() { return match outcome { Ok(batch) => { if let Some(telemetry) = &self.telemetry { diff --git a/src/volume.rs b/src/volume.rs index dd75ddb8..8abedd67 100644 --- a/src/volume.rs +++ b/src/volume.rs @@ -36,6 +36,7 @@ use tokio_util::sync::CancellationToken; /// replacement; an existing writable file in a restricted directory uses private /// temporary storage followed by a non-atomic copy, which can fail partially. /// Download failure or cancellation before publication preserves existing bytes. +/// GET decodes gzip Content-Encoding before writing the downloaded bytes. /// Filesystem setup and publication are synchronous and can delay cancellation. /// Cancellation and close can also wait for another statement's GET publication /// in the same session. diff --git a/tests/v0_volume_wiremock.rs b/tests/v0_volume_wiremock.rs index a4544953..dcf0af77 100644 --- a/tests/v0_volume_wiremock.rs +++ b/tests/v0_volume_wiremock.rs @@ -132,6 +132,12 @@ async fn instruction_batches_preserve_one_row_and_reject_extra_rows() { panic!("expected buffered instruction batch"); }; assert_eq!(batch.num_rows(), 1); + if !valid { + let Some(ResultBatch::Arrow(batch)) = executed.next_batch().await.unwrap() else { + panic!("expected second instruction batch"); + }; + assert_eq!(batch.num_rows(), 1); + } assert!(executed.next_batch().await.unwrap().is_none()); executed.close().await.unwrap(); session.close().await.unwrap(); From 2f765a98b5f14102b4d605caa6162a0f182e339a Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Thu, 19 Nov 2026 17:49:51 +0000 Subject: [PATCH 42/63] docs(volume): clarify replacement metadata Signed-off-by: Aakash Saravanan --- src/volume.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/volume.rs b/src/volume.rs index 8abedd67..9d6e29a0 100644 --- a/src/volume.rs +++ b/src/volume.rs @@ -35,6 +35,7 @@ use tokio_util::sync::CancellationToken; /// GET stages downloads before publication. Sibling staging permits atomic /// replacement; an existing writable file in a restricted directory uses private /// temporary storage followed by a non-atomic copy, which can fail partially. +/// Atomic replacement copies mode bits, but not ownership, ACLs or extended attributes. /// Download failure or cancellation before publication preserves existing bytes. /// GET decodes gzip Content-Encoding before writing the downloaded bytes. /// Filesystem setup and publication are synchronous and can delay cancellation. From 8095194d049b7f8f1329190f4d0c4461c948d708 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Thu, 19 Nov 2026 21:32:49 +0000 Subject: [PATCH 43/63] fix(volume): publish downloads through the destination file Signed-off-by: Aakash Saravanan --- src/c_abi/result.rs | 7 +-- src/session.rs | 7 --- src/telemetry/statement.rs | 7 +-- src/volume.rs | 104 ++++++++++++------------------------- 4 files changed, 35 insertions(+), 90 deletions(-) diff --git a/src/c_abi/result.rs b/src/c_abi/result.rs index dc25ec30..099e83dc 100644 --- a/src/c_abi/result.rs +++ b/src/c_abi/result.rs @@ -784,12 +784,7 @@ mod tests { ) .unwrap(); let rt = tokio::runtime::Runtime::new().unwrap(); - let volume = crate::volume::VolumeState::new( - Default::default(), - None, - Default::default(), - Default::default(), - ); + let volume = crate::volume::VolumeState::new(Default::default(), None, Default::default()); let stream = rt.block_on(async { let mut stream = ResultStream::from_reader(Box::new(MockReader::new(vec![batch.clone()]))) diff --git a/src/session.rs b/src/session.rs index bbbea3eb..40d6136f 100644 --- a/src/session.rs +++ b/src/session.rs @@ -100,7 +100,6 @@ pub(crate) struct SessionInner { storage_client: Arc, storage_retry: RetryConfig, volume_cancellation: tokio_util::sync::CancellationToken, - volume_publish: Arc>, /// Server-issued session identifier. session_id: String, @@ -167,15 +166,10 @@ impl SessionInner { self.storage_retry.clone(), self.config.http.storage_read_timeout, self.volume_cancellation.child_token(), - Arc::clone(&self.volume_publish), ) } fn cancel_volume_operations(&self) { - let _publish = self - .volume_publish - .lock() - .unwrap_or_else(|e| e.into_inner()); self.volume_cancellation.cancel(); } @@ -503,7 +497,6 @@ impl Session { storage_client, storage_retry, volume_cancellation: tokio_util::sync::CancellationToken::new(), - volume_publish: Default::default(), session_id: session_info.session_id, config, runtime_handle, diff --git a/src/telemetry/statement.rs b/src/telemetry/statement.rs index 30951b45..2c300531 100644 --- a/src/telemetry/statement.rs +++ b/src/telemetry/statement.rs @@ -409,12 +409,7 @@ mod tests { stream.attach_volume( true, - crate::volume::VolumeState::new( - Default::default(), - None, - Default::default(), - Default::default(), - ), + crate::volume::VolumeState::new(Default::default(), None, Default::default()), Arc::new( crate::client::DatabricksHttpClient::with_default_retry(Default::default()) .unwrap() diff --git a/src/volume.rs b/src/volume.rs index 9d6e29a0..45cb89bc 100644 --- a/src/volume.rs +++ b/src/volume.rs @@ -32,15 +32,13 @@ use tokio_util::sync::CancellationToken; /// /// Requested and resolved paths must be within allowed roots. Symlinks between /// authorized roots work; path components must remain stable during file access. -/// GET stages downloads before publication. Sibling staging permits atomic -/// replacement; an existing writable file in a restricted directory uses private -/// temporary storage followed by a non-atomic copy, which can fail partially. -/// Atomic replacement copies mode bits, but not ownership, ACLs or extended attributes. -/// Download failure or cancellation before publication preserves existing bytes. +/// GET downloads into a temporary file, beside the destination when its directory +/// allows it and in the system temporary directory otherwise, then copies it into +/// the destination in place. Download failure or cancellation before publication +/// preserves existing bytes; a failure during the copy can leave the destination +/// partially written. Cancellation after publication starts does not interrupt it. /// GET decodes gzip Content-Encoding before writing the downloaded bytes. /// Filesystem setup and publication are synchronous and can delay cancellation. -/// Cancellation and close can also wait for another statement's GET publication -/// in the same session. #[derive(Debug, Clone, Default)] pub struct VolumeOptions { pub allowed_paths: Vec, @@ -56,14 +54,12 @@ pub enum VolumeCompletion { Completed, } -/// The synchronous gate makes cancellation and local publication mutually exclusive. #[derive(Default)] pub(crate) struct VolumeState { retry: RetryConfig, read_timeout: Option, completion: OnceCell>, cancellation: CancellationToken, - publish: Arc>, started: AtomicBool, } @@ -76,19 +72,16 @@ impl VolumeState { retry: RetryConfig, read_timeout: Option, cancellation: CancellationToken, - publish: Arc>, ) -> Arc { Arc::new(Self { retry, read_timeout, cancellation, - publish, ..Self::default() }) } pub(crate) fn cancel(&self) { - let _publish = self.publish.lock().unwrap_or_else(|e| e.into_inner()); self.cancellation.cancel(); } @@ -215,54 +208,21 @@ impl VolumeState { Operation::Remove => Operation::Remove, }; let mut destination = if let Operation::Get(path) = &operation { - // Replacement must still honor the destination's write permissions. let existing = match std::fs::OpenOptions::new().write(true).open(path) { Ok(file) => Some(file), Err(error) if error.kind() == std::io::ErrorKind::NotFound => None, Err(error) => return Err(local_error(error, &local_file)), }; - #[cfg(unix)] - let mut builder = tempfile::Builder::new(); - #[cfg(not(unix))] - let builder = tempfile::Builder::new(); - #[cfg(unix)] - { - use std::os::unix::fs::PermissionsExt; - builder.permissions(std::fs::Permissions::from_mode(0o666)); - } - let (temp, in_place) = match builder.tempfile_in( + let temp = tempfile::tempfile_in( path.parent() .ok_or_else(|| invalid("Missing destination parent"))?, - ) { - Ok(temp) => { - if let Some(file) = existing { - temp.as_file() - .set_permissions( - file.metadata() - .map_err(|e| local_error(e, &local_file))? - .permissions(), - ) - .map_err(|e| local_error(e, &local_file))?; - } - (temp, None) - } - Err(error) - if error.kind() == std::io::ErrorKind::PermissionDenied - && existing.is_some() => - { - // An existing file may be writable without permission to replace its entry. - let temp = - tempfile::NamedTempFile::new().map_err(|e| local_error(e, &local_file))?; - (temp, existing) - } - Err(error) => return Err(local_error(error, &local_file)), - }; + ) + .or_else(|_| tempfile::tempfile()) + .map_err(|e| local_error(e, &local_file))?; let writer = tokio::fs::File::from_std( - temp.as_file() - .try_clone() - .map_err(|e| local_error(e, &local_file))?, + temp.try_clone().map_err(|e| local_error(e, &local_file))?, ); - Some((temp, writer, in_place, path)) + Some((temp, writer, existing, path)) } else { None }; @@ -328,27 +288,28 @@ impl VolumeState { .map_err(|e| local_error(e, &local_file))?; } } - if let Some((mut temp, mut writer, in_place, path)) = destination.take() { + if let Some((mut temp, mut writer, existing, path)) = destination.take() { writer .flush() .await .map_err(|e| local_error(e, &local_file))?; drop(writer); - let _publish = self.publish.lock().unwrap_or_else(|e| e.into_inner()); if self.cancellation.is_cancelled() { return Err(cancelled()); } - if let Some(mut file) = in_place { - std::io::Seek::rewind(temp.as_file_mut()) - .map_err(|e| local_error(e, &local_file))?; - let length = std::io::copy(temp.as_file_mut(), &mut file) - .map_err(|e| local_error(e, &local_file))?; - file.set_len(length) - .map_err(|e| local_error(e, &local_file))?; - } else { - temp.persist(path) - .map_err(|e| local_error(e.error, &local_file))?; - } + let mut file = match existing { + Some(file) => file, + None => std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(path) + .map_err(|e| local_error(e, &local_file))?, + }; + std::io::Seek::rewind(&mut temp).map_err(|e| local_error(e, &local_file))?; + let length = + std::io::copy(&mut temp, &mut file).map_err(|e| local_error(e, &local_file))?; + file.set_len(length) + .map_err(|e| local_error(e, &local_file))?; } Ok(VolumeCompletion::Completed) } @@ -671,7 +632,7 @@ mod tests { use arrow_array::{ArrayRef, RecordBatch}; use arrow_schema::{DataType, Field, Schema}; #[cfg(unix)] - use std::os::unix::fs::PermissionsExt; + use std::os::unix::fs::{MetadataExt, PermissionsExt}; use std::time::Duration; use wiremock::matchers::{body_bytes, header, method, path}; use wiremock::{Mock, MockServer, ResponseTemplate}; @@ -714,7 +675,6 @@ mod tests { }, None, Default::default(), - Default::default(), ) } @@ -875,7 +835,6 @@ mod tests { }, None, Default::default(), - Default::default(), ); let batch = instruction( operation, @@ -918,7 +877,6 @@ mod tests { }, None, Default::default(), - Default::default(), ); let batch = instruction("REMOVE", &server.uri(), Path::new("")); let client = Client::new(); @@ -1000,7 +958,7 @@ mod tests { } #[tokio::test] - async fn get_replaces_destination_and_caches_error_without_replay() { + async fn get_writes_in_place_and_preserves_old_bytes_on_download_failure() { let server = MockServer::start().await; Mock::given(method("GET")) .and(path("/ok")) @@ -1018,6 +976,8 @@ mod tests { let dest = dir.path().join("download"); std::fs::write(&dest, b"old bytes").unwrap(); #[cfg(unix)] + let inode = std::fs::metadata(&dest).unwrap().ino(); + #[cfg(unix)] std::fs::set_permissions(&dest, std::fs::Permissions::from_mode(0o200)).unwrap(); let batch = instruction("GET", &format!("{}/ok", server.uri()), &dest); let completed = transfer_state(0); @@ -1031,6 +991,7 @@ mod tests { .unwrap(); #[cfg(unix)] { + assert_eq!(std::fs::metadata(&dest).unwrap().ino(), inode); assert_eq!( std::fs::metadata(&dest).unwrap().permissions().mode() & 0o777, 0o200 @@ -1069,8 +1030,11 @@ mod tests { std::fs::metadata(&dest).unwrap().permissions().mode() & 0o777, 0o200 ); + assert_eq!(std::fs::metadata(&dest).unwrap().ino(), inode); std::fs::set_permissions(&dest, std::fs::Permissions::from_mode(0o600)).unwrap(); assert_eq!(std::fs::read(&dest).unwrap(), b"new bytes"); + } else { + eprintln!("SKIP: restricted-directory permissions are not enforced for this user"); } } let state = transfer_state(0); @@ -1202,7 +1166,6 @@ mod tests { .clone(), Some(Duration::from_millis(150)), Default::default(), - Default::default(), ); let batch = instruction(operation, &url, &dest); let error = tokio::time::timeout( @@ -1262,7 +1225,6 @@ mod tests { transfer_state(0).retry.clone(), Some(Duration::from_millis(150)), Default::default(), - Default::default(), ); state .complete( From 1748e2d9875700daf3904b263990269091de2407 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Thu, 19 Nov 2026 21:44:31 +0000 Subject: [PATCH 44/63] fix(volume): move file work off the async runtime Signed-off-by: Aakash Saravanan --- src/volume.rs | 289 +++++++++++++++++++++++++++++++------------------- 1 file changed, 181 insertions(+), 108 deletions(-) diff --git a/src/volume.rs b/src/volume.rs index 45cb89bc..b386bc5a 100644 --- a/src/volume.rs +++ b/src/volume.rs @@ -38,7 +38,6 @@ use tokio_util::sync::CancellationToken; /// preserves existing bytes; a failure during the copy can leave the destination /// partially written. Cancellation after publication starts does not interrupt it. /// GET decodes gzip Content-Encoding before writing the downloaded bytes. -/// Filesystem setup and publication are synchronous and can delay cancellation. #[derive(Debug, Clone, Default)] pub struct VolumeOptions { pub allowed_paths: Vec, @@ -99,7 +98,11 @@ impl VolumeState { return Ok(Err(cancelled())); } let complete = async { - let (batch, client) = prepare.await?; + let (batch, client) = tokio::select! { + biased; + result = prepare => result?, + _ = self.cancellation.cancelled() => return Err(cancelled()), + }; let instruction = Instruction::decode(&batch)?; if matches!(instruction.operation, Operation::Put(Source::Stream)) && input_bytes.is_none() @@ -109,11 +112,7 @@ impl VolumeState { self.transfer(instruction, &client, options, input_bytes) .await }; - let result = tokio::select! { - biased; - result = complete => result, - _ = self.cancellation.cancelled() => Err(cancelled()), - }; + let result = complete.await; if matches!(result, Ok(VolumeCompletion::NeedsInputStream)) { self.started.store(false, Ordering::Release); // Leave the cell uninitialized so completion can resume with input bytes. @@ -168,7 +167,10 @@ impl VolumeState { if started.elapsed().saturating_add(wait) >= self.retry.overall_timeout { return Err(error.with_retryable(false)); } - tokio::time::sleep(wait).await; + tokio::select! { + _ = tokio::time::sleep(wait) => {} + _ = self.cancellation.cancelled() => return Err(cancelled()), + } attempt += 1; } } @@ -181,12 +183,62 @@ impl VolumeState { input: Option<&Bytes>, retry_after: &mut Option, ) -> Result { - let (method, local_file) = match &instruction.operation { - Operation::Put(Source::File(path)) => (Method::PUT, path.to_string_lossy()), - Operation::Get(path) => (Method::GET, path.to_string_lossy()), - Operation::Put(Source::Stream) => (Method::PUT, std::borrow::Cow::Borrowed("")), - Operation::Remove => (Method::DELETE, std::borrow::Cow::Borrowed("")), + let operation = instruction.operation.clone(); + let roots = options.allowed_paths.clone(); + let preparation = tokio::task::spawn_blocking(move || { + let mut source = None; + let mut destination = None; + let (method, local_file) = match operation { + Operation::Put(Source::File(path)) => { + let local_file = path.to_string_lossy().into_owned(); + let path = allowed_path(&local_file, &roots)?; + let mut file = + std::fs::File::open(path).map_err(|e| local_error(e, &local_file))?; + let metadata = file.metadata().map_err(|e| local_error(e, &local_file))?; + if metadata.is_dir() { + // Reading the opened directory retains the platform's filesystem cause. + let error = std::io::Read::read(&mut file, &mut [0]) + .err() + .unwrap_or_else(|| std::io::ErrorKind::IsADirectory.into()); + return Err(local_error(error, &local_file)); + } + source = Some((file, metadata.len())); + (Method::PUT, local_file) + } + Operation::Get(path) => { + let local_file = path.to_string_lossy().into_owned(); + let path = allowed_path(&local_file, &roots)?; + let existing = match std::fs::OpenOptions::new().write(true).open(&path) { + Ok(file) => Some(file), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => None, + Err(error) => return Err(local_error(error, &local_file)), + }; + let temp = tempfile::tempfile_in( + path.parent() + .ok_or_else(|| invalid("Missing destination parent"))?, + ) + .or_else(|_| tempfile::tempfile()) + .map_err(|e| local_error(e, &local_file))?; + let writer = tokio::fs::File::from_std( + temp.try_clone().map_err(|e| local_error(e, &local_file))?, + ); + destination = Some((temp, writer, existing, path)); + (Method::GET, local_file) + } + Operation::Put(Source::Stream) => (Method::PUT, String::new()), + Operation::Remove => (Method::DELETE, String::new()), + }; + Ok((method, local_file, source, destination)) + }); + let (method, local_file, source, mut destination) = tokio::select! { + biased; + result = preparation => result.map_err(|e| { + Error::internal().message(format!("Volume file preparation task failed: {e}")) + })??, + _ = self.cancellation.cancelled() => return Err(cancelled()), }; + let upload = method == Method::PUT; + let remove = method == Method::DELETE; let mut request = client .request(method, &instruction.url) .headers(instruction.headers.clone()); @@ -198,118 +250,89 @@ impl VolumeState { )])) .body(bytes.clone()); } - let operation = match &instruction.operation { - Operation::Put(Source::File(_)) => Operation::Put(Source::File(allowed_path( - &local_file, - &options.allowed_paths, - )?)), - Operation::Get(_) => Operation::Get(allowed_path(&local_file, &options.allowed_paths)?), - Operation::Put(Source::Stream) => Operation::Put(Source::Stream), - Operation::Remove => Operation::Remove, - }; - let mut destination = if let Operation::Get(path) = &operation { - let existing = match std::fs::OpenOptions::new().write(true).open(path) { - Ok(file) => Some(file), - Err(error) if error.kind() == std::io::ErrorKind::NotFound => None, - Err(error) => return Err(local_error(error, &local_file)), - }; - let temp = tempfile::tempfile_in( - path.parent() - .ok_or_else(|| invalid("Missing destination parent"))?, - ) - .or_else(|_| tempfile::tempfile()) - .map_err(|e| local_error(e, &local_file))?; - let writer = tokio::fs::File::from_std( - temp.try_clone().map_err(|e| local_error(e, &local_file))?, - ); - Some((temp, writer, existing, path)) - } else { - None - }; - - let retry_timeout = !matches!(operation, Operation::Put(_)); let upload_error = Arc::new(Mutex::new(None)); - if let Operation::Put(Source::File(path)) = &operation { - let mut file = std::fs::File::open(path).map_err(|e| local_error(e, &local_file))?; - let metadata = file.metadata().map_err(|e| local_error(e, &local_file))?; - if metadata.is_dir() { - // Reading the opened directory retains the platform's filesystem cause. - let error = std::io::Read::read(&mut file, &mut [0]) - .err() - .unwrap_or_else(|| std::io::ErrorKind::IsADirectory.into()); - return Err(local_error(error, &local_file)); - } + if let Some((file, length)) = source { request = request .headers(HeaderMap::from_iter([( reqwest::header::CONTENT_LENGTH, - metadata.len().into(), + length.into(), )])) .body(upload_body( tokio::fs::File::from_std(file), - local_file.to_string(), + local_file.clone(), Arc::clone(&upload_error), )); } - let mut response = storage_send( - request, - self.read_timeout, - matches!(operation, Operation::Put(_)), - upload_error, - ) - .await?; - let status = response.status(); - if !(status.is_success() - || (matches!(operation, Operation::Remove) - && status.as_u16() == 404 - && options.remove_not_found_is_success)) - { - *retry_after = response - .headers() - .get(reqwest::header::RETRY_AFTER) - .and_then(|value| value.to_str().ok()) - .map(str::to_owned); - return Err(Error::from_http_status(status.as_u16()) - .with_error_code("VOLUME_STORAGE_HTTP_ERROR") - .with_retryable(matches!(status.as_u16(), 408 | 429 | 500 | 502 | 503 | 504)) - .message(format!( - "Volume storage request failed: HTTP {}", - status.as_u16() - ))); - } - while let Some(bytes) = storage_read(self.read_timeout, retry_timeout, async { - response.chunk().await.map_err(response_body_error) - }) - .await? - { + let transfer = async { + let mut response = + storage_send(request, self.read_timeout, upload, upload_error).await?; + let status = response.status(); + if !(status.is_success() + || (remove && status.as_u16() == 404 && options.remove_not_found_is_success)) + { + *retry_after = response + .headers() + .get(reqwest::header::RETRY_AFTER) + .and_then(|value| value.to_str().ok()) + .map(str::to_owned); + return Err(Error::from_http_status(status.as_u16()) + .with_error_code("VOLUME_STORAGE_HTTP_ERROR") + .with_retryable(matches!(status.as_u16(), 408 | 429 | 500 | 502 | 503 | 504)) + .message(format!( + "Volume storage request failed: HTTP {}", + status.as_u16() + ))); + } + while let Some(bytes) = storage_read(self.read_timeout, !upload, async { + response.chunk().await.map_err(response_body_error) + }) + .await? + { + if let Some((_, writer, _, _)) = destination.as_mut() { + writer + .write_all(&bytes) + .await + .map_err(|e| local_error(e, &local_file))?; + } + } if let Some((_, writer, _, _)) = destination.as_mut() { writer - .write_all(&bytes) + .flush() .await .map_err(|e| local_error(e, &local_file))?; } + Ok(()) + }; + tokio::select! { + biased; + result = transfer => result?, + _ = self.cancellation.cancelled() => return Err(cancelled()), } - if let Some((mut temp, mut writer, existing, path)) = destination.take() { - writer - .flush() - .await - .map_err(|e| local_error(e, &local_file))?; + if let Some((mut temp, writer, existing, path)) = destination.take() { drop(writer); - if self.cancellation.is_cancelled() { - return Err(cancelled()); - } - let mut file = match existing { - Some(file) => file, - None => std::fs::OpenOptions::new() - .write(true) - .create_new(true) - .open(path) - .map_err(|e| local_error(e, &local_file))?, - }; - std::io::Seek::rewind(&mut temp).map_err(|e| local_error(e, &local_file))?; - let length = - std::io::copy(&mut temp, &mut file).map_err(|e| local_error(e, &local_file))?; - file.set_len(length) - .map_err(|e| local_error(e, &local_file))?; + let cancellation = self.cancellation.clone(); + tokio::task::spawn_blocking(move || { + if cancellation.is_cancelled() { + return Err(cancelled()); + } + let mut file = match existing { + Some(file) => file, + None => std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(path) + .map_err(|e| local_error(e, &local_file))?, + }; + std::io::Seek::rewind(&mut temp).map_err(|e| local_error(e, &local_file))?; + let length = + std::io::copy(&mut temp, &mut file).map_err(|e| local_error(e, &local_file))?; + file.set_len(length) + .map_err(|e| local_error(e, &local_file)) + }) + .await + .map_err(|e| { + Error::internal().message(format!("Volume publication task failed: {e}")) + })??; } Ok(VolumeCompletion::Completed) } @@ -530,11 +553,13 @@ fn allowed_path(requested: &str, roots: &[PathBuf]) -> Result { )) } +#[derive(Clone)] enum Source { File(PathBuf), Stream, } +#[derive(Clone)] enum Operation { Put(Source), Get(PathBuf), @@ -1059,6 +1084,54 @@ mod tests { assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 1); } + #[tokio::test] + #[cfg(unix)] + async fn cancellation_returns_while_local_preparation_waits_for_a_fifo_writer() { + let dir = tempfile::tempdir().unwrap(); + let source = dir.path().join("source"); + assert!(std::process::Command::new("mkfifo") + .arg(&source) + .status() + .unwrap() + .success()); + let state = transfer_state(0); + let canceller = Arc::clone(&state); + let client = Client::new(); + let batch = instruction("PUT", "http://unused.invalid/object", &source); + let (release, released) = std::sync::mpsc::channel(); + let writer = std::thread::spawn(move || { + released.recv().unwrap(); + std::thread::sleep(Duration::from_millis(50)); + let started = std::time::Instant::now(); + canceller.cancel(); + let cancel_elapsed = started.elapsed(); + let completion_wait_expired = released.recv_timeout(Duration::from_secs(2)).is_err(); + let _writer = std::fs::OpenOptions::new() + .write(true) + .open(source) + .unwrap(); + (cancel_elapsed, completion_wait_expired) + }); + let started = std::time::Instant::now(); + let result = state + .complete( + async { + release.send(()).unwrap(); + Ok((batch, client)) + }, + &options(dir.path()), + None, + ) + .await; + let completion_elapsed = started.elapsed(); + let _ = release.send(()); + let (cancel_elapsed, completion_wait_expired) = writer.join().unwrap(); + assert_eq!(result.unwrap_err().code, crate::ErrorCode::Cancelled); + assert!(cancel_elapsed < Duration::from_millis(500)); + assert!(completion_elapsed < Duration::from_millis(500)); + assert!(!completion_wait_expired); + } + #[tokio::test] async fn abandoned_or_cancelled_get_cannot_publish_or_restart() { let server = MockServer::start().await; From 49e36efac448e7cede7b0f6093fc9b1657f085fb Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Fri, 20 Nov 2026 00:39:58 +0000 Subject: [PATCH 45/63] fix(volume): bound idle transfers and preserve completion diagnostics Signed-off-by: Aakash Saravanan --- NEXT_CHANGELOG.md | 4 +- README.md | 11 +- adbc/src/config.rs | 11 +- adbc/src/statement.rs | 10 +- include/databricks_kernel.h | 10 +- napi/README.md | 2 +- napi/index.d.ts | 18 +- napi/src/async_statement.rs | 14 +- napi/src/database.rs | 26 +- napi/src/error.rs | 35 +-- napi/src/statement.rs | 16 +- pyo3/NEXT_CHANGELOG.md | 2 +- pyo3/src/errors.rs | 15 +- pyo3/src/result_stream.rs | 40 ++- pyo3/src/statement.rs | 20 +- src/c_abi/error.rs | 46 ++- src/c_abi/result.rs | 53 ++-- src/c_abi/session.rs | 46 ++- src/client/http.rs | 11 +- src/client/http_tls_tests.rs | 2 +- src/config.rs | 5 +- src/kernel_error.rs | 10 +- src/result_stream.rs | 42 +-- src/session.rs | 6 +- src/statement/executed_async.rs | 2 +- src/statement/mutable.rs | 8 +- src/telemetry/statement.rs | 13 +- src/volume.rs | 497 +++++++++++++++++++++----------- tests/v0_volume_wiremock.rs | 145 +++++----- 29 files changed, 658 insertions(+), 462 deletions(-) diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index 5721d60b..9e1f9242 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -12,8 +12,8 @@ changes go in their respective binding's NEXT_CHANGELOG. ### Added - Explicit, execution-scoped completion of server-marked Volume PUT/GET/REMOVE - instructions, with allowed-root checks, resumable owned-byte PUT input, safe GET - replacement and cached completion outcomes. Resolved symlink targets must remain + instructions, with allowed-root checks, resumable owned-byte PUT input, in-place GET + publication and cached completion outcomes. Resolved symlink targets must remain within the configured roots. ### Changed diff --git a/README.md b/README.md index 4ef32a2a..8d325241 100644 --- a/README.md +++ b/README.md @@ -68,13 +68,10 @@ and security vulnerabilities should be reported according to ## Volume file operations -Call `ResultStream::complete_volume_operation` with `VolumeOptions` to complete -server-marked PUT, GET and REMOVE instructions before reading their rows. Omit -completion for raw results. File paths must satisfy the configured lexical and -resolved roots. Stream PUT returns `NeedsInputStream` until owned bytes are supplied. -Completion caches its outcome, including errors; owner/session close cancels pending -work. See [`VolumeOptions`](https://docs.rs/databricks-sql-kernel/latest/databricks_sql_kernel/struct.VolumeOptions.html) -for local file and transfer behavior. +Call `ResultStream::complete_volume_operation` with `VolumeOptions` before reading +server-marked PUT, GET and REMOVE rows; omit completion for raw results. +See [`VolumeOptions`](https://docs.rs/databricks-sql-kernel/latest/databricks_sql_kernel/struct.VolumeOptions.html) +for authorization, completion and transfer behavior. ## License diff --git a/adbc/src/config.rs b/adbc/src/config.rs index 65b42e9e..ca15f31e 100644 --- a/adbc/src/config.rs +++ b/adbc/src/config.rs @@ -386,7 +386,11 @@ impl DatabaseConfig { "adbc.databricks.http_request_timeout" => { self.http.request_timeout = duration_seconds(value, key)? } - "SocketTimeout" => self.http.request_timeout = duration(value, key, false)?, + "SocketTimeout" => { + let timeout = duration(value, key, false)?; + self.http.request_timeout = timeout; + self.http.storage_read_timeout = Some(timeout); + } _ if key.starts_with(HTTP_PREFIX) => self.set_http(key, value)?, _ if key.starts_with(PROXY_PREFIX) => self.set_proxy(key, value)?, _ if key.starts_with(TLS_PREFIX) => self.set_tls(key, value)?, @@ -1695,6 +1699,7 @@ mod tests { #[test] fn http_pool_and_custom_headers_reach_kernel_config() { let mut config = DatabaseConfig::default(); + set(&mut config, "SocketTimeout", 4500_i64); set(&mut config, HOST, "https://example.databricks.com"); set(&mut config, HTTP_PATH, "/sql/1.0/warehouses/warehouse-id"); set(&mut config, ACCESS_TOKEN, "sentinel-token"); @@ -1712,6 +1717,10 @@ mod tests { let resolved = config.resolve().unwrap(); assert_eq!(resolved.http.pool_max_idle_per_host, 37); + assert_eq!( + resolved.http.storage_read_timeout, + Some(Duration::from_millis(4500)) + ); assert_eq!( resolved.user_agent_entry.as_deref(), Some("partner+product") diff --git a/adbc/src/statement.rs b/adbc/src/statement.rs index 33fd2a79..e0bb15e5 100644 --- a/adbc/src/statement.rs +++ b/adbc/src/statement.rs @@ -501,10 +501,10 @@ impl Statement { Status::InvalidArguments, ) })?; - self.volume_options = Some(kernel::VolumeOptions { - allowed_paths: roots.into_iter().map(Into::into).collect(), - remove_not_found_is_success: false, - }); + self.volume_options = Some(kernel::VolumeOptions::new( + roots.into_iter().map(Into::into).collect(), + true, + )); Ok(()) } ENABLE_DIRECT_RESULTS_OPTION => { @@ -1600,7 +1600,7 @@ mod tests { .await; Mock::given(method("DELETE")) .and(path("/object")) - .respond_with(ResponseTemplate::new(200)) + .respond_with(ResponseTemplate::new(404)) .with_priority(1) .expect(7) .mount(&server) diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h index b41b99f5..696b0b38 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -375,11 +375,16 @@ KernelStatusCode kernel_session_config_set_sea_response_compression_enabled( /* Configure the total timeout for one HTTP request, from connection start * through response-body completion. A separate 30s connection timeout also * applies, so connection establishment is bounded by the shorter limit. - * Does not bound Volume storage requests or configure their inactivity limit. + * Volume storage inactivity uses the separate storage-read-timeout setter. * `request_timeout_ms == 0` keeps the kernel default (120s). */ KernelStatusCode kernel_session_config_set_request_timeout(KernelSessionConfig* config, uint64_t request_timeout_ms); +/* Configure Volume storage idle time for reads, upload progress and PUT response + * waits. Zero disables it. Redirected stream PUT resends have no idle bound. */ +KernelStatusCode kernel_session_config_set_storage_read_timeout(KernelSessionConfig* config, + uint64_t timeout_ms); + /* Configure the maximum number of idle HTTP connections retained per host. * `max_connections` must be greater than zero. Omitting this setter keeps the * kernel default (100). */ @@ -979,7 +984,8 @@ typedef enum KernelVolumeCompletion { KernelVolumeCompletion_Completed = 2 } KernelVolumeCompletion; -/* Volume completion preserves raw rows. Roots are a JSON array of strings. +/* Complete a server-marked file transfer while retaining its instruction rows. + * Roots are a JSON array of strings. * The detached result-stream canceller can interrupt completion. */ KernelStatusCode kernel_executed_statement_is_volume_operation( const kernel_executed_statement_t* exec, bool* out); diff --git a/napi/README.md b/napi/README.md index b7d6cdc4..b71d3df3 100644 --- a/napi/README.md +++ b/napi/README.md @@ -8,7 +8,7 @@ The binding itself lives under `src/`; its public TypeScript surface is declared in `index.d.ts`. `Statement` and `AsyncResultHandle` expose `isVolumeOperation` and -`completeVolumeOperation(allowedPaths, removeNotFoundIsSuccess?)`. Completion +`completeVolumeOperation(allowedPaths, removeNotFoundIsSuccess)`. Completion returns `not_volume`, `needs_input_stream` or `completed` and preserves the instruction rows. The caller opts into transfer by supplying allowed local roots; both lexical paths and resolved symlink targets must stay inside them. diff --git a/napi/index.d.ts b/napi/index.d.ts index 4e29856a..4ea46e56 100644 --- a/napi/index.d.ts +++ b/napi/index.d.ts @@ -603,15 +603,11 @@ export interface ConnectionOptions { */ proxy?: ProxyInput /** - * Per-connection HTTP request deadline, in milliseconds. Caps a single - * request through response-body completion. Maps onto the kernel - * [`HttpConfig::request_timeout`] (the internal reqwest - * `Client::timeout`). Does not bound Volume storage requests or configure - * their inactivity limit. Storage connection setup has a separate timeout. - * - * Omitted ⇒ kernel default (120 000 ms / 120 s). Napi-rs - * serialises `u32` as JS `number`; the largest representable value - * (~49.7 days) far exceeds any sensible socket timeout. + * SQL request deadline and Volume storage idle timeout, in milliseconds. + * Storage idle time bounds reads, upload progress and the PUT response wait; + * a redirected stream PUT resend has no idle bound. + * Omitted: SQL uses the kernel default; storage uses 15 minutes. + * Zero disables storage inactivity and keeps the SQL default. */ socketTimeoutMs?: number } @@ -879,7 +875,7 @@ export declare class AsyncStatement { export declare class AsyncResultHandle { get isVolumeOperation(): boolean /** Completes marked file transfers and retains the instruction rows. */ - completeVolumeOperation(allowedPaths: Array, removeNotFoundIsSuccess?: boolean | undefined | null): Promise + completeVolumeOperation(allowedPaths: Array, removeNotFoundIsSuccess: boolean): Promise /** * Server-issued statement id. Cached at construction; readable * for log correlation. Matches the parent `AsyncStatement`'s @@ -1176,7 +1172,7 @@ export declare class Connection { export declare class Statement { get isVolumeOperation(): boolean /** Completes marked file transfers and retains the instruction rows. */ - completeVolumeOperation(allowedPaths: Array, removeNotFoundIsSuccess?: boolean | undefined | null): Promise + completeVolumeOperation(allowedPaths: Array, removeNotFoundIsSuccess: boolean): Promise /** * Server-issued statement id. Cached at construction; readable * even after `close()` so JS-side log lines can correlate against diff --git a/napi/src/async_statement.rs b/napi/src/async_statement.rs index 5f0a8a6d..669c6991 100644 --- a/napi/src/async_statement.rs +++ b/napi/src/async_statement.rs @@ -497,12 +497,12 @@ impl AsyncResultHandle { pub async fn complete_volume_operation( &self, allowed_paths: Vec, - remove_not_found_is_success: Option, + remove_not_found_is_success: bool, ) -> napi::Result { - let options = VolumeOptions { - allowed_paths: allowed_paths.into_iter().map(Into::into).collect(), - remove_not_found_is_success: remove_not_found_is_success.unwrap_or(false), - }; + let options = VolumeOptions::new( + allowed_paths.into_iter().map(Into::into).collect(), + remove_not_found_is_success, + ); let inner = Arc::clone(&self.inner); guarded(async move { let mut guard = inner.lock().await; @@ -818,8 +818,6 @@ mod tests { .expect("closed result must release its session after the operation finishes"); let second = telemetry_connection(&server, 1_000, Duration::from_secs(300)).await; - tokio::time::sleep(Duration::from_millis(500)).await; - assert_eq!(exports_for(&server, SECOND_SESSION).await, 0); second.close().await.expect("close second session"); assert!(exports_for(&server, SECOND_SESSION).await > 0); drop((statement, result)); @@ -860,8 +858,6 @@ mod tests { sync_statement.close().await.expect("close is terminal"); connection.close().await.expect("close session"); let second = telemetry_connection(&server, 1_000, Duration::from_secs(300)).await; - tokio::time::sleep(Duration::from_millis(500)).await; - assert_eq!(exports_for(&server, SECOND_SESSION).await, 0); second.close().await.expect("close second session"); drop(sync_statement); } diff --git a/napi/src/database.rs b/napi/src/database.rs index 3cb14629..3409b062 100644 --- a/napi/src/database.rs +++ b/napi/src/database.rs @@ -453,15 +453,11 @@ pub struct ConnectionOptions { /// server) can now route a single connection through a proxy /// programmatically. pub proxy: Option, - /// Per-connection HTTP request deadline, in milliseconds. Caps a single - /// request through response-body completion. Maps onto the kernel - /// [`HttpConfig::request_timeout`] (the internal reqwest - /// `Client::timeout`). Does not bound Volume storage requests or configure - /// their inactivity limit. Storage connection setup has a separate timeout. - /// - /// Omitted ⇒ kernel default (120 000 ms / 120 s). Napi-rs - /// serialises `u32` as JS `number`; the largest representable value - /// (~49.7 days) far exceeds any sensible socket timeout. + /// SQL request deadline and Volume storage idle timeout, in milliseconds. + /// Storage idle time bounds reads, upload progress and the PUT response wait; + /// a redirected stream PUT resend has no idle bound. + /// Omitted: SQL uses the kernel default; storage uses 15 minutes. + /// Zero disables storage inactivity and keeps the SQL default. pub socket_timeout_ms: Option, } @@ -656,9 +652,14 @@ fn build_http_config(options: &mut ConnectionOptions) -> HttpConfig { // Per-connection request deadline. Maps onto the kernel's // `request_timeout` (the reqwest `Client::timeout`). Omitted ⇒ kernel // default (120 s). - if let Some(ms) = options.socket_timeout_ms { + if let Some(ms) = options.socket_timeout_ms.filter(|ms| *ms != 0) { http.request_timeout = std::time::Duration::from_millis(u64::from(ms)); } + http.storage_read_timeout = options + .socket_timeout_ms + .or(Some(15 * 60 * 1000)) + .filter(|ms| *ms != 0) + .map(|ms| std::time::Duration::from_millis(u64::from(ms))); http } @@ -1587,11 +1588,16 @@ mod tests { #[test] fn http_retry_knobs_map_onto_http_config() { let mut o = base(); + o.socket_timeout_ms = Some(4_500); o.retry_min_wait_secs = Some(2); o.retry_max_wait_secs = Some(45); o.retry_max_attempts = Some(4); // total attempts → 3 retries o.retry_overall_timeout_secs = Some(120); let http = build_http_config(&mut o); + assert_eq!( + http.storage_read_timeout, + Some(std::time::Duration::from_millis(4_500)) + ); assert_eq!(http.retry_min_wait, std::time::Duration::from_secs(2)); assert_eq!(http.retry_max_wait, std::time::Duration::from_secs(45)); // total attempts (4) → retries after the first (3): the off-by-one. diff --git a/napi/src/error.rs b/napi/src/error.rs index a12070f9..4a359062 100644 --- a/napi/src/error.rs +++ b/napi/src/error.rs @@ -82,14 +82,8 @@ 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. +/// Both bindings carry extended status; NAPI encodes camelCase JSON and PyO3 +/// attaches snake_case exception attributes. /// /// The whole JSON-envelope-on-`reason` scheme is interim. The follow-up /// PR that lands the first `#[napi]` entry points (PR #25) is expected @@ -326,29 +320,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…`. + /// Both bindings expose structured kernel fields; NAPI uses camelCase JSON + /// and PyO3 uses snake_case exception attributes. #[test] fn envelope_field_set_matches_pyo3_setattr_contract() { // Build a kernel error with every optional field populated so diff --git a/napi/src/statement.rs b/napi/src/statement.rs index 112bd683..0db77527 100644 --- a/napi/src/statement.rs +++ b/napi/src/statement.rs @@ -207,12 +207,12 @@ impl Statement { pub async fn complete_volume_operation( &self, allowed_paths: Vec, - remove_not_found_is_success: Option, + remove_not_found_is_success: bool, ) -> napi::Result { - let options = VolumeOptions { - allowed_paths: allowed_paths.into_iter().map(Into::into).collect(), - remove_not_found_is_success: remove_not_found_is_success.unwrap_or(false), - }; + let options = VolumeOptions::new( + allowed_paths.into_iter().map(Into::into).collect(), + remove_not_found_is_success, + ); let inner = Arc::clone(&self.inner); guarded(async move { let mut guard = inner.lock().await; @@ -706,7 +706,7 @@ mod tests { assert!(result.is_volume_operation()); assert_eq!( result - .complete_volume_operation(vec![], None) + .complete_volume_operation(vec![], false) .await .unwrap(), crate::result::VolumeCompletion::Completed @@ -720,7 +720,7 @@ mod tests { assert!(result.is_volume_operation()); assert_eq!( result - .complete_volume_operation(vec![], None) + .complete_volume_operation(vec![], false) .await .unwrap(), crate::result::VolumeCompletion::Completed @@ -762,7 +762,7 @@ mod tests { parent.spec().sql("operation"); let executed = parent.execute().await.unwrap(); let result = Statement::from_executed(parent, executed); - let completion = result.complete_volume_operation(vec![], None); + let completion = result.complete_volume_operation(vec![], false); tokio::pin!(completion); tokio::select! { finished = &mut completion => panic!("completion finished before close: {finished:?}"), diff --git a/pyo3/NEXT_CHANGELOG.md b/pyo3/NEXT_CHANGELOG.md index b10c0fa0..f64d405b 100644 --- a/pyo3/NEXT_CHANGELOG.md +++ b/pyo3/NEXT_CHANGELOG.md @@ -15,7 +15,7 @@ changes go in the root `NEXT_CHANGELOG.md`. - `ExecutedStatement` and `ResultStream` expose `is_volume_operation` and `complete_volume_operation` for explicit Volume transfers, including owned-byte - stream uploads. Filesystem errors retain their OS code, kind and requested path. + stream uploads. Filesystem errors retain their OS code and requested path. ### Changed diff --git a/pyo3/src/errors.rs b/pyo3/src/errors.rs index fc11becd..1a40fb7a 100644 --- a/pyo3/src/errors.rs +++ b/pyo3/src/errors.rs @@ -70,7 +70,10 @@ fn attach_attrs( display_message: Option<&str>, diagnostic_info: Option<&str>, error_details_json: Option<&str>, + local: Option<&databricks_sql_kernel::kernel_error::LocalFileError>, ) -> PyResult<()> { + bound.setattr("local_os_error", local.and_then(|e| e.raw_os_error))?; + bound.setattr("local_path", local.map(|e| e.path.as_str()))?; bound.setattr("code", code)?; bound.setattr("message", message)?; bound.setattr("sql_state", sql_state)?; @@ -138,6 +141,7 @@ pub(crate) fn to_py_err(py: Python<'_>, err: KError) -> PyErr { err.display_message.as_deref(), err.diagnostic_info.as_deref(), err.error_details_json.as_deref(), + err.local_error.as_deref(), ) { // Attribute attachment is best-effort. If something goes wrong // (extremely unlikely for plain string/int setattrs — but @@ -154,16 +158,6 @@ pub(crate) fn to_py_err(py: Python<'_>, err: KError) -> PyErr { chained.set_cause(py, Some(setattr_err)); return chained; } - let local = err.local_error.as_ref(); - if let Err(error) = (|| -> PyResult<()> { - bound.setattr("local_os_error", local.and_then(|e| e.raw_os_error))?; - bound.setattr("local_error_kind", local.map(|e| format!("{:?}", e.kind)))?; - bound.setattr("local_path", local.map(|e| e.path.as_str()))?; - Ok(()) - })() { - py_err.set_cause(py, Some(error)); - return py_err; - } py_err } @@ -192,6 +186,7 @@ pub(crate) fn closed_err(handle_name: &str) -> PyErr { None, None, None, + None, ) { return setattr_err; } diff --git a/pyo3/src/result_stream.rs b/pyo3/src/result_stream.rs index 1f9a62ad..0f94b335 100644 --- a/pyo3/src/result_stream.rs +++ b/pyo3/src/result_stream.rs @@ -72,6 +72,26 @@ impl From for VolumeCompletion { } } +pub(crate) fn complete_volume( + py: Python<'_>, + runtime: &Arc, + stream: &mut KResultStream, + allowed_paths: Vec, + remove_not_found_is_success: bool, + input_bytes: Option>, +) -> PyResult { + let options = databricks_sql_kernel::VolumeOptions::new( + allowed_paths.into_iter().map(Into::into).collect(), + remove_not_found_is_success, + ); + Ok(run_kernel_interruptible!( + py, + runtime, + stream.complete_volume_operation(&options, input_bytes) + )? + .into()) +} + #[pymethods] impl ResultStream { #[getter] @@ -80,7 +100,7 @@ impl ResultStream { Ok(inner.stream.is_volume_operation()) } - #[pyo3(signature = (allowed_paths, remove_not_found_is_success=false, input_bytes=None))] + #[pyo3(signature = (allowed_paths, remove_not_found_is_success, input_bytes=None))] fn complete_volume_operation( &mut self, py: Python<'_>, @@ -89,18 +109,14 @@ impl ResultStream { input_bytes: Option>, ) -> PyResult { let inner = alive_mut!(self, "ResultStream"); - let runtime = inner.runtime.clone(); - let options = databricks_sql_kernel::VolumeOptions { - allowed_paths: allowed_paths.into_iter().map(Into::into).collect(), - remove_not_found_is_success, - }; - let stream = &mut inner.stream; - let outcome = run_kernel_interruptible!( + complete_volume( py, - &runtime, - stream.complete_volume_operation(&options, input_bytes) - )?; - Ok(outcome.into()) + &inner.runtime, + &mut inner.stream, + allowed_paths, + remove_not_found_is_success, + input_bytes, + ) } /// Result schema as a `pyarrow.Schema`. Available even after `close()`. diff --git a/pyo3/src/statement.rs b/pyo3/src/statement.rs index 61072e10..c052f3a9 100644 --- a/pyo3/src/statement.rs +++ b/pyo3/src/statement.rs @@ -327,7 +327,7 @@ impl ExecutedStatement { Ok(inner.exec.result_stream().is_volume_operation()) } - #[pyo3(signature = (allowed_paths, remove_not_found_is_success=false, input_bytes=None))] + #[pyo3(signature = (allowed_paths, remove_not_found_is_success, input_bytes=None))] fn complete_volume_operation( &mut self, py: Python<'_>, @@ -336,18 +336,14 @@ impl ExecutedStatement { input_bytes: Option>, ) -> PyResult { let inner = alive_mut!(self, "ExecutedStatement"); - let runtime = inner.runtime.clone(); - let options = databricks_sql_kernel::VolumeOptions { - allowed_paths: allowed_paths.into_iter().map(Into::into).collect(), - remove_not_found_is_success, - }; - let stream = inner.exec.result_stream_mut(); - let outcome = run_kernel_interruptible!( + crate::result_stream::complete_volume( py, - &runtime, - stream.complete_volume_operation(&options, input_bytes) - )?; - Ok(outcome.into()) + &inner.runtime, + inner.exec.result_stream_mut(), + allowed_paths, + remove_not_found_is_success, + input_bytes, + ) } #[getter] diff --git a/src/c_abi/error.rs b/src/c_abi/error.rs index 92581035..d6e67ad7 100644 --- a/src/c_abi/error.rs +++ b/src/c_abi/error.rs @@ -230,28 +230,6 @@ pub(crate) fn store_invalid_arg(msg: &str) -> KernelStatusCode { mod tests { use super::*; - #[test] - fn local_error_getters_preserve_error_until_clear() { - let mut error = Error::not_found().message("missing local file"); - error.local_error = Some(Box::new(crate::kernel_error::LocalFileError { - raw_os_error: Some(2), - kind: std::io::ErrorKind::NotFound, - path: "local-file".into(), - })); - store_error(error); - assert_eq!(kernel_get_last_error_local_os_error(), 2); - assert_eq!( - unsafe { std::ffi::CStr::from_ptr(kernel_get_last_error_local_path()) } - .to_str() - .unwrap(), - "local-file" - ); - with_last_error(|error| assert!(error.is_some())); - clear_error(); - assert_eq!(kernel_get_last_error_local_os_error(), 0); - assert!(kernel_get_last_error_local_path().is_null()); - } - /// Helper: read the thread-local error into a `KernelError` and run /// `f` with the borrowed C strings still alive. fn with_last_error(f: impl FnOnce(Option) -> R) -> R { @@ -304,11 +282,15 @@ mod tests { #[test] fn store_error_folds_error_code_slug_into_message() { - store_error( - Error::sql_error() - .message("statement gone") - .with_error_code("STATEMENT_NOT_FOUND"), - ); + let mut error = Error::sql_error() + .message("statement gone") + .with_error_code("STATEMENT_NOT_FOUND"); + error.local_error = Some(Box::new(crate::kernel_error::LocalFileError { + raw_os_error: Some(2), + kind: std::io::ErrorKind::NotFound, + path: "local-file".into(), + })); + store_error(error); with_last_error(|e| { let e = e.expect("error present"); let msg = unsafe { std::ffi::CStr::from_ptr(e.message) } @@ -323,8 +305,18 @@ mod tests { "STATEMENT_NOT_FOUND" ); }); + assert_eq!(kernel_get_last_error_local_os_error(), 2); + assert_eq!( + unsafe { std::ffi::CStr::from_ptr(kernel_get_last_error_local_path()) } + .to_str() + .unwrap(), + "local-file" + ); + with_last_error(|error| assert!(error.is_some())); clear_error(); assert!(kernel_get_last_error_code().is_null()); + assert_eq!(kernel_get_last_error_local_os_error(), 0); + assert!(kernel_get_last_error_local_path().is_null()); } #[test] diff --git a/src/c_abi/result.rs b/src/c_abi/result.rs index 099e83dc..4f03b75e 100644 --- a/src/c_abi/result.rs +++ b/src/c_abi/result.rs @@ -535,8 +535,7 @@ pub unsafe extern "C" fn kernel_result_stream_close( if stream.is_null() { return store_invalid_arg("kernel_result_stream_close: stream must not be null"); } - let inner = Box::from_raw(stream as *mut ResultStreamInner); - drop(inner); + drop(Box::from_raw(stream as *mut ResultStreamInner)); KernelStatusCode::Success } @@ -700,10 +699,10 @@ pub unsafe extern "C" fn kernel_result_stream_complete_volume_operation( return store_invalid_arg("Volume allowed paths must be a JSON array of strings") } }; - let options = crate::VolumeOptions { - allowed_paths: roots.into_iter().map(Into::into).collect(), + let options = crate::VolumeOptions::new( + roots.into_iter().map(Into::into).collect(), remove_not_found_is_success, - }; + ); let p = stream as *mut ResultStreamInner; let shape = &mut *std::ptr::addr_of_mut!((*p).shape); let result = match shape { @@ -784,21 +783,21 @@ mod tests { ) .unwrap(); let rt = tokio::runtime::Runtime::new().unwrap(); - let volume = crate::volume::VolumeState::new(Default::default(), None, Default::default()); + let volume = crate::volume::VolumeState::new( + Default::default(), + Arc::new( + crate::client::DatabricksHttpClient::with_default_retry(Default::default()) + .unwrap() + .storage_client(None), + ), + Default::default(), + ); let stream = rt.block_on(async { let mut stream = ResultStream::from_reader(Box::new(MockReader::new(vec![batch.clone()]))) .await .unwrap(); - stream.attach_volume( - true, - Arc::clone(&volume), - Arc::new( - crate::client::DatabricksHttpClient::with_default_retry(Default::default()) - .unwrap() - .storage_client(None), - ), - ); + stream.attach_volume(true, Arc::clone(&volume)); into_raw_result_stream(schema.clone(), stream) }); let mut is_volume = false; @@ -818,19 +817,17 @@ mod tests { unsafe { kernel_result_stream_canceller_cancel(canceller) }, KernelStatusCode::Success ); - for _ in 0..2 { - assert_eq!( - unsafe { - kernel_result_stream_complete_volume_operation( - stream, - roots.as_ptr(), - false, - &mut status, - ) - }, - KernelStatusCode::Cancelled - ); - } + assert_eq!( + unsafe { + kernel_result_stream_complete_volume_operation( + stream, + roots.as_ptr(), + false, + &mut status, + ) + }, + KernelStatusCode::Cancelled + ); unsafe { kernel_result_stream_canceller_free(canceller) }; unsafe { kernel_result_stream_close(stream) }; } diff --git a/src/c_abi/session.rs b/src/c_abi/session.rs index 10978a55..b99c0e8c 100644 --- a/src/c_abi/session.rs +++ b/src/c_abi/session.rs @@ -155,6 +155,7 @@ pub struct KernelSessionConfig { /// Total request timeout (populated by `..._set_request_timeout`). `None` /// keeps [`HttpConfig::default`]'s 120-second timeout. request_timeout: Option, + storage_read_timeout: Option, /// Maximum idle connections retained per host. `None` keeps the kernel /// default; populated by `..._set_max_connections`. max_connections: Option, @@ -289,6 +290,7 @@ pub unsafe extern "C" fn kernel_session_config_new( custom_headers: Vec::new(), sea_response_compression_enabled: false, request_timeout: None, + storage_read_timeout: None, max_connections: None, retry: None, // Default to ignoring transactions, matching IgnoreTransactions=1. @@ -629,7 +631,7 @@ pub unsafe extern "C" fn kernel_session_config_set_sea_response_compression_enab /// Configure the total timeout for one HTTP request, from connection start /// through response-body completion. A separate 30-second connection timeout /// also applies, so connection establishment is bounded by the shorter limit. -/// Does not bound Volume storage requests or configure their inactivity limit. +/// Volume storage inactivity is configured by `kernel_session_config_set_storage_read_timeout`. /// `request_timeout_ms == 0` clears an earlier override and keeps the kernel /// default (120 seconds); a positive value overrides it. /// @@ -647,6 +649,23 @@ pub unsafe extern "C" fn kernel_session_config_set_request_timeout( }) } +/// Configure the Volume storage idle timeout; zero disables it. +/// Bounds reads, upload progress and PUT response waits. Redirected stream PUT +/// resends have no idle bound. +/// +/// # Safety +/// `config` must be a live config handle. +#[no_mangle] +pub unsafe extern "C" fn kernel_session_config_set_storage_read_timeout( + config: *mut KernelSessionConfig, + timeout_ms: u64, +) -> KernelStatusCode { + set_on_config(config, |c| { + c.storage_read_timeout = (timeout_ms != 0).then(|| Duration::from_millis(timeout_ms)); + Ok(()) + }) +} + /// Configure the maximum number of idle HTTP connections retained per host. /// The value must be greater than zero; omitting this setter keeps the kernel /// default (100). @@ -1515,10 +1534,12 @@ fn merge_http_config( request_timeout: Option, max_connections: Option, retry: Option, + storage_read_timeout: Option, ) -> HttpConfig { let mut http = HttpConfig { custom_headers, sea_response_compression_enabled, + storage_read_timeout, ..HttpConfig::default() }; if let Some(t) = request_timeout { @@ -1653,6 +1674,7 @@ fn build_session(config: KernelSessionConfig) -> Result Result Result, } +#[derive(Default)] pub(crate) struct StorageClient { + pub(crate) read_timeout: Option, config: HttpClientConfig, client: tokio::sync::OnceCell, } @@ -513,6 +515,7 @@ impl DatabricksHttpClient { let client = Self::build_reqwest_client( &config, reqwest::redirect::Policy::default(), + // `read_timeout` is historical: reqwest applies it as a total SQL deadline. Some(config.read_timeout), true, )?; @@ -776,12 +779,13 @@ impl DatabricksHttpClient { } /// Storage transfers can outlive SQL RPCs, so retain connection settings without their deadline. - pub(crate) fn storage_client(&self, connect_timeout: Option) -> StorageClient { + pub(crate) fn storage_client(&self, storage_read_timeout: Option) -> StorageClient { let mut config = self.config.clone(); - if let Some(timeout) = connect_timeout { + if let Some(timeout) = storage_read_timeout { config.connect_timeout = config.connect_timeout.min(timeout); } StorageClient { + read_timeout: storage_read_timeout, config, client: tokio::sync::OnceCell::new(), } @@ -1620,7 +1624,8 @@ lGrv15pBcePj let mut config = HttpClientConfig::default(); config.tls.trusted_certificate_path = Some(tmp.path().to_string_lossy().to_string()); - assert!(DatabricksHttpClient::new(config, default_retry_configs()).is_ok()); + let client = DatabricksHttpClient::new(config, default_retry_configs()); + assert!(client.is_ok()); } #[test] diff --git a/src/client/http_tls_tests.rs b/src/client/http_tls_tests.rs index ee67a03e..c676c0c8 100644 --- a/src/client/http_tls_tests.rs +++ b/src/client/http_tls_tests.rs @@ -357,7 +357,7 @@ async fn storage_redirect_rejects_https_to_http_on_the_same_port() { } #[tokio::test] -async fn storage_connection_timeout_preserves_unconfigured_limits() { +async fn storage_idle_timeout_also_bounds_connection_setup() { let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); let address = listener.local_addr().unwrap(); let (shutdown, mut stopped) = oneshot::channel(); diff --git a/src/config.rs b/src/config.rs index bf61d50d..1a33dfec 100644 --- a/src/config.rs +++ b/src/config.rs @@ -758,9 +758,8 @@ pub struct HttpConfig { /// Does not bound Volume storage requests; use `storage_read_timeout` for inactivity. pub request_timeout: Duration, - /// Inactivity limit for Volume GET/REMOVE response headers and each response-body read. - /// Separate from the SQL request deadline so progressing transfers can finish. - /// Also caps connection establishment; PUT response headers have no deadline. + /// Volume idle limit for reads, upload progress and PUT response-header waits. + /// Also caps connection setup; redirected stream PUT resends have no idle bound. pub storage_read_timeout: Option, /// Maximum total time across retries for a single logical RPC. diff --git a/src/kernel_error.rs b/src/kernel_error.rs index 0de63179..372b7263 100644 --- a/src/kernel_error.rs +++ b/src/kernel_error.rs @@ -41,8 +41,8 @@ //! Aborted, Unimplemented, …) lands in a follow-on PR. External //! `match` arms get a forced `_ =>` fallback — they keep compiling //! when the enum grows. -//! - `Error` **is not** `#[non_exhaustive]`: wrappers use struct patterns -//! with `..` for logging and host-language exception mapping. +//! - `Error` supports struct patterns with `..`; constructors and setters avoid +//! coupling callers to its full field list. #![allow(dead_code)] @@ -447,6 +447,12 @@ impl Error { self } + /// Attach the original local filesystem error for binding-specific mapping. + pub fn with_local_error(mut self, local_error: LocalFileError) -> Self { + self.local_error = Some(Box::new(local_error)); + self + } + pub fn with_vendor_code(mut self, vendor_code: i32) -> Self { self.vendor_code = Some(vendor_code); self diff --git a/src/result_stream.rs b/src/result_stream.rs index bd1f0f4b..b3b1a3ad 100644 --- a/src/result_stream.rs +++ b/src/result_stream.rs @@ -494,10 +494,7 @@ pub struct ResultStream { close_guard: Option, telemetry: Option, - volume: Option<( - Arc, - Arc, - )>, + volume: Option>, } struct ResultStreamTelemetry { @@ -644,14 +641,9 @@ impl ResultStream { Ok(stream) } - pub(crate) fn attach_volume( - &mut self, - marked: bool, - state: Arc, - client: Arc, - ) { + pub(crate) fn attach_volume(&mut self, marked: bool, state: Arc) { if marked { - self.volume = Some((state, client)); + self.volume = Some(state); } } @@ -660,7 +652,7 @@ impl ResultStream { self.volume.is_some() } - /// Complete a marked instruction without consuming its result row. + /// Complete a server-marked file transfer while retaining its instruction rows. /// /// Ordinary results and read-only attachments have no transfer authority. /// `NeedsInputStream` requests owned bytes for the server's stream sentinel; @@ -670,9 +662,15 @@ impl ResultStream { options: &crate::volume::VolumeOptions, input_bytes: Option>, ) -> Result { - let Some((state, client)) = self.volume.clone() else { + let Some(state) = self.volume.clone() else { return Ok(crate::volume::VolumeCompletion::NotVolume); }; + if !state.completion.initialized() + && (self.current.is_some() || (self.exhausted && self.prefetched.is_empty())) + { + return Err(Error::invalid_state() + .message("complete_volume_operation must be called before reading result rows")); + } let result = state .complete( async { @@ -693,18 +691,22 @@ impl ResultStream { .as_mut() .expect("Volume completion retains its reader") .next_batch() - .await? + .await { - Some(batch) if batch.num_rows() != 0 => { + Err(error) => { + self.prefetched.push_back(Err(Box::new(error.clone()))); + return Err(error); + } + Ok(Some(batch)) if batch.num_rows() != 0 => { self.prefetched.push_back(Ok(ResultBatch::Arrow(batch))); return Err(Error::invalid_argument() .message("Expected one Volume instruction row")); } - Some(_) => {} - None => self.exhausted = true, + Ok(Some(_)) => {} + Ok(None) => self.exhausted = true, } } - Ok((batch, client.get().await?.clone())) + Ok(batch) }, options, input_bytes, @@ -717,11 +719,11 @@ impl ResultStream { } pub(crate) fn volume_state(&self) -> Option> { - self.volume.as_ref().map(|(state, _)| Arc::clone(state)) + self.volume.as_ref().map(Arc::clone) } pub(crate) fn cancel_volume(&self) { - if let Some((state, _)) = &self.volume { + if let Some(state) = &self.volume { state.cancel(); } } diff --git a/src/session.rs b/src/session.rs index 40d6136f..8798c410 100644 --- a/src/session.rs +++ b/src/session.rs @@ -164,7 +164,7 @@ impl SessionInner { pub(crate) fn new_volume_state(&self) -> Arc { crate::volume::VolumeState::new( self.storage_retry.clone(), - self.config.http.storage_read_timeout, + Arc::clone(&self.storage_client), self.volume_cancellation.child_token(), ) } @@ -173,10 +173,6 @@ impl SessionInner { self.volume_cancellation.cancel(); } - pub(crate) fn storage_client(&self) -> Arc { - Arc::clone(&self.storage_client) - } - /// Crate-internal accessor for the session's transport. Used by /// `Metadata` (and PR 4's `Statement`) to drive RPCs without /// reaching into private fields. diff --git a/src/statement/executed_async.rs b/src/statement/executed_async.rs index af71f96b..65453ae3 100644 --- a/src/statement/executed_async.rs +++ b/src/statement/executed_async.rs @@ -954,7 +954,7 @@ impl ExecutedAsyncStatement { .is_some_and(|m| m.is_volume_operation); let mut stream = ResultStream::from_reader(result.reader).await?; if let Some(volume) = &self.volume { - stream.attach_volume(marked, Arc::clone(volume), self.session.storage_client()); + stream.attach_volume(marked, Arc::clone(volume)); } stream.attach_telemetry(self.statement_telemetry.clone()); // SEA carries no row count on the async status either; for a diff --git a/src/statement/mutable.rs b/src/statement/mutable.rs index 684a693e..72720918 100644 --- a/src/statement/mutable.rs +++ b/src/statement/mutable.rs @@ -418,7 +418,7 @@ impl Statement { .as_ref() .is_some_and(|m| m.is_volume_operation); let mut result_stream = ResultStream::from_reader(result.reader).await?; - result_stream.attach_volume(marked, self.volume_state(), self.session.storage_client()); + result_stream.attach_volume(marked, self.volume_state()); result_stream.attach_telemetry(telemetry_for_body.clone()); // SEA puts no row count on the status envelope; for a DML it // returns the count as the result set. If the server didn't @@ -659,11 +659,7 @@ impl Statement { .as_ref() .is_some_and(|m| m.is_volume_operation); let mut result_stream = ResultStream::from_reader(result.reader).await?; - result_stream.attach_volume( - marked, - self.volume_state(), - self.session.storage_client(), - ); + result_stream.attach_volume(marked, self.volume_state()); result_stream.attach_telemetry(telemetry_for_body.clone()); let mut status = result.status; if status.num_modified_rows.is_none() { diff --git a/src/telemetry/statement.rs b/src/telemetry/statement.rs index 2c300531..4030937a 100644 --- a/src/telemetry/statement.rs +++ b/src/telemetry/statement.rs @@ -409,11 +409,14 @@ mod tests { stream.attach_volume( true, - crate::volume::VolumeState::new(Default::default(), None, Default::default()), - Arc::new( - crate::client::DatabricksHttpClient::with_default_retry(Default::default()) - .unwrap() - .storage_client(None), + crate::volume::VolumeState::new( + Default::default(), + Arc::new( + crate::client::DatabricksHttpClient::with_default_retry(Default::default()) + .unwrap() + .storage_client(None), + ), + Default::default(), ), ); let options = Default::default(); diff --git a/src/volume.rs b/src/volume.rs index b386bc5a..78e3f405 100644 --- a/src/volume.rs +++ b/src/volume.rs @@ -31,19 +31,35 @@ use tokio_util::sync::CancellationToken; /// Local file authorization and driver-specific storage response policy. /// /// Requested and resolved paths must be within allowed roots. Symlinks between -/// authorized roots work; path components must remain stable during file access. +/// authorized roots work; `..` collapses before symlink resolution. Path components +/// must remain stable during file access. /// GET downloads into a temporary file, beside the destination when its directory /// allows it and in the system temporary directory otherwise, then copies it into /// the destination in place. Download failure or cancellation before publication /// preserves existing bytes; a failure during the copy can leave the destination /// partially written. Cancellation after publication starts does not interrupt it. /// GET decodes gzip Content-Encoding before writing the downloaded bytes. +/// The storage idle timeout bounds GET reads, PUT upload progress and the wait for +/// the PUT response. A stream PUT that storage redirects is sent again with its +/// full body, and that resend has no idle bound. A cancelled PUT or REMOVE may +/// already have changed storage. +#[non_exhaustive] #[derive(Debug, Clone, Default)] pub struct VolumeOptions { pub allowed_paths: Vec, pub remove_not_found_is_success: bool, } +impl VolumeOptions { + /// Configure local roots and the binding's missing-object REMOVE policy. + pub fn new(allowed_paths: Vec, remove_not_found_is_success: bool) -> Self { + Self { + allowed_paths, + remove_not_found_is_success, + } + } +} + /// Result of explicitly completing a server-marked Volume instruction. #[derive(Debug, Clone, Copy, PartialEq, Eq)] #[repr(C)] @@ -56,8 +72,8 @@ pub enum VolumeCompletion { #[derive(Default)] pub(crate) struct VolumeState { retry: RetryConfig, - read_timeout: Option, - completion: OnceCell>, + storage: Arc, + pub(crate) completion: OnceCell>, cancellation: CancellationToken, started: AtomicBool, } @@ -69,12 +85,12 @@ fn cancelled() -> Error { impl VolumeState { pub(crate) fn new( retry: RetryConfig, - read_timeout: Option, + storage: Arc, cancellation: CancellationToken, ) -> Arc { Arc::new(Self { retry, - read_timeout, + storage, cancellation, ..Self::default() }) @@ -86,7 +102,7 @@ impl VolumeState { pub(crate) async fn complete( &self, - prepare: impl std::future::Future>, + prepare: impl std::future::Future>, options: &VolumeOptions, input_bytes: Option>, ) -> Result { @@ -98,7 +114,7 @@ impl VolumeState { return Ok(Err(cancelled())); } let complete = async { - let (batch, client) = tokio::select! { + let batch = tokio::select! { biased; result = prepare => result?, _ = self.cancellation.cancelled() => return Err(cancelled()), @@ -109,7 +125,12 @@ impl VolumeState { { return Ok(VolumeCompletion::NeedsInputStream); } - self.transfer(instruction, &client, options, input_bytes) + let client = tokio::select! { + biased; + client = self.storage.get() => client?, + _ = self.cancellation.cancelled() => return Err(cancelled()), + }; + self.transfer(instruction, client, options, input_bytes) .await }; let result = complete.await; @@ -160,12 +181,12 @@ impl VolumeState { Err(error) => error, }; if !error.retryable || attempt >= self.retry.max_retries { - return Err(error.with_retryable(false)); + return Err(error.message(format!("after {} attempts", attempt + 1))); } let wait = calculate_backoff(&self.retry, attempt, retry_after.as_deref()); // Retry budgets govern recovery, not the duration of a healthy transfer. if started.elapsed().saturating_add(wait) >= self.retry.overall_timeout { - return Err(error.with_retryable(false)); + return Err(error.message(format!("after {} attempts", attempt + 1))); } tokio::select! { _ = tokio::time::sleep(wait) => {} @@ -242,30 +263,55 @@ impl VolumeState { let mut request = client .request(method, &instruction.url) .headers(instruction.headers.clone()); - if let Some(bytes) = input { - request = request - .headers(HeaderMap::from_iter([( - reqwest::header::CONTENT_LENGTH, - bytes.len().into(), - )])) - .body(bytes.clone()); - } let upload_error = Arc::new(Mutex::new(None)); - if let Some((file, length)) = source { + let (progress, changed) = tokio::sync::watch::channel(tokio::time::Instant::now()); + let reader: Option<(Box, u64)> = + if let Some((file, length)) = source { + Some((Box::new(tokio::fs::File::from_std(file)), length)) + } else { + input.map(|bytes| { + ( + Box::new(std::io::Cursor::new(bytes.clone())) as _, + bytes.len() as u64, + ) + }) + }; + if let Some((reader, length)) = reader { request = request .headers(HeaderMap::from_iter([( reqwest::header::CONTENT_LENGTH, length.into(), )])) .body(upload_body( - tokio::fs::File::from_std(file), + reader, local_file.clone(), Arc::clone(&upload_error), + progress, )); } let transfer = async { - let mut response = - storage_send(request, self.read_timeout, upload, upload_error).await?; + let mut response = storage_send( + request, + self.storage.read_timeout, + upload, + upload_error, + changed, + ) + .await?; + if let Some(bytes) = input.filter(|_| matches!(response.status().as_u16(), 307 | 308)) { + // Reusable bytes let reqwest apply its redirect and credential policy. + response = client + .put(&instruction.url) + .headers(instruction.headers.clone()) + .headers(HeaderMap::from_iter([( + reqwest::header::CONTENT_LENGTH, + bytes.len().into(), + )])) + .body(reqwest::Body::from(bytes.clone())) + .send() + .await + .map_err(storage_error)?; + } let status = response.status(); if !(status.is_success() || (remove && status.as_u16() == 404 && options.remove_not_found_is_success)) @@ -275,15 +321,47 @@ impl VolumeState { .get(reqwest::header::RETRY_AFTER) .and_then(|value| value.to_str().ok()) .map(str::to_owned); - return Err(Error::from_http_status(status.as_u16()) + let mut error = Error::from_http_status(status.as_u16()) .with_error_code("VOLUME_STORAGE_HTTP_ERROR") - .with_retryable(matches!(status.as_u16(), 408 | 429 | 500 | 502 | 503 | 504)) + .with_retryable( + !crate::client::retry::is_non_retryable_status(status.as_u16()) + && RetryStrategy::for_request( + RequestType::CloudFetchDownload, + &self.retry, + ) + .is_retryable_status(status, retry_after.is_some()), + ) .message(format!( "Volume storage request failed: HTTP {}", status.as_u16() - ))); + )); + let mut body = Vec::new(); + while body.len() < 4096 { + match storage_read(self.storage.read_timeout, !upload, async { + response.chunk().await.map_err(response_body_error) + }) + .await + { + Ok(Some(chunk)) => { + body.extend_from_slice(&chunk[..chunk.len().min(4096 - body.len())]) + } + _ => break, + } + } + let text = String::from_utf8_lossy(&body); + for tag in ["Code", "Message"] { + if let Some(value) = text + .split_once(&format!("<{tag}>")) + .and_then(|(_, tail)| tail.split_once(&format!(""))) + .map(|(value, _)| value) + .filter(|value| !value.contains(['<', '>'])) + { + error = error.message(format!("{tag}: {value}")); + } + } + return Err(error); } - while let Some(bytes) = storage_read(self.read_timeout, !upload, async { + while let Some(bytes) = storage_read(self.storage.read_timeout, !upload, async { response.chunk().await.map_err(response_body_error) }) .await? @@ -342,13 +420,18 @@ fn upload_body( reader: impl tokio::io::AsyncRead + Unpin + Send + 'static, path: String, error: Arc>>, + progress: tokio::sync::watch::Sender, ) -> reqwest::Body { - reqwest::Body::wrap_stream(ReaderStream::with_capacity(reader, 256 * 1024).map_err( - move |cause| { - *error.lock().unwrap_or_else(|e| e.into_inner()) = Some(local_error(cause, &path)); - std::io::Error::other("Volume upload source could not be read") - }, - )) + reqwest::Body::wrap_stream( + ReaderStream::with_capacity(reader, 256 * 1024) + .inspect_ok(move |_| { + progress.send_replace(tokio::time::Instant::now()); + }) + .map_err(move |cause| { + *error.lock().unwrap_or_else(|e| e.into_inner()) = Some(local_error(cause, &path)); + std::io::Error::other("Volume upload source could not be read") + }), + ) } fn invalid(message: &str) -> Error { @@ -360,10 +443,23 @@ async fn storage_send( timeout: Option, upload: bool, upload_error: Arc>>, + mut progress: tokio::sync::watch::Receiver, ) -> Result { let send = async { request.send().await.map_err(storage_error) }; - let response = if upload { - // Request-body production does not establish that transport buffers have flushed. + tokio::pin!(send); + let response = if let (true, Some(timeout)) = (upload, timeout) { + loop { + let deadline = *progress.borrow_and_update() + timeout; + tokio::select! { + biased; + response = &mut send => break response, + _ = progress.changed(), if progress.has_changed().is_ok() => {} + _ = tokio::time::sleep_until(deadline) => break Err(Error::network_error() + .with_error_code("VOLUME_STORAGE_NETWORK_ERROR") + .with_retryable(false).message("Volume storage upload or response wait timed out")), + } + } + } else if upload { send.await } else { storage_read(timeout, true, send).await @@ -422,7 +518,7 @@ fn response_body_error(error: reqwest::Error) -> Error { } fn local_error(error: std::io::Error, path: &str) -> Error { - let mut result = match error.kind() { + match error.kind() { std::io::ErrorKind::NotFound => Error::not_found(), std::io::ErrorKind::PermissionDenied => Error::permission_denied(), std::io::ErrorKind::InvalidInput @@ -432,13 +528,12 @@ fn local_error(error: std::io::Error, path: &str) -> Error { } .with_error_code("VOLUME_LOCAL_FILE_ERROR") .with_sql_state("HY000") - .message(format!("{error}: {path}")); - result.local_error = Some(Box::new(LocalFileError { + .message(format!("{error}: {path}")) + .with_local_error(LocalFileError { raw_os_error: error.raw_os_error(), kind: error.kind(), path: path.to_owned(), - })); - result + }) } fn normalize(path: &Path) -> Result { @@ -655,7 +750,7 @@ mod tests { use super::*; use arrow_array::builder::{MapBuilder, StringBuilder}; use arrow_array::{ArrayRef, RecordBatch}; - use arrow_schema::{DataType, Field, Schema}; + use arrow_schema::{Field, Schema}; #[cfg(unix)] use std::os::unix::fs::{MetadataExt, PermissionsExt}; use std::time::Duration; @@ -698,7 +793,7 @@ mod tests { max_wait: Duration::ZERO, ..Default::default() }, - None, + Arc::default(), Default::default(), ) } @@ -725,6 +820,7 @@ mod tests { FailedRead(Some(cause)), source.to_str().unwrap().into(), Arc::clone(&captured), + tokio::sync::watch::channel(tokio::time::Instant::now()).0, ); let error = storage_send( Client::new() @@ -733,6 +829,7 @@ mod tests { None, true, captured, + tokio::sync::watch::channel(tokio::time::Instant::now()).1, ) .await .unwrap_err(); @@ -749,31 +846,26 @@ mod tests { async fn transient_storage_statuses_replay_full_inputs_and_cache_completion() { use std::sync::atomic::{AtomicUsize, Ordering}; for (operation, stream) in [("PUT", false), ("PUT", true), ("GET", false)] { - let statuses: &[u16] = &[503]; - let requests = statuses.len() as u64 + 1; + let requests = 2; let server = MockServer::start().await; let attempts = Arc::new(AtomicUsize::new(0)); let count = Arc::clone(&attempts); - Mock::given(method(if operation == "REMOVE" { - "DELETE" - } else { - operation - })) - .and(path("/object")) - .and(header("x-storage-token", "server-token")) - .respond_with(move |request: &wiremock::Request| { - if operation == "PUT" { - assert_eq!(request.body, b"payload"); - } - if let Some(status) = statuses.get(count.fetch_add(1, Ordering::SeqCst)) { - ResponseTemplate::new(*status).insert_header("retry-after", "0") - } else { - ResponseTemplate::new(200).set_body_bytes(b"payload") - } - }) - .expect(requests) - .mount(&server) - .await; + Mock::given(method(operation)) + .and(path("/object")) + .and(header("x-storage-token", "server-token")) + .respond_with(move |request: &wiremock::Request| { + if operation == "PUT" { + assert_eq!(request.body, b"payload"); + } + if count.fetch_add(1, Ordering::SeqCst) == 0 { + ResponseTemplate::new(503).insert_header("retry-after", "0") + } else { + ResponseTemplate::new(200).set_body_bytes(b"payload") + } + }) + .expect(requests) + .mount(&server) + .await; let dir = tempfile::tempdir().unwrap(); let file = dir.path().join("file"); std::fs::write( @@ -792,12 +884,11 @@ mod tests { }; let batch = instruction(operation, &format!("{}/object", server.uri()), local); let state = transfer_state(6); - let client = Client::new(); let options = options(dir.path()); assert_eq!( state .complete( - async { Ok((batch.clone(), client.clone())) }, + async { Ok(batch.clone()) }, &options, stream.then(|| b"payload".to_vec()) ) @@ -807,11 +898,7 @@ mod tests { ); assert_eq!( state - .complete( - async { Ok((batch.clone(), client.clone())) }, - &options, - None - ) + .complete(async { Ok(batch.clone()) }, &options, None) .await .unwrap(), VolumeCompletion::Completed @@ -823,14 +910,15 @@ mod tests { } #[tokio::test] - async fn permanent_statuses_and_retry_limits_preserve_terminal_errors() { - for (operation, status, retries, budget, requests) in [ - ("PUT", 307, 2, Duration::from_secs(10), 1), - ("REMOVE", 403, 2, Duration::from_secs(10), 1), - ("REMOVE", 404, 2, Duration::from_secs(10), 1), - ("REMOVE", 503, 0, Duration::from_secs(10), 1), - ("REMOVE", 503, 2, Duration::ZERO, 1), - ("REMOVE", 503, 2, Duration::from_secs(10), 3), + async fn storage_statuses_and_retry_limits_preserve_classification() { + for (operation, status, retries, budget, requests, missing_success) in [ + ("PUT", 307, 2, Duration::from_secs(10), 1, true), + ("REMOVE", 403, 2, Duration::from_secs(10), 1, true), + ("REMOVE", 404, 2, Duration::from_secs(10), 1, true), + ("REMOVE", 404, 2, Duration::from_secs(10), 1, false), + ("REMOVE", 503, 0, Duration::from_secs(10), 1, true), + ("REMOVE", 503, 2, Duration::ZERO, 1, true), + ("REMOVE", 503, 2, Duration::from_secs(10), 3, true), ] { let server = MockServer::start().await; Mock::given(method(if operation == "PUT" { "PUT" } else { "DELETE" })) @@ -838,7 +926,8 @@ mod tests { .respond_with( ResponseTemplate::new(status) .insert_header("retry-after", "0") - .insert_header("location", "/redirected"), + .insert_header("location", "/redirected") + .set_body_string("AccessDeniedPermission refusedsecret"), ) .expect(requests) .mount(&server) @@ -848,7 +937,7 @@ mod tests { std::fs::write(&file, b"payload").unwrap(); let options = VolumeOptions { allowed_paths: vec![directory.path().to_owned()], - remove_not_found_is_success: true, + remove_not_found_is_success: missing_success, }; let state = VolumeState::new( RetryConfig { @@ -858,7 +947,7 @@ mod tests { max_wait: Duration::ZERO, ..Default::default() }, - None, + Arc::default(), Default::default(), ); let batch = instruction( @@ -868,9 +957,9 @@ mod tests { ); for _ in 0..2 { let result = state - .complete(async { Ok((batch.clone(), Client::new())) }, &options, None) + .complete(async { Ok(batch.clone()) }, &options, None) .await; - if status == 404 { + if status == 404 && missing_success { assert_eq!(result.unwrap(), VolumeCompletion::Completed); continue; } @@ -880,7 +969,11 @@ mod tests { error.error_code.as_deref(), Some("VOLUME_STORAGE_HTTP_ERROR") ); - assert!(!error.retryable); + assert_eq!(error.retryable, status == 503); + assert!(error.message.contains("AccessDenied")); + assert!(error + .message + .contains(&format!("after {requests} attempts"))); assert!(!error.message.contains("secret")); } } @@ -900,17 +993,12 @@ mod tests { max_wait: Duration::from_secs(30), ..Default::default() }, - None, + Arc::default(), Default::default(), ); let batch = instruction("REMOVE", &server.uri(), Path::new("")); - let client = Client::new(); let options = VolumeOptions::default(); - let complete = state.complete( - async { Ok((batch.clone(), client.clone())) }, - &options, - None, - ); + let complete = state.complete(async { Ok(batch.clone()) }, &options, None); let cancel = async { while server.received_requests().await.unwrap().is_empty() { tokio::task::yield_now().await; @@ -944,14 +1032,9 @@ mod tests { Path::new("__input_stream__"), ); let state = transfer_state(0); - let client = Client::new(); assert_eq!( state - .complete( - async { Ok((batch.clone(), client.clone())) }, - &VolumeOptions::default(), - None - ) + .complete(async { Ok(batch.clone()) }, &VolumeOptions::default(), None) .await .unwrap(), VolumeCompletion::NeedsInputStream @@ -960,7 +1043,7 @@ mod tests { assert_eq!( state .complete( - async { Ok((batch.clone(), client.clone())) }, + async { Ok(batch.clone()) }, &VolumeOptions::default(), Some(vec![]) ) @@ -972,7 +1055,7 @@ mod tests { assert_eq!( state .complete( - async { Ok((batch.clone(), client.clone())) }, + async { Ok(batch.clone()) }, &VolumeOptions::default(), Some(vec![1]) ) @@ -1007,11 +1090,7 @@ mod tests { let batch = instruction("GET", &format!("{}/ok", server.uri()), &dest); let completed = transfer_state(0); completed - .complete( - async { Ok((batch.clone(), Client::new())) }, - &options(dir.path()), - None, - ) + .complete(async { Ok(batch.clone()) }, &options(dir.path()), None) .await .unwrap(); #[cfg(unix)] @@ -1042,11 +1121,7 @@ mod tests { let state = transfer_state(0); assert_eq!( state - .complete( - async { Ok((batch.clone(), Client::new())) }, - &options(dir.path()), - None - ) + .complete(async { Ok(batch.clone()) }, &options(dir.path()), None) .await .unwrap(), VolumeCompletion::Completed @@ -1069,11 +1144,7 @@ mod tests { &dest, ); let error = state - .complete( - async { Ok((batch.clone(), Client::new())) }, - &options(dir.path()), - None, - ) + .complete(async { Ok(batch.clone()) }, &options(dir.path()), None) .await .unwrap_err(); assert_eq!(error.http_status, Some(403)); @@ -1096,7 +1167,6 @@ mod tests { .success()); let state = transfer_state(0); let canceller = Arc::clone(&state); - let client = Client::new(); let batch = instruction("PUT", "http://unused.invalid/object", &source); let (release, released) = std::sync::mpsc::channel(); let writer = std::thread::spawn(move || { @@ -1117,7 +1187,7 @@ mod tests { .complete( async { release.send(()).unwrap(); - Ok((batch, client)) + Ok(batch) }, &options(dir.path()), None, @@ -1149,14 +1219,9 @@ mod tests { std::fs::write(&dest, b"old").unwrap(); let batch = instruction("GET", &server.uri(), &dest); let options = options(dir.path()); - let client = Client::new(); for cancel in [false, true] { let state = transfer_state(0); - let mut future = Box::pin(state.complete( - async { Ok((batch.clone(), client.clone())) }, - &options, - None, - )); + let mut future = Box::pin(state.complete(async { Ok(batch.clone()) }, &options, None)); tokio::select! { result = &mut future => panic!("unexpected early completion: {result:?}"), _ = async { @@ -1176,11 +1241,7 @@ mod tests { drop(future); assert_eq!( state - .complete( - async { Ok((batch.clone(), client.clone())) }, - &options, - None - ) + .complete(async { Ok(batch.clone()) }, &options, None) .await .unwrap_err() .code, @@ -1237,17 +1298,17 @@ mod tests { transfer_state(if operation == "PUT" { 1 } else { 0 }) .retry .clone(), - Some(Duration::from_millis(150)), + Arc::new( + crate::client::DatabricksHttpClient::with_default_retry(Default::default()) + .unwrap() + .storage_client(Some(Duration::from_millis(150))), + ), Default::default(), ); let batch = instruction(operation, &url, &dest); let error = tokio::time::timeout( Duration::from_secs(2), - state.complete( - async { Ok((batch.clone(), Client::new())) }, - &options(dir.path()), - None, - ), + state.complete(async { Ok(batch.clone()) }, &options(dir.path()), None), ) .await .unwrap() @@ -1259,11 +1320,7 @@ mod tests { ); assert!(error.message.contains("read timed out")); let repeated = state - .complete( - async { Ok((batch.clone(), Client::new())) }, - &options(dir.path()), - None, - ) + .complete(async { Ok(batch.clone()) }, &options(dir.path()), None) .await .unwrap_err(); assert_eq!(repeated.message, error.message); @@ -1275,7 +1332,7 @@ mod tests { } #[tokio::test] - async fn get_inactivity_resets_on_progress_and_put_has_no_header_deadline() { + async fn get_progress_and_file_and_stream_put_idle_limits() { use tokio::io::AsyncReadExt; let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); let url = format!("http://{}", listener.local_addr().unwrap()); @@ -1296,12 +1353,16 @@ mod tests { let dest = dir.path().join("download"); let state = VolumeState::new( transfer_state(0).retry.clone(), - Some(Duration::from_millis(150)), + Arc::new( + crate::client::DatabricksHttpClient::with_default_retry(Default::default()) + .unwrap() + .storage_client(Some(Duration::from_millis(150))), + ), Default::default(), ); state .complete( - async { Ok((instruction("GET", &url, &dest), Client::new())) }, + async { Ok(instruction("GET", &url, &dest)) }, &options(dir.path()), None, ) @@ -1313,7 +1374,7 @@ mod tests { let server = MockServer::start().await; Mock::given(method("PUT")) .and(body_bytes(b"xxxxx")) - .respond_with(ResponseTemplate::new(200).set_delay(Duration::from_millis(300))) + .respond_with(ResponseTemplate::new(200)) .expect(1) .mount(&server) .await; @@ -1325,7 +1386,8 @@ mod tests { } }); let error = Arc::new(Mutex::new(None)); - let body = upload_body(reader, "input".into(), Arc::clone(&error)); + let (progress, changed) = tokio::sync::watch::channel(tokio::time::Instant::now()); + let body = upload_body(reader, "input".into(), Arc::clone(&error), progress); storage_send( Client::new() .put(server.uri()) @@ -1334,10 +1396,69 @@ mod tests { Some(Duration::from_millis(150)), true, error, + changed, ) .await .unwrap(); producer.await.unwrap(); + + for stream in [false, true] { + for header_wait in [false, true] { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}", listener.local_addr().unwrap()); + let payload = vec![b'x'; 16 * 1024 * 1024]; + std::fs::write(&dest, &payload).unwrap(); + let length = payload.len(); + let peer = tokio::spawn(async move { + let (mut socket, _) = listener.accept().await.unwrap(); + if header_wait { + let mut headers = Vec::new(); + while !headers.ends_with(b"\r\n\r\n") { + headers.push(socket.read_u8().await.unwrap()); + } + let mut remaining = length; + let mut buffer = vec![0; 256 * 1024]; + while remaining > 0 { + let n = socket.read(&mut buffer).await.unwrap(); + assert!(n > 0); + remaining -= n; + } + } + std::future::pending::<()>().await; + }); + let state = VolumeState::new( + transfer_state(0).retry.clone(), + Arc::new( + crate::client::DatabricksHttpClient::with_default_retry(Default::default()) + .unwrap() + .storage_client(Some(Duration::from_millis(150))), + ), + Default::default(), + ); + let local = if stream { + Path::new("__input_stream__") + } else { + &dest + }; + let error = tokio::time::timeout( + Duration::from_secs(3), + state.complete( + async { Ok(instruction("PUT", &url, local)) }, + &options(dir.path()), + stream.then_some(payload), + ), + ) + .await + .expect("PUT idle watchdog") + .unwrap_err(); + assert_eq!( + error.error_code.as_deref(), + Some("VOLUME_STORAGE_NETWORK_ERROR") + ); + assert!(error.message.contains("timed out")); + peer.abort(); + } + } } #[tokio::test] @@ -1365,11 +1486,7 @@ mod tests { std::fs::write(&dest, b"old").unwrap(); let batch = instruction("GET", &url, &dest); let result = transfer_state(retries) - .complete( - async { Ok((batch.clone(), Client::new())) }, - &options(dir.path()), - None, - ) + .complete(async { Ok(batch.clone()) }, &options(dir.path()), None) .await; if retries == 0 { assert_eq!(result.unwrap_err().code, crate::ErrorCode::NetworkError); @@ -1495,11 +1612,7 @@ mod tests { ); let state = transfer_state(1); let error = state - .complete( - async { Ok((batch.clone(), Client::new())) }, - &options(dir.path()), - None, - ) + .complete(async { Ok(batch.clone()) }, &options(dir.path()), None) .await .unwrap_err(); assert_eq!(error.code, code); @@ -1513,11 +1626,7 @@ mod tests { assert!(!error.message.contains("hidden")); assert_eq!( state - .complete( - async { Ok((batch.clone(), Client::new())) }, - &options(dir.path()), - None - ) + .complete(async { Ok(batch.clone()) }, &options(dir.path()), None) .await .unwrap_err() .local_error @@ -1559,18 +1668,68 @@ mod tests { assert!(!mapped.message.contains("hidden"), "{mapped}"); } - #[test] - fn malformed_instruction_is_rejected() { - let schema = Arc::new(Schema::new(vec![Field::new( - "operation", - DataType::Utf8, - true, - )])); - let batch = - RecordBatch::try_new(schema, vec![Arc::new(StringArray::from(vec!["PUT"]))]).unwrap(); + #[tokio::test] + async fn redirected_stream_put_replays_full_bytes() { + let server = MockServer::start().await; + let payload = vec![b'x'; 512 * 1024 + 1]; + Mock::given(method("PUT")) + .and(path("/original")) + .and(body_bytes(payload.clone())) + .respond_with(ResponseTemplate::new(307).insert_header("location", "/target")) + .expect(2) + .mount(&server) + .await; + Mock::given(method("PUT")) + .and(path("/target")) + .and(body_bytes(payload.clone())) + .respond_with(ResponseTemplate::new(200)) + .expect(1) + .mount(&server) + .await; assert_eq!( - Instruction::decode(&batch).err().unwrap().code, - crate::ErrorCode::InvalidArgument + transfer_state(0) + .complete( + async { + Ok(instruction( + "PUT", + &format!("{}/original", server.uri()), + Path::new("__input_stream__"), + )) + }, + &VolumeOptions::default(), + Some(payload), + ) + .await + .unwrap(), + VolumeCompletion::Completed ); } + + #[tokio::test] + async fn get_decodes_gzip_content_encoding() { + let server = MockServer::start().await; + Mock::given(method("GET")) + .respond_with( + ResponseTemplate::new(200) + .insert_header("content-encoding", "gzip") + .set_body_bytes(vec![ + 31, 139, 8, 0, 0, 0, 0, 0, 2, 3, 75, 73, 77, 206, 79, 73, 77, 97, 72, 170, + 44, 73, 45, 6, 0, 196, 224, 211, 9, 13, 0, 0, 0, + ]), + ) + .expect(1) + .mount(&server) + .await; + let dir = tempfile::tempdir().unwrap(); + let dest = dir.path().join("download"); + transfer_state(0) + .complete( + async { Ok(instruction("GET", &server.uri(), &dest)) }, + &options(dir.path()), + None, + ) + .await + .unwrap(); + assert_eq!(std::fs::read(dest).unwrap(), b"decoded\x00bytes"); + } } diff --git a/tests/v0_volume_wiremock.rs b/tests/v0_volume_wiremock.rs index dcf0af77..6117206b 100644 --- a/tests/v0_volume_wiremock.rs +++ b/tests/v0_volume_wiremock.rs @@ -101,10 +101,7 @@ async fn instruction_batches_preserve_one_row_and_reject_extra_rows() { let mut statement = session.statement(); statement.spec().sql("operation"); let mut executed = statement.execute().await.unwrap(); - let options = VolumeOptions { - allowed_paths: vec![dir.path().to_owned()], - ..Default::default() - }; + let options = VolumeOptions::new(vec![dir.path().to_owned()], false); for _ in 0..2 { let result = executed .result_stream_mut() @@ -195,61 +192,47 @@ async fn session_with_http( } #[tokio::test] -async fn storage_transfers_outlive_rpc_deadline_while_sql_requests_still_time_out() { - for operation in ["GET"] { - let server = MockServer::start().await; - let dir = tempfile::tempdir().unwrap(); - let local = dir.path().join("file"); - std::fs::write(&local, b"original").unwrap(); - let mut http = HttpConfig::default(); - http.request_timeout = Duration::from_millis(100); - http.overall_timeout = Duration::from_millis(200); - let session = session_with_http( - &server, - response_with_batches(&server, true, local.to_str().unwrap(), operation, &[1]), - http, +async fn storage_transfers_outlive_rpc_deadline() { + let server = MockServer::start().await; + let dir = tempfile::tempdir().unwrap(); + let local = dir.path().join("file"); + std::fs::write(&local, b"original").unwrap(); + let mut http = HttpConfig::default(); + http.request_timeout = Duration::from_millis(100); + http.overall_timeout = Duration::from_millis(200); + let session = session_with_http( + &server, + response_with_batches(&server, true, local.to_str().unwrap(), "GET", &[1]), + http, + ) + .await; + Mock::given(method("GET")) + .and(path("/object")) + .respond_with( + ResponseTemplate::new(200) + .set_delay(Duration::from_millis(300)) + .set_body_bytes(b"downloaded"), ) + .expect(1) + .mount(&server) .await; - Mock::given(method(operation)) - .and(path("/object")) - .respond_with( - ResponseTemplate::new(200) - .set_delay(Duration::from_millis(300)) - .set_body_bytes(b"downloaded"), + let mut statement = session.statement(); + statement.spec().sql("operation"); + let mut executed = statement.execute().await.unwrap(); + assert_eq!( + executed + .result_stream_mut() + .complete_volume_operation( + &VolumeOptions::new(vec![dir.path().to_owned()], false), + None, ) - .expect(1) - .mount(&server) - .await; - let mut statement = session.statement(); - statement.spec().sql("operation"); - let mut executed = statement.execute().await.unwrap(); - assert_eq!( - executed - .result_stream_mut() - .complete_volume_operation( - &VolumeOptions { - allowed_paths: vec![dir.path().to_owned()], - ..Default::default() - }, - None, - ) - .await - .unwrap(), - VolumeCompletion::Completed - ); - assert_eq!(std::fs::read(&local).unwrap(), b"downloaded"); - executed.close().await.unwrap(); - Mock::given(method("POST")) - .and(path("/api/2.0/sql/statements")) - .respond_with(ResponseTemplate::new(200).set_delay(Duration::from_millis(300))) - .with_priority(1) - .mount(&server) - .await; - let error = statement.execute().await.err().expect("RPC deadline"); - assert_eq!(error.code, ErrorCode::NetworkError); - assert!(error.message.contains("timed out"), "{error}"); - session.close().await.unwrap(); - } + .await + .unwrap(), + VolumeCompletion::Completed + ); + assert_eq!(std::fs::read(&local).unwrap(), b"downloaded"); + executed.close().await.unwrap(); + session.close().await.unwrap(); } #[tokio::test] @@ -278,10 +261,7 @@ async fn sync_and_direct_closed_results_complete_explicitly_and_keep_raw_rows() assert!(!dest.exists()); let stream = exec.result_stream_mut(); assert!(stream.is_volume_operation()); - let options = VolumeOptions { - allowed_paths: vec![dir.path().to_owned()], - ..Default::default() - }; + let options = VolumeOptions::new(vec![dir.path().to_owned()], false); assert_eq!( stream .complete_volume_operation(&options, None) @@ -366,10 +346,7 @@ async fn owner_reader_and_repeated_materialization_share_one_completion() { reader.fetch_result().await.unwrap().close(); let mut first = reader.fetch_result().await.unwrap(); let mut second = owner.fetch_result().await.unwrap(); - let options = VolumeOptions { - allowed_paths: vec![dir.path().to_owned()], - ..Default::default() - }; + let options = VolumeOptions::new(vec![dir.path().to_owned()], false); let (a, b) = tokio::join!( first.complete_volume_operation(&options, None), second.complete_volume_operation(&options, None) @@ -426,10 +403,7 @@ async fn cancellation_and_session_close_interrupt_instruction_or_storage_after_s let canceller = stmt.canceller(); stmt.spec().sql("operation"); let mut exec = stmt.execute().await.unwrap(); - let options = VolumeOptions { - allowed_paths: vec![dir.path().to_owned()], - ..Default::default() - }; + let options = VolumeOptions::new(vec![dir.path().to_owned()], false); let complete = exec .result_stream_mut() .complete_volume_operation(&options, None); @@ -482,3 +456,38 @@ async fn cancellation_and_session_close_interrupt_instruction_or_storage_after_s } } } + +#[tokio::test] +async fn reading_before_volume_completion_returns_invalid_state() { + let server = MockServer::start().await; + let dir = tempfile::tempdir().unwrap(); + let local = dir.path().join("download"); + let session = session_with_http( + &server, + response_with_batches(&server, true, local.to_str().unwrap(), "GET", &[1]), + HttpConfig::default(), + ) + .await; + let mut statement = session.statement(); + statement.spec().sql("GET"); + let mut executed = statement.execute().await.unwrap(); + assert!(executed.next_batch().await.unwrap().is_some()); + let error = executed + .result_stream_mut() + .complete_volume_operation( + &VolumeOptions::new(vec![dir.path().to_owned()], false), + None, + ) + .await + .unwrap_err(); + assert_eq!( + error.code, + databricks_sql_kernel::Error::invalid_state().code + ); + assert!(error + .message + .contains("complete_volume_operation must be called before reading result rows")); + assert!(!local.exists()); + executed.close().await.unwrap(); + session.close().await.unwrap(); +} From 0b19817d392b1af365129ae5238cc977a823870f Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Fri, 20 Nov 2026 02:05:28 +0000 Subject: [PATCH 46/63] fixup! fix(volume): bound idle transfers and preserve completion diagnostics Signed-off-by: Aakash Saravanan --- napi/src/error.rs | 35 +++- src/client/http.rs | 1 - src/result_stream.rs | 2 +- src/volume.rs | 443 +++++++++++++++++++++---------------------- 4 files changed, 243 insertions(+), 238 deletions(-) diff --git a/napi/src/error.rs b/napi/src/error.rs index 4a359062..a12070f9 100644 --- a/napi/src/error.rs +++ b/napi/src/error.rs @@ -82,8 +82,14 @@ pub(crate) const ERROR_SENTINEL: &str = "__databricks_error__:"; /// and `cause` are intentionally omitted from the v1 envelope — see /// the module-level doc for rationale. /// -/// Both bindings carry extended status; NAPI encodes camelCase JSON and PyO3 -/// attaches snake_case exception attributes. +/// **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 @@ -320,8 +326,29 @@ mod tests { ); } - /// Both bindings expose structured kernel fields; NAPI uses camelCase JSON - /// and PyO3 uses snake_case exception attributes. + /// 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() { // Build a kernel error with every optional field populated so diff --git a/src/client/http.rs b/src/client/http.rs index aa27441b..0f301a30 100644 --- a/src/client/http.rs +++ b/src/client/http.rs @@ -388,7 +388,6 @@ pub struct DatabricksHttpClient { retry_configs: HashMap, } -#[derive(Default)] pub(crate) struct StorageClient { pub(crate) read_timeout: Option, config: HttpClientConfig, diff --git a/src/result_stream.rs b/src/result_stream.rs index b3b1a3ad..9b825c74 100644 --- a/src/result_stream.rs +++ b/src/result_stream.rs @@ -652,7 +652,7 @@ impl ResultStream { self.volume.is_some() } - /// Complete a server-marked file transfer while retaining its instruction rows. + /// Complete a server-marked Volume operation while retaining its instruction rows. /// /// Ordinary results and read-only attachments have no transfer authority. /// `NeedsInputStream` requests owned bytes for the server's stream sentinel; diff --git a/src/volume.rs b/src/volume.rs index 78e3f405..d6737584 100644 --- a/src/volume.rs +++ b/src/volume.rs @@ -69,7 +69,6 @@ pub enum VolumeCompletion { Completed, } -#[derive(Default)] pub(crate) struct VolumeState { retry: RetryConfig, storage: Arc, @@ -92,7 +91,8 @@ impl VolumeState { retry, storage, cancellation, - ..Self::default() + completion: OnceCell::new(), + started: AtomicBool::new(false), }) } @@ -113,25 +113,54 @@ impl VolumeState { if self.started.swap(true, Ordering::AcqRel) || self.cancellation.is_cancelled() { return Ok(Err(cancelled())); } - let complete = async { - let batch = tokio::select! { - biased; - result = prepare => result?, - _ = self.cancellation.cancelled() => return Err(cancelled()), - }; + let transfer = async { + let batch = prepare.await?; let instruction = Instruction::decode(&batch)?; if matches!(instruction.operation, Operation::Put(Source::Stream)) && input_bytes.is_none() { - return Ok(VolumeCompletion::NeedsInputStream); + return Ok::<_, Error>((VolumeCompletion::NeedsInputStream, None)); } - let client = tokio::select! { + let client = self.storage.get().await?; + let destination = self + .transfer(instruction, client, options, input_bytes) + .await?; + Ok((VolumeCompletion::Completed, destination)) + }; + let complete = async { + let (outcome, destination) = tokio::select! { biased; - client = self.storage.get() => client?, + result = transfer => result?, _ = self.cancellation.cancelled() => return Err(cancelled()), }; - self.transfer(instruction, client, options, input_bytes) + if let Some((mut temp, existing, path, local_file)) = destination { + let cancellation = self.cancellation.clone(); + tokio::task::spawn_blocking(move || { + if cancellation.is_cancelled() { + return Err(cancelled()); + } + let mut file = match existing { + Some(file) => file, + None => std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(path) + .map_err(|e| local_error(e, &local_file))?, + }; + std::io::Seek::rewind(&mut temp) + .map_err(|e| local_error(e, &local_file))?; + let length = std::io::copy(&mut temp, &mut file) + .map_err(|e| local_error(e, &local_file))?; + file.set_len(length) + .map_err(|e| local_error(e, &local_file)) + }) .await + .map_err(|e| { + Error::internal() + .message(format!("Volume publication task failed: {e}")) + })??; + } + Ok(outcome) }; let result = complete.await; if matches!(result, Ok(VolumeCompletion::NeedsInputStream)) { @@ -155,7 +184,7 @@ impl VolumeState { client: &Client, options: &VolumeOptions, input_bytes: Option>, - ) -> Result { + ) -> Result, PathBuf, String)>> { let input = if matches!(instruction.operation, Operation::Put(Source::Stream)) { Some(Bytes::from( input_bytes.ok_or_else(|| invalid("Missing input stream"))?, @@ -188,10 +217,7 @@ impl VolumeState { if started.elapsed().saturating_add(wait) >= self.retry.overall_timeout { return Err(error.message(format!("after {} attempts", attempt + 1))); } - tokio::select! { - _ = tokio::time::sleep(wait) => {} - _ = self.cancellation.cancelled() => return Err(cancelled()), - } + tokio::time::sleep(wait).await; attempt += 1; } } @@ -203,7 +229,7 @@ impl VolumeState { options: &VolumeOptions, input: Option<&Bytes>, retry_after: &mut Option, - ) -> Result { + ) -> Result, PathBuf, String)>> { let operation = instruction.operation.clone(); let roots = options.allowed_paths.clone(); let preparation = tokio::task::spawn_blocking(move || { @@ -251,13 +277,9 @@ impl VolumeState { }; Ok((method, local_file, source, destination)) }); - let (method, local_file, source, mut destination) = tokio::select! { - biased; - result = preparation => result.map_err(|e| { - Error::internal().message(format!("Volume file preparation task failed: {e}")) - })??, - _ = self.cancellation.cancelled() => return Err(cancelled()), - }; + let (method, local_file, source, mut destination) = preparation.await.map_err(|e| { + Error::internal().message(format!("Volume file preparation task failed: {e}")) + })??; let upload = method == Method::PUT; let remove = method == Method::DELETE; let mut request = client @@ -289,130 +311,95 @@ impl VolumeState { progress, )); } - let transfer = async { - let mut response = storage_send( - request, - self.storage.read_timeout, - upload, - upload_error, - changed, - ) - .await?; - if let Some(bytes) = input.filter(|_| matches!(response.status().as_u16(), 307 | 308)) { - // Reusable bytes let reqwest apply its redirect and credential policy. - response = client - .put(&instruction.url) - .headers(instruction.headers.clone()) - .headers(HeaderMap::from_iter([( - reqwest::header::CONTENT_LENGTH, - bytes.len().into(), - )])) - .body(reqwest::Body::from(bytes.clone())) - .send() - .await - .map_err(storage_error)?; - } - let status = response.status(); - if !(status.is_success() - || (remove && status.as_u16() == 404 && options.remove_not_found_is_success)) - { - *retry_after = response - .headers() - .get(reqwest::header::RETRY_AFTER) - .and_then(|value| value.to_str().ok()) - .map(str::to_owned); - let mut error = Error::from_http_status(status.as_u16()) - .with_error_code("VOLUME_STORAGE_HTTP_ERROR") - .with_retryable( - !crate::client::retry::is_non_retryable_status(status.as_u16()) - && RetryStrategy::for_request( - RequestType::CloudFetchDownload, - &self.retry, - ) - .is_retryable_status(status, retry_after.is_some()), - ) - .message(format!( - "Volume storage request failed: HTTP {}", - status.as_u16() - )); - let mut body = Vec::new(); - while body.len() < 4096 { - match storage_read(self.storage.read_timeout, !upload, async { - response.chunk().await.map_err(response_body_error) - }) - .await - { - Ok(Some(chunk)) => { - body.extend_from_slice(&chunk[..chunk.len().min(4096 - body.len())]) - } - _ => break, - } - } - let text = String::from_utf8_lossy(&body); - for tag in ["Code", "Message"] { - if let Some(value) = text - .split_once(&format!("<{tag}>")) - .and_then(|(_, tail)| tail.split_once(&format!(""))) - .map(|(value, _)| value) - .filter(|value| !value.contains(['<', '>'])) - { - error = error.message(format!("{tag}: {value}")); + let mut response = storage_send( + request, + self.storage.read_timeout, + upload, + upload_error, + changed, + ) + .await?; + if let Some(bytes) = input.filter(|_| matches!(response.status().as_u16(), 307 | 308)) { + // Reusable bytes let reqwest apply its redirect and credential policy. + response = client + .put(&instruction.url) + .headers(instruction.headers.clone()) + .headers(HeaderMap::from_iter([( + reqwest::header::CONTENT_LENGTH, + bytes.len().into(), + )])) + .body(reqwest::Body::from(bytes.clone())) + .send() + .await + .map_err(storage_error)?; + } + let status = response.status(); + if !(status.is_success() + || (remove && status.as_u16() == 404 && options.remove_not_found_is_success)) + { + *retry_after = response + .headers() + .get(reqwest::header::RETRY_AFTER) + .and_then(|value| value.to_str().ok()) + .map(str::to_owned); + let mut error = Error::from_http_status(status.as_u16()) + .with_error_code("VOLUME_STORAGE_HTTP_ERROR") + .with_retryable( + RetryStrategy::for_request(RequestType::CloudFetchDownload, &self.retry) + .is_retryable_status(status, retry_after.is_some()), + ) + .message(format!( + "Volume storage request failed: HTTP {}", + status.as_u16() + )); + let mut body = Vec::new(); + while body.len() < 4096 { + match storage_read(self.storage.read_timeout, !upload, async { + response.chunk().await.map_err(response_body_error) + }) + .await + { + Ok(Some(chunk)) => { + body.extend_from_slice(&chunk[..chunk.len().min(4096 - body.len())]) } + _ => break, } - return Err(error); } - while let Some(bytes) = storage_read(self.storage.read_timeout, !upload, async { - response.chunk().await.map_err(response_body_error) - }) - .await? - { - if let Some((_, writer, _, _)) = destination.as_mut() { - writer - .write_all(&bytes) - .await - .map_err(|e| local_error(e, &local_file))?; + let text = String::from_utf8_lossy(&body); + for tag in ["Code", "Message"] { + if let Some(value) = text + .split_once(&format!("<{tag}>")) + .and_then(|(_, tail)| tail.split_once(&format!(""))) + .map(|(value, _)| value) + .filter(|value| !value.contains(['<', '>'])) + { + error = error.message(format!("{tag}: {value}")); } } + return Err(error); + } + while let Some(bytes) = storage_read(self.storage.read_timeout, !upload, async { + response.chunk().await.map_err(response_body_error) + }) + .await? + { if let Some((_, writer, _, _)) = destination.as_mut() { writer - .flush() + .write_all(&bytes) .await .map_err(|e| local_error(e, &local_file))?; } - Ok(()) - }; - tokio::select! { - biased; - result = transfer => result?, - _ = self.cancellation.cancelled() => return Err(cancelled()), } - if let Some((mut temp, writer, existing, path)) = destination.take() { - drop(writer); - let cancellation = self.cancellation.clone(); - tokio::task::spawn_blocking(move || { - if cancellation.is_cancelled() { - return Err(cancelled()); - } - let mut file = match existing { - Some(file) => file, - None => std::fs::OpenOptions::new() - .write(true) - .create_new(true) - .open(path) - .map_err(|e| local_error(e, &local_file))?, - }; - std::io::Seek::rewind(&mut temp).map_err(|e| local_error(e, &local_file))?; - let length = - std::io::copy(&mut temp, &mut file).map_err(|e| local_error(e, &local_file))?; - file.set_len(length) - .map_err(|e| local_error(e, &local_file)) - }) - .await - .map_err(|e| { - Error::internal().message(format!("Volume publication task failed: {e}")) - })??; + if let Some((_, writer, _, _)) = destination.as_mut() { + writer + .flush() + .await + .map_err(|e| local_error(e, &local_file))?; } - Ok(VolumeCompletion::Completed) + Ok(destination.map(|(temp, writer, existing, path)| { + drop(writer); + (temp, existing, path, local_file) + })) } } @@ -618,9 +605,10 @@ fn allowed_path(requested: &str, roots: &[PathBuf]) -> Result { .map(|root| normalize(root)) .collect::>>()?; if !roots.iter().any(|root| within_root(&path, root)) { - return Err(invalid( - "Local file path is outside the configured allowed roots", - )); + return Err( + invalid("Local file path is outside the configured allowed roots") + .with_error_code("VOLUME_PATH_NOT_ALLOWED"), + ); } let resolved = resolve_existing_parent(&path, requested, MAX_SYMLINK_RESOLUTIONS)?; let mut root_error = None; @@ -643,9 +631,10 @@ fn allowed_path(requested: &str, roots: &[PathBuf]) -> Result { if let Some(error) = root_error { return Err(error); } - Err(invalid( - "Resolved local file path is outside the configured allowed roots", - )) + Err( + invalid("Resolved local file path is outside the configured allowed roots") + .with_error_code("VOLUME_PATH_NOT_ALLOWED"), + ) } #[derive(Clone)] @@ -793,7 +782,11 @@ mod tests { max_wait: Duration::ZERO, ..Default::default() }, - Arc::default(), + Arc::new( + crate::client::DatabricksHttpClient::with_default_retry(Default::default()) + .unwrap() + .storage_client(None), + ), Default::default(), ) } @@ -947,7 +940,11 @@ mod tests { max_wait: Duration::ZERO, ..Default::default() }, - Arc::default(), + Arc::new( + crate::client::DatabricksHttpClient::with_default_retry(Default::default()) + .unwrap() + .storage_client(None), + ), Default::default(), ); let batch = instruction( @@ -993,7 +990,11 @@ mod tests { max_wait: Duration::from_secs(30), ..Default::default() }, - Arc::default(), + Arc::new( + crate::client::DatabricksHttpClient::with_default_retry(Default::default()) + .unwrap() + .storage_client(None), + ), Default::default(), ); let batch = instruction("REMOVE", &server.uri(), Path::new("")); @@ -1168,38 +1169,23 @@ mod tests { let state = transfer_state(0); let canceller = Arc::clone(&state); let batch = instruction("PUT", "http://unused.invalid/object", &source); - let (release, released) = std::sync::mpsc::channel(); - let writer = std::thread::spawn(move || { - released.recv().unwrap(); - std::thread::sleep(Duration::from_millis(50)); - let started = std::time::Instant::now(); + tokio::spawn(async move { + tokio::time::sleep(Duration::from_millis(50)).await; canceller.cancel(); - let cancel_elapsed = started.elapsed(); - let completion_wait_expired = released.recv_timeout(Duration::from_secs(2)).is_err(); - let _writer = std::fs::OpenOptions::new() - .write(true) - .open(source) - .unwrap(); - (cancel_elapsed, completion_wait_expired) }); - let started = std::time::Instant::now(); - let result = state - .complete( - async { - release.send(()).unwrap(); - Ok(batch) - }, - &options(dir.path()), - None, - ) - .await; - let completion_elapsed = started.elapsed(); - let _ = release.send(()); - let (cancel_elapsed, completion_wait_expired) = writer.join().unwrap(); - assert_eq!(result.unwrap_err().code, crate::ErrorCode::Cancelled); - assert!(cancel_elapsed < Duration::from_millis(500)); - assert!(completion_elapsed < Duration::from_millis(500)); - assert!(!completion_wait_expired); + let result = tokio::time::timeout( + Duration::from_secs(2), + state.complete(async { Ok(batch) }, &options(dir.path()), None), + ) + .await; + let _writer = std::fs::OpenOptions::new() + .write(true) + .open(source) + .unwrap(); + assert_eq!( + result.unwrap().unwrap_err().code, + crate::ErrorCode::Cancelled + ); } #[tokio::test] @@ -1332,7 +1318,7 @@ mod tests { } #[tokio::test] - async fn get_progress_and_file_and_stream_put_idle_limits() { + async fn get_progress_and_put_idle_limits() { use tokio::io::AsyncReadExt; let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); let url = format!("http://{}", listener.local_addr().unwrap()); @@ -1402,62 +1388,55 @@ mod tests { .unwrap(); producer.await.unwrap(); - for stream in [false, true] { - for header_wait in [false, true] { - let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); - let url = format!("http://{}", listener.local_addr().unwrap()); - let payload = vec![b'x'; 16 * 1024 * 1024]; - std::fs::write(&dest, &payload).unwrap(); - let length = payload.len(); - let peer = tokio::spawn(async move { - let (mut socket, _) = listener.accept().await.unwrap(); - if header_wait { - let mut headers = Vec::new(); - while !headers.ends_with(b"\r\n\r\n") { - headers.push(socket.read_u8().await.unwrap()); - } - let mut remaining = length; - let mut buffer = vec![0; 256 * 1024]; - while remaining > 0 { - let n = socket.read(&mut buffer).await.unwrap(); - assert!(n > 0); - remaining -= n; - } + for header_wait in [false, true] { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}", listener.local_addr().unwrap()); + let payload = vec![b'x'; 16 * 1024 * 1024]; + std::fs::write(&dest, &payload).unwrap(); + let length = payload.len(); + let peer = tokio::spawn(async move { + let (mut socket, _) = listener.accept().await.unwrap(); + if header_wait { + let mut headers = Vec::new(); + while !headers.ends_with(b"\r\n\r\n") { + headers.push(socket.read_u8().await.unwrap()); } - std::future::pending::<()>().await; - }); - let state = VolumeState::new( - transfer_state(0).retry.clone(), - Arc::new( - crate::client::DatabricksHttpClient::with_default_retry(Default::default()) - .unwrap() - .storage_client(Some(Duration::from_millis(150))), - ), - Default::default(), - ); - let local = if stream { - Path::new("__input_stream__") - } else { - &dest - }; - let error = tokio::time::timeout( - Duration::from_secs(3), - state.complete( - async { Ok(instruction("PUT", &url, local)) }, - &options(dir.path()), - stream.then_some(payload), - ), - ) - .await - .expect("PUT idle watchdog") - .unwrap_err(); - assert_eq!( - error.error_code.as_deref(), - Some("VOLUME_STORAGE_NETWORK_ERROR") - ); - assert!(error.message.contains("timed out")); - peer.abort(); - } + let mut remaining = length; + let mut buffer = vec![0; 256 * 1024]; + while remaining > 0 { + let n = socket.read(&mut buffer).await.unwrap(); + assert!(n > 0); + remaining -= n; + } + } + std::future::pending::<()>().await; + }); + let state = VolumeState::new( + transfer_state(0).retry.clone(), + Arc::new( + crate::client::DatabricksHttpClient::with_default_retry(Default::default()) + .unwrap() + .storage_client(Some(Duration::from_millis(150))), + ), + Default::default(), + ); + let error = tokio::time::timeout( + Duration::from_secs(3), + state.complete( + async { Ok(instruction("PUT", &url, &dest)) }, + &options(dir.path()), + None, + ), + ) + .await + .expect("PUT idle watchdog") + .unwrap_err(); + assert_eq!( + error.error_code.as_deref(), + Some("VOLUME_STORAGE_NETWORK_ERROR") + ); + assert!(error.message.contains("timed out")); + peer.abort(); } } From 40bab443db4ea45a57a74ce9829fa4fc85b81de4 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Fri, 20 Nov 2026 03:03:49 +0000 Subject: [PATCH 47/63] fix(volume): start retries on failure and clear ADBC staging Signed-off-by: Aakash Saravanan --- NEXT_CHANGELOG.md | 2 ++ adbc/src/statement.rs | 67 +++++++++++++++++++++++++++++++++---- include/databricks_kernel.h | 12 ++++--- napi/src/async_statement.rs | 2 +- napi/src/error.rs | 10 +++--- napi/src/result.rs | 17 +++++++--- napi/src/statement.rs | 2 +- pyo3/src/result_stream.rs | 28 ++++++++++------ src/c_abi/error.rs | 10 +++--- src/kernel_error.rs | 15 +++++++++ src/volume.rs | 65 +++++++++++++++-------------------- 11 files changed, 153 insertions(+), 77 deletions(-) diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index 9e1f9242..c95587bf 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -18,6 +18,8 @@ changes go in their respective binding's NEXT_CHANGELOG. ### Changed +- This minor release adds public fields to `Error` and `ResultManifest`; no Rust consumer outside this repository's PyO3, NAPI and ADBC bindings builds these structs with literals. + ### Updated ### Fixed diff --git a/adbc/src/statement.rs b/adbc/src/statement.rs index e0bb15e5..49327b27 100644 --- a/adbc/src/statement.rs +++ b/adbc/src/statement.rs @@ -495,16 +495,15 @@ impl Statement { match key { STAGING_ALLOWED_PATHS_OPTION => { let text = expect_string(value, key)?; - let roots: Vec = serde_json::from_str(&text).map_err(|_| { + let roots: Option> = serde_json::from_str(&text).map_err(|_| { adbc_error( - format!("{key} expects a JSON array of strings"), + format!("{key} expects a JSON array of strings or null"), Status::InvalidArguments, ) })?; - self.volume_options = Some(kernel::VolumeOptions::new( - roots.into_iter().map(Into::into).collect(), - true, - )); + self.volume_options = roots.map(|roots| { + kernel::VolumeOptions::new(roots.into_iter().map(Into::into).collect(), true) + }); Ok(()) } ENABLE_DIRECT_RESULTS_OPTION => { @@ -1239,6 +1238,7 @@ fn complete_volume( Err(unsupported("Volume PUT with input streams")) } kernel::VolumeCompletion::Completed | kernel::VolumeCompletion::NotVolume => Ok(()), + _ => Err(unsupported("Volume completion outcome")), } } @@ -1539,6 +1539,61 @@ mod tests { use wiremock::matchers::{method, path}; use wiremock::{Mock, MockServer, ResponseTemplate}; + #[test] + fn volume_option_null_clears_paths_across_statement_reuse() { + let runtime = RuntimeHandle::create().unwrap(); + let server = runtime.block_on_safe(MockServer::start()); + runtime.block_on_safe(async { + Mock::given(method("POST")) + .and(path("/api/2.0/sql/warehouses/wh/sessions")) + .respond_with( + ResponseTemplate::new(200).set_body_json(json!({"session_id":"session"})), + ) + .expect(1) + .mount(&server) + .await; + Mock::given(method("DELETE")) + .respond_with(ResponseTemplate::new(200)) + .mount(&server) + .await; + }); + let session = runtime + .block_on_safe( + kernel::Session::builder() + .http_path(server.uri(), "/sql/1.0/warehouses/wh") + .auth(kernel::AuthConfig::Pat { + token: "test-token".into(), + identity_federation_client_id: None, + }) + .open(), + ) + .unwrap(); + let mut statement = Statement::new( + session.statement(), + session.metadata(), + Arc::clone(&runtime), + Arc::new(CancellationRegistry::default()), + false, + ); + let key = OptionStatement::Other(STAGING_ALLOWED_PATHS_OPTION.into()); + statement + .set_option(key.clone(), r#"["/allowed"]"#.into()) + .unwrap(); + statement.set_sql_query("SELECT 1").unwrap(); + assert_eq!( + statement.get_option_string(key.clone()).unwrap(), + r#"["/allowed"]"# + ); + statement.set_option(key.clone(), "null".into()).unwrap(); + statement.set_sql_query("SELECT 2").unwrap(); + assert!(statement.volume_options.is_none()); + assert_eq!( + statement.get_option_string(key).unwrap_err().status, + Status::NotFound + ); + runtime.block_on_safe(session.close()).unwrap(); + } + #[test] fn volume_option_controls_completion_on_all_execution_paths_and_preserves_rows() { let runtime = RuntimeHandle::create().unwrap(); diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h index 696b0b38..9ae08e46 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -984,15 +984,17 @@ typedef enum KernelVolumeCompletion { KernelVolumeCompletion_Completed = 2 } KernelVolumeCompletion; -/* Complete a server-marked file transfer while retaining its instruction rows. - * Roots are a JSON array of strings. - * The detached result-stream canceller can interrupt completion. */ +/* out is written only on success. */ KernelStatusCode kernel_executed_statement_is_volume_operation( const kernel_executed_statement_t* exec, bool* out); -/* The cached marker does not establish whether the executed owner is valid. */ +/* The cached marker does not establish whether the executed owner is valid. + * out is written only on success. */ KernelStatusCode kernel_result_stream_is_volume_operation( const kernel_result_stream_t* stream, bool* out); -/* out_status is written only on success. */ +/* Complete a server-marked Volume operation while retaining its instruction rows. + * Roots are a JSON array of strings. + * The detached result-stream canceller can interrupt completion. + * out_status is written only on success. */ KernelStatusCode kernel_result_stream_complete_volume_operation( kernel_result_stream_t* stream, const char* allowed_paths_json, bool remove_not_found_is_success, KernelVolumeCompletion* out_status); diff --git a/napi/src/async_statement.rs b/napi/src/async_statement.rs index 669c6991..7aecee93 100644 --- a/napi/src/async_statement.rs +++ b/napi/src/async_statement.rs @@ -511,7 +511,7 @@ impl AsyncResultHandle { .ok_or_else(|| closed_err("AsyncResultHandle"))? .complete_volume_operation(&options, None) .await - .map(crate::result::VolumeCompletion::from) + .and_then(crate::result::VolumeCompletion::try_from) .map_err(napi_err_from_kernel) }) .await diff --git a/napi/src/error.rs b/napi/src/error.rs index a12070f9..7f4b9f95 100644 --- a/napi/src/error.rs +++ b/napi/src/error.rs @@ -209,11 +209,11 @@ mod tests { #[test] fn local_error_metadata_is_optional_and_preserved() { let mut error = KernelError::not_found().message("missing local file"); - error.local_error = Some(Box::new(databricks_sql_kernel::LocalFileError { - raw_os_error: Some(2), - kind: std::io::ErrorKind::NotFound, - path: "local-file".into(), - })); + error.local_error = Some(Box::new(databricks_sql_kernel::LocalFileError::new( + Some(2), + std::io::ErrorKind::NotFound, + "local-file", + ))); let encoded = napi_err_from_kernel(error); let value: Value = serde_json::from_str(&encoded.reason[ERROR_SENTINEL.len()..]).unwrap(); assert_eq!(value["localOsError"], 2); diff --git a/napi/src/result.rs b/napi/src/result.rs index 80907046..1f0259dc 100644 --- a/napi/src/result.rs +++ b/napi/src/result.rs @@ -102,12 +102,19 @@ pub enum VolumeCompletion { Completed, } -impl From for VolumeCompletion { - fn from(value: databricks_sql_kernel::VolumeCompletion) -> Self { +impl TryFrom for VolumeCompletion { + type Error = KernelError; + + fn try_from( + value: databricks_sql_kernel::VolumeCompletion, + ) -> databricks_sql_kernel::Result { match value { - databricks_sql_kernel::VolumeCompletion::NotVolume => Self::NotVolume, - databricks_sql_kernel::VolumeCompletion::NeedsInputStream => Self::NeedsInputStream, - databricks_sql_kernel::VolumeCompletion::Completed => Self::Completed, + databricks_sql_kernel::VolumeCompletion::NotVolume => Ok(Self::NotVolume), + databricks_sql_kernel::VolumeCompletion::NeedsInputStream => Ok(Self::NeedsInputStream), + databricks_sql_kernel::VolumeCompletion::Completed => Ok(Self::Completed), + _ => { + Err(KernelError::not_implemented().message("Unsupported Volume completion outcome")) + } } } } diff --git a/napi/src/statement.rs b/napi/src/statement.rs index 0db77527..e4e5deb6 100644 --- a/napi/src/statement.rs +++ b/napi/src/statement.rs @@ -223,7 +223,7 @@ impl Statement { stream .complete_volume_operation(&options, None) .await - .map(crate::result::VolumeCompletion::from) + .and_then(crate::result::VolumeCompletion::try_from) .map_err(napi_err_from_kernel) }) .await diff --git a/pyo3/src/result_stream.rs b/pyo3/src/result_stream.rs index 0f94b335..1ab4f421 100644 --- a/pyo3/src/result_stream.rs +++ b/pyo3/src/result_stream.rs @@ -62,12 +62,18 @@ pub enum VolumeCompletion { Completed, } -impl From for VolumeCompletion { - fn from(value: databricks_sql_kernel::VolumeCompletion) -> Self { +impl TryFrom for VolumeCompletion { + type Error = databricks_sql_kernel::Error; + + fn try_from( + value: databricks_sql_kernel::VolumeCompletion, + ) -> databricks_sql_kernel::Result { match value { - databricks_sql_kernel::VolumeCompletion::NotVolume => Self::NotVolume, - databricks_sql_kernel::VolumeCompletion::NeedsInputStream => Self::NeedsInputStream, - databricks_sql_kernel::VolumeCompletion::Completed => Self::Completed, + databricks_sql_kernel::VolumeCompletion::NotVolume => Ok(Self::NotVolume), + databricks_sql_kernel::VolumeCompletion::NeedsInputStream => Ok(Self::NeedsInputStream), + databricks_sql_kernel::VolumeCompletion::Completed => Ok(Self::Completed), + _ => Err(databricks_sql_kernel::Error::not_implemented() + .message("Unsupported Volume completion outcome")), } } } @@ -84,12 +90,12 @@ pub(crate) fn complete_volume( allowed_paths.into_iter().map(Into::into).collect(), remove_not_found_is_success, ); - Ok(run_kernel_interruptible!( - py, - runtime, - stream.complete_volume_operation(&options, input_bytes) - )? - .into()) + run_kernel_interruptible!(py, runtime, async { + stream + .complete_volume_operation(&options, input_bytes) + .await + .and_then(VolumeCompletion::try_from) + }) } #[pymethods] diff --git a/src/c_abi/error.rs b/src/c_abi/error.rs index d6e67ad7..10248b7e 100644 --- a/src/c_abi/error.rs +++ b/src/c_abi/error.rs @@ -285,11 +285,11 @@ mod tests { let mut error = Error::sql_error() .message("statement gone") .with_error_code("STATEMENT_NOT_FOUND"); - error.local_error = Some(Box::new(crate::kernel_error::LocalFileError { - raw_os_error: Some(2), - kind: std::io::ErrorKind::NotFound, - path: "local-file".into(), - })); + error.local_error = Some(Box::new(crate::kernel_error::LocalFileError::new( + Some(2), + std::io::ErrorKind::NotFound, + "local-file", + ))); store_error(error); with_last_error(|e| { let e = e.expect("error present"); diff --git a/src/kernel_error.rs b/src/kernel_error.rs index 372b7263..ffcb51f3 100644 --- a/src/kernel_error.rs +++ b/src/kernel_error.rs @@ -247,6 +247,7 @@ pub struct Error { } /// Local filesystem error details retained across language boundaries. +#[non_exhaustive] #[derive(Debug, Clone)] pub struct LocalFileError { pub raw_os_error: Option, @@ -254,6 +255,20 @@ pub struct LocalFileError { pub path: String, } +impl LocalFileError { + pub fn new( + raw_os_error: Option, + kind: std::io::ErrorKind, + path: impl Into, + ) -> Self { + Self { + raw_os_error, + kind, + path: path.into(), + } + } +} + impl Error { // ─── Core constructors ────────────────────────────────────────── diff --git a/src/volume.rs b/src/volume.rs index d6737584..2f1a261e 100644 --- a/src/volume.rs +++ b/src/volume.rs @@ -61,6 +61,7 @@ impl VolumeOptions { } /// Result of explicitly completing a server-marked Volume instruction. +#[non_exhaustive] #[derive(Debug, Clone, Copy, PartialEq, Eq)] #[repr(C)] pub enum VolumeCompletion { @@ -192,7 +193,7 @@ impl VolumeState { } else { None }; - let started = std::time::Instant::now(); + let mut retry_started = None; let mut attempt = 0; loop { let mut retry_after = None; @@ -209,6 +210,7 @@ impl VolumeState { Ok(completion) => return Ok(completion), Err(error) => error, }; + let started = retry_started.get_or_insert_with(std::time::Instant::now); if !error.retryable || attempt >= self.retry.max_retries { return Err(error.message(format!("after {} attempts", attempt + 1))); } @@ -516,11 +518,11 @@ fn local_error(error: std::io::Error, path: &str) -> Error { .with_error_code("VOLUME_LOCAL_FILE_ERROR") .with_sql_state("HY000") .message(format!("{error}: {path}")) - .with_local_error(LocalFileError { - raw_os_error: error.raw_os_error(), - kind: error.kind(), - path: path.to_owned(), - }) + .with_local_error(LocalFileError::new( + error.raw_os_error(), + error.kind(), + path, + )) } fn normalize(path: &Path) -> Result { @@ -774,6 +776,14 @@ mod tests { } } + fn storage(read_timeout: Option) -> Arc { + Arc::new( + crate::client::DatabricksHttpClient::with_default_retry(Default::default()) + .unwrap() + .storage_client(read_timeout), + ) + } + fn transfer_state(max_retries: u32) -> Arc { VolumeState::new( RetryConfig { @@ -782,11 +792,7 @@ mod tests { max_wait: Duration::ZERO, ..Default::default() }, - Arc::new( - crate::client::DatabricksHttpClient::with_default_retry(Default::default()) - .unwrap() - .storage_client(None), - ), + storage(None), Default::default(), ) } @@ -851,7 +857,9 @@ mod tests { assert_eq!(request.body, b"payload"); } if count.fetch_add(1, Ordering::SeqCst) == 0 { - ResponseTemplate::new(503).insert_header("retry-after", "0") + ResponseTemplate::new(503) + .insert_header("retry-after", "0") + .set_delay(Duration::from_millis(200)) } else { ResponseTemplate::new(200).set_body_bytes(b"payload") } @@ -876,7 +884,8 @@ mod tests { &file }; let batch = instruction(operation, &format!("{}/object", server.uri()), local); - let state = transfer_state(6); + let mut state = transfer_state(6); + Arc::get_mut(&mut state).unwrap().retry.overall_timeout = Duration::from_millis(100); let options = options(dir.path()); assert_eq!( state @@ -940,11 +949,7 @@ mod tests { max_wait: Duration::ZERO, ..Default::default() }, - Arc::new( - crate::client::DatabricksHttpClient::with_default_retry(Default::default()) - .unwrap() - .storage_client(None), - ), + storage(None), Default::default(), ); let batch = instruction( @@ -990,11 +995,7 @@ mod tests { max_wait: Duration::from_secs(30), ..Default::default() }, - Arc::new( - crate::client::DatabricksHttpClient::with_default_retry(Default::default()) - .unwrap() - .storage_client(None), - ), + storage(None), Default::default(), ); let batch = instruction("REMOVE", &server.uri(), Path::new("")); @@ -1284,11 +1285,7 @@ mod tests { transfer_state(if operation == "PUT" { 1 } else { 0 }) .retry .clone(), - Arc::new( - crate::client::DatabricksHttpClient::with_default_retry(Default::default()) - .unwrap() - .storage_client(Some(Duration::from_millis(150))), - ), + storage(Some(Duration::from_millis(150))), Default::default(), ); let batch = instruction(operation, &url, &dest); @@ -1339,11 +1336,7 @@ mod tests { let dest = dir.path().join("download"); let state = VolumeState::new( transfer_state(0).retry.clone(), - Arc::new( - crate::client::DatabricksHttpClient::with_default_retry(Default::default()) - .unwrap() - .storage_client(Some(Duration::from_millis(150))), - ), + storage(Some(Duration::from_millis(150))), Default::default(), ); state @@ -1413,11 +1406,7 @@ mod tests { }); let state = VolumeState::new( transfer_state(0).retry.clone(), - Arc::new( - crate::client::DatabricksHttpClient::with_default_retry(Default::default()) - .unwrap() - .storage_client(Some(Duration::from_millis(150))), - ), + storage(Some(Duration::from_millis(150))), Default::default(), ); let error = tokio::time::timeout( From f41140c06b86c2a7585278ec7f3632a76e1e6ded Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Fri, 20 Nov 2026 03:43:26 +0000 Subject: [PATCH 48/63] fixup! fix(volume): start retries on failure and clear ADBC staging Signed-off-by: Aakash Saravanan --- adbc/src/statement.rs | 62 +++++-------------------------------------- 1 file changed, 7 insertions(+), 55 deletions(-) diff --git a/adbc/src/statement.rs b/adbc/src/statement.rs index 49327b27..9116a2a4 100644 --- a/adbc/src/statement.rs +++ b/adbc/src/statement.rs @@ -1539,61 +1539,6 @@ mod tests { use wiremock::matchers::{method, path}; use wiremock::{Mock, MockServer, ResponseTemplate}; - #[test] - fn volume_option_null_clears_paths_across_statement_reuse() { - let runtime = RuntimeHandle::create().unwrap(); - let server = runtime.block_on_safe(MockServer::start()); - runtime.block_on_safe(async { - Mock::given(method("POST")) - .and(path("/api/2.0/sql/warehouses/wh/sessions")) - .respond_with( - ResponseTemplate::new(200).set_body_json(json!({"session_id":"session"})), - ) - .expect(1) - .mount(&server) - .await; - Mock::given(method("DELETE")) - .respond_with(ResponseTemplate::new(200)) - .mount(&server) - .await; - }); - let session = runtime - .block_on_safe( - kernel::Session::builder() - .http_path(server.uri(), "/sql/1.0/warehouses/wh") - .auth(kernel::AuthConfig::Pat { - token: "test-token".into(), - identity_federation_client_id: None, - }) - .open(), - ) - .unwrap(); - let mut statement = Statement::new( - session.statement(), - session.metadata(), - Arc::clone(&runtime), - Arc::new(CancellationRegistry::default()), - false, - ); - let key = OptionStatement::Other(STAGING_ALLOWED_PATHS_OPTION.into()); - statement - .set_option(key.clone(), r#"["/allowed"]"#.into()) - .unwrap(); - statement.set_sql_query("SELECT 1").unwrap(); - assert_eq!( - statement.get_option_string(key.clone()).unwrap(), - r#"["/allowed"]"# - ); - statement.set_option(key.clone(), "null".into()).unwrap(); - statement.set_sql_query("SELECT 2").unwrap(); - assert!(statement.volume_options.is_none()); - assert_eq!( - statement.get_option_string(key).unwrap_err().status, - Status::NotFound - ); - runtime.block_on_safe(session.close()).unwrap(); - } - #[test] fn volume_option_controls_completion_on_all_execution_paths_and_preserves_rows() { let runtime = RuntimeHandle::create().unwrap(); @@ -1691,7 +1636,14 @@ mod tests { ); } statement.set_option(key.clone(), "[]".into()).unwrap(); + statement.set_sql_query("SELECT 1").unwrap(); assert_eq!(statement.get_option_string(key.clone()).unwrap(), "[]"); + statement.set_option(key.clone(), "null".into()).unwrap(); + assert_eq!( + statement.get_option_string(key.clone()).unwrap_err().status, + Status::NotFound + ); + statement.set_option(key.clone(), "[]".into()).unwrap(); let mut transfers = 0; for mode in ["raw", "sync", "async", "await", "fetch", "bound", "update"] { let mut statement = Statement::new( From 28006b2d359c00a476604445d97a3d2c932f1a12 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Fri, 20 Nov 2026 05:59:20 +0000 Subject: [PATCH 49/63] fixup! fix(volume): start retries on failure and clear ADBC staging Signed-off-by: Aakash Saravanan --- NEXT_CHANGELOG.md | 4 +++- adbc/src/error.rs | 11 ++++++++- adbc/src/statement.rs | 1 - napi/src/async_statement.rs | 2 +- napi/src/result.rs | 17 ++++---------- napi/src/statement.rs | 2 +- pyo3/src/result_stream.rs | 28 +++++++++-------------- pyo3/src/session.rs | 4 ++-- src/client/http_tls_tests.rs | 2 -- src/statement/mutable.rs | 1 - src/telemetry/statement.rs | 44 ++++++++++++++++++++++++++++++++++-- src/volume.rs | 1 - tests/v0_volume_wiremock.rs | 35 ++++++++++++++++++++++++++++ 13 files changed, 110 insertions(+), 42 deletions(-) diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index c95587bf..d59874d9 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -18,7 +18,9 @@ changes go in their respective binding's NEXT_CHANGELOG. ### Changed -- This minor release adds public fields to `Error` and `ResultManifest`; no Rust consumer outside this repository's PyO3, NAPI and ADBC bindings builds these structs with literals. +- Adds public fields to `Error` and `ResultManifest`. Code that builds these + structs with struct literals must be updated. Supported consumers are the PyO3, + NAPI, C ABI and ADBC bindings. ### Updated diff --git a/adbc/src/error.rs b/adbc/src/error.rs index 81c96097..c8a84533 100644 --- a/adbc/src/error.rs +++ b/adbc/src/error.rs @@ -115,7 +115,12 @@ mod tests { kernel::Error::sql_error() .message("bad query") .with_sql_state("42000") - .with_vendor_code(42), + .with_vendor_code(42) + .with_local_error(kernel::LocalFileError::new( + Some(2), + std::io::ErrorKind::NotFound, + "/allowed/missing", + )), ); assert_eq!(mapped.status, Status::InvalidData); assert_eq!(mapped.vendor_code, 42); @@ -123,6 +128,10 @@ mod tests { mapped.sqlstate, (*b"42000").map(|byte| byte as std::ffi::c_char) ); + assert!(mapped + .details + .unwrap() + .contains(&("databricks.local_path".into(), b"/allowed/missing".to_vec()))); } #[test] diff --git a/adbc/src/statement.rs b/adbc/src/statement.rs index 9116a2a4..6d648de9 100644 --- a/adbc/src/statement.rs +++ b/adbc/src/statement.rs @@ -1238,7 +1238,6 @@ fn complete_volume( Err(unsupported("Volume PUT with input streams")) } kernel::VolumeCompletion::Completed | kernel::VolumeCompletion::NotVolume => Ok(()), - _ => Err(unsupported("Volume completion outcome")), } } diff --git a/napi/src/async_statement.rs b/napi/src/async_statement.rs index 7aecee93..669c6991 100644 --- a/napi/src/async_statement.rs +++ b/napi/src/async_statement.rs @@ -511,7 +511,7 @@ impl AsyncResultHandle { .ok_or_else(|| closed_err("AsyncResultHandle"))? .complete_volume_operation(&options, None) .await - .and_then(crate::result::VolumeCompletion::try_from) + .map(crate::result::VolumeCompletion::from) .map_err(napi_err_from_kernel) }) .await diff --git a/napi/src/result.rs b/napi/src/result.rs index 1f0259dc..80907046 100644 --- a/napi/src/result.rs +++ b/napi/src/result.rs @@ -102,19 +102,12 @@ pub enum VolumeCompletion { Completed, } -impl TryFrom for VolumeCompletion { - type Error = KernelError; - - fn try_from( - value: databricks_sql_kernel::VolumeCompletion, - ) -> databricks_sql_kernel::Result { +impl From for VolumeCompletion { + fn from(value: databricks_sql_kernel::VolumeCompletion) -> Self { match value { - databricks_sql_kernel::VolumeCompletion::NotVolume => Ok(Self::NotVolume), - databricks_sql_kernel::VolumeCompletion::NeedsInputStream => Ok(Self::NeedsInputStream), - databricks_sql_kernel::VolumeCompletion::Completed => Ok(Self::Completed), - _ => { - Err(KernelError::not_implemented().message("Unsupported Volume completion outcome")) - } + databricks_sql_kernel::VolumeCompletion::NotVolume => Self::NotVolume, + databricks_sql_kernel::VolumeCompletion::NeedsInputStream => Self::NeedsInputStream, + databricks_sql_kernel::VolumeCompletion::Completed => Self::Completed, } } } diff --git a/napi/src/statement.rs b/napi/src/statement.rs index e4e5deb6..0db77527 100644 --- a/napi/src/statement.rs +++ b/napi/src/statement.rs @@ -223,7 +223,7 @@ impl Statement { stream .complete_volume_operation(&options, None) .await - .and_then(crate::result::VolumeCompletion::try_from) + .map(crate::result::VolumeCompletion::from) .map_err(napi_err_from_kernel) }) .await diff --git a/pyo3/src/result_stream.rs b/pyo3/src/result_stream.rs index 1ab4f421..0f94b335 100644 --- a/pyo3/src/result_stream.rs +++ b/pyo3/src/result_stream.rs @@ -62,18 +62,12 @@ pub enum VolumeCompletion { Completed, } -impl TryFrom for VolumeCompletion { - type Error = databricks_sql_kernel::Error; - - fn try_from( - value: databricks_sql_kernel::VolumeCompletion, - ) -> databricks_sql_kernel::Result { +impl From for VolumeCompletion { + fn from(value: databricks_sql_kernel::VolumeCompletion) -> Self { match value { - databricks_sql_kernel::VolumeCompletion::NotVolume => Ok(Self::NotVolume), - databricks_sql_kernel::VolumeCompletion::NeedsInputStream => Ok(Self::NeedsInputStream), - databricks_sql_kernel::VolumeCompletion::Completed => Ok(Self::Completed), - _ => Err(databricks_sql_kernel::Error::not_implemented() - .message("Unsupported Volume completion outcome")), + databricks_sql_kernel::VolumeCompletion::NotVolume => Self::NotVolume, + databricks_sql_kernel::VolumeCompletion::NeedsInputStream => Self::NeedsInputStream, + databricks_sql_kernel::VolumeCompletion::Completed => Self::Completed, } } } @@ -90,12 +84,12 @@ pub(crate) fn complete_volume( allowed_paths.into_iter().map(Into::into).collect(), remove_not_found_is_success, ); - run_kernel_interruptible!(py, runtime, async { - stream - .complete_volume_operation(&options, input_bytes) - .await - .and_then(VolumeCompletion::try_from) - }) + Ok(run_kernel_interruptible!( + py, + runtime, + stream.complete_volume_operation(&options, input_bytes) + )? + .into()) } #[pymethods] diff --git a/pyo3/src/session.rs b/pyo3/src/session.rs index b6afec53..51331b4d 100644 --- a/pyo3/src/session.rs +++ b/pyo3/src/session.rs @@ -324,8 +324,8 @@ impl Session { /// is bounded by the shorter limit. Unset or `0` keeps the kernel default /// (120 seconds). /// For Volume transfers, a positive value bounds connection establishment, - /// GET/REMOVE response-header waits and all response-body reads. PUT header - /// waits have no deadline, allowing progressing uploads to finish. + /// GET/REMOVE header and body reads, PUT upload inactivity and the PUT + /// response-header wait. Redirected stream PUT resends have no idle bound. /// /// `max_connections` sets the maximum idle connections retained per host. /// Unset keeps the kernel default (100); zero is rejected. diff --git a/src/client/http_tls_tests.rs b/src/client/http_tls_tests.rs index c676c0c8..5d326292 100644 --- a/src/client/http_tls_tests.rs +++ b/src/client/http_tls_tests.rs @@ -347,8 +347,6 @@ async fn storage_redirect_rejects_https_to_http_on_the_same_port() { .await .unwrap() .get(format!("https://{address}/object")) - .header("authorization", "storage-secret") - .header("cookie", "storage-cookie") .send() .await .unwrap_err(); diff --git a/src/statement/mutable.rs b/src/statement/mutable.rs index 72720918..b8d7a4db 100644 --- a/src/statement/mutable.rs +++ b/src/statement/mutable.rs @@ -1028,7 +1028,6 @@ impl StatementCanceller { impl Drop for Statement { fn drop(&mut self) { - self.volume_state().cancel(); // Flip the validity flag so any executed handle the caller // still holds short-circuits to InvalidStatementHandle on its // next call without a network round-trip. Server-side cleanup diff --git a/src/telemetry/statement.rs b/src/telemetry/statement.rs index 4030937a..b2cc5b5b 100644 --- a/src/telemetry/statement.rs +++ b/src/telemetry/statement.rs @@ -292,7 +292,7 @@ fn duration_millis(duration: Duration) -> i64 { mod tests { use super::*; use crate::kernel_error::ErrorCode; - use crate::reader::test_utils::{BatchThenErrorReader, MockReader}; + use crate::reader::test_utils::{BatchThenErrorReader, ErrorReader, MockReader}; use crate::reader::{ResultReader, ResultReaderMetrics}; use crate::result_stream::ResultStream; use crate::telemetry::models::OperationType; @@ -368,7 +368,47 @@ mod tests { } #[tokio::test] - async fn result_errors_finalize_statement_with_error_before_drop() { + async fn peek_first_batch_error_finalizes_statement_with_error_before_drop() { + let connection = Arc::new(CapturingConnectionTelemetry::default()); + let telemetry = StatementTelemetry::new( + connection.clone(), + StatementType::Sql, + OperationType::ExecuteStatement, + ); + let reader = ErrorReader { + schema: Arc::new(Schema::empty()), + }; + let mut stream = ResultStream::from_reader(Box::new(reader)) + .await + .expect("schema succeeds"); + stream.attach_telemetry(telemetry); + + let error = match stream.peek_first_batch().await { + Ok(_) => panic!("peek should surface reader error"), + Err(error) => error, + }; + assert_eq!(error.code, ErrorCode::Internal); + + drop(stream); + + let events = connection.statement_events.lock().expect("events mutex"); + assert_eq!( + events.len(), + 1, + "peek error should finalize once; Drop must not overwrite it with success" + ); + let event = &events[0]; + assert_eq!(event.context.statement_type, StatementType::Sql); + assert_eq!(event.error_code, Some(ErrorCode::Internal)); + assert_eq!(event.error_message.as_deref(), Some("simulated read error")); + assert!( + event.context.consumption_latency.is_some(), + "failed consumption should still record result-consumption latency" + ); + } + + #[tokio::test] + async fn volume_errors_finalize_statement_with_error_before_drop() { enum Case { VolumeReader, Instruction, diff --git a/src/volume.rs b/src/volume.rs index 2f1a261e..dbc99f0c 100644 --- a/src/volume.rs +++ b/src/volume.rs @@ -61,7 +61,6 @@ impl VolumeOptions { } /// Result of explicitly completing a server-marked Volume instruction. -#[non_exhaustive] #[derive(Debug, Clone, Copy, PartialEq, Eq)] #[repr(C)] pub enum VolumeCompletion { diff --git a/tests/v0_volume_wiremock.rs b/tests/v0_volume_wiremock.rs index 6117206b..1965edcf 100644 --- a/tests/v0_volume_wiremock.rs +++ b/tests/v0_volume_wiremock.rs @@ -289,6 +289,41 @@ async fn sync_and_direct_closed_results_complete_explicitly_and_keep_raw_rows() } } +#[tokio::test] +async fn completion_outlives_parent_statement() { + let server = MockServer::start().await; + let dir = tempfile::tempdir().unwrap(); + let destination = dir.path().join("download"); + let session = session( + &server, + response(&server, true, destination.to_str().unwrap()), + ) + .await; + Mock::given(method("GET")) + .and(path("/object")) + .respond_with(ResponseTemplate::new(200).set_body_bytes(b"downloaded")) + .mount(&server) + .await; + let mut statement = session.statement(); + statement.spec().sql("operation"); + let mut executed = statement.execute().await.unwrap(); + drop(statement); + assert_eq!( + executed + .result_stream_mut() + .complete_volume_operation( + &VolumeOptions::new(vec![dir.path().to_owned()], false), + None, + ) + .await + .unwrap(), + VolumeCompletion::Completed + ); + assert_eq!(std::fs::read(&destination).unwrap(), b"downloaded"); + executed.close().await.unwrap(); + session.close().await.unwrap(); +} + #[tokio::test] async fn marker_false_and_id_attachment_cannot_initiate_transfer() { for marked in [false, true] { From 9066fedd2e0fced90d10780bbe4f0256f74b0baf Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Fri, 20 Nov 2026 08:38:30 +0000 Subject: [PATCH 50/63] fixup! fix(volume): start retries on failure and clear ADBC staging Signed-off-by: Aakash Saravanan --- .github/workflows/pr-checks.yml | 26 +++++++++++++++++++++++++ .github/workflows/release-debuginfo.yml | 4 ---- napi/src/database.rs | 14 +++++++++++++ src/result_stream.rs | 2 +- src/statement/executed_async.rs | 26 +++++++++++-------------- src/statement/mutable.rs | 5 +---- src/volume.rs | 13 +++++++++---- 7 files changed, 62 insertions(+), 28 deletions(-) diff --git a/.github/workflows/pr-checks.yml b/.github/workflows/pr-checks.yml index ffaa60bd..ea0f1da2 100644 --- a/.github/workflows/pr-checks.yml +++ b/.github/workflows/pr-checks.yml @@ -131,6 +131,32 @@ jobs: # a live workspace; `rust-e2e.yml` runs them separately. run: cargo test --workspace + volume-windows: + name: Volume tests (Windows) + runs-on: + group: databricks-protected-runner-group + labels: [windows-server-latest] + timeout-minutes: 45 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + + - uses: ./.github/actions/setup-jfrog + with: + cargo: "true" + + - uses: actions-rust-lang/setup-rust-toolchain@166cdcfd11aee3cb47222f9ddb555ce30ddb9659 # v1.17.0 + with: + toolchain: stable + + - name: Set up MSVC environment + uses: ilammy/msvc-dev-cmd@0b201ec74fa43914dc39ae48a89fd1d8cb592756 # v1 + with: + arch: x64 + + - name: Volume file and cancellation tests + shell: pwsh + run: cargo test --locked --lib volume::tests + c-abi: name: C ABI smoke test runs-on: diff --git a/.github/workflows/release-debuginfo.yml b/.github/workflows/release-debuginfo.yml index 2b9aefa2..afdae1a4 100644 --- a/.github/workflows/release-debuginfo.yml +++ b/.github/workflows/release-debuginfo.yml @@ -132,10 +132,6 @@ jobs: with: arch: x64 - - name: Volume file and cancellation tests - shell: pwsh - run: cargo test --locked --lib volume::tests - - name: Verify linker PDB shell: pwsh run: ./.github/scripts/check-release-debuginfo.ps1 diff --git a/napi/src/database.rs b/napi/src/database.rs index 3409b062..45d93613 100644 --- a/napi/src/database.rs +++ b/napi/src/database.rs @@ -1585,6 +1585,20 @@ mod tests { assert!(build_http_config(&mut enabled).sea_response_compression_enabled); } + #[test] + fn http_socket_timeout_default_and_zero_preserve_request_timeout() { + for (socket_timeout_ms, storage_read_timeout) in [ + (None, Some(std::time::Duration::from_secs(15 * 60))), + (Some(0), None), + ] { + let mut options = base(); + options.socket_timeout_ms = socket_timeout_ms; + let http = build_http_config(&mut options); + assert_eq!(http.storage_read_timeout, storage_read_timeout); + assert_eq!(http.request_timeout, std::time::Duration::from_secs(120)); + } + } + #[test] fn http_retry_knobs_map_onto_http_config() { let mut o = base(); diff --git a/src/result_stream.rs b/src/result_stream.rs index 9b825c74..6f9b03b9 100644 --- a/src/result_stream.rs +++ b/src/result_stream.rs @@ -719,7 +719,7 @@ impl ResultStream { } pub(crate) fn volume_state(&self) -> Option> { - self.volume.as_ref().map(Arc::clone) + self.volume.clone() } pub(crate) fn cancel_volume(&self) { diff --git a/src/statement/executed_async.rs b/src/statement/executed_async.rs index 65453ae3..ec4c9517 100644 --- a/src/statement/executed_async.rs +++ b/src/statement/executed_async.rs @@ -277,13 +277,17 @@ fn deadline_policy(timeout: ExecutionTimeout) -> (Option, bo } impl ExecutedAsyncStatement { + fn cancel_volume(&self) { + if let Some(volume) = &self.volume { + volume.cancel(); + } + } + /// Produce the stable client query-timeout error and schedule bounded, /// best-effort server cleanup when a deadline retained across /// caller-driven status polls expires. pub(crate) fn expire_client_query_timeout(&self) -> Error { - if let Some(volume) = &self.volume { - volume.cancel(); - } + self.cancel_volume(); self.owner_released.store(true, Ordering::Release); self.clear_pending_result(); if !self.client_timeout_expired.swap(true, Ordering::AcqRel) { @@ -1101,9 +1105,7 @@ impl ExecutedStatementHandle for ExecutedAsyncStatement { submitted it", )); } - if let Some(volume) = &self.volume { - volume.cancel(); - } + self.cancel_volume(); self.session .transport() .cancel_statement(&self.statement_id) @@ -1134,9 +1136,7 @@ impl ExecutedAsyncStatement { async fn close_server_statement(&self) -> Result<()> { if self.owning { - if let Some(volume) = &self.volume { - volume.cancel(); - } + self.cancel_volume(); self.owner_released.store(true, Ordering::Release); self.clear_pending_result(); } @@ -1255,9 +1255,7 @@ impl AsyncStatementCanceller { is owned by whoever submitted it", )); } - if let Some(volume) = &self.volume { - volume.cancel(); - } + self.cancel_volume_operation(); self.session .transport() .cancel_statement(&self.statement_id) @@ -1276,9 +1274,7 @@ impl AsyncStatementCanceller { impl Drop for ExecutedAsyncStatement { fn drop(&mut self) { if self.owning { - if let Some(volume) = &self.volume { - volume.cancel(); - } + self.cancel_volume(); self.owner_released.store(true, Ordering::Release); self.clear_pending_result(); } diff --git a/src/statement/mutable.rs b/src/statement/mutable.rs index b8d7a4db..bc33f249 100644 --- a/src/statement/mutable.rs +++ b/src/statement/mutable.rs @@ -993,10 +993,7 @@ impl StatementCanceller { /// concurrently with the `execute()` it targets — the two share /// only the id slot (behind a `Mutex`), no mutable statement state. pub async fn cancel(&self) -> Result { - self.volume - .lock() - .unwrap_or_else(|e| e.into_inner()) - .cancel(); + self.cancel_volume_operation(); let id = self.inflight_id.lock().ok().and_then(|g| g.clone()); async { // Log both outcomes at the decision point so a host debugging a diff --git a/src/volume.rs b/src/volume.rs index dbc99f0c..0759af1a 100644 --- a/src/volume.rs +++ b/src/volume.rs @@ -64,9 +64,9 @@ impl VolumeOptions { #[derive(Debug, Clone, Copy, PartialEq, Eq)] #[repr(C)] pub enum VolumeCompletion { - NotVolume, - NeedsInputStream, - Completed, + NotVolume = 0, + NeedsInputStream = 1, + Completed = 2, } pub(crate) struct VolumeState { @@ -1467,7 +1467,6 @@ mod tests { } } - #[cfg(any(unix, windows))] #[test] fn symlinks_require_lexical_authority_and_resolved_target_in_any_allowed_root() { #[cfg(unix)] @@ -1480,6 +1479,12 @@ mod tests { std::fs::create_dir(&root).unwrap(); std::fs::create_dir(&other).unwrap(); std::fs::write(root.join("file"), b"ok").unwrap(); + #[cfg(windows)] + assert!(allowed_path( + root.join("file").to_str().unwrap(), + &[dir.path().join("ROOT")] + ) + .is_ok()); symlink_file(root.join("file"), root.join("inside")).unwrap(); symlink_file(other.join("missing"), root.join("escape")).unwrap(); symlink_dir(&root, dir.path().join("alias")).unwrap(); From f00cd91d4bb19e9408129ec1c1324b1c2b8f2349 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Fri, 20 Nov 2026 20:01:41 +0000 Subject: [PATCH 51/63] fixup! fix(volume): start retries on failure and clear ADBC staging Signed-off-by: Aakash Saravanan --- README.md | 4 ++-- include/databricks_kernel.h | 24 ++++++++++---------- napi/index.d.ts | 18 +++++++++------ napi/src/async_statement.rs | 6 +++-- napi/src/database.rs | 8 +++---- napi/src/statement.rs | 3 ++- pyo3/src/session.rs | 6 ++--- src/c_abi/error.rs | 3 ++- src/c_abi/result.rs | 12 ++++++---- src/c_abi/session.rs | 7 +++--- src/c_abi/statement.rs | 2 +- src/config.rs | 6 ++--- src/kernel_error.rs | 14 ++++++++---- src/result_stream.rs | 31 +++++++++++++------------- src/volume.rs | 44 ++++++++++++++++++------------------- tests/v0_volume_wiremock.rs | 2 +- 16 files changed, 103 insertions(+), 87 deletions(-) diff --git a/README.md b/README.md index 8d325241..29676784 100644 --- a/README.md +++ b/README.md @@ -70,8 +70,8 @@ and security vulnerabilities should be reported according to Call `ResultStream::complete_volume_operation` with `VolumeOptions` before reading server-marked PUT, GET and REMOVE rows; omit completion for raw results. -See [`VolumeOptions`](https://docs.rs/databricks-sql-kernel/latest/databricks_sql_kernel/struct.VolumeOptions.html) -for authorization, completion and transfer behavior. +See [`ResultStream::complete_volume_operation`](https://docs.rs/databricks-sql-kernel/latest/databricks_sql_kernel/struct.ResultStream.html#method.complete_volume_operation) +for transfer behavior. ## License diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h index 9ae08e46..4cf94ff9 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -56,7 +56,7 @@ * - **A result stream borrows its executed handle.** Closing the executed * handle invalidates any stream obtained from it: schema access, fetching * and Volume completion return `InvalidStatementHandle` (a defined error, - * not UB). The cached Volume marker remains readable until stream close. + * not UB). * - **Close is awaited.** `kernel_session_close` waits for the server-side * delete to complete and flushes close-session telemetry before returning. * If close fails, the kernel still schedules best-effort cleanup when the @@ -375,13 +375,13 @@ KernelStatusCode kernel_session_config_set_sea_response_compression_enabled( /* Configure the total timeout for one HTTP request, from connection start * through response-body completion. A separate 30s connection timeout also * applies, so connection establishment is bounded by the shorter limit. - * Volume storage inactivity uses the separate storage-read-timeout setter. + * Does not apply to Volume file transfers; see the storage read timeout. * `request_timeout_ms == 0` keeps the kernel default (120s). */ KernelStatusCode kernel_session_config_set_request_timeout(KernelSessionConfig* config, uint64_t request_timeout_ms); -/* Configure Volume storage idle time for reads, upload progress and PUT response - * waits. Zero disables it. Redirected stream PUT resends have no idle bound. */ +/* Idle limit for Volume file transfers: a transfer fails after this long without + * progress. Also caps connection setup. Zero sets no limit. */ KernelStatusCode kernel_session_config_set_storage_read_timeout(KernelSessionConfig* config, uint64_t timeout_ms); @@ -984,17 +984,19 @@ typedef enum KernelVolumeCompletion { KernelVolumeCompletion_Completed = 2 } KernelVolumeCompletion; -/* out is written only on success. */ +/* Whether the statement is a Volume PUT, GET or REMOVE. */ KernelStatusCode kernel_executed_statement_is_volume_operation( const kernel_executed_statement_t* exec, bool* out); -/* The cached marker does not establish whether the executed owner is valid. - * out is written only on success. */ +/* Same flag, read from the stream. Still succeeds after the executed statement + * is closed. */ KernelStatusCode kernel_result_stream_is_volume_operation( const kernel_result_stream_t* stream, bool* out); -/* Complete a server-marked Volume operation while retaining its instruction rows. - * Roots are a JSON array of strings. - * The detached result-stream canceller can interrupt completion. - * out_status is written only on success. */ +/* Runs the file transfer for a Volume PUT, GET or REMOVE result. Call before + * fetching; the rows stay readable afterwards. + * allowed_paths_json: JSON array of local directories the transfer may use. + * remove_not_found_is_success: report success when the remote file is missing. + * Returns NeedsInputStream for a stream upload, which this API cannot perform. + * kernel_result_stream_canceller_cancel interrupts it from another thread. */ KernelStatusCode kernel_result_stream_complete_volume_operation( kernel_result_stream_t* stream, const char* allowed_paths_json, bool remove_not_found_is_success, KernelVolumeCompletion* out_status); diff --git a/napi/index.d.ts b/napi/index.d.ts index 4ea46e56..ef84673f 100644 --- a/napi/index.d.ts +++ b/napi/index.d.ts @@ -603,11 +603,9 @@ export interface ConnectionOptions { */ proxy?: ProxyInput /** - * SQL request deadline and Volume storage idle timeout, in milliseconds. - * Storage idle time bounds reads, upload progress and the PUT response wait; - * a redirected stream PUT resend has no idle bound. - * Omitted: SQL uses the kernel default; storage uses 15 minutes. - * Zero disables storage inactivity and keeps the SQL default. + * Timeout in milliseconds. SQL requests: total time for one request (kernel + * default when omitted or 0). Volume file transfers: time allowed without + * progress (15 minutes when omitted, no limit when 0). */ socketTimeoutMs?: number } @@ -874,7 +872,10 @@ export declare class AsyncStatement { */ export declare class AsyncResultHandle { get isVolumeOperation(): boolean - /** Completes marked file transfers and retains the instruction rows. */ + /** + * Runs the file transfer for a Volume PUT, GET or REMOVE result. Call before + * fetching; the rows stay readable afterwards. + */ completeVolumeOperation(allowedPaths: Array, removeNotFoundIsSuccess: boolean): Promise /** * Server-issued statement id. Cached at construction; readable @@ -1171,7 +1172,10 @@ export declare class Connection { */ export declare class Statement { get isVolumeOperation(): boolean - /** Completes marked file transfers and retains the instruction rows. */ + /** + * Runs the file transfer for a Volume PUT, GET or REMOVE result. Call before + * fetching; the rows stay readable afterwards. + */ completeVolumeOperation(allowedPaths: Array, removeNotFoundIsSuccess: boolean): Promise /** * Server-issued statement id. Cached at construction; readable diff --git a/napi/src/async_statement.rs b/napi/src/async_statement.rs index 669c6991..b874708c 100644 --- a/napi/src/async_statement.rs +++ b/napi/src/async_statement.rs @@ -410,7 +410,8 @@ impl AsyncStatement { .map_err(napi_err_from_kernel); // Release what holds the session, so JS references to closed // handles don't keep it (and the host's telemetry client) alive. - // Queue busy slots so close need not wait for an in-flight operation. + // A slot in use is cleared in the background, so close() does not wait + // for the running call. canceller .lock() .unwrap_or_else(PoisonError::into_inner) @@ -492,7 +493,8 @@ impl AsyncResultHandle { self.is_volume_operation } - /// Complete a server-marked file transfer while retaining its instruction rows. + /// Runs the file transfer for a Volume PUT, GET or REMOVE result. Call before + /// fetching; the rows stay readable afterwards. #[napi] pub async fn complete_volume_operation( &self, diff --git a/napi/src/database.rs b/napi/src/database.rs index 45d93613..ee5b68b2 100644 --- a/napi/src/database.rs +++ b/napi/src/database.rs @@ -453,11 +453,9 @@ pub struct ConnectionOptions { /// server) can now route a single connection through a proxy /// programmatically. pub proxy: Option, - /// SQL request deadline and Volume storage idle timeout, in milliseconds. - /// Storage idle time bounds reads, upload progress and the PUT response wait; - /// a redirected stream PUT resend has no idle bound. - /// Omitted: SQL uses the kernel default; storage uses 15 minutes. - /// Zero disables storage inactivity and keeps the SQL default. + /// Timeout in milliseconds. SQL requests: total time for one request (kernel + /// default when omitted or 0). Volume file transfers: time allowed without + /// progress (15 minutes when omitted, no limit when 0). pub socket_timeout_ms: Option, } diff --git a/napi/src/statement.rs b/napi/src/statement.rs index 0db77527..0c314025 100644 --- a/napi/src/statement.rs +++ b/napi/src/statement.rs @@ -202,7 +202,8 @@ impl Statement { self.is_volume_operation } - /// Complete a server-marked file transfer while retaining its instruction rows. + /// Runs the file transfer for a Volume PUT, GET or REMOVE result. Call before + /// fetching; the rows stay readable afterwards. #[napi] pub async fn complete_volume_operation( &self, diff --git a/pyo3/src/session.rs b/pyo3/src/session.rs index 51331b4d..d94c53f9 100644 --- a/pyo3/src/session.rs +++ b/pyo3/src/session.rs @@ -323,9 +323,9 @@ impl Session { /// 30-second connection timeout also applies, so connection establishment /// is bounded by the shorter limit. Unset or `0` keeps the kernel default /// (120 seconds). - /// For Volume transfers, a positive value bounds connection establishment, - /// GET/REMOVE header and body reads, PUT upload inactivity and the PUT - /// response-header wait. Redirected stream PUT resends have no idle bound. + /// For Volume file transfers a positive value is an idle limit instead: + /// a transfer fails after that long without progress. + /// Unset or `0` sets no Volume idle limit. /// /// `max_connections` sets the maximum idle connections retained per host. /// Unset keeps the kernel default (100); zero is rejected. diff --git a/src/c_abi/error.rs b/src/c_abi/error.rs index 10248b7e..a6234f0b 100644 --- a/src/c_abi/error.rs +++ b/src/c_abi/error.rs @@ -139,7 +139,8 @@ pub extern "C" fn kernel_get_last_error_local_os_error() -> i32 { LAST_ERROR.with(|last| last.borrow().local_os_error) } -/// Borrowed structured error identifier, or null. Valid until the next error-clearing call. +/// The error's string code, such as VOLUME_PATH_NOT_ALLOWED, or null. +/// Valid until the next call that clears the error. #[no_mangle] pub extern "C" fn kernel_get_last_error_code() -> *const c_char { LAST_ERROR.with(|last| { diff --git a/src/c_abi/result.rs b/src/c_abi/result.rs index 4f03b75e..a481442c 100644 --- a/src/c_abi/result.rs +++ b/src/c_abi/result.rs @@ -654,8 +654,8 @@ pub unsafe extern "C" fn kernel_result_stream_canceller_free( }) } -/// Read the Volume marker captured when this stream was created. -/// Success does not establish whether the executed owner is valid. +/// Same flag, read from the stream. Still succeeds after the executed statement +/// is closed. /// # Safety /// `stream` must be live and `out` must be writable. #[no_mangle] @@ -673,8 +673,12 @@ pub unsafe extern "C" fn kernel_result_stream_is_volume_operation( }) } -/// Complete a marked instruction while preserving its result rows. -/// `allowed_paths_json` is a JSON array of strings. This API supplies no input bytes. +/// Runs the file transfer for a Volume PUT, GET or REMOVE result. Call before +/// fetching; the rows stay readable afterwards. +/// `allowed_paths_json`: JSON array of local directories the transfer may use. +/// `remove_not_found_is_success`: report success when the remote file is missing. +/// Returns NeedsInputStream for a stream upload, which this API cannot perform. +/// `kernel_result_stream_canceller_cancel` interrupts it from another thread. /// # Safety /// `stream` must be live with exclusive fetch access, `allowed_paths_json` must /// be NUL-terminated UTF-8, and `out_status` must be writable. diff --git a/src/c_abi/session.rs b/src/c_abi/session.rs index b99c0e8c..1ecbd185 100644 --- a/src/c_abi/session.rs +++ b/src/c_abi/session.rs @@ -631,7 +631,7 @@ pub unsafe extern "C" fn kernel_session_config_set_sea_response_compression_enab /// Configure the total timeout for one HTTP request, from connection start /// through response-body completion. A separate 30-second connection timeout /// also applies, so connection establishment is bounded by the shorter limit. -/// Volume storage inactivity is configured by `kernel_session_config_set_storage_read_timeout`. +/// Does not apply to Volume file transfers; see the storage read timeout. /// `request_timeout_ms == 0` clears an earlier override and keeps the kernel /// default (120 seconds); a positive value overrides it. /// @@ -649,9 +649,8 @@ pub unsafe extern "C" fn kernel_session_config_set_request_timeout( }) } -/// Configure the Volume storage idle timeout; zero disables it. -/// Bounds reads, upload progress and PUT response waits. Redirected stream PUT -/// resends have no idle bound. +/// Idle limit for Volume file transfers: a transfer fails after this long +/// without progress. Also caps connection setup. Zero sets no limit. /// /// # Safety /// `config` must be a live config handle. diff --git a/src/c_abi/statement.rs b/src/c_abi/statement.rs index 84ab0106..3a5df251 100644 --- a/src/c_abi/statement.rs +++ b/src/c_abi/statement.rs @@ -1239,7 +1239,7 @@ unsafe fn with_statement( }) } -/// Read the server-authorized Volume marker before taking a result stream. +/// Whether the statement is a Volume PUT, GET or REMOVE. /// # Safety /// `exec` must be live and `out` must be writable; no fetch may be in flight. #[no_mangle] diff --git a/src/config.rs b/src/config.rs index 1a33dfec..e385e3bf 100644 --- a/src/config.rs +++ b/src/config.rs @@ -755,11 +755,11 @@ pub struct HttpConfig { /// Total timeout for one HTTP request, from connection start through /// response-body completion. A separate 30-second connection timeout also /// applies, so connection establishment is bounded by the shorter limit. - /// Does not bound Volume storage requests; use `storage_read_timeout` for inactivity. + /// Does not apply to Volume file transfers; see the storage read timeout. pub request_timeout: Duration, - /// Volume idle limit for reads, upload progress and PUT response-header waits. - /// Also caps connection setup; redirected stream PUT resends have no idle bound. + /// Idle limit for Volume file transfers: a transfer fails after this long + /// without progress. Also caps connection setup. None sets no limit. pub storage_read_timeout: Option, /// Maximum total time across retries for a single logical RPC. diff --git a/src/kernel_error.rs b/src/kernel_error.rs index ffcb51f3..e59e397d 100644 --- a/src/kernel_error.rs +++ b/src/kernel_error.rs @@ -41,8 +41,12 @@ //! Aborted, Unimplemented, …) lands in a follow-on PR. External //! `match` arms get a forced `_ =>` fallback — they keep compiling //! when the enum grows. -//! - `Error` supports struct patterns with `..`; constructors and setters avoid -//! coupling callers to its full field list. +//! - `Error` **is not** `#[non_exhaustive]`: wrappers want to +//! pattern-match (`let Error { code, message, sql_state, .. }`) for +//! logging and host-language exception mapping. New fields go +//! through `Error::new(...).with_*(...)`, so adding a field is +//! non-breaking without the marker. Keeping the marker would block +//! useful pattern-matches for no real benefit. #![allow(dead_code)] @@ -165,6 +169,9 @@ impl ErrorCode { /// chain `with_*` setters. **Pattern-matching is supported** — /// wrappers writing a comprehensive logger or host-language exception /// adapter can do `let Error { code, message, sql_state, .. } = err;`. +/// New fields land through additive setters, so the type does not +/// need `#[non_exhaustive]` (and the marker would block the +/// pattern-matching wrappers actually want). #[derive(Debug, Clone)] pub struct Error { pub code: ErrorCode, @@ -246,7 +253,7 @@ pub struct Error { pub local_error: Option>, } -/// Local filesystem error details retained across language boundaries. +/// The OS error behind a failed local file operation. #[non_exhaustive] #[derive(Debug, Clone)] pub struct LocalFileError { @@ -462,7 +469,6 @@ impl Error { self } - /// Attach the original local filesystem error for binding-specific mapping. pub fn with_local_error(mut self, local_error: LocalFileError) -> Self { self.local_error = Some(Box::new(local_error)); self diff --git a/src/result_stream.rs b/src/result_stream.rs index 6f9b03b9..97131052 100644 --- a/src/result_stream.rs +++ b/src/result_stream.rs @@ -467,7 +467,7 @@ pub struct ResultStream { /// until the next call to `next_batch` replaces it. current: Option, - /// Buffered outcomes retained for subsequent reads after inspection. + /// Batches and read errors already pulled from the reader but not yet returned to the caller. prefetched: Prefetched, /// Row cursor inside [`current`](Self::current). Reset to `0` @@ -647,16 +647,19 @@ impl ResultStream { } } - /// Whether this execution has server-authorized Volume completion. + /// True when the server marked this result as a Volume PUT, GET or REMOVE. pub fn is_volume_operation(&self) -> bool { self.volume.is_some() } - /// Complete a server-marked Volume operation while retaining its instruction rows. + /// Runs the file transfer for a Volume PUT, GET or REMOVE result. /// - /// Ordinary results and read-only attachments have no transfer authority. - /// `NeedsInputStream` requests owned bytes for the server's stream sentinel; - /// supplying an empty buffer is a valid upload. + /// Call before reading rows; the rows stay readable afterwards. The outcome is + /// cached, so a repeat call does not transfer again. A GET downloads to a + /// temporary file and then copies it over the destination, so a failed + /// download leaves an existing file unchanged. + /// Results from [`Session::attach_async_statement`](crate::Session::attach_async_statement) + /// cannot run transfers and return `NotVolume`. pub async fn complete_volume_operation( &mut self, options: &crate::volume::VolumeOptions, @@ -684,7 +687,7 @@ impl ResultStream { } self.prefetched.pop_front(); }; - // Later batches cannot authorize a partial transfer of a multi-row result. + // Read to the end before transferring: a result with more than one row is rejected. while !self.exhausted { match self .reader @@ -801,8 +804,8 @@ impl ResultStream { /// performed on this path, so calling from a tokio runtime /// (napi-rs, PyO3 async) is safe. pub async fn next_batch(&mut self) -> Result> { - // Replay inspected batches first so DML counts and Volume validation - // do not consume callers' result rows. + // Return buffered batches first, so rows read ahead by a peek or by Volume + // completion still reach the caller. if let Some(batch) = self.prefetched.pop_front() { self.set_current_batch(batch.map_err(|error| *error)?); return Ok(self.current.as_ref()); @@ -874,11 +877,8 @@ impl ResultStream { } } - /// Non-consuming peek at the next buffered batch. - /// - /// Pulls a batch or error when none is current or buffered and the reader is not - /// exhausted. A subsequent [`next_batch`](Self::next_batch) still returns - /// the buffered outcome. + /// Before the first next_batch, returns the first batch without consuming it. + /// The following next_batch returns the same batch or error. pub(crate) async fn peek_first_batch(&mut self) -> Result> { if self.prefetched.is_empty() && self.current.is_none() && !self.exhausted { let reader = self @@ -1003,7 +1003,7 @@ impl ResultStream { /// runtime at all. Errors are surfaced once; subsequent calls /// after an `Err` keep returning `None`. pub fn into_owned_batches(mut self) -> OwnedBatchIter { - // Inspected batches were pulled from the reader; yield them first to preserve row order. + // Buffered batches were read first, so yield them first to keep row order. let prefetched = std::mem::take(&mut self.prefetched) .into_iter() .map(|outcome| outcome.map(|ResultBatch::Arrow(rb)| rb)) @@ -1042,7 +1042,6 @@ impl Drop for ResultStream { /// reader's natural end-of-stream the same way. pub struct OwnedBatchIter { reader: Box, - /// Inspected batches must precede the reader's remaining rows. prefetched: Prefetched, telemetry: Option, done: bool, diff --git a/src/volume.rs b/src/volume.rs index 0759af1a..4887c664 100644 --- a/src/volume.rs +++ b/src/volume.rs @@ -12,7 +12,11 @@ // See the License for the specific language governing permissions and // limitations under the License. -//! Explicit completion of server-authorized Volume file transfers. +//! File transfers for Volume PUT, GET and REMOVE statements. +//! +//! The server answers these statements with one row holding a presigned +//! storage URL, request headers and a local path. This module makes that +//! storage request when the caller asks. use crate::client::retry::{calculate_backoff, RequestType, RetryConfig, RetryStrategy}; use crate::kernel_error::{Error, LocalFileError, Result}; @@ -28,30 +32,21 @@ use tokio_util::bytes::Bytes; use tokio_util::io::ReaderStream; use tokio_util::sync::CancellationToken; -/// Local file authorization and driver-specific storage response policy. -/// -/// Requested and resolved paths must be within allowed roots. Symlinks between -/// authorized roots work; `..` collapses before symlink resolution. Path components -/// must remain stable during file access. -/// GET downloads into a temporary file, beside the destination when its directory -/// allows it and in the system temporary directory otherwise, then copies it into -/// the destination in place. Download failure or cancellation before publication -/// preserves existing bytes; a failure during the copy can leave the destination -/// partially written. Cancellation after publication starts does not interrupt it. -/// GET decodes gzip Content-Encoding before writing the downloaded bytes. -/// The storage idle timeout bounds GET reads, PUT upload progress and the wait for -/// the PUT response. A stream PUT that storage redirects is sent again with its -/// full body, and that resend has no idle bound. A cancelled PUT or REMOVE may -/// already have changed storage. +/// Caller settings for a Volume file transfer. #[non_exhaustive] #[derive(Debug, Clone, Default)] pub struct VolumeOptions { + /// Local directories a PUT may read from and a GET may write to. Both the + /// path named in the statement and the file it resolves to through + /// symlinks must be inside one of them. Empty allows no local file access. + /// The check runs before the file is opened, so nothing else may swap + /// files or links in these directories during a transfer. pub allowed_paths: Vec, + /// Report success when REMOVE targets a file that does not exist. pub remove_not_found_is_success: bool, } impl VolumeOptions { - /// Configure local roots and the binding's missing-object REMOVE policy. pub fn new(allowed_paths: Vec, remove_not_found_is_success: bool) -> Self { Self { allowed_paths, @@ -60,12 +55,15 @@ impl VolumeOptions { } } -/// Result of explicitly completing a server-marked Volume instruction. +/// Outcome of `ResultStream::complete_volume_operation`. #[derive(Debug, Clone, Copy, PartialEq, Eq)] #[repr(C)] pub enum VolumeCompletion { + /// The result is not a Volume statement; nothing was done. NotVolume = 0, + /// The PUT uploads caller-supplied bytes; call again with `input_bytes`. NeedsInputStream = 1, + /// The transfer finished. Completed = 2, } @@ -109,7 +107,7 @@ impl VolumeState { match self .completion .get_or_try_init(|| async { - // An abandoned initializer must not replay an already-dispatched transfer. + // If an earlier call was dropped mid-transfer, do not run the transfer again. if self.started.swap(true, Ordering::AcqRel) || self.cancellation.is_cancelled() { return Ok(Err(cancelled())); } @@ -209,12 +207,13 @@ impl VolumeState { Ok(completion) => return Ok(completion), Err(error) => error, }; + // The retry clock starts at the first failure, so a long transfer does not + // use up the retry budget. let started = retry_started.get_or_insert_with(std::time::Instant::now); if !error.retryable || attempt >= self.retry.max_retries { return Err(error.message(format!("after {} attempts", attempt + 1))); } let wait = calculate_backoff(&self.retry, attempt, retry_after.as_deref()); - // Retry budgets govern recovery, not the duration of a healthy transfer. if started.elapsed().saturating_add(wait) >= self.retry.overall_timeout { return Err(error.message(format!("after {} attempts", attempt + 1))); } @@ -244,7 +243,7 @@ impl VolumeState { std::fs::File::open(path).map_err(|e| local_error(e, &local_file))?; let metadata = file.metadata().map_err(|e| local_error(e, &local_file))?; if metadata.is_dir() { - // Reading the opened directory retains the platform's filesystem cause. + // A directory opens without error on Unix; reading it produces the OS error to report. let error = std::io::Read::read(&mut file, &mut [0]) .err() .unwrap_or_else(|| std::io::ErrorKind::IsADirectory.into()); @@ -321,7 +320,8 @@ impl VolumeState { ) .await?; if let Some(bytes) = input.filter(|_| matches!(response.status().as_u16(), 307 | 308)) { - // Reusable bytes let reqwest apply its redirect and credential policy. + // reqwest cannot replay a streamed body on a redirect. Resend from memory + // so it can follow; this resend has no idle timeout. response = client .put(&instruction.url) .headers(instruction.headers.clone()) diff --git a/tests/v0_volume_wiremock.rs b/tests/v0_volume_wiremock.rs index 1965edcf..4cd5594b 100644 --- a/tests/v0_volume_wiremock.rs +++ b/tests/v0_volume_wiremock.rs @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -//! Volume completion authority and lifecycle through public execution handles. +//! Wiremock tests for Volume file transfers through Statement and ResultStream. use arrow_array::{RecordBatch, StringArray}; use arrow_ipc::writer::StreamWriter; From b1dedde5c4e2774c507e37edc64f85b3ddb04df5 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Fri, 20 Nov 2026 21:21:11 +0000 Subject: [PATCH 52/63] fixup! fix(volume): start retries on failure and clear ADBC staging Signed-off-by: Aakash Saravanan --- include/databricks_kernel.h | 9 ++++++--- pyo3/src/session.rs | 3 ++- src/config.rs | 1 + src/kernel_error.rs | 13 ++++--------- src/result_stream.rs | 3 +++ 5 files changed, 16 insertions(+), 13 deletions(-) diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h index 4cf94ff9..f1d27a86 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -984,11 +984,13 @@ typedef enum KernelVolumeCompletion { KernelVolumeCompletion_Completed = 2 } KernelVolumeCompletion; -/* Whether the statement is a Volume PUT, GET or REMOVE. */ +/* Whether the statement is a Volume PUT, GET or REMOVE. + * out is written only on success. */ KernelStatusCode kernel_executed_statement_is_volume_operation( const kernel_executed_statement_t* exec, bool* out); /* Same flag, read from the stream. Still succeeds after the executed statement - * is closed. */ + * is closed. + * out is written only on success. */ KernelStatusCode kernel_result_stream_is_volume_operation( const kernel_result_stream_t* stream, bool* out); /* Runs the file transfer for a Volume PUT, GET or REMOVE result. Call before @@ -996,7 +998,8 @@ KernelStatusCode kernel_result_stream_is_volume_operation( * allowed_paths_json: JSON array of local directories the transfer may use. * remove_not_found_is_success: report success when the remote file is missing. * Returns NeedsInputStream for a stream upload, which this API cannot perform. - * kernel_result_stream_canceller_cancel interrupts it from another thread. */ + * kernel_result_stream_canceller_cancel interrupts it from another thread. + * out_status is written only on success. */ KernelStatusCode kernel_result_stream_complete_volume_operation( kernel_result_stream_t* stream, const char* allowed_paths_json, bool remove_not_found_is_success, KernelVolumeCompletion* out_status); diff --git a/pyo3/src/session.rs b/pyo3/src/session.rs index d94c53f9..4746dffc 100644 --- a/pyo3/src/session.rs +++ b/pyo3/src/session.rs @@ -324,7 +324,8 @@ impl Session { /// is bounded by the shorter limit. Unset or `0` keeps the kernel default /// (120 seconds). /// For Volume file transfers a positive value is an idle limit instead: - /// a transfer fails after that long without progress. + /// a transfer fails after that long without progress, except a stream PUT + /// that storage redirects, which is resent without the limit. /// Unset or `0` sets no Volume idle limit. /// /// `max_connections` sets the maximum idle connections retained per host. diff --git a/src/config.rs b/src/config.rs index e385e3bf..135b52c3 100644 --- a/src/config.rs +++ b/src/config.rs @@ -760,6 +760,7 @@ pub struct HttpConfig { /// Idle limit for Volume file transfers: a transfer fails after this long /// without progress. Also caps connection setup. None sets no limit. + /// Exception: a stream PUT that storage redirects is resent without this limit. pub storage_read_timeout: Option, /// Maximum total time across retries for a single logical RPC. diff --git a/src/kernel_error.rs b/src/kernel_error.rs index e59e397d..a5126853 100644 --- a/src/kernel_error.rs +++ b/src/kernel_error.rs @@ -41,12 +41,10 @@ //! Aborted, Unimplemented, …) lands in a follow-on PR. External //! `match` arms get a forced `_ =>` fallback — they keep compiling //! when the enum grows. -//! - `Error` **is not** `#[non_exhaustive]`: wrappers want to -//! pattern-match (`let Error { code, message, sql_state, .. }`) for -//! logging and host-language exception mapping. New fields go -//! through `Error::new(...).with_*(...)`, so adding a field is -//! non-breaking without the marker. Keeping the marker would block -//! useful pattern-matches for no real benefit. +//! - `Error` **is not** `#[non_exhaustive]`, so wrappers can pattern-match +//! (`let Error { code, message, sql_state, .. }`). Build it with +//! `Error::new(...).with_*(...)`: a struct literal stops compiling when a +//! field is added. #![allow(dead_code)] @@ -169,9 +167,6 @@ impl ErrorCode { /// chain `with_*` setters. **Pattern-matching is supported** — /// wrappers writing a comprehensive logger or host-language exception /// adapter can do `let Error { code, message, sql_state, .. } = err;`. -/// New fields land through additive setters, so the type does not -/// need `#[non_exhaustive]` (and the marker would block the -/// pattern-matching wrappers actually want). #[derive(Debug, Clone)] pub struct Error { pub code: ErrorCode, diff --git a/src/result_stream.rs b/src/result_stream.rs index 97131052..576f1db0 100644 --- a/src/result_stream.rs +++ b/src/result_stream.rs @@ -658,6 +658,9 @@ impl ResultStream { /// cached, so a repeat call does not transfer again. A GET downloads to a /// temporary file and then copies it over the destination, so a failed /// download leaves an existing file unchanged. + /// A failure during that copy can leave the destination partly written. + /// Cancelling does not undo work already done: a PUT or REMOVE may already + /// have reached storage, and a copy that has started runs to the end. /// Results from [`Session::attach_async_statement`](crate::Session::attach_async_statement) /// cannot run transfers and return `NotVolume`. pub async fn complete_volume_operation( From 97a8f26156f2694abd65da4e20a883c9abfe3114 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Sat, 21 Nov 2026 01:03:40 +0000 Subject: [PATCH 53/63] fixup! fix(volume): start retries on failure and clear ADBC staging Signed-off-by: Aakash Saravanan --- CONNECTION_PARAMETERS.md | 1 + Cargo.toml | 4 +++- NEXT_CHANGELOG.md | 8 ++++---- README.md | 5 +++-- napi/NEXT_CHANGELOG.md | 5 +++-- napi/README.md | 10 +++++----- napi/index.d.ts | 12 ++++++++--- napi/src/async_statement.rs | 1 - napi/src/database.rs | 40 ++++++++++--------------------------- pyo3/NEXT_CHANGELOG.md | 5 +++-- src/c_abi/error.rs | 2 +- src/client/http.rs | 1 + src/session.rs | 2 +- src/statement/mutable.rs | 22 +++++++++++++------- src/volume.rs | 8 +++++++- tests/v0_volume_wiremock.rs | 9 ++------- 16 files changed, 69 insertions(+), 66 deletions(-) diff --git a/CONNECTION_PARAMETERS.md b/CONNECTION_PARAMETERS.md index 2a11227d..b64ac488 100644 --- a/CONNECTION_PARAMETERS.md +++ b/CONNECTION_PARAMETERS.md @@ -128,6 +128,7 @@ until implemented) and `External` (a caller-supplied `TokenProvider`). | Field | Description | Default | |-------|-------------|---------| | `request_timeout` | Per-request timeout (connect + body). | `120s` | +| `storage_read_timeout` | Idle limit for Volume file transfers: a transfer fails after this long without progress. | `None` (no limit) | | `overall_timeout` | Maximum total time across retries for one logical RPC. | `900s` | | `pool_max_idle_per_host` | Connection-pool size (max idle warm sockets per host). Raise for bursty concurrent workloads. | `100` | | `retry_min_wait` | Minimum backoff between retries; also the floor for a server `Retry-After` and the base of exponential backoff (`min_wait × 2^attempt`). | `1s` | diff --git a/Cargo.toml b/Cargo.toml index 67ae5bd3..a20ef673 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -106,9 +106,11 @@ moka = { version = "0.12.16", features = ["future"] } # Async utilities futures = "0.3" tokio-util = { version = "0.7", features = ["io"] } -tempfile = "3" async-trait = "0.1" +# Temporary file that holds a Volume GET download before it is copied into place +tempfile = "3" + # Error handling thiserror = "2" diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index d59874d9..867d604c 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -11,10 +11,10 @@ changes go in their respective binding's NEXT_CHANGELOG. ### Added -- Explicit, execution-scoped completion of server-marked Volume PUT/GET/REMOVE - instructions, with allowed-root checks, resumable owned-byte PUT input, in-place GET - publication and cached completion outcomes. Resolved symlink targets must remain - within the configured roots. +- Volume `PUT`, `GET` and `REMOVE`: `ResultStream::complete_volume_operation` + runs the file transfer. Local paths, and the files they resolve to through + symlinks, must be inside the caller's allowed directories. A `PUT` can also + upload bytes the caller supplies. ### Changed diff --git a/README.md b/README.md index 29676784..c7b02315 100644 --- a/README.md +++ b/README.md @@ -68,8 +68,9 @@ and security vulnerabilities should be reported according to ## Volume file operations -Call `ResultStream::complete_volume_operation` with `VolumeOptions` before reading -server-marked PUT, GET and REMOVE rows; omit completion for raw results. +For a Volume `PUT`, `GET` or `REMOVE`, call +`ResultStream::complete_volume_operation` before reading rows. It runs the +file transfer; without it the result is only the server's instruction row. See [`ResultStream::complete_volume_operation`](https://docs.rs/databricks-sql-kernel/latest/databricks_sql_kernel/struct.ResultStream.html#method.complete_volume_operation) for transfer behavior. diff --git a/napi/NEXT_CHANGELOG.md b/napi/NEXT_CHANGELOG.md index 38d38821..77ba04ed 100644 --- a/napi/NEXT_CHANGELOG.md +++ b/napi/NEXT_CHANGELOG.md @@ -14,8 +14,9 @@ layout, or npm publishing. Pure-kernel changes go in the root ### Added -- Explicit Volume completion and marker access on synchronous and asynchronous - result handles, with structured local filesystem error details. +- `Statement` and `AsyncResultHandle` gain `isVolumeOperation` and + `completeVolumeOperation` for Volume `PUT`, `GET` and `REMOVE`. Local file + errors carry `localOsError`, `localErrorKind` and `localPath`. ### Changed diff --git a/napi/README.md b/napi/README.md index b71d3df3..bee4aa19 100644 --- a/napi/README.md +++ b/napi/README.md @@ -8,11 +8,11 @@ The binding itself lives under `src/`; its public TypeScript surface is declared in `index.d.ts`. `Statement` and `AsyncResultHandle` expose `isVolumeOperation` and -`completeVolumeOperation(allowedPaths, removeNotFoundIsSuccess)`. Completion -returns `not_volume`, `needs_input_stream` or `completed` and preserves the -instruction rows. The caller opts into transfer by supplying allowed local -roots; both lexical paths and resolved symlink targets must stay inside them. -The Node binding does not supply stream-upload bytes. +`completeVolumeOperation(allowedPaths, removeNotFoundIsSuccess)`, which runs +the file transfer for a Volume `PUT`, `GET` or `REMOVE`. It returns +`not_volume`, `needs_input_stream` or `completed`, and the result rows stay +readable. Local paths, and the files they resolve to through symlinks, must be +inside `allowedPaths`. The Node binding cannot upload from a stream. --- diff --git a/napi/index.d.ts b/napi/index.d.ts index ef84673f..877a40c3 100644 --- a/napi/index.d.ts +++ b/napi/index.d.ts @@ -603,9 +603,15 @@ export interface ConnectionOptions { */ proxy?: ProxyInput /** - * Timeout in milliseconds. SQL requests: total time for one request (kernel - * default when omitted or 0). Volume file transfers: time allowed without - * progress (15 minutes when omitted, no limit when 0). + * Per-connection socket read timeout, in milliseconds. Caps how + * long a single HTTP round-trip may block waiting on the server + * before the request errors out. Maps onto the kernel + * [`HttpConfig::request_timeout`] (the internal reqwest + * `Client::timeout`). + * + * Omitted ⇒ kernel default (120 000 ms / 120 s). Napi-rs + * serialises `u32` as JS `number`; the largest representable value + * (~49.7 days) far exceeds any sensible socket timeout. */ socketTimeoutMs?: number } diff --git a/napi/src/async_statement.rs b/napi/src/async_statement.rs index b874708c..5c754215 100644 --- a/napi/src/async_statement.rs +++ b/napi/src/async_statement.rs @@ -366,7 +366,6 @@ impl AsyncStatement { let Some(canceller) = canceller else { return Err(closed_err("AsyncStatement")); }; - canceller.cancel_volume_operation(); guarded(async move { canceller.cancel().await.map_err(napi_err_from_kernel) }).await } diff --git a/napi/src/database.rs b/napi/src/database.rs index ee5b68b2..4a8fbe3f 100644 --- a/napi/src/database.rs +++ b/napi/src/database.rs @@ -453,9 +453,15 @@ pub struct ConnectionOptions { /// server) can now route a single connection through a proxy /// programmatically. pub proxy: Option, - /// Timeout in milliseconds. SQL requests: total time for one request (kernel - /// default when omitted or 0). Volume file transfers: time allowed without - /// progress (15 minutes when omitted, no limit when 0). + /// Per-connection socket read timeout, in milliseconds. Caps how + /// long a single HTTP round-trip may block waiting on the server + /// before the request errors out. Maps onto the kernel + /// [`HttpConfig::request_timeout`] (the internal reqwest + /// `Client::timeout`). + /// + /// Omitted ⇒ kernel default (120 000 ms / 120 s). Napi-rs + /// serialises `u32` as JS `number`; the largest representable value + /// (~49.7 days) far exceeds any sensible socket timeout. pub socket_timeout_ms: Option, } @@ -647,17 +653,12 @@ fn build_http_config(options: &mut ConnectionOptions) -> HttpConfig { if let Some(s) = options.retry_overall_timeout_secs { http.overall_timeout = std::time::Duration::from_secs(u64::from(s)); } - // Per-connection request deadline. Maps onto the kernel's + // Per-connection socket read timeout. Maps onto the kernel's // `request_timeout` (the reqwest `Client::timeout`). Omitted ⇒ kernel // default (120 s). - if let Some(ms) = options.socket_timeout_ms.filter(|ms| *ms != 0) { + if let Some(ms) = options.socket_timeout_ms { http.request_timeout = std::time::Duration::from_millis(u64::from(ms)); } - http.storage_read_timeout = options - .socket_timeout_ms - .or(Some(15 * 60 * 1000)) - .filter(|ms| *ms != 0) - .map(|ms| std::time::Duration::from_millis(u64::from(ms))); http } @@ -1583,33 +1584,14 @@ mod tests { assert!(build_http_config(&mut enabled).sea_response_compression_enabled); } - #[test] - fn http_socket_timeout_default_and_zero_preserve_request_timeout() { - for (socket_timeout_ms, storage_read_timeout) in [ - (None, Some(std::time::Duration::from_secs(15 * 60))), - (Some(0), None), - ] { - let mut options = base(); - options.socket_timeout_ms = socket_timeout_ms; - let http = build_http_config(&mut options); - assert_eq!(http.storage_read_timeout, storage_read_timeout); - assert_eq!(http.request_timeout, std::time::Duration::from_secs(120)); - } - } - #[test] fn http_retry_knobs_map_onto_http_config() { let mut o = base(); - o.socket_timeout_ms = Some(4_500); o.retry_min_wait_secs = Some(2); o.retry_max_wait_secs = Some(45); o.retry_max_attempts = Some(4); // total attempts → 3 retries o.retry_overall_timeout_secs = Some(120); let http = build_http_config(&mut o); - assert_eq!( - http.storage_read_timeout, - Some(std::time::Duration::from_millis(4_500)) - ); assert_eq!(http.retry_min_wait, std::time::Duration::from_secs(2)); assert_eq!(http.retry_max_wait, std::time::Duration::from_secs(45)); // total attempts (4) → retries after the first (3): the off-by-one. diff --git a/pyo3/NEXT_CHANGELOG.md b/pyo3/NEXT_CHANGELOG.md index f64d405b..95e170cb 100644 --- a/pyo3/NEXT_CHANGELOG.md +++ b/pyo3/NEXT_CHANGELOG.md @@ -14,8 +14,9 @@ changes go in the root `NEXT_CHANGELOG.md`. ### Added - `ExecutedStatement` and `ResultStream` expose `is_volume_operation` and - `complete_volume_operation` for explicit Volume transfers, including owned-byte - stream uploads. Filesystem errors retain their OS code and requested path. + `complete_volume_operation` for Volume `PUT`, `GET` and `REMOVE`, including + uploads from `input_bytes`. Local file errors carry `local_os_error` and + `local_path`. ### Changed diff --git a/src/c_abi/error.rs b/src/c_abi/error.rs index a6234f0b..d8ff9ffa 100644 --- a/src/c_abi/error.rs +++ b/src/c_abi/error.rs @@ -282,7 +282,7 @@ mod tests { } #[test] - fn store_error_folds_error_code_slug_into_message() { + fn store_error_exposes_error_code_and_local_file_details() { let mut error = Error::sql_error() .message("statement gone") .with_error_code("STATEMENT_NOT_FOUND"); diff --git a/src/client/http.rs b/src/client/http.rs index 0f301a30..33c9b502 100644 --- a/src/client/http.rs +++ b/src/client/http.rs @@ -413,6 +413,7 @@ impl StorageClient { } }), None, + // No Referer on redirects: it would carry the presigned URL. false, ) }) diff --git a/src/session.rs b/src/session.rs index 8798c410..8824c02f 100644 --- a/src/session.rs +++ b/src/session.rs @@ -470,7 +470,7 @@ impl Session { &config.connection, &config.auth, config.driver_system_configuration.clone(), - http_client.clone(), + http_client, session_info.session_id.clone(), )); telemetry diff --git a/src/statement/mutable.rs b/src/statement/mutable.rs index bc33f249..aeb246ba 100644 --- a/src/statement/mutable.rs +++ b/src/statement/mutable.rs @@ -245,6 +245,9 @@ pub struct Statement { /// new `execute()` / `submit()` so a canceller never targets a /// stale prior statement. inflight_id: InflightId, + /// Volume transfer state of the current execution, shared with any + /// [`StatementCanceller`]. Replaced at the start of each new execution, so + /// a canceller always reaches the current transfer. volume: Arc>>, } @@ -780,8 +783,8 @@ impl Statement { build_execute_params(&self.spec, wait_timeout_secs) } - /// Clear the shared in-flight-id slot at the very start of a new - /// dispatch, before any `.await`. + /// Clear the shared in-flight-id slot and replace the Volume transfer + /// state at the very start of a new dispatch, before any `.await`. /// /// The slot still holds the *prior* execution's server statement id /// until this runs. A [`StatementCanceller`] retained across a @@ -796,6 +799,10 @@ impl Statement { /// nothing: a canceller firing before the new id is observed is a /// tolerated no-op (`dispatched = false`), never a hit on the stale id. /// + /// The prior execution's Volume transfer is cancelled and a fresh state + /// installed in the same step, so a retained canceller reaches the new + /// execution's transfer, not the previous one. + /// /// Kept out of [`invalidate_prior`] deliberately — that is also called /// by [`Statement::close`], where the slot must survive so a detached /// canceller can still dispatch against the just-closed statement (its @@ -947,12 +954,12 @@ impl Drop for MidExecuteCancelGuard { /// [`Statement`]. Produced by [`Statement::canceller`]. /// /// Holds only the shared session handle and the `Statement`'s shared -/// in-flight-id slot — **not** the `Statement` itself — so a binding -/// can fire a server-side cancel from another thread while `execute()` -/// is blocked. The sync-execute analogue of +/// in-flight-id slot and its Volume transfer state — **not** the `Statement` +/// itself — so a binding can fire a server-side cancel from another thread +/// while `execute()` is blocked. The sync-execute analogue of /// [`AsyncStatementCanceller`](crate::statement::executed_async::AsyncStatementCanceller). /// -/// Cheap to [`Clone`] (two `Arc` bumps). +/// Cheap to [`Clone`] (three `Arc` bumps). #[derive(Clone)] pub struct StatementCanceller { session: Arc, @@ -991,7 +998,8 @@ 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 the Volume state (each behind a `Mutex`), no + /// mutable statement state. pub async fn cancel(&self) -> Result { self.cancel_volume_operation(); let id = self.inflight_id.lock().ok().and_then(|g| g.clone()); diff --git a/src/volume.rs b/src/volume.rs index 4887c664..313a5012 100644 --- a/src/volume.rs +++ b/src/volume.rs @@ -155,7 +155,7 @@ impl VolumeState { .await .map_err(|e| { Error::internal() - .message(format!("Volume publication task failed: {e}")) + .message(format!("Volume download copy task failed: {e}")) })??; } Ok(outcome) @@ -1675,6 +1675,12 @@ mod tests { .unwrap(), VolumeCompletion::Completed ); + assert!(server + .received_requests() + .await + .unwrap() + .iter() + .all(|request| !request.headers.contains_key("referer"))); } #[tokio::test] diff --git a/tests/v0_volume_wiremock.rs b/tests/v0_volume_wiremock.rs index 4cd5594b..5df4280f 100644 --- a/tests/v0_volume_wiremock.rs +++ b/tests/v0_volume_wiremock.rs @@ -202,7 +202,7 @@ async fn storage_transfers_outlive_rpc_deadline() { http.overall_timeout = Duration::from_millis(200); let session = session_with_http( &server, - response_with_batches(&server, true, local.to_str().unwrap(), "GET", &[1]), + response(&server, true, local.to_str().unwrap()), http, ) .await; @@ -497,12 +497,7 @@ async fn reading_before_volume_completion_returns_invalid_state() { let server = MockServer::start().await; let dir = tempfile::tempdir().unwrap(); let local = dir.path().join("download"); - let session = session_with_http( - &server, - response_with_batches(&server, true, local.to_str().unwrap(), "GET", &[1]), - HttpConfig::default(), - ) - .await; + let session = session(&server, response(&server, true, local.to_str().unwrap())).await; let mut statement = session.statement(); statement.spec().sql("GET"); let mut executed = statement.execute().await.unwrap(); From f58a73c926a701d2e5f7a16099aeacbd63f896a1 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Sun, 22 Nov 2026 07:07:38 +0000 Subject: [PATCH 54/63] fixup! fix(volume): start retries on failure and clear ADBC staging Signed-off-by: Aakash Saravanan --- src/volume.rs | 106 ++++++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 89 insertions(+), 17 deletions(-) diff --git a/src/volume.rs b/src/volume.rs index 313a5012..7b9f08ba 100644 --- a/src/volume.rs +++ b/src/volume.rs @@ -437,7 +437,10 @@ async fn storage_send( tokio::pin!(send); let response = if let (true, Some(timeout)) = (upload, timeout) { loop { - let deadline = *progress.borrow_and_update() + timeout; + let last = *progress.borrow_and_update(); + let Some(deadline) = last.checked_add(timeout) else { + break (&mut send).await; + }; tokio::select! { biased; response = &mut send => break response, @@ -578,21 +581,27 @@ fn resolve_existing_parent( } } -fn within_root(path: &Path, root: &Path) -> bool { - #[cfg(windows)] - { - let mut path = path.components(); - root.components().all(|root| { - path.next().is_some_and(|part| { - part.as_os_str().to_string_lossy().to_lowercase() - == root.as_os_str().to_string_lossy().to_lowercase() - }) +/// Whether `path` is `root` or inside it. The drive or share prefix never +/// depends on case. After resolving links, pass `ignore_name_case: false`: +/// a case-sensitive directory can hold two names that differ only by case. +#[cfg(windows)] +fn within_root(path: &Path, root: &Path, ignore_name_case: bool) -> bool { + let lower = |part: Component<'_>| part.as_os_str().to_string_lossy().to_lowercase(); + let mut path = path.components(); + root.components().all(|root| { + path.next().is_some_and(|part| { + if ignore_name_case || matches!(root, Component::Prefix(_)) { + lower(part) == lower(root) + } else { + part == root + } }) - } - #[cfg(not(windows))] - { - path.starts_with(root) - } + }) +} + +#[cfg(not(windows))] +fn within_root(path: &Path, root: &Path, _ignore_name_case: bool) -> bool { + path.starts_with(root) } fn allowed_path(requested: &str, roots: &[PathBuf]) -> Result { @@ -605,7 +614,7 @@ fn allowed_path(requested: &str, roots: &[PathBuf]) -> Result { .filter(|root| !root.as_os_str().is_empty()) .map(|root| normalize(root)) .collect::>>()?; - if !roots.iter().any(|root| within_root(&path, root)) { + if !roots.iter().any(|root| within_root(&path, root, true)) { return Err( invalid("Local file path is outside the configured allowed roots") .with_error_code("VOLUME_PATH_NOT_ALLOWED"), @@ -625,7 +634,7 @@ fn allowed_path(requested: &str, roots: &[PathBuf]) -> Result { continue; } }; - if within_root(&resolved, &root) { + if within_root(&resolved, &root, false) { return Ok(resolved); } } @@ -1313,6 +1322,39 @@ mod tests { } } + #[tokio::test] + async fn upload_accepts_maximum_idle_timeout() { + let server = MockServer::start().await; + Mock::given(method("PUT")) + .and(body_bytes(b"upload")) + .respond_with(ResponseTemplate::new(200)) + .expect(1) + .mount(&server) + .await; + let state = VolumeState::new( + transfer_state(0).retry.clone(), + storage(Some(Duration::MAX)), + Default::default(), + ); + assert_eq!( + state + .complete( + async { + Ok(instruction( + "PUT", + &server.uri(), + Path::new("__input_stream__"), + )) + }, + &VolumeOptions::default(), + Some(b"upload".to_vec()), + ) + .await + .unwrap(), + VolumeCompletion::Completed + ); + } + #[tokio::test] async fn get_progress_and_put_idle_limits() { use tokio::io::AsyncReadExt; @@ -1467,6 +1509,36 @@ mod tests { } } + #[cfg(windows)] + #[test] + fn resolved_names_match_exactly_and_prefix_ignores_case() { + for (path, root, allowed) in [ + (r"\\?\C:\data\safe\x", r"\\?\C:\data\safe", true), + (r"\\?\c:\data\safe\x", r"\\?\C:\data\safe", true), + (r"\\?\C:\data\SAFE\x", r"\\?\C:\data\safe", false), + ( + r"\\?\UNC\server\share\dir\x", + r"\\?\UNC\Server\Share\dir", + true, + ), + ( + r"\\?\UNC\server\share\DIR\x", + r"\\?\UNC\Server\Share\dir", + false, + ), + ] { + assert_eq!( + within_root(Path::new(path), Path::new(root), false), + allowed, + "{path}" + ); + assert!( + within_root(Path::new(path), Path::new(root), true), + "{path}" + ); + } + } + #[test] fn symlinks_require_lexical_authority_and_resolved_target_in_any_allowed_root() { #[cfg(unix)] From 724411ef25a2d06d11099ba1e221e7f37bce57ec Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Sun, 22 Nov 2026 23:49:15 +0000 Subject: [PATCH 55/63] fixup! fix(volume): start retries on failure and clear ADBC staging Signed-off-by: Aakash Saravanan --- CONNECTION_PARAMETERS.md | 2 +- include/databricks_kernel.h | 14 ++- pyo3/src/session.rs | 2 +- src/c_abi/result.rs | 6 +- src/config.rs | 2 +- src/result_stream.rs | 8 +- src/volume.rs | 239 +++++++++++++++++++++++++----------- tests/v0_volume_wiremock.rs | 55 +++++++++ 8 files changed, 239 insertions(+), 89 deletions(-) diff --git a/CONNECTION_PARAMETERS.md b/CONNECTION_PARAMETERS.md index b64ac488..3a8ba972 100644 --- a/CONNECTION_PARAMETERS.md +++ b/CONNECTION_PARAMETERS.md @@ -127,7 +127,7 @@ until implemented) and `External` (a caller-supplied `TokenProvider`). | Field | Description | Default | |-------|-------------|---------| -| `request_timeout` | Per-request timeout (connect + body). | `120s` | +| `request_timeout` | Per-request timeout (connect + body) for SQL requests. Volume file transfers are limited by storage_read_timeout instead. | `120s` | | `storage_read_timeout` | Idle limit for Volume file transfers: a transfer fails after this long without progress. | `None` (no limit) | | `overall_timeout` | Maximum total time across retries for one logical RPC. | `900s` | | `pool_max_idle_per_host` | Connection-pool size (max idle warm sockets per host). Raise for bursty concurrent workloads. | `100` | diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h index f1d27a86..4f78960c 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -225,12 +225,12 @@ typedef struct kernel_statement_canceller_t kernel_statement_canceller_t; /* Detached canceller for a result stream, returned by * kernel_result_stream_canceller_new. Firing it interrupts an in-flight * kernel_result_stream_next_batch so it returns KernelStatusCode_Cancelled - * promptly instead of blocking until the (possibly slow / CloudFetch-link) - * batch fetch finishes. Unlike the statement canceller it holds ONLY a shared - * client-side cancellation token (no server RPC, no borrow of the stream's - * mutable state), so — see its doc — it is safe to obtain and to fire - * concurrently with a next_batch/close on the owning thread. Once fired, the - * stream is permanently aborted (every later next_batch returns Cancelled). */ + * promptly instead of waiting for the batch fetch to finish. It also stops a + * running Volume file transfer. Unlike the statement canceller it makes no + * server RPC and borrows no mutable stream state, so — see its doc — it is + * safe to obtain and fire concurrently with a next_batch/close on the owning + * thread. Once fired, the stream is permanently aborted (every later next_batch + * returns Cancelled). */ typedef struct kernel_result_stream_canceller_t kernel_result_stream_canceller_t; /* ─── Session config ────────────────────────────────────────────────── @@ -995,6 +995,8 @@ KernelStatusCode kernel_result_stream_is_volume_operation( const kernel_result_stream_t* stream, bool* out); /* Runs the file transfer for a Volume PUT, GET or REMOVE result. Call before * fetching; the rows stay readable afterwards. + * The outcome, success or failure, is cached, so a repeat call does not + * transfer again. * allowed_paths_json: JSON array of local directories the transfer may use. * remove_not_found_is_success: report success when the remote file is missing. * Returns NeedsInputStream for a stream upload, which this API cannot perform. diff --git a/pyo3/src/session.rs b/pyo3/src/session.rs index 4746dffc..0ed7a4f7 100644 --- a/pyo3/src/session.rs +++ b/pyo3/src/session.rs @@ -324,7 +324,7 @@ impl Session { /// is bounded by the shorter limit. Unset or `0` keeps the kernel default /// (120 seconds). /// For Volume file transfers a positive value is an idle limit instead: - /// a transfer fails after that long without progress, except a stream PUT + /// a transfer fails after that long without progress, except a PUT /// that storage redirects, which is resent without the limit. /// Unset or `0` sets no Volume idle limit. /// diff --git a/src/c_abi/result.rs b/src/c_abi/result.rs index a481442c..b744c33a 100644 --- a/src/c_abi/result.rs +++ b/src/c_abi/result.rs @@ -120,6 +120,7 @@ enum ResultStreamShape { /// Detached canceller for a result stream. Holds a clone of the stream's /// [`CancellationToken`], so firing it interrupts an in-flight `next_batch`. +/// It also stops a running Volume file transfer. /// /// A `CancellationToken` clone shares the same underlying atomic state, so the /// canceller keeps working after the stream handle is closed — closing the @@ -602,8 +603,9 @@ pub unsafe extern "C" fn kernel_result_stream_canceller_new( /// Fire the cancellation of the result stream this canceller was created for /// (odbc#355-B). Purely client-side (no server RPC): it flips the shared token, /// which an in-flight `kernel_result_stream_next_batch` observes via its -/// `tokio::select!` and unwinds. Idempotent, non-blocking, and safe to call -/// concurrently with `next_batch`/`close` on the stream's owning thread. +/// `tokio::select!` and unwinds. It also stops a running Volume file transfer. +/// Idempotent, non-blocking, and safe to call concurrently with +/// `next_batch`/`close` on the stream's owning thread. /// /// Always returns `Success` for a live handle. After this returns, the stream is /// permanently aborted: every subsequent `next_batch` returns `Cancelled`. diff --git a/src/config.rs b/src/config.rs index 135b52c3..4457382b 100644 --- a/src/config.rs +++ b/src/config.rs @@ -760,7 +760,7 @@ pub struct HttpConfig { /// Idle limit for Volume file transfers: a transfer fails after this long /// without progress. Also caps connection setup. None sets no limit. - /// Exception: a stream PUT that storage redirects is resent without this limit. + /// Exception: a PUT that storage redirects is resent without this limit. pub storage_read_timeout: Option, /// Maximum total time across retries for a single logical RPC. diff --git a/src/result_stream.rs b/src/result_stream.rs index 576f1db0..928d95c3 100644 --- a/src/result_stream.rs +++ b/src/result_stream.rs @@ -654,10 +654,10 @@ impl ResultStream { /// Runs the file transfer for a Volume PUT, GET or REMOVE result. /// - /// Call before reading rows; the rows stay readable afterwards. The outcome is - /// cached, so a repeat call does not transfer again. A GET downloads to a - /// temporary file and then copies it over the destination, so a failed - /// download leaves an existing file unchanged. + /// Call before reading rows; the rows stay readable afterwards. The outcome, + /// success or failure, is cached, so a repeat call does not transfer again. + /// A GET downloads to a temporary file and then copies it over the destination, + /// so a failed download leaves an existing file unchanged. /// A failure during that copy can leave the destination partly written. /// Cancelling does not undo work already done: a PUT or REMOVE may already /// have reached storage, and a copy that has started runs to the end. diff --git a/src/volume.rs b/src/volume.rs index 7b9f08ba..a777353b 100644 --- a/src/volume.rs +++ b/src/volume.rs @@ -21,7 +21,7 @@ use crate::client::retry::{calculate_backoff, RequestType, RetryConfig, RetryStrategy}; use crate::kernel_error::{Error, LocalFileError, Result}; use arrow_array::{Array, LargeStringArray, MapArray, RecordBatch, StringArray, StringViewArray}; -use futures::TryStreamExt; +use futures::{StreamExt, TryStreamExt}; use reqwest::{header::HeaderMap, Client, Method}; use std::path::{Component, Path, PathBuf}; use std::sync::atomic::{AtomicBool, Ordering}; @@ -260,11 +260,15 @@ impl VolumeState { Err(error) if error.kind() == std::io::ErrorKind::NotFound => None, Err(error) => return Err(local_error(error, &local_file)), }; - let temp = tempfile::tempfile_in( - path.parent() - .ok_or_else(|| invalid("Missing destination parent"))?, - ) - .or_else(|_| tempfile::tempfile()) + let parent = path + .parent() + .ok_or_else(|| invalid("Missing destination parent"))?; + let temp = match tempfile::tempfile_in(parent) { + Err(error) if error.kind() == std::io::ErrorKind::PermissionDenied => { + tempfile::tempfile() + } + other => other, + } .map_err(|e| local_error(e, &local_file))?; let writer = tokio::fs::File::from_std( temp.try_clone().map_err(|e| local_error(e, &local_file))?, @@ -287,17 +291,45 @@ impl VolumeState { .headers(instruction.headers.clone()); let upload_error = Arc::new(Mutex::new(None)); let (progress, changed) = tokio::sync::watch::channel(tokio::time::Instant::now()); - let reader: Option<(Box, u64)> = - if let Some((file, length)) = source { - Some((Box::new(tokio::fs::File::from_std(file)), length)) - } else { - input.map(|bytes| { - ( - Box::new(std::io::Cursor::new(bytes.clone())) as _, - bytes.len() as u64, - ) + let mut upload_file = None; + let reader: Option<( + futures::stream::BoxStream<'static, std::io::Result>, + u64, + )> = if let Some((file, length)) = source.as_ref() { + let reader = Arc::new(tokio::sync::Mutex::new(Some(tokio::fs::File::from_std( + file.try_clone().map_err(|e| local_error(e, &local_file))?, + )))); + upload_file = Some(Arc::clone(&reader)); + Some(( + futures::stream::try_unfold(reader, |reader| async move { + let mut bytes = Vec::with_capacity(256 * 1024); + let count = { + let mut file = reader.lock().await; + match file.as_mut() { + Some(file) => { + tokio::io::AsyncReadExt::read_buf(file, &mut bytes).await? + } + None => 0, + } + }; + Ok::<_, std::io::Error>(if count == 0 { + None + } else { + Some((Bytes::from(bytes), reader)) + }) }) - }; + .boxed(), + *length, + )) + } else { + input.map(|bytes| { + ( + ReaderStream::with_capacity(std::io::Cursor::new(bytes.clone()), 256 * 1024) + .boxed(), + bytes.len() as u64, + ) + }) + }; if let Some((reader, length)) = reader { request = request .headers(HeaderMap::from_iter([( @@ -319,20 +351,51 @@ impl VolumeState { changed, ) .await?; - if let Some(bytes) = input.filter(|_| matches!(response.status().as_u16(), 307 | 308)) { - // reqwest cannot replay a streamed body on a redirect. Resend from memory - // so it can follow; this resend has no idle timeout. - response = client - .put(&instruction.url) - .headers(instruction.headers.clone()) - .headers(HeaderMap::from_iter([( - reqwest::header::CONTENT_LENGTH, - bytes.len().into(), - )])) - .body(reqwest::Body::from(bytes.clone())) - .send() - .await - .map_err(storage_error)?; + if matches!(response.status().as_u16(), 307 | 308) { + if let Some(upload_file) = upload_file { + let file = upload_file.lock().await.take(); + if let Some(file) = file { + // The cloned handles share a cursor; finish the first reader before rewinding. + drop(file.into_std().await); + } + } + let bytes = match (input, source) { + (Some(bytes), _) => Some(bytes.clone()), + (None, Some((mut file, _))) => { + let local_file = local_file.clone(); + Some( + tokio::task::spawn_blocking(move || { + use std::io::{Read, Seek}; + file.rewind().map_err(|e| local_error(e, &local_file))?; + let mut bytes = Vec::new(); + file.read_to_end(&mut bytes) + .map_err(|e| local_error(e, &local_file))?; + Ok::<_, Error>(Bytes::from(bytes)) + }) + .await + .map_err(|e| { + Error::internal() + .message(format!("Volume upload read task failed: {e}")) + })??, + ) + } + _ => None, + }; + if let Some(bytes) = bytes { + // reqwest cannot replay a streamed body on a redirect. Resend from memory + // so it can follow; this resend has no idle timeout. + response = client + .put(&instruction.url) + .headers(instruction.headers.clone()) + .headers(HeaderMap::from_iter([( + reqwest::header::CONTENT_LENGTH, + bytes.len().into(), + )])) + .body(reqwest::Body::from(bytes)) + .send() + .await + .map_err(storage_error)?; + } } let status = response.status(); if !(status.is_success() @@ -405,13 +468,13 @@ impl VolumeState { } fn upload_body( - reader: impl tokio::io::AsyncRead + Unpin + Send + 'static, + reader: impl futures::Stream> + Send + 'static, path: String, error: Arc>>, progress: tokio::sync::watch::Sender, ) -> reqwest::Body { reqwest::Body::wrap_stream( - ReaderStream::with_capacity(reader, 256 * 1024) + reader .inspect_ok(move |_| { progress.send_replace(tokio::time::Instant::now()); }) @@ -441,6 +504,7 @@ async fn storage_send( let Some(deadline) = last.checked_add(timeout) else { break (&mut send).await; }; + // PUT response timeouts may follow a committed write; GET retries only rewrite the temporary file. tokio::select! { biased; response = &mut send => break response, @@ -824,7 +888,7 @@ mod tests { let os_code = cause.raw_os_error(); let captured = Arc::new(Mutex::new(None)); let body = upload_body( - FailedRead(Some(cause)), + ReaderStream::with_capacity(FailedRead(Some(cause)), 256 * 1024), source.to_str().unwrap().into(), Arc::clone(&captured), tokio::sync::watch::channel(tokio::time::Instant::now()).0, @@ -922,7 +986,7 @@ mod tests { #[tokio::test] async fn storage_statuses_and_retry_limits_preserve_classification() { for (operation, status, retries, budget, requests, missing_success) in [ - ("PUT", 307, 2, Duration::from_secs(10), 1, true), + ("PUT", 403, 2, Duration::from_secs(10), 1, true), ("REMOVE", 403, 2, Duration::from_secs(10), 1, true), ("REMOVE", 404, 2, Duration::from_secs(10), 1, true), ("REMOVE", 404, 2, Duration::from_secs(10), 1, false), @@ -1075,6 +1139,20 @@ mod tests { ); } + #[tokio::test] + async fn get_with_missing_parent_fails_before_downloading() { + let server = MockServer::start().await; + let directory = tempfile::tempdir().unwrap(); + let destination = directory.path().join("missing/download"); + let batch = instruction("GET", &server.uri(), &destination); + let error = transfer_state(0) + .complete(async { Ok(batch) }, &options(directory.path()), None) + .await + .unwrap_err(); + assert_eq!(error.code, crate::ErrorCode::NotFound); + assert!(server.received_requests().await.unwrap().is_empty()); + } + #[tokio::test] async fn get_writes_in_place_and_preserves_old_bytes_on_download_failure() { let server = MockServer::start().await; @@ -1407,7 +1485,12 @@ mod tests { }); let error = Arc::new(Mutex::new(None)); let (progress, changed) = tokio::sync::watch::channel(tokio::time::Instant::now()); - let body = upload_body(reader, "input".into(), Arc::clone(&error), progress); + let body = upload_body( + ReaderStream::with_capacity(reader, 256 * 1024), + "input".into(), + Arc::clone(&error), + progress, + ); storage_send( Client::new() .put(server.uri()) @@ -1713,46 +1796,54 @@ mod tests { } #[tokio::test] - async fn redirected_stream_put_replays_full_bytes() { - let server = MockServer::start().await; - let payload = vec![b'x'; 512 * 1024 + 1]; - Mock::given(method("PUT")) - .and(path("/original")) - .and(body_bytes(payload.clone())) - .respond_with(ResponseTemplate::new(307).insert_header("location", "/target")) - .expect(2) - .mount(&server) - .await; - Mock::given(method("PUT")) - .and(path("/target")) - .and(body_bytes(payload.clone())) - .respond_with(ResponseTemplate::new(200)) - .expect(1) - .mount(&server) - .await; - assert_eq!( - transfer_state(0) - .complete( - async { - Ok(instruction( - "PUT", - &format!("{}/original", server.uri()), - Path::new("__input_stream__"), - )) - }, - &VolumeOptions::default(), - Some(payload), - ) + async fn redirected_put_replays_full_bytes() { + for (stream, status) in [(true, 307), (false, 307), (false, 308)] { + let server = MockServer::start().await; + let payload = vec![b'x'; 512 * 1024 + 1]; + let directory = tempfile::tempdir().unwrap(); + let source = directory.path().join("source"); + std::fs::write(&source, &payload).unwrap(); + Mock::given(method("PUT")) + .and(path("/original")) + .and(body_bytes(payload.clone())) + .respond_with(ResponseTemplate::new(status).insert_header("location", "/target")) + .expect(2) + .mount(&server) + .await; + Mock::given(method("PUT")) + .and(path("/target")) + .and(body_bytes(payload.clone())) + .respond_with(ResponseTemplate::new(200)) + .expect(1) + .mount(&server) + .await; + let batch = instruction( + "PUT", + &format!("{}/original", server.uri()), + if stream { + Path::new("__input_stream__") + } else { + &source + }, + ); + assert_eq!( + transfer_state(0) + .complete( + async { Ok(batch) }, + &options(directory.path()), + stream.then_some(payload), + ) + .await + .unwrap(), + VolumeCompletion::Completed + ); + assert!(server + .received_requests() .await - .unwrap(), - VolumeCompletion::Completed - ); - assert!(server - .received_requests() - .await - .unwrap() - .iter() - .all(|request| !request.headers.contains_key("referer"))); + .unwrap() + .iter() + .all(|request| !request.headers.contains_key("referer"))); + } } #[tokio::test] diff --git a/tests/v0_volume_wiremock.rs b/tests/v0_volume_wiremock.rs index 5df4280f..cbf7af3f 100644 --- a/tests/v0_volume_wiremock.rs +++ b/tests/v0_volume_wiremock.rs @@ -393,6 +393,61 @@ async fn owner_reader_and_repeated_materialization_share_one_completion() { session.close().await.unwrap(); } +#[tokio::test] +async fn async_executed_canceller_interrupts_volume_transfer() { + let server = MockServer::start().await; + let directory = tempfile::tempdir().unwrap(); + let destination = directory.path().join("download"); + let session = session( + &server, + response(&server, true, destination.to_str().unwrap()), + ) + .await; + Mock::given(method("GET")) + .and(path("/object")) + .respond_with( + ResponseTemplate::new(200) + .set_delay(Duration::from_secs(3)) + .set_body_bytes(b"data"), + ) + .expect(1) + .mount(&server) + .await; + let mut statement = session.statement(); + statement.spec().sql("operation"); + let executed = statement.submit().await.unwrap(); + let canceller = executed.canceller(); + let mut stream = executed.fetch_result().await.unwrap(); + let options = VolumeOptions::new(vec![directory.path().to_owned()], false); + let cancel = async { + while !server + .received_requests() + .await + .unwrap() + .iter() + .any(|request| request.url.path() == "/object") + { + tokio::task::yield_now().await; + } + canceller.cancel().await.unwrap(); + }; + let (result, _) = tokio::time::timeout(Duration::from_secs(1), async { + tokio::join!(stream.complete_volume_operation(&options, None), cancel) + }) + .await + .unwrap(); + assert_eq!(result.unwrap_err().code, ErrorCode::Cancelled); + assert_eq!( + stream + .complete_volume_operation(&options, None) + .await + .unwrap_err() + .code, + ErrorCode::Cancelled + ); + session.close().await.unwrap(); +} + #[tokio::test] async fn cancellation_and_session_close_interrupt_instruction_or_storage_after_sql_closed() { for (instruction_page, close_session) in From 5e7a9b292dea37ce91d1506b43f81dcef4a2663b Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Mon, 23 Nov 2026 00:17:52 +0000 Subject: [PATCH 56/63] fixup! fix(volume): start retries on failure and clear ADBC staging Signed-off-by: Aakash Saravanan --- src/volume.rs | 139 +++++++++++++++++++++++++++----------------------- 1 file changed, 75 insertions(+), 64 deletions(-) diff --git a/src/volume.rs b/src/volume.rs index a777353b..26f6b06a 100644 --- a/src/volume.rs +++ b/src/volume.rs @@ -21,7 +21,7 @@ use crate::client::retry::{calculate_backoff, RequestType, RetryConfig, RetryStrategy}; use crate::kernel_error::{Error, LocalFileError, Result}; use arrow_array::{Array, LargeStringArray, MapArray, RecordBatch, StringArray, StringViewArray}; -use futures::{StreamExt, TryStreamExt}; +use futures::TryStreamExt; use reqwest::{header::HeaderMap, Client, Method}; use std::path::{Component, Path, PathBuf}; use std::sync::atomic::{AtomicBool, Ordering}; @@ -291,45 +291,22 @@ impl VolumeState { .headers(instruction.headers.clone()); let upload_error = Arc::new(Mutex::new(None)); let (progress, changed) = tokio::sync::watch::channel(tokio::time::Instant::now()); - let mut upload_file = None; - let reader: Option<( - futures::stream::BoxStream<'static, std::io::Result>, - u64, - )> = if let Some((file, length)) = source.as_ref() { - let reader = Arc::new(tokio::sync::Mutex::new(Some(tokio::fs::File::from_std( - file.try_clone().map_err(|e| local_error(e, &local_file))?, - )))); - upload_file = Some(Arc::clone(&reader)); - Some(( - futures::stream::try_unfold(reader, |reader| async move { - let mut bytes = Vec::with_capacity(256 * 1024); - let count = { - let mut file = reader.lock().await; - match file.as_mut() { - Some(file) => { - tokio::io::AsyncReadExt::read_buf(file, &mut bytes).await? - } - None => 0, - } - }; - Ok::<_, std::io::Error>(if count == 0 { - None - } else { - Some((Bytes::from(bytes), reader)) - }) + let reader: Option<(Box, u64)> = + if let Some((file, length)) = source.as_ref() { + Some(( + Box::new(tokio::fs::File::from_std( + file.try_clone().map_err(|e| local_error(e, &local_file))?, + )), + *length, + )) + } else { + input.map(|bytes| { + ( + Box::new(std::io::Cursor::new(bytes.clone())) as _, + bytes.len() as u64, + ) }) - .boxed(), - *length, - )) - } else { - input.map(|bytes| { - ( - ReaderStream::with_capacity(std::io::Cursor::new(bytes.clone()), 256 * 1024) - .boxed(), - bytes.len() as u64, - ) - }) - }; + }; if let Some((reader, length)) = reader { request = request .headers(HeaderMap::from_iter([( @@ -352,32 +329,20 @@ impl VolumeState { ) .await?; if matches!(response.status().as_u16(), 307 | 308) { - if let Some(upload_file) = upload_file { - let file = upload_file.lock().await.take(); - if let Some(file) = file { - // The cloned handles share a cursor; finish the first reader before rewinding. - drop(file.into_std().await); - } - } let bytes = match (input, source) { (Some(bytes), _) => Some(bytes.clone()), - (None, Some((mut file, _))) => { + (None, Some((file, length))) => { let local_file = local_file.clone(); - Some( + Some(Bytes::from( tokio::task::spawn_blocking(move || { - use std::io::{Read, Seek}; - file.rewind().map_err(|e| local_error(e, &local_file))?; - let mut bytes = Vec::new(); - file.read_to_end(&mut bytes) - .map_err(|e| local_error(e, &local_file))?; - Ok::<_, Error>(Bytes::from(bytes)) + read_from_start(&file, length).map_err(|e| local_error(e, &local_file)) }) .await .map_err(|e| { Error::internal() .message(format!("Volume upload read task failed: {e}")) })??, - ) + )) } _ => None, }; @@ -468,13 +433,13 @@ impl VolumeState { } fn upload_body( - reader: impl futures::Stream> + Send + 'static, + reader: impl tokio::io::AsyncRead + Unpin + Send + 'static, path: String, error: Arc>>, progress: tokio::sync::watch::Sender, ) -> reqwest::Body { reqwest::Body::wrap_stream( - reader + ReaderStream::with_capacity(reader, 256 * 1024) .inspect_ok(move |_| { progress.send_replace(tokio::time::Instant::now()); }) @@ -572,6 +537,34 @@ fn response_body_error(error: reqwest::Error) -> Error { error } +/// Reads the first `length` bytes of `file` by offset. The first request's body +/// shares this handle's position and may still be moving it. +fn read_from_start(file: &std::fs::File, length: u64) -> std::io::Result> { + let length = usize::try_from(length).map_err(|_| std::io::ErrorKind::OutOfMemory)?; + let mut bytes = Vec::new(); + bytes + .try_reserve_exact(length) + .map_err(|_| std::io::ErrorKind::OutOfMemory)?; + bytes.resize(length, 0); + #[cfg(unix)] + { + std::os::unix::fs::FileExt::read_exact_at(file, &mut bytes, 0)?; + Ok(bytes) + } + #[cfg(windows)] + { + use std::os::windows::fs::FileExt; + let mut filled = 0; + while filled < bytes.len() { + match file.seek_read(&mut bytes[filled..], filled as u64)? { + 0 => return Err(std::io::ErrorKind::UnexpectedEof.into()), + read => filled += read, + } + } + Ok(bytes) + } +} + fn local_error(error: std::io::Error, path: &str) -> Error { match error.kind() { std::io::ErrorKind::NotFound => Error::not_found(), @@ -820,6 +813,29 @@ mod tests { use wiremock::matchers::{body_bytes, header, method, path}; use wiremock::{Mock, MockServer, ResponseTemplate}; + #[test] + fn replay_read_ignores_the_shared_file_position() { + use std::io::{Seek, SeekFrom}; + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("source"); + let payload = b"0123456789".to_vec(); + std::fs::write(&path, &payload).unwrap(); + let mut file = std::fs::File::open(&path).unwrap(); + file.seek(SeekFrom::Start(3)).unwrap(); + assert_eq!( + read_from_start(&file, payload.len() as u64).unwrap(), + payload + ); + #[cfg(unix)] + assert_eq!(file.stream_position().unwrap(), 3); + assert_eq!( + read_from_start(&file, payload.len() as u64 + 1) + .unwrap_err() + .kind(), + std::io::ErrorKind::UnexpectedEof + ); + } + fn instruction(operation: &str, url: &str, local: &Path) -> RecordBatch { let mut headers = MapBuilder::new(None, StringBuilder::new(), StringBuilder::new()); headers.keys().append_value("x-storage-token"); @@ -888,7 +904,7 @@ mod tests { let os_code = cause.raw_os_error(); let captured = Arc::new(Mutex::new(None)); let body = upload_body( - ReaderStream::with_capacity(FailedRead(Some(cause)), 256 * 1024), + FailedRead(Some(cause)), source.to_str().unwrap().into(), Arc::clone(&captured), tokio::sync::watch::channel(tokio::time::Instant::now()).0, @@ -1485,12 +1501,7 @@ mod tests { }); let error = Arc::new(Mutex::new(None)); let (progress, changed) = tokio::sync::watch::channel(tokio::time::Instant::now()); - let body = upload_body( - ReaderStream::with_capacity(reader, 256 * 1024), - "input".into(), - Arc::clone(&error), - progress, - ); + let body = upload_body(reader, "input".into(), Arc::clone(&error), progress); storage_send( Client::new() .put(server.uri()) From c0694d89a11da41bb66a8455119b54a8de3e5ac2 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Mon, 23 Nov 2026 19:57:07 +0000 Subject: [PATCH 57/63] fixup! fix(volume): start retries on failure and clear ADBC staging Signed-off-by: Aakash Saravanan --- napi/NEXT_CHANGELOG.md | 4 ++++ napi/index.d.ts | 3 ++- napi/src/cancellable.rs | 4 +++- src/volume.rs | 14 ++++++++++++++ 4 files changed, 23 insertions(+), 2 deletions(-) diff --git a/napi/NEXT_CHANGELOG.md b/napi/NEXT_CHANGELOG.md index 77ba04ed..6b1eef17 100644 --- a/napi/NEXT_CHANGELOG.md +++ b/napi/NEXT_CHANGELOG.md @@ -24,6 +24,10 @@ layout, or npm publishing. Pure-kernel changes go in the root ### Fixed +- `AsyncStatement.close()` also releases a result stream that an in-flight + fetch holds, once that operation finishes; later fetches return + `InvalidStatementHandle`. `close()` still does not wait for it. + --- *Note: When making changes, please add your change under the appropriate section with a brief description. At release time, move the entries here diff --git a/napi/index.d.ts b/napi/index.d.ts index 877a40c3..88be1248 100644 --- a/napi/index.d.ts +++ b/napi/index.d.ts @@ -965,7 +965,8 @@ export declare class CancellableExecution { * behind it. No-op (returns `Ok`) if `result()` already finished * successfully, or if no statement id has been observed yet (query still * in its initial submit round-trip), and idempotent against a server - * already in a terminal state. + * already in a terminal state. It still stops a Volume transfer in progress + * after `result()` has finished. */ cancel(): Promise } diff --git a/napi/src/cancellable.rs b/napi/src/cancellable.rs index bc445019..d2695f55 100644 --- a/napi/src/cancellable.rs +++ b/napi/src/cancellable.rs @@ -219,9 +219,11 @@ impl CancellableExecution { /// behind it. No-op (returns `Ok`) if `result()` already finished /// successfully, or if no statement id has been observed yet (query still /// in its initial submit round-trip), and idempotent against a server - /// already in a terminal state. + /// already in a terminal state. It still stops a Volume transfer in progress + /// after `result()` has finished. #[napi] pub async fn cancel(&self) -> napi::Result<()> { + self.canceller.cancel_volume_operation(); // Skip the server-side cancel RPC once the statement is terminal (success // OR error) — it would be a redundant no-op-at-server call + confusing log. if self.terminal.load(Ordering::Acquire) { diff --git a/src/volume.rs b/src/volume.rs index 26f6b06a..4a64372f 100644 --- a/src/volume.rs +++ b/src/volume.rs @@ -405,6 +405,15 @@ impl VolumeState { error = error.message(format!("{tag}: {value}")); } } + for (label, header) in [("RequestId", "x-amz-request-id"), ("HostId", "x-amz-id-2")] { + if let Some(value) = response + .headers() + .get(header) + .and_then(|value| value.to_str().ok()) + { + error = error.message(format!("{label}: {value}")); + } + } return Err(error); } while let Some(bytes) = storage_read(self.storage.read_timeout, !upload, async { @@ -1017,6 +1026,8 @@ mod tests { ResponseTemplate::new(status) .insert_header("retry-after", "0") .insert_header("location", "/redirected") + .insert_header("x-amz-request-id", "request-1") + .insert_header("x-amz-id-2", "host-1") .set_body_string("AccessDeniedPermission refusedsecret"), ) .expect(requests) @@ -1061,6 +1072,9 @@ mod tests { ); assert_eq!(error.retryable, status == 503); assert!(error.message.contains("AccessDenied")); + assert!(error + .message + .contains("RequestId: request-1; HostId: host-1")); assert!(error .message .contains(&format!("after {requests} attempts"))); From fe7d755fe27d07f30c0b722fdf6d764e0a49473f Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Tue, 24 Nov 2026 08:10:08 +0000 Subject: [PATCH 58/63] fix(volume): classify instructions and log transfer attempts Signed-off-by: Aakash Saravanan --- src/c_abi/result.rs | 2 +- src/result_stream.rs | 11 +++-- src/statement/executed_async.rs | 6 ++- src/statement/mutable.rs | 8 +++- src/telemetry/statement.rs | 19 ++++---- src/volume.rs | 81 ++++++++++++++++++++++++++------- tests/v0_volume_wiremock.rs | 14 ++++-- 7 files changed, 98 insertions(+), 43 deletions(-) diff --git a/src/c_abi/result.rs b/src/c_abi/result.rs index b744c33a..a1498893 100644 --- a/src/c_abi/result.rs +++ b/src/c_abi/result.rs @@ -803,7 +803,7 @@ mod tests { ResultStream::from_reader(Box::new(MockReader::new(vec![batch.clone()]))) .await .unwrap(); - stream.attach_volume(true, Arc::clone(&volume)); + stream.attach_volume(Arc::clone(&volume)); into_raw_result_stream(schema.clone(), stream) }); let mut is_volume = false; diff --git a/src/result_stream.rs b/src/result_stream.rs index 928d95c3..7ba9f9cd 100644 --- a/src/result_stream.rs +++ b/src/result_stream.rs @@ -641,10 +641,8 @@ impl ResultStream { Ok(stream) } - pub(crate) fn attach_volume(&mut self, marked: bool, state: Arc) { - if marked { - self.volume = Some(state); - } + pub(crate) fn attach_volume(&mut self, state: Arc) { + self.volume = Some(state); } /// True when the server marked this result as a Volume PUT, GET or REMOVE. @@ -682,7 +680,9 @@ impl ResultStream { async { let batch = loop { let batch = self.peek_first_batch().await?.ok_or_else(|| { - Error::invalid_argument().message("Missing Volume instruction row") + Error::invalid_argument() + .with_error_code("VOLUME_INVALID_INSTRUCTION") + .message("Missing Volume instruction row") })?; let ResultBatch::Arrow(batch) = batch; if batch.num_rows() != 0 { @@ -706,6 +706,7 @@ impl ResultStream { Ok(Some(batch)) if batch.num_rows() != 0 => { self.prefetched.push_back(Ok(ResultBatch::Arrow(batch))); return Err(Error::invalid_argument() + .with_error_code("VOLUME_INVALID_INSTRUCTION") .message("Expected one Volume instruction row")); } Ok(Some(_)) => {} diff --git a/src/statement/executed_async.rs b/src/statement/executed_async.rs index ec4c9517..28c2d379 100644 --- a/src/statement/executed_async.rs +++ b/src/statement/executed_async.rs @@ -957,8 +957,10 @@ impl ExecutedAsyncStatement { .as_ref() .is_some_and(|m| m.is_volume_operation); let mut stream = ResultStream::from_reader(result.reader).await?; - if let Some(volume) = &self.volume { - stream.attach_volume(marked, Arc::clone(volume)); + if marked { + if let Some(volume) = &self.volume { + stream.attach_volume(Arc::clone(volume)); + } } stream.attach_telemetry(self.statement_telemetry.clone()); // SEA carries no row count on the async status either; for a diff --git a/src/statement/mutable.rs b/src/statement/mutable.rs index aeb246ba..ab286573 100644 --- a/src/statement/mutable.rs +++ b/src/statement/mutable.rs @@ -421,7 +421,9 @@ impl Statement { .as_ref() .is_some_and(|m| m.is_volume_operation); let mut result_stream = ResultStream::from_reader(result.reader).await?; - result_stream.attach_volume(marked, self.volume_state()); + if marked { + result_stream.attach_volume(self.volume_state()); + } result_stream.attach_telemetry(telemetry_for_body.clone()); // SEA puts no row count on the status envelope; for a DML it // returns the count as the result set. If the server didn't @@ -662,7 +664,9 @@ impl Statement { .as_ref() .is_some_and(|m| m.is_volume_operation); let mut result_stream = ResultStream::from_reader(result.reader).await?; - result_stream.attach_volume(marked, self.volume_state()); + if marked { + result_stream.attach_volume(self.volume_state()); + } result_stream.attach_telemetry(telemetry_for_body.clone()); let mut status = result.status; if status.num_modified_rows.is_none() { diff --git a/src/telemetry/statement.rs b/src/telemetry/statement.rs index b2cc5b5b..8ceee6c4 100644 --- a/src/telemetry/statement.rs +++ b/src/telemetry/statement.rs @@ -447,18 +447,15 @@ mod tests { .expect("schema succeeds"); stream.attach_telemetry(telemetry); - stream.attach_volume( - true, - crate::volume::VolumeState::new( - Default::default(), - Arc::new( - crate::client::DatabricksHttpClient::with_default_retry(Default::default()) - .unwrap() - .storage_client(None), - ), - Default::default(), + stream.attach_volume(crate::volume::VolumeState::new( + Default::default(), + Arc::new( + crate::client::DatabricksHttpClient::with_default_retry(Default::default()) + .unwrap() + .storage_client(None), ), - ); + Default::default(), + )); let options = Default::default(); let error = stream .complete_volume_operation(&options, None) diff --git a/src/volume.rs b/src/volume.rs index 4a64372f..a038f450 100644 --- a/src/volume.rs +++ b/src/volume.rs @@ -70,11 +70,19 @@ pub enum VolumeCompletion { pub(crate) struct VolumeState { retry: RetryConfig, storage: Arc, + /// Unset until the transfer reaches a final outcome. A PUT waiting for caller bytes leaves it unset. pub(crate) completion: OnceCell>, cancellation: CancellationToken, started: AtomicBool, } +struct Download { + temp: std::fs::File, + existing: Option, + path: PathBuf, + local_file: String, +} + fn cancelled() -> Error { Error::cancelled().message("Volume transfer was cancelled") } @@ -131,7 +139,13 @@ impl VolumeState { result = transfer => result?, _ = self.cancellation.cancelled() => return Err(cancelled()), }; - if let Some((mut temp, existing, path, local_file)) = destination { + if let Some(Download { + mut temp, + existing, + path, + local_file, + }) = destination + { let cancellation = self.cancellation.clone(); tokio::task::spawn_blocking(move || { if cancellation.is_cancelled() { @@ -182,7 +196,7 @@ impl VolumeState { client: &Client, options: &VolumeOptions, input_bytes: Option>, - ) -> Result, PathBuf, String)>> { + ) -> Result> { let input = if matches!(instruction.operation, Operation::Put(Source::Stream)) { Some(Bytes::from( input_bytes.ok_or_else(|| invalid("Missing input stream"))?, @@ -194,6 +208,7 @@ impl VolumeState { let mut attempt = 0; loop { let mut retry_after = None; + let attempt_started = std::time::Instant::now(); let error = match self .transfer_once( &instruction, @@ -204,9 +219,25 @@ impl VolumeState { ) .await { - Ok(completion) => return Ok(completion), + Ok(completion) => { + tracing::debug!( + target: crate::klog::KERNEL_LOG_TARGET, + attempt = attempt + 1, + attempt_ms = attempt_started.elapsed().as_millis() as u64, + "volume transfer attempt succeeded" + ); + return Ok(completion); + } Err(error) => error, }; + tracing::debug!( + target: crate::klog::KERNEL_LOG_TARGET, + attempt = attempt + 1, + attempt_ms = attempt_started.elapsed().as_millis() as u64, + retryable = error.retryable, + error = %error.message, + "volume transfer attempt failed" + ); // The retry clock starts at the first failure, so a long transfer does not // use up the retry budget. let started = retry_started.get_or_insert_with(std::time::Instant::now); @@ -217,6 +248,12 @@ impl VolumeState { if started.elapsed().saturating_add(wait) >= self.retry.overall_timeout { return Err(error.message(format!("after {} attempts", attempt + 1))); } + tracing::debug!( + target: crate::klog::KERNEL_LOG_TARGET, + attempt = attempt + 1, + wait_ms = wait.as_millis() as u64, + "waiting before retrying volume transfer" + ); tokio::time::sleep(wait).await; attempt += 1; } @@ -229,7 +266,7 @@ impl VolumeState { options: &VolumeOptions, input: Option<&Bytes>, retry_after: &mut Option, - ) -> Result, PathBuf, String)>> { + ) -> Result> { let operation = instruction.operation.clone(); let roots = options.allowed_paths.clone(); let preparation = tokio::task::spawn_blocking(move || { @@ -273,7 +310,15 @@ impl VolumeState { let writer = tokio::fs::File::from_std( temp.try_clone().map_err(|e| local_error(e, &local_file))?, ); - destination = Some((temp, writer, existing, path)); + destination = Some(( + Download { + temp, + existing, + path, + local_file: local_file.clone(), + }, + writer, + )); (Method::GET, local_file) } Operation::Put(Source::Stream) => (Method::PUT, String::new()), @@ -347,8 +392,8 @@ impl VolumeState { _ => None, }; if let Some(bytes) = bytes { - // reqwest cannot replay a streamed body on a redirect. Resend from memory - // so it can follow; this resend has no idle timeout. + // reqwest cannot replay a streamed body on a redirect. Send the original URL again + // with the body in memory so reqwest can follow; this resend has no idle timeout. response = client .put(&instruction.url) .headers(instruction.headers.clone()) @@ -421,22 +466,22 @@ impl VolumeState { }) .await? { - if let Some((_, writer, _, _)) = destination.as_mut() { + if let Some((_, writer)) = destination.as_mut() { writer .write_all(&bytes) .await .map_err(|e| local_error(e, &local_file))?; } } - if let Some((_, writer, _, _)) = destination.as_mut() { + if let Some((_, writer)) = destination.as_mut() { writer .flush() .await .map_err(|e| local_error(e, &local_file))?; } - Ok(destination.map(|(temp, writer, existing, path)| { + Ok(destination.map(|(download, writer)| { drop(writer); - (temp, existing, path, local_file) + download })) } } @@ -460,7 +505,9 @@ fn upload_body( } fn invalid(message: &str) -> Error { - Error::invalid_argument().message(message) + Error::invalid_argument() + .with_error_code("VOLUME_INVALID_INSTRUCTION") + .message(message) } async fn storage_send( @@ -1110,7 +1157,7 @@ mod tests { tokio::time::sleep(Duration::from_millis(50)).await; state.cancel(); }; - let (result, _) = tokio::time::timeout(Duration::from_secs(1), async { + let (result, _) = tokio::time::timeout(Duration::from_secs(10), async { tokio::join!(complete, cancel) }) .await @@ -1477,7 +1524,7 @@ mod tests { .await .unwrap(); for _ in 0..5 { - tokio::time::sleep(Duration::from_millis(60)).await; + tokio::time::sleep(Duration::from_millis(150)).await; socket.write_all(b"x").await.unwrap(); } }); @@ -1485,7 +1532,7 @@ mod tests { let dest = dir.path().join("download"); let state = VolumeState::new( transfer_state(0).retry.clone(), - storage(Some(Duration::from_millis(150))), + storage(Some(Duration::from_millis(500))), Default::default(), ); state @@ -1509,7 +1556,7 @@ mod tests { let (mut writer, reader) = tokio::io::duplex(1); let producer = tokio::spawn(async move { for _ in 0..5 { - tokio::time::sleep(Duration::from_millis(60)).await; + tokio::time::sleep(Duration::from_millis(150)).await; writer.write_all(b"x").await.unwrap(); } }); @@ -1521,7 +1568,7 @@ mod tests { .put(server.uri()) .header(reqwest::header::CONTENT_LENGTH, 5) .body(body), - Some(Duration::from_millis(150)), + Some(Duration::from_millis(500)), true, error, changed, diff --git a/tests/v0_volume_wiremock.rs b/tests/v0_volume_wiremock.rs index cbf7af3f..b134eafe 100644 --- a/tests/v0_volume_wiremock.rs +++ b/tests/v0_volume_wiremock.rs @@ -112,6 +112,10 @@ async fn instruction_batches_preserve_one_row_and_reject_extra_rows() { } else { let error = result.unwrap_err(); assert_eq!(error.code, ErrorCode::InvalidArgument); + assert_eq!( + error.error_code.as_deref(), + Some("VOLUME_INVALID_INSTRUCTION") + ); assert_eq!(error.message, "Expected one Volume instruction row"); } } @@ -407,7 +411,7 @@ async fn async_executed_canceller_interrupts_volume_transfer() { .and(path("/object")) .respond_with( ResponseTemplate::new(200) - .set_delay(Duration::from_secs(3)) + .set_delay(Duration::from_secs(30)) .set_body_bytes(b"data"), ) .expect(1) @@ -431,7 +435,7 @@ async fn async_executed_canceller_interrupts_volume_transfer() { } canceller.cancel().await.unwrap(); }; - let (result, _) = tokio::time::timeout(Duration::from_secs(1), async { + let (result, _) = tokio::time::timeout(Duration::from_secs(10), async { tokio::join!(stream.complete_volume_operation(&options, None), cancel) }) .await @@ -469,7 +473,7 @@ async fn cancellation_and_session_close_interrupt_instruction_or_storage_after_s .and(path("/api/2.0/sql/statements/volume-stmt/result/chunks/1")) .respond_with( ResponseTemplate::new(200) - .set_delay(Duration::from_secs(3)) + .set_delay(Duration::from_secs(30)) .set_body_json(next), ) .mount(&server) @@ -483,7 +487,7 @@ async fn cancellation_and_session_close_interrupt_instruction_or_storage_after_s .and(path("/object")) .respond_with( ResponseTemplate::new(200) - .set_delay(Duration::from_secs(3)) + .set_delay(Duration::from_secs(30)) .set_body_bytes(b"new"), ) .expect(if instruction_page { 0 } else { 1 }) @@ -516,7 +520,7 @@ async fn cancellation_and_session_close_interrupt_instruction_or_storage_after_s canceller.cancel().await.unwrap(); } }; - let (result, _) = tokio::time::timeout(Duration::from_secs(1), async { + let (result, _) = tokio::time::timeout(Duration::from_secs(10), async { tokio::join!(complete, cancel) }) .await From 9934c0ea0b656c59cc7fdc68ea1564e55c202fb7 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Tue, 24 Nov 2026 08:16:11 +0000 Subject: [PATCH 59/63] refactor(volume): extract transfer preparation and response handling Signed-off-by: Aakash Saravanan --- src/volume.rs | 261 ++++++++++++++++++++++++++++---------------------- 1 file changed, 149 insertions(+), 112 deletions(-) diff --git a/src/volume.rs b/src/volume.rs index a038f450..4774a9f8 100644 --- a/src/volume.rs +++ b/src/volume.rs @@ -267,68 +267,8 @@ impl VolumeState { input: Option<&Bytes>, retry_after: &mut Option, ) -> Result> { - let operation = instruction.operation.clone(); - let roots = options.allowed_paths.clone(); - let preparation = tokio::task::spawn_blocking(move || { - let mut source = None; - let mut destination = None; - let (method, local_file) = match operation { - Operation::Put(Source::File(path)) => { - let local_file = path.to_string_lossy().into_owned(); - let path = allowed_path(&local_file, &roots)?; - let mut file = - std::fs::File::open(path).map_err(|e| local_error(e, &local_file))?; - let metadata = file.metadata().map_err(|e| local_error(e, &local_file))?; - if metadata.is_dir() { - // A directory opens without error on Unix; reading it produces the OS error to report. - let error = std::io::Read::read(&mut file, &mut [0]) - .err() - .unwrap_or_else(|| std::io::ErrorKind::IsADirectory.into()); - return Err(local_error(error, &local_file)); - } - source = Some((file, metadata.len())); - (Method::PUT, local_file) - } - Operation::Get(path) => { - let local_file = path.to_string_lossy().into_owned(); - let path = allowed_path(&local_file, &roots)?; - let existing = match std::fs::OpenOptions::new().write(true).open(&path) { - Ok(file) => Some(file), - Err(error) if error.kind() == std::io::ErrorKind::NotFound => None, - Err(error) => return Err(local_error(error, &local_file)), - }; - let parent = path - .parent() - .ok_or_else(|| invalid("Missing destination parent"))?; - let temp = match tempfile::tempfile_in(parent) { - Err(error) if error.kind() == std::io::ErrorKind::PermissionDenied => { - tempfile::tempfile() - } - other => other, - } - .map_err(|e| local_error(e, &local_file))?; - let writer = tokio::fs::File::from_std( - temp.try_clone().map_err(|e| local_error(e, &local_file))?, - ); - destination = Some(( - Download { - temp, - existing, - path, - local_file: local_file.clone(), - }, - writer, - )); - (Method::GET, local_file) - } - Operation::Put(Source::Stream) => (Method::PUT, String::new()), - Operation::Remove => (Method::DELETE, String::new()), - }; - Ok((method, local_file, source, destination)) - }); - let (method, local_file, source, mut destination) = preparation.await.map_err(|e| { - Error::internal().message(format!("Volume file preparation task failed: {e}")) - })??; + let (method, local_file, source, mut destination) = + Self::prepare_local(instruction, options).await?; let upload = method == Method::PUT; let remove = method == Method::DELETE; let mut request = client @@ -411,56 +351,156 @@ impl VolumeState { if !(status.is_success() || (remove && status.as_u16() == 404 && options.remove_not_found_is_success)) { - *retry_after = response - .headers() - .get(reqwest::header::RETRY_AFTER) - .and_then(|value| value.to_str().ok()) - .map(str::to_owned); - let mut error = Error::from_http_status(status.as_u16()) - .with_error_code("VOLUME_STORAGE_HTTP_ERROR") - .with_retryable( - RetryStrategy::for_request(RequestType::CloudFetchDownload, &self.retry) - .is_retryable_status(status, retry_after.is_some()), - ) - .message(format!( - "Volume storage request failed: HTTP {}", - status.as_u16() - )); - let mut body = Vec::new(); - while body.len() < 4096 { - match storage_read(self.storage.read_timeout, !upload, async { - response.chunk().await.map_err(response_body_error) - }) - .await - { - Ok(Some(chunk)) => { - body.extend_from_slice(&chunk[..chunk.len().min(4096 - body.len())]) + return Err(self + .storage_failure(&mut response, status, upload, retry_after) + .await); + } + self.download_body(&mut response, upload, &local_file, &mut destination) + .await?; + Ok(destination.map(|(download, writer)| { + drop(writer); + download + })) + } + + async fn prepare_local( + instruction: &Instruction, + options: &VolumeOptions, + ) -> Result<( + Method, + String, + Option<(std::fs::File, u64)>, + Option<(Download, tokio::fs::File)>, + )> { + let operation = instruction.operation.clone(); + let roots = options.allowed_paths.clone(); + let preparation = tokio::task::spawn_blocking(move || { + let mut source = None; + let mut destination = None; + let (method, local_file) = match operation { + Operation::Put(Source::File(path)) => { + let local_file = path.to_string_lossy().into_owned(); + let path = allowed_path(&local_file, &roots)?; + let mut file = + std::fs::File::open(path).map_err(|e| local_error(e, &local_file))?; + let metadata = file.metadata().map_err(|e| local_error(e, &local_file))?; + if metadata.is_dir() { + // A directory opens without error on Unix; reading it produces the OS error to report. + let error = std::io::Read::read(&mut file, &mut [0]) + .err() + .unwrap_or_else(|| std::io::ErrorKind::IsADirectory.into()); + return Err(local_error(error, &local_file)); } - _ => break, + source = Some((file, metadata.len())); + (Method::PUT, local_file) } - } - let text = String::from_utf8_lossy(&body); - for tag in ["Code", "Message"] { - if let Some(value) = text - .split_once(&format!("<{tag}>")) - .and_then(|(_, tail)| tail.split_once(&format!(""))) - .map(|(value, _)| value) - .filter(|value| !value.contains(['<', '>'])) - { - error = error.message(format!("{tag}: {value}")); + Operation::Get(path) => { + let local_file = path.to_string_lossy().into_owned(); + let path = allowed_path(&local_file, &roots)?; + let existing = match std::fs::OpenOptions::new().write(true).open(&path) { + Ok(file) => Some(file), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => None, + Err(error) => return Err(local_error(error, &local_file)), + }; + let parent = path + .parent() + .ok_or_else(|| invalid("Missing destination parent"))?; + let temp = match tempfile::tempfile_in(parent) { + Err(error) if error.kind() == std::io::ErrorKind::PermissionDenied => { + tempfile::tempfile() + } + other => other, + } + .map_err(|e| local_error(e, &local_file))?; + let writer = tokio::fs::File::from_std( + temp.try_clone().map_err(|e| local_error(e, &local_file))?, + ); + destination = Some(( + Download { + temp, + existing, + path, + local_file: local_file.clone(), + }, + writer, + )); + (Method::GET, local_file) } - } - for (label, header) in [("RequestId", "x-amz-request-id"), ("HostId", "x-amz-id-2")] { - if let Some(value) = response - .headers() - .get(header) - .and_then(|value| value.to_str().ok()) - { - error = error.message(format!("{label}: {value}")); + Operation::Put(Source::Stream) => (Method::PUT, String::new()), + Operation::Remove => (Method::DELETE, String::new()), + }; + Ok((method, local_file, source, destination)) + }); + preparation.await.map_err(|e| { + Error::internal().message(format!("Volume file preparation task failed: {e}")) + })? + } + + async fn storage_failure( + &self, + response: &mut reqwest::Response, + status: reqwest::StatusCode, + upload: bool, + retry_after: &mut Option, + ) -> Error { + *retry_after = response + .headers() + .get(reqwest::header::RETRY_AFTER) + .and_then(|value| value.to_str().ok()) + .map(str::to_owned); + let mut error = Error::from_http_status(status.as_u16()) + .with_error_code("VOLUME_STORAGE_HTTP_ERROR") + .with_retryable( + RetryStrategy::for_request(RequestType::CloudFetchDownload, &self.retry) + .is_retryable_status(status, retry_after.is_some()), + ) + .message(format!( + "Volume storage request failed: HTTP {}", + status.as_u16() + )); + let mut body = Vec::new(); + while body.len() < 4096 { + match storage_read(self.storage.read_timeout, !upload, async { + response.chunk().await.map_err(response_body_error) + }) + .await + { + Ok(Some(chunk)) => { + body.extend_from_slice(&chunk[..chunk.len().min(4096 - body.len())]) } + _ => break, + } + } + let text = String::from_utf8_lossy(&body); + for tag in ["Code", "Message"] { + if let Some(value) = text + .split_once(&format!("<{tag}>")) + .and_then(|(_, tail)| tail.split_once(&format!(""))) + .map(|(value, _)| value) + .filter(|value| !value.contains(['<', '>'])) + { + error = error.message(format!("{tag}: {value}")); } - return Err(error); } + for (label, header) in [("RequestId", "x-amz-request-id"), ("HostId", "x-amz-id-2")] { + if let Some(value) = response + .headers() + .get(header) + .and_then(|value| value.to_str().ok()) + { + error = error.message(format!("{label}: {value}")); + } + } + error + } + + async fn download_body( + &self, + response: &mut reqwest::Response, + upload: bool, + local_file: &str, + destination: &mut Option<(Download, tokio::fs::File)>, + ) -> Result<()> { while let Some(bytes) = storage_read(self.storage.read_timeout, !upload, async { response.chunk().await.map_err(response_body_error) }) @@ -470,19 +510,16 @@ impl VolumeState { writer .write_all(&bytes) .await - .map_err(|e| local_error(e, &local_file))?; + .map_err(|e| local_error(e, local_file))?; } } if let Some((_, writer)) = destination.as_mut() { writer .flush() .await - .map_err(|e| local_error(e, &local_file))?; + .map_err(|e| local_error(e, local_file))?; } - Ok(destination.map(|(download, writer)| { - drop(writer); - download - })) + Ok(()) } } From 6d664a87688f689c9f9d70f6c4f15b746c0f5244 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Tue, 24 Nov 2026 08:38:19 +0000 Subject: [PATCH 60/63] fix(ci): use public package proxy for Windows Volume tests Signed-off-by: Aakash Saravanan --- .github/workflows/pr-checks.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/pr-checks.yml b/.github/workflows/pr-checks.yml index ea0f1da2..a8f6d728 100644 --- a/.github/workflows/pr-checks.yml +++ b/.github/workflows/pr-checks.yml @@ -140,7 +140,7 @@ jobs: steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - - uses: ./.github/actions/setup-jfrog + - uses: ./.github/actions/setup-public-package-proxies with: cargo: "true" From 3dbd1f05d20dc365010f2d64021797812fb30ce1 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Tue, 24 Nov 2026 17:13:36 +0000 Subject: [PATCH 61/63] fix(deps): update rustix to 1.1.6 Signed-off-by: Aakash Saravanan --- Cargo.lock | 4 ++-- adbc/Cargo.lock | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index d4992a7f..4f312715 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2383,9 +2383,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/adbc/Cargo.lock b/adbc/Cargo.lock index 2ba2ff78..dce29af2 100644 --- a/adbc/Cargo.lock +++ b/adbc/Cargo.lock @@ -2172,9 +2172,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", From dd6ab2afa836e55b2be1d7e4ed00471b836f89af Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Tue, 24 Nov 2026 23:27:47 +0000 Subject: [PATCH 62/63] docs(volume): clarify transfer lifetime and redirect memory Signed-off-by: Aakash Saravanan --- napi/index.d.ts | 2 ++ napi/src/async_statement.rs | 2 ++ src/result_stream.rs | 2 ++ 3 files changed, 6 insertions(+) diff --git a/napi/index.d.ts b/napi/index.d.ts index 88be1248..b58173ec 100644 --- a/napi/index.d.ts +++ b/napi/index.d.ts @@ -881,6 +881,8 @@ export declare class AsyncResultHandle { /** * Runs the file transfer for a Volume PUT, GET or REMOVE result. Call before * fetching; the rows stay readable afterwards. + * Keep the parent AsyncStatement alive until the transfer finishes; closing or + * collecting it stops the transfer. */ completeVolumeOperation(allowedPaths: Array, removeNotFoundIsSuccess: boolean): Promise /** diff --git a/napi/src/async_statement.rs b/napi/src/async_statement.rs index 5c754215..8a39c376 100644 --- a/napi/src/async_statement.rs +++ b/napi/src/async_statement.rs @@ -494,6 +494,8 @@ impl AsyncResultHandle { /// Runs the file transfer for a Volume PUT, GET or REMOVE result. Call before /// fetching; the rows stay readable afterwards. + /// Keep the parent AsyncStatement alive until the transfer finishes; closing or + /// collecting it stops the transfer. #[napi] pub async fn complete_volume_operation( &self, diff --git a/src/result_stream.rs b/src/result_stream.rs index 7ba9f9cd..f3b3d666 100644 --- a/src/result_stream.rs +++ b/src/result_stream.rs @@ -657,6 +657,8 @@ impl ResultStream { /// A GET downloads to a temporary file and then copies it over the destination, /// so a failed download leaves an existing file unchanged. /// A failure during that copy can leave the destination partly written. + /// A file PUT that storage redirects with 307 or 308 is resent from memory, + /// so that upload needs memory equal to the file size. /// Cancelling does not undo work already done: a PUT or REMOVE may already /// have reached storage, and a copy that has started runs to the end. /// Results from [`Session::attach_async_statement`](crate::Session::attach_async_statement) From 088cb40f4f6e861936688fb4115f712d28bef4da Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Thu, 26 Nov 2026 05:29:59 +0000 Subject: [PATCH 63/63] fix(volume): retain transfer docs and bound cancellation test Signed-off-by: Aakash Saravanan --- NOTICE | 5 +++++ adbc/NOTICE | 5 +++++ adbc/README.md | 14 ++++++++++++++ napi/index.d.ts | 2 +- napi/src/async_statement.rs | 2 +- src/volume.rs | 4 ++-- 6 files changed, 28 insertions(+), 4 deletions(-) diff --git a/NOTICE b/NOTICE index 7cda1ab7..55dd3e4b 100644 --- a/NOTICE +++ b/NOTICE @@ -142,6 +142,11 @@ Project URL: https://github.com/serde-rs/json Copyright: Copyright serde_json Authors. +Package: tempfile +Project URL: https://github.com/Stebalien/tempfile +Copyright: Copyright (c) 2015 Steven Allen + + Package: thiserror Project URL: https://github.com/dtolnay/thiserror Copyright: Copyright thiserror Authors. diff --git a/adbc/NOTICE b/adbc/NOTICE index 7cda1ab7..55dd3e4b 100644 --- a/adbc/NOTICE +++ b/adbc/NOTICE @@ -142,6 +142,11 @@ Project URL: https://github.com/serde-rs/json Copyright: Copyright serde_json Authors. +Package: tempfile +Project URL: https://github.com/Stebalien/tempfile +Copyright: Copyright (c) 2015 Steven Allen + + Package: thiserror Project URL: https://github.com/dtolnay/thiserror Copyright: Copyright thiserror Authors. diff --git a/adbc/README.md b/adbc/README.md index de153783..a2445d20 100644 --- a/adbc/README.md +++ b/adbc/README.md @@ -73,6 +73,20 @@ optional C interface and native Rust asynchronous submission and polling. Transactions, partitioned execution, statistics, and progress reporting are not currently implemented. +## Volume file operations + +Set `adbc.databricks.statement.staging_allowed_local_paths` to a JSON array of +local directories to run the file transfer for Volume `PUT`, `GET` and `REMOVE` +before results are returned. The result rows stay readable. Without the option +no file moves and the result is only the server's instruction row. +The option remains enabled for the statement until set to JSON `null`; an empty +array still permits REMOVE while denying file PUT and GET. Local `..` components collapse +before symlink resolution. REMOVE of a missing object succeeds. Input-stream PUT is unsupported. +The client timeout ends at the terminal SQL status and does not bound Volume transfers. +`SocketTimeout` (milliseconds) also sets the idle limit for Volume transfers; +`adbc.databricks.http_request_timeout` sets only the SQL request deadline. +See the kernel [Volume file operations](../README.md#volume-file-operations). + ## Compatibility and status The current implementation targets Rust 1.89+, Rust edition 2021, ADBC 1.1, diff --git a/napi/index.d.ts b/napi/index.d.ts index b58173ec..45c9a3b1 100644 --- a/napi/index.d.ts +++ b/napi/index.d.ts @@ -881,7 +881,7 @@ export declare class AsyncResultHandle { /** * Runs the file transfer for a Volume PUT, GET or REMOVE result. Call before * fetching; the rows stay readable afterwards. - * Keep the parent AsyncStatement alive until the transfer finishes; closing or + * Keep the parent `AsyncStatement` alive until the transfer finishes; closing or * collecting it stops the transfer. */ completeVolumeOperation(allowedPaths: Array, removeNotFoundIsSuccess: boolean): Promise diff --git a/napi/src/async_statement.rs b/napi/src/async_statement.rs index 8a39c376..073ec5ed 100644 --- a/napi/src/async_statement.rs +++ b/napi/src/async_statement.rs @@ -494,7 +494,7 @@ impl AsyncResultHandle { /// Runs the file transfer for a Volume PUT, GET or REMOVE result. Call before /// fetching; the rows stay readable afterwards. - /// Keep the parent AsyncStatement alive until the transfer finishes; closing or + /// Keep the parent `AsyncStatement` alive until the transfer finishes; closing or /// collecting it stops the transfer. #[napi] pub async fn complete_volume_operation( diff --git a/src/volume.rs b/src/volume.rs index 4774a9f8..674a8d7a 100644 --- a/src/volume.rs +++ b/src/volume.rs @@ -1411,12 +1411,12 @@ mod tests { let mut future = Box::pin(state.complete(async { Ok(batch.clone()) }, &options, None)); tokio::select! { result = &mut future => panic!("unexpected early completion: {result:?}"), - _ = async { + sent = tokio::time::timeout(Duration::from_secs(10), async { loop { if server.received_requests().await.unwrap().len() >= if cancel { 2 } else { 1 } { break; } tokio::task::yield_now().await; } - } => {} + }) => sent.expect("storage request was not sent"), } if cancel { state.cancel();