From 52c59e1aebe68f58572995a70d3389ebb6382f3a Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Tue, 1 Dec 2026 00:05:05 +0000 Subject: [PATCH 01/43] feat(volume): complete Volume PUT, GET and REMOVE in the kernel core ResultStream::complete_volume_operation runs the storage transfer for a result the server marks as a Volume operation. Local paths, with symlinks resolved, must be inside the caller's allowed directories. Transfers use the session's connection, TLS and proxy settings without the SQL request deadline, follow redirects without turning a write into a GET, retry transient failures, and fail after HttpConfig::storage_read_timeout without progress. Co-authored-by: Isaac Signed-off-by: Aakash Saravanan --- .github/workflows/pr-checks.yml | 26 + CONNECTION_PARAMETERS.md | 3 +- Cargo.lock | 12 +- Cargo.toml | 6 +- NEXT_CHANGELOG.md | 7 + NOTICE | 5 + adbc/Cargo.lock | 11 +- adbc/NOTICE | 5 + napi/Cargo.lock | 39 + pyo3/Cargo.lock | 39 + src/client/http.rs | 27 +- src/client/mod.rs | 2 +- src/client/sea.rs | 1 + src/config.rs | 6 + src/kernel_error.rs | 33 + src/lib.rs | 4 +- src/reader/mod.rs | 2 + src/reader/post_processor/mod.rs | 1 + src/result_stream.rs | 65 +- src/session.rs | 14 + src/statement/executed.rs | 2 + src/statement/executed_async.rs | 42 +- src/statement/mutable.rs | 44 +- src/telemetry/statement.rs | 41 + src/types/sea.rs | 2 + src/volume.rs | 1311 ++++++++++++++++++++++++++++++ tests/v0_volume_wiremock.rs | 319 ++++++++ 27 files changed, 2033 insertions(+), 36 deletions(-) create mode 100644 src/volume.rs create mode 100644 tests/v0_volume_wiremock.rs diff --git a/.github/workflows/pr-checks.yml b/.github/workflows/pr-checks.yml index 2e6848a6..5f94bef8 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-public-package-proxies + 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 tests + shell: pwsh + run: cargo test --locked --lib volume::tests + c-abi: name: C ABI smoke test runs-on: diff --git a/CONNECTION_PARAMETERS.md b/CONNECTION_PARAMETERS.md index 6f421c57..769461c2 100644 --- a/CONNECTION_PARAMETERS.md +++ b/CONNECTION_PARAMETERS.md @@ -167,7 +167,8 @@ 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). Does not apply to Volume file transfers. | `120s` | +| `storage_read_timeout` | Volume file transfers fail after this long without progress; `None` sets no limit. | `Some(900s)` | | `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.lock b/Cargo.lock index bc909a3e..15476fdc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -824,7 +824,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -2146,7 +2146,7 @@ dependencies = [ "once_cell", "socket2", "tracing", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -2394,15 +2394,15 @@ dependencies = [ [[package]] name = "rustix" -version = "1.1.4" +version = "1.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" dependencies = [ "bitflags", "errno", "libc", "linux-raw-sys", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -2777,7 +2777,7 @@ dependencies = [ "getrandom 0.4.3", "once_cell", "rustix", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 14e1e80a..aea8296f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -105,13 +105,16 @@ lz4_flex = "0.14" # Random number generation (retry jitter) rand = "0.10" +# Temporary files for Volume GET downloads +tempfile = "3" + # Concurrent data structures dashmap = "6" moka = { version = "0.12.16", features = ["future"] } # Async utilities futures = "0.3" -tokio-util = "0.7" +tokio-util = { version = "0.7", features = ["io"] } async-trait = "0.1" # Error handling @@ -181,7 +184,6 @@ libc = "0.2" [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 1313dae0..effc2f2e 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -22,11 +22,18 @@ changes go in their respective binding's NEXT_CHANGELOG. if the host has credentials, a path, query or fragment. - `ProxyConfig.url`, the Rust ADBC driver's `adbc.databricks.proxy.url`, `HTTPS_PROXY` and `ALL_PROXY` accept SOCKS4 and SOCKS5 proxy URLs. +- Volume `PUT`, `GET` and `REMOVE`: `ResultStream::complete_volume_operation` + runs the file transfer for a result the server marks as a Volume operation. + Local paths, with symlinks resolved, must be inside the caller's allowed + directories. `HttpConfig::storage_read_timeout` limits how long a transfer + may go without progress (15 minutes by default). ### Changed - Proxy credentials are redacted from proxy URLs in errors, logs and `Debug` output. +- `Error` and `ResultManifest` have new public fields (`local_error`, + `is_volume_operation`). Code that builds them with struct literals must set them. ### Updated diff --git a/NOTICE b/NOTICE index cdc63bbf..1a5bb418 100644 --- a/NOTICE +++ b/NOTICE @@ -162,6 +162,11 @@ Project URL: https://github.com/jedisct1/rust-siphash Copyright: Copyright 2012-2016 The Rust Project Developers; Copyright 2016-2026 Frank Denis +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/Cargo.lock b/adbc/Cargo.lock index 64db58f1..31c75b01 100644 --- a/adbc/Cargo.lock +++ b/adbc/Cargo.lock @@ -692,6 +692,7 @@ dependencies = [ "serde", "serde_json", "sha2 0.11.1", + "tempfile", "thiserror 2.0.21", "tokio", "tokio-util", @@ -806,7 +807,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -2202,15 +2203,15 @@ dependencies = [ [[package]] name = "rustix" -version = "1.1.5" +version = "1.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" dependencies = [ "bitflags", "errno", "libc", "linux-raw-sys", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -2546,7 +2547,7 @@ dependencies = [ "getrandom 0.4.3", "once_cell", "rustix", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] diff --git a/adbc/NOTICE b/adbc/NOTICE index cdc63bbf..1a5bb418 100644 --- a/adbc/NOTICE +++ b/adbc/NOTICE @@ -162,6 +162,11 @@ Project URL: https://github.com/jedisct1/rust-siphash Copyright: Copyright 2012-2016 The Rust Project Developers; Copyright 2016-2026 Frank Denis +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/napi/Cargo.lock b/napi/Cargo.lock index dedcf797..c2eec113 100644 --- a/napi/Cargo.lock +++ b/napi/Cargo.lock @@ -647,6 +647,7 @@ dependencies = [ "serde", "serde_json", "sha2 0.11.0", + "tempfile", "thiserror 2.0.19", "tokio", "tokio-util", @@ -806,6 +807,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" @@ -1504,6 +1511,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" @@ -2211,6 +2224,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" @@ -2557,6 +2583,19 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7b2093cf4c8eb1e67749a6762251bc9cd836b6fc171623bd0a9d324d37af2417" +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.4.3", + "once_cell", + "rustix", + "windows-sys 0.61.2", +] + [[package]] name = "thiserror" version = "1.0.69" diff --git a/pyo3/Cargo.lock b/pyo3/Cargo.lock index 55bef07f..205684e9 100644 --- a/pyo3/Cargo.lock +++ b/pyo3/Cargo.lock @@ -643,6 +643,7 @@ dependencies = [ "serde", "serde_json", "sha2 0.11.0", + "tempfile", "thiserror 2.0.19", "tokio", "tokio-util", @@ -779,6 +780,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" @@ -1434,6 +1441,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" @@ -2123,6 +2136,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" @@ -2475,6 +2501,19 @@ version = "0.13.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "adb6935a6f5c20170eeceb1a3835a49e12e19d792f6dd344ccc76a985ca5a6ca" +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.4.3", + "once_cell", + "rustix", + "windows-sys 0.61.2", +] + [[package]] name = "thiserror" version = "1.0.69" diff --git a/src/client/http.rs b/src/client/http.rs index 1211e03e..7b8005e3 100644 --- a/src/client/http.rs +++ b/src/client/http.rs @@ -561,8 +561,14 @@ impl DatabricksHttpClient { let revocation = revocation.filter(|_| config.tls.allow_self_signed != Some(true)); // Follow redirects for normal traffic (reqwest's default policy). - let client = - Self::build_reqwest_client(&config, reqwest::redirect::Policy::default(), revocation)?; + // `read_timeout` is a historical name; reqwest applies it as the + // total deadline from connect through response-body completion. + let client = Self::build_reqwest_client( + &config, + reqwest::redirect::Policy::default(), + revocation, + 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 @@ -589,7 +595,8 @@ impl DatabricksHttpClient { }) } - /// Build a `reqwest::Client` from `config` with the given redirect policy. + /// Build a `reqwest::Client` from `config` with the given redirect policy + /// and total request timeout. /// /// Factored out of `new()` so tenant discovery can obtain a client that /// does NOT follow redirects (to read the first `/aad/auth` hop's @@ -599,16 +606,17 @@ impl DatabricksHttpClient { config: &HttpClientConfig, redirect: reqwest::redirect::Policy, revocation: Option, + timeout: Option, ) -> Result { check_revocation_support(&config.tls, revocation)?; 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) = timeout { + builder = builder.timeout(timeout); + } // Apply TLS configuration if config.tls.enabled == Some(false) { @@ -837,6 +845,12 @@ impl DatabricksHttpClient { .expect("Auth provider can only be set once"); } + /// Build the client for Volume storage requests: the session's connection + /// settings without a total deadline, and redirects left to the caller. + pub(crate) fn storage_client(config: &HttpClientConfig) -> Result { + Self::build_reqwest_client(config, reqwest::redirect::Policy::none(), None, None) + } + /// Returns the client configuration. pub fn config(&self) -> &HttpClientConfig { &self.config @@ -926,6 +940,7 @@ impl DatabricksHttpClient { &self.config, reqwest::redirect::Policy::none(), self.revocation, + 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/client/mod.rs b/src/client/mod.rs index 0edc69d2..65dff979 100644 --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -38,7 +38,7 @@ pub mod sea; pub(crate) mod tls_revocation; pub(crate) mod transport; -fn error_chain<'a>( +pub(crate) fn error_chain<'a>( error: &'a (dyn std::error::Error + 'static), ) -> impl Iterator { std::iter::successors(Some(error), |error| { diff --git a/src/client/sea.rs b/src/client/sea.rs index 42c58990..c9348305 100644 --- a/src/client/sea.rs +++ b/src/client/sea.rs @@ -2441,6 +2441,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/config.rs b/src/config.rs index ddea3ce1..004f8348 100644 --- a/src/config.rs +++ b/src/config.rs @@ -943,6 +943,11 @@ pub struct HttpConfig { /// applies, so connection establishment is bounded by the shorter limit. pub request_timeout: Duration, + /// Idle limit for Volume file transfers, which `request_timeout` does not + /// bound: a transfer fails after this long without progress. `None` sets + /// no limit. + pub storage_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, @@ -1022,6 +1027,7 @@ impl Default for HttpConfig { Self { sea_response_compression_enabled: false, request_timeout: Duration::from_secs(120), + storage_read_timeout: Some(Duration::from_secs(900)), overall_timeout: Duration::from_secs(900), pool_max_idle_per_host: 100, // Mirror `RetryConfig::default()` so a stock `HttpConfig` diff --git a/src/kernel_error.rs b/src/kernel_error.rs index ecfb7fb2..58d43cab 100644 --- a/src/kernel_error.rs +++ b/src/kernel_error.rs @@ -248,6 +248,33 @@ pub struct Error { /// Underlying cause. Boxed to keep the struct stack-friendly. pub cause: Option>, + + /// The OS error behind a failed local file operation. + pub local_error: Option>, +} + +/// The OS error behind a failed local file operation, for mapping to a +/// host-language file error. +#[non_exhaustive] +#[derive(Debug, Clone)] +pub struct LocalFileError { + pub raw_os_error: Option, + pub kind: std::io::ErrorKind, + 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 { @@ -270,6 +297,7 @@ impl Error { diagnostic_info: None, error_details_json: None, cause: None, + local_error: None, } } @@ -442,6 +470,11 @@ impl Error { self } + 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/lib.rs b/src/lib.rs index 9b5ebb50..3de15f70 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 @@ -161,6 +162,7 @@ pub use telemetry::DriverSystemConfiguration; /// pyo3 crates own. Not a supported API. #[doc(hidden)] pub use util::runtime::block_sigpipe_on_current_thread; +pub use volume::{VolumeCompletion, VolumeOptions}; // === Compile-time guarantees on auto-traits === // diff --git a/src/reader/mod.rs b/src/reader/mod.rs index 7f6be171..709ccaf3 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, @@ -2150,6 +2151,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..063f70af 100644 --- a/src/result_stream.rs +++ b/src/result_stream.rs @@ -493,6 +493,8 @@ pub struct ResultStream { close_guard: Option, telemetry: Option, + + volume: Option>, } struct ResultStreamTelemetry { @@ -608,6 +610,7 @@ impl ResultStream { exhausted: false, close_guard: None, telemetry: None, + volume: None, }) } @@ -642,6 +645,62 @@ impl ResultStream { self.telemetry = Some(ResultStreamTelemetry::new(telemetry)); } + pub(crate) fn attach_volume( + &mut self, + manifest: Option<&crate::types::sea::ResultManifest>, + volume: &Arc, + ) { + if manifest.is_some_and(|manifest| manifest.is_volume_operation) { + self.volume = Some(Arc::clone(volume)); + } + } + + pub(crate) fn cancel_volume(&self) { + if let Some(volume) = &self.volume { + volume.cancel(); + } + } + + /// 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() + } + + /// Runs the file transfer for a Volume PUT, GET or REMOVE result. Later + /// calls, including from other result streams of the same execution, + /// return the first outcome without transferring again. + /// + /// Call before reading rows; the instruction row stays readable. A GET + /// replaces the destination only after the download succeeds. A PUT of + /// caller-supplied bytes returns `NeedsInputStream` until called with + /// `input_bytes`. Cancelling stops the transfer but cannot undo a PUT or + /// REMOVE that storage already applied. + pub async fn complete_volume_operation( + &mut self, + options: &crate::volume::VolumeOptions, + input_bytes: Option>, + ) -> Result { + let Some(volume) = self.volume.clone() else { + return Ok(crate::volume::VolumeCompletion::NotVolume); + }; + if let Some(outcome) = volume.outcome() { + return outcome; + } + if self.current.is_some() { + return Err(Error::invalid_state() + .message("complete_volume_operation must be called before reading result rows")); + } + let instruction = self + .peek_first_batch() + .await + .map(|batch| batch.map(|ResultBatch::Arrow(batch)| batch.clone())); + let result = volume.complete(instruction, options, input_bytes).await; + if let Err(error) = &result { + self.finalize_telemetry(Some(error)); + } + result + } + fn reader_metrics(&self) -> Option { self.reader.as_ref().and_then(|reader| reader.metrics()) } @@ -788,10 +847,8 @@ impl ResultStream { /// /// 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. + /// stream. Only valid before any `next_batch` has run (it no-ops if a + /// batch is already current or buffered). 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/session.rs b/src/session.rs index bcc691a8..3191f3d6 100644 --- a/src/session.rs +++ b/src/session.rs @@ -97,6 +97,7 @@ pub(crate) struct SessionInner { /// behind the trait object; future variants slot in via /// `TransportMode`. transport: Arc, + storage: Arc, /// Server-issued session identifier. session_id: String, @@ -165,6 +166,10 @@ impl SessionInner { &self.transport } + pub(crate) fn new_volume_state(&self) -> Arc { + self.storage.transfer_state() + } + /// Crate-internal accessor for the server-issued session ID. pub(crate) fn session_id(&self) -> &str { &self.session_id @@ -226,6 +231,7 @@ impl SessionInner { /// explicit close genuinely *initiates* the delete rather than /// deferring it to an idle-timeout. pub(crate) fn initiate_delete(&self) { + self.storage.cancel_all(); if self .closed .compare_exchange( @@ -375,12 +381,18 @@ impl Session { crate::client::http::check_revocation_support(&http_client_config.tls, revocation)?; validate_revocation_endpoint_scheme(&config, revocation)?; let retry_configs = build_retry_configs_for_session(&config); + let storage_retry = retry_configs[&RequestCategory::Sea].clone(); let http_client = Arc::new( DatabricksHttpClient::with_revocation(http_client_config, retry_configs, revocation) .map_err(|e| { Error::network_error().message(format!("Failed to construct HTTP client: {e}")) })?, ); + let storage = Arc::new(crate::volume::Storage::new( + http_client.config().clone(), + storage_retry, + config.http.storage_read_timeout, + )); // 2. Auth provider — async because OAuth flows hit the OIDC // discovery endpoint. @@ -482,6 +494,7 @@ impl Session { Ok(Session { inner: Arc::new(SessionInner { transport, + storage, session_id: session_info.session_id, config, runtime_handle, @@ -788,6 +801,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.storage.cancel_all(); // 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..296878b1 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 diff --git a/src/statement/executed_async.rs b/src/statement/executed_async.rs index c5739c47..3c9dc945 100644 --- a/src/statement/executed_async.rs +++ b/src/statement/executed_async.rs @@ -224,6 +224,7 @@ pub struct ExecutedAsyncStatement { /// Take-once ownership avoids retaining raw payloads after reader construction. pending_result: std::sync::Mutex>, parameter_set_count: usize, + volume: Option>, statement_telemetry: StatementTelemetry, /// Set once result materialisation hands success finalization to /// the returned `ResultStream`. @@ -337,6 +338,7 @@ impl ExecutedAsyncStatement { latest_status: Arc::new(std::sync::Mutex::new(initial_status)), pending_result: std::sync::Mutex::new(None), parameter_set_count: 0, + volume: None, statement_telemetry, result_stream_owns_success_telemetry: AtomicBool::new(false), client_deadline, @@ -351,6 +353,17 @@ impl ExecutedAsyncStatement { self } + pub(crate) fn with_volume(mut self, volume: Option>) -> Self { + self.volume = volume; + self + } + + fn cancel_volume(&self) { + if let Some(volume) = self.volume.as_ref().filter(|_| self.owning) { + volume.cancel(); + } + } + /// Crate-internal constructor for a **non-owning** (read-only /// adopt) handle, built by /// [`Session::attach_async_statement`](crate::Session::attach_async_statement). @@ -403,6 +416,7 @@ impl ExecutedAsyncStatement { latest_status: Arc::new(std::sync::Mutex::new(initial_status)), pending_result: std::sync::Mutex::new(None), parameter_set_count: 0, + volume: None, statement_telemetry: StatementTelemetry::noop(), result_stream_owns_success_telemetry: AtomicBool::new(false), client_deadline: None, @@ -430,7 +444,8 @@ impl ExecutedAsyncStatement { self.session_attribution, status, ) - .with_parameter_set_count(self.parameter_set_count), + .with_parameter_set_count(self.parameter_set_count) + .with_volume(self.volume.clone()), }) } @@ -1006,6 +1021,9 @@ impl ExecutedAsyncStatement { } let mut stream = ResultStream::from_reader(result.reader).await?; stream.attach_telemetry(self.statement_telemetry.clone()); + if let Some(volume) = &self.volume { + stream.attach_volume(result.manifest.as_ref(), volume); + } // SEA carries no row count on the async status either; for a // DML the count rides in the result set. Derive it once // (non-consuming) and record it onto the latest status so @@ -1149,6 +1167,7 @@ impl ExecutedStatementHandle for ExecutedAsyncStatement { } async fn cancel(&self) -> Result<()> { + self.cancel_volume(); async { self.valid.check()?; // A non-owning (attached) handle must not cancel a statement @@ -1191,6 +1210,7 @@ impl ExecutedAsyncStatement { } async fn close_server_statement(&self) -> Result<()> { + self.cancel_volume(); if self.owning { self.owner_released.store(true, Ordering::Release); self.clear_pending_result(); @@ -1252,20 +1272,21 @@ impl ExecutedAsyncStatement { // either — otherwise the footgun just moves to the detached // canceller. owning: self.owning, + volume: self.volume.clone().filter(|_| self.owning), } } } /// Detached canceller for an in-flight async statement. /// -/// Holds only the shared session handle, the statement id, and the -/// shared [`ValidityFlag`] — **not** the [`ExecutedAsyncStatement`] +/// Holds only the shared session handle, the statement id, the shared +/// [`ValidityFlag`] and the Volume transfer state — **not** the [`ExecutedAsyncStatement`] /// itself — so a binding can fire a server-side cancel while the handle /// is borrowed elsewhere (e.g. parked inside a long-running /// [`ExecutedAsyncStatement::await_result`] that a binding-side lock is /// held across). Produced by [`ExecutedAsyncStatement::canceller`]. /// -/// Cheap to [`Clone`] (one `Arc` bump plus a `String` / flag clone). +/// Cheap to [`Clone`] (`Arc` bumps plus a `String` / flag clone). #[derive(Clone)] pub struct AsyncStatementCanceller { session: Arc, @@ -1276,9 +1297,17 @@ pub struct AsyncStatementCanceller { /// cancel a statement it doesn't own. See /// [`ExecutedAsyncStatement::owning`]. owning: bool, + volume: Option>, } impl AsyncStatementCanceller { + /// Stops a running Volume transfer without a server request. + pub fn cancel_volume_operation(&self) { + if let Some(volume) = &self.volume { + volume.cancel(); + } + } + /// Server-side cancel via `cancel_statement(statement_id)`. /// /// Short-circuits to `InvalidStatementHandle` (no wire round-trip) @@ -1288,8 +1317,10 @@ impl AsyncStatementCanceller { /// there. Byte-for-byte the same operation as /// [`ExecutedAsyncStatement::cancel`]; the two share no mutable /// state, so this can run concurrently with an in-flight - /// `await_result` on the same statement. + /// `await_result` on the same statement. A running Volume transfer + /// stops too, even after the parent `Statement` is dropped. pub async fn cancel(&self) -> Result<()> { + self.cancel_volume_operation(); async { self.valid.check()?; if !self.owning { @@ -1316,6 +1347,7 @@ impl AsyncStatementCanceller { impl Drop for ExecutedAsyncStatement { fn drop(&mut self) { + self.cancel_volume(); if self.owning { self.owner_released.store(true, Ordering::Release); self.clear_pending_result(); diff --git a/src/statement/mutable.rs b/src/statement/mutable.rs index c1130b7e..304d22d4 100644 --- a/src/statement/mutable.rs +++ b/src/statement/mutable.rs @@ -103,6 +103,8 @@ pub enum DirectStatement { /// the binding's `block_on` runs the execute future to completion. type InflightId = Arc>>; +type VolumeSlot = Arc>>; + /// Resolve the SEA `(wait_timeout, on_wait_timeout)` pair for an execute / /// submit dispatch. Pure so the precedence rules are unit-testable without /// a live `Session`. @@ -305,12 +307,16 @@ 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 execution. + volume: VolumeSlot, } 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 = Arc::new(Mutex::new(session.new_volume_state())); Self { session, spec: StatementSpec::new(), @@ -318,6 +324,7 @@ impl Statement { last_valid: None, last_closed: None, inflight_id: Arc::new(Mutex::new(None)), + volume, } } @@ -334,7 +341,7 @@ impl Statement { /// once the server issues the statement id mid-execute, the /// canceller's [`cancel`](StatementCanceller::cancel) reaches it. /// - /// Cheap to clone (two `Arc` bumps). If `cancel()` fires before the + /// Cheap to clone (three `Arc` bumps). If `cancel()` fires before the /// id is observed (query still in the initial submit round-trip) it /// is a no-op; the per-call drop guard still covers the /// future-dropped case. @@ -342,6 +349,7 @@ impl Statement { StatementCanceller { session: Arc::clone(&self.session), inflight_id: Arc::clone(&self.inflight_id), + volume: Arc::clone(&self.volume), } } @@ -472,6 +480,7 @@ impl Statement { let mut result_stream = ResultStream::from_reader(result.reader).await?; result_stream.attach_telemetry(telemetry_for_body.clone()); + result_stream.attach_volume(result.manifest.as_ref(), &self.current_volume()); // 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 // already supply `num_modified_rows`, derive it from that @@ -619,7 +628,8 @@ impl Statement { telemetry_for_body, timeout, ) - .with_parameter_set_count(exec_params.parameter_sets.len())) + .with_parameter_set_count(exec_params.parameter_sets.len()) + .with_volume(Some(self.current_volume()))) } .instrument(span) .await; @@ -717,6 +727,7 @@ impl Statement { self.last_closed = Some(Arc::clone(&closed)); let mut result_stream = ResultStream::from_reader(result.reader).await?; result_stream.attach_telemetry(telemetry_for_body.clone()); + result_stream.attach_volume(result.manifest.as_ref(), &self.current_volume()); let mut status = result.status; let parameter_set_count = exec_params.parameter_sets.len(); // Optional count reads must not turn a successful write into an execute error. @@ -768,7 +779,8 @@ impl Statement { telemetry_for_body, ExecutionTimeout::Default, ) - .with_parameter_set_count(exec_params.parameter_sets.len()), + .with_parameter_set_count(exec_params.parameter_sets.len()) + .with_volume(Some(self.current_volume())), )) } } @@ -825,6 +837,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.current_volume().cancel(); let span = self.session.log_span().clone(); async { self.invalidate_prior().await; @@ -875,10 +888,20 @@ impl Statement { /// by [`Statement::close`], where the slot must survive so a detached /// canceller can still dispatch against the just-closed statement (its /// cloned session `Arc` keeps the client side alive). + /// + /// Also installs a fresh Volume transfer state, stopping the previous + /// execution's transfer. fn reset_inflight_slot(&self) { if let Ok(mut slot) = self.inflight_id.lock() { *slot = None; } + let mut volume = self.volume.lock().unwrap_or_else(|e| e.into_inner()); + volume.cancel(); + *volume = self.session.new_volume_state(); + } + + fn current_volume(&self) -> Arc { + Arc::clone(&self.volume.lock().unwrap_or_else(|e| e.into_inner())) } /// Auto-close any prior executed handle this `Statement` produced. @@ -1024,14 +1047,23 @@ impl Drop for MidExecuteCancelGuard { /// is blocked. The sync-execute analogue of /// [`AsyncStatementCanceller`](crate::statement::executed_async::AsyncStatementCanceller). /// -/// Cheap to [`Clone`] (two `Arc` bumps). +/// Cheap to [`Clone`] (three `Arc` bumps). #[derive(Clone)] pub struct StatementCanceller { session: Arc, inflight_id: InflightId, + volume: VolumeSlot, } impl StatementCanceller { + /// Stops a running Volume transfer without 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)`. /// @@ -1054,8 +1086,10 @@ 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. A running Volume transfer stops too. pub async fn cancel(&self) -> Result { + 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/telemetry/statement.rs b/src/telemetry/statement.rs index 88b62b75..88b4fe1b 100644 --- a/src/telemetry/statement.rs +++ b/src/telemetry/statement.rs @@ -373,6 +373,47 @@ mod tests { } } + #[tokio::test] + async fn failed_volume_completion_finalizes_statement_with_error() { + let connection = Arc::new(CapturingConnectionTelemetry::default()); + let telemetry = StatementTelemetry::new( + connection.clone(), + StatementType::Sql, + OperationType::ExecuteStatement, + ); + let batch = RecordBatch::try_from_iter([( + "n", + Arc::new(arrow_array::Int64Array::from(vec![1])) as arrow_array::ArrayRef, + )]) + .unwrap(); + let reader = crate::reader::test_utils::MockReader::new(vec![batch]); + let mut stream = ResultStream::from_reader(Box::new(reader)).await.unwrap(); + stream.attach_telemetry(telemetry); + let manifest: crate::types::sea::ResultManifest = + serde_json::from_value(serde_json::json!({ + "is_volume_operation": true, + "format": "ARROW_STREAM", + "schema": {"column_count": 1, "columns": []}, + })) + .unwrap(); + let storage = Arc::new(crate::volume::Storage::new( + Default::default(), + Default::default(), + None, + )); + stream.attach_volume(Some(&manifest), &storage.transfer_state()); + let error = stream + .complete_volume_operation(&Default::default(), None) + .await + .unwrap_err(); + + drop(stream); + + let events = connection.statement_events.lock().expect("events mutex"); + assert_eq!(events.len(), 1); + assert_eq!(events[0].error_code, Some(error.code)); + } + #[tokio::test] async fn peek_first_batch_error_finalizes_statement_with_error_before_drop() { let connection = Arc::new(CapturingConnectionTelemetry::default()); diff --git a/src/types/sea.rs b/src/types/sea.rs index 32e18c62..2dd34b85 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..1626a1a0 --- /dev/null +++ b/src/volume.rs @@ -0,0 +1,1311 @@ +// 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 PUT, GET and REMOVE file transfers. +//! +//! The server answers these statements with one row holding a presigned +//! storage URL, request headers and a local path. This module makes the +//! storage request that row describes. + +use crate::client::http::{DatabricksHttpClient, HttpClientConfig}; +use crate::client::retry::{calculate_backoff, RequestType, RetryConfig, RetryStrategy}; +use crate::kernel_error::{Error, LocalFileError, Result}; +use arrow_array::cast::AsArray; +use arrow_array::{Array, ArrayRef, RecordBatch}; +use arrow_schema::DataType; +use futures::TryStreamExt; +use reqwest::header::{ + HeaderMap, HeaderName, HeaderValue, AUTHORIZATION, CONTENT_LENGTH, COOKIE, LOCATION, + PROXY_AUTHORIZATION, RETRY_AFTER, +}; +use reqwest::{Client, Method, Response, StatusCode, Url}; +use std::io::{Read, Seek}; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::time::{Duration, Instant}; +use tokio::io::{AsyncSeekExt, AsyncWriteExt}; +use tokio::sync::{watch, OnceCell}; +use tokio_util::bytes::Bytes; +use tokio_util::io::ReaderStream; +use tokio_util::sync::CancellationToken; + +const MAX_REDIRECTS: usize = 10; +const ERROR_BODY_LIMIT: usize = 4096; + +/// Caller settings for a Volume file transfer. +#[non_exhaustive] +#[derive(Debug, Clone, Default)] +pub struct VolumeOptions { + /// Directories a PUT may read from and a GET may write to. The local path, + /// with symlinks resolved, must be inside one of them. + pub allowed_paths: Vec, + /// Report success when REMOVE targets an object that does not exist. + pub remove_not_found_is_success: bool, +} + +impl VolumeOptions { + pub fn new(allowed_paths: Vec, remove_not_found_is_success: bool) -> Self { + Self { + allowed_paths, + remove_not_found_is_success, + } + } +} + +/// Outcome of [`ResultStream::complete_volume_operation`](crate::ResultStream::complete_volume_operation). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[repr(C)] +pub enum VolumeCompletion { + /// The result is not a Volume operation; nothing was done. + NotVolume = 0, + /// The PUT uploads caller-supplied bytes; call again with them. + NeedsInputStream = 1, + /// The transfer finished. + Completed = 2, +} + +/// Storage access shared by a session's Volume transfers. +pub(crate) struct Storage { + config: HttpClientConfig, + client: OnceCell, + retry: RetryConfig, + idle_limit: Option, + cancellation: CancellationToken, +} + +impl Storage { + pub(crate) fn new( + config: HttpClientConfig, + retry: RetryConfig, + idle_limit: Option, + ) -> Self { + Self { + config, + client: OnceCell::new(), + retry, + idle_limit, + cancellation: CancellationToken::new(), + } + } + + /// State for one execution's transfer. + pub(crate) fn transfer_state(self: &Arc) -> Arc { + Arc::new(VolumeState { + storage: Arc::clone(self), + cancellation: self.cancellation.child_token(), + outcome: OnceCell::new(), + }) + } + + /// Stops every transfer of the session. + pub(crate) fn cancel_all(&self) { + self.cancellation.cancel(); + } + + async fn client(&self) -> Result<&Client> { + self.client + .get_or_try_init(|| async { DatabricksHttpClient::storage_client(&self.config) }) + .await + } +} + +/// One execution's transfer. Every result stream of the execution shares it, +/// so the transfer runs at most once. +pub(crate) struct VolumeState { + storage: Arc, + cancellation: CancellationToken, + outcome: OnceCell>, +} + +impl VolumeState { + pub(crate) fn cancel(&self) { + self.cancellation.cancel(); + } + + pub(crate) fn outcome(&self) -> Option> { + self.outcome.get().cloned() + } + + pub(crate) async fn complete( + &self, + instruction: Result>, + options: &VolumeOptions, + input_bytes: Option>, + ) -> Result { + let outcome = self + .outcome + .get_or_try_init(|| async { + let transfer = async { + let batch = + instruction?.ok_or_else(|| invalid("Missing Volume instruction row"))?; + let instruction = Instruction::decode(&batch)?; + if matches!(instruction.operation, Operation::Put(None)) + && input_bytes.is_none() + { + return Ok(VolumeCompletion::NeedsInputStream); + } + self.transfer(instruction, options, input_bytes).await?; + Ok(VolumeCompletion::Completed) + }; + let result = tokio::select! { + biased; + _ = self.cancellation.cancelled() => Err(cancelled()), + result = transfer => result, + }; + match result { + // Not cached, so the caller can call again with the bytes. + Ok(VolumeCompletion::NeedsInputStream) => Err(()), + result => Ok(result), + } + }) + .await; + match outcome { + Ok(outcome) => outcome.clone(), + Err(()) => Ok(VolumeCompletion::NeedsInputStream), + } + } + + async fn transfer( + &self, + instruction: Instruction, + options: &VolumeOptions, + input_bytes: Option>, + ) -> Result<()> { + let local = prepare( + instruction.operation.clone(), + options.allowed_paths.clone(), + input_bytes, + ) + .await?; + let client = self.storage.client().await?; + let retry = &self.storage.retry; + let strategy = RetryStrategy::for_request(RequestType::CloudFetchDownload, retry); + let mut first_failure = None; + let mut attempt = 0; + loop { + let (error, retry_after) = match self + .attempt(client, &instruction, &local, options, &strategy) + .await + { + Ok(()) => return local.publish().await, + Err(failure) => failure, + }; + let wait = calculate_backoff(retry, attempt, retry_after.as_deref()); + let waited = first_failure.get_or_insert_with(Instant::now).elapsed(); + if !error.retryable + || attempt >= retry.max_retries + || waited.saturating_add(wait) > retry.overall_timeout + { + return Err(error); + } + crate::klog::debug!( + attempt = attempt + 1, + wait_ms = wait.as_millis() as u64, + error = %error.message, + "retrying Volume storage request" + ); + tokio::time::sleep(wait).await; + attempt += 1; + } + } + + /// One storage request, following redirects. A failure carries the + /// response's `Retry-After` value. + async fn attempt( + &self, + client: &Client, + instruction: &Instruction, + local: &Local, + options: &VolumeOptions, + strategy: &RetryStrategy, + ) -> std::result::Result<(), (Error, Option)> { + let method = local.method(); + let mut url = Url::parse(&instruction.url) + .map_err(|_| (invalid("Invalid Volume storage URL"), None))?; + let mut headers = instruction.headers.clone(); + for _ in 0..=MAX_REDIRECTS { + let (progress, mut progressed) = watch::channel(()); + let mut request = client + .request(method.clone(), url.clone()) + .headers(headers.clone()); + if let Some((body, length)) = local.body(progress).await.map_err(|e| (e, None))? { + request = request.header(CONTENT_LENGTH, length).body(body); + } + let response = self + .idle_bounded(&mut progressed, async { + request.send().await.map_err(|e| storage_error(e, strategy)) + }) + .await + .map_err(|e| (e, None))?; + let location = response.headers().get(LOCATION); + if let Some(next) = redirect_target(response.status(), location, &url, &method) + .map_err(|e| (e, None))? + { + if next.host_str() != url.host_str() { + for name in [AUTHORIZATION, COOKIE, PROXY_AUTHORIZATION] { + headers.remove(name); + } + } + url = next; + continue; + } + let status = response.status(); + if status.is_success() + || (method == Method::DELETE + && status == StatusCode::NOT_FOUND + && options.remove_not_found_is_success) + { + return self + .receive(response, local, strategy) + .await + .map_err(|e| (e, None)); + } + return Err(self.http_failure(response, strategy).await); + } + Err(( + network("Volume storage request was redirected too many times"), + None, + )) + } + + /// Writes a GET response body to the download's temporary file. + async fn receive( + &self, + mut response: Response, + local: &Local, + strategy: &RetryStrategy, + ) -> Result<()> { + let Local::Download(download) = local else { + return Ok(()); + }; + let local_error = |e| local_error(e, &download.name); + let mut file = tokio::fs::File::from_std(download.temp.try_clone().map_err(local_error)?); + file.set_len(0).await.map_err(local_error)?; + file.rewind().await.map_err(local_error)?; + let (_, mut no_progress) = watch::channel(()); + while let Some(chunk) = self + .idle_bounded(&mut no_progress, async { + response + .chunk() + .await + .map_err(|e| storage_error(e, strategy)) + }) + .await? + { + file.write_all(&chunk).await.map_err(local_error)?; + } + file.flush().await.map_err(local_error) + } + + async fn http_failure( + &self, + mut response: Response, + strategy: &RetryStrategy, + ) -> (Error, Option) { + let status = response.status(); + let retry_after = response + .headers() + .get(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(strategy.is_retryable_status(status, retry_after.is_some())) + .message(format!( + "Volume storage request failed: HTTP {}", + status.as_u16() + )); + 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}")); + } + } + let (_, mut no_progress) = watch::channel(()); + let mut body = Vec::new(); + while body.len() < ERROR_BODY_LIMIT { + match self + .idle_bounded(&mut no_progress, async { + response + .chunk() + .await + .map_err(|e| storage_error(e, strategy)) + }) + .await + { + Ok(Some(chunk)) => body.extend_from_slice(&chunk), + _ => break, + } + } + let body = String::from_utf8_lossy(&body); + for tag in ["Code", "Message"] { + if let Some(value) = xml_value(&body, tag) { + error = error.message(format!("{tag}: {value}")); + } + } + (error, retry_after) + } + + /// Runs `work`, failing once the idle limit passes without `progress` changing. + async fn idle_bounded( + &self, + progress: &mut watch::Receiver<()>, + work: impl std::future::Future>, + ) -> Result { + let Some(limit) = self.storage.idle_limit else { + return work.await; + }; + tokio::pin!(work); + loop { + tokio::select! { + result = &mut work => return result, + Ok(()) = progress.changed() => {} + () = tokio::time::sleep(limit) => { + return Err(network(format!( + "Volume storage transfer made no progress for {} seconds", + limit.as_secs_f64() + )) + .with_retryable(true)); + } + } + } + } +} + +#[derive(Clone)] +enum Operation { + /// `None` uploads caller-supplied bytes. + Put(Option), + Get(PathBuf), + Remove, +} + +struct Instruction { + operation: Operation, + url: String, + headers: HeaderMap, +} + +impl Instruction { + fn decode(batch: &RecordBatch) -> Result { + if batch.num_rows() != 1 { + return Err(invalid("Expected one Volume instruction row")); + } + let column = |name: &str| { + batch + .column_by_name(name) + .ok_or_else(|| invalid(&format!("Missing Volume instruction column {name}"))) + }; + let text = |name: &str| { + string_value(column(name)?)? + .ok_or_else(|| invalid(&format!("Missing Volume instruction field {name}"))) + }; + let local_path = || match text("localFile")? { + path if path.is_empty() => Err(invalid("Missing Volume instruction field localFile")), + path => Ok(PathBuf::from(path)), + }; + let operation = match text("operation")?.to_ascii_uppercase().as_str() { + "PUT" if text("localFile")? == "__input_stream__" => Operation::Put(None), + "PUT" => Operation::Put(Some(local_path()?)), + "GET" => Operation::Get(local_path()?), + "REMOVE" => Operation::Remove, + _ => return Err(invalid("Unsupported Volume operation")), + }; + Ok(Self { + operation, + url: text("presignedUrl")?, + headers: headers(column("headers")?)?, + }) + } +} + +fn string_value(column: &ArrayRef) -> Result> { + Ok(strings(column)?.into_iter().next().flatten()) +} + +fn strings(column: &ArrayRef) -> Result>> { + let column = arrow_cast::cast(column, &DataType::Utf8) + .map_err(|_| invalid("Invalid Volume instruction column type"))?; + Ok(column + .as_string::() + .iter() + .map(|value| value.map(str::to_owned)) + .collect()) +} + +/// Storage headers arrive as a map or as a JSON object. +fn headers(column: &ArrayRef) -> Result { + let pairs: Vec<(String, String)> = if column.is_null(0) { + Vec::new() + } else if let Some(map) = column.as_map_opt() { + let entries = map.value(0); + strings(entries.column(0))? + .into_iter() + .zip(strings(entries.column(1))?) + .map(|pair| match pair { + (Some(name), Some(value)) => Ok((name, value)), + _ => Err(invalid("Invalid Volume storage headers")), + }) + .collect::>()? + } else { + let text = string_value(column)?.unwrap_or_default(); + serde_json::from_str::>(&text) + .map_err(|_| invalid("Invalid Volume storage headers"))? + .into_iter() + .collect() + }; + let mut headers = HeaderMap::new(); + for (name, value) in pairs { + headers.insert( + HeaderName::from_bytes(name.as_bytes()) + .map_err(|_| invalid("Invalid Volume storage header name"))?, + HeaderValue::from_str(&value) + .map_err(|_| invalid("Invalid Volume storage header value"))?, + ); + } + Ok(headers) +} + +/// The local side of a transfer, prepared before the first storage request. +enum Local { + Upload(Upload), + Download(Download), + Remove, +} + +enum Upload { + /// Reopened for each request. + File { + path: PathBuf, + length: u64, + name: String, + }, + Bytes(Bytes), +} + +/// A GET downloads to `temp` and copies it to `path` only after success, so a +/// failed download leaves an existing file unchanged. +struct Download { + temp: std::fs::File, + existing: Option, + path: PathBuf, + name: String, +} + +async fn prepare( + operation: Operation, + roots: Vec, + input_bytes: Option>, +) -> Result { + tokio::task::spawn_blocking(move || match operation { + Operation::Put(None) => Ok(Local::Upload(Upload::Bytes( + input_bytes.unwrap_or_default().into(), + ))), + Operation::Put(Some(requested)) => { + let path = allowed_path(&requested, &roots)?; + let name = requested.to_string_lossy().into_owned(); + let local_error = |e| local_error(e, &name); + let mut file = std::fs::File::open(&path).map_err(local_error)?; + let metadata = file.metadata().map_err(local_error)?; + if metadata.is_file() && metadata.len() > 0 { + return Ok(Local::Upload(Upload::File { + path, + length: metadata.len(), + name, + })); + } + // Pipes and files such as procfs entries report no usable size. + let mut bytes = Vec::new(); + file.read_to_end(&mut bytes).map_err(local_error)?; + Ok(Local::Upload(Upload::Bytes(bytes.into()))) + } + Operation::Get(requested) => { + let path = allowed_path(&requested, &roots)?; + let name = requested.to_string_lossy().into_owned(); + let local_error = |e| local_error(e, &name); + 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)), + }; + let parent = path + .parent() + .ok_or_else(|| invalid("Invalid Volume local file"))?; + let temp = match tempfile::tempfile_in(parent) { + Err(error) + if error.kind() == std::io::ErrorKind::PermissionDenied + && existing.is_some() => + { + tempfile::tempfile() + } + temp => temp, + } + .map_err(local_error)?; + Ok(Local::Download(Download { + temp, + existing, + path, + name, + })) + } + Operation::Remove => Ok(Local::Remove), + }) + .await + .map_err(|e| Error::internal().message(format!("Volume file preparation failed: {e}")))? +} + +impl Local { + fn method(&self) -> Method { + match self { + Local::Upload(_) => Method::PUT, + Local::Download(_) => Method::GET, + Local::Remove => Method::DELETE, + } + } + + async fn body(&self, progress: watch::Sender<()>) -> Result> { + match self { + Local::Upload(Upload::File { path, length, name }) => { + let file = tokio::fs::File::open(path) + .await + .map_err(|e| local_error(e, name))?; + let name = name.clone(); + let stream = ReaderStream::new(file) + .inspect_ok(move |_| { + progress.send_replace(()); + }) + .map_err(move |e| local_error(e, &name)); + Ok(Some((reqwest::Body::wrap_stream(stream), *length))) + } + Local::Upload(Upload::Bytes(bytes)) => Ok(Some(( + reqwest::Body::from(bytes.clone()), + bytes.len() as u64, + ))), + Local::Download(_) | Local::Remove => Ok(None), + } + } + + async fn publish(self) -> Result<()> { + let Local::Download(Download { + mut temp, + existing, + path, + name, + }) = self + else { + return Ok(()); + }; + tokio::task::spawn_blocking(move || { + let local_error = |e| local_error(e, &name); + let mut file = match existing { + Some(file) => file, + None => std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(&path) + .map_err(local_error)?, + }; + temp.rewind().map_err(local_error)?; + let length = std::io::copy(&mut temp, &mut file).map_err(local_error)?; + if file.metadata().map_err(local_error)?.is_file() { + file.set_len(length).map_err(local_error)?; + } + Ok(()) + }) + .await + .map_err(|e| Error::internal().message(format!("Volume download copy failed: {e}")))? + } +} + +/// The URL to follow when a response is a redirect the request should take. +fn redirect_target( + status: StatusCode, + location: Option<&HeaderValue>, + url: &Url, + method: &Method, +) -> Result> { + let follow = match status { + StatusCode::MOVED_PERMANENTLY + | StatusCode::FOUND + | StatusCode::TEMPORARY_REDIRECT + | StatusCode::PERMANENT_REDIRECT => true, + // A 303 asks for a GET, which would not upload or delete anything. + StatusCode::SEE_OTHER => method == Method::GET, + _ => false, + }; + let Some(location) = location.filter(|_| follow) else { + return Ok(None); + }; + let next = location + .to_str() + .ok() + .and_then(|location| url.join(location).ok()) + .ok_or_else(|| network("Volume storage redirect has an invalid location"))?; + if url.scheme() == "https" && next.scheme() != "https" { + return Err(network( + "Volume storage redirect cannot downgrade HTTPS to HTTP", + )); + } + Ok(Some(next)) +} + +fn xml_value<'a>(body: &'a str, tag: &str) -> Option<&'a str> { + let (_, rest) = body.split_once(&format!("<{tag}>"))?; + let (value, _) = rest.split_once(&format!(""))?; + (!value.contains(['<', '>'])).then_some(value) +} + +/// The requested path with symlinks resolved, if it is inside an allowed root. +fn allowed_path(requested: &Path, roots: &[PathBuf]) -> Result { + let name = requested.to_string_lossy(); + let path = resolve(requested).map_err(|e| local_error(e, &name))?; + if roots + .iter() + .filter(|root| !root.as_os_str().is_empty()) + .filter_map(|root| resolve(root).ok()) + .any(|root| path.starts_with(root)) + { + Ok(path) + } else { + Err(Error::invalid_argument() + .with_error_code("VOLUME_PATH_NOT_ALLOWED") + .message(format!( + "Local file path is outside the configured allowed roots: {name}" + ))) + } +} + +/// `path` made absolute with symlinks resolved. Trailing components that do +/// not exist yet are kept as written; a dangling symlink is an error. +fn resolve(path: &Path) -> std::io::Result { + let absolute = std::path::absolute(path)?; + let mut existing = absolute.as_path(); + let mut missing = Vec::new(); + loop { + match existing.canonicalize() { + Ok(resolved) => { + return Ok(missing + .iter() + .rev() + .fold(resolved, |path, name| path.join(name))) + } + Err(error) + if error.kind() == std::io::ErrorKind::NotFound + && existing.symlink_metadata().is_err() => + { + match (existing.parent(), existing.file_name()) { + (Some(parent), Some(name)) => { + missing.push(name); + existing = parent; + } + _ => return Err(error), + } + } + Err(error) => return Err(error), + } + } +} + +fn invalid(message: &str) -> Error { + Error::invalid_argument() + .with_error_code("VOLUME_INVALID_INSTRUCTION") + .message(message) +} + +fn cancelled() -> Error { + Error::cancelled().message("Volume transfer was cancelled") +} + +fn network(message: impl AsRef) -> Error { + Error::network_error() + .with_error_code("VOLUME_STORAGE_NETWORK_ERROR") + .message(message) +} + +fn storage_error(error: reqwest::Error, strategy: &RetryStrategy) -> Error { + // The upload body reports a failed read of the local source as a local error. + if let Some(local) = + crate::client::error_chain(&error).find_map(|cause| cause.downcast_ref::()) + { + return local.clone(); + } + let retryable = error.is_body() || error.is_decode() || strategy.is_retryable_error(&error); + // The URL is presigned; it must not reach the message. + let error = error.without_url(); + let mut causes = crate::client::error_chain(&error) + .map(ToString::to_string) + .collect::>(); + causes.dedup(); + network(format!( + "Volume storage request failed: {}", + causes.join(": ") + )) + .with_retryable(retryable) +} + +fn local_error(error: std::io::Error, path: &str) -> Error { + 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}")) + .with_local_error(LocalFileError::new( + error.raw_os_error(), + error.kind(), + path, + )) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::ErrorCode; + use arrow_array::builder::{MapBuilder, StringBuilder}; + use arrow_array::StringArray; + use tokio::io::AsyncReadExt; + use wiremock::matchers::{body_bytes, header, method, path}; + use wiremock::{Mock, MockServer, ResponseTemplate}; + + fn state(max_retries: u32, idle_limit: Option) -> Arc { + let retry = RetryConfig { + max_retries, + min_wait: Duration::ZERO, + max_wait: Duration::ZERO, + ..Default::default() + }; + Arc::new(Storage::new(HttpClientConfig::default(), retry, idle_limit)).transfer_state() + } + + fn instruction(operation: &str, url: &str, local: &Path) -> RecordBatch { + RecordBatch::try_from_iter([ + ( + "operation", + Arc::new(StringArray::from(vec![operation])) as ArrayRef, + ), + ("presignedUrl", Arc::new(StringArray::from(vec![url])) as _), + ( + "headers", + Arc::new(StringArray::from(vec![r#"{"x-test":"yes"}"#])) as _, + ), + ( + "localFile", + Arc::new(StringArray::from(vec![local.to_str().unwrap()])) as _, + ), + ]) + .unwrap() + } + + async fn run( + state: &VolumeState, + batch: RecordBatch, + root: &Path, + input_bytes: Option>, + ) -> Result { + let options = VolumeOptions::new(vec![root.to_owned()], false); + state.complete(Ok(Some(batch)), &options, input_bytes).await + } + + #[tokio::test] + async fn put_get_and_remove_move_exact_bytes() { + let payload = b"\0\xffvolume bytes".to_vec(); + let server = MockServer::start().await; + Mock::given(method("PUT")) + .and(path("/put")) + .and(header("x-test", "yes")) + .and(header("content-length", payload.len().to_string().as_str())) + .and(body_bytes(payload.clone())) + .respond_with(ResponseTemplate::new(200)) + .expect(2) + .mount(&server) + .await; + Mock::given(method("GET")) + .and(path("/get")) + .respond_with(ResponseTemplate::new(200).set_body_bytes(payload.clone())) + .expect(1) + .mount(&server) + .await; + Mock::given(method("DELETE")) + .and(path("/remove")) + .respond_with(ResponseTemplate::new(200)) + .expect(1) + .mount(&server) + .await; + let dir = tempfile::tempdir().unwrap(); + let source = dir.path().join("source"); + std::fs::write(&source, &payload).unwrap(); + let destination = dir.path().join("destination"); + std::fs::write(&destination, b"an older and longer file").unwrap(); + let url = |name: &str| format!("{}/{name}", server.uri()); + + let put = instruction("PUT", &url("put"), &source); + assert_eq!( + run(&state(0, None), put, dir.path(), None).await.unwrap(), + VolumeCompletion::Completed + ); + let stream_put = state(0, None); + let put = instruction("PUT", &url("put"), Path::new("__input_stream__")); + assert_eq!( + run(&stream_put, put.clone(), dir.path(), None) + .await + .unwrap(), + VolumeCompletion::NeedsInputStream + ); + assert_eq!( + run(&stream_put, put, dir.path(), Some(payload.clone())) + .await + .unwrap(), + VolumeCompletion::Completed + ); + let get = instruction("GET", &url("get"), &destination); + run(&state(0, None), get, dir.path(), None).await.unwrap(); + assert_eq!(std::fs::read(&destination).unwrap(), payload); + let remove = instruction("REMOVE", &url("remove"), Path::new("")); + run(&state(0, None), remove, dir.path(), None) + .await + .unwrap(); + } + + #[tokio::test] + async fn storage_failures_keep_local_files_and_report_storage_details() { + let server = MockServer::start().await; + Mock::given(method("GET")) + .respond_with( + ResponseTemplate::new(404) + .insert_header("x-amz-request-id", "request-1") + .set_body_string( + "NoSuchKeygone", + ), + ) + .mount(&server) + .await; + Mock::given(method("DELETE")) + .respond_with(ResponseTemplate::new(404)) + .mount(&server) + .await; + let dir = tempfile::tempdir().unwrap(); + let existing = dir.path().join("existing"); + std::fs::write(&existing, b"old").unwrap(); + let missing = dir.path().join("missing"); + for destination in [&existing, &missing] { + let get = instruction("GET", &server.uri(), destination); + let error = run(&state(0, None), get, dir.path(), None) + .await + .unwrap_err(); + assert_eq!( + error.error_code.as_deref(), + Some("VOLUME_STORAGE_HTTP_ERROR") + ); + assert_eq!(error.http_status, Some(404)); + assert_eq!( + error.message, + "Volume storage request failed: HTTP 404; RequestId: request-1; \ + Code: NoSuchKey; Message: gone" + ); + } + assert_eq!(std::fs::read(&existing).unwrap(), b"old"); + assert!(!missing.exists()); + + let remove = instruction("REMOVE", &server.uri(), Path::new("")); + for remove_not_found_is_success in [true, false] { + let options = VolumeOptions::new(Vec::new(), remove_not_found_is_success); + let result = state(0, None) + .complete(Ok(Some(remove.clone())), &options, None) + .await; + assert_eq!(result.is_ok(), remove_not_found_is_success); + } + } + + #[tokio::test] + async fn transient_storage_failures_are_retried() { + let server = MockServer::start().await; + Mock::given(path("/flaky")) + .respond_with(ResponseTemplate::new(503)) + .up_to_n_times(1) + .mount(&server) + .await; + Mock::given(path("/flaky")) + .respond_with(ResponseTemplate::new(200).set_body_string("recovered")) + .mount(&server) + .await; + Mock::given(path("/denied")) + .respond_with(ResponseTemplate::new(403)) + .expect(1) + .mount(&server) + .await; + let dir = tempfile::tempdir().unwrap(); + let destination = dir.path().join("destination"); + let flaky = instruction("GET", &format!("{}/flaky", server.uri()), &destination); + run(&state(1, None), flaky, dir.path(), None).await.unwrap(); + assert_eq!(std::fs::read(&destination).unwrap(), b"recovered"); + let denied = instruction("GET", &format!("{}/denied", server.uri()), &destination); + let error = run(&state(1, None), denied, dir.path(), None) + .await + .unwrap_err(); + assert_eq!(error.code, ErrorCode::PermissionDenied); + } + + #[tokio::test] + async fn redirects_keep_the_method_and_body_except_see_other_for_writes() { + let server = MockServer::start().await; + for status in [301, 307] { + Mock::given(method("PUT")) + .and(path(format!("/put-{status}"))) + .respond_with(ResponseTemplate::new(status).insert_header("location", "/stored")) + .mount(&server) + .await; + } + Mock::given(method("PUT")) + .and(path("/stored")) + .and(body_bytes(b"payload".to_vec())) + .respond_with(ResponseTemplate::new(200)) + .expect(2) + .mount(&server) + .await; + Mock::given(path("/see-other")) + .respond_with(ResponseTemplate::new(303).insert_header("location", "/object")) + .mount(&server) + .await; + Mock::given(method("GET")) + .and(path("/object")) + .respond_with(ResponseTemplate::new(200).set_body_string("redirected")) + .expect(1) + .mount(&server) + .await; + let dir = tempfile::tempdir().unwrap(); + let source = dir.path().join("source"); + std::fs::write(&source, b"payload").unwrap(); + let destination = dir.path().join("destination"); + for status in [301, 307] { + let put = instruction("PUT", &format!("{}/put-{status}", server.uri()), &source); + run(&state(0, None), put, dir.path(), None).await.unwrap(); + } + let see_other = format!("{}/see-other", server.uri()); + let get = instruction("GET", &see_other, &destination); + run(&state(0, None), get, dir.path(), None).await.unwrap(); + assert_eq!(std::fs::read(&destination).unwrap(), b"redirected"); + let put = instruction("PUT", &see_other, &source); + let error = run(&state(0, None), put, dir.path(), None) + .await + .unwrap_err(); + assert_eq!(error.http_status, Some(303)); + } + + #[tokio::test] + async fn idle_limit_fails_stalled_transfers_but_not_slow_ones() { + let dir = tempfile::tempdir().unwrap(); + let source = dir.path().join("source"); + std::fs::write(&source, vec![b'x'; 16 * 1024 * 1024]).unwrap(); + let destination = dir.path().join("destination"); + // (operation, scheme, bytes the peer trickles before stalling, expected to finish). + // The peer never answers a TLS handshake, so the https row stalls connection setup. + for (operation, scheme, sent, finishes) in [ + ("GET", "http", 5, true), + ("GET", "http", 1, false), + ("PUT", "http", 0, false), + ("GET", "https", 0, false), + ] { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("{scheme}://{}", listener.local_addr().unwrap()); + let peer = tokio::spawn(async move { + let (mut socket, _) = listener.accept().await.unwrap(); + if sent > 0 { + assert!(socket.read(&mut [0; 4096]).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..sent { + tokio::time::sleep(Duration::from_millis(50)).await; + socket.write_all(b"x").await.unwrap(); + } + } + std::future::pending::<()>().await; + drop(socket); + }); + let local = if operation == "PUT" { + &source + } else { + &destination + }; + let transfer = instruction(operation, &url, local); + let result = run( + &state(0, Some(Duration::from_millis(500))), + transfer, + dir.path(), + None, + ) + .await; + peer.abort(); + if finishes { + result.unwrap(); + assert_eq!(std::fs::read(&destination).unwrap(), b"xxxxx"); + } else { + let error = result.unwrap_err(); + assert_eq!( + error.error_code.as_deref(), + Some("VOLUME_STORAGE_NETWORK_ERROR"), + "{operation}" + ); + assert!(error.message.contains("made no progress"), "{operation}"); + } + } + } + + #[tokio::test] + async fn unreadable_upload_sources_are_local_errors() { + let server = MockServer::start().await; + let body = reqwest::Body::wrap_stream(futures::stream::once(async { + Err::(local_error(std::io::ErrorKind::Other.into(), "source")) + })); + let error = Client::new() + .put(server.uri()) + .body(body) + .send() + .await + .unwrap_err(); + let strategy = + RetryStrategy::for_request(RequestType::CloudFetchDownload, &RetryConfig::default()); + let error = storage_error(error, &strategy); + assert_eq!(error.error_code.as_deref(), Some("VOLUME_LOCAL_FILE_ERROR")); + assert!(!error.retryable); + } + + #[test] + fn redirects_cannot_downgrade_https_to_http() { + let location = HeaderValue::from_static("http://storage/object"); + let error = redirect_target( + StatusCode::FOUND, + Some(&location), + &Url::parse("https://storage/object").unwrap(), + &Method::GET, + ) + .unwrap_err(); + assert!(error.message.contains("downgrade")); + } + + #[test] + fn local_paths_must_resolve_inside_an_allowed_root() { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path().join("root"); + let outside = dir.path().join("outside"); + std::fs::create_dir(&root).unwrap(); + std::fs::create_dir(&outside).unwrap(); + let roots = [root.clone()]; + let not_allowed = |path: PathBuf, roots: &[PathBuf]| { + allowed_path(&path, roots) + .unwrap_err() + .error_code + .as_deref() + == Some("VOLUME_PATH_NOT_ALLOWED") + }; + assert!(allowed_path(&root.join("new"), &roots).is_ok()); + assert!(not_allowed(outside.join("file"), &roots)); + assert!(not_allowed(root.join("../outside/file"), &roots)); + assert!(not_allowed(root.join("file"), &[])); + #[cfg(unix)] + { + use std::os::unix::fs::symlink; + symlink(&outside, root.join("out")).unwrap(); + assert!(not_allowed(root.join("out/file"), &roots)); + symlink(&root, outside.join("in")).unwrap(); + assert!(allowed_path(&outside.join("in/file"), &roots).is_ok()); + symlink(root.join("missing"), root.join("dangling")).unwrap(); + assert_eq!( + allowed_path(&root.join("dangling"), &roots) + .unwrap_err() + .code, + ErrorCode::NotFound + ); + } + } + + #[tokio::test] + async fn put_sources_without_a_usable_size_upload_their_content() { + let server = MockServer::start().await; + Mock::given(method("PUT")) + .respond_with(ResponseTemplate::new(200)) + .mount(&server) + .await; + let dir = tempfile::tempdir().unwrap(); + let empty = dir.path().join("empty"); + std::fs::write(&empty, b"").unwrap(); + let mut sources = vec![(empty, dir.path().to_owned(), Vec::new())]; + #[cfg(unix)] + { + let fifo = dir.path().join("fifo"); + assert!(std::process::Command::new("mkfifo") + .arg(&fifo) + .status() + .unwrap() + .success()); + let writer = fifo.clone(); + std::thread::spawn(move || std::fs::write(writer, b"piped").unwrap()); + sources.push((fifo, dir.path().to_owned(), b"piped".to_vec())); + } + #[cfg(target_os = "linux")] + sources.push(( + PathBuf::from("/proc/self/cmdline"), + PathBuf::from("/proc"), + std::fs::read("/proc/self/cmdline").unwrap(), + )); + for (source, root, expected) in sources { + let put = instruction("PUT", &server.uri(), &source); + run(&state(0, None), put, &root, None).await.unwrap(); + let requests = server.received_requests().await.unwrap(); + assert_eq!(requests.last().unwrap().body, expected, "{source:?}"); + } + } + + #[tokio::test] + async fn local_failures_happen_before_any_storage_request() { + let server = MockServer::start().await; + let dir = tempfile::tempdir().unwrap(); + let url = format!("{}/object?signature=secret", server.uri()); + let missing = dir.path().join("missing"); + let error = run( + &state(0, None), + instruction("PUT", &url, &missing), + dir.path(), + None, + ) + .await + .unwrap_err(); + assert_eq!(error.code, ErrorCode::NotFound); + assert_eq!(error.error_code.as_deref(), Some("VOLUME_LOCAL_FILE_ERROR")); + assert_eq!(error.sql_state.as_deref(), Some("HY000")); + let local = error.local_error.unwrap(); + assert_eq!(local.kind, std::io::ErrorKind::NotFound); + assert!(local.raw_os_error.is_some()); + assert_eq!(local.path, missing.to_str().unwrap()); + assert!(!error.message.contains("secret")); + + let no_parent = instruction("GET", &url, &dir.path().join("no-dir/file")); + let error = run(&state(0, None), no_parent, dir.path(), None) + .await + .unwrap_err(); + assert_eq!(error.code, ErrorCode::NotFound); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let read_only = dir.path().join("read-only"); + std::fs::create_dir(&read_only).unwrap(); + std::fs::set_permissions(&read_only, std::fs::Permissions::from_mode(0o500)).unwrap(); + // Permissions do not bind a privileged user. + if tempfile::tempfile_in(&read_only).is_err() { + let get = instruction("GET", &url, &read_only.join("file")); + let error = run(&state(0, None), get, dir.path(), None) + .await + .unwrap_err(); + assert_eq!(error.code, ErrorCode::PermissionDenied); + } + std::fs::set_permissions(&read_only, std::fs::Permissions::from_mode(0o700)).unwrap(); + } + assert!(server.received_requests().await.unwrap().is_empty()); + } + + #[tokio::test] + async fn cancel_stops_a_running_transfer_and_is_remembered() { + let server = MockServer::start().await; + Mock::given(method("GET")) + .respond_with( + ResponseTemplate::new(200) + .set_body_string("new") + .set_delay(Duration::from_secs(30)), + ) + .mount(&server) + .await; + let dir = tempfile::tempdir().unwrap(); + let destination = dir.path().join("destination"); + std::fs::write(&destination, b"old").unwrap(); + let get = instruction("GET", &server.uri(), &destination); + let state = state(0, None); + let cancel = async { + while server.received_requests().await.unwrap().is_empty() { + tokio::task::yield_now().await; + } + state.cancel(); + }; + let (result, ()) = tokio::time::timeout(Duration::from_secs(10), async { + tokio::join!(run(&state, get.clone(), dir.path(), None), cancel) + }) + .await + .unwrap(); + assert_eq!(result.unwrap_err().code, ErrorCode::Cancelled); + let repeated = run(&state, get, dir.path(), None).await.unwrap_err(); + assert_eq!(repeated.code, ErrorCode::Cancelled); + assert_eq!(std::fs::read(&destination).unwrap(), b"old"); + } + + #[test] + fn instructions_must_be_one_well_formed_row() { + let mut map = MapBuilder::new(None, StringBuilder::new(), StringBuilder::new()); + map.keys().append_value("x-test"); + map.values().append_value("yes"); + map.append(true).unwrap(); + let mapped = RecordBatch::try_from_iter([ + ( + "operation", + Arc::new(StringArray::from(vec!["REMOVE"])) as ArrayRef, + ), + ( + "presignedUrl", + Arc::new(StringArray::from(vec!["https://storage"])) as _, + ), + ("headers", Arc::new(map.finish()) as _), + ( + "localFile", + Arc::new(StringArray::from(vec![None::<&str>])) as _, + ), + ]) + .unwrap(); + assert_eq!( + Instruction::decode(&mapped).unwrap().headers["x-test"], + "yes" + ); + + let valid = instruction("GET", "https://storage", Path::new("/tmp/file")); + let replace = |name: &str, value: &str| { + let mut columns = valid.columns().to_vec(); + columns[valid.schema().index_of(name).unwrap()] = + Arc::new(StringArray::from(vec![value])); + RecordBatch::try_new(valid.schema(), columns).unwrap() + }; + let invalid = [ + arrow_select::concat::concat_batches(&valid.schema(), [&valid, &valid]).unwrap(), + valid.project(&[0, 1, 2]).unwrap(), + replace("operation", "COPY"), + replace("headers", "not json"), + replace("localFile", ""), + ]; + for batch in invalid { + assert_eq!( + Instruction::decode(&batch) + .err() + .unwrap() + .error_code + .as_deref(), + Some("VOLUME_INVALID_INSTRUCTION") + ); + } + } +} diff --git a/tests/v0_volume_wiremock.rs b/tests/v0_volume_wiremock.rs new file mode 100644 index 00000000..cd69824c --- /dev/null +++ b/tests/v0_volume_wiremock.rs @@ -0,0 +1,319 @@ +// 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 through sessions and statements, against a mock server. + +use arrow_array::{ArrayRef, RecordBatch, StringArray}; +use arrow_ipc::writer::StreamWriter; +use base64::{engine::general_purpose::STANDARD, Engine}; +use databricks_sql_kernel::{ + AuthConfig, ConnectionConfig, ErrorCode, HttpConfig, Session, VolumeCompletion, VolumeOptions, +}; +use serde_json::json; +use std::path::Path; +use std::sync::Arc; +use std::time::Duration; +use wiremock::matchers::{method, path, path_regex}; +use wiremock::{Mock, MockServer, ResponseTemplate}; + +async fn session(server: &MockServer, http: HttpConfig) -> Session { + Mock::given(method("POST")) + .and(path("/api/2.0/sql/warehouses/test_wh/sessions")) + .respond_with( + ResponseTemplate::new(200) + .set_body_string(r#"{"session_id":"sess-test","warehouse_id":"test_wh"}"#), + ) + .mount(server) + .await; + Mock::given(method("POST")) + .and(path_regex("/cancel$")) + .respond_with(ResponseTemplate::new(200).set_body_string("{}")) + .mount(server) + .await; + Mock::given(method("DELETE")) + .respond_with(ResponseTemplate::new(200).set_body_string("{}")) + .mount(server) + .await; + Session::builder() + .connection( + ConnectionConfig::from_http_path(server.uri(), "/sql/1.0/warehouses/test_wh").unwrap(), + ) + .auth(AuthConfig::Pat { + token: "dapi_test_token".into(), + identity_federation_client_id: None, + }) + .http(http) + .open() + .await + .unwrap() +} + +/// Answers every statement with a GET instruction for `local`. +async fn mount_volume_result(server: &MockServer, local: &Path, marked: bool) { + let batch = RecordBatch::try_from_iter([ + ( + "operation", + Arc::new(StringArray::from(vec!["GET"])) as ArrayRef, + ), + ( + "presignedUrl", + Arc::new(StringArray::from(vec![format!("{}/object", server.uri())])) as _, + ), + ("headers", Arc::new(StringArray::from(vec!["{}"])) as _), + ( + "localFile", + Arc::new(StringArray::from(vec![local.to_str().unwrap()])) as _, + ), + ]) + .unwrap(); + let mut ipc = Vec::new(); + let mut writer = StreamWriter::try_new(&mut ipc, &batch.schema()).unwrap(); + writer.write(&batch).unwrap(); + writer.finish().unwrap(); + drop(writer); + let columns: Vec<_> = batch + .schema() + .fields() + .iter() + .enumerate() + .map(|(position, field)| { + json!({"name": field.name(), "type_name": "STRING", "type_text": "STRING", "position": position}) + }) + .collect(); + let body = json!({ + "statement_id": "stmt-volume", + "status": {"state": "SUCCEEDED"}, + "manifest": { + "is_volume_operation": marked, + "format": "ARROW_STREAM", + "schema": {"column_count": 4, "columns": columns}, + "total_chunk_count": 1, + "total_row_count": 1, + "total_byte_count": ipc.len(), + "truncated": false, + }, + "result": { + "chunk_index": 0, + "row_offset": 0, + "row_count": 1, + "byte_count": ipc.len(), + "attachment": STANDARD.encode(&ipc), + }, + }); + for (verb, route) in [ + ("POST", "/api/2.0/sql/statements"), + ("GET", "/api/2.0/sql/statements/stmt-volume"), + ] { + Mock::given(method(verb)) + .and(path(route)) + .respond_with(ResponseTemplate::new(200).set_body_string(body.to_string())) + .mount(server) + .await; + } +} + +async fn mount_object(server: &MockServer, delay: Duration, expected_requests: u64) { + Mock::given(method("GET")) + .and(path("/object")) + .respond_with( + ResponseTemplate::new(200) + .set_body_string("data") + .set_delay(delay), + ) + .expect(expected_requests) + .mount(server) + .await; +} + +async fn object_requested(server: &MockServer) { + while !server + .received_requests() + .await + .unwrap() + .iter() + .any(|request| request.url.path() == "/object") + { + tokio::task::yield_now().await; + } +} + +#[tokio::test] +async fn sync_volume_result_completes_once_and_keeps_its_row() { + let server = MockServer::start().await; + let dir = tempfile::tempdir().unwrap(); + let destination = dir.path().join("download"); + mount_object(&server, Duration::ZERO, 1).await; + mount_volume_result(&server, &destination, true).await; + let session = session(&server, HttpConfig::default()).await; + let options = VolumeOptions::new(vec![dir.path().to_owned()], false); + let mut statement = session.statement(); + statement.spec().sql("GET"); + let mut executed = statement.execute().await.unwrap(); + let stream = executed.result_stream_mut(); + assert!(stream.is_volume_operation()); + for _ in 0..2 { + assert_eq!( + stream + .complete_volume_operation(&options, None) + .await + .unwrap(), + VolumeCompletion::Completed + ); + } + assert_eq!(std::fs::read(&destination).unwrap(), b"data"); + match stream.next_batch().await.unwrap().unwrap() { + databricks_sql_kernel::ResultBatch::Arrow(row) => assert_eq!(row.num_rows(), 1), + _ => unreachable!(), + } +} + +#[tokio::test] +async fn only_marked_results_transfer_and_only_before_rows_are_read() { + for marked in [false, true] { + let server = MockServer::start().await; + let dir = tempfile::tempdir().unwrap(); + mount_object(&server, Duration::ZERO, 0).await; + mount_volume_result(&server, &dir.path().join("download"), marked).await; + let session = session(&server, HttpConfig::default()).await; + let options = VolumeOptions::new(vec![dir.path().to_owned()], false); + let mut statement = session.statement(); + statement.spec().sql("GET"); + let mut executed = statement.execute().await.unwrap(); + let stream = executed.result_stream_mut(); + if marked { + stream.next_batch().await.unwrap(); + let error = stream + .complete_volume_operation(&options, None) + .await + .unwrap_err(); + assert!(error.message.contains("before reading result rows")); + } else { + assert_eq!( + stream + .complete_volume_operation(&options, None) + .await + .unwrap(), + VolumeCompletion::NotVolume + ); + } + } +} + +#[tokio::test] +async fn async_result_streams_share_one_transfer() { + let server = MockServer::start().await; + let dir = tempfile::tempdir().unwrap(); + mount_object(&server, Duration::ZERO, 1).await; + mount_volume_result(&server, &dir.path().join("download"), true).await; + let session = session(&server, HttpConfig::default()).await; + let options = VolumeOptions::new(vec![dir.path().to_owned()], false); + let mut statement = session.statement(); + statement.spec().sql("GET"); + let executed = statement.submit().await.unwrap(); + let reader = executed.reader().unwrap(); + let mut owner = executed.await_result().await.unwrap(); + let mut other = reader.fetch_result().await.unwrap(); + for stream in [&mut owner, &mut other] { + assert_eq!( + stream + .complete_volume_operation(&options, None) + .await + .unwrap(), + VolumeCompletion::Completed + ); + } +} + +#[tokio::test] +async fn cancellers_and_session_close_stop_a_running_transfer() { + for case in ["statement canceller", "async canceller", "session close"] { + let server = MockServer::start().await; + let dir = tempfile::tempdir().unwrap(); + let destination = dir.path().join("download"); + mount_object(&server, Duration::from_secs(30), 1).await; + mount_volume_result(&server, &destination, true).await; + let session = session(&server, HttpConfig::default()).await; + let options = VolumeOptions::new(vec![dir.path().to_owned()], false); + let mut statement = session.statement(); + statement.spec().sql("GET"); + let completion = async { + match case { + "statement canceller" => { + let canceller = statement.canceller(); + let mut executed = statement.execute().await.unwrap(); + let stop = async { + object_requested(&server).await; + canceller.cancel().await.unwrap(); + }; + let complete = executed + .result_stream_mut() + .complete_volume_operation(&options, None); + tokio::join!(complete, stop).0 + } + "async canceller" => { + let executed = statement.submit().await.unwrap(); + let canceller = executed.canceller(); + let mut stream = executed.await_result().await.unwrap(); + // The transfer stops even after the parent statement is gone. + drop(statement); + let stop = async { + object_requested(&server).await; + let error = canceller.cancel().await.unwrap_err(); + assert_eq!(error.code, ErrorCode::InvalidStatementHandle); + }; + tokio::join!(stream.complete_volume_operation(&options, None), stop).0 + } + _ => { + let mut executed = statement.execute().await.unwrap(); + let stop = async { + object_requested(&server).await; + session.close().await.unwrap(); + }; + let complete = executed + .result_stream_mut() + .complete_volume_operation(&options, None); + tokio::join!(complete, stop).0 + } + } + }; + let result = tokio::time::timeout(Duration::from_secs(10), completion) + .await + .unwrap(); + assert_eq!(result.unwrap_err().code, ErrorCode::Cancelled, "{case}"); + assert!(!destination.exists(), "{case}"); + } +} + +#[tokio::test] +async fn storage_transfer_is_not_bound_by_the_sql_request_timeout() { + let server = MockServer::start().await; + let dir = tempfile::tempdir().unwrap(); + mount_object(&server, Duration::from_secs(2), 1).await; + mount_volume_result(&server, &dir.path().join("download"), true).await; + let mut http = HttpConfig::default(); + http.request_timeout = Duration::from_secs(1); + let session = session(&server, http).await; + let mut statement = session.statement(); + statement.spec().sql("GET"); + let mut executed = statement.execute().await.unwrap(); + let options = VolumeOptions::new(vec![dir.path().to_owned()], false); + assert_eq!( + executed + .result_stream_mut() + .complete_volume_operation(&options, None) + .await + .unwrap(), + VolumeCompletion::Completed + ); +} From beefd52dd3efd6c2ed17781f3446b6cceab2aef8 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Tue, 1 Dec 2026 02:28:19 +0000 Subject: [PATCH 02/43] fix(volume): run each transfer at most once and stream uploads by offset A completion call abandoned mid-transfer makes later calls return Cancelled instead of transferring again. Uploads read the validated file by offset for each request instead of reopening it by path, and caller-supplied bytes are sent in chunks so the idle limit sees their progress. The root and adbc lockfiles keep windows-sys 0.61.2 for the crates the rustix update moved. Co-authored-by: Isaac Signed-off-by: Aakash Saravanan --- Cargo.lock | 8 +- Cargo.toml | 2 +- adbc/Cargo.lock | 6 +- src/result_stream.rs | 4 +- src/volume.rs | 201 +++++++++++++++++++++++++++++++------------ 5 files changed, 158 insertions(+), 63 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 15476fdc..501a95b0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -824,7 +824,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -2146,7 +2146,7 @@ dependencies = [ "once_cell", "socket2", "tracing", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -2402,7 +2402,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -2777,7 +2777,7 @@ dependencies = [ "getrandom 0.4.3", "once_cell", "rustix", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index aea8296f..b9bfeba0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -114,7 +114,7 @@ moka = { version = "0.12.16", features = ["future"] } # Async utilities futures = "0.3" -tokio-util = { version = "0.7", features = ["io"] } +tokio-util = "0.7" async-trait = "0.1" # Error handling diff --git a/adbc/Cargo.lock b/adbc/Cargo.lock index 31c75b01..89294293 100644 --- a/adbc/Cargo.lock +++ b/adbc/Cargo.lock @@ -807,7 +807,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -2211,7 +2211,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -2547,7 +2547,7 @@ dependencies = [ "getrandom 0.4.3", "once_cell", "rustix", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] diff --git a/src/result_stream.rs b/src/result_stream.rs index 063f70af..c4ff7ba5 100644 --- a/src/result_stream.rs +++ b/src/result_stream.rs @@ -671,7 +671,9 @@ impl ResultStream { /// return the first outcome without transferring again. /// /// Call before reading rows; the instruction row stays readable. A GET - /// replaces the destination only after the download succeeds. A PUT of + /// replaces the destination only after the download succeeds; a failure + /// while copying into an existing file can leave it partly written. A + /// call abandoned mid-transfer makes later calls return `Cancelled`. A PUT of /// caller-supplied bytes returns `NeedsInputStream` until called with /// `input_bytes`. Cancelling stops the transfer but cannot undo a PUT or /// REMOVE that storage already applied. diff --git a/src/volume.rs b/src/volume.rs index 1626a1a0..d729f0bf 100644 --- a/src/volume.rs +++ b/src/volume.rs @@ -24,7 +24,7 @@ use crate::kernel_error::{Error, LocalFileError, Result}; use arrow_array::cast::AsArray; use arrow_array::{Array, ArrayRef, RecordBatch}; use arrow_schema::DataType; -use futures::TryStreamExt; +use futures::{Stream, StreamExt, TryStreamExt}; use reqwest::header::{ HeaderMap, HeaderName, HeaderValue, AUTHORIZATION, CONTENT_LENGTH, COOKIE, LOCATION, PROXY_AUTHORIZATION, RETRY_AFTER, @@ -32,16 +32,17 @@ use reqwest::header::{ use reqwest::{Client, Method, Response, StatusCode, Url}; use std::io::{Read, Seek}; use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; use std::time::{Duration, Instant}; use tokio::io::{AsyncSeekExt, AsyncWriteExt}; use tokio::sync::{watch, OnceCell}; use tokio_util::bytes::Bytes; -use tokio_util::io::ReaderStream; use tokio_util::sync::CancellationToken; const MAX_REDIRECTS: usize = 10; const ERROR_BODY_LIMIT: usize = 4096; +const UPLOAD_CHUNK: usize = 256 * 1024; /// Caller settings for a Volume file transfer. #[non_exhaustive] @@ -105,6 +106,7 @@ impl Storage { storage: Arc::clone(self), cancellation: self.cancellation.child_token(), outcome: OnceCell::new(), + started: AtomicBool::new(false), }) } @@ -126,6 +128,9 @@ pub(crate) struct VolumeState { storage: Arc, cancellation: CancellationToken, outcome: OnceCell>, + /// Set when a transfer starts. A call abandoned mid-transfer caches + /// nothing, and the transfer must not run again. + started: AtomicBool, } impl VolumeState { @@ -155,6 +160,9 @@ impl VolumeState { { return Ok(VolumeCompletion::NeedsInputStream); } + if self.started.swap(true, Ordering::AcqRel) { + return Err(cancelled()); + } self.transfer(instruction, options, input_bytes).await?; Ok(VolumeCompletion::Completed) }; @@ -239,8 +247,13 @@ impl VolumeState { let mut request = client .request(method.clone(), url.clone()) .headers(headers.clone()); - if let Some((body, length)) = local.body(progress).await.map_err(|e| (e, None))? { - request = request.header(CONTENT_LENGTH, length).body(body); + if let Some((chunks, length)) = local.upload() { + let chunks = chunks.inspect_ok(move |_| { + progress.send_replace(()); + }); + request = request + .header(CONTENT_LENGTH, length) + .body(reqwest::Body::wrap_stream(chunks)); } let response = self .idle_bounded(&mut progressed, async { @@ -488,9 +501,9 @@ enum Local { } enum Upload { - /// Reopened for each request. + /// The validated file, read by offset for each request. File { - path: PathBuf, + file: Arc, length: u64, name: String, }, @@ -523,7 +536,7 @@ async fn prepare( let metadata = file.metadata().map_err(local_error)?; if metadata.is_file() && metadata.len() > 0 { return Ok(Local::Upload(Upload::File { - path, + file: Arc::new(file), length: metadata.len(), name, })); @@ -577,26 +590,22 @@ impl Local { } } - async fn body(&self, progress: watch::Sender<()>) -> Result> { - match self { - Local::Upload(Upload::File { path, length, name }) => { - let file = tokio::fs::File::open(path) - .await - .map_err(|e| local_error(e, name))?; - let name = name.clone(); - let stream = ReaderStream::new(file) - .inspect_ok(move |_| { - progress.send_replace(()); - }) - .map_err(move |e| local_error(e, &name)); - Ok(Some((reqwest::Body::wrap_stream(stream), *length))) + /// The upload as chunks, each a separate unit of progress, and its length. + fn upload(&self) -> Option<(futures::stream::BoxStream<'static, Result>, u64)> { + Some(match self { + Local::Upload(Upload::File { file, length, name }) => ( + file_chunks(Arc::clone(file), *length, name.clone()).boxed(), + *length, + ), + Local::Upload(Upload::Bytes(bytes)) => { + let all = bytes.clone(); + let chunks = (0..bytes.len()) + .step_by(UPLOAD_CHUNK) + .map(move |start| Ok(all.slice(start..all.len().min(start + UPLOAD_CHUNK)))); + (futures::stream::iter(chunks).boxed(), bytes.len() as u64) } - Local::Upload(Upload::Bytes(bytes)) => Ok(Some(( - reqwest::Body::from(bytes.clone()), - bytes.len() as u64, - ))), - Local::Download(_) | Local::Remove => Ok(None), - } + Local::Download(_) | Local::Remove => return None, + }) } async fn publish(self) -> Result<()> { @@ -631,6 +640,49 @@ impl Local { } } +/// Reads the first `length` bytes of `file` by offset, so a request never +/// shares a file position with an earlier one that still holds the handle. +fn file_chunks( + file: Arc, + length: u64, + name: String, +) -> impl Stream> + Send + 'static { + futures::stream::try_unfold(0, move |offset| { + let (file, name) = (Arc::clone(&file), name.clone()); + async move { + if offset >= length { + return Ok(None); + } + let size = (length - offset).min(UPLOAD_CHUNK as u64) as usize; + let chunk = tokio::task::spawn_blocking(move || { + let mut chunk = vec![0; size]; + let read = read_at(&file, &mut chunk, offset)?; + chunk.truncate(read); + Ok::<_, std::io::Error>(chunk) + }) + .await + .map_err(|e| Error::internal().message(format!("Volume upload read failed: {e}")))? + .map_err(|e| local_error(e, &name))?; + if chunk.is_empty() { + return Err(local_error(std::io::ErrorKind::UnexpectedEof.into(), &name)); + } + let next = offset + chunk.len() as u64; + Ok(Some((Bytes::from(chunk), next))) + } + }) +} + +fn read_at(file: &std::fs::File, buf: &mut [u8], offset: u64) -> std::io::Result { + #[cfg(unix)] + { + std::os::unix::fs::FileExt::read_at(file, buf, offset) + } + #[cfg(windows)] + { + std::os::windows::fs::FileExt::seek_read(file, buf, offset) + } +} + /// The URL to follow when a response is a redirect the request should take. fn redirect_target( status: StatusCode, @@ -1224,36 +1276,77 @@ mod tests { } #[tokio::test] - async fn cancel_stops_a_running_transfer_and_is_remembered() { - let server = MockServer::start().await; - Mock::given(method("GET")) - .respond_with( - ResponseTemplate::new(200) - .set_body_string("new") - .set_delay(Duration::from_secs(30)), - ) - .mount(&server) - .await; + async fn cancelled_or_abandoned_transfers_do_not_run_again() { + for abandon in [false, true] { + let server = MockServer::start().await; + Mock::given(method("GET")) + .respond_with( + ResponseTemplate::new(200) + .set_body_string("new") + .set_delay(Duration::from_secs(30)), + ) + .expect(1) + .mount(&server) + .await; + let dir = tempfile::tempdir().unwrap(); + let destination = dir.path().join("destination"); + std::fs::write(&destination, b"old").unwrap(); + let get = instruction("GET", &server.uri(), &destination); + let state = state(0, None); + let requested = async { + while server.received_requests().await.unwrap().is_empty() { + tokio::task::yield_now().await; + } + }; + tokio::time::timeout(Duration::from_secs(10), async { + let transfer = run(&state, get.clone(), dir.path(), None); + if abandon { + tokio::select! { + result = transfer => panic!("transfer finished early: {result:?}"), + () = requested => {} + } + } else { + let (result, ()) = tokio::join!(transfer, async { + requested.await; + state.cancel(); + }); + assert_eq!(result.unwrap_err().code, ErrorCode::Cancelled); + } + }) + .await + .unwrap(); + let repeated = run(&state, get, dir.path(), None).await.unwrap_err(); + assert_eq!(repeated.code, ErrorCode::Cancelled, "abandon={abandon}"); + assert_eq!(std::fs::read(&destination).unwrap(), b"old"); + } + } + + #[tokio::test] + async fn uploads_are_chunked_and_each_read_covers_the_whole_source() { + let payload: Vec = (0..3 * UPLOAD_CHUNK + 1).map(|i| i as u8).collect(); let dir = tempfile::tempdir().unwrap(); - let destination = dir.path().join("destination"); - std::fs::write(&destination, b"old").unwrap(); - let get = instruction("GET", &server.uri(), &destination); - let state = state(0, None); - let cancel = async { - while server.received_requests().await.unwrap().is_empty() { - tokio::task::yield_now().await; - } - state.cancel(); + let source = dir.path().join("source"); + std::fs::write(&source, &payload).unwrap(); + let file = Upload::File { + file: Arc::new(std::fs::File::open(&source).unwrap()), + length: payload.len() as u64, + name: "source".into(), }; - let (result, ()) = tokio::time::timeout(Duration::from_secs(10), async { - tokio::join!(run(&state, get.clone(), dir.path(), None), cancel) - }) - .await - .unwrap(); - assert_eq!(result.unwrap_err().code, ErrorCode::Cancelled); - let repeated = run(&state, get, dir.path(), None).await.unwrap_err(); - assert_eq!(repeated.code, ErrorCode::Cancelled); - assert_eq!(std::fs::read(&destination).unwrap(), b"old"); + let bytes = Upload::Bytes(payload.clone().into()); + let joined = |chunks: &[Bytes]| chunks.iter().flat_map(|c| c.to_vec()).collect::>(); + for upload in [Local::Upload(file), Local::Upload(bytes)] { + // A retry or redirect starts a new read while an earlier one may still be open. + let (mut first, length) = upload.upload().unwrap(); + let head = first.try_next().await.unwrap().unwrap(); + let (second, _) = upload.upload().unwrap(); + let second: Vec = second.try_collect().await.unwrap(); + let mut rest: Vec = first.try_collect().await.unwrap(); + rest.insert(0, head); + assert_eq!(length, payload.len() as u64); + assert_eq!(second.len(), 4); + assert_eq!(joined(&second), payload); + assert_eq!(joined(&rest), payload); + } } #[test] From e886bde02bf8013ddec27369d800cbf541d170f3 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Tue, 1 Dec 2026 02:56:43 +0000 Subject: [PATCH 03/43] fix(volume): recheck new destinations and refuse transfers on attached results A new GET destination is checked against the allowed roots again when it is created. A result from Session::attach_async_statement reports a marked Volume operation and fails completion instead of returning NotVolume. The upload length replaces any Content-Length in the instruction headers, and credentials are dropped on a redirect to another origin. Co-authored-by: Isaac Signed-off-by: Aakash Saravanan --- src/result_stream.rs | 4 +- src/session.rs | 4 + src/statement/executed_async.rs | 2 + src/volume.rs | 128 +++++++++++++++++++++++++++----- tests/v0_volume_wiremock.rs | 9 +++ 5 files changed, 126 insertions(+), 21 deletions(-) diff --git a/src/result_stream.rs b/src/result_stream.rs index c4ff7ba5..427a8191 100644 --- a/src/result_stream.rs +++ b/src/result_stream.rs @@ -673,7 +673,9 @@ impl ResultStream { /// Call before reading rows; the instruction row stays readable. A GET /// replaces the destination only after the download succeeds; a failure /// while copying into an existing file can leave it partly written. A - /// call abandoned mid-transfer makes later calls return `Cancelled`. A PUT of + /// call abandoned mid-transfer makes later calls return `Cancelled`. A result + /// from [`Session::attach_async_statement`](crate::Session::attach_async_statement) + /// cannot transfer and returns an error. A PUT of /// caller-supplied bytes returns `NeedsInputStream` until called with /// `input_bytes`. Cancelling stops the transfer but cannot undo a PUT or /// REMOVE that storage already applied. diff --git a/src/session.rs b/src/session.rs index 3191f3d6..79129e19 100644 --- a/src/session.rs +++ b/src/session.rs @@ -170,6 +170,10 @@ impl SessionInner { self.storage.transfer_state() } + pub(crate) fn refused_volume_state(&self) -> Arc { + self.storage.refused_state() + } + /// Crate-internal accessor for the server-issued session ID. pub(crate) fn session_id(&self) -> &str { &self.session_id diff --git a/src/statement/executed_async.rs b/src/statement/executed_async.rs index 3c9dc945..b12b6741 100644 --- a/src/statement/executed_async.rs +++ b/src/statement/executed_async.rs @@ -386,6 +386,7 @@ impl ExecutedAsyncStatement { statement_id: String, initial_status: crate::types::sea::StatementStatus, ) -> Self { + let volume = session.refused_volume_state(); Self::new_read_only( session, statement_id, @@ -394,6 +395,7 @@ impl ExecutedAsyncStatement { SessionAttribution::Detached, initial_status, ) + .with_volume(Some(volume)) } fn new_read_only( diff --git a/src/volume.rs b/src/volume.rs index d729f0bf..d5876321 100644 --- a/src/volume.rs +++ b/src/volume.rs @@ -110,6 +110,15 @@ impl Storage { }) } + /// State for a handle that only observes another handle's statement, so a + /// marked result reports the refusal instead of transferring. + pub(crate) fn refused_state(self: &Arc) -> Arc { + let state = self.transfer_state(); + let _ = state.outcome.set(Err(Error::invalid_state() + .message("Volume transfers run only on the statement that submitted them"))); + state + } + /// Stops every transfer of the session. pub(crate) fn cancel_all(&self) { self.cancellation.cancel(); @@ -244,16 +253,19 @@ impl VolumeState { let mut headers = instruction.headers.clone(); for _ in 0..=MAX_REDIRECTS { let (progress, mut progressed) = watch::channel(()); - let mut request = client - .request(method.clone(), url.clone()) - .headers(headers.clone()); + let mut request_headers = headers.clone(); + let mut body = None; if let Some((chunks, length)) = local.upload() { - let chunks = chunks.inspect_ok(move |_| { + request_headers.insert(CONTENT_LENGTH, length.into()); + body = Some(reqwest::Body::wrap_stream(chunks.inspect_ok(move |_| { progress.send_replace(()); - }); - request = request - .header(CONTENT_LENGTH, length) - .body(reqwest::Body::wrap_stream(chunks)); + }))); + } + let mut request = client + .request(method.clone(), url.clone()) + .headers(request_headers); + if let Some(body) = body { + request = request.body(body); } let response = self .idle_bounded(&mut progressed, async { @@ -265,7 +277,7 @@ impl VolumeState { if let Some(next) = redirect_target(response.status(), location, &url, &method) .map_err(|e| (e, None))? { - if next.host_str() != url.host_str() { + if next.origin() != url.origin() { for name in [AUTHORIZATION, COOKIE, PROXY_AUTHORIZATION] { headers.remove(name); } @@ -510,12 +522,14 @@ enum Upload { Bytes(Bytes), } -/// A GET downloads to `temp` and copies it to `path` only after success, so a -/// failed download leaves an existing file unchanged. +/// A GET downloads to `temp` and copies it to the destination only after +/// success, so a failed download leaves an existing file unchanged. A new +/// destination is checked against the allowed roots again when it is created. struct Download { temp: std::fs::File, existing: Option, - path: PathBuf, + requested: PathBuf, + roots: Vec, name: String, } @@ -571,7 +585,8 @@ async fn prepare( Ok(Local::Download(Download { temp, existing, - path, + requested, + roots, name, })) } @@ -612,7 +627,8 @@ impl Local { let Local::Download(Download { mut temp, existing, - path, + requested, + roots, name, }) = self else { @@ -625,7 +641,7 @@ impl Local { None => std::fs::OpenOptions::new() .write(true) .create_new(true) - .open(&path) + .open(allowed_path(&requested, &roots)?) .map_err(local_error)?, }; temp.rewind().map_err(local_error)?; @@ -849,16 +865,22 @@ mod tests { } fn instruction(operation: &str, url: &str, local: &Path) -> RecordBatch { + instruction_with_headers(operation, url, local, r#"{"x-test":"yes"}"#) + } + + fn instruction_with_headers( + operation: &str, + url: &str, + local: &Path, + headers: &str, + ) -> RecordBatch { RecordBatch::try_from_iter([ ( "operation", Arc::new(StringArray::from(vec![operation])) as ArrayRef, ), ("presignedUrl", Arc::new(StringArray::from(vec![url])) as _), - ( - "headers", - Arc::new(StringArray::from(vec![r#"{"x-test":"yes"}"#])) as _, - ), + ("headers", Arc::new(StringArray::from(vec![headers])) as _), ( "localFile", Arc::new(StringArray::from(vec![local.to_str().unwrap()])) as _, @@ -909,7 +931,13 @@ mod tests { std::fs::write(&destination, b"an older and longer file").unwrap(); let url = |name: &str| format!("{}/{name}", server.uri()); - let put = instruction("PUT", &url("put"), &source); + // The upload's own length replaces one in the instruction headers. + let put = instruction_with_headers( + "PUT", + &url("put"), + &source, + r#"{"x-test":"yes","Content-Length":"1"}"#, + ); assert_eq!( run(&state(0, None), put, dir.path(), None).await.unwrap(), VolumeCompletion::Completed @@ -1060,6 +1088,32 @@ mod tests { .await .unwrap_err(); assert_eq!(error.http_status, Some(303)); + + // A redirect to another origin drops credentials. + let other = MockServer::start().await; + Mock::given(wiremock::matchers::header_exists("authorization")) + .respond_with(ResponseTemplate::new(403)) + .mount(&other) + .await; + Mock::given(method("PUT")) + .respond_with(ResponseTemplate::new(200)) + .expect(1) + .mount(&other) + .await; + Mock::given(path("/cross-origin")) + .respond_with( + ResponseTemplate::new(307) + .insert_header("location", format!("{}/object", other.uri())), + ) + .mount(&server) + .await; + let put = instruction_with_headers( + "PUT", + &format!("{}/cross-origin", server.uri()), + &source, + r#"{"Authorization":"secret"}"#, + ); + run(&state(0, None), put, dir.path(), None).await.unwrap(); } #[tokio::test] @@ -1191,6 +1245,40 @@ mod tests { } } + #[tokio::test] + #[cfg(unix)] + async fn a_new_destination_is_checked_again_when_it_is_created() { + let server = MockServer::start().await; + Mock::given(method("GET")) + .respond_with( + ResponseTemplate::new(200) + .set_body_string("data") + .set_delay(Duration::from_millis(300)), + ) + .mount(&server) + .await; + let dir = tempfile::tempdir().unwrap(); + let root = dir.path().join("root"); + let outside = dir.path().join("outside"); + std::fs::create_dir_all(root.join("sub")).unwrap(); + std::fs::create_dir(&outside).unwrap(); + let get = instruction("GET", &server.uri(), &root.join("sub/file")); + let swap = async { + while server.received_requests().await.unwrap().is_empty() { + tokio::task::yield_now().await; + } + std::fs::remove_dir(root.join("sub")).unwrap(); + std::os::unix::fs::symlink(&outside, root.join("sub")).unwrap(); + }; + let state = state(0, None); + let (result, ()) = tokio::join!(run(&state, get, &root, None), swap); + assert_eq!( + result.unwrap_err().error_code.as_deref(), + Some("VOLUME_PATH_NOT_ALLOWED") + ); + assert!(!outside.join("file").exists()); + } + #[tokio::test] async fn put_sources_without_a_usable_size_upload_their_content() { let server = MockServer::start().await; diff --git a/tests/v0_volume_wiremock.rs b/tests/v0_volume_wiremock.rs index cd69824c..21cede81 100644 --- a/tests/v0_volume_wiremock.rs +++ b/tests/v0_volume_wiremock.rs @@ -233,6 +233,15 @@ async fn async_result_streams_share_one_transfer() { VolumeCompletion::Completed ); } + // A handle that only observes the statement must not transfer. + let attached = session.attach_async_statement("stmt-volume").await.unwrap(); + let mut observed = attached.fetch_result().await.unwrap(); + assert!(observed.is_volume_operation()); + let error = observed + .complete_volume_operation(&options, None) + .await + .unwrap_err(); + assert!(error.message.contains("statement that submitted them")); } #[tokio::test] From 12be7310d2632955f6dab60bb7d9691368e60b1f Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Tue, 1 Dec 2026 03:14:57 +0000 Subject: [PATCH 04/43] docs(volume): state what a transfer requires of its caller VolumeOptions documents that the allowed directories must not change during a transfer, and complete_volume_operation that an async statement must stay open until its transfer finishes. The idle-limit test's slow download now lasts longer than the limit. Co-authored-by: Isaac Signed-off-by: Aakash Saravanan --- src/result_stream.rs | 5 ++++- src/volume.rs | 10 ++++++---- 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/src/result_stream.rs b/src/result_stream.rs index 427a8191..bbb639ef 100644 --- a/src/result_stream.rs +++ b/src/result_stream.rs @@ -675,7 +675,10 @@ impl ResultStream { /// while copying into an existing file can leave it partly written. A /// call abandoned mid-transfer makes later calls return `Cancelled`. A result /// from [`Session::attach_async_statement`](crate::Session::attach_async_statement) - /// cannot transfer and returns an error. A PUT of + /// cannot transfer and returns an error. Keep an + /// [`ExecutedAsyncStatement`](crate::ExecutedAsyncStatement) open until its + /// transfer finishes: cancelling, closing or dropping it stops the transfer. + /// A PUT of /// caller-supplied bytes returns `NeedsInputStream` until called with /// `input_bytes`. Cancelling stops the transfer but cannot undo a PUT or /// REMOVE that storage already applied. diff --git a/src/volume.rs b/src/volume.rs index d5876321..a8a54e4b 100644 --- a/src/volume.rs +++ b/src/volume.rs @@ -49,7 +49,9 @@ const UPLOAD_CHUNK: usize = 256 * 1024; #[derive(Debug, Clone, Default)] pub struct VolumeOptions { /// Directories a PUT may read from and a GET may write to. The local path, - /// with symlinks resolved, must be inside one of them. + /// with symlinks resolved, must be inside one of them. 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 an object that does not exist. pub remove_not_found_is_success: bool, @@ -1125,7 +1127,7 @@ mod tests { // (operation, scheme, bytes the peer trickles before stalling, expected to finish). // The peer never answers a TLS handshake, so the https row stalls connection setup. for (operation, scheme, sent, finishes) in [ - ("GET", "http", 5, true), + ("GET", "http", 15, true), ("GET", "http", 1, false), ("PUT", "http", 0, false), ("GET", "https", 0, false), @@ -1137,7 +1139,7 @@ mod tests { if sent > 0 { assert!(socket.read(&mut [0; 4096]).await.unwrap() > 0); socket - .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\n") + .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 15\r\n\r\n") .await .unwrap(); for _ in 0..sent { @@ -1164,7 +1166,7 @@ mod tests { peer.abort(); if finishes { result.unwrap(); - assert_eq!(std::fs::read(&destination).unwrap(), b"xxxxx"); + assert_eq!(std::fs::read(&destination).unwrap(), vec![b'x'; 15]); } else { let error = result.unwrap_err(); assert_eq!( From 6080a3cc77d89777a47bb8a5a117056a87081573 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Tue, 1 Dec 2026 03:31:00 +0000 Subject: [PATCH 05/43] fix(volume): refuse completion once a stream is read to the end A stream whose rows were all read fails `complete_volume_operation` with InvalidState, as it does while a batch is current, instead of caching a missing-instruction error for the whole execution. Co-authored-by: Isaac Signed-off-by: Aakash Saravanan --- src/result_stream.rs | 2 +- tests/v0_volume_wiremock.rs | 15 +++++++++------ 2 files changed, 10 insertions(+), 7 deletions(-) diff --git a/src/result_stream.rs b/src/result_stream.rs index bbb639ef..e00051d5 100644 --- a/src/result_stream.rs +++ b/src/result_stream.rs @@ -693,7 +693,7 @@ impl ResultStream { if let Some(outcome) = volume.outcome() { return outcome; } - if self.current.is_some() { + if self.current.is_some() || self.exhausted { return Err(Error::invalid_state() .message("complete_volume_operation must be called before reading result rows")); } diff --git a/tests/v0_volume_wiremock.rs b/tests/v0_volume_wiremock.rs index 21cede81..2bffc994 100644 --- a/tests/v0_volume_wiremock.rs +++ b/tests/v0_volume_wiremock.rs @@ -192,12 +192,15 @@ async fn only_marked_results_transfer_and_only_before_rows_are_read() { let mut executed = statement.execute().await.unwrap(); let stream = executed.result_stream_mut(); if marked { - stream.next_batch().await.unwrap(); - let error = stream - .complete_volume_operation(&options, None) - .await - .unwrap_err(); - assert!(error.message.contains("before reading result rows")); + // First with the instruction row current, then with the stream exhausted. + for _ in 0..2 { + stream.next_batch().await.unwrap(); + let error = stream + .complete_volume_operation(&options, None) + .await + .unwrap_err(); + assert!(error.message.contains("before reading result rows")); + } } else { assert_eq!( stream From f303a57d499439e2773782cf078c88f1ce99e8d5 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Tue, 1 Dec 2026 03:53:25 +0000 Subject: [PATCH 06/43] fix(volume): confirm opened files on Unix and run Volume statements live - On Unix, every local file a transfer opens must still be the file its path resolves to inside the allowed roots, so a link swapped in after the path check cannot redirect a PUT source or a GET destination. - A zero `storage_read_timeout` sets no limit, as `None` does, instead of failing transfers that are still making progress. - A completion that returns another stream's cached failure finalizes this stream's telemetry with that error. - `tests/v0_volume_e2e.rs` runs PUT from a file and from caller bytes, GET into new and existing files, and REMOVE against a live warehouse, and the Rust E2E workflow runs it. Co-authored-by: Isaac Signed-off-by: Aakash Saravanan --- .github/workflows/rust-e2e.yml | 2 +- CONNECTION_PARAMETERS.md | 2 +- src/config.rs | 4 +- src/result_stream.rs | 27 ++++---- src/telemetry/statement.rs | 37 ++++++----- src/volume.rs | 109 ++++++++++++++++++++++++------- tests/v0_volume_e2e.rs | 113 +++++++++++++++++++++++++++++++++ 7 files changed, 238 insertions(+), 56 deletions(-) create mode 100644 tests/v0_volume_e2e.rs diff --git a/.github/workflows/rust-e2e.yml b/.github/workflows/rust-e2e.yml index cf0cef74..fa094808 100644 --- a/.github/workflows/rust-e2e.yml +++ b/.github/workflows/rust-e2e.yml @@ -93,7 +93,7 @@ jobs: - name: Run v0 E2E tests run: | - for suite in v0_session_e2e v0_execute_e2e v0_async_execute_e2e v0_metadata_e2e v0_query_tags_headers_e2e; do + for suite in v0_session_e2e v0_execute_e2e v0_async_execute_e2e v0_metadata_e2e v0_query_tags_headers_e2e v0_volume_e2e; do echo "::group::cargo test --test ${suite}" cargo test --test "${suite}" -- --ignored --nocapture echo "::endgroup::" diff --git a/CONNECTION_PARAMETERS.md b/CONNECTION_PARAMETERS.md index 769461c2..84a922c6 100644 --- a/CONNECTION_PARAMETERS.md +++ b/CONNECTION_PARAMETERS.md @@ -168,7 +168,7 @@ until implemented) and `External` (a caller-supplied `TokenProvider`). | Field | Description | Default | |-------|-------------|---------| | `request_timeout` | Per-request timeout (connect + body). Does not apply to Volume file transfers. | `120s` | -| `storage_read_timeout` | Volume file transfers fail after this long without progress; `None` sets no limit. | `Some(900s)` | +| `storage_read_timeout` | Volume file transfers fail after this long without progress; `None` or zero sets no limit. | `Some(900s)` | | `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/src/config.rs b/src/config.rs index 004f8348..21424666 100644 --- a/src/config.rs +++ b/src/config.rs @@ -944,8 +944,8 @@ pub struct HttpConfig { pub request_timeout: Duration, /// Idle limit for Volume file transfers, which `request_timeout` does not - /// bound: a transfer fails after this long without progress. `None` sets - /// no limit. + /// bound: a transfer fails after this long without progress. `None` or + /// zero sets no 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 e00051d5..4a90bf11 100644 --- a/src/result_stream.rs +++ b/src/result_stream.rs @@ -690,18 +690,21 @@ impl ResultStream { let Some(volume) = self.volume.clone() else { return Ok(crate::volume::VolumeCompletion::NotVolume); }; - if let Some(outcome) = volume.outcome() { - return outcome; - } - if self.current.is_some() || self.exhausted { - return Err(Error::invalid_state() - .message("complete_volume_operation must be called before reading result rows")); - } - let instruction = self - .peek_first_batch() - .await - .map(|batch| batch.map(|ResultBatch::Arrow(batch)| batch.clone())); - let result = volume.complete(instruction, options, input_bytes).await; + let result = match volume.outcome() { + Some(outcome) => outcome, + None => { + if self.current.is_some() || self.exhausted { + return Err(Error::invalid_state().message( + "complete_volume_operation must be called before reading result rows", + )); + } + let instruction = self + .peek_first_batch() + .await + .map(|batch| batch.map(|ResultBatch::Arrow(batch)| batch.clone())); + volume.complete(instruction, options, input_bytes).await + } + }; if let Err(error) = &result { self.finalize_telemetry(Some(error)); } diff --git a/src/telemetry/statement.rs b/src/telemetry/statement.rs index 88b4fe1b..b3d8cbd6 100644 --- a/src/telemetry/statement.rs +++ b/src/telemetry/statement.rs @@ -376,19 +376,11 @@ mod tests { #[tokio::test] async fn failed_volume_completion_finalizes_statement_with_error() { let connection = Arc::new(CapturingConnectionTelemetry::default()); - let telemetry = StatementTelemetry::new( - connection.clone(), - StatementType::Sql, - OperationType::ExecuteStatement, - ); let batch = RecordBatch::try_from_iter([( "n", Arc::new(arrow_array::Int64Array::from(vec![1])) as arrow_array::ArrayRef, )]) .unwrap(); - let reader = crate::reader::test_utils::MockReader::new(vec![batch]); - let mut stream = ResultStream::from_reader(Box::new(reader)).await.unwrap(); - stream.attach_telemetry(telemetry); let manifest: crate::types::sea::ResultManifest = serde_json::from_value(serde_json::json!({ "is_volume_operation": true, @@ -401,17 +393,28 @@ mod tests { Default::default(), None, )); - stream.attach_volume(Some(&manifest), &storage.transfer_state()); - let error = stream - .complete_volume_operation(&Default::default(), None) - .await - .unwrap_err(); - - drop(stream); + let state = storage.transfer_state(); + // The second stream of the execution gets the first one's cached failure. + let mut codes = Vec::new(); + for _ in 0..2 { + let reader = crate::reader::test_utils::MockReader::new(vec![batch.clone()]); + let mut stream = ResultStream::from_reader(Box::new(reader)).await.unwrap(); + stream.attach_telemetry(StatementTelemetry::new( + connection.clone(), + StatementType::Sql, + OperationType::ExecuteStatement, + )); + stream.attach_volume(Some(&manifest), &state); + let error = stream + .complete_volume_operation(&Default::default(), None) + .await + .unwrap_err(); + codes.push(Some(error.code)); + } let events = connection.statement_events.lock().expect("events mutex"); - assert_eq!(events.len(), 1); - assert_eq!(events[0].error_code, Some(error.code)); + let reported: Vec<_> = events.iter().map(|event| event.error_code).collect(); + assert_eq!(reported, codes); } #[tokio::test] diff --git a/src/volume.rs b/src/volume.rs index a8a54e4b..8d59abb5 100644 --- a/src/volume.rs +++ b/src/volume.rs @@ -49,9 +49,10 @@ const UPLOAD_CHUNK: usize = 256 * 1024; #[derive(Debug, Clone, Default)] pub struct VolumeOptions { /// Directories a PUT may read from and a GET may write to. The local path, - /// with symlinks resolved, must be inside one of them. The check runs before - /// the file is opened, so nothing else may swap files or links in these - /// directories during a transfer. + /// with symlinks resolved, must be inside one of them. On Unix the opened + /// file must also be the one the path still resolves to. Elsewhere the check + /// runs only 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 an object that does not exist. pub remove_not_found_is_success: bool, @@ -97,7 +98,7 @@ impl Storage { config, client: OnceCell::new(), retry, - idle_limit, + idle_limit: idle_limit.filter(|limit| !limit.is_zero()), cancellation: CancellationToken::new(), } } @@ -549,6 +550,7 @@ async fn prepare( let name = requested.to_string_lossy().into_owned(); let local_error = |e| local_error(e, &name); let mut file = std::fs::File::open(&path).map_err(local_error)?; + confirm_opened(&file, &requested, &roots)?; let metadata = file.metadata().map_err(local_error)?; if metadata.is_file() && metadata.len() > 0 { return Ok(Local::Upload(Upload::File { @@ -567,7 +569,10 @@ async fn prepare( let name = requested.to_string_lossy().into_owned(); let local_error = |e| local_error(e, &name); let existing = match std::fs::OpenOptions::new().write(true).open(&path) { - Ok(file) => Some(file), + Ok(file) => { + confirm_opened(&file, &requested, &roots)?; + Some(file) + } Err(error) if error.kind() == std::io::ErrorKind::NotFound => None, Err(error) => return Err(local_error(error)), }; @@ -640,11 +645,15 @@ impl Local { let local_error = |e| local_error(e, &name); let mut file = match existing { Some(file) => file, - None => std::fs::OpenOptions::new() - .write(true) - .create_new(true) - .open(allowed_path(&requested, &roots)?) - .map_err(local_error)?, + None => { + let file = std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(allowed_path(&requested, &roots)?) + .map_err(local_error)?; + confirm_opened(&file, &requested, &roots)?; + file + } }; temp.rewind().map_err(local_error)?; let length = std::io::copy(&mut temp, &mut file).map_err(local_error)?; @@ -751,14 +760,39 @@ fn allowed_path(requested: &Path, roots: &[PathBuf]) -> Result { { Ok(path) } else { - Err(Error::invalid_argument() - .with_error_code("VOLUME_PATH_NOT_ALLOWED") - .message(format!( - "Local file path is outside the configured allowed roots: {name}" - ))) + Err(path_not_allowed(&name)) } } +fn path_not_allowed(name: &str) -> Error { + Error::invalid_argument() + .with_error_code("VOLUME_PATH_NOT_ALLOWED") + .message(format!( + "Local file path is outside the configured allowed roots: {name}" + )) +} + +/// Fails unless `file` is the file `requested` resolves to now, inside the +/// allowed roots, so a link swapped in after the check cannot redirect the open. +#[cfg(unix)] +fn confirm_opened(file: &std::fs::File, requested: &Path, roots: &[PathBuf]) -> Result<()> { + use std::os::unix::fs::MetadataExt; + let name = requested.to_string_lossy(); + let current = + std::fs::metadata(allowed_path(requested, roots)?).map_err(|e| local_error(e, &name))?; + let opened = file.metadata().map_err(|e| local_error(e, &name))?; + if (opened.dev(), opened.ino()) == (current.dev(), current.ino()) { + Ok(()) + } else { + Err(path_not_allowed(&name)) + } +} + +#[cfg(not(unix))] +fn confirm_opened(_: &std::fs::File, _: &Path, _: &[PathBuf]) -> Result<()> { + Ok(()) +} + /// `path` made absolute with symlinks resolved. Trailing components that do /// not exist yet are kept as written; a dangling symlink is an error. fn resolve(path: &Path) -> std::io::Result { @@ -1124,13 +1158,15 @@ mod tests { let source = dir.path().join("source"); std::fs::write(&source, vec![b'x'; 16 * 1024 * 1024]).unwrap(); let destination = dir.path().join("destination"); - // (operation, scheme, bytes the peer trickles before stalling, expected to finish). - // The peer never answers a TLS handshake, so the https row stalls connection setup. - for (operation, scheme, sent, finishes) in [ - ("GET", "http", 15, true), - ("GET", "http", 1, false), - ("PUT", "http", 0, false), - ("GET", "https", 0, false), + // (operation, scheme, bytes the peer trickles before stalling, idle limit in ms, + // expected to finish). Zero sets no limit. The peer never answers a TLS + // handshake, so the https row stalls connection setup. + for (operation, scheme, sent, limit, finishes) in [ + ("GET", "http", 15, 500, true), + ("GET", "http", 15, 0, true), + ("GET", "http", 1, 500, false), + ("PUT", "http", 0, 500, false), + ("GET", "https", 0, 500, false), ] { let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); let url = format!("{scheme}://{}", listener.local_addr().unwrap()); @@ -1157,7 +1193,7 @@ mod tests { }; let transfer = instruction(operation, &url, local); let result = run( - &state(0, Some(Duration::from_millis(500))), + &state(0, Some(Duration::from_millis(limit))), transfer, dir.path(), None, @@ -1281,6 +1317,33 @@ mod tests { assert!(!outside.join("file").exists()); } + #[test] + #[cfg(unix)] + fn an_opened_file_must_be_the_one_its_path_still_resolves_to() { + let dir = tempfile::tempdir().unwrap(); + let (root, outside) = (dir.path().join("root"), dir.path().join("outside")); + std::fs::create_dir(&root).unwrap(); + std::fs::create_dir(&outside).unwrap(); + let (file, secret) = (root.join("file"), outside.join("secret")); + std::fs::write(&file, b"file").unwrap(); + std::fs::write(&secret, b"secret").unwrap(); + let roots = [root]; + confirm_opened(&std::fs::File::open(&file).unwrap(), &file, &roots).unwrap(); + let not_allowed = |opened: &std::fs::File| { + confirm_opened(opened, &file, &roots) + .unwrap_err() + .error_code + .unwrap() + }; + // The open followed a link to `secret` that was swapped back before the check. + let followed = std::fs::File::open(&secret).unwrap(); + assert_eq!(not_allowed(&followed), "VOLUME_PATH_NOT_ALLOWED"); + // The link is still in place. + std::fs::remove_file(&file).unwrap(); + std::os::unix::fs::symlink(&secret, &file).unwrap(); + assert_eq!(not_allowed(&followed), "VOLUME_PATH_NOT_ALLOWED"); + } + #[tokio::test] async fn put_sources_without_a_usable_size_upload_their_content() { let server = MockServer::start().await; diff --git a/tests/v0_volume_e2e.rs b/tests/v0_volume_e2e.rs new file mode 100644 index 00000000..ae7024bb --- /dev/null +++ b/tests/v0_volume_e2e.rs @@ -0,0 +1,113 @@ +// 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. + +//! End-to-end Volume PUT, GET and REMOVE against a live Databricks workspace. +//! +//! The test uses the `main.oss_odbc_probe.kernel_volume_e2e` Volume and skips +//! (rather than fails) if it can't create it. +//! +//! Run with: +//! +//! ```sh +//! set -a && source ~/.databricks/pecotesting-creds && set +a +//! cargo test --test v0_volume_e2e -- --ignored +//! ``` + +mod common; + +use databricks_sql_kernel::{Session, VolumeCompletion, VolumeOptions}; +use std::time::{SystemTime, UNIX_EPOCH}; + +const SCHEMA: &str = "main.oss_odbc_probe"; +const VOLUME: &str = "main.oss_odbc_probe.kernel_volume_e2e"; + +async fn complete( + session: &Session, + sql: &str, + options: &VolumeOptions, + input: Option>, +) -> databricks_sql_kernel::Result { + let mut statement = session.statement(); + statement.spec().sql(sql); + let mut executed = statement.execute().await?; + let stream = executed.result_stream_mut(); + assert!(stream.is_volume_operation(), "{sql}"); + match stream.complete_volume_operation(options, None).await? { + VolumeCompletion::NeedsInputStream if input.is_some() => { + stream.complete_volume_operation(options, input).await + } + outcome => Ok(outcome), + } +} + +#[tokio::test] +#[ignore] +async fn put_get_and_remove_move_files_through_a_volume() { + let session = common::live_session().await; + for sql in [ + format!("CREATE SCHEMA IF NOT EXISTS {SCHEMA}"), + format!("CREATE VOLUME IF NOT EXISTS {VOLUME}"), + ] { + let mut statement = session.statement(); + statement.spec().sql(&sql); + if let Err(error) = statement.execute().await { + eprintln!("skipping: {sql} failed: {error}"); + return; + } + } + let dir = tempfile::tempdir().unwrap(); + let options = VolumeOptions::new(vec![dir.path().to_owned()], false); + let unique = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_nanos(); + let remote = format!("/Volumes/main/oss_odbc_probe/kernel_volume_e2e/{unique}"); + let source = dir.path().join("source"); + let destination = dir.path().join("destination"); + let content: Vec = (0..=255).cycle().take(1 << 20).collect(); + std::fs::write(&source, &content).unwrap(); + let get = format!("GET '{remote}' TO '{}'", destination.display()); + + // A file upload, then a shorter upload from caller bytes that replaces it + // and is downloaded over the existing destination. + for (sql, input, expected) in [ + ( + format!("PUT '{}' INTO '{remote}' OVERWRITE", source.display()), + None, + content, + ), + ( + format!("PUT '__input_stream__' INTO '{remote}' OVERWRITE"), + Some(b"from bytes".to_vec()), + b"from bytes".to_vec(), + ), + ] { + assert_eq!( + complete(&session, &sql, &options, input).await.unwrap(), + VolumeCompletion::Completed + ); + assert_eq!( + complete(&session, &get, &options, None).await.unwrap(), + VolumeCompletion::Completed + ); + assert_eq!(std::fs::read(&destination).unwrap(), expected); + } + + let remove = format!("REMOVE '{remote}'"); + assert_eq!( + complete(&session, &remove, &options, None).await.unwrap(), + VolumeCompletion::Completed + ); + assert!(complete(&session, &get, &options, None).await.is_err()); +} From 7a2ea6c23be20048a5fe7367a82decc14df4ac49 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Tue, 1 Dec 2026 04:19:37 +0000 Subject: [PATCH 07/43] fix(volume): infer the Windows test buffer type and drop the live Volume test - `put_sources_without_a_usable_size_upload_their_content` names its buffer type, which Windows cannot infer without the Unix-only rows. - `tests/v0_volume_e2e.rs` is removed with its Rust E2E entry: the CI principal cannot create a Volume, so it only ever skipped. Co-authored-by: Isaac Signed-off-by: Aakash Saravanan --- .github/workflows/rust-e2e.yml | 2 +- src/volume.rs | 2 +- tests/v0_volume_e2e.rs | 113 --------------------------------- 3 files changed, 2 insertions(+), 115 deletions(-) delete mode 100644 tests/v0_volume_e2e.rs diff --git a/.github/workflows/rust-e2e.yml b/.github/workflows/rust-e2e.yml index fa094808..cf0cef74 100644 --- a/.github/workflows/rust-e2e.yml +++ b/.github/workflows/rust-e2e.yml @@ -93,7 +93,7 @@ jobs: - name: Run v0 E2E tests run: | - for suite in v0_session_e2e v0_execute_e2e v0_async_execute_e2e v0_metadata_e2e v0_query_tags_headers_e2e v0_volume_e2e; do + for suite in v0_session_e2e v0_execute_e2e v0_async_execute_e2e v0_metadata_e2e v0_query_tags_headers_e2e; do echo "::group::cargo test --test ${suite}" cargo test --test "${suite}" -- --ignored --nocapture echo "::endgroup::" diff --git a/src/volume.rs b/src/volume.rs index 8d59abb5..0aeeb877 100644 --- a/src/volume.rs +++ b/src/volume.rs @@ -1354,7 +1354,7 @@ mod tests { let dir = tempfile::tempdir().unwrap(); let empty = dir.path().join("empty"); std::fs::write(&empty, b"").unwrap(); - let mut sources = vec![(empty, dir.path().to_owned(), Vec::new())]; + let mut sources = vec![(empty, dir.path().to_owned(), Vec::::new())]; #[cfg(unix)] { let fifo = dir.path().join("fifo"); diff --git a/tests/v0_volume_e2e.rs b/tests/v0_volume_e2e.rs deleted file mode 100644 index ae7024bb..00000000 --- a/tests/v0_volume_e2e.rs +++ /dev/null @@ -1,113 +0,0 @@ -// 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. - -//! End-to-end Volume PUT, GET and REMOVE against a live Databricks workspace. -//! -//! The test uses the `main.oss_odbc_probe.kernel_volume_e2e` Volume and skips -//! (rather than fails) if it can't create it. -//! -//! Run with: -//! -//! ```sh -//! set -a && source ~/.databricks/pecotesting-creds && set +a -//! cargo test --test v0_volume_e2e -- --ignored -//! ``` - -mod common; - -use databricks_sql_kernel::{Session, VolumeCompletion, VolumeOptions}; -use std::time::{SystemTime, UNIX_EPOCH}; - -const SCHEMA: &str = "main.oss_odbc_probe"; -const VOLUME: &str = "main.oss_odbc_probe.kernel_volume_e2e"; - -async fn complete( - session: &Session, - sql: &str, - options: &VolumeOptions, - input: Option>, -) -> databricks_sql_kernel::Result { - let mut statement = session.statement(); - statement.spec().sql(sql); - let mut executed = statement.execute().await?; - let stream = executed.result_stream_mut(); - assert!(stream.is_volume_operation(), "{sql}"); - match stream.complete_volume_operation(options, None).await? { - VolumeCompletion::NeedsInputStream if input.is_some() => { - stream.complete_volume_operation(options, input).await - } - outcome => Ok(outcome), - } -} - -#[tokio::test] -#[ignore] -async fn put_get_and_remove_move_files_through_a_volume() { - let session = common::live_session().await; - for sql in [ - format!("CREATE SCHEMA IF NOT EXISTS {SCHEMA}"), - format!("CREATE VOLUME IF NOT EXISTS {VOLUME}"), - ] { - let mut statement = session.statement(); - statement.spec().sql(&sql); - if let Err(error) = statement.execute().await { - eprintln!("skipping: {sql} failed: {error}"); - return; - } - } - let dir = tempfile::tempdir().unwrap(); - let options = VolumeOptions::new(vec![dir.path().to_owned()], false); - let unique = SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap() - .as_nanos(); - let remote = format!("/Volumes/main/oss_odbc_probe/kernel_volume_e2e/{unique}"); - let source = dir.path().join("source"); - let destination = dir.path().join("destination"); - let content: Vec = (0..=255).cycle().take(1 << 20).collect(); - std::fs::write(&source, &content).unwrap(); - let get = format!("GET '{remote}' TO '{}'", destination.display()); - - // A file upload, then a shorter upload from caller bytes that replaces it - // and is downloaded over the existing destination. - for (sql, input, expected) in [ - ( - format!("PUT '{}' INTO '{remote}' OVERWRITE", source.display()), - None, - content, - ), - ( - format!("PUT '__input_stream__' INTO '{remote}' OVERWRITE"), - Some(b"from bytes".to_vec()), - b"from bytes".to_vec(), - ), - ] { - assert_eq!( - complete(&session, &sql, &options, input).await.unwrap(), - VolumeCompletion::Completed - ); - assert_eq!( - complete(&session, &get, &options, None).await.unwrap(), - VolumeCompletion::Completed - ); - assert_eq!(std::fs::read(&destination).unwrap(), expected); - } - - let remove = format!("REMOVE '{remote}'"); - assert_eq!( - complete(&session, &remove, &options, None).await.unwrap(), - VolumeCompletion::Completed - ); - assert!(complete(&session, &get, &options, None).await.is_err()); -} From 964eef2a40d36b86cca02cfcf81c07984f974517 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Tue, 1 Dec 2026 04:43:05 +0000 Subject: [PATCH 08/43] test(volume): allow the unused mut on Windows in the size-less source test Only Unix adds rows to the list of sources, so Windows builds the test with an unused `mut`, which `-D warnings` rejects. Co-authored-by: Isaac 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 0aeeb877..37191826 100644 --- a/src/volume.rs +++ b/src/volume.rs @@ -1354,6 +1354,7 @@ mod tests { let dir = tempfile::tempdir().unwrap(); let empty = dir.path().join("empty"); std::fs::write(&empty, b"").unwrap(); + #[cfg_attr(not(unix), allow(unused_mut))] let mut sources = vec![(empty, dir.path().to_owned(), Vec::::new())]; #[cfg(unix)] { From dbdbfa7ff446208f1fd5f9033ac3f0a43af73f47 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Tue, 1 Dec 2026 05:06:04 +0000 Subject: [PATCH 09/43] docs(volume): state that a GET decodes a gzip Content-Encoding `complete_volume_operation` and the storage client say that a GET of an object stored with a gzip `Content-Encoding` writes the decoded content, which is what the header says the object holds. Co-authored-by: Isaac Signed-off-by: Aakash Saravanan --- src/client/http.rs | 2 ++ src/result_stream.rs | 17 +++++++++-------- 2 files changed, 11 insertions(+), 8 deletions(-) diff --git a/src/client/http.rs b/src/client/http.rs index 7b8005e3..5ce3b71e 100644 --- a/src/client/http.rs +++ b/src/client/http.rs @@ -847,6 +847,8 @@ impl DatabricksHttpClient { /// Build the client for Volume storage requests: the session's connection /// settings without a total deadline, and redirects left to the caller. + /// Response decoding stays on, so a GET of an object stored with a gzip + /// `Content-Encoding` writes the content that header says it holds. pub(crate) fn storage_client(config: &HttpClientConfig) -> Result { Self::build_reqwest_client(config, reqwest::redirect::Policy::none(), None, None) } diff --git a/src/result_stream.rs b/src/result_stream.rs index 4a90bf11..6af07c0b 100644 --- a/src/result_stream.rs +++ b/src/result_stream.rs @@ -671,17 +671,18 @@ impl ResultStream { /// return the first outcome without transferring again. /// /// Call before reading rows; the instruction row stays readable. A GET - /// replaces the destination only after the download succeeds; a failure - /// while copying into an existing file can leave it partly written. A - /// call abandoned mid-transfer makes later calls return `Cancelled`. A result - /// from [`Session::attach_async_statement`](crate::Session::attach_async_statement) + /// writes the object's content: a gzip `Content-Encoding` is decoded, + /// because it marks the stored bytes as a compressed form of that content. + /// A GET replaces the destination only after the download succeeds; a + /// failure while copying into an existing file can leave it partly written. + /// A call abandoned mid-transfer makes later calls return `Cancelled`. A + /// result from [`Session::attach_async_statement`](crate::Session::attach_async_statement) /// cannot transfer and returns an error. Keep an /// [`ExecutedAsyncStatement`](crate::ExecutedAsyncStatement) open until its /// transfer finishes: cancelling, closing or dropping it stops the transfer. - /// A PUT of - /// caller-supplied bytes returns `NeedsInputStream` until called with - /// `input_bytes`. Cancelling stops the transfer but cannot undo a PUT or - /// REMOVE that storage already applied. + /// A PUT of caller-supplied bytes returns `NeedsInputStream` until called + /// with `input_bytes`. Cancelling stops the transfer but cannot undo a PUT + /// or REMOVE that storage already applied. pub async fn complete_volume_operation( &mut self, options: &crate::volume::VolumeOptions, From 38ac5a1b91ddac561953a3e952e42f807da0de95 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Tue, 1 Dec 2026 05:12:04 +0000 Subject: [PATCH 10/43] docs(volume): state the allowed-directory assumption on every platform The Unix check after opening narrows the window for a swapped link but does not close it, so `VolumeOptions.allowed_paths` states the assumption for every platform. Co-authored-by: Isaac Signed-off-by: Aakash Saravanan --- src/volume.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/volume.rs b/src/volume.rs index 37191826..0af3e4d3 100644 --- a/src/volume.rs +++ b/src/volume.rs @@ -49,10 +49,10 @@ const UPLOAD_CHUNK: usize = 256 * 1024; #[derive(Debug, Clone, Default)] pub struct VolumeOptions { /// Directories a PUT may read from and a GET may write to. The local path, - /// with symlinks resolved, must be inside one of them. On Unix the opened - /// file must also be the one the path still resolves to. Elsewhere the check - /// runs only before the file is opened, so nothing else may swap files or - /// links in these directories during a transfer. + /// with symlinks resolved, must be inside one of them, and on Unix the + /// opened file must also be the one the path still resolves to. The checks + /// assume nothing else swaps files or links in these directories during a + /// transfer. pub allowed_paths: Vec, /// Report success when REMOVE targets an object that does not exist. pub remove_not_found_is_success: bool, From 23cb9c6c74e0c9049c035ac307d1fb842ccc7c10 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Tue, 1 Dec 2026 06:14:25 +0000 Subject: [PATCH 11/43] fix(volume): transfer regular local files only and check paths once - A PUT source or an existing GET destination must be a regular file, checked before the open: a pipe or device has no length to send and can block the open indefinitely. Other data goes to a PUT as caller-supplied bytes. - The Unix recheck after opening is removed. It narrowed a link swap during a transfer but could not close it, so the allowed-directory check runs once per open or create and documents its assumption. Co-authored-by: Isaac Signed-off-by: Aakash Saravanan --- src/result_stream.rs | 5 +- src/volume.rs | 161 +++++++++++++++++++------------------------ 2 files changed, 73 insertions(+), 93 deletions(-) diff --git a/src/result_stream.rs b/src/result_stream.rs index 6af07c0b..0f9f8205 100644 --- a/src/result_stream.rs +++ b/src/result_stream.rs @@ -680,8 +680,9 @@ impl ResultStream { /// cannot transfer and returns an error. Keep an /// [`ExecutedAsyncStatement`](crate::ExecutedAsyncStatement) open until its /// transfer finishes: cancelling, closing or dropping it stops the transfer. - /// A PUT of caller-supplied bytes returns `NeedsInputStream` until called - /// with `input_bytes`. Cancelling stops the transfer but cannot undo a PUT + /// Local files must be regular files. A PUT of caller-supplied bytes, such + /// as a pipe's content, returns `NeedsInputStream` until called with + /// `input_bytes`. Cancelling stops the transfer but cannot undo a PUT /// or REMOVE that storage already applied. pub async fn complete_volume_operation( &mut self, diff --git a/src/volume.rs b/src/volume.rs index 0af3e4d3..1b54a58b 100644 --- a/src/volume.rs +++ b/src/volume.rs @@ -49,10 +49,9 @@ const UPLOAD_CHUNK: usize = 256 * 1024; #[derive(Debug, Clone, Default)] pub struct VolumeOptions { /// Directories a PUT may read from and a GET may write to. The local path, - /// with symlinks resolved, must be inside one of them, and on Unix the - /// opened file must also be the one the path still resolves to. The checks - /// assume nothing else swaps files or links in these directories during a - /// transfer. + /// with symlinks resolved, must be inside one of them when the file is + /// opened or created. The check assumes nothing else swaps files or links in + /// these directories during a transfer. pub allowed_paths: Vec, /// Report success when REMOVE targets an object that does not exist. pub remove_not_found_is_success: bool, @@ -549,17 +548,19 @@ async fn prepare( let path = allowed_path(&requested, &roots)?; let name = requested.to_string_lossy().into_owned(); let local_error = |e| local_error(e, &name); + let metadata = std::fs::metadata(&path).map_err(local_error)?; + if !metadata.is_file() { + return Err(not_a_regular_file(&metadata, &name)); + } let mut file = std::fs::File::open(&path).map_err(local_error)?; - confirm_opened(&file, &requested, &roots)?; - let metadata = file.metadata().map_err(local_error)?; - if metadata.is_file() && metadata.len() > 0 { + if metadata.len() > 0 { return Ok(Local::Upload(Upload::File { file: Arc::new(file), length: metadata.len(), name, })); } - // Pipes and files such as procfs entries report no usable size. + // Files such as procfs entries report no size. let mut bytes = Vec::new(); file.read_to_end(&mut bytes).map_err(local_error)?; Ok(Local::Upload(Upload::Bytes(bytes.into()))) @@ -568,11 +569,16 @@ async fn prepare( let path = allowed_path(&requested, &roots)?; let name = requested.to_string_lossy().into_owned(); let local_error = |e| local_error(e, &name); - let existing = match std::fs::OpenOptions::new().write(true).open(&path) { - Ok(file) => { - confirm_opened(&file, &requested, &roots)?; - Some(file) + let existing = match std::fs::metadata(&path) { + Ok(metadata) if !metadata.is_file() => { + return Err(not_a_regular_file(&metadata, &name)) } + Ok(_) => Some( + std::fs::OpenOptions::new() + .write(true) + .open(&path) + .map_err(local_error)?, + ), Err(error) if error.kind() == std::io::ErrorKind::NotFound => None, Err(error) => return Err(local_error(error)), }; @@ -645,21 +651,15 @@ impl Local { let local_error = |e| local_error(e, &name); let mut file = match existing { Some(file) => file, - None => { - let file = std::fs::OpenOptions::new() - .write(true) - .create_new(true) - .open(allowed_path(&requested, &roots)?) - .map_err(local_error)?; - confirm_opened(&file, &requested, &roots)?; - file - } + None => std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(allowed_path(&requested, &roots)?) + .map_err(local_error)?, }; temp.rewind().map_err(local_error)?; let length = std::io::copy(&mut temp, &mut file).map_err(local_error)?; - if file.metadata().map_err(local_error)?.is_file() { - file.set_len(length).map_err(local_error)?; - } + file.set_len(length).map_err(local_error)?; Ok(()) }) .await @@ -760,37 +760,26 @@ fn allowed_path(requested: &Path, roots: &[PathBuf]) -> Result { { Ok(path) } else { - Err(path_not_allowed(&name)) + Err(Error::invalid_argument() + .with_error_code("VOLUME_PATH_NOT_ALLOWED") + .message(format!( + "Local file path is outside the configured allowed roots: {name}" + ))) } } -fn path_not_allowed(name: &str) -> Error { - Error::invalid_argument() - .with_error_code("VOLUME_PATH_NOT_ALLOWED") - .message(format!( - "Local file path is outside the configured allowed roots: {name}" - )) -} - -/// Fails unless `file` is the file `requested` resolves to now, inside the -/// allowed roots, so a link swapped in after the check cannot redirect the open. -#[cfg(unix)] -fn confirm_opened(file: &std::fs::File, requested: &Path, roots: &[PathBuf]) -> Result<()> { - use std::os::unix::fs::MetadataExt; - let name = requested.to_string_lossy(); - let current = - std::fs::metadata(allowed_path(requested, roots)?).map_err(|e| local_error(e, &name))?; - let opened = file.metadata().map_err(|e| local_error(e, &name))?; - if (opened.dev(), opened.ino()) == (current.dev(), current.ino()) { - Ok(()) +/// Transfers use regular files only: a pipe or device has no length to send +/// and can block the open indefinitely. +fn not_a_regular_file(metadata: &std::fs::Metadata, name: &str) -> Error { + let kind = if metadata.is_dir() { + std::io::ErrorKind::IsADirectory } else { - Err(path_not_allowed(&name)) - } -} - -#[cfg(not(unix))] -fn confirm_opened(_: &std::fs::File, _: &Path, _: &[PathBuf]) -> Result<()> { - Ok(()) + std::io::ErrorKind::InvalidInput + }; + local_error( + std::io::Error::new(kind, "Volume transfers use regular files only"), + name, + ) } /// `path` made absolute with symlinks resolved. Trailing components that do @@ -1317,33 +1306,6 @@ mod tests { assert!(!outside.join("file").exists()); } - #[test] - #[cfg(unix)] - fn an_opened_file_must_be_the_one_its_path_still_resolves_to() { - let dir = tempfile::tempdir().unwrap(); - let (root, outside) = (dir.path().join("root"), dir.path().join("outside")); - std::fs::create_dir(&root).unwrap(); - std::fs::create_dir(&outside).unwrap(); - let (file, secret) = (root.join("file"), outside.join("secret")); - std::fs::write(&file, b"file").unwrap(); - std::fs::write(&secret, b"secret").unwrap(); - let roots = [root]; - confirm_opened(&std::fs::File::open(&file).unwrap(), &file, &roots).unwrap(); - let not_allowed = |opened: &std::fs::File| { - confirm_opened(opened, &file, &roots) - .unwrap_err() - .error_code - .unwrap() - }; - // The open followed a link to `secret` that was swapped back before the check. - let followed = std::fs::File::open(&secret).unwrap(); - assert_eq!(not_allowed(&followed), "VOLUME_PATH_NOT_ALLOWED"); - // The link is still in place. - std::fs::remove_file(&file).unwrap(); - std::os::unix::fs::symlink(&secret, &file).unwrap(); - assert_eq!(not_allowed(&followed), "VOLUME_PATH_NOT_ALLOWED"); - } - #[tokio::test] async fn put_sources_without_a_usable_size_upload_their_content() { let server = MockServer::start().await; @@ -1354,20 +1316,8 @@ mod tests { let dir = tempfile::tempdir().unwrap(); let empty = dir.path().join("empty"); std::fs::write(&empty, b"").unwrap(); - #[cfg_attr(not(unix), allow(unused_mut))] + #[cfg_attr(not(target_os = "linux"), allow(unused_mut))] let mut sources = vec![(empty, dir.path().to_owned(), Vec::::new())]; - #[cfg(unix)] - { - let fifo = dir.path().join("fifo"); - assert!(std::process::Command::new("mkfifo") - .arg(&fifo) - .status() - .unwrap() - .success()); - let writer = fifo.clone(); - std::thread::spawn(move || std::fs::write(writer, b"piped").unwrap()); - sources.push((fifo, dir.path().to_owned(), b"piped".to_vec())); - } #[cfg(target_os = "linux")] sources.push(( PathBuf::from("/proc/self/cmdline"), @@ -1382,6 +1332,35 @@ mod tests { } } + #[tokio::test] + #[cfg(unix)] + async fn pipes_are_refused_without_waiting_for_the_other_end() { + let server = MockServer::start().await; + let dir = tempfile::tempdir().unwrap(); + let fifo = dir.path().join("fifo"); + assert!(std::process::Command::new("mkfifo") + .arg(&fifo) + .status() + .unwrap() + .success()); + for operation in ["PUT", "GET"] { + let transfer = instruction(operation, &server.uri(), &fifo); + let error = tokio::time::timeout( + Duration::from_secs(10), + run(&state(0, None), transfer, dir.path(), None), + ) + .await + .expect("a pipe must not block the open") + .unwrap_err(); + assert_eq!( + error.error_code.as_deref(), + Some("VOLUME_LOCAL_FILE_ERROR"), + "{operation}" + ); + } + assert!(server.received_requests().await.unwrap().is_empty()); + } + #[tokio::test] async fn local_failures_happen_before_any_storage_request() { let server = MockServer::start().await; From 703952a053dfa27ee36c33302051de0823d5049a Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Tue, 1 Dec 2026 21:50:37 +0000 Subject: [PATCH 12/43] fix(volume): apply the session's revocation policy to storage connections The session's certificate revocation mode covers every connection it makes, including CloudFetch downloads. Volume storage requests use their own client, which now receives the same effective mode. Co-authored-by: Isaac Signed-off-by: Aakash Saravanan --- src/client/http.rs | 7 +++++-- src/session.rs | 1 + src/telemetry/statement.rs | 1 + src/volume.rs | 33 +++++++++++++++++++++++++++++++-- 4 files changed, 38 insertions(+), 4 deletions(-) diff --git a/src/client/http.rs b/src/client/http.rs index 5ce3b71e..1797d897 100644 --- a/src/client/http.rs +++ b/src/client/http.rs @@ -849,8 +849,11 @@ impl DatabricksHttpClient { /// settings without a total deadline, and redirects left to the caller. /// Response decoding stays on, so a GET of an object stored with a gzip /// `Content-Encoding` writes the content that header says it holds. - pub(crate) fn storage_client(config: &HttpClientConfig) -> Result { - Self::build_reqwest_client(config, reqwest::redirect::Policy::none(), None, None) + pub(crate) fn storage_client( + config: &HttpClientConfig, + revocation: Option, + ) -> Result { + Self::build_reqwest_client(config, reqwest::redirect::Policy::none(), revocation, None) } /// Returns the client configuration. diff --git a/src/session.rs b/src/session.rs index 79129e19..0ecc9cf6 100644 --- a/src/session.rs +++ b/src/session.rs @@ -394,6 +394,7 @@ impl Session { ); let storage = Arc::new(crate::volume::Storage::new( http_client.config().clone(), + http_client.revocation(), storage_retry, config.http.storage_read_timeout, )); diff --git a/src/telemetry/statement.rs b/src/telemetry/statement.rs index b3d8cbd6..fd7c6e54 100644 --- a/src/telemetry/statement.rs +++ b/src/telemetry/statement.rs @@ -390,6 +390,7 @@ mod tests { .unwrap(); let storage = Arc::new(crate::volume::Storage::new( Default::default(), + None, Default::default(), None, )); diff --git a/src/volume.rs b/src/volume.rs index 1b54a58b..5f087644 100644 --- a/src/volume.rs +++ b/src/volume.rs @@ -81,6 +81,7 @@ pub enum VolumeCompletion { /// Storage access shared by a session's Volume transfers. pub(crate) struct Storage { config: HttpClientConfig, + revocation: Option, client: OnceCell, retry: RetryConfig, idle_limit: Option, @@ -90,11 +91,13 @@ pub(crate) struct Storage { impl Storage { pub(crate) fn new( config: HttpClientConfig, + revocation: Option, retry: RetryConfig, idle_limit: Option, ) -> Self { Self { config, + revocation, client: OnceCell::new(), retry, idle_limit: idle_limit.filter(|limit| !limit.is_zero()), @@ -128,7 +131,9 @@ impl Storage { async fn client(&self) -> Result<&Client> { self.client - .get_or_try_init(|| async { DatabricksHttpClient::storage_client(&self.config) }) + .get_or_try_init(|| async { + DatabricksHttpClient::storage_client(&self.config, self.revocation) + }) .await } } @@ -886,7 +891,13 @@ mod tests { max_wait: Duration::ZERO, ..Default::default() }; - Arc::new(Storage::new(HttpClientConfig::default(), retry, idle_limit)).transfer_state() + Arc::new(Storage::new( + HttpClientConfig::default(), + None, + retry, + idle_limit, + )) + .transfer_state() } fn instruction(operation: &str, url: &str, local: &Path) -> RecordBatch { @@ -1141,6 +1152,24 @@ mod tests { run(&state(0, None), put, dir.path(), None).await.unwrap(); } + #[tokio::test] + async fn storage_connections_apply_the_session_revocation_policy() { + let storage = Storage::new( + HttpClientConfig::default(), + Some(false), + RetryConfig::default(), + None, + ); + let unsupported = crate::client::http::revocation_unsupported_message( + cfg!(windows), + cfg!(feature = "tls-rustls"), + ); + assert_eq!( + storage.client().await.err().map(|error| error.message), + unsupported.map(String::from) + ); + } + #[tokio::test] async fn idle_limit_fails_stalled_transfers_but_not_slow_ones() { let dir = tempfile::tempdir().unwrap(); From e4687ec30a023e018fe78ed43651cc5c75757695 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Tue, 1 Dec 2026 22:33:16 +0000 Subject: [PATCH 13/43] fix(volume): write a new GET destination once and keep directory OS errors - A GET into a new file downloads to a temporary file in the destination folder, created with a new file's mode, and renames it into place after the path check, instead of copying it. A GET that overwrites an existing file still copies into it, keeping the file itself. - A PUT of a directory or a GET onto one reports the OS error for a directory (EISDIR on Unix), as opening it would, so drivers can raise their native error. - A cross-origin redirect is detected by comparing scheme, host and port instead of calling `Url::origin()`. Co-authored-by: Isaac Signed-off-by: Aakash Saravanan --- src/volume.rs | 165 +++++++++++++++++++++++++++++++++----------------- 1 file changed, 111 insertions(+), 54 deletions(-) diff --git a/src/volume.rs b/src/volume.rs index 5f087644..486e4589 100644 --- a/src/volume.rs +++ b/src/volume.rs @@ -284,7 +284,9 @@ impl VolumeState { if let Some(next) = redirect_target(response.status(), location, &url, &method) .map_err(|e| (e, None))? { - if next.origin() != url.origin() { + if (next.scheme(), next.host_str(), next.port_or_known_default()) + != (url.scheme(), url.host_str(), url.port_or_known_default()) + { for name in [AUTHORIZATION, COOKIE, PROXY_AUTHORIZATION] { headers.remove(name); } @@ -529,17 +531,26 @@ enum Upload { Bytes(Bytes), } -/// A GET downloads to `temp` and copies it to the destination only after -/// success, so a failed download leaves an existing file unchanged. A new -/// destination is checked against the allowed roots again when it is created. +/// A GET downloads to `temp`, so a failed download leaves the destination +/// unchanged. struct Download { temp: std::fs::File, - existing: Option, - requested: PathBuf, - roots: Vec, + destination: Destination, name: String, } +enum Destination { + /// Overwritten with a copy of the download, keeping the file itself. + Existing(std::fs::File), + /// `temp`, renamed into place after its path is checked against the + /// allowed roots again. + New { + temp: tempfile::TempPath, + requested: PathBuf, + roots: Vec, + }, +} + async fn prepare( operation: Operation, roots: Vec, @@ -574,37 +585,50 @@ async fn prepare( let path = allowed_path(&requested, &roots)?; let name = requested.to_string_lossy().into_owned(); let local_error = |e| local_error(e, &name); - let existing = match std::fs::metadata(&path) { + let parent = path + .parent() + .ok_or_else(|| invalid("Invalid Volume local file"))?; + let (temp, destination) = match std::fs::metadata(&path) { Ok(metadata) if !metadata.is_file() => { return Err(not_a_regular_file(&metadata, &name)) } - Ok(_) => Some( - std::fs::OpenOptions::new() + Ok(_) => { + let file = std::fs::OpenOptions::new() .write(true) .open(&path) - .map_err(local_error)?, - ), - Err(error) if error.kind() == std::io::ErrorKind::NotFound => None, + .map_err(local_error)?; + let temp = match tempfile::tempfile_in(parent) { + Err(error) if error.kind() == std::io::ErrorKind::PermissionDenied => { + tempfile::tempfile() + } + temp => temp, + } + .map_err(local_error)?; + (temp, Destination::Existing(file)) + } + Err(error) if error.kind() == std::io::ErrorKind::NotFound => { + let mut builder = tempfile::Builder::new(); + // The mode a newly created file gets, rather than owner-only. + #[cfg(unix)] + builder.permissions(std::os::unix::fs::PermissionsExt::from_mode(0o666)); + let (temp, path) = builder + .tempfile_in(parent) + .map_err(local_error)? + .into_parts(); + ( + temp, + Destination::New { + temp: path, + requested, + roots, + }, + ) + } Err(error) => return Err(local_error(error)), }; - let parent = path - .parent() - .ok_or_else(|| invalid("Invalid Volume local file"))?; - let temp = match tempfile::tempfile_in(parent) { - Err(error) - if error.kind() == std::io::ErrorKind::PermissionDenied - && existing.is_some() => - { - tempfile::tempfile() - } - temp => temp, - } - .map_err(local_error)?; Ok(Local::Download(Download { temp, - existing, - requested, - roots, + destination, name, })) } @@ -644,9 +668,7 @@ impl Local { async fn publish(self) -> Result<()> { let Local::Download(Download { mut temp, - existing, - requested, - roots, + destination, name, }) = self else { @@ -654,18 +676,22 @@ impl Local { }; tokio::task::spawn_blocking(move || { let local_error = |e| local_error(e, &name); - let mut file = match existing { - Some(file) => file, - None => std::fs::OpenOptions::new() - .write(true) - .create_new(true) - .open(allowed_path(&requested, &roots)?) - .map_err(local_error)?, - }; - temp.rewind().map_err(local_error)?; - let length = std::io::copy(&mut temp, &mut file).map_err(local_error)?; - file.set_len(length).map_err(local_error)?; - Ok(()) + match destination { + Destination::Existing(mut file) => { + temp.rewind().map_err(local_error)?; + let length = std::io::copy(&mut temp, &mut file).map_err(local_error)?; + file.set_len(length).map_err(local_error) + } + Destination::New { + temp: path, + requested, + roots, + } => { + drop(temp); + path.persist_noclobber(allowed_path(&requested, &roots)?) + .map_err(|e| local_error(e.error)) + } + } }) .await .map_err(|e| Error::internal().message(format!("Volume download copy failed: {e}")))? @@ -774,17 +800,22 @@ fn allowed_path(requested: &Path, roots: &[PathBuf]) -> Result { } /// Transfers use regular files only: a pipe or device has no length to send -/// and can block the open indefinitely. +/// and can block the open indefinitely. A directory gets the error the OS +/// gives for reading or writing one. fn not_a_regular_file(metadata: &std::fs::Metadata, name: &str) -> Error { - let kind = if metadata.is_dir() { - std::io::ErrorKind::IsADirectory + let error = if metadata.is_dir() { + #[cfg(unix)] + let error = std::io::Error::from_raw_os_error(libc::EISDIR); + #[cfg(not(unix))] + let error = std::io::Error::from(std::io::ErrorKind::IsADirectory); + error } else { - std::io::ErrorKind::InvalidInput + std::io::Error::new( + std::io::ErrorKind::InvalidInput, + "Volume transfers use regular files only", + ) }; - local_error( - std::io::Error::new(kind, "Volume transfers use regular files only"), - name, - ) + local_error(error, name) } /// `path` made absolute with symlinks resolved. Trailing components that do @@ -951,7 +982,7 @@ mod tests { Mock::given(method("GET")) .and(path("/get")) .respond_with(ResponseTemplate::new(200).set_body_bytes(payload.clone())) - .expect(1) + .expect(2) .mount(&server) .await; Mock::given(method("DELETE")) @@ -995,6 +1026,18 @@ mod tests { let get = instruction("GET", &url("get"), &destination); run(&state(0, None), get, dir.path(), None).await.unwrap(); assert_eq!(std::fs::read(&destination).unwrap(), payload); + // A new destination is the download itself, with a new file's mode. + let new = dir.path().join("new"); + let get = instruction("GET", &url("get"), &new); + run(&state(0, None), get, dir.path(), None).await.unwrap(); + assert_eq!(std::fs::read(&new).unwrap(), payload); + assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 3); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let mode = |path: &Path| std::fs::metadata(path).unwrap().permissions().mode(); + assert_eq!(mode(&new), mode(&source)); + } let remove = instruction("REMOVE", &url("remove"), Path::new("")); run(&state(0, None), remove, dir.path(), None) .await @@ -1323,7 +1366,7 @@ mod tests { while server.received_requests().await.unwrap().is_empty() { tokio::task::yield_now().await; } - std::fs::remove_dir(root.join("sub")).unwrap(); + std::fs::rename(root.join("sub"), dir.path().join("moved")).unwrap(); std::os::unix::fs::symlink(&outside, root.join("sub")).unwrap(); }; let state = state(0, None); @@ -1418,6 +1461,20 @@ mod tests { .await .unwrap_err(); assert_eq!(error.code, ErrorCode::NotFound); + for operation in ["PUT", "GET"] { + let error = run( + &state(0, None), + instruction(operation, &url, dir.path()), + dir.path(), + None, + ) + .await + .unwrap_err(); + let local = error.local_error.unwrap(); + assert_eq!(local.kind, std::io::ErrorKind::IsADirectory, "{operation}"); + #[cfg(unix)] + assert_eq!(local.raw_os_error, Some(libc::EISDIR), "{operation}"); + } #[cfg(unix)] { use std::os::unix::fs::PermissionsExt; From 9e0b4726147b28ad2104c681dbce28a7f81fd7d0 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Tue, 1 Dec 2026 23:22:42 +0000 Subject: [PATCH 14/43] feat(volume): let a GET write into an existing pipe or character device On Unix a GET into an existing pipe or character device, such as `/dev/null`, writes the download as it arrives instead of being refused. - A pipe is opened when the storage response arrives. A non-blocking open fails until the pipe has a reader, so it is retried until one appears, the idle limit passes or the transfer is cancelled. - Writes are async and count against the idle limit, so a reader that stops reading fails the transfer instead of blocking it. - The pipe stays open across retries, and once bytes reach it a failure is not retried, since they cannot be taken back. - Block devices and sockets are still refused, as is any non-regular file on Windows. A PUT still reads regular files only. Co-authored-by: Isaac Signed-off-by: Aakash Saravanan --- NEXT_CHANGELOG.md | 3 +- src/result_stream.rs | 9 +- src/volume.rs | 365 ++++++++++++++++++++++++++++++++++--------- 3 files changed, 298 insertions(+), 79 deletions(-) diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index effc2f2e..f4e749e8 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -26,7 +26,8 @@ changes go in their respective binding's NEXT_CHANGELOG. runs the file transfer for a result the server marks as a Volume operation. Local paths, with symlinks resolved, must be inside the caller's allowed directories. `HttpConfig::storage_read_timeout` limits how long a transfer - may go without progress (15 minutes by default). + may go without progress (15 minutes by default). On Unix a GET can also + write into an existing pipe or character device as the download arrives. ### Changed diff --git a/src/result_stream.rs b/src/result_stream.rs index 0f9f8205..fadc6e8d 100644 --- a/src/result_stream.rs +++ b/src/result_stream.rs @@ -673,15 +673,18 @@ impl ResultStream { /// Call before reading rows; the instruction row stays readable. A GET /// writes the object's content: a gzip `Content-Encoding` is decoded, /// because it marks the stored bytes as a compressed form of that content. - /// A GET replaces the destination only after the download succeeds; a + /// A GET into a file replaces it only after the download succeeds; a /// failure while copying into an existing file can leave it partly written. + /// On Unix a GET also writes into an existing pipe or character device as + /// the download arrives: a pipe waits for a reader up to the idle limit, and + /// a failure after the first bytes reach it is not retried. /// A call abandoned mid-transfer makes later calls return `Cancelled`. A /// result from [`Session::attach_async_statement`](crate::Session::attach_async_statement) /// cannot transfer and returns an error. Keep an /// [`ExecutedAsyncStatement`](crate::ExecutedAsyncStatement) open until its /// transfer finishes: cancelling, closing or dropping it stops the transfer. - /// Local files must be regular files. A PUT of caller-supplied bytes, such - /// as a pipe's content, returns `NeedsInputStream` until called with + /// A PUT reads a regular file. A PUT of caller-supplied bytes, such as a + /// pipe's content, returns `NeedsInputStream` until called with /// `input_bytes`. Cancelling stops the transfer but cannot undo a PUT /// or REMOVE that storage already applied. pub async fn complete_volume_operation( diff --git a/src/volume.rs b/src/volume.rs index 486e4589..e6c3e436 100644 --- a/src/volume.rs +++ b/src/volume.rs @@ -35,7 +35,7 @@ use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; use std::time::{Duration, Instant}; -use tokio::io::{AsyncSeekExt, AsyncWriteExt}; +use tokio::io::{AsyncSeekExt, AsyncWrite, AsyncWriteExt}; use tokio::sync::{watch, OnceCell}; use tokio_util::bytes::Bytes; use tokio_util::sync::CancellationToken; @@ -43,6 +43,8 @@ use tokio_util::sync::CancellationToken; const MAX_REDIRECTS: usize = 10; const ERROR_BODY_LIMIT: usize = 4096; const UPLOAD_CHUNK: usize = 256 * 1024; +#[cfg(unix)] +const PIPE_READER_POLL: Duration = Duration::from_millis(50); /// Caller settings for a Volume file transfer. #[non_exhaustive] @@ -313,7 +315,9 @@ impl VolumeState { )) } - /// Writes a GET response body to the download's temporary file. + /// Writes a GET response body to the download's temporary file, or to its + /// pipe or device. Bytes a pipe or device already took cannot be taken + /// back, so a failure after the first write is not retried. async fn receive( &self, mut response: Response, @@ -324,22 +328,103 @@ impl VolumeState { return Ok(()); }; let local_error = |e| local_error(e, &download.name); - let mut file = tokio::fs::File::from_std(download.temp.try_clone().map_err(local_error)?); - file.set_len(0).await.map_err(local_error)?; - file.rewind().await.map_err(local_error)?; + let mut temp_file; + #[cfg(unix)] + let mut stream; + let (sink, rewindable): (&mut (dyn AsyncWrite + Send + Unpin), bool) = + match &download.destination { + Destination::Existing { temp, .. } | Destination::New { temp, .. } => { + temp_file = tokio::fs::File::from_std(temp.try_clone().map_err(local_error)?); + temp_file.set_len(0).await.map_err(local_error)?; + temp_file.rewind().await.map_err(local_error)?; + (&mut temp_file, true) + } + #[cfg(unix)] + Destination::Stream { + fifo, + requested, + roots, + writer, + } => { + stream = writer.lock().await; + if stream.is_none() { + *stream = Some( + self.open_stream(requested, roots, *fifo, &download.name) + .await?, + ); + } + (stream.as_mut().expect("opened above").as_mut(), false) + } + }; let (_, mut no_progress) = watch::channel(()); - while let Some(chunk) = self - .idle_bounded(&mut no_progress, async { - response - .chunk() - .await - .map_err(|e| storage_error(e, strategy)) - }) - .await? - { - file.write_all(&chunk).await.map_err(local_error)?; + let mut written = false; + let result = async { + while let Some(chunk) = self + .idle_bounded(&mut no_progress, async { + response + .chunk() + .await + .map_err(|e| storage_error(e, strategy)) + }) + .await? + { + self.idle_bounded(&mut no_progress, async { + sink.write_all(&chunk).await.map_err(local_error) + }) + .await?; + written = true; + } + sink.flush().await.map_err(local_error) } - file.flush().await.map_err(local_error) + .await; + result.map_err(|error| { + if written && !rewindable { + error.with_retryable(false) + } else { + error + } + }) + } + + /// Opens a GET's pipe or device. A pipe refuses a non-blocking open until + /// it has a reader, so the open is retried until one appears, the idle + /// limit passes or the transfer is cancelled. + #[cfg(unix)] + async fn open_stream( + &self, + requested: &Path, + roots: &[PathBuf], + fifo: bool, + name: &str, + ) -> Result> { + let path = allowed_path(requested, roots)?; + let local_error = |e| local_error(e, name); + if !fifo { + let device = tokio::fs::OpenOptions::new() + .write(true) + .open(&path) + .await + .map_err(local_error)?; + return Ok(Box::new(device)); + } + let wait_for_reader = async { + loop { + match tokio::net::unix::pipe::OpenOptions::new().open_sender(&path) { + Err(error) if error.raw_os_error() == Some(libc::ENXIO) => { + tokio::time::sleep(PIPE_READER_POLL).await + } + result => return result, + } + } + }; + let sender = match self.storage.idle_limit { + Some(limit) => tokio::time::timeout(limit, wait_for_reader) + .await + .unwrap_or_else(|_| Err(std::io::Error::from_raw_os_error(libc::ENXIO))), + None => wait_for_reader.await, + } + .map_err(local_error)?; + Ok(Box::new(sender)) } async fn http_failure( @@ -531,24 +616,37 @@ enum Upload { Bytes(Bytes), } -/// A GET downloads to `temp`, so a failed download leaves the destination -/// unchanged. struct Download { - temp: std::fs::File, destination: Destination, name: String, } +/// A GET into a file downloads to `temp` first, so a failed download leaves +/// the file unchanged. enum Destination { - /// Overwritten with a copy of the download, keeping the file itself. - Existing(std::fs::File), + /// Overwritten with a copy of `temp`, keeping the file itself. + Existing { + file: std::fs::File, + temp: std::fs::File, + }, /// `temp`, renamed into place after its path is checked against the /// allowed roots again. New { - temp: tempfile::TempPath, + temp: std::fs::File, + path: tempfile::TempPath, requested: PathBuf, roots: Vec, }, + /// A pipe or character device, written as the download arrives. It is + /// opened once, for the first response, and kept open across retries so + /// its reader does not see an early end. + #[cfg(unix)] + Stream { + fifo: bool, + requested: PathBuf, + roots: Vec, + writer: tokio::sync::Mutex>>, + }, } async fn prepare( @@ -566,7 +664,11 @@ async fn prepare( let local_error = |e| local_error(e, &name); let metadata = std::fs::metadata(&path).map_err(local_error)?; if !metadata.is_file() { - return Err(not_a_regular_file(&metadata, &name)); + return Err(unsupported_file( + &metadata, + &name, + "A Volume PUT reads regular files only", + )); } let mut file = std::fs::File::open(&path).map_err(local_error)?; if metadata.len() > 0 { @@ -588,11 +690,8 @@ async fn prepare( let parent = path .parent() .ok_or_else(|| invalid("Invalid Volume local file"))?; - let (temp, destination) = match std::fs::metadata(&path) { - Ok(metadata) if !metadata.is_file() => { - return Err(not_a_regular_file(&metadata, &name)) - } - Ok(_) => { + let destination = match std::fs::metadata(&path) { + Ok(metadata) if metadata.is_file() => { let file = std::fs::OpenOptions::new() .write(true) .open(&path) @@ -604,7 +703,25 @@ async fn prepare( temp => temp, } .map_err(local_error)?; - (temp, Destination::Existing(file)) + Destination::Existing { file, temp } + } + #[cfg(unix)] + Ok(metadata) if is_stream(&metadata) => Destination::Stream { + fifo: std::os::unix::fs::FileTypeExt::is_fifo(&metadata.file_type()), + requested, + roots, + writer: tokio::sync::Mutex::new(None), + }, + Ok(metadata) => { + return Err(unsupported_file( + &metadata, + &name, + if cfg!(unix) { + "A Volume GET writes regular files, pipes and character devices only" + } else { + "A Volume GET writes regular files only" + }, + )) } Err(error) if error.kind() == std::io::ErrorKind::NotFound => { let mut builder = tempfile::Builder::new(); @@ -615,22 +732,16 @@ async fn prepare( .tempfile_in(parent) .map_err(local_error)? .into_parts(); - ( + Destination::New { temp, - Destination::New { - temp: path, - requested, - roots, - }, - ) + path, + requested, + roots, + } } Err(error) => return Err(local_error(error)), }; - Ok(Local::Download(Download { - temp, - destination, - name, - })) + Ok(Local::Download(Download { destination, name })) } Operation::Remove => Ok(Local::Remove), }) @@ -666,24 +777,20 @@ impl Local { } async fn publish(self) -> Result<()> { - let Local::Download(Download { - mut temp, - destination, - name, - }) = self - else { + let Local::Download(Download { destination, name }) = self else { return Ok(()); }; tokio::task::spawn_blocking(move || { let local_error = |e| local_error(e, &name); match destination { - Destination::Existing(mut file) => { + Destination::Existing { mut file, mut temp } => { temp.rewind().map_err(local_error)?; let length = std::io::copy(&mut temp, &mut file).map_err(local_error)?; file.set_len(length).map_err(local_error) } Destination::New { - temp: path, + temp, + path, requested, roots, } => { @@ -691,6 +798,8 @@ impl Local { path.persist_noclobber(allowed_path(&requested, &roots)?) .map_err(|e| local_error(e.error)) } + #[cfg(unix)] + Destination::Stream { .. } => Ok(()), } }) .await @@ -799,10 +908,10 @@ fn allowed_path(requested: &Path, roots: &[PathBuf]) -> Result { } } -/// Transfers use regular files only: a pipe or device has no length to send -/// and can block the open indefinitely. A directory gets the error the OS +/// A PUT needs the length a regular file has. A GET also writes into a pipe +/// or character device (see `is_stream`). A directory gets the error the OS /// gives for reading or writing one. -fn not_a_regular_file(metadata: &std::fs::Metadata, name: &str) -> Error { +fn unsupported_file(metadata: &std::fs::Metadata, name: &str, allowed: &str) -> Error { let error = if metadata.is_dir() { #[cfg(unix)] let error = std::io::Error::from_raw_os_error(libc::EISDIR); @@ -810,14 +919,20 @@ fn not_a_regular_file(metadata: &std::fs::Metadata, name: &str) -> Error { let error = std::io::Error::from(std::io::ErrorKind::IsADirectory); error } else { - std::io::Error::new( - std::io::ErrorKind::InvalidInput, - "Volume transfers use regular files only", - ) + std::io::Error::new(std::io::ErrorKind::InvalidInput, allowed) }; local_error(error, name) } +/// A pipe or character device, which a GET writes as the download arrives. +/// Block devices and sockets are refused. +#[cfg(unix)] +fn is_stream(metadata: &std::fs::Metadata) -> bool { + use std::os::unix::fs::FileTypeExt; + let file_type = metadata.file_type(); + file_type.is_fifo() || file_type.is_char_device() +} + /// `path` made absolute with symlinks resolved. Trailing components that do /// not exist yet are kept as written; a dangling symlink is an error. fn resolve(path: &Path) -> std::io::Result { @@ -1404,33 +1519,133 @@ mod tests { } } - #[tokio::test] #[cfg(unix)] - async fn pipes_are_refused_without_waiting_for_the_other_end() { - let server = MockServer::start().await; - let dir = tempfile::tempdir().unwrap(); - let fifo = dir.path().join("fifo"); + fn mkfifo(path: &Path) { assert!(std::process::Command::new("mkfifo") - .arg(&fifo) + .arg(path) .status() .unwrap() .success()); - for operation in ["PUT", "GET"] { - let transfer = instruction(operation, &server.uri(), &fifo); - let error = tokio::time::timeout( - Duration::from_secs(10), - run(&state(0, None), transfer, dir.path(), None), - ) + } + + #[tokio::test] + #[cfg(unix)] + async fn a_get_writes_into_pipes_and_devices_but_a_put_reads_only_files() { + let payload = b"\0\xffvolume bytes".to_vec(); + let server = MockServer::start().await; + Mock::given(path("/large")) + .respond_with(ResponseTemplate::new(200).set_body_bytes(vec![b'x'; 1 << 20])) + .mount(&server) + .await; + Mock::given(method("GET")) + .respond_with(ResponseTemplate::new(200).set_body_bytes(payload.clone())) + .mount(&server) + .await; + let dir = tempfile::tempdir().unwrap(); + let fifo = dir.path().join("fifo"); + mkfifo(&fifo); + + // A PUT needs the source's length, so it refuses a pipe without opening it. + let put = instruction("PUT", &server.uri(), &fifo); + let error = run(&state(0, None), put, dir.path(), None) .await - .expect("a pipe must not block the open") .unwrap_err(); - assert_eq!( - error.error_code.as_deref(), - Some("VOLUME_LOCAL_FILE_ERROR"), - "{operation}" - ); - } + assert_eq!(error.error_code.as_deref(), Some("VOLUME_LOCAL_FILE_ERROR")); assert!(server.received_requests().await.unwrap().is_empty()); + + // A GET waits for a reader that arrives after the download starts. + let reader = { + let fifo = fifo.clone(); + std::thread::spawn(move || { + std::thread::sleep(Duration::from_millis(300)); + std::fs::read(fifo).unwrap() + }) + }; + let get = instruction("GET", &server.uri(), &fifo); + run(&state(0, None), get, dir.path(), None).await.unwrap(); + assert_eq!(reader.join().unwrap(), payload); + + // With no reader, it stops waiting at the idle limit. + let get = instruction("GET", &server.uri(), &fifo); + let error = run( + &state(0, Some(Duration::from_millis(300))), + get, + dir.path(), + None, + ) + .await + .unwrap_err(); + assert_eq!(error.local_error.unwrap().raw_os_error, Some(libc::ENXIO)); + + // A reader that stops reading also stops the transfer at the idle limit. + let stalled = { + let fifo = fifo.clone(); + std::thread::spawn(move || { + let _held = std::fs::File::open(fifo).unwrap(); + std::thread::sleep(Duration::from_secs(2)); + }) + }; + let get = instruction("GET", &format!("{}/large", server.uri()), &fifo); + let error = run( + &state(0, Some(Duration::from_millis(300))), + get, + dir.path(), + None, + ) + .await + .unwrap_err(); + assert!( + error.message.contains("made no progress"), + "{}", + error.message + ); + stalled.join().unwrap(); + + let get = instruction("GET", &server.uri(), Path::new("/dev/null")); + run(&state(0, None), get, Path::new("/dev"), None) + .await + .unwrap(); + } + + #[tokio::test] + #[cfg(unix)] + async fn a_download_cut_off_after_bytes_reach_a_pipe_is_not_retried() { + let dir = tempfile::tempdir().unwrap(); + let fifo = dir.path().join("fifo"); + mkfifo(&fifo); + // (destination, requests with two retries allowed) + for (destination, requests) in [(dir.path().join("file"), 3), (fifo.clone(), 1)] { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}", listener.local_addr().unwrap()); + let accepted = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let peer = tokio::spawn({ + let accepted = Arc::clone(&accepted); + async move { + loop { + let (mut socket, _) = listener.accept().await.unwrap(); + accepted.fetch_add(1, Ordering::SeqCst); + assert!(socket.read(&mut [0; 4096]).await.unwrap() > 0); + socket + .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\nabc") + .await + .unwrap(); + } + } + }); + let reader = (destination == fifo).then(|| { + let fifo = fifo.clone(); + std::thread::spawn(move || std::fs::read(fifo).unwrap()) + }); + let get = instruction("GET", &url, &destination); + run(&state(2, None), get, dir.path(), None) + .await + .unwrap_err(); + peer.abort(); + assert_eq!(accepted.load(Ordering::SeqCst), requests, "{destination:?}"); + if let Some(reader) = reader { + assert_eq!(reader.join().unwrap(), b"abc"); + } + } } #[tokio::test] From 76555ee3ff3b03d5c43a3b3c253e842a3b102d34 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Wed, 2 Dec 2026 00:16:06 +0000 Subject: [PATCH 15/43] fix(volume): never retry a partial write into a pipe and settle temp writes - A GET into a pipe or device counts as written once a write starts, so a write the idle limit cuts short, after some bytes reached the reader, is not retried into the same pipe. - When an attempt into the temporary file fails, a write still in flight finishes before the retry truncates and rewinds the file. Co-authored-by: Isaac Signed-off-by: Aakash Saravanan --- src/volume.rs | 51 ++++++++++++++++++++++++++++++++++++++------------- 1 file changed, 38 insertions(+), 13 deletions(-) diff --git a/src/volume.rs b/src/volume.rs index e6c3e436..318a55c9 100644 --- a/src/volume.rs +++ b/src/volume.rs @@ -357,7 +357,7 @@ impl VolumeState { } }; let (_, mut no_progress) = watch::channel(()); - let mut written = false; + let mut writing = false; let result = async { while let Some(chunk) = self .idle_bounded(&mut no_progress, async { @@ -368,17 +368,26 @@ impl VolumeState { }) .await? { + // A write cut short may already have reached the pipe or device. + writing = true; self.idle_bounded(&mut no_progress, async { sink.write_all(&chunk).await.map_err(local_error) }) .await?; - written = true; } sink.flush().await.map_err(local_error) } .await; + if result.is_err() && rewindable { + // A write still in flight must land before a retry rewinds the file. + let _ = self + .idle_bounded(&mut no_progress, async { + sink.flush().await.map_err(local_error) + }) + .await; + } result.map_err(|error| { - if written && !rewindable { + if writing && !rewindable { error.with_retryable(false) } else { error @@ -1531,6 +1540,7 @@ mod tests { #[tokio::test] #[cfg(unix)] async fn a_get_writes_into_pipes_and_devices_but_a_put_reads_only_files() { + use std::os::unix::fs::OpenOptionsExt; let payload = b"\0\xffvolume bytes".to_vec(); let server = MockServer::start().await; Mock::given(path("/large")) @@ -1577,17 +1587,27 @@ mod tests { .unwrap_err(); assert_eq!(error.local_error.unwrap().raw_os_error, Some(libc::ENXIO)); - // A reader that stops reading also stops the transfer at the idle limit. - let stalled = { - let fifo = fifo.clone(); - std::thread::spawn(move || { - let _held = std::fs::File::open(fifo).unwrap(); - std::thread::sleep(Duration::from_secs(2)); - }) - }; + // A reader that stops reading stops the transfer at the idle limit, and + // a write that only partly reached the pipe is not retried. + let stalled = std::fs::OpenOptions::new() + .read(true) + .custom_flags(libc::O_NONBLOCK) + .open(&fifo) + .unwrap(); + // A small pipe buffer makes the first write stall partway. + #[cfg(target_os = "linux")] + assert!( + unsafe { + libc::fcntl( + std::os::fd::AsRawFd::as_raw_fd(&stalled), + libc::F_SETPIPE_SZ, + 4096, + ) + } >= 0 + ); let get = instruction("GET", &format!("{}/large", server.uri()), &fifo); let error = run( - &state(0, Some(Duration::from_millis(300))), + &state(2, Some(Duration::from_millis(300))), get, dir.path(), None, @@ -1599,7 +1619,12 @@ mod tests { "{}", error.message ); - stalled.join().unwrap(); + let requests = server.received_requests().await.unwrap(); + assert_eq!( + requests.iter().filter(|r| r.url.path() == "/large").count(), + 1 + ); + drop(stalled); let get = instruction("GET", &server.uri(), Path::new("/dev/null")); run(&state(0, None), get, Path::new("/dev"), None) From 2e2c34d55166a80d4d7625471e1b00ad514b36b7 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Wed, 2 Dec 2026 00:49:57 +0000 Subject: [PATCH 16/43] fix(volume): allow the unused mut on Windows for the download builder Only Unix sets a file mode on the temporary-file builder, so Windows builds it with an unused `mut`, which `-D warnings` rejects. Co-authored-by: Isaac 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 318a55c9..a57384e4 100644 --- a/src/volume.rs +++ b/src/volume.rs @@ -733,6 +733,7 @@ async fn prepare( )) } Err(error) if error.kind() == std::io::ErrorKind::NotFound => { + #[cfg_attr(not(unix), allow(unused_mut))] let mut builder = tempfile::Builder::new(); // The mode a newly created file gets, rather than owner-only. #[cfg(unix)] From 5a99db667de67892526e1932cc0d056ebdb961af Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Wed, 2 Dec 2026 01:00:43 +0000 Subject: [PATCH 17/43] fix(volume): bound a download's final flush by the idle limit A file or device write is handed to a background thread, so a stalled device holds up the final flush. That flush now fails at the idle limit like the writes before it. Co-authored-by: Isaac Signed-off-by: Aakash Saravanan --- src/volume.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/volume.rs b/src/volume.rs index a57384e4..84348adb 100644 --- a/src/volume.rs +++ b/src/volume.rs @@ -375,7 +375,10 @@ impl VolumeState { }) .await?; } - sink.flush().await.map_err(local_error) + self.idle_bounded(&mut no_progress, async { + sink.flush().await.map_err(local_error) + }) + .await } .await; if result.is_err() && rewindable { From 2832721993c90be6b537949d7df6b103efc99705 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Wed, 2 Dec 2026 01:15:41 +0000 Subject: [PATCH 18/43] fix(volume): keep only the transfer's outcome for an execution Reading and decoding the instruction now happens before the run-once transfer, so a failed read is not kept for the execution and another result stream can still transfer. A PUT waiting for its bytes is no longer a special case of the cached outcome. Co-authored-by: Isaac Signed-off-by: Aakash Saravanan --- src/telemetry/statement.rs | 37 +++++++++++------------ src/volume.rs | 61 +++++++++++++++++--------------------- 2 files changed, 45 insertions(+), 53 deletions(-) diff --git a/src/telemetry/statement.rs b/src/telemetry/statement.rs index fd7c6e54..a7dc0f78 100644 --- a/src/telemetry/statement.rs +++ b/src/telemetry/statement.rs @@ -376,11 +376,19 @@ mod tests { #[tokio::test] async fn failed_volume_completion_finalizes_statement_with_error() { let connection = Arc::new(CapturingConnectionTelemetry::default()); + let telemetry = StatementTelemetry::new( + connection.clone(), + StatementType::Sql, + OperationType::ExecuteStatement, + ); let batch = RecordBatch::try_from_iter([( "n", Arc::new(arrow_array::Int64Array::from(vec![1])) as arrow_array::ArrayRef, )]) .unwrap(); + let reader = crate::reader::test_utils::MockReader::new(vec![batch]); + let mut stream = ResultStream::from_reader(Box::new(reader)).await.unwrap(); + stream.attach_telemetry(telemetry); let manifest: crate::types::sea::ResultManifest = serde_json::from_value(serde_json::json!({ "is_volume_operation": true, @@ -394,28 +402,17 @@ mod tests { Default::default(), None, )); - let state = storage.transfer_state(); - // The second stream of the execution gets the first one's cached failure. - let mut codes = Vec::new(); - for _ in 0..2 { - let reader = crate::reader::test_utils::MockReader::new(vec![batch.clone()]); - let mut stream = ResultStream::from_reader(Box::new(reader)).await.unwrap(); - stream.attach_telemetry(StatementTelemetry::new( - connection.clone(), - StatementType::Sql, - OperationType::ExecuteStatement, - )); - stream.attach_volume(Some(&manifest), &state); - let error = stream - .complete_volume_operation(&Default::default(), None) - .await - .unwrap_err(); - codes.push(Some(error.code)); - } + stream.attach_volume(Some(&manifest), &storage.transfer_state()); + let error = stream + .complete_volume_operation(&Default::default(), None) + .await + .unwrap_err(); + + drop(stream); let events = connection.statement_events.lock().expect("events mutex"); - let reported: Vec<_> = events.iter().map(|event| event.error_code).collect(); - assert_eq!(reported, codes); + assert_eq!(events.len(), 1); + assert_eq!(events[0].error_code, Some(error.code)); } #[tokio::test] diff --git a/src/volume.rs b/src/volume.rs index 84348adb..27bec3bc 100644 --- a/src/volume.rs +++ b/src/volume.rs @@ -166,40 +166,32 @@ impl VolumeState { options: &VolumeOptions, input_bytes: Option>, ) -> Result { - let outcome = self - .outcome - .get_or_try_init(|| async { - let transfer = async { - let batch = - instruction?.ok_or_else(|| invalid("Missing Volume instruction row"))?; - let instruction = Instruction::decode(&batch)?; - if matches!(instruction.operation, Operation::Put(None)) - && input_bytes.is_none() - { - return Ok(VolumeCompletion::NeedsInputStream); - } - if self.started.swap(true, Ordering::AcqRel) { - return Err(cancelled()); - } - self.transfer(instruction, options, input_bytes).await?; - Ok(VolumeCompletion::Completed) - }; - let result = tokio::select! { + if let Some(outcome) = self.outcome() { + return outcome; + } + // Nothing before the transfer is cached: another result stream of the + // execution may still read the instruction, and a PUT waiting for its + // bytes is called again with them. + let batch = instruction?.ok_or_else(|| invalid("Missing Volume instruction row"))?; + let instruction = Instruction::decode(&batch)?; + if matches!(instruction.operation, Operation::Put(None)) && input_bytes.is_none() { + return Ok(VolumeCompletion::NeedsInputStream); + } + self.outcome + .get_or_init(|| async { + if self.started.swap(true, Ordering::AcqRel) { + return Err(cancelled()); + } + tokio::select! { biased; _ = self.cancellation.cancelled() => Err(cancelled()), - result = transfer => result, - }; - match result { - // Not cached, so the caller can call again with the bytes. - Ok(VolumeCompletion::NeedsInputStream) => Err(()), - result => Ok(result), + result = self.transfer(instruction, options, input_bytes) => { + result.map(|()| VolumeCompletion::Completed) + } } }) - .await; - match outcome { - Ok(outcome) => outcome.clone(), - Err(()) => Ok(VolumeCompletion::NeedsInputStream), - } + .await + .clone() } async fn transfer( @@ -1166,10 +1158,13 @@ mod tests { let mode = |path: &Path| std::fs::metadata(path).unwrap().permissions().mode(); assert_eq!(mode(&new), mode(&source)); } + // A failed read of the instruction is not kept for the execution. + let remove_state = state(0, None); + let options = VolumeOptions::new(Vec::new(), false); + let read = remove_state.complete(Err(Error::network_error()), &options, None); + assert!(read.await.is_err()); let remove = instruction("REMOVE", &url("remove"), Path::new("")); - run(&state(0, None), remove, dir.path(), None) - .await - .unwrap(); + run(&remove_state, remove, dir.path(), None).await.unwrap(); } #[tokio::test] From fc222423d736918333713f50be78fc6b5710e2e2 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Wed, 2 Dec 2026 04:02:51 +0000 Subject: [PATCH 19/43] fix(volume): take caller-supplied upload bytes as Bytes `complete_volume_operation` takes the upload as `Bytes`, so a binding can hand over a buffer it already holds without copying it. A `Vec` converts with `.into()`. Co-authored-by: Isaac Signed-off-by: Aakash Saravanan --- src/result_stream.rs | 2 +- src/volume.rs | 12 +++++++----- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/src/result_stream.rs b/src/result_stream.rs index fadc6e8d..fc4be886 100644 --- a/src/result_stream.rs +++ b/src/result_stream.rs @@ -690,7 +690,7 @@ impl ResultStream { pub async fn complete_volume_operation( &mut self, options: &crate::volume::VolumeOptions, - input_bytes: Option>, + input_bytes: Option, ) -> Result { let Some(volume) = self.volume.clone() else { return Ok(crate::volume::VolumeCompletion::NotVolume); diff --git a/src/volume.rs b/src/volume.rs index 27bec3bc..51537717 100644 --- a/src/volume.rs +++ b/src/volume.rs @@ -164,7 +164,7 @@ impl VolumeState { &self, instruction: Result>, options: &VolumeOptions, - input_bytes: Option>, + input_bytes: Option, ) -> Result { if let Some(outcome) = self.outcome() { return outcome; @@ -198,7 +198,7 @@ impl VolumeState { &self, instruction: Instruction, options: &VolumeOptions, - input_bytes: Option>, + input_bytes: Option, ) -> Result<()> { let local = prepare( instruction.operation.clone(), @@ -656,11 +656,11 @@ enum Destination { async fn prepare( operation: Operation, roots: Vec, - input_bytes: Option>, + input_bytes: Option, ) -> Result { tokio::task::spawn_blocking(move || match operation { Operation::Put(None) => Ok(Local::Upload(Upload::Bytes( - input_bytes.unwrap_or_default().into(), + input_bytes.unwrap_or_default(), ))), Operation::Put(Some(requested)) => { let path = allowed_path(&requested, &roots)?; @@ -1083,7 +1083,9 @@ mod tests { input_bytes: Option>, ) -> Result { let options = VolumeOptions::new(vec![root.to_owned()], false); - state.complete(Ok(Some(batch)), &options, input_bytes).await + state + .complete(Ok(Some(batch)), &options, input_bytes.map(Bytes::from)) + .await } #[tokio::test] From 4c7d412f6b398d988b57488857c45f3e960689f5 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Wed, 2 Dec 2026 04:17:03 +0000 Subject: [PATCH 20/43] fix(volume): run transfers on runtime threads and copy when rename fails - The transfer runs as a task on the runtime's own threads, which kernel-owned runtimes set to block SIGPIPE, so a GET into a pipe whose reader exits fails with a broken pipe instead of killing a host that drives the call from its own thread. Dropping the call still stops it. - A GET into a new file copies the download into place when the filesystem supports neither a rename that keeps an existing file nor hard links, instead of failing after a complete download. - The temporary download is named after its destination. Co-authored-by: Isaac Signed-off-by: Aakash Saravanan --- src/volume.rs | 54 +++++++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 46 insertions(+), 8 deletions(-) diff --git a/src/volume.rs b/src/volume.rs index 51537717..ab723e07 100644 --- a/src/volume.rs +++ b/src/volume.rs @@ -140,6 +140,15 @@ impl Storage { } } +/// Stops a spawned transfer when the call driving it is dropped. +struct AbortOnDrop(tokio::task::AbortHandle); + +impl Drop for AbortOnDrop { + fn drop(&mut self) { + self.0.abort(); + } +} + /// One execution's transfer. Every result stream of the execution shares it, /// so the transfer runs at most once. pub(crate) struct VolumeState { @@ -161,7 +170,7 @@ impl VolumeState { } pub(crate) async fn complete( - &self, + self: &Arc, instruction: Result>, options: &VolumeOptions, input_bytes: Option, @@ -182,12 +191,21 @@ impl VolumeState { if self.started.swap(true, Ordering::AcqRel) { return Err(cancelled()); } + // On the runtime's own threads, which kernel-owned runtimes set to block + // SIGPIPE, a pipe whose reader exits fails the write instead of killing + // the host. + let (state, options) = (Arc::clone(self), options.clone()); + let task = tokio::spawn(async move { + state.transfer(instruction, &options, input_bytes).await + }); + let _abort = AbortOnDrop(task.abort_handle()); tokio::select! { biased; _ = self.cancellation.cancelled() => Err(cancelled()), - result = self.transfer(instruction, options, input_bytes) => { - result.map(|()| VolumeCompletion::Completed) - } + joined = task => match joined { + Ok(result) => result.map(|()| VolumeCompletion::Completed), + Err(e) => Err(Error::internal().message(format!("Volume transfer failed: {e}"))), + }, } }) .await @@ -728,8 +746,12 @@ async fn prepare( )) } Err(error) if error.kind() == std::io::ErrorKind::NotFound => { - #[cfg_attr(not(unix), allow(unused_mut))] + // Named after the destination, so one left by a killed process is recognisable. + let mut prefix = std::ffi::OsString::from("."); + prefix.push(path.file_name().unwrap_or_default()); + prefix.push("."); let mut builder = tempfile::Builder::new(); + builder.prefix(&prefix); // The mode a newly created file gets, rather than owner-only. #[cfg(unix)] builder.permissions(std::os::unix::fs::PermissionsExt::from_mode(0o666)); @@ -800,8 +822,24 @@ impl Local { roots, } => { drop(temp); - path.persist_noclobber(allowed_path(&requested, &roots)?) - .map_err(|e| local_error(e.error)) + let destination = allowed_path(&requested, &roots)?; + match path.persist_noclobber(&destination) { + // Some filesystems support neither a rename that keeps an existing + // file nor hard links, so the download is copied instead. + Err(error) if error.error.kind() != std::io::ErrorKind::AlreadyExists => { + let mut source = + std::fs::File::open(&error.path).map_err(local_error)?; + let mut file = std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(&destination) + .map_err(local_error)?; + std::io::copy(&mut source, &mut file) + .map(drop) + .map_err(local_error) + } + result => result.map_err(|e| local_error(e.error)), + } } #[cfg(unix)] Destination::Stream { .. } => Ok(()), @@ -1077,7 +1115,7 @@ mod tests { } async fn run( - state: &VolumeState, + state: &Arc, batch: RecordBatch, root: &Path, input_bytes: Option>, From d405efc423c4afcb8b8161df404f81939db8ec08 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Wed, 2 Dec 2026 06:46:57 +0000 Subject: [PATCH 21/43] test(volume): cover completion after the parent statement is dropped The sync completion test drops its `Statement` before completing, and the canceller test also cancels an async transfer through the handle itself after its parent is gone. Co-authored-by: Isaac Signed-off-by: Aakash Saravanan --- tests/v0_volume_wiremock.rs | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/tests/v0_volume_wiremock.rs b/tests/v0_volume_wiremock.rs index 2bffc994..66d0b11b 100644 --- a/tests/v0_volume_wiremock.rs +++ b/tests/v0_volume_wiremock.rs @@ -18,7 +18,8 @@ use arrow_array::{ArrayRef, RecordBatch, StringArray}; use arrow_ipc::writer::StreamWriter; use base64::{engine::general_purpose::STANDARD, Engine}; use databricks_sql_kernel::{ - AuthConfig, ConnectionConfig, ErrorCode, HttpConfig, Session, VolumeCompletion, VolumeOptions, + AuthConfig, ConnectionConfig, ErrorCode, ExecutedStatementHandle, HttpConfig, Session, + VolumeCompletion, VolumeOptions, }; use serde_json::json; use std::path::Path; @@ -160,6 +161,8 @@ async fn sync_volume_result_completes_once_and_keeps_its_row() { let mut statement = session.statement(); statement.spec().sql("GET"); let mut executed = statement.execute().await.unwrap(); + // Completion outlives its parent statement. + drop(statement); let stream = executed.result_stream_mut(); assert!(stream.is_volume_operation()); for _ in 0..2 { @@ -249,7 +252,12 @@ async fn async_result_streams_share_one_transfer() { #[tokio::test] async fn cancellers_and_session_close_stop_a_running_transfer() { - for case in ["statement canceller", "async canceller", "session close"] { + for case in [ + "statement canceller", + "async canceller", + "async handle", + "session close", + ] { let server = MockServer::start().await; let dir = tempfile::tempdir().unwrap(); let destination = dir.path().join("download"); @@ -273,7 +281,7 @@ async fn cancellers_and_session_close_stop_a_running_transfer() { .complete_volume_operation(&options, None); tokio::join!(complete, stop).0 } - "async canceller" => { + "async canceller" | "async handle" => { let executed = statement.submit().await.unwrap(); let canceller = executed.canceller(); let mut stream = executed.await_result().await.unwrap(); @@ -281,7 +289,12 @@ async fn cancellers_and_session_close_stop_a_running_transfer() { drop(statement); let stop = async { object_requested(&server).await; - let error = canceller.cancel().await.unwrap_err(); + let error = if case == "async handle" { + executed.cancel().await + } else { + canceller.cancel().await + } + .unwrap_err(); assert_eq!(error.code, ErrorCode::InvalidStatementHandle); }; tokio::join!(stream.complete_volume_operation(&options, None), stop).0 From b5aa1997daa5dc01989aac36f41e961c55c26146 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Wed, 2 Dec 2026 06:58:25 +0000 Subject: [PATCH 22/43] fix(volume): fail redirect policy errors without retrying - An HTTPS-to-HTTP redirect, an invalid redirect location or too many redirects cannot succeed on retry, so they fail at once instead of repeating after backoff. - When the copy fallback fails partway, it removes the new destination, so a failed GET leaves no file behind. Co-authored-by: Isaac Signed-off-by: Aakash Saravanan --- src/volume.rs | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/src/volume.rs b/src/volume.rs index ab723e07..c00e9b5a 100644 --- a/src/volume.rs +++ b/src/volume.rs @@ -320,7 +320,7 @@ impl VolumeState { return Err(self.http_failure(response, strategy).await); } Err(( - network("Volume storage request was redirected too many times"), + network("Volume storage request was redirected too many times").with_retryable(false), None, )) } @@ -836,7 +836,11 @@ impl Local { .map_err(local_error)?; std::io::copy(&mut source, &mut file) .map(drop) - .map_err(local_error) + .map_err(|e| { + // A failed GET leaves no new file behind. + let _ = std::fs::remove_file(&destination); + local_error(e) + }) } result => result.map_err(|e| local_error(e.error)), } @@ -916,11 +920,13 @@ fn redirect_target( .to_str() .ok() .and_then(|location| url.join(location).ok()) - .ok_or_else(|| network("Volume storage redirect has an invalid location"))?; + .ok_or_else(|| { + network("Volume storage redirect has an invalid location").with_retryable(false) + })?; if url.scheme() == "https" && next.scheme() != "https" { - return Err(network( - "Volume storage redirect cannot downgrade HTTPS to HTTP", - )); + return Err( + network("Volume storage redirect cannot downgrade HTTPS to HTTP").with_retryable(false), + ); } Ok(Some(next)) } @@ -1469,6 +1475,7 @@ mod tests { ) .unwrap_err(); assert!(error.message.contains("downgrade")); + assert!(!error.retryable); } #[test] From 0f32c65a427fbfb32d141b021d70adacb01419d9 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Wed, 2 Dec 2026 07:24:20 +0000 Subject: [PATCH 23/43] fix(volume): let a stream's transfer outlive its async handle and trim tests - Dropping an `ExecutedAsyncStatement` no longer cancels a Volume transfer: a stream returned by `await_result` outlives the handle, as it already does for rows. Cancelling or closing the handle, the canceller, and session close still stop it. The canceller test now drops the handle before its transfer runs. - The rustix lockfile bump is reverted; tempfile works with main's versions. - A single read or write is bounded by a plain timeout instead of a progress channel with no sender. - `AsyncStatementCanceller` stops the transfer inside `cancel()` instead of through a separate public method. - Tests: the size-less PUT test keeps only the procfs case, the root-dependent read-only case is gone, the cut-off test covers the file retry that nothing else does, and one test is renamed for what it checks. Co-authored-by: Isaac Signed-off-by: Aakash Saravanan --- Cargo.lock | 4 +- adbc/Cargo.lock | 4 +- src/result_stream.rs | 6 +- src/session.rs | 2 + src/statement/executed_async.rs | 12 +-- src/volume.rs | 149 +++++++++++++------------------- tests/v0_volume_wiremock.rs | 11 +-- 7 files changed, 76 insertions(+), 112 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 501a95b0..bc909a3e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2394,9 +2394,9 @@ dependencies = [ [[package]] name = "rustix" -version = "1.1.6" +version = "1.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" +checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190" dependencies = [ "bitflags", "errno", diff --git a/adbc/Cargo.lock b/adbc/Cargo.lock index 89294293..cd5e7677 100644 --- a/adbc/Cargo.lock +++ b/adbc/Cargo.lock @@ -2203,9 +2203,9 @@ dependencies = [ [[package]] name = "rustix" -version = "1.1.6" +version = "1.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" +checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d" dependencies = [ "bitflags", "errno", diff --git a/src/result_stream.rs b/src/result_stream.rs index fc4be886..11984643 100644 --- a/src/result_stream.rs +++ b/src/result_stream.rs @@ -680,9 +680,9 @@ impl ResultStream { /// a failure after the first bytes reach it is not retried. /// A call abandoned mid-transfer makes later calls return `Cancelled`. A /// result from [`Session::attach_async_statement`](crate::Session::attach_async_statement) - /// cannot transfer and returns an error. Keep an - /// [`ExecutedAsyncStatement`](crate::ExecutedAsyncStatement) open until its - /// transfer finishes: cancelling, closing or dropping it stops the transfer. + /// cannot transfer and returns an error. Cancelling or closing the + /// [`ExecutedAsyncStatement`](crate::ExecutedAsyncStatement) it came from + /// stops the transfer. /// A PUT reads a regular file. A PUT of caller-supplied bytes, such as a /// pipe's content, returns `NeedsInputStream` until called with /// `input_bytes`. Cancelling stops the transfer but cannot undo a PUT diff --git a/src/session.rs b/src/session.rs index 0ecc9cf6..6f345611 100644 --- a/src/session.rs +++ b/src/session.rs @@ -385,6 +385,8 @@ impl Session { crate::client::http::check_revocation_support(&http_client_config.tls, revocation)?; validate_revocation_endpoint_scheme(&config, revocation)?; let retry_configs = build_retry_configs_for_session(&config); + // Volume transfers retry with the SQL settings; the CloudFetch ones + // disable retries because its chunk loop retries on its own. let storage_retry = retry_configs[&RequestCategory::Sea].clone(); let http_client = Arc::new( DatabricksHttpClient::with_revocation(http_client_config, retry_configs, revocation) diff --git a/src/statement/executed_async.rs b/src/statement/executed_async.rs index b12b6741..9c44480e 100644 --- a/src/statement/executed_async.rs +++ b/src/statement/executed_async.rs @@ -1303,13 +1303,6 @@ pub struct AsyncStatementCanceller { } impl AsyncStatementCanceller { - /// Stops a running Volume transfer without a server request. - pub fn cancel_volume_operation(&self) { - if let Some(volume) = &self.volume { - volume.cancel(); - } - } - /// Server-side cancel via `cancel_statement(statement_id)`. /// /// Short-circuits to `InvalidStatementHandle` (no wire round-trip) @@ -1322,7 +1315,9 @@ impl AsyncStatementCanceller { /// `await_result` on the same statement. A running Volume transfer /// stops too, even after the parent `Statement` is dropped. pub async fn cancel(&self) -> Result<()> { - self.cancel_volume_operation(); + if let Some(volume) = &self.volume { + volume.cancel(); + } async { self.valid.check()?; if !self.owning { @@ -1349,7 +1344,6 @@ impl AsyncStatementCanceller { impl Drop for ExecutedAsyncStatement { fn drop(&mut self) { - self.cancel_volume(); if self.owning { self.owner_released.store(true, Ordering::Release); self.clear_pending_result(); diff --git a/src/volume.rs b/src/volume.rs index c00e9b5a..5b6400cd 100644 --- a/src/volume.rs +++ b/src/volume.rs @@ -366,11 +366,10 @@ impl VolumeState { (stream.as_mut().expect("opened above").as_mut(), false) } }; - let (_, mut no_progress) = watch::channel(()); let mut writing = false; let result = async { while let Some(chunk) = self - .idle_bounded(&mut no_progress, async { + .bounded(async { response .chunk() .await @@ -380,23 +379,17 @@ impl VolumeState { { // A write cut short may already have reached the pipe or device. writing = true; - self.idle_bounded(&mut no_progress, async { - sink.write_all(&chunk).await.map_err(local_error) - }) - .await?; + self.bounded(async { sink.write_all(&chunk).await.map_err(local_error) }) + .await?; } - self.idle_bounded(&mut no_progress, async { - sink.flush().await.map_err(local_error) - }) - .await + self.bounded(async { sink.flush().await.map_err(local_error) }) + .await } .await; if result.is_err() && rewindable { // A write still in flight must land before a retry rewinds the file. let _ = self - .idle_bounded(&mut no_progress, async { - sink.flush().await.map_err(local_error) - }) + .bounded(async { sink.flush().await.map_err(local_error) }) .await; } result.map_err(|error| { @@ -476,11 +469,10 @@ impl VolumeState { error = error.message(format!("{label}: {value}")); } } - let (_, mut no_progress) = watch::channel(()); let mut body = Vec::new(); while body.len() < ERROR_BODY_LIMIT { match self - .idle_bounded(&mut no_progress, async { + .bounded(async { response .chunk() .await @@ -515,16 +507,20 @@ impl VolumeState { tokio::select! { result = &mut work => return result, Ok(()) = progress.changed() => {} - () = tokio::time::sleep(limit) => { - return Err(network(format!( - "Volume storage transfer made no progress for {} seconds", - limit.as_secs_f64() - )) - .with_retryable(true)); - } + () = tokio::time::sleep(limit) => return Err(no_progress(limit)), } } } + + /// Runs one read or write, failing if it takes longer than the idle limit. + async fn bounded(&self, work: impl std::future::Future>) -> Result { + match self.storage.idle_limit { + Some(limit) => tokio::time::timeout(limit, work) + .await + .unwrap_or_else(|_| Err(no_progress(limit))), + None => work.await, + } + } } #[derive(Clone)] @@ -1023,6 +1019,13 @@ fn cancelled() -> Error { Error::cancelled().message("Volume transfer was cancelled") } +fn no_progress(limit: Duration) -> Error { + network(format!( + "Volume storage transfer made no progress for {} seconds", + limit.as_secs_f64() + )) +} + fn network(message: impl AsRef) -> Error { Error::network_error() .with_error_code("VOLUME_STORAGE_NETWORK_ERROR") @@ -1446,7 +1449,7 @@ mod tests { } #[tokio::test] - async fn unreadable_upload_sources_are_local_errors() { + async fn storage_error_reports_a_failed_upload_read_as_local() { let server = MockServer::start().await; let body = reqwest::Body::wrap_stream(futures::stream::once(async { Err::(local_error(std::io::ErrorKind::Other.into(), "source")) @@ -1549,29 +1552,21 @@ mod tests { } #[tokio::test] + #[cfg(target_os = "linux")] async fn put_sources_without_a_usable_size_upload_their_content() { let server = MockServer::start().await; Mock::given(method("PUT")) .respond_with(ResponseTemplate::new(200)) .mount(&server) .await; - let dir = tempfile::tempdir().unwrap(); - let empty = dir.path().join("empty"); - std::fs::write(&empty, b"").unwrap(); - #[cfg_attr(not(target_os = "linux"), allow(unused_mut))] - let mut sources = vec![(empty, dir.path().to_owned(), Vec::::new())]; - #[cfg(target_os = "linux")] - sources.push(( - PathBuf::from("/proc/self/cmdline"), - PathBuf::from("/proc"), - std::fs::read("/proc/self/cmdline").unwrap(), - )); - for (source, root, expected) in sources { - let put = instruction("PUT", &server.uri(), &source); - run(&state(0, None), put, &root, None).await.unwrap(); - let requests = server.received_requests().await.unwrap(); - assert_eq!(requests.last().unwrap().body, expected, "{source:?}"); - } + // procfs files report size 0 but have content. + let source = Path::new("/proc/self/cmdline"); + let put = instruction("PUT", &server.uri(), source); + run(&state(0, None), put, Path::new("/proc"), None) + .await + .unwrap(); + let requests = server.received_requests().await.unwrap(); + assert_eq!(requests[0].body, std::fs::read(source).unwrap()); } #[cfg(unix)] @@ -1679,44 +1674,32 @@ mod tests { } #[tokio::test] - #[cfg(unix)] - async fn a_download_cut_off_after_bytes_reach_a_pipe_is_not_retried() { + async fn a_download_cut_off_mid_body_is_retried_into_a_file() { let dir = tempfile::tempdir().unwrap(); - let fifo = dir.path().join("fifo"); - mkfifo(&fifo); - // (destination, requests with two retries allowed) - for (destination, requests) in [(dir.path().join("file"), 3), (fifo.clone(), 1)] { - let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); - let url = format!("http://{}", listener.local_addr().unwrap()); - let accepted = Arc::new(std::sync::atomic::AtomicUsize::new(0)); - let peer = tokio::spawn({ - let accepted = Arc::clone(&accepted); - async move { - loop { - let (mut socket, _) = listener.accept().await.unwrap(); - accepted.fetch_add(1, Ordering::SeqCst); - assert!(socket.read(&mut [0; 4096]).await.unwrap() > 0); - socket - .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\nabc") - .await - .unwrap(); - } + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}", listener.local_addr().unwrap()); + let accepted = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let peer = tokio::spawn({ + let accepted = Arc::clone(&accepted); + async move { + loop { + let (mut socket, _) = listener.accept().await.unwrap(); + accepted.fetch_add(1, Ordering::SeqCst); + assert!(socket.read(&mut [0; 4096]).await.unwrap() > 0); + socket + .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\nabc") + .await + .unwrap(); } - }); - let reader = (destination == fifo).then(|| { - let fifo = fifo.clone(); - std::thread::spawn(move || std::fs::read(fifo).unwrap()) - }); - let get = instruction("GET", &url, &destination); - run(&state(2, None), get, dir.path(), None) - .await - .unwrap_err(); - peer.abort(); - assert_eq!(accepted.load(Ordering::SeqCst), requests, "{destination:?}"); - if let Some(reader) = reader { - assert_eq!(reader.join().unwrap(), b"abc"); } - } + }); + let get = instruction("GET", &url, &dir.path().join("file")); + run(&state(2, None), get, dir.path(), None) + .await + .unwrap_err(); + peer.abort(); + assert_eq!(accepted.load(Ordering::SeqCst), 3); + assert!(!dir.path().join("file").exists()); } #[tokio::test] @@ -1761,22 +1744,6 @@ mod tests { #[cfg(unix)] assert_eq!(local.raw_os_error, Some(libc::EISDIR), "{operation}"); } - #[cfg(unix)] - { - use std::os::unix::fs::PermissionsExt; - let read_only = dir.path().join("read-only"); - std::fs::create_dir(&read_only).unwrap(); - std::fs::set_permissions(&read_only, std::fs::Permissions::from_mode(0o500)).unwrap(); - // Permissions do not bind a privileged user. - if tempfile::tempfile_in(&read_only).is_err() { - let get = instruction("GET", &url, &read_only.join("file")); - let error = run(&state(0, None), get, dir.path(), None) - .await - .unwrap_err(); - assert_eq!(error.code, ErrorCode::PermissionDenied); - } - std::fs::set_permissions(&read_only, std::fs::Permissions::from_mode(0o700)).unwrap(); - } assert!(server.received_requests().await.unwrap().is_empty()); } diff --git a/tests/v0_volume_wiremock.rs b/tests/v0_volume_wiremock.rs index 66d0b11b..4d71fde7 100644 --- a/tests/v0_volume_wiremock.rs +++ b/tests/v0_volume_wiremock.rs @@ -285,14 +285,15 @@ async fn cancellers_and_session_close_stop_a_running_transfer() { let executed = statement.submit().await.unwrap(); let canceller = executed.canceller(); let mut stream = executed.await_result().await.unwrap(); - // The transfer stops even after the parent statement is gone. + // The transfer outlives its parent statement and, for the + // canceller, the handle too. drop(statement); + let executed = (case == "async handle").then_some(executed); let stop = async { object_requested(&server).await; - let error = if case == "async handle" { - executed.cancel().await - } else { - canceller.cancel().await + let error = match &executed { + Some(executed) => executed.cancel().await, + None => canceller.cancel().await, } .unwrap_err(); assert_eq!(error.code, ErrorCode::InvalidStatementHandle); From 9fb01973a974e5cd8ab075e59c1f4f07952fe19a Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Wed, 2 Dec 2026 17:46:56 +0000 Subject: [PATCH 24/43] fix(volume): keep rustix at 1.1.6 now that tempfile is a direct dependency The kernel's direct tempfile dependency puts rustix in the shipped Linux dependency graph, where before it came in only through native-tls on macOS. The Security Scan reads that graph, so rustix 1.1.4 and 1.1.5 fail it on RUSTSEC-2026-0486. 1.1.6 is the version the napi and pyo3 lockfiles already use. Co-authored-by: Isaac 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 bc909a3e..501a95b0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2394,9 +2394,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 cd5e7677..89294293 100644 --- a/adbc/Cargo.lock +++ b/adbc/Cargo.lock @@ -2203,9 +2203,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 4199670205f07aa22f578ad65984c5a5035ffadd Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Wed, 2 Dec 2026 18:40:27 +0000 Subject: [PATCH 25/43] fix(volume): run transfers on the session runtime The transfer task now spawns through the session's runtime handle, like the kernel's other session work, instead of whichever runtime awaits the completion. Its writes then always run on the session runtime's threads, so a session on a kernel-owned runtime keeps SIGPIPE blocked for a GET into a pipe wherever the caller awaits. Co-authored-by: Isaac Signed-off-by: Aakash Saravanan --- src/session.rs | 1 + src/telemetry/statement.rs | 1 + src/volume.rs | 14 ++++++++++---- 3 files changed, 12 insertions(+), 4 deletions(-) diff --git a/src/session.rs b/src/session.rs index 6f345611..8de946a9 100644 --- a/src/session.rs +++ b/src/session.rs @@ -399,6 +399,7 @@ impl Session { http_client.revocation(), storage_retry, config.http.storage_read_timeout, + runtime_handle.clone(), )); // 2. Auth provider — async because OAuth flows hit the OIDC diff --git a/src/telemetry/statement.rs b/src/telemetry/statement.rs index a7dc0f78..da683017 100644 --- a/src/telemetry/statement.rs +++ b/src/telemetry/statement.rs @@ -401,6 +401,7 @@ mod tests { None, Default::default(), None, + tokio::runtime::Handle::current(), )); stream.attach_volume(Some(&manifest), &storage.transfer_state()); let error = stream diff --git a/src/volume.rs b/src/volume.rs index 5b6400cd..0662260f 100644 --- a/src/volume.rs +++ b/src/volume.rs @@ -88,6 +88,8 @@ pub(crate) struct Storage { retry: RetryConfig, idle_limit: Option, cancellation: CancellationToken, + /// The session's runtime, which runs every transfer. + runtime: tokio::runtime::Handle, } impl Storage { @@ -96,6 +98,7 @@ impl Storage { revocation: Option, retry: RetryConfig, idle_limit: Option, + runtime: tokio::runtime::Handle, ) -> Self { Self { config, @@ -104,6 +107,7 @@ impl Storage { retry, idle_limit: idle_limit.filter(|limit| !limit.is_zero()), cancellation: CancellationToken::new(), + runtime, } } @@ -191,11 +195,11 @@ impl VolumeState { if self.started.swap(true, Ordering::AcqRel) { return Err(cancelled()); } - // On the runtime's own threads, which kernel-owned runtimes set to block - // SIGPIPE, a pipe whose reader exits fails the write instead of killing - // the host. + // On the session runtime's threads, which kernel-owned runtimes set to + // block SIGPIPE, a pipe whose reader exits fails the write instead of + // killing the host. let (state, options) = (Arc::clone(self), options.clone()); - let task = tokio::spawn(async move { + let task = self.storage.runtime.spawn(async move { state.transfer(instruction, &options, input_bytes).await }); let _abort = AbortOnDrop(task.abort_handle()); @@ -1094,6 +1098,7 @@ mod tests { None, retry, idle_limit, + tokio::runtime::Handle::current(), )) .transfer_state() } @@ -1374,6 +1379,7 @@ mod tests { Some(false), RetryConfig::default(), None, + tokio::runtime::Handle::current(), ); let unsupported = crate::client::http::revocation_unsupported_message( cfg!(windows), From 7bf90272628430cabd04425a367914317d78cd32 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Wed, 2 Dec 2026 18:56:39 +0000 Subject: [PATCH 26/43] fix(volume): read a blank headers string as no storage headers An instruction whose headers column is an empty or blank string now sends the storage request without extra headers instead of failing as an invalid instruction. A blank string has no other meaning, and storage still rejects a request that needed a header. Co-authored-by: Isaac Signed-off-by: Aakash Saravanan --- src/volume.rs | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/src/volume.rs b/src/volume.rs index 0662260f..aaac62ee 100644 --- a/src/volume.rs +++ b/src/volume.rs @@ -588,7 +588,7 @@ fn strings(column: &ArrayRef) -> Result>> { .collect()) } -/// Storage headers arrive as a map or as a JSON object. +/// Storage headers arrive as a map or as a JSON object; a blank string means none. fn headers(column: &ArrayRef) -> Result { let pairs: Vec<(String, String)> = if column.is_null(0) { Vec::new() @@ -603,11 +603,13 @@ fn headers(column: &ArrayRef) -> Result { }) .collect::>()? } else { - let text = string_value(column)?.unwrap_or_default(); - serde_json::from_str::>(&text) - .map_err(|_| invalid("Invalid Volume storage headers"))? - .into_iter() - .collect() + match string_value(column)?.unwrap_or_default().trim() { + "" => Vec::new(), + text => serde_json::from_str::>(text) + .map_err(|_| invalid("Invalid Volume storage headers"))? + .into_iter() + .collect(), + } }; let mut headers = HeaderMap::new(); for (name, value) in pairs { @@ -1861,6 +1863,8 @@ mod tests { Arc::new(StringArray::from(vec![value])); RecordBatch::try_new(valid.schema(), columns).unwrap() }; + let blank = Instruction::decode(&replace("headers", " ")).unwrap(); + assert!(blank.headers.is_empty()); let invalid = [ arrow_select::concat::concat_batches(&valid.schema(), [&valid, &valid]).unwrap(), valid.project(&[0, 1, 2]).unwrap(), From e18d76e63369d41399e9f132ed15ead9bdfcb775 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Wed, 2 Dec 2026 22:09:07 +0000 Subject: [PATCH 27/43] refactor(volume): run the transfer inside execution and fix two GET errors Volume options now go on `StatementSpec::volume`. Executing a statement the server marks as a Volume operation runs the transfer before the result is returned, on the sync, async and direct paths, and a failed transfer fails the execution. Without options the instruction row is returned and nothing moves. This removes `ResultStream::complete_volume_operation`, `VolumeCompletion` and `StatementCanceller::cancel_volume_operation`; caller bytes for `PUT '__input_stream__'` are `VolumeOptions::input_bytes` and apply to one execution. A cancel that arrives while a GET puts its download in place no longer reports `Cancelled` while the file is still written: that step runs to the end and the result reports it. A GET into a missing folder reports the folder's OS error and the requested path, not the temporary file's name. Tests use instruction rows shaped like the server's (headers as a map, no `localFile` for REMOVE), check gzip decoding, and are split so each covers one behavior. Co-authored-by: Isaac Signed-off-by: Aakash Saravanan --- NEXT_CHANGELOG.md | 8 +- src/lib.rs | 2 +- src/result_stream.rs | 85 ++--- src/session.rs | 11 +- src/statement/executed.rs | 2 - src/statement/executed_async.rs | 10 +- src/statement/mutable.rs | 39 +- src/statement/spec.rs | 15 +- src/telemetry/statement.rs | 4 +- src/volume.rs | 646 +++++++++++++++++--------------- tests/v0_volume_wiremock.rs | 200 +++++----- 11 files changed, 505 insertions(+), 517 deletions(-) diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index f4e749e8..6551a879 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -22,10 +22,10 @@ changes go in their respective binding's NEXT_CHANGELOG. if the host has credentials, a path, query or fragment. - `ProxyConfig.url`, the Rust ADBC driver's `adbc.databricks.proxy.url`, `HTTPS_PROXY` and `ALL_PROXY` accept SOCKS4 and SOCKS5 proxy URLs. -- Volume `PUT`, `GET` and `REMOVE`: `ResultStream::complete_volume_operation` - runs the file transfer for a result the server marks as a Volume operation. - Local paths, with symlinks resolved, must be inside the caller's allowed - directories. `HttpConfig::storage_read_timeout` limits how long a transfer +- Volume `PUT`, `GET` and `REMOVE`: with `StatementSpec::volume` set, executing + a statement the server marks as a Volume operation also runs its file + transfer. Local paths, with symlinks resolved, must be inside the caller's + allowed directories. `HttpConfig::storage_read_timeout` limits how long a transfer may go without progress (15 minutes by default). On Unix a GET can also write into an existing pipe or character device as the download arrives. diff --git a/src/lib.rs b/src/lib.rs index 3de15f70..cb525199 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -162,7 +162,7 @@ pub use telemetry::DriverSystemConfiguration; /// pyo3 crates own. Not a supported API. #[doc(hidden)] pub use util::runtime::block_sigpipe_on_current_thread; -pub use volume::{VolumeCompletion, VolumeOptions}; +pub use volume::VolumeOptions; // === Compile-time guarantees on auto-traits === // diff --git a/src/result_stream.rs b/src/result_stream.rs index 11984643..011b188b 100644 --- a/src/result_stream.rs +++ b/src/result_stream.rs @@ -494,7 +494,7 @@ pub struct ResultStream { telemetry: Option, - volume: Option>, + is_volume_operation: bool, } struct ResultStreamTelemetry { @@ -610,7 +610,7 @@ impl ResultStream { exhausted: false, close_guard: None, telemetry: None, - volume: None, + is_volume_operation: false, }) } @@ -645,77 +645,34 @@ impl ResultStream { self.telemetry = Some(ResultStreamTelemetry::new(telemetry)); } - pub(crate) fn attach_volume( + /// Records whether the server marked this result as a Volume PUT, GET or + /// REMOVE and, if so, runs the transfer `volume` holds before any row is + /// read. `None` transfers nothing. + pub(crate) async fn complete_volume( &mut self, manifest: Option<&crate::types::sea::ResultManifest>, - volume: &Arc, - ) { - if manifest.is_some_and(|manifest| manifest.is_volume_operation) { - self.volume = Some(Arc::clone(volume)); - } - } - - pub(crate) fn cancel_volume(&self) { - if let Some(volume) = &self.volume { - volume.cancel(); - } - } - - /// 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() - } - - /// Runs the file transfer for a Volume PUT, GET or REMOVE result. Later - /// calls, including from other result streams of the same execution, - /// return the first outcome without transferring again. - /// - /// Call before reading rows; the instruction row stays readable. A GET - /// writes the object's content: a gzip `Content-Encoding` is decoded, - /// because it marks the stored bytes as a compressed form of that content. - /// A GET into a file replaces it only after the download succeeds; a - /// failure while copying into an existing file can leave it partly written. - /// On Unix a GET also writes into an existing pipe or character device as - /// the download arrives: a pipe waits for a reader up to the idle limit, and - /// a failure after the first bytes reach it is not retried. - /// A call abandoned mid-transfer makes later calls return `Cancelled`. A - /// result from [`Session::attach_async_statement`](crate::Session::attach_async_statement) - /// cannot transfer and returns an error. Cancelling or closing the - /// [`ExecutedAsyncStatement`](crate::ExecutedAsyncStatement) it came from - /// stops the transfer. - /// A PUT reads a regular file. A PUT of caller-supplied bytes, such as a - /// pipe's content, returns `NeedsInputStream` until called with - /// `input_bytes`. Cancelling stops the transfer but cannot undo a PUT - /// or REMOVE that storage already applied. - pub async fn complete_volume_operation( - &mut self, - options: &crate::volume::VolumeOptions, - input_bytes: Option, - ) -> Result { - let Some(volume) = self.volume.clone() else { - return Ok(crate::volume::VolumeCompletion::NotVolume); - }; - let result = match volume.outcome() { - Some(outcome) => outcome, - None => { - if self.current.is_some() || self.exhausted { - return Err(Error::invalid_state().message( - "complete_volume_operation must be called before reading result rows", - )); - } - let instruction = self - .peek_first_batch() - .await - .map(|batch| batch.map(|ResultBatch::Arrow(batch)| batch.clone())); - volume.complete(instruction, options, input_bytes).await - } + volume: Option<&Arc>, + ) -> Result<()> { + self.is_volume_operation = manifest.is_some_and(|manifest| manifest.is_volume_operation); + let Some(volume) = volume.filter(|_| self.is_volume_operation) else { + return Ok(()); }; + let instruction = self + .peek_first_batch() + .await + .map(|batch| batch.map(|ResultBatch::Arrow(batch)| batch.clone())); + let result = volume.complete(instruction).await; if let Err(error) = &result { self.finalize_telemetry(Some(error)); } result } + /// True when the server marked this result as a Volume PUT, GET or REMOVE. + pub fn is_volume_operation(&self) -> bool { + self.is_volume_operation + } + fn reader_metrics(&self) -> Option { self.reader.as_ref().and_then(|reader| reader.metrics()) } diff --git a/src/session.rs b/src/session.rs index 8de946a9..9af794d1 100644 --- a/src/session.rs +++ b/src/session.rs @@ -166,12 +166,11 @@ impl SessionInner { &self.transport } - pub(crate) fn new_volume_state(&self) -> Arc { - self.storage.transfer_state() - } - - pub(crate) fn refused_volume_state(&self) -> Arc { - self.storage.refused_state() + pub(crate) fn new_volume_state( + &self, + options: Option, + ) -> Arc { + self.storage.transfer_state(options) } /// Crate-internal accessor for the server-issued session ID. diff --git a/src/statement/executed.rs b/src/statement/executed.rs index 296878b1..025db78e 100644 --- a/src/statement/executed.rs +++ b/src/statement/executed.rs @@ -189,7 +189,6 @@ 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. // @@ -349,7 +348,6 @@ 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 diff --git a/src/statement/executed_async.rs b/src/statement/executed_async.rs index 9c44480e..6cfb465d 100644 --- a/src/statement/executed_async.rs +++ b/src/statement/executed_async.rs @@ -386,7 +386,6 @@ impl ExecutedAsyncStatement { statement_id: String, initial_status: crate::types::sea::StatementStatus, ) -> Self { - let volume = session.refused_volume_state(); Self::new_read_only( session, statement_id, @@ -395,7 +394,6 @@ impl ExecutedAsyncStatement { SessionAttribution::Detached, initial_status, ) - .with_volume(Some(volume)) } fn new_read_only( @@ -1023,9 +1021,9 @@ impl ExecutedAsyncStatement { } let mut stream = ResultStream::from_reader(result.reader).await?; stream.attach_telemetry(self.statement_telemetry.clone()); - if let Some(volume) = &self.volume { - stream.attach_volume(result.manifest.as_ref(), volume); - } + stream + .complete_volume(result.manifest.as_ref(), self.volume.as_ref()) + .await?; // SEA carries no row count on the async status either; for a // DML the count rides in the result set. Derive it once // (non-consuming) and record it onto the latest status so @@ -1313,7 +1311,7 @@ impl AsyncStatementCanceller { /// [`ExecutedAsyncStatement::cancel`]; the two share no mutable /// state, so this can run concurrently with an in-flight /// `await_result` on the same statement. A running Volume transfer - /// stops too, even after the parent `Statement` is dropped. + /// stops too. pub async fn cancel(&self) -> Result<()> { if let Some(volume) = &self.volume { volume.cancel(); diff --git a/src/statement/mutable.rs b/src/statement/mutable.rs index 304d22d4..8bfc70b7 100644 --- a/src/statement/mutable.rs +++ b/src/statement/mutable.rs @@ -316,7 +316,7 @@ 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 = Arc::new(Mutex::new(session.new_volume_state())); + let volume = Arc::new(Mutex::new(session.new_volume_state(None))); Self { session, spec: StatementSpec::new(), @@ -480,7 +480,9 @@ impl Statement { let mut result_stream = ResultStream::from_reader(result.reader).await?; result_stream.attach_telemetry(telemetry_for_body.clone()); - result_stream.attach_volume(result.manifest.as_ref(), &self.current_volume()); + result_stream + .complete_volume(result.manifest.as_ref(), Some(&self.current_volume())) + .await?; // 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 // already supply `num_modified_rows`, derive it from that @@ -727,7 +729,9 @@ impl Statement { self.last_closed = Some(Arc::clone(&closed)); let mut result_stream = ResultStream::from_reader(result.reader).await?; result_stream.attach_telemetry(telemetry_for_body.clone()); - result_stream.attach_volume(result.manifest.as_ref(), &self.current_volume()); + result_stream + .complete_volume(result.manifest.as_ref(), Some(&self.current_volume())) + .await?; let mut status = result.status; let parameter_set_count = exec_params.parameter_sets.len(); // Optional count reads must not turn a successful write into an execute error. @@ -889,15 +893,23 @@ impl Statement { /// canceller can still dispatch against the just-closed statement (its /// cloned session `Arc` keeps the client side alive). /// - /// Also installs a fresh Volume transfer state, stopping the previous - /// execution's transfer. - fn reset_inflight_slot(&self) { + /// Also installs a fresh Volume transfer state with the spec's options, + /// stopping the previous execution's transfer. The execution takes the + /// spec's `input_bytes`. + fn reset_inflight_slot(&mut self) { if let Ok(mut slot) = self.inflight_id.lock() { *slot = None; } + let options = self.spec.volume.as_mut().map(|options| { + let input_bytes = options.input_bytes.take(); + crate::volume::VolumeOptions { + input_bytes, + ..options.clone() + } + }); let mut volume = self.volume.lock().unwrap_or_else(|e| e.into_inner()); volume.cancel(); - *volume = self.session.new_volume_state(); + *volume = self.session.new_volume_state(options); } fn current_volume(&self) -> Arc { @@ -1056,14 +1068,6 @@ pub struct StatementCanceller { } impl StatementCanceller { - /// Stops a running Volume transfer without 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)`. /// @@ -1089,7 +1093,10 @@ impl StatementCanceller { /// only the id slot and the Volume state (each behind a `Mutex`), no /// mutable statement state. A running Volume transfer stops too. pub async fn cancel(&self) -> Result { - self.cancel_volume_operation(); + 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 diff --git a/src/statement/spec.rs b/src/statement/spec.rs index 4ff8693a..912cc0d2 100644 --- a/src/statement/spec.rs +++ b/src/statement/spec.rs @@ -26,6 +26,7 @@ //! between executions. use crate::kernel_error::{Error, ErrorCode, Result}; +use crate::volume::VolumeOptions; use std::collections::HashMap; /// A typed value bound as a SQL parameter. @@ -232,6 +233,11 @@ pub struct StatementSpec { /// Result wire format. pub result_format: ResultFormat, + + /// Volume transfer settings. With them, executing a Volume PUT, GET or + /// REMOVE also runs its storage transfer; see [`VolumeOptions`]. Their + /// `input_bytes` apply to the next execution only. + pub volume: Option, } impl StatementSpec { @@ -245,7 +251,7 @@ impl StatementSpec { /// parameter sets, so each `sql()` begins a fresh set of *bound parameters*. /// /// Scope note: this clears bound parameters and native parameter sets. It does - /// **not** reset `statement_conf` (e.g. query tags) or `row_limit`, which + /// **not** reset `statement_conf` (e.g. query tags), `row_limit` or `volume`, which /// survive a `sql()` call and must be re-set explicitly if a reused handle /// should not carry them into the next query. /// @@ -428,6 +434,13 @@ impl StatementSpec { self.result_format = fmt; self } + + /// Set the Volume transfer settings. `None` returns a Volume instruction + /// row without transferring. + pub fn volume(&mut self, options: Option) -> &mut Self { + self.volume = options; + self + } } /// Serialise a tag map to the comma-separated `key:value` wire shape the diff --git a/src/telemetry/statement.rs b/src/telemetry/statement.rs index da683017..80f65acd 100644 --- a/src/telemetry/statement.rs +++ b/src/telemetry/statement.rs @@ -403,9 +403,9 @@ mod tests { None, tokio::runtime::Handle::current(), )); - stream.attach_volume(Some(&manifest), &storage.transfer_state()); + let volume = storage.transfer_state(Some(Default::default())); let error = stream - .complete_volume_operation(&Default::default(), None) + .complete_volume(Some(&manifest), Some(&volume)) .await .unwrap_err(); diff --git a/src/volume.rs b/src/volume.rs index aaac62ee..3f5257b9 100644 --- a/src/volume.rs +++ b/src/volume.rs @@ -46,7 +46,26 @@ const UPLOAD_CHUNK: usize = 256 * 1024; #[cfg(unix)] const PIPE_READER_POLL: Duration = Duration::from_millis(50); -/// Caller settings for a Volume file transfer. +/// Caller settings for Volume file transfers, set on +/// [`StatementSpec::volume`](crate::StatementSpec::volume). +/// +/// With options set, executing a statement the server answers with a Volume +/// PUT, GET or REMOVE instruction also runs that storage transfer, and the +/// execution fails if the transfer does. Without them, the execution returns +/// the instruction row and moves no file. Either way the instruction row stays +/// readable. +/// +/// A PUT reads a regular file, or uploads [`input_bytes`](Self::input_bytes) +/// for `PUT '__input_stream__'`. A GET writes the object's content: a gzip +/// `Content-Encoding` is decoded, because it marks the stored bytes as a +/// compressed form of that content. A GET into a file replaces it only after +/// the download succeeds; a failure while copying into an existing file can +/// leave it partly written. On Unix a GET also writes into an existing pipe or +/// character device as the download arrives: a pipe waits for a reader up to +/// the idle limit, and a failure after the first bytes reach it is not retried. +/// Cancelling the execution stops the transfer but cannot undo a PUT or REMOVE +/// that storage already applied, or stop a GET's file that is already being +/// put in place. #[non_exhaustive] #[derive(Debug, Clone, Default)] pub struct VolumeOptions { @@ -57,6 +76,8 @@ pub struct VolumeOptions { pub allowed_paths: Vec, /// Report success when REMOVE targets an object that does not exist. pub remove_not_found_is_success: bool, + /// The content `PUT '__input_stream__'` uploads. Without it, that PUT fails. + pub input_bytes: Option, } impl VolumeOptions { @@ -64,20 +85,15 @@ impl VolumeOptions { Self { allowed_paths, remove_not_found_is_success, + input_bytes: None, } } -} -/// Outcome of [`ResultStream::complete_volume_operation`](crate::ResultStream::complete_volume_operation). -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -#[repr(C)] -pub enum VolumeCompletion { - /// The result is not a Volume operation; nothing was done. - NotVolume = 0, - /// The PUT uploads caller-supplied bytes; call again with them. - NeedsInputStream = 1, - /// The transfer finished. - Completed = 2, + /// Sets the content `PUT '__input_stream__'` uploads. + pub fn with_input_bytes(mut self, input_bytes: Bytes) -> Self { + self.input_bytes = Some(input_bytes); + self + } } /// Storage access shared by a session's Volume transfers. @@ -111,25 +127,21 @@ impl Storage { } } - /// State for one execution's transfer. - pub(crate) fn transfer_state(self: &Arc) -> Arc { + /// State for one execution's transfer. Without options, the execution + /// transfers nothing. + pub(crate) fn transfer_state( + self: &Arc, + options: Option, + ) -> Arc { Arc::new(VolumeState { storage: Arc::clone(self), + options, cancellation: self.cancellation.child_token(), outcome: OnceCell::new(), started: AtomicBool::new(false), }) } - /// State for a handle that only observes another handle's statement, so a - /// marked result reports the refusal instead of transferring. - pub(crate) fn refused_state(self: &Arc) -> Arc { - let state = self.transfer_state(); - let _ = state.outcome.set(Err(Error::invalid_state() - .message("Volume transfers run only on the statement that submitted them"))); - state - } - /// Stops every transfer of the session. pub(crate) fn cancel_all(&self) { self.cancellation.cancel(); @@ -157,8 +169,9 @@ impl Drop for AbortOnDrop { /// so the transfer runs at most once. pub(crate) struct VolumeState { storage: Arc, + options: Option, cancellation: CancellationToken, - outcome: OnceCell>, + outcome: OnceCell>, /// Set when a transfer starts. A call abandoned mid-transfer caches /// nothing, and the transfer must not run again. started: AtomicBool, @@ -169,26 +182,25 @@ impl VolumeState { self.cancellation.cancel(); } - pub(crate) fn outcome(&self) -> Option> { - self.outcome.get().cloned() - } - + /// Runs the transfer `instruction` describes, once per execution. Without + /// options it does nothing. pub(crate) async fn complete( self: &Arc, instruction: Result>, - options: &VolumeOptions, - input_bytes: Option, - ) -> Result { - if let Some(outcome) = self.outcome() { - return outcome; + ) -> Result<()> { + let Some(options) = &self.options else { + return Ok(()); + }; + if let Some(outcome) = self.outcome.get() { + return outcome.clone(); } // Nothing before the transfer is cached: another result stream of the - // execution may still read the instruction, and a PUT waiting for its - // bytes is called again with them. + // execution may still read the instruction. let batch = instruction?.ok_or_else(|| invalid("Missing Volume instruction row"))?; let instruction = Instruction::decode(&batch)?; - if matches!(instruction.operation, Operation::Put(None)) && input_bytes.is_none() { - return Ok(VolumeCompletion::NeedsInputStream); + if matches!(instruction.operation, Operation::Put(None)) && options.input_bytes.is_none() { + return Err(Error::invalid_argument() + .message("A Volume PUT of __input_stream__ needs input bytes")); } self.outcome .get_or_init(|| async { @@ -199,33 +211,33 @@ impl VolumeState { // block SIGPIPE, a pipe whose reader exits fails the write instead of // killing the host. let (state, options) = (Arc::clone(self), options.clone()); - let task = self.storage.runtime.spawn(async move { - state.transfer(instruction, &options, input_bytes).await - }); + let task = self + .storage + .runtime + .spawn(async move { state.transfer(instruction, &options).await }); let _abort = AbortOnDrop(task.abort_handle()); - tokio::select! { + let local = tokio::select! { biased; - _ = self.cancellation.cancelled() => Err(cancelled()), - joined = task => match joined { - Ok(result) => result.map(|()| VolumeCompletion::Completed), - Err(e) => Err(Error::internal().message(format!("Volume transfer failed: {e}"))), - }, - } + _ = self.cancellation.cancelled() => return Err(cancelled()), + joined = task => joined.map_err(|e| { + Error::internal().message(format!("Volume transfer failed: {e}")) + })??, + }; + // Putting a download in place cannot be stopped midway, so it runs to the + // end and the outcome reports the file it left. + local.publish().await }) .await .clone() } - async fn transfer( - &self, - instruction: Instruction, - options: &VolumeOptions, - input_bytes: Option, - ) -> Result<()> { + /// Prepares the local side and makes the storage request, returning the + /// local side for a GET to put its download in place. + async fn transfer(&self, instruction: Instruction, options: &VolumeOptions) -> Result { let local = prepare( instruction.operation.clone(), options.allowed_paths.clone(), - input_bytes, + options.input_bytes.clone(), ) .await?; let client = self.storage.client().await?; @@ -238,10 +250,12 @@ impl VolumeState { .attempt(client, &instruction, &local, options, &strategy) .await { - Ok(()) => return local.publish().await, + Ok(()) => return Ok(local), Err(failure) => failure, }; let wait = calculate_backoff(retry, attempt, retry_after.as_deref()); + // The retry budget runs from the first failure, so a long transfer that + // is still making progress keeps the whole budget for a late failure. let waited = first_failure.get_or_insert_with(Instant::now).elapsed(); if !error.retryable || attempt >= retry.max_retries @@ -726,7 +740,7 @@ async fn prepare( } temp => temp, } - .map_err(local_error)?; + .map_err(|e| local_error(temp_error(e)))?; Destination::Existing { file, temp } } #[cfg(unix)] @@ -757,9 +771,11 @@ async fn prepare( // The mode a newly created file gets, rather than owner-only. #[cfg(unix)] builder.permissions(std::os::unix::fs::PermissionsExt::from_mode(0o666)); + // A missing or unusable folder reports its own error, with the OS code. + std::fs::metadata(parent).map_err(local_error)?; let (temp, path) = builder .tempfile_in(parent) - .map_err(local_error)? + .map_err(|e| local_error(temp_error(e)))? .into_parts(); Destination::New { temp, @@ -1059,6 +1075,15 @@ fn storage_error(error: reqwest::Error, strategy: &RetryStrategy) -> Error { .with_retryable(retryable) } +/// `tempfile` wraps its errors with the temporary file's name, hiding the OS +/// code; such an error keeps only its kind, so it names the requested file. +fn temp_error(error: std::io::Error) -> std::io::Error { + match error.raw_os_error() { + Some(_) => error, + None => error.kind().into(), + } +} + fn local_error(error: std::io::Error, path: &str) -> Error { match error.kind() { std::io::ErrorKind::NotFound => Error::not_found(), @@ -1088,7 +1113,7 @@ mod tests { use wiremock::matchers::{body_bytes, header, method, path}; use wiremock::{Mock, MockServer, ResponseTemplate}; - fn state(max_retries: u32, idle_limit: Option) -> Arc { + fn storage(max_retries: u32, idle_limit: Option) -> Arc { let retry = RetryConfig { max_retries, min_wait: Duration::ZERO, @@ -1102,44 +1127,64 @@ mod tests { idle_limit, tokio::runtime::Handle::current(), )) - .transfer_state() } + /// One execution's transfer state with `root` allowed. + fn state(storage: &Arc, root: &Path) -> Arc { + storage.transfer_state(Some(VolumeOptions::new(vec![root.to_owned()], false))) + } + + /// Runs one execution's transfer of `batch` with `root` allowed. + async fn run(storage: &Arc, batch: RecordBatch, root: &Path) -> Result<()> { + state(storage, root).complete(Ok(Some(batch))).await + } + + /// An instruction row as the server sends it, with headers as a map. fn instruction(operation: &str, url: &str, local: &Path) -> RecordBatch { - instruction_with_headers(operation, url, local, r#"{"x-test":"yes"}"#) + instruction_with_headers(operation, url, Some(local), &[("x-test", "yes")]) + } + + /// A REMOVE instruction row, which has no `localFile` column. + fn remove(url: &str) -> RecordBatch { + instruction_with_headers("REMOVE", url, None, &[]) } fn instruction_with_headers( operation: &str, url: &str, - local: &Path, - headers: &str, + local: Option<&Path>, + headers: &[(&str, &str)], ) -> RecordBatch { - RecordBatch::try_from_iter([ + let mut map = MapBuilder::new(None, StringBuilder::new(), StringBuilder::new()); + for (name, value) in headers { + map.keys().append_value(name); + map.values().append_value(value); + } + map.append(true).unwrap(); + let mut columns = vec![ ( "operation", Arc::new(StringArray::from(vec![operation])) as ArrayRef, ), ("presignedUrl", Arc::new(StringArray::from(vec![url])) as _), - ("headers", Arc::new(StringArray::from(vec![headers])) as _), - ( + ("headers", Arc::new(map.finish()) as _), + ]; + if let Some(local) = local { + columns.push(( "localFile", Arc::new(StringArray::from(vec![local.to_str().unwrap()])) as _, - ), - ]) - .unwrap() + )); + } + RecordBatch::try_from_iter(columns).unwrap() } - async fn run( - state: &Arc, - batch: RecordBatch, - root: &Path, - input_bytes: Option>, - ) -> Result { - let options = VolumeOptions::new(vec![root.to_owned()], false); - state - .complete(Ok(Some(batch)), &options, input_bytes.map(Bytes::from)) - .await + async fn mount(server: &MockServer, verb: &str, route: &str, response: ResponseTemplate) { + Mock::given(method(verb)) + .and(path(route)) + .respond_with(response) + .expect(1) + .mount(server) + .await; } #[tokio::test] @@ -1149,78 +1194,129 @@ mod tests { Mock::given(method("PUT")) .and(path("/put")) .and(header("x-test", "yes")) - .and(header("content-length", payload.len().to_string().as_str())) .and(body_bytes(payload.clone())) .respond_with(ResponseTemplate::new(200)) - .expect(2) - .mount(&server) - .await; - Mock::given(method("GET")) - .and(path("/get")) - .respond_with(ResponseTemplate::new(200).set_body_bytes(payload.clone())) - .expect(2) - .mount(&server) - .await; - Mock::given(method("DELETE")) - .and(path("/remove")) - .respond_with(ResponseTemplate::new(200)) .expect(1) .mount(&server) .await; + let get = ResponseTemplate::new(200).set_body_bytes(payload.clone()); + mount(&server, "GET", "/get", get).await; + mount(&server, "DELETE", "/remove", ResponseTemplate::new(200)).await; let dir = tempfile::tempdir().unwrap(); let source = dir.path().join("source"); std::fs::write(&source, &payload).unwrap(); + // An existing destination ends with exactly the download, even if it was longer. let destination = dir.path().join("destination"); std::fs::write(&destination, b"an older and longer file").unwrap(); let url = |name: &str| format!("{}/{name}", server.uri()); + let storage = storage(0, None); - // The upload's own length replaces one in the instruction headers. - let put = instruction_with_headers( - "PUT", - &url("put"), - &source, - r#"{"x-test":"yes","Content-Length":"1"}"#, - ); - assert_eq!( - run(&state(0, None), put, dir.path(), None).await.unwrap(), - VolumeCompletion::Completed - ); - let stream_put = state(0, None); - let put = instruction("PUT", &url("put"), Path::new("__input_stream__")); - assert_eq!( - run(&stream_put, put.clone(), dir.path(), None) - .await - .unwrap(), - VolumeCompletion::NeedsInputStream - ); - assert_eq!( - run(&stream_put, put, dir.path(), Some(payload.clone())) - .await - .unwrap(), - VolumeCompletion::Completed - ); + run( + &storage, + instruction("PUT", &url("put"), &source), + dir.path(), + ) + .await + .unwrap(); let get = instruction("GET", &url("get"), &destination); - run(&state(0, None), get, dir.path(), None).await.unwrap(); + run(&storage, get, dir.path()).await.unwrap(); assert_eq!(std::fs::read(&destination).unwrap(), payload); - // A new destination is the download itself, with a new file's mode. + run(&storage, remove(&url("remove")), dir.path()) + .await + .unwrap(); + } + + #[tokio::test] + async fn the_upload_length_replaces_an_instruction_content_length() { + let server = MockServer::start().await; + Mock::given(method("PUT")) + .and(header("content-length", "7")) + .respond_with(ResponseTemplate::new(200)) + .expect(1) + .mount(&server) + .await; + let dir = tempfile::tempdir().unwrap(); + let source = dir.path().join("source"); + std::fs::write(&source, b"payload").unwrap(); + let headers = [("Content-Length", "1")]; + let put = instruction_with_headers("PUT", &server.uri(), Some(&source), &headers); + run(&storage(0, None), put, dir.path()).await.unwrap(); + } + + #[tokio::test] + async fn an_input_stream_put_uploads_the_input_bytes() { + let server = MockServer::start().await; + Mock::given(method("PUT")) + .and(body_bytes(b"caller bytes".to_vec())) + .respond_with(ResponseTemplate::new(200)) + .expect(1) + .mount(&server) + .await; + let put = instruction("PUT", &server.uri(), Path::new("__input_stream__")); + let storage = storage(0, None); + let without = storage.transfer_state(Some(VolumeOptions::default())); + let error = without.complete(Ok(Some(put.clone()))).await.unwrap_err(); + assert_eq!(error.code, ErrorCode::InvalidArgument); + let options = + VolumeOptions::default().with_input_bytes(Bytes::from_static(b"caller bytes")); + let with = storage.transfer_state(Some(options)); + with.complete(Ok(Some(put))).await.unwrap(); + } + + #[tokio::test] + async fn a_get_into_a_new_file_leaves_only_that_file() { + let server = MockServer::start().await; + let get = ResponseTemplate::new(200).set_body_string("content"); + mount(&server, "GET", "/", get).await; + let dir = tempfile::tempdir().unwrap(); + let created = dir.path().join("created"); + std::fs::write(&created, b"").unwrap(); let new = dir.path().join("new"); - let get = instruction("GET", &url("get"), &new); - run(&state(0, None), get, dir.path(), None).await.unwrap(); - assert_eq!(std::fs::read(&new).unwrap(), payload); - assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 3); + let get = instruction("GET", &server.uri(), &new); + run(&storage(0, None), get, dir.path()).await.unwrap(); + assert_eq!(std::fs::read(&new).unwrap(), b"content"); + assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 2); + // It has the mode any newly created file gets, not the temporary file's. #[cfg(unix)] { use std::os::unix::fs::PermissionsExt; let mode = |path: &Path| std::fs::metadata(path).unwrap().permissions().mode(); - assert_eq!(mode(&new), mode(&source)); + assert_eq!(mode(&new), mode(&created)); } - // A failed read of the instruction is not kept for the execution. - let remove_state = state(0, None); - let options = VolumeOptions::new(Vec::new(), false); - let read = remove_state.complete(Err(Error::network_error()), &options, None); - assert!(read.await.is_err()); - let remove = instruction("REMOVE", &url("remove"), Path::new("")); - run(&remove_state, remove, dir.path(), None).await.unwrap(); + } + + #[tokio::test] + async fn a_gzip_encoded_download_is_written_decoded() { + // gzip of "decoded content". + const GZIP: [u8; 35] = [ + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x03, 0x4b, 0x49, 0x4d, 0xce, + 0x4f, 0x49, 0x4d, 0x51, 0x48, 0xce, 0xcf, 0x2b, 0x49, 0xcd, 0x2b, 0x01, 0x00, 0x6d, + 0xf0, 0x83, 0xb2, 0x0f, 0x00, 0x00, 0x00, + ]; + let server = MockServer::start().await; + let get = ResponseTemplate::new(200) + .insert_header("content-encoding", "gzip") + .set_body_bytes(GZIP.to_vec()); + mount(&server, "GET", "/", get).await; + let dir = tempfile::tempdir().unwrap(); + let destination = dir.path().join("destination"); + let get = instruction("GET", &server.uri(), &destination); + run(&storage(0, None), get, dir.path()).await.unwrap(); + assert_eq!(std::fs::read(&destination).unwrap(), b"decoded content"); + } + + #[tokio::test] + async fn a_failed_instruction_read_is_not_kept_for_the_execution() { + let server = MockServer::start().await; + mount(&server, "DELETE", "/", ResponseTemplate::new(200)).await; + let dir = tempfile::tempdir().unwrap(); + let state = state(&storage(0, None), dir.path()); + let read = state.complete(Err(Error::network_error())).await; + assert!(read.is_err()); + state + .complete(Ok(Some(remove(&server.uri())))) + .await + .unwrap(); } #[tokio::test] @@ -1244,11 +1340,10 @@ mod tests { let existing = dir.path().join("existing"); std::fs::write(&existing, b"old").unwrap(); let missing = dir.path().join("missing"); + let storage = storage(0, None); for destination in [&existing, &missing] { let get = instruction("GET", &server.uri(), destination); - let error = run(&state(0, None), get, dir.path(), None) - .await - .unwrap_err(); + let error = run(&storage, get, dir.path()).await.unwrap_err(); assert_eq!( error.error_code.as_deref(), Some("VOLUME_STORAGE_HTTP_ERROR") @@ -1263,18 +1358,18 @@ mod tests { assert_eq!(std::fs::read(&existing).unwrap(), b"old"); assert!(!missing.exists()); - let remove = instruction("REMOVE", &server.uri(), Path::new("")); for remove_not_found_is_success in [true, false] { let options = VolumeOptions::new(Vec::new(), remove_not_found_is_success); - let result = state(0, None) - .complete(Ok(Some(remove.clone())), &options, None) + let result = storage + .transfer_state(Some(options)) + .complete(Ok(Some(remove(&server.uri())))) .await; assert_eq!(result.is_ok(), remove_not_found_is_success); } } #[tokio::test] - async fn transient_storage_failures_are_retried() { + async fn only_transient_storage_failures_are_retried() { let server = MockServer::start().await; Mock::given(path("/flaky")) .respond_with(ResponseTemplate::new(503)) @@ -1285,20 +1380,16 @@ mod tests { .respond_with(ResponseTemplate::new(200).set_body_string("recovered")) .mount(&server) .await; - Mock::given(path("/denied")) - .respond_with(ResponseTemplate::new(403)) - .expect(1) - .mount(&server) - .await; + let denied = ResponseTemplate::new(403); + mount(&server, "GET", "/denied", denied).await; let dir = tempfile::tempdir().unwrap(); let destination = dir.path().join("destination"); + let storage = storage(1, None); let flaky = instruction("GET", &format!("{}/flaky", server.uri()), &destination); - run(&state(1, None), flaky, dir.path(), None).await.unwrap(); + run(&storage, flaky, dir.path()).await.unwrap(); assert_eq!(std::fs::read(&destination).unwrap(), b"recovered"); let denied = instruction("GET", &format!("{}/denied", server.uri()), &destination); - let error = run(&state(1, None), denied, dir.path(), None) - .await - .unwrap_err(); + let error = run(&storage, denied, dir.path()).await.unwrap_err(); assert_eq!(error.code, ErrorCode::PermissionDenied); } @@ -1323,55 +1414,44 @@ mod tests { .respond_with(ResponseTemplate::new(303).insert_header("location", "/object")) .mount(&server) .await; - Mock::given(method("GET")) - .and(path("/object")) - .respond_with(ResponseTemplate::new(200).set_body_string("redirected")) - .expect(1) - .mount(&server) - .await; + let get = ResponseTemplate::new(200).set_body_string("redirected"); + mount(&server, "GET", "/object", get).await; let dir = tempfile::tempdir().unwrap(); let source = dir.path().join("source"); std::fs::write(&source, b"payload").unwrap(); let destination = dir.path().join("destination"); + let storage = storage(0, None); for status in [301, 307] { let put = instruction("PUT", &format!("{}/put-{status}", server.uri()), &source); - run(&state(0, None), put, dir.path(), None).await.unwrap(); + run(&storage, put, dir.path()).await.unwrap(); } let see_other = format!("{}/see-other", server.uri()); let get = instruction("GET", &see_other, &destination); - run(&state(0, None), get, dir.path(), None).await.unwrap(); + run(&storage, get, dir.path()).await.unwrap(); assert_eq!(std::fs::read(&destination).unwrap(), b"redirected"); let put = instruction("PUT", &see_other, &source); - let error = run(&state(0, None), put, dir.path(), None) - .await - .unwrap_err(); + let error = run(&storage, put, dir.path()).await.unwrap_err(); assert_eq!(error.http_status, Some(303)); + } - // A redirect to another origin drops credentials. + #[tokio::test] + async fn a_cross_origin_redirect_drops_credentials() { + let server = MockServer::start().await; let other = MockServer::start().await; Mock::given(wiremock::matchers::header_exists("authorization")) .respond_with(ResponseTemplate::new(403)) .mount(&other) .await; - Mock::given(method("PUT")) - .respond_with(ResponseTemplate::new(200)) - .expect(1) - .mount(&other) - .await; - Mock::given(path("/cross-origin")) - .respond_with( - ResponseTemplate::new(307) - .insert_header("location", format!("{}/object", other.uri())), - ) - .mount(&server) - .await; - let put = instruction_with_headers( - "PUT", - &format!("{}/cross-origin", server.uri()), - &source, - r#"{"Authorization":"secret"}"#, - ); - run(&state(0, None), put, dir.path(), None).await.unwrap(); + mount(&other, "PUT", "/object", ResponseTemplate::new(200)).await; + let moved = + ResponseTemplate::new(307).insert_header("location", format!("{}/object", other.uri())); + mount(&server, "PUT", "/", moved).await; + let dir = tempfile::tempdir().unwrap(); + let source = dir.path().join("source"); + std::fs::write(&source, b"payload").unwrap(); + let headers = [("Authorization", "secret")]; + let put = instruction_with_headers("PUT", &server.uri(), Some(&source), &headers); + run(&storage(0, None), put, dir.path()).await.unwrap(); } #[tokio::test] @@ -1433,13 +1513,8 @@ mod tests { &destination }; let transfer = instruction(operation, &url, local); - let result = run( - &state(0, Some(Duration::from_millis(limit))), - transfer, - dir.path(), - None, - ) - .await; + let storage = storage(0, Some(Duration::from_millis(limit))); + let result = run(&storage, transfer, dir.path()).await; peer.abort(); if finishes { result.unwrap(); @@ -1550,8 +1625,8 @@ mod tests { std::fs::rename(root.join("sub"), dir.path().join("moved")).unwrap(); std::os::unix::fs::symlink(&outside, root.join("sub")).unwrap(); }; - let state = state(0, None); - let (result, ()) = tokio::join!(run(&state, get, &root, None), swap); + let storage = storage(0, None); + let (result, ()) = tokio::join!(run(&storage, get, &root), swap); assert_eq!( result.unwrap_err().error_code.as_deref(), Some("VOLUME_PATH_NOT_ALLOWED") @@ -1570,7 +1645,7 @@ mod tests { // procfs files report size 0 but have content. let source = Path::new("/proc/self/cmdline"); let put = instruction("PUT", &server.uri(), source); - run(&state(0, None), put, Path::new("/proc"), None) + run(&storage(0, None), put, Path::new("/proc")) .await .unwrap(); let requests = server.received_requests().await.unwrap(); @@ -1588,31 +1663,17 @@ mod tests { #[tokio::test] #[cfg(unix)] - async fn a_get_writes_into_pipes_and_devices_but_a_put_reads_only_files() { - use std::os::unix::fs::OpenOptionsExt; - let payload = b"\0\xffvolume bytes".to_vec(); + async fn a_get_writes_into_pipes_and_character_devices() { let server = MockServer::start().await; - Mock::given(path("/large")) - .respond_with(ResponseTemplate::new(200).set_body_bytes(vec![b'x'; 1 << 20])) - .mount(&server) - .await; Mock::given(method("GET")) - .respond_with(ResponseTemplate::new(200).set_body_bytes(payload.clone())) + .respond_with(ResponseTemplate::new(200).set_body_string("content")) .mount(&server) .await; let dir = tempfile::tempdir().unwrap(); let fifo = dir.path().join("fifo"); mkfifo(&fifo); - - // A PUT needs the source's length, so it refuses a pipe without opening it. - let put = instruction("PUT", &server.uri(), &fifo); - let error = run(&state(0, None), put, dir.path(), None) - .await - .unwrap_err(); - assert_eq!(error.error_code.as_deref(), Some("VOLUME_LOCAL_FILE_ERROR")); - assert!(server.received_requests().await.unwrap().is_empty()); - - // A GET waits for a reader that arrives after the download starts. + let storage = storage(0, None); + // A reader that arrives after the download starts gets all of it. let reader = { let fifo = fifo.clone(); std::thread::spawn(move || { @@ -1620,24 +1681,39 @@ mod tests { std::fs::read(fifo).unwrap() }) }; - let get = instruction("GET", &server.uri(), &fifo); - run(&state(0, None), get, dir.path(), None).await.unwrap(); - assert_eq!(reader.join().unwrap(), payload); - - // With no reader, it stops waiting at the idle limit. - let get = instruction("GET", &server.uri(), &fifo); - let error = run( - &state(0, Some(Duration::from_millis(300))), - get, + run( + &storage, + instruction("GET", &server.uri(), &fifo), dir.path(), - None, ) .await - .unwrap_err(); + .unwrap(); + assert_eq!(reader.join().unwrap(), b"content"); + let get = instruction("GET", &server.uri(), Path::new("/dev/null")); + run(&storage, get, Path::new("/dev")).await.unwrap(); + } + + #[tokio::test] + #[cfg(unix)] + async fn a_get_into_a_pipe_stops_at_the_idle_limit_without_retrying() { + use std::os::unix::fs::OpenOptionsExt; + let server = MockServer::start().await; + Mock::given(method("GET")) + .respond_with(ResponseTemplate::new(200).set_body_bytes(vec![b'x'; 1 << 20])) + .mount(&server) + .await; + let dir = tempfile::tempdir().unwrap(); + let fifo = dir.path().join("fifo"); + mkfifo(&fifo); + let get = instruction("GET", &server.uri(), &fifo); + let storage = storage(2, Some(Duration::from_millis(300))); + + // With no reader, it stops waiting for one. + let error = run(&storage, get.clone(), dir.path()).await.unwrap_err(); assert_eq!(error.local_error.unwrap().raw_os_error, Some(libc::ENXIO)); - // A reader that stops reading stops the transfer at the idle limit, and - // a write that only partly reached the pipe is not retried. + // A reader that stops reading stops the transfer, and a write that only + // partly reached the pipe is not retried. let stalled = std::fs::OpenOptions::new() .read(true) .custom_flags(libc::O_NONBLOCK) @@ -1654,31 +1730,15 @@ mod tests { ) } >= 0 ); - let get = instruction("GET", &format!("{}/large", server.uri()), &fifo); - let error = run( - &state(2, Some(Duration::from_millis(300))), - get, - dir.path(), - None, - ) - .await - .unwrap_err(); + let before = server.received_requests().await.unwrap().len(); + let error = run(&storage, get, dir.path()).await.unwrap_err(); assert!( error.message.contains("made no progress"), "{}", error.message ); - let requests = server.received_requests().await.unwrap(); - assert_eq!( - requests.iter().filter(|r| r.url.path() == "/large").count(), - 1 - ); + assert_eq!(server.received_requests().await.unwrap().len(), before + 1); drop(stalled); - - let get = instruction("GET", &server.uri(), Path::new("/dev/null")); - run(&state(0, None), get, Path::new("/dev"), None) - .await - .unwrap(); } #[tokio::test] @@ -1702,9 +1762,7 @@ mod tests { } }); let get = instruction("GET", &url, &dir.path().join("file")); - run(&state(2, None), get, dir.path(), None) - .await - .unwrap_err(); + run(&storage(2, None), get, dir.path()).await.unwrap_err(); peer.abort(); assert_eq!(accepted.load(Ordering::SeqCst), 3); assert!(!dir.path().join("file").exists()); @@ -1715,43 +1773,39 @@ mod tests { let server = MockServer::start().await; let dir = tempfile::tempdir().unwrap(); let url = format!("{}/object?signature=secret", server.uri()); + let storage = storage(0, None); let missing = dir.path().join("missing"); - let error = run( - &state(0, None), - instruction("PUT", &url, &missing), - dir.path(), - None, - ) - .await - .unwrap_err(); - assert_eq!(error.code, ErrorCode::NotFound); - assert_eq!(error.error_code.as_deref(), Some("VOLUME_LOCAL_FILE_ERROR")); - assert_eq!(error.sql_state.as_deref(), Some("HY000")); - let local = error.local_error.unwrap(); - assert_eq!(local.kind, std::io::ErrorKind::NotFound); - assert!(local.raw_os_error.is_some()); - assert_eq!(local.path, missing.to_str().unwrap()); - assert!(!error.message.contains("secret")); - - let no_parent = instruction("GET", &url, &dir.path().join("no-dir/file")); - let error = run(&state(0, None), no_parent, dir.path(), None) - .await - .unwrap_err(); - assert_eq!(error.code, ErrorCode::NotFound); + let no_parent = dir.path().join("no-dir/file"); + for (operation, local) in [("PUT", &missing), ("GET", &no_parent)] { + let transfer = instruction(operation, &url, local); + let error = run(&storage, transfer, dir.path()).await.unwrap_err(); + assert_eq!(error.code, ErrorCode::NotFound, "{operation}"); + assert_eq!(error.error_code.as_deref(), Some("VOLUME_LOCAL_FILE_ERROR")); + assert_eq!(error.sql_state.as_deref(), Some("HY000")); + assert!(!error.message.contains("secret"), "{operation}"); + let details = error.local_error.unwrap(); + assert_eq!(details.kind, std::io::ErrorKind::NotFound, "{operation}"); + #[cfg(unix)] + assert_eq!(details.raw_os_error, Some(libc::ENOENT), "{operation}"); + assert_eq!(details.path, local.to_str().unwrap(), "{operation}"); + } for operation in ["PUT", "GET"] { - let error = run( - &state(0, None), - instruction(operation, &url, dir.path()), - dir.path(), - None, - ) - .await - .unwrap_err(); + let transfer = instruction(operation, &url, dir.path()); + let error = run(&storage, transfer, dir.path()).await.unwrap_err(); let local = error.local_error.unwrap(); assert_eq!(local.kind, std::io::ErrorKind::IsADirectory, "{operation}"); #[cfg(unix)] assert_eq!(local.raw_os_error, Some(libc::EISDIR), "{operation}"); } + // A PUT needs the source's length, so it refuses a pipe without opening it. + #[cfg(unix)] + { + let fifo = dir.path().join("fifo"); + mkfifo(&fifo); + let put = instruction("PUT", &url, &fifo); + let error = run(&storage, put, dir.path()).await.unwrap_err(); + assert_eq!(error.error_code.as_deref(), Some("VOLUME_LOCAL_FILE_ERROR")); + } assert!(server.received_requests().await.unwrap().is_empty()); } @@ -1772,14 +1826,14 @@ mod tests { let destination = dir.path().join("destination"); std::fs::write(&destination, b"old").unwrap(); let get = instruction("GET", &server.uri(), &destination); - let state = state(0, None); + let state = state(&storage(0, None), dir.path()); let requested = async { while server.received_requests().await.unwrap().is_empty() { tokio::task::yield_now().await; } }; tokio::time::timeout(Duration::from_secs(10), async { - let transfer = run(&state, get.clone(), dir.path(), None); + let transfer = state.complete(Ok(Some(get.clone()))); if abandon { tokio::select! { result = transfer => panic!("transfer finished early: {result:?}"), @@ -1795,7 +1849,7 @@ mod tests { }) .await .unwrap(); - let repeated = run(&state, get, dir.path(), None).await.unwrap_err(); + let repeated = state.complete(Ok(Some(get))).await.unwrap_err(); assert_eq!(repeated.code, ErrorCode::Cancelled, "abandon={abandon}"); assert_eq!(std::fs::read(&destination).unwrap(), b"old"); } @@ -1831,38 +1885,30 @@ mod tests { #[test] fn instructions_must_be_one_well_formed_row() { - let mut map = MapBuilder::new(None, StringBuilder::new(), StringBuilder::new()); - map.keys().append_value("x-test"); - map.values().append_value("yes"); - map.append(true).unwrap(); - let mapped = RecordBatch::try_from_iter([ - ( - "operation", - Arc::new(StringArray::from(vec!["REMOVE"])) as ArrayRef, - ), - ( - "presignedUrl", - Arc::new(StringArray::from(vec!["https://storage"])) as _, - ), - ("headers", Arc::new(map.finish()) as _), - ( - "localFile", - Arc::new(StringArray::from(vec![None::<&str>])) as _, - ), - ]) - .unwrap(); + let removed = Instruction::decode(&remove("https://storage")).unwrap(); + assert!(matches!(removed.operation, Operation::Remove)); + let valid = instruction("GET", "https://storage", Path::new("/tmp/file")); assert_eq!( - Instruction::decode(&mapped).unwrap().headers["x-test"], + Instruction::decode(&valid).unwrap().headers["x-test"], "yes" ); - - let valid = instruction("GET", "https://storage", Path::new("/tmp/file")); let replace = |name: &str, value: &str| { - let mut columns = valid.columns().to_vec(); - columns[valid.schema().index_of(name).unwrap()] = - Arc::new(StringArray::from(vec![value])); - RecordBatch::try_new(valid.schema(), columns).unwrap() + let schema = valid.schema(); + RecordBatch::try_from_iter(schema.fields().iter().zip(valid.columns()).map( + |(field, column)| { + let column = if field.name() == name { + Arc::new(StringArray::from(vec![value])) as ArrayRef + } else { + Arc::clone(column) + }; + (field.name().clone(), column) + }, + )) + .unwrap() }; + // Headers may also arrive as a JSON object, and a blank string means none. + let json = Instruction::decode(&replace("headers", r#"{"x-test":"yes"}"#)).unwrap(); + assert_eq!(json.headers["x-test"], "yes"); let blank = Instruction::decode(&replace("headers", " ")).unwrap(); assert!(blank.headers.is_empty()); let invalid = [ diff --git a/tests/v0_volume_wiremock.rs b/tests/v0_volume_wiremock.rs index 4d71fde7..ee796bab 100644 --- a/tests/v0_volume_wiremock.rs +++ b/tests/v0_volume_wiremock.rs @@ -12,20 +12,22 @@ // See the License for the specific language governing permissions and // limitations under the License. -//! Volume completion through sessions and statements, against a mock server. +//! Volume transfers through sessions and statements, against a mock server. +use arrow_array::builder::{MapBuilder, StringBuilder}; use arrow_array::{ArrayRef, RecordBatch, StringArray}; use arrow_ipc::writer::StreamWriter; use base64::{engine::general_purpose::STANDARD, Engine}; use databricks_sql_kernel::{ - AuthConfig, ConnectionConfig, ErrorCode, ExecutedStatementHandle, HttpConfig, Session, - VolumeCompletion, VolumeOptions, + AuthConfig, ConnectionConfig, ErrorCode, ExecutedStatementHandle, HttpConfig, ResultStream, + Session, VolumeOptions, }; use serde_json::json; use std::path::Path; use std::sync::Arc; use std::time::Duration; -use wiremock::matchers::{method, path, path_regex}; +use tokio_util::bytes::Bytes; +use wiremock::matchers::{body_bytes, method, path, path_regex}; use wiremock::{Mock, MockServer, ResponseTemplate}; async fn session(server: &MockServer, http: HttpConfig) -> Session { @@ -60,22 +62,22 @@ async fn session(server: &MockServer, http: HttpConfig) -> Session { .unwrap() } -/// Answers every statement with a GET instruction for `local`. -async fn mount_volume_result(server: &MockServer, local: &Path, marked: bool) { +/// Answers every statement with one `operation` instruction for `local`, the +/// way the server does: headers as a map, and `is_volume_operation` when marked. +async fn mount_volume_result(server: &MockServer, operation: &str, local: &str, marked: bool) { + let mut headers = MapBuilder::new(None, StringBuilder::new(), StringBuilder::new()); + headers.append(true).unwrap(); let batch = RecordBatch::try_from_iter([ ( "operation", - Arc::new(StringArray::from(vec!["GET"])) as ArrayRef, + Arc::new(StringArray::from(vec![operation])) as ArrayRef, ), ( "presignedUrl", Arc::new(StringArray::from(vec![format!("{}/object", server.uri())])) as _, ), - ("headers", Arc::new(StringArray::from(vec!["{}"])) as _), - ( - "localFile", - Arc::new(StringArray::from(vec![local.to_str().unwrap()])) as _, - ), + ("headers", Arc::new(headers.finish()) as _), + ("localFile", Arc::new(StringArray::from(vec![local])) as _), ]) .unwrap(); let mut ipc = Vec::new(); @@ -149,105 +151,95 @@ async fn object_requested(server: &MockServer) { } } +fn options(root: &Path) -> Option { + Some(VolumeOptions::new(vec![root.to_owned()], false)) +} + +async fn instruction_rows(stream: &mut ResultStream) -> usize { + match stream.next_batch().await.unwrap().unwrap() { + databricks_sql_kernel::ResultBatch::Arrow(row) => row.num_rows(), + _ => unreachable!(), + } +} + #[tokio::test] -async fn sync_volume_result_completes_once_and_keeps_its_row() { +async fn execution_with_options_transfers_and_keeps_the_instruction_row() { let server = MockServer::start().await; let dir = tempfile::tempdir().unwrap(); let destination = dir.path().join("download"); mount_object(&server, Duration::ZERO, 1).await; - mount_volume_result(&server, &destination, true).await; + mount_volume_result(&server, "GET", destination.to_str().unwrap(), true).await; let session = session(&server, HttpConfig::default()).await; - let options = VolumeOptions::new(vec![dir.path().to_owned()], false); let mut statement = session.statement(); - statement.spec().sql("GET"); + statement.spec().sql("GET").volume(options(dir.path())); let mut executed = statement.execute().await.unwrap(); - // Completion outlives its parent statement. - drop(statement); + assert_eq!(std::fs::read(&destination).unwrap(), b"data"); let stream = executed.result_stream_mut(); assert!(stream.is_volume_operation()); - for _ in 0..2 { - assert_eq!( - stream - .complete_volume_operation(&options, None) - .await - .unwrap(), - VolumeCompletion::Completed - ); - } - assert_eq!(std::fs::read(&destination).unwrap(), b"data"); - match stream.next_batch().await.unwrap().unwrap() { - databricks_sql_kernel::ResultBatch::Arrow(row) => assert_eq!(row.num_rows(), 1), - _ => unreachable!(), - } + assert_eq!(instruction_rows(stream).await, 1); } #[tokio::test] -async fn only_marked_results_transfer_and_only_before_rows_are_read() { - for marked in [false, true] { +async fn only_a_marked_result_with_options_transfers() { + for (marked, with_options) in [(false, true), (true, false)] { let server = MockServer::start().await; let dir = tempfile::tempdir().unwrap(); + let destination = dir.path().join("download"); mount_object(&server, Duration::ZERO, 0).await; - mount_volume_result(&server, &dir.path().join("download"), marked).await; + mount_volume_result(&server, "GET", destination.to_str().unwrap(), marked).await; let session = session(&server, HttpConfig::default()).await; - let options = VolumeOptions::new(vec![dir.path().to_owned()], false); let mut statement = session.statement(); - statement.spec().sql("GET"); + statement + .spec() + .sql("GET") + .volume(options(dir.path()).filter(|_| with_options)); let mut executed = statement.execute().await.unwrap(); let stream = executed.result_stream_mut(); - if marked { - // First with the instruction row current, then with the stream exhausted. - for _ in 0..2 { - stream.next_batch().await.unwrap(); - let error = stream - .complete_volume_operation(&options, None) - .await - .unwrap_err(); - assert!(error.message.contains("before reading result rows")); - } - } else { - assert_eq!( - stream - .complete_volume_operation(&options, None) - .await - .unwrap(), - VolumeCompletion::NotVolume - ); - } + assert_eq!(stream.is_volume_operation(), marked); + assert_eq!(instruction_rows(stream).await, 1); + assert!(!destination.exists()); } } #[tokio::test] -async fn async_result_streams_share_one_transfer() { +async fn input_bytes_apply_to_one_execution() { + let server = MockServer::start().await; + Mock::given(method("PUT")) + .and(path("/object")) + .and(body_bytes(b"caller bytes".to_vec())) + .respond_with(ResponseTemplate::new(200)) + .expect(1) + .mount(&server) + .await; + mount_volume_result(&server, "PUT", "__input_stream__", true).await; + let session = session(&server, HttpConfig::default()).await; + let mut statement = session.statement(); + let options = VolumeOptions::default().with_input_bytes(Bytes::from_static(b"caller bytes")); + statement.spec().sql("PUT").volume(Some(options)); + statement.execute().await.unwrap(); + let error = statement.execute().await.err().unwrap(); + assert_eq!(error.code, ErrorCode::InvalidArgument); +} + +#[tokio::test] +async fn async_results_share_one_transfer_and_attached_handles_transfer_nothing() { let server = MockServer::start().await; let dir = tempfile::tempdir().unwrap(); + let destination = dir.path().join("download"); mount_object(&server, Duration::ZERO, 1).await; - mount_volume_result(&server, &dir.path().join("download"), true).await; + mount_volume_result(&server, "GET", destination.to_str().unwrap(), true).await; let session = session(&server, HttpConfig::default()).await; - let options = VolumeOptions::new(vec![dir.path().to_owned()], false); let mut statement = session.statement(); - statement.spec().sql("GET"); + statement.spec().sql("GET").volume(options(dir.path())); let executed = statement.submit().await.unwrap(); let reader = executed.reader().unwrap(); - let mut owner = executed.await_result().await.unwrap(); - let mut other = reader.fetch_result().await.unwrap(); - for stream in [&mut owner, &mut other] { - assert_eq!( - stream - .complete_volume_operation(&options, None) - .await - .unwrap(), - VolumeCompletion::Completed - ); - } - // A handle that only observes the statement must not transfer. + executed.await_result().await.unwrap(); + reader.fetch_result().await.unwrap(); + assert_eq!(std::fs::read(&destination).unwrap(), b"data"); let attached = session.attach_async_statement("stmt-volume").await.unwrap(); let mut observed = attached.fetch_result().await.unwrap(); assert!(observed.is_volume_operation()); - let error = observed - .complete_volume_operation(&options, None) - .await - .unwrap_err(); - assert!(error.message.contains("statement that submitted them")); + assert_eq!(instruction_rows(&mut observed).await, 1); } #[tokio::test] @@ -262,58 +254,43 @@ async fn cancellers_and_session_close_stop_a_running_transfer() { let dir = tempfile::tempdir().unwrap(); let destination = dir.path().join("download"); mount_object(&server, Duration::from_secs(30), 1).await; - mount_volume_result(&server, &destination, true).await; + mount_volume_result(&server, "GET", destination.to_str().unwrap(), true).await; let session = session(&server, HttpConfig::default()).await; - let options = VolumeOptions::new(vec![dir.path().to_owned()], false); let mut statement = session.statement(); - statement.spec().sql("GET"); - let completion = async { + statement.spec().sql("GET").volume(options(dir.path())); + let execution = async { match case { "statement canceller" => { let canceller = statement.canceller(); - let mut executed = statement.execute().await.unwrap(); let stop = async { object_requested(&server).await; canceller.cancel().await.unwrap(); }; - let complete = executed - .result_stream_mut() - .complete_volume_operation(&options, None); - tokio::join!(complete, stop).0 + tokio::join!(statement.execute(), stop).0.map(drop) } "async canceller" | "async handle" => { let executed = statement.submit().await.unwrap(); let canceller = executed.canceller(); - let mut stream = executed.await_result().await.unwrap(); - // The transfer outlives its parent statement and, for the - // canceller, the handle too. - drop(statement); - let executed = (case == "async handle").then_some(executed); let stop = async { object_requested(&server).await; - let error = match &executed { - Some(executed) => executed.cancel().await, - None => canceller.cancel().await, + if case == "async handle" { + let _ = executed.cancel().await; + } else { + let _ = canceller.cancel().await; } - .unwrap_err(); - assert_eq!(error.code, ErrorCode::InvalidStatementHandle); }; - tokio::join!(stream.complete_volume_operation(&options, None), stop).0 + tokio::join!(executed.await_result(), stop).0.map(drop) } _ => { - let mut executed = statement.execute().await.unwrap(); let stop = async { object_requested(&server).await; session.close().await.unwrap(); }; - let complete = executed - .result_stream_mut() - .complete_volume_operation(&options, None); - tokio::join!(complete, stop).0 + tokio::join!(statement.execute(), stop).0.map(drop) } } }; - let result = tokio::time::timeout(Duration::from_secs(10), completion) + let result = tokio::time::timeout(Duration::from_secs(10), execution) .await .unwrap(); assert_eq!(result.unwrap_err().code, ErrorCode::Cancelled, "{case}"); @@ -325,21 +302,14 @@ async fn cancellers_and_session_close_stop_a_running_transfer() { async fn storage_transfer_is_not_bound_by_the_sql_request_timeout() { let server = MockServer::start().await; let dir = tempfile::tempdir().unwrap(); + let destination = dir.path().join("download"); mount_object(&server, Duration::from_secs(2), 1).await; - mount_volume_result(&server, &dir.path().join("download"), true).await; + mount_volume_result(&server, "GET", destination.to_str().unwrap(), true).await; let mut http = HttpConfig::default(); http.request_timeout = Duration::from_secs(1); let session = session(&server, http).await; let mut statement = session.statement(); - statement.spec().sql("GET"); - let mut executed = statement.execute().await.unwrap(); - let options = VolumeOptions::new(vec![dir.path().to_owned()], false); - assert_eq!( - executed - .result_stream_mut() - .complete_volume_operation(&options, None) - .await - .unwrap(), - VolumeCompletion::Completed - ); + statement.spec().sql("GET").volume(options(dir.path())); + statement.execute().await.unwrap(); + assert_eq!(std::fs::read(&destination).unwrap(), b"data"); } From 31adbbc7df5d135b0575bf18b1f8e54ef2b922a5 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Wed, 2 Dec 2026 22:47:55 +0000 Subject: [PATCH 28/43] fix(volume): keep OS codes for new GET files and stop transfers on drop A GET into a new file creates its temporary file with its own open, so a folder that refuses the file reports the OS code, and uses a fixed name prefix, so a destination name near the OS limit still fits. A GET into an existing file in a folder on a read-only filesystem stages in the system temp directory, as one in a folder that denies permission already did. Upload bytes are released once their transfer starts. Dropping the owning async statement or the `Statement` stops a running transfer, as closing them does, instead of letting a reader write the file and then report an invalid handle. Tests cover the direct path, a cancel while a download is put in place, the retry budget running from the first failure, the system-temp fallback, a refused new file, and each close and drop path; pipe tests wait for the storage request instead of sleeping, and combined tests are split. Co-authored-by: Isaac Signed-off-by: Aakash Saravanan --- src/session.rs | 1 - src/statement/executed_async.rs | 2 + src/statement/mutable.rs | 32 ++-- src/volume.rs | 312 ++++++++++++++++++++++++-------- tests/v0_volume_wiremock.rs | 106 ++++++++--- 5 files changed, 342 insertions(+), 111 deletions(-) diff --git a/src/session.rs b/src/session.rs index 9af794d1..7fee29a1 100644 --- a/src/session.rs +++ b/src/session.rs @@ -234,7 +234,6 @@ impl SessionInner { /// explicit close genuinely *initiates* the delete rather than /// deferring it to an idle-timeout. pub(crate) fn initiate_delete(&self) { - self.storage.cancel_all(); if self .closed .compare_exchange( diff --git a/src/statement/executed_async.rs b/src/statement/executed_async.rs index 6cfb465d..05172770 100644 --- a/src/statement/executed_async.rs +++ b/src/statement/executed_async.rs @@ -1342,6 +1342,8 @@ impl AsyncStatementCanceller { impl Drop for ExecutedAsyncStatement { fn drop(&mut self) { + // Its readers cannot report a transfer once it is gone, so stop it. + self.cancel_volume(); if self.owning { self.owner_released.store(true, Ordering::Release); self.clear_pending_result(); diff --git a/src/statement/mutable.rs b/src/statement/mutable.rs index 8bfc70b7..117dfe41 100644 --- a/src/statement/mutable.rs +++ b/src/statement/mutable.rs @@ -415,6 +415,7 @@ impl Statement { // canceller retained across a re-execute can't target the prior // query during the handoff (see `reset_inflight_slot`). self.reset_inflight_slot(); + let volume = self.begin_volume(); let telemetry = self.statement_telemetry(OperationType::ExecuteStatement); let telemetry_for_body = telemetry.clone(); let mut result = async { @@ -481,7 +482,7 @@ impl Statement { let mut result_stream = ResultStream::from_reader(result.reader).await?; result_stream.attach_telemetry(telemetry_for_body.clone()); result_stream - .complete_volume(result.manifest.as_ref(), Some(&self.current_volume())) + .complete_volume(result.manifest.as_ref(), Some(&volume)) .await?; // 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 @@ -554,6 +555,7 @@ impl Statement { // Clear the shared in-flight-id slot before the first `.await` // (see `reset_inflight_slot`). self.reset_inflight_slot(); + let volume = self.begin_volume(); let telemetry = self.statement_telemetry(OperationType::ExecuteStatementAsync); let telemetry_for_body = telemetry.clone(); let mut result = async { @@ -631,7 +633,7 @@ impl Statement { timeout, ) .with_parameter_set_count(exec_params.parameter_sets.len()) - .with_volume(Some(self.current_volume()))) + .with_volume(Some(volume))) } .instrument(span) .await; @@ -674,6 +676,7 @@ impl Statement { // Clear the shared in-flight-id slot before the first `.await` // (see `reset_inflight_slot`). self.reset_inflight_slot(); + let volume = self.begin_volume(); let telemetry = self.statement_telemetry(OperationType::ExecuteStatement); let telemetry_for_body = telemetry.clone(); let mut result = async { @@ -730,7 +733,7 @@ impl Statement { let mut result_stream = ResultStream::from_reader(result.reader).await?; result_stream.attach_telemetry(telemetry_for_body.clone()); result_stream - .complete_volume(result.manifest.as_ref(), Some(&self.current_volume())) + .complete_volume(result.manifest.as_ref(), Some(&volume)) .await?; let mut status = result.status; let parameter_set_count = exec_params.parameter_sets.len(); @@ -784,7 +787,7 @@ impl Statement { ExecutionTimeout::Default, ) .with_parameter_set_count(exec_params.parameter_sets.len()) - .with_volume(Some(self.current_volume())), + .with_volume(Some(Arc::clone(&volume))), )) } } @@ -892,14 +895,16 @@ impl Statement { /// by [`Statement::close`], where the slot must survive so a detached /// canceller can still dispatch against the just-closed statement (its /// cloned session `Arc` keeps the client side alive). - /// - /// Also installs a fresh Volume transfer state with the spec's options, - /// stopping the previous execution's transfer. The execution takes the - /// spec's `input_bytes`. - fn reset_inflight_slot(&mut self) { + fn reset_inflight_slot(&self) { if let Ok(mut slot) = self.inflight_id.lock() { *slot = None; } + } + + /// Installs the Volume transfer state of the execution starting now, with + /// the spec's options, and stops the previous execution's transfer. The + /// execution takes the spec's `input_bytes`. + fn begin_volume(&mut self) -> Arc { let options = self.spec.volume.as_mut().map(|options| { let input_bytes = options.input_bytes.take(); crate::volume::VolumeOptions { @@ -907,9 +912,10 @@ impl Statement { ..options.clone() } }); - let mut volume = self.volume.lock().unwrap_or_else(|e| e.into_inner()); - volume.cancel(); - *volume = self.session.new_volume_state(options); + let state = self.session.new_volume_state(options); + let mut slot = self.volume.lock().unwrap_or_else(|e| e.into_inner()); + std::mem::replace(&mut *slot, Arc::clone(&state)).cancel(); + state } fn current_volume(&self) -> Arc { @@ -1138,6 +1144,8 @@ impl Drop for Statement { if let Some(valid) = self.last_valid.take() { valid.invalidate(); } + // An invalidated handle cannot report a transfer, so stop it. + self.current_volume().cancel(); // `last_statement_id` is left as-is. By construction it is // only set immediately before `ExecutedStatement::new` // wraps it; if the caller still holds an `ExecutedStatement`, diff --git a/src/volume.rs b/src/volume.rs index 3f5257b9..e734f5f1 100644 --- a/src/volume.rs +++ b/src/volume.rs @@ -64,8 +64,10 @@ const PIPE_READER_POLL: Duration = Duration::from_millis(50); /// character device as the download arrives: a pipe waits for a reader up to /// the idle limit, and a failure after the first bytes reach it is not retried. /// Cancelling the execution stops the transfer but cannot undo a PUT or REMOVE -/// that storage already applied, or stop a GET's file that is already being -/// put in place. +/// that storage already applied. A GET whose download is already being put in +/// place finishes that step; if the call is dropped meanwhile, the step keeps +/// running after the call returns, and later calls for that execution report +/// `Cancelled`. #[non_exhaustive] #[derive(Debug, Clone, Default)] pub struct VolumeOptions { @@ -77,6 +79,8 @@ pub struct VolumeOptions { /// Report success when REMOVE targets an object that does not exist. pub remove_not_found_is_success: bool, /// The content `PUT '__input_stream__'` uploads. Without it, that PUT fails. + /// On a [`StatementSpec`](crate::StatementSpec), the next execution takes + /// them, even one that fails or is not a Volume PUT. pub input_bytes: Option, } @@ -90,8 +94,8 @@ impl VolumeOptions { } /// Sets the content `PUT '__input_stream__'` uploads. - pub fn with_input_bytes(mut self, input_bytes: Bytes) -> Self { - self.input_bytes = Some(input_bytes); + pub fn with_input_bytes(mut self, input_bytes: impl Into) -> Self { + self.input_bytes = Some(input_bytes.into()); self } } @@ -131,11 +135,15 @@ impl Storage { /// transfers nothing. pub(crate) fn transfer_state( self: &Arc, - options: Option, + mut options: Option, ) -> Arc { + let input_bytes = options + .as_mut() + .and_then(|options| options.input_bytes.take()); Arc::new(VolumeState { storage: Arc::clone(self), options, + input_bytes: std::sync::Mutex::new(input_bytes), cancellation: self.cancellation.child_token(), outcome: OnceCell::new(), started: AtomicBool::new(false), @@ -170,6 +178,8 @@ impl Drop for AbortOnDrop { pub(crate) struct VolumeState { storage: Arc, options: Option, + /// Taken when the transfer starts, so the upload does not outlive it. + input_bytes: std::sync::Mutex>, cancellation: CancellationToken, outcome: OnceCell>, /// Set when a transfer starts. A call abandoned mid-transfer caches @@ -182,6 +192,10 @@ impl VolumeState { self.cancellation.cancel(); } + fn input(&self) -> std::sync::MutexGuard<'_, Option> { + self.input_bytes.lock().unwrap_or_else(|e| e.into_inner()) + } + /// Runs the transfer `instruction` describes, once per execution. Without /// options it does nothing. pub(crate) async fn complete( @@ -198,7 +212,7 @@ impl VolumeState { // execution may still read the instruction. let batch = instruction?.ok_or_else(|| invalid("Missing Volume instruction row"))?; let instruction = Instruction::decode(&batch)?; - if matches!(instruction.operation, Operation::Put(None)) && options.input_bytes.is_none() { + if matches!(instruction.operation, Operation::Put(None)) && self.input().is_none() { return Err(Error::invalid_argument() .message("A Volume PUT of __input_stream__ needs input bytes")); } @@ -207,6 +221,7 @@ impl VolumeState { if self.started.swap(true, Ordering::AcqRel) { return Err(cancelled()); } + let input_bytes = self.input().take(); // On the session runtime's threads, which kernel-owned runtimes set to // block SIGPIPE, a pipe whose reader exits fails the write instead of // killing the host. @@ -214,7 +229,7 @@ impl VolumeState { let task = self .storage .runtime - .spawn(async move { state.transfer(instruction, &options).await }); + .spawn(async move { state.transfer(instruction, &options, input_bytes).await }); let _abort = AbortOnDrop(task.abort_handle()); let local = tokio::select! { biased; @@ -233,11 +248,16 @@ impl VolumeState { /// Prepares the local side and makes the storage request, returning the /// local side for a GET to put its download in place. - async fn transfer(&self, instruction: Instruction, options: &VolumeOptions) -> Result { + async fn transfer( + &self, + instruction: Instruction, + options: &VolumeOptions, + input_bytes: Option, + ) -> Result { let local = prepare( instruction.operation.clone(), options.allowed_paths.clone(), - options.input_bytes.clone(), + input_bytes, ) .await?; let client = self.storage.client().await?; @@ -735,12 +755,18 @@ async fn prepare( .open(&path) .map_err(local_error)?; let temp = match tempfile::tempfile_in(parent) { - Err(error) if error.kind() == std::io::ErrorKind::PermissionDenied => { + Err(error) + if matches!( + error.kind(), + std::io::ErrorKind::PermissionDenied + | std::io::ErrorKind::ReadOnlyFilesystem + ) => + { tempfile::tempfile() } temp => temp, } - .map_err(|e| local_error(temp_error(e)))?; + .map_err(local_error)?; Destination::Existing { file, temp } } #[cfg(unix)] @@ -762,20 +788,19 @@ async fn prepare( )) } Err(error) if error.kind() == std::io::ErrorKind::NotFound => { - // Named after the destination, so one left by a killed process is recognisable. - let mut prefix = std::ffi::OsString::from("."); - prefix.push(path.file_name().unwrap_or_default()); - prefix.push("."); - let mut builder = tempfile::Builder::new(); - builder.prefix(&prefix); - // The mode a newly created file gets, rather than owner-only. - #[cfg(unix)] - builder.permissions(std::os::unix::fs::PermissionsExt::from_mode(0o666)); - // A missing or unusable folder reports its own error, with the OS code. - std::fs::metadata(parent).map_err(local_error)?; - let (temp, path) = builder - .tempfile_in(parent) - .map_err(|e| local_error(temp_error(e)))? + // Opened here rather than by `tempfile`, which hides the OS code of + // a failure. A fixed prefix keeps the name within the OS limit. + let (temp, path) = tempfile::Builder::new() + .prefix(".volume-get-") + .make_in(parent, |path| { + let mut file = std::fs::OpenOptions::new(); + file.write(true).create_new(true); + // The mode a newly created file gets, rather than owner-only. + #[cfg(unix)] + std::os::unix::fs::OpenOptionsExt::mode(&mut file, 0o666); + file.open(path) + }) + .map_err(local_error)? .into_parts(); Destination::New { temp, @@ -1075,15 +1100,6 @@ fn storage_error(error: reqwest::Error, strategy: &RetryStrategy) -> Error { .with_retryable(retryable) } -/// `tempfile` wraps its errors with the temporary file's name, hiding the OS -/// code; such an error keeps only its kind, so it names the requested file. -fn temp_error(error: std::io::Error) -> std::io::Error { - match error.raw_os_error() { - Some(_) => error, - None => error.kind().into(), - } -} - fn local_error(error: std::io::Error, path: &str) -> Error { match error.kind() { std::io::ErrorKind::NotFound => Error::not_found(), @@ -1187,6 +1203,19 @@ mod tests { .await; } + /// Returns once `server` has received a request. + async fn requested(server: &MockServer) { + while server.received_requests().await.unwrap().is_empty() { + tokio::task::yield_now().await; + } + } + + /// True when the process can write where permissions say it cannot. + #[cfg(unix)] + fn privileged() -> bool { + unsafe { libc::geteuid() == 0 } + } + #[tokio::test] async fn put_get_and_remove_move_exact_bytes() { let payload = b"\0\xffvolume bytes".to_vec(); @@ -1257,10 +1286,12 @@ mod tests { let without = storage.transfer_state(Some(VolumeOptions::default())); let error = without.complete(Ok(Some(put.clone()))).await.unwrap_err(); assert_eq!(error.code, ErrorCode::InvalidArgument); - let options = - VolumeOptions::default().with_input_bytes(Bytes::from_static(b"caller bytes")); + let bytes = Bytes::from(b"caller bytes".to_vec()); + let options = VolumeOptions::default().with_input_bytes(bytes.clone()); let with = storage.transfer_state(Some(options)); with.complete(Ok(Some(put))).await.unwrap(); + // The finished transfer no longer holds the upload. + assert!(bytes.is_unique()); } #[tokio::test] @@ -1271,7 +1302,8 @@ mod tests { let dir = tempfile::tempdir().unwrap(); let created = dir.path().join("created"); std::fs::write(&created, b"").unwrap(); - let new = dir.path().join("new"); + // A name near the OS limit still leaves room for the temporary file's. + let new = dir.path().join("n".repeat(250)); let get = instruction("GET", &server.uri(), &new); run(&storage(0, None), get, dir.path()).await.unwrap(); assert_eq!(std::fs::read(&new).unwrap(), b"content"); @@ -1332,10 +1364,6 @@ mod tests { ) .mount(&server) .await; - Mock::given(method("DELETE")) - .respond_with(ResponseTemplate::new(404)) - .mount(&server) - .await; let dir = tempfile::tempdir().unwrap(); let existing = dir.path().join("existing"); std::fs::write(&existing, b"old").unwrap(); @@ -1357,7 +1385,16 @@ mod tests { } assert_eq!(std::fs::read(&existing).unwrap(), b"old"); assert!(!missing.exists()); + } + #[tokio::test] + async fn a_remove_answered_with_not_found_succeeds_only_when_allowed() { + let server = MockServer::start().await; + Mock::given(method("DELETE")) + .respond_with(ResponseTemplate::new(404)) + .mount(&server) + .await; + let storage = storage(0, None); for remove_not_found_is_success in [true, false] { let options = VolumeOptions::new(Vec::new(), remove_not_found_is_success); let result = storage @@ -1619,9 +1656,7 @@ mod tests { std::fs::create_dir(&outside).unwrap(); let get = instruction("GET", &server.uri(), &root.join("sub/file")); let swap = async { - while server.received_requests().await.unwrap().is_empty() { - tokio::task::yield_now().await; - } + requested(&server).await; std::fs::rename(root.join("sub"), dir.path().join("moved")).unwrap(); std::os::unix::fs::symlink(&outside, root.join("sub")).unwrap(); }; @@ -1663,7 +1698,7 @@ mod tests { #[tokio::test] #[cfg(unix)] - async fn a_get_writes_into_pipes_and_character_devices() { + async fn a_get_writes_into_a_pipe_whose_reader_arrives_later() { let server = MockServer::start().await; Mock::given(method("GET")) .respond_with(ResponseTemplate::new(200).set_body_string("content")) @@ -1672,48 +1707,67 @@ mod tests { let dir = tempfile::tempdir().unwrap(); let fifo = dir.path().join("fifo"); mkfifo(&fifo); - let storage = storage(0, None); - // A reader that arrives after the download starts gets all of it. - let reader = { + // The reader opens the pipe only after the download has started. + let reader = async { + requested(&server).await; let fifo = fifo.clone(); - std::thread::spawn(move || { - std::thread::sleep(Duration::from_millis(300)); - std::fs::read(fifo).unwrap() - }) + tokio::task::spawn_blocking(move || std::fs::read(fifo).unwrap()) + .await + .unwrap() }; - run( - &storage, - instruction("GET", &server.uri(), &fifo), - dir.path(), + let get = instruction("GET", &server.uri(), &fifo); + let storage = storage(0, None); + let (result, content) = tokio::join!(run(&storage, get, dir.path()), reader); + result.unwrap(); + assert_eq!(content, b"content"); + } + + #[tokio::test] + #[cfg(unix)] + async fn a_get_writes_into_a_character_device() { + let server = MockServer::start().await; + mount( + &server, + "GET", + "/", + ResponseTemplate::new(200).set_body_string("content"), ) - .await - .unwrap(); - assert_eq!(reader.join().unwrap(), b"content"); + .await; let get = instruction("GET", &server.uri(), Path::new("/dev/null")); - run(&storage, get, Path::new("/dev")).await.unwrap(); + run(&storage(0, None), get, Path::new("/dev")) + .await + .unwrap(); } #[tokio::test] #[cfg(unix)] - async fn a_get_into_a_pipe_stops_at_the_idle_limit_without_retrying() { - use std::os::unix::fs::OpenOptionsExt; + async fn a_get_into_a_pipe_without_a_reader_stops_at_the_idle_limit() { let server = MockServer::start().await; Mock::given(method("GET")) - .respond_with(ResponseTemplate::new(200).set_body_bytes(vec![b'x'; 1 << 20])) + .respond_with(ResponseTemplate::new(200).set_body_string("content")) .mount(&server) .await; let dir = tempfile::tempdir().unwrap(); let fifo = dir.path().join("fifo"); mkfifo(&fifo); let get = instruction("GET", &server.uri(), &fifo); - let storage = storage(2, Some(Duration::from_millis(300))); - - // With no reader, it stops waiting for one. - let error = run(&storage, get.clone(), dir.path()).await.unwrap_err(); + let storage = storage(0, Some(Duration::from_millis(300))); + let error = run(&storage, get, dir.path()).await.unwrap_err(); assert_eq!(error.local_error.unwrap().raw_os_error, Some(libc::ENXIO)); + } - // A reader that stops reading stops the transfer, and a write that only - // partly reached the pipe is not retried. + #[tokio::test] + #[cfg(unix)] + async fn a_stalled_pipe_reader_stops_the_transfer_without_a_retry() { + use std::os::unix::fs::OpenOptionsExt; + let server = MockServer::start().await; + Mock::given(method("GET")) + .respond_with(ResponseTemplate::new(200).set_body_bytes(vec![b'x'; 1 << 20])) + .mount(&server) + .await; + let dir = tempfile::tempdir().unwrap(); + let fifo = dir.path().join("fifo"); + mkfifo(&fifo); let stalled = std::fs::OpenOptions::new() .read(true) .custom_flags(libc::O_NONBLOCK) @@ -1730,14 +1784,15 @@ mod tests { ) } >= 0 ); - let before = server.received_requests().await.unwrap().len(); + let get = instruction("GET", &server.uri(), &fifo); + let storage = storage(2, Some(Duration::from_millis(300))); let error = run(&storage, get, dir.path()).await.unwrap_err(); assert!( error.message.contains("made no progress"), "{}", error.message ); - assert_eq!(server.received_requests().await.unwrap().len(), before + 1); + assert_eq!(server.received_requests().await.unwrap().len(), 1); drop(stalled); } @@ -1806,9 +1861,118 @@ mod tests { let error = run(&storage, put, dir.path()).await.unwrap_err(); assert_eq!(error.error_code.as_deref(), Some("VOLUME_LOCAL_FILE_ERROR")); } + // A folder that refuses a new file reports the OS code and the requested path. + #[cfg(unix)] + if !privileged() { + use std::os::unix::fs::PermissionsExt; + let locked = dir.path().join("locked"); + std::fs::create_dir(&locked).unwrap(); + std::fs::set_permissions(&locked, PermissionsExt::from_mode(0o555)).unwrap(); + let new = locked.join("new"); + let get = instruction("GET", &url, &new); + let error = run(&storage, get, dir.path()).await.unwrap_err(); + std::fs::set_permissions(&locked, PermissionsExt::from_mode(0o755)).unwrap(); + assert!(!error.message.contains(".volume-get-"), "{}", error.message); + let details = error.local_error.unwrap(); + assert_eq!(details.raw_os_error, Some(libc::EACCES)); + assert_eq!(details.path, new.to_str().unwrap()); + } assert!(server.received_requests().await.unwrap().is_empty()); } + #[tokio::test] + #[cfg(unix)] + async fn an_existing_file_in_a_folder_that_refuses_files_is_still_replaced() { + use std::os::unix::fs::PermissionsExt; + if privileged() { + return; + } + let server = MockServer::start().await; + mount( + &server, + "GET", + "/", + ResponseTemplate::new(200).set_body_string("new"), + ) + .await; + let dir = tempfile::tempdir().unwrap(); + let existing = dir.path().join("existing"); + std::fs::write(&existing, b"old content").unwrap(); + std::fs::set_permissions(dir.path(), PermissionsExt::from_mode(0o555)).unwrap(); + let get = instruction("GET", &server.uri(), &existing); + let result = run(&storage(0, None), get, dir.path()).await; + std::fs::set_permissions(dir.path(), PermissionsExt::from_mode(0o755)).unwrap(); + result.unwrap(); + assert_eq!(std::fs::read(&existing).unwrap(), b"new"); + } + + #[tokio::test] + async fn a_cancel_while_a_download_is_put_in_place_lets_it_finish() { + let body = vec![b'x'; 32 << 20]; + let server = MockServer::start().await; + let get = ResponseTemplate::new(200).set_body_bytes(body.clone()); + mount(&server, "GET", "/", get).await; + let dir = tempfile::tempdir().unwrap(); + // An existing empty file changes length only once the download is put in place. + let destination = dir.path().join("destination"); + std::fs::write(&destination, b"").unwrap(); + let state = state(&storage(0, None), dir.path()); + let watcher = { + let (state, destination) = (Arc::clone(&state), destination.clone()); + std::thread::spawn(move || { + while std::fs::metadata(&destination).map_or(0, |m| m.len()) == 0 {} + state.cancel(); + }) + }; + let get = instruction("GET", &server.uri(), &destination); + state.complete(Ok(Some(get))).await.unwrap(); + watcher.join().unwrap(); + assert_eq!(std::fs::read(&destination).unwrap().len(), body.len()); + } + + #[tokio::test] + async fn the_retry_budget_runs_from_the_first_failure() { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}", listener.local_addr().unwrap()); + let accepted = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let peer = tokio::spawn({ + let accepted = Arc::clone(&accepted); + async move { + loop { + let (mut socket, _) = listener.accept().await.unwrap(); + accepted.fetch_add(1, Ordering::SeqCst); + assert!(socket.read(&mut [0; 4096]).await.unwrap() > 0); + socket + .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\nabc") + .await + .unwrap(); + // Each attempt outlasts the whole budget before it is cut off. + tokio::time::sleep(Duration::from_millis(300)).await; + } + } + }); + let retry = RetryConfig { + max_retries: 2, + min_wait: Duration::ZERO, + max_wait: Duration::ZERO, + overall_timeout: Duration::from_millis(100), + ..Default::default() + }; + let storage = Arc::new(Storage::new( + HttpClientConfig::default(), + None, + retry, + None, + tokio::runtime::Handle::current(), + )); + let dir = tempfile::tempdir().unwrap(); + let get = instruction("GET", &url, &dir.path().join("file")); + run(&storage, get, dir.path()).await.unwrap_err(); + peer.abort(); + // One retry: measured from the start, the budget would allow none. + assert_eq!(accepted.load(Ordering::SeqCst), 2); + } + #[tokio::test] async fn cancelled_or_abandoned_transfers_do_not_run_again() { for abandon in [false, true] { @@ -1827,11 +1991,7 @@ mod tests { std::fs::write(&destination, b"old").unwrap(); let get = instruction("GET", &server.uri(), &destination); let state = state(&storage(0, None), dir.path()); - let requested = async { - while server.received_requests().await.unwrap().is_empty() { - tokio::task::yield_now().await; - } - }; + let requested = requested(&server); tokio::time::timeout(Duration::from_secs(10), async { let transfer = state.complete(Ok(Some(get.clone()))); if abandon { diff --git a/tests/v0_volume_wiremock.rs b/tests/v0_volume_wiremock.rs index ee796bab..fdcec66b 100644 --- a/tests/v0_volume_wiremock.rs +++ b/tests/v0_volume_wiremock.rs @@ -19,8 +19,8 @@ use arrow_array::{ArrayRef, RecordBatch, StringArray}; use arrow_ipc::writer::StreamWriter; use base64::{engine::general_purpose::STANDARD, Engine}; use databricks_sql_kernel::{ - AuthConfig, ConnectionConfig, ErrorCode, ExecutedStatementHandle, HttpConfig, ResultStream, - Session, VolumeOptions, + AuthConfig, ConnectionConfig, DirectStatement, ErrorCode, ExecutedStatementHandle, HttpConfig, + ResultStream, Session, VolumeOptions, }; use serde_json::json; use std::path::Path; @@ -91,7 +91,11 @@ async fn mount_volume_result(server: &MockServer, operation: &str, local: &str, .iter() .enumerate() .map(|(position, field)| { - json!({"name": field.name(), "type_name": "STRING", "type_text": "STRING", "position": position}) + let (type_name, type_text) = match field.name().as_str() { + "headers" => ("MAP", "MAP"), + _ => ("STRING", "STRING"), + }; + json!({"name": field.name(), "type_name": type_name, "type_text": type_text, "position": position}) }) .collect(); let body = json!({ @@ -164,19 +168,32 @@ async fn instruction_rows(stream: &mut ResultStream) -> usize { #[tokio::test] async fn execution_with_options_transfers_and_keeps_the_instruction_row() { - let server = MockServer::start().await; - let dir = tempfile::tempdir().unwrap(); - let destination = dir.path().join("download"); - mount_object(&server, Duration::ZERO, 1).await; - mount_volume_result(&server, "GET", destination.to_str().unwrap(), true).await; - let session = session(&server, HttpConfig::default()).await; - let mut statement = session.statement(); - statement.spec().sql("GET").volume(options(dir.path())); - let mut executed = statement.execute().await.unwrap(); - assert_eq!(std::fs::read(&destination).unwrap(), b"data"); - let stream = executed.result_stream_mut(); - assert!(stream.is_volume_operation()); - assert_eq!(instruction_rows(stream).await, 1); + for direct in [false, true] { + let server = MockServer::start().await; + let dir = tempfile::tempdir().unwrap(); + let destination = dir.path().join("download"); + mount_object(&server, Duration::ZERO, 1).await; + mount_volume_result(&server, "GET", destination.to_str().unwrap(), true).await; + let session = session(&server, HttpConfig::default()).await; + let mut statement = session.statement(); + statement.spec().sql("GET").volume(options(dir.path())); + let mut executed = if direct { + match statement.execute_direct().await.unwrap() { + DirectStatement::Completed(executed) => executed, + DirectStatement::Running(_) => panic!("the mock answers inline"), + } + } else { + statement.execute().await.unwrap() + }; + assert_eq!( + std::fs::read(&destination).unwrap(), + b"data", + "direct={direct}" + ); + let stream = executed.result_stream_mut(); + assert!(stream.is_volume_operation()); + assert_eq!(instruction_rows(stream).await, 1); + } } #[tokio::test] @@ -222,7 +239,7 @@ async fn input_bytes_apply_to_one_execution() { } #[tokio::test] -async fn async_results_share_one_transfer_and_attached_handles_transfer_nothing() { +async fn async_results_of_one_execution_share_one_transfer() { let server = MockServer::start().await; let dir = tempfile::tempdir().unwrap(); let destination = dir.path().join("download"); @@ -236,6 +253,21 @@ async fn async_results_share_one_transfer_and_attached_handles_transfer_nothing( executed.await_result().await.unwrap(); reader.fetch_result().await.unwrap(); assert_eq!(std::fs::read(&destination).unwrap(), b"data"); +} + +#[tokio::test] +async fn an_attached_handle_returns_the_instruction_row_without_transferring() { + let server = MockServer::start().await; + let dir = tempfile::tempdir().unwrap(); + mount_object(&server, Duration::ZERO, 0).await; + mount_volume_result( + &server, + "GET", + dir.path().join("download").to_str().unwrap(), + true, + ) + .await; + let session = session(&server, HttpConfig::default()).await; let attached = session.attach_async_statement("stmt-volume").await.unwrap(); let mut observed = attached.fetch_result().await.unwrap(); assert!(observed.is_volume_operation()); @@ -248,6 +280,11 @@ async fn cancellers_and_session_close_stop_a_running_transfer() { "statement canceller", "async canceller", "async handle", + "async close", + "owner dropped", + "statement close", + "statement dropped", + "re-execute", "session close", ] { let server = MockServer::start().await; @@ -268,15 +305,40 @@ async fn cancellers_and_session_close_stop_a_running_transfer() { }; tokio::join!(statement.execute(), stop).0.map(drop) } - "async canceller" | "async handle" => { + "async canceller" | "async handle" | "async close" => { let executed = statement.submit().await.unwrap(); let canceller = executed.canceller(); let stop = async { object_requested(&server).await; - if case == "async handle" { - let _ = executed.cancel().await; - } else { - let _ = canceller.cancel().await; + let _ = match case { + "async handle" => executed.cancel().await, + "async close" => ExecutedStatementHandle::close(&executed).await, + _ => canceller.cancel().await, + }; + }; + tokio::join!(executed.await_result(), stop).0.map(drop) + } + "owner dropped" => { + let executed = statement.submit().await.unwrap(); + let reader = executed.reader().unwrap(); + let server = &server; + let stop = async move { + object_requested(server).await; + drop(executed); + }; + tokio::join!(reader.fetch_result(), stop).0.map(drop) + } + "statement close" | "statement dropped" | "re-execute" => { + let executed = statement.submit().await.unwrap(); + let stop = async { + object_requested(&server).await; + match case { + "statement close" => statement.close().await.unwrap(), + "statement dropped" => drop(statement), + _ => { + statement.spec().volume(None); + statement.execute().await.unwrap(); + } } }; tokio::join!(executed.await_result(), stop).0.map(drop) From 751ac2c87067bb92f801b3d8061d12c1362b9641 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Wed, 2 Dec 2026 22:58:18 +0000 Subject: [PATCH 29/43] fix(volume): let concurrent calls share an input-stream PUT A second call on an execution whose `PUT '__input_stream__'` is still uploading shares that upload's outcome instead of failing for missing bytes: whether the execution has bytes is decided once, when its transfer starts. A pipe GET with no reader is checked to wait up to the idle limit, and the retry tests share one cut-off peer. Co-authored-by: Isaac Signed-off-by: Aakash Saravanan --- src/volume.rs | 128 ++++++++++++++++++++++++++++---------------------- 1 file changed, 71 insertions(+), 57 deletions(-) diff --git a/src/volume.rs b/src/volume.rs index e734f5f1..8014935b 100644 --- a/src/volume.rs +++ b/src/volume.rs @@ -192,10 +192,6 @@ impl VolumeState { self.cancellation.cancel(); } - fn input(&self) -> std::sync::MutexGuard<'_, Option> { - self.input_bytes.lock().unwrap_or_else(|e| e.into_inner()) - } - /// Runs the transfer `instruction` describes, once per execution. Without /// options it does nothing. pub(crate) async fn complete( @@ -212,16 +208,20 @@ impl VolumeState { // execution may still read the instruction. let batch = instruction?.ok_or_else(|| invalid("Missing Volume instruction row"))?; let instruction = Instruction::decode(&batch)?; - if matches!(instruction.operation, Operation::Put(None)) && self.input().is_none() { - return Err(Error::invalid_argument() - .message("A Volume PUT of __input_stream__ needs input bytes")); - } self.outcome .get_or_init(|| async { if self.started.swap(true, Ordering::AcqRel) { return Err(cancelled()); } - let input_bytes = self.input().take(); + let input_bytes = self + .input_bytes + .lock() + .unwrap_or_else(|e| e.into_inner()) + .take(); + if matches!(instruction.operation, Operation::Put(None)) && input_bytes.is_none() { + return Err(Error::invalid_argument() + .message("A Volume PUT of __input_stream__ needs input bytes")); + } // On the session runtime's threads, which kernel-owned runtimes set to // block SIGPIPE, a pipe whose reader exits fails the write instead of // killing the host. @@ -1136,6 +1136,10 @@ mod tests { max_wait: Duration::ZERO, ..Default::default() }; + storage_with(retry, idle_limit) + } + + fn storage_with(retry: RetryConfig, idle_limit: Option) -> Arc { Arc::new(Storage::new( HttpClientConfig::default(), None, @@ -1203,6 +1207,37 @@ mod tests { .await; } + /// A peer that answers every connection with a 10-byte body, sends 3 bytes, + /// holds the connection for `hold` and closes it. Returns its URL and a + /// count of accepted connections. + async fn cut_off_peer( + hold: Duration, + ) -> ( + String, + Arc, + tokio::task::JoinHandle<()>, + ) { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}", listener.local_addr().unwrap()); + let accepted = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let peer = tokio::spawn({ + let accepted = Arc::clone(&accepted); + async move { + loop { + let (mut socket, _) = listener.accept().await.unwrap(); + accepted.fetch_add(1, Ordering::SeqCst); + assert!(socket.read(&mut [0; 4096]).await.unwrap() > 0); + socket + .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\nabc") + .await + .unwrap(); + tokio::time::sleep(hold).await; + } + } + }); + (url, accepted, peer) + } + /// Returns once `server` has received a request. async fn requested(server: &MockServer) { while server.received_requests().await.unwrap().is_empty() { @@ -1277,7 +1312,7 @@ mod tests { let server = MockServer::start().await; Mock::given(method("PUT")) .and(body_bytes(b"caller bytes".to_vec())) - .respond_with(ResponseTemplate::new(200)) + .respond_with(ResponseTemplate::new(200).set_delay(Duration::from_millis(200))) .expect(1) .mount(&server) .await; @@ -1289,7 +1324,14 @@ mod tests { let bytes = Bytes::from(b"caller bytes".to_vec()); let options = VolumeOptions::default().with_input_bytes(bytes.clone()); let with = storage.transfer_state(Some(options)); - with.complete(Ok(Some(put))).await.unwrap(); + // A second call while the upload runs shares its outcome. + let second = async { + requested(&server).await; + with.complete(Ok(Some(put.clone()))).await + }; + let (first, second) = tokio::join!(with.complete(Ok(Some(put.clone()))), second); + first.unwrap(); + second.unwrap(); // The finished transfer no longer holds the upload. assert!(bytes.is_unique()); } @@ -1302,8 +1344,13 @@ mod tests { let dir = tempfile::tempdir().unwrap(); let created = dir.path().join("created"); std::fs::write(&created, b"").unwrap(); - // A name near the OS limit still leaves room for the temporary file's. - let new = dir.path().join("n".repeat(250)); + // On Unix, a name near the 255-byte limit still leaves room for the + // temporary file's. + let new = dir.path().join(if cfg!(unix) { + "n".repeat(250) + } else { + "new".into() + }); let get = instruction("GET", &server.uri(), &new); run(&storage(0, None), get, dir.path()).await.unwrap(); assert_eq!(std::fs::read(&new).unwrap(), b"content"); @@ -1752,7 +1799,10 @@ mod tests { mkfifo(&fifo); let get = instruction("GET", &server.uri(), &fifo); let storage = storage(0, Some(Duration::from_millis(300))); + let started = Instant::now(); let error = run(&storage, get, dir.path()).await.unwrap_err(); + // It waited for a reader before giving up. + assert!(started.elapsed() >= Duration::from_millis(300)); assert_eq!(error.local_error.unwrap().raw_os_error, Some(libc::ENXIO)); } @@ -1799,23 +1849,7 @@ mod tests { #[tokio::test] async fn a_download_cut_off_mid_body_is_retried_into_a_file() { let dir = tempfile::tempdir().unwrap(); - let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); - let url = format!("http://{}", listener.local_addr().unwrap()); - let accepted = Arc::new(std::sync::atomic::AtomicUsize::new(0)); - let peer = tokio::spawn({ - let accepted = Arc::clone(&accepted); - async move { - loop { - let (mut socket, _) = listener.accept().await.unwrap(); - accepted.fetch_add(1, Ordering::SeqCst); - assert!(socket.read(&mut [0; 4096]).await.unwrap() > 0); - socket - .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\nabc") - .await - .unwrap(); - } - } - }); + let (url, accepted, peer) = cut_off_peer(Duration::ZERO).await; let get = instruction("GET", &url, &dir.path().join("file")); run(&storage(2, None), get, dir.path()).await.unwrap_err(); peer.abort(); @@ -1920,7 +1954,10 @@ mod tests { let watcher = { let (state, destination) = (Arc::clone(&state), destination.clone()); std::thread::spawn(move || { - while std::fs::metadata(&destination).map_or(0, |m| m.len()) == 0 {} + let deadline = Instant::now() + Duration::from_secs(30); + while std::fs::metadata(&destination).map_or(0, |m| m.len()) == 0 + && Instant::now() < deadline + {} state.cancel(); }) }; @@ -1932,25 +1969,8 @@ mod tests { #[tokio::test] async fn the_retry_budget_runs_from_the_first_failure() { - let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); - let url = format!("http://{}", listener.local_addr().unwrap()); - let accepted = Arc::new(std::sync::atomic::AtomicUsize::new(0)); - let peer = tokio::spawn({ - let accepted = Arc::clone(&accepted); - async move { - loop { - let (mut socket, _) = listener.accept().await.unwrap(); - accepted.fetch_add(1, Ordering::SeqCst); - assert!(socket.read(&mut [0; 4096]).await.unwrap() > 0); - socket - .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\nabc") - .await - .unwrap(); - // Each attempt outlasts the whole budget before it is cut off. - tokio::time::sleep(Duration::from_millis(300)).await; - } - } - }); + // Each attempt outlasts the whole budget before it is cut off. + let (url, accepted, peer) = cut_off_peer(Duration::from_millis(300)).await; let retry = RetryConfig { max_retries: 2, min_wait: Duration::ZERO, @@ -1958,13 +1978,7 @@ mod tests { overall_timeout: Duration::from_millis(100), ..Default::default() }; - let storage = Arc::new(Storage::new( - HttpClientConfig::default(), - None, - retry, - None, - tokio::runtime::Handle::current(), - )); + let storage = storage_with(retry, None); let dir = tempfile::tempdir().unwrap(); let get = instruction("GET", &url, &dir.path().join("file")); run(&storage, get, dir.path()).await.unwrap_err(); From bc422067d81b5a2e6ef71b98e254ce5189516815 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Wed, 2 Dec 2026 23:18:07 +0000 Subject: [PATCH 30/43] fix(volume): fail an unmarked Volume command and write refusing folders in place A PUT, GET or REMOVE executed with Volume options whose result the server did not mark as a Volume operation, such as one with bound parameters, now fails instead of succeeding with no file moved. A GET into an existing file whose folder refuses a temporary file writes into the file directly, as the Thrift drivers do, instead of staging the whole download in the system temp directory. Local file errors no longer carry SQLSTATE HY000, which belongs to the ODBC mapping. `VolumeOptions` prints the length of its input bytes, not their content. Tests drop the cases that only re-checked fixes to earlier commits of this change (the concurrent input-stream caller, the retry budget, the system-temp fallback). Co-authored-by: Isaac Signed-off-by: Aakash Saravanan --- src/kernel_error.rs | 9 +- src/result_stream.rs | 5 +- src/session.rs | 4 +- src/statement/mutable.rs | 6 +- src/telemetry/statement.rs | 2 +- src/volume.rs | 212 ++++++++++++++++++------------------ tests/v0_volume_wiremock.rs | 30 ++++- 7 files changed, 144 insertions(+), 124 deletions(-) diff --git a/src/kernel_error.rs b/src/kernel_error.rs index 58d43cab..b7be386b 100644 --- a/src/kernel_error.rs +++ b/src/kernel_error.rs @@ -43,10 +43,11 @@ //! 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. +//! logging and host-language exception mapping. Build it with +//! `Error::new(...)` and the `with_*(...)` setters, which a new field +//! does not break; code that builds it with a struct literal must set +//! every field. Keeping the marker would block useful pattern-matches +//! for no real benefit. #![allow(dead_code)] diff --git a/src/result_stream.rs b/src/result_stream.rs index 011b188b..9ef6a636 100644 --- a/src/result_stream.rs +++ b/src/result_stream.rs @@ -654,9 +654,12 @@ impl ResultStream { volume: Option<&Arc>, ) -> Result<()> { self.is_volume_operation = manifest.is_some_and(|manifest| manifest.is_volume_operation); - let Some(volume) = volume.filter(|_| self.is_volume_operation) else { + let Some(volume) = volume else { return Ok(()); }; + if !self.is_volume_operation { + return volume.unmarked(); + } let instruction = self .peek_first_batch() .await diff --git a/src/session.rs b/src/session.rs index 7fee29a1..b459ae1c 100644 --- a/src/session.rs +++ b/src/session.rs @@ -169,8 +169,10 @@ impl SessionInner { pub(crate) fn new_volume_state( &self, options: Option, + sql: Option<&str>, ) -> Arc { - self.storage.transfer_state(options) + let volume_command = sql.is_some_and(crate::volume::is_volume_command); + self.storage.transfer_state(options, volume_command) } /// Crate-internal accessor for the server-issued session ID. diff --git a/src/statement/mutable.rs b/src/statement/mutable.rs index 117dfe41..af238400 100644 --- a/src/statement/mutable.rs +++ b/src/statement/mutable.rs @@ -316,7 +316,7 @@ 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 = Arc::new(Mutex::new(session.new_volume_state(None))); + let volume = Arc::new(Mutex::new(session.new_volume_state(None, None))); Self { session, spec: StatementSpec::new(), @@ -912,7 +912,9 @@ impl Statement { ..options.clone() } }); - let state = self.session.new_volume_state(options); + let state = self + .session + .new_volume_state(options, self.spec.sql.as_deref()); let mut slot = self.volume.lock().unwrap_or_else(|e| e.into_inner()); std::mem::replace(&mut *slot, Arc::clone(&state)).cancel(); state diff --git a/src/telemetry/statement.rs b/src/telemetry/statement.rs index 80f65acd..0ff537d8 100644 --- a/src/telemetry/statement.rs +++ b/src/telemetry/statement.rs @@ -403,7 +403,7 @@ mod tests { None, tokio::runtime::Handle::current(), )); - let volume = storage.transfer_state(Some(Default::default())); + let volume = storage.transfer_state(Some(Default::default()), false); let error = stream .complete_volume(Some(&manifest), Some(&volume)) .await diff --git a/src/volume.rs b/src/volume.rs index 8014935b..5ef377d7 100644 --- a/src/volume.rs +++ b/src/volume.rs @@ -60,7 +60,9 @@ const PIPE_READER_POLL: Duration = Duration::from_millis(50); /// `Content-Encoding` is decoded, because it marks the stored bytes as a /// compressed form of that content. A GET into a file replaces it only after /// the download succeeds; a failure while copying into an existing file can -/// leave it partly written. On Unix a GET also writes into an existing pipe or +/// leave it partly written. An existing file whose folder refuses a temporary +/// file is written directly, so there a failed download can leave it partly +/// written. On Unix a GET also writes into an existing pipe or /// character device as the download arrives: a pipe waits for a reader up to /// the idle limit, and a failure after the first bytes reach it is not retried. /// Cancelling the execution stops the transfer but cannot undo a PUT or REMOVE @@ -69,7 +71,7 @@ const PIPE_READER_POLL: Duration = Duration::from_millis(50); /// running after the call returns, and later calls for that execution report /// `Cancelled`. #[non_exhaustive] -#[derive(Debug, Clone, Default)] +#[derive(Clone, Default)] pub struct VolumeOptions { /// Directories a PUT may read from and a GET may write to. The local path, /// with symlinks resolved, must be inside one of them when the file is @@ -100,6 +102,42 @@ impl VolumeOptions { } } +impl std::fmt::Debug for VolumeOptions { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("VolumeOptions") + .field("allowed_paths", &self.allowed_paths) + .field( + "remove_not_found_is_success", + &self.remove_not_found_is_success, + ) + .field("input_bytes", &self.input_bytes.as_ref().map(Bytes::len)) + .finish() + } +} + +/// Whether `sql` is a Volume PUT, GET or REMOVE, judged by its first keyword +/// after any leading comments. +pub(crate) fn is_volume_command(sql: &str) -> bool { + let mut rest = sql.trim_start(); + loop { + if let Some(comment) = rest.strip_prefix("--") { + rest = comment.split_once('\n').map_or("", |(_, rest)| rest); + } else if let Some(comment) = rest.strip_prefix("/*") { + rest = comment.split_once("*/").map_or("", |(_, rest)| rest); + } else { + break; + } + rest = rest.trim_start(); + } + let keyword = rest + .split(|c: char| !c.is_ascii_alphabetic()) + .next() + .unwrap_or(""); + ["PUT", "GET", "REMOVE"] + .iter() + .any(|command| keyword.eq_ignore_ascii_case(command)) +} + /// Storage access shared by a session's Volume transfers. pub(crate) struct Storage { config: HttpClientConfig, @@ -132,10 +170,12 @@ impl Storage { } /// State for one execution's transfer. Without options, the execution - /// transfers nothing. + /// transfers nothing. `volume_command` is whether the statement is a Volume + /// PUT, GET or REMOVE. pub(crate) fn transfer_state( self: &Arc, mut options: Option, + volume_command: bool, ) -> Arc { let input_bytes = options .as_mut() @@ -143,6 +183,7 @@ impl Storage { Arc::new(VolumeState { storage: Arc::clone(self), options, + volume_command, input_bytes: std::sync::Mutex::new(input_bytes), cancellation: self.cancellation.child_token(), outcome: OnceCell::new(), @@ -178,6 +219,7 @@ impl Drop for AbortOnDrop { pub(crate) struct VolumeState { storage: Arc, options: Option, + volume_command: bool, /// Taken when the transfer starts, so the upload does not outlive it. input_bytes: std::sync::Mutex>, cancellation: CancellationToken, @@ -192,6 +234,18 @@ impl VolumeState { self.cancellation.cancel(); } + /// The outcome for a result the server did not mark as a Volume + /// operation. A Volume command the caller wants transferred fails rather + /// than moving no file. + pub(crate) fn unmarked(&self) -> Result<()> { + if self.options.is_some() && self.volume_command { + return Err(invalid( + "The server did not mark this PUT, GET or REMOVE as a Volume operation, so no file was transferred", + )); + } + Ok(()) + } + /// Runs the transfer `instruction` describes, once per execution. Without /// options it does nothing. pub(crate) async fn complete( @@ -381,7 +435,11 @@ impl VolumeState { let mut stream; let (sink, rewindable): (&mut (dyn AsyncWrite + Send + Unpin), bool) = match &download.destination { - Destination::Existing { temp, .. } | Destination::New { temp, .. } => { + Destination::Existing { + temp: Some(temp), .. + } + | Destination::Existing { file: temp, .. } + | Destination::New { temp, .. } => { temp_file = tokio::fs::File::from_std(temp.try_clone().map_err(local_error)?); temp_file.set_len(0).await.map_err(local_error)?; temp_file.rewind().await.map_err(local_error)?; @@ -682,10 +740,11 @@ struct Download { /// A GET into a file downloads to `temp` first, so a failed download leaves /// the file unchanged. enum Destination { - /// Overwritten with a copy of `temp`, keeping the file itself. + /// Overwritten with a copy of `temp`, keeping the file itself. Without + /// `temp`, because the folder refuses one, the download writes into it. Existing { file: std::fs::File, - temp: std::fs::File, + temp: Option, }, /// `temp`, renamed into place after its path is checked against the /// allowed roots again. @@ -755,6 +814,7 @@ async fn prepare( .open(&path) .map_err(local_error)?; let temp = match tempfile::tempfile_in(parent) { + Ok(temp) => Some(temp), Err(error) if matches!( error.kind(), @@ -762,11 +822,10 @@ async fn prepare( | std::io::ErrorKind::ReadOnlyFilesystem ) => { - tempfile::tempfile() + None } - temp => temp, - } - .map_err(local_error)?; + Err(error) => return Err(local_error(error)), + }; Destination::Existing { file, temp } } #[cfg(unix)] @@ -853,11 +912,15 @@ impl Local { tokio::task::spawn_blocking(move || { let local_error = |e| local_error(e, &name); match destination { - Destination::Existing { mut file, mut temp } => { + Destination::Existing { + mut file, + temp: Some(mut temp), + } => { temp.rewind().map_err(local_error)?; let length = std::io::copy(&mut temp, &mut file).map_err(local_error)?; file.set_len(length).map_err(local_error) } + Destination::Existing { temp: None, .. } => Ok(()), Destination::New { temp, path, @@ -1110,7 +1173,6 @@ fn local_error(error: std::io::Error, path: &str) -> Error { _ => Error::io(), } .with_error_code("VOLUME_LOCAL_FILE_ERROR") - .with_sql_state("HY000") .message(format!("{error}: {path}")) .with_local_error(LocalFileError::new( error.raw_os_error(), @@ -1136,10 +1198,6 @@ mod tests { max_wait: Duration::ZERO, ..Default::default() }; - storage_with(retry, idle_limit) - } - - fn storage_with(retry: RetryConfig, idle_limit: Option) -> Arc { Arc::new(Storage::new( HttpClientConfig::default(), None, @@ -1151,7 +1209,10 @@ mod tests { /// One execution's transfer state with `root` allowed. fn state(storage: &Arc, root: &Path) -> Arc { - storage.transfer_state(Some(VolumeOptions::new(vec![root.to_owned()], false))) + storage.transfer_state( + Some(VolumeOptions::new(vec![root.to_owned()], false)), + false, + ) } /// Runs one execution's transfer of `batch` with `root` allowed. @@ -1207,37 +1268,6 @@ mod tests { .await; } - /// A peer that answers every connection with a 10-byte body, sends 3 bytes, - /// holds the connection for `hold` and closes it. Returns its URL and a - /// count of accepted connections. - async fn cut_off_peer( - hold: Duration, - ) -> ( - String, - Arc, - tokio::task::JoinHandle<()>, - ) { - let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); - let url = format!("http://{}", listener.local_addr().unwrap()); - let accepted = Arc::new(std::sync::atomic::AtomicUsize::new(0)); - let peer = tokio::spawn({ - let accepted = Arc::clone(&accepted); - async move { - loop { - let (mut socket, _) = listener.accept().await.unwrap(); - accepted.fetch_add(1, Ordering::SeqCst); - assert!(socket.read(&mut [0; 4096]).await.unwrap() > 0); - socket - .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\nabc") - .await - .unwrap(); - tokio::time::sleep(hold).await; - } - } - }); - (url, accepted, peer) - } - /// Returns once `server` has received a request. async fn requested(server: &MockServer) { while server.received_requests().await.unwrap().is_empty() { @@ -1312,26 +1342,19 @@ mod tests { let server = MockServer::start().await; Mock::given(method("PUT")) .and(body_bytes(b"caller bytes".to_vec())) - .respond_with(ResponseTemplate::new(200).set_delay(Duration::from_millis(200))) + .respond_with(ResponseTemplate::new(200)) .expect(1) .mount(&server) .await; let put = instruction("PUT", &server.uri(), Path::new("__input_stream__")); let storage = storage(0, None); - let without = storage.transfer_state(Some(VolumeOptions::default())); + let without = storage.transfer_state(Some(VolumeOptions::default()), false); let error = without.complete(Ok(Some(put.clone()))).await.unwrap_err(); assert_eq!(error.code, ErrorCode::InvalidArgument); let bytes = Bytes::from(b"caller bytes".to_vec()); let options = VolumeOptions::default().with_input_bytes(bytes.clone()); - let with = storage.transfer_state(Some(options)); - // A second call while the upload runs shares its outcome. - let second = async { - requested(&server).await; - with.complete(Ok(Some(put.clone()))).await - }; - let (first, second) = tokio::join!(with.complete(Ok(Some(put.clone()))), second); - first.unwrap(); - second.unwrap(); + let with = storage.transfer_state(Some(options), false); + with.complete(Ok(Some(put))).await.unwrap(); // The finished transfer no longer holds the upload. assert!(bytes.is_unique()); } @@ -1445,7 +1468,7 @@ mod tests { for remove_not_found_is_success in [true, false] { let options = VolumeOptions::new(Vec::new(), remove_not_found_is_success); let result = storage - .transfer_state(Some(options)) + .transfer_state(Some(options), false) .complete(Ok(Some(remove(&server.uri())))) .await; assert_eq!(result.is_ok(), remove_not_found_is_success); @@ -1849,7 +1872,23 @@ mod tests { #[tokio::test] async fn a_download_cut_off_mid_body_is_retried_into_a_file() { let dir = tempfile::tempdir().unwrap(); - let (url, accepted, peer) = cut_off_peer(Duration::ZERO).await; + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}", listener.local_addr().unwrap()); + let accepted = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let peer = tokio::spawn({ + let accepted = Arc::clone(&accepted); + async move { + loop { + let (mut socket, _) = listener.accept().await.unwrap(); + accepted.fetch_add(1, Ordering::SeqCst); + assert!(socket.read(&mut [0; 4096]).await.unwrap() > 0); + socket + .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\nabc") + .await + .unwrap(); + } + } + }); let get = instruction("GET", &url, &dir.path().join("file")); run(&storage(2, None), get, dir.path()).await.unwrap_err(); peer.abort(); @@ -1870,7 +1909,6 @@ mod tests { let error = run(&storage, transfer, dir.path()).await.unwrap_err(); assert_eq!(error.code, ErrorCode::NotFound, "{operation}"); assert_eq!(error.error_code.as_deref(), Some("VOLUME_LOCAL_FILE_ERROR")); - assert_eq!(error.sql_state.as_deref(), Some("HY000")); assert!(!error.message.contains("secret"), "{operation}"); let details = error.local_error.unwrap(); assert_eq!(details.kind, std::io::ErrorKind::NotFound, "{operation}"); @@ -1914,32 +1952,6 @@ mod tests { assert!(server.received_requests().await.unwrap().is_empty()); } - #[tokio::test] - #[cfg(unix)] - async fn an_existing_file_in_a_folder_that_refuses_files_is_still_replaced() { - use std::os::unix::fs::PermissionsExt; - if privileged() { - return; - } - let server = MockServer::start().await; - mount( - &server, - "GET", - "/", - ResponseTemplate::new(200).set_body_string("new"), - ) - .await; - let dir = tempfile::tempdir().unwrap(); - let existing = dir.path().join("existing"); - std::fs::write(&existing, b"old content").unwrap(); - std::fs::set_permissions(dir.path(), PermissionsExt::from_mode(0o555)).unwrap(); - let get = instruction("GET", &server.uri(), &existing); - let result = run(&storage(0, None), get, dir.path()).await; - std::fs::set_permissions(dir.path(), PermissionsExt::from_mode(0o755)).unwrap(); - result.unwrap(); - assert_eq!(std::fs::read(&existing).unwrap(), b"new"); - } - #[tokio::test] async fn a_cancel_while_a_download_is_put_in_place_lets_it_finish() { let body = vec![b'x'; 32 << 20]; @@ -1957,7 +1969,9 @@ mod tests { let deadline = Instant::now() + Duration::from_secs(30); while std::fs::metadata(&destination).map_or(0, |m| m.len()) == 0 && Instant::now() < deadline - {} + { + std::thread::sleep(Duration::from_millis(1)); + } state.cancel(); }) }; @@ -1967,26 +1981,6 @@ mod tests { assert_eq!(std::fs::read(&destination).unwrap().len(), body.len()); } - #[tokio::test] - async fn the_retry_budget_runs_from_the_first_failure() { - // Each attempt outlasts the whole budget before it is cut off. - let (url, accepted, peer) = cut_off_peer(Duration::from_millis(300)).await; - let retry = RetryConfig { - max_retries: 2, - min_wait: Duration::ZERO, - max_wait: Duration::ZERO, - overall_timeout: Duration::from_millis(100), - ..Default::default() - }; - let storage = storage_with(retry, None); - let dir = tempfile::tempdir().unwrap(); - let get = instruction("GET", &url, &dir.path().join("file")); - run(&storage, get, dir.path()).await.unwrap_err(); - peer.abort(); - // One retry: measured from the start, the budget would allow none. - assert_eq!(accepted.load(Ordering::SeqCst), 2); - } - #[tokio::test] async fn cancelled_or_abandoned_transfers_do_not_run_again() { for abandon in [false, true] { diff --git a/tests/v0_volume_wiremock.rs b/tests/v0_volume_wiremock.rs index fdcec66b..61bda2d2 100644 --- a/tests/v0_volume_wiremock.rs +++ b/tests/v0_volume_wiremock.rs @@ -198,7 +198,14 @@ async fn execution_with_options_transfers_and_keeps_the_instruction_row() { #[tokio::test] async fn only_a_marked_result_with_options_transfers() { - for (marked, with_options) in [(false, true), (true, false)] { + // (SQL, marked by the server, options set, fails) + for (sql, marked, with_options, fails) in [ + ("SELECT 1", false, true, false), + ("GET", true, false, false), + // The server leaves some Volume commands unmarked; one the caller wants + // transferred fails instead of moving no file. + ("/* tag */ get 'x' TO 'y'", false, true, true), + ] { let server = MockServer::start().await; let dir = tempfile::tempdir().unwrap(); let destination = dir.path().join("download"); @@ -208,12 +215,23 @@ async fn only_a_marked_result_with_options_transfers() { let mut statement = session.statement(); statement .spec() - .sql("GET") + .sql(sql) .volume(options(dir.path()).filter(|_| with_options)); - let mut executed = statement.execute().await.unwrap(); - let stream = executed.result_stream_mut(); - assert_eq!(stream.is_volume_operation(), marked); - assert_eq!(instruction_rows(stream).await, 1); + match statement.execute().await { + Ok(mut executed) => { + assert!(!fails, "{sql}"); + let stream = executed.result_stream_mut(); + assert_eq!(stream.is_volume_operation(), marked); + assert_eq!(instruction_rows(stream).await, 1); + } + Err(error) => { + assert!(fails, "{sql}: {}", error.message); + assert_eq!( + error.error_code.as_deref(), + Some("VOLUME_INVALID_INSTRUCTION") + ); + } + } assert!(!destination.exists()); } } From 27e265920aab6e2c3b2d2a4b333c37dcefafe0cd Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Wed, 2 Dec 2026 23:28:43 +0000 Subject: [PATCH 31/43] fix(volume): record a failed unmarked check and match whole keywords A Volume command the server left unmarked now finalizes its statement with the error, as a failed transfer does, instead of recording success. The command check compares the whole first word, so a SQL script label such as `get_rows:` is not taken for a GET. The test of an existing file in a folder that refuses temporary files is restored; it covers the in-place write. Co-authored-by: Isaac Signed-off-by: Aakash Saravanan --- NEXT_CHANGELOG.md | 4 +- src/result_stream.rs | 17 ++++---- src/telemetry/statement.rs | 80 +++++++++++++++++++------------------ src/volume.rs | 40 +++++++++++++++---- tests/v0_volume_wiremock.rs | 1 + 5 files changed, 88 insertions(+), 54 deletions(-) diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index 6551a879..8fc3a9d6 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -27,7 +27,9 @@ changes go in their respective binding's NEXT_CHANGELOG. transfer. Local paths, with symlinks resolved, must be inside the caller's allowed directories. `HttpConfig::storage_read_timeout` limits how long a transfer may go without progress (15 minutes by default). On Unix a GET can also - write into an existing pipe or character device as the download arrives. + write into an existing pipe or character device as the download arrives. A + PUT, GET or REMOVE executed with those options whose result the server did not + mark as a Volume operation fails rather than moving no file. ### Changed diff --git a/src/result_stream.rs b/src/result_stream.rs index 9ef6a636..8f6ef486 100644 --- a/src/result_stream.rs +++ b/src/result_stream.rs @@ -657,14 +657,15 @@ impl ResultStream { let Some(volume) = volume else { return Ok(()); }; - if !self.is_volume_operation { - return volume.unmarked(); - } - let instruction = self - .peek_first_batch() - .await - .map(|batch| batch.map(|ResultBatch::Arrow(batch)| batch.clone())); - let result = volume.complete(instruction).await; + let result = if self.is_volume_operation { + let instruction = self + .peek_first_batch() + .await + .map(|batch| batch.map(|ResultBatch::Arrow(batch)| batch.clone())); + volume.complete(instruction).await + } else { + volume.unmarked() + }; if let Err(error) = &result { self.finalize_telemetry(Some(error)); } diff --git a/src/telemetry/statement.rs b/src/telemetry/statement.rs index 0ff537d8..86e95e78 100644 --- a/src/telemetry/statement.rs +++ b/src/telemetry/statement.rs @@ -375,45 +375,49 @@ mod tests { #[tokio::test] async fn failed_volume_completion_finalizes_statement_with_error() { - let connection = Arc::new(CapturingConnectionTelemetry::default()); - let telemetry = StatementTelemetry::new( - connection.clone(), - StatementType::Sql, - OperationType::ExecuteStatement, - ); - let batch = RecordBatch::try_from_iter([( - "n", - Arc::new(arrow_array::Int64Array::from(vec![1])) as arrow_array::ArrayRef, - )]) - .unwrap(); - let reader = crate::reader::test_utils::MockReader::new(vec![batch]); - let mut stream = ResultStream::from_reader(Box::new(reader)).await.unwrap(); - stream.attach_telemetry(telemetry); - let manifest: crate::types::sea::ResultManifest = - serde_json::from_value(serde_json::json!({ - "is_volume_operation": true, - "format": "ARROW_STREAM", - "schema": {"column_count": 1, "columns": []}, - })) + // (server marked it, statement is a Volume command): a failed transfer, + // then a Volume command the server left unmarked. + for (marked, volume_command) in [(true, false), (false, true)] { + let connection = Arc::new(CapturingConnectionTelemetry::default()); + let telemetry = StatementTelemetry::new( + connection.clone(), + StatementType::Sql, + OperationType::ExecuteStatement, + ); + let batch = RecordBatch::try_from_iter([( + "n", + Arc::new(arrow_array::Int64Array::from(vec![1])) as arrow_array::ArrayRef, + )]) .unwrap(); - let storage = Arc::new(crate::volume::Storage::new( - Default::default(), - None, - Default::default(), - None, - tokio::runtime::Handle::current(), - )); - let volume = storage.transfer_state(Some(Default::default()), false); - let error = stream - .complete_volume(Some(&manifest), Some(&volume)) - .await - .unwrap_err(); - - drop(stream); - - let events = connection.statement_events.lock().expect("events mutex"); - assert_eq!(events.len(), 1); - assert_eq!(events[0].error_code, Some(error.code)); + let reader = crate::reader::test_utils::MockReader::new(vec![batch]); + let mut stream = ResultStream::from_reader(Box::new(reader)).await.unwrap(); + stream.attach_telemetry(telemetry); + let manifest: crate::types::sea::ResultManifest = + serde_json::from_value(serde_json::json!({ + "is_volume_operation": marked, + "format": "ARROW_STREAM", + "schema": {"column_count": 1, "columns": []}, + })) + .unwrap(); + let storage = Arc::new(crate::volume::Storage::new( + Default::default(), + None, + Default::default(), + None, + tokio::runtime::Handle::current(), + )); + let volume = storage.transfer_state(Some(Default::default()), volume_command); + let error = stream + .complete_volume(Some(&manifest), Some(&volume)) + .await + .unwrap_err(); + + drop(stream); + + let events = connection.statement_events.lock().expect("events mutex"); + assert_eq!(events.len(), 1, "marked={marked}"); + assert_eq!(events[0].error_code, Some(error.code), "marked={marked}"); + } } #[tokio::test] diff --git a/src/volume.rs b/src/volume.rs index 5ef377d7..aea2387b 100644 --- a/src/volume.rs +++ b/src/volume.rs @@ -61,8 +61,8 @@ const PIPE_READER_POLL: Duration = Duration::from_millis(50); /// compressed form of that content. A GET into a file replaces it only after /// the download succeeds; a failure while copying into an existing file can /// leave it partly written. An existing file whose folder refuses a temporary -/// file is written directly, so there a failed download can leave it partly -/// written. On Unix a GET also writes into an existing pipe or +/// file is written directly, so there a failed or cancelled download can leave +/// it truncated or partly written. On Unix a GET also writes into an existing pipe or /// character device as the download arrives: a pipe waits for a reader up to /// the idle limit, and a failure after the first bytes reach it is not retried. /// Cancelling the execution stops the transfer but cannot undo a PUT or REMOVE @@ -130,7 +130,7 @@ pub(crate) fn is_volume_command(sql: &str) -> bool { rest = rest.trim_start(); } let keyword = rest - .split(|c: char| !c.is_ascii_alphabetic()) + .split(|c: char| !(c.is_ascii_alphanumeric() || c == '_')) .next() .unwrap_or(""); ["PUT", "GET", "REMOVE"] @@ -436,11 +436,11 @@ impl VolumeState { let (sink, rewindable): (&mut (dyn AsyncWrite + Send + Unpin), bool) = match &download.destination { Destination::Existing { - temp: Some(temp), .. + temp: Some(target), .. } - | Destination::Existing { file: temp, .. } - | Destination::New { temp, .. } => { - temp_file = tokio::fs::File::from_std(temp.try_clone().map_err(local_error)?); + | Destination::Existing { file: target, .. } + | Destination::New { temp: target, .. } => { + temp_file = tokio::fs::File::from_std(target.try_clone().map_err(local_error)?); temp_file.set_len(0).await.map_err(local_error)?; temp_file.rewind().await.map_err(local_error)?; (&mut temp_file, true) @@ -1952,6 +1952,32 @@ mod tests { assert!(server.received_requests().await.unwrap().is_empty()); } + #[tokio::test] + #[cfg(unix)] + async fn an_existing_file_in_a_folder_that_refuses_files_is_still_replaced() { + use std::os::unix::fs::PermissionsExt; + if privileged() { + return; + } + let server = MockServer::start().await; + mount( + &server, + "GET", + "/", + ResponseTemplate::new(200).set_body_string("new"), + ) + .await; + let dir = tempfile::tempdir().unwrap(); + let existing = dir.path().join("existing"); + std::fs::write(&existing, b"old content").unwrap(); + std::fs::set_permissions(dir.path(), PermissionsExt::from_mode(0o555)).unwrap(); + let get = instruction("GET", &server.uri(), &existing); + let result = run(&storage(0, None), get, dir.path()).await; + std::fs::set_permissions(dir.path(), PermissionsExt::from_mode(0o755)).unwrap(); + result.unwrap(); + assert_eq!(std::fs::read(&existing).unwrap(), b"new"); + } + #[tokio::test] async fn a_cancel_while_a_download_is_put_in_place_lets_it_finish() { let body = vec![b'x'; 32 << 20]; diff --git a/tests/v0_volume_wiremock.rs b/tests/v0_volume_wiremock.rs index 61bda2d2..7f2548f9 100644 --- a/tests/v0_volume_wiremock.rs +++ b/tests/v0_volume_wiremock.rs @@ -201,6 +201,7 @@ async fn only_a_marked_result_with_options_transfers() { // (SQL, marked by the server, options set, fails) for (sql, marked, with_options, fails) in [ ("SELECT 1", false, true, false), + ("get_rows: BEGIN SELECT 1; END", false, true, false), ("GET", true, false, false), // The server leaves some Volume commands unmarked; one the caller wants // transferred fails instead of moving no file. From 3d5ceebc9e3e5f3fcace6a3028ab077d09a6e719 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Thu, 3 Dec 2026 00:34:02 +0000 Subject: [PATCH 32/43] refactor(volume): drop the check for unmarked PUT, GET and REMOVE Only a result the server marks as a Volume operation runs a transfer again; an unmarked one returns its row and moves no file. Removes is_volume_command, the per-execution flag and VolumeState::unmarked, with the telemetry case and wiremock rows that covered them. Co-authored-by: Isaac Signed-off-by: Aakash Saravanan --- NEXT_CHANGELOG.md | 4 +- src/result_stream.rs | 16 +++----- src/session.rs | 4 +- src/statement/mutable.rs | 6 +-- src/telemetry/statement.rs | 80 ++++++++++++++++++------------------- src/volume.rs | 52 +++--------------------- tests/v0_volume_wiremock.rs | 31 +++----------- 7 files changed, 59 insertions(+), 134 deletions(-) diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index 8fc3a9d6..6551a879 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -27,9 +27,7 @@ changes go in their respective binding's NEXT_CHANGELOG. transfer. Local paths, with symlinks resolved, must be inside the caller's allowed directories. `HttpConfig::storage_read_timeout` limits how long a transfer may go without progress (15 minutes by default). On Unix a GET can also - write into an existing pipe or character device as the download arrives. A - PUT, GET or REMOVE executed with those options whose result the server did not - mark as a Volume operation fails rather than moving no file. + write into an existing pipe or character device as the download arrives. ### Changed diff --git a/src/result_stream.rs b/src/result_stream.rs index 8f6ef486..011b188b 100644 --- a/src/result_stream.rs +++ b/src/result_stream.rs @@ -654,18 +654,14 @@ impl ResultStream { volume: Option<&Arc>, ) -> Result<()> { self.is_volume_operation = manifest.is_some_and(|manifest| manifest.is_volume_operation); - let Some(volume) = volume else { + let Some(volume) = volume.filter(|_| self.is_volume_operation) else { return Ok(()); }; - let result = if self.is_volume_operation { - let instruction = self - .peek_first_batch() - .await - .map(|batch| batch.map(|ResultBatch::Arrow(batch)| batch.clone())); - volume.complete(instruction).await - } else { - volume.unmarked() - }; + let instruction = self + .peek_first_batch() + .await + .map(|batch| batch.map(|ResultBatch::Arrow(batch)| batch.clone())); + let result = volume.complete(instruction).await; if let Err(error) = &result { self.finalize_telemetry(Some(error)); } diff --git a/src/session.rs b/src/session.rs index b459ae1c..7fee29a1 100644 --- a/src/session.rs +++ b/src/session.rs @@ -169,10 +169,8 @@ impl SessionInner { pub(crate) fn new_volume_state( &self, options: Option, - sql: Option<&str>, ) -> Arc { - let volume_command = sql.is_some_and(crate::volume::is_volume_command); - self.storage.transfer_state(options, volume_command) + self.storage.transfer_state(options) } /// Crate-internal accessor for the server-issued session ID. diff --git a/src/statement/mutable.rs b/src/statement/mutable.rs index af238400..117dfe41 100644 --- a/src/statement/mutable.rs +++ b/src/statement/mutable.rs @@ -316,7 +316,7 @@ 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 = Arc::new(Mutex::new(session.new_volume_state(None, None))); + let volume = Arc::new(Mutex::new(session.new_volume_state(None))); Self { session, spec: StatementSpec::new(), @@ -912,9 +912,7 @@ impl Statement { ..options.clone() } }); - let state = self - .session - .new_volume_state(options, self.spec.sql.as_deref()); + let state = self.session.new_volume_state(options); let mut slot = self.volume.lock().unwrap_or_else(|e| e.into_inner()); std::mem::replace(&mut *slot, Arc::clone(&state)).cancel(); state diff --git a/src/telemetry/statement.rs b/src/telemetry/statement.rs index 86e95e78..80f65acd 100644 --- a/src/telemetry/statement.rs +++ b/src/telemetry/statement.rs @@ -375,49 +375,45 @@ mod tests { #[tokio::test] async fn failed_volume_completion_finalizes_statement_with_error() { - // (server marked it, statement is a Volume command): a failed transfer, - // then a Volume command the server left unmarked. - for (marked, volume_command) in [(true, false), (false, true)] { - let connection = Arc::new(CapturingConnectionTelemetry::default()); - let telemetry = StatementTelemetry::new( - connection.clone(), - StatementType::Sql, - OperationType::ExecuteStatement, - ); - let batch = RecordBatch::try_from_iter([( - "n", - Arc::new(arrow_array::Int64Array::from(vec![1])) as arrow_array::ArrayRef, - )]) + let connection = Arc::new(CapturingConnectionTelemetry::default()); + let telemetry = StatementTelemetry::new( + connection.clone(), + StatementType::Sql, + OperationType::ExecuteStatement, + ); + let batch = RecordBatch::try_from_iter([( + "n", + Arc::new(arrow_array::Int64Array::from(vec![1])) as arrow_array::ArrayRef, + )]) + .unwrap(); + let reader = crate::reader::test_utils::MockReader::new(vec![batch]); + let mut stream = ResultStream::from_reader(Box::new(reader)).await.unwrap(); + stream.attach_telemetry(telemetry); + let manifest: crate::types::sea::ResultManifest = + serde_json::from_value(serde_json::json!({ + "is_volume_operation": true, + "format": "ARROW_STREAM", + "schema": {"column_count": 1, "columns": []}, + })) .unwrap(); - let reader = crate::reader::test_utils::MockReader::new(vec![batch]); - let mut stream = ResultStream::from_reader(Box::new(reader)).await.unwrap(); - stream.attach_telemetry(telemetry); - let manifest: crate::types::sea::ResultManifest = - serde_json::from_value(serde_json::json!({ - "is_volume_operation": marked, - "format": "ARROW_STREAM", - "schema": {"column_count": 1, "columns": []}, - })) - .unwrap(); - let storage = Arc::new(crate::volume::Storage::new( - Default::default(), - None, - Default::default(), - None, - tokio::runtime::Handle::current(), - )); - let volume = storage.transfer_state(Some(Default::default()), volume_command); - let error = stream - .complete_volume(Some(&manifest), Some(&volume)) - .await - .unwrap_err(); - - drop(stream); - - let events = connection.statement_events.lock().expect("events mutex"); - assert_eq!(events.len(), 1, "marked={marked}"); - assert_eq!(events[0].error_code, Some(error.code), "marked={marked}"); - } + let storage = Arc::new(crate::volume::Storage::new( + Default::default(), + None, + Default::default(), + None, + tokio::runtime::Handle::current(), + )); + let volume = storage.transfer_state(Some(Default::default())); + let error = stream + .complete_volume(Some(&manifest), Some(&volume)) + .await + .unwrap_err(); + + drop(stream); + + let events = connection.statement_events.lock().expect("events mutex"); + assert_eq!(events.len(), 1); + assert_eq!(events[0].error_code, Some(error.code)); } #[tokio::test] diff --git a/src/volume.rs b/src/volume.rs index aea2387b..50aaff9c 100644 --- a/src/volume.rs +++ b/src/volume.rs @@ -115,29 +115,6 @@ impl std::fmt::Debug for VolumeOptions { } } -/// Whether `sql` is a Volume PUT, GET or REMOVE, judged by its first keyword -/// after any leading comments. -pub(crate) fn is_volume_command(sql: &str) -> bool { - let mut rest = sql.trim_start(); - loop { - if let Some(comment) = rest.strip_prefix("--") { - rest = comment.split_once('\n').map_or("", |(_, rest)| rest); - } else if let Some(comment) = rest.strip_prefix("/*") { - rest = comment.split_once("*/").map_or("", |(_, rest)| rest); - } else { - break; - } - rest = rest.trim_start(); - } - let keyword = rest - .split(|c: char| !(c.is_ascii_alphanumeric() || c == '_')) - .next() - .unwrap_or(""); - ["PUT", "GET", "REMOVE"] - .iter() - .any(|command| keyword.eq_ignore_ascii_case(command)) -} - /// Storage access shared by a session's Volume transfers. pub(crate) struct Storage { config: HttpClientConfig, @@ -170,12 +147,10 @@ impl Storage { } /// State for one execution's transfer. Without options, the execution - /// transfers nothing. `volume_command` is whether the statement is a Volume - /// PUT, GET or REMOVE. + /// transfers nothing. pub(crate) fn transfer_state( self: &Arc, mut options: Option, - volume_command: bool, ) -> Arc { let input_bytes = options .as_mut() @@ -183,7 +158,6 @@ impl Storage { Arc::new(VolumeState { storage: Arc::clone(self), options, - volume_command, input_bytes: std::sync::Mutex::new(input_bytes), cancellation: self.cancellation.child_token(), outcome: OnceCell::new(), @@ -219,7 +193,6 @@ impl Drop for AbortOnDrop { pub(crate) struct VolumeState { storage: Arc, options: Option, - volume_command: bool, /// Taken when the transfer starts, so the upload does not outlive it. input_bytes: std::sync::Mutex>, cancellation: CancellationToken, @@ -234,18 +207,6 @@ impl VolumeState { self.cancellation.cancel(); } - /// The outcome for a result the server did not mark as a Volume - /// operation. A Volume command the caller wants transferred fails rather - /// than moving no file. - pub(crate) fn unmarked(&self) -> Result<()> { - if self.options.is_some() && self.volume_command { - return Err(invalid( - "The server did not mark this PUT, GET or REMOVE as a Volume operation, so no file was transferred", - )); - } - Ok(()) - } - /// Runs the transfer `instruction` describes, once per execution. Without /// options it does nothing. pub(crate) async fn complete( @@ -1209,10 +1170,7 @@ mod tests { /// One execution's transfer state with `root` allowed. fn state(storage: &Arc, root: &Path) -> Arc { - storage.transfer_state( - Some(VolumeOptions::new(vec![root.to_owned()], false)), - false, - ) + storage.transfer_state(Some(VolumeOptions::new(vec![root.to_owned()], false))) } /// Runs one execution's transfer of `batch` with `root` allowed. @@ -1348,12 +1306,12 @@ mod tests { .await; let put = instruction("PUT", &server.uri(), Path::new("__input_stream__")); let storage = storage(0, None); - let without = storage.transfer_state(Some(VolumeOptions::default()), false); + let without = storage.transfer_state(Some(VolumeOptions::default())); let error = without.complete(Ok(Some(put.clone()))).await.unwrap_err(); assert_eq!(error.code, ErrorCode::InvalidArgument); let bytes = Bytes::from(b"caller bytes".to_vec()); let options = VolumeOptions::default().with_input_bytes(bytes.clone()); - let with = storage.transfer_state(Some(options), false); + let with = storage.transfer_state(Some(options)); with.complete(Ok(Some(put))).await.unwrap(); // The finished transfer no longer holds the upload. assert!(bytes.is_unique()); @@ -1468,7 +1426,7 @@ mod tests { for remove_not_found_is_success in [true, false] { let options = VolumeOptions::new(Vec::new(), remove_not_found_is_success); let result = storage - .transfer_state(Some(options), false) + .transfer_state(Some(options)) .complete(Ok(Some(remove(&server.uri())))) .await; assert_eq!(result.is_ok(), remove_not_found_is_success); diff --git a/tests/v0_volume_wiremock.rs b/tests/v0_volume_wiremock.rs index 7f2548f9..fdcec66b 100644 --- a/tests/v0_volume_wiremock.rs +++ b/tests/v0_volume_wiremock.rs @@ -198,15 +198,7 @@ async fn execution_with_options_transfers_and_keeps_the_instruction_row() { #[tokio::test] async fn only_a_marked_result_with_options_transfers() { - // (SQL, marked by the server, options set, fails) - for (sql, marked, with_options, fails) in [ - ("SELECT 1", false, true, false), - ("get_rows: BEGIN SELECT 1; END", false, true, false), - ("GET", true, false, false), - // The server leaves some Volume commands unmarked; one the caller wants - // transferred fails instead of moving no file. - ("/* tag */ get 'x' TO 'y'", false, true, true), - ] { + for (marked, with_options) in [(false, true), (true, false)] { let server = MockServer::start().await; let dir = tempfile::tempdir().unwrap(); let destination = dir.path().join("download"); @@ -216,23 +208,12 @@ async fn only_a_marked_result_with_options_transfers() { let mut statement = session.statement(); statement .spec() - .sql(sql) + .sql("GET") .volume(options(dir.path()).filter(|_| with_options)); - match statement.execute().await { - Ok(mut executed) => { - assert!(!fails, "{sql}"); - let stream = executed.result_stream_mut(); - assert_eq!(stream.is_volume_operation(), marked); - assert_eq!(instruction_rows(stream).await, 1); - } - Err(error) => { - assert!(fails, "{sql}: {}", error.message); - assert_eq!( - error.error_code.as_deref(), - Some("VOLUME_INVALID_INSTRUCTION") - ); - } - } + let mut executed = statement.execute().await.unwrap(); + let stream = executed.result_stream_mut(); + assert_eq!(stream.is_volume_operation(), marked); + assert_eq!(instruction_rows(stream).await, 1); assert!(!destination.exists()); } } From 655e55e333a698194f07d1d3de782be0e8044f42 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Thu, 3 Dec 2026 00:35:23 +0000 Subject: [PATCH 33/43] docs(volume): drop comments that restate the code Removes doc comments on private helpers and test helpers whose name and body already say what they do, comments that repeat the VolumeOptions contract elsewhere, and a stale Destination summary. Contracts, caveats and non-obvious reasons stay. Co-authored-by: Isaac Signed-off-by: Aakash Saravanan --- src/client/http.rs | 2 -- src/result_stream.rs | 2 +- src/session.rs | 4 +-- src/statement/executed_async.rs | 1 - src/statement/mutable.rs | 8 ++--- src/statement/spec.rs | 7 ++--- src/volume.rs | 52 +++++++++------------------------ 7 files changed, 20 insertions(+), 56 deletions(-) diff --git a/src/client/http.rs b/src/client/http.rs index 1797d897..bb432dc9 100644 --- a/src/client/http.rs +++ b/src/client/http.rs @@ -847,8 +847,6 @@ impl DatabricksHttpClient { /// Build the client for Volume storage requests: the session's connection /// settings without a total deadline, and redirects left to the caller. - /// Response decoding stays on, so a GET of an object stored with a gzip - /// `Content-Encoding` writes the content that header says it holds. pub(crate) fn storage_client( config: &HttpClientConfig, revocation: Option, diff --git a/src/result_stream.rs b/src/result_stream.rs index 011b188b..02620f77 100644 --- a/src/result_stream.rs +++ b/src/result_stream.rs @@ -647,7 +647,7 @@ impl ResultStream { /// Records whether the server marked this result as a Volume PUT, GET or /// REMOVE and, if so, runs the transfer `volume` holds before any row is - /// read. `None` transfers nothing. + /// read. pub(crate) async fn complete_volume( &mut self, manifest: Option<&crate::types::sea::ResultManifest>, diff --git a/src/session.rs b/src/session.rs index 7fee29a1..13d36240 100644 --- a/src/session.rs +++ b/src/session.rs @@ -383,8 +383,8 @@ impl Session { crate::client::http::check_revocation_support(&http_client_config.tls, revocation)?; validate_revocation_endpoint_scheme(&config, revocation)?; let retry_configs = build_retry_configs_for_session(&config); - // Volume transfers retry with the SQL settings; the CloudFetch ones - // disable retries because its chunk loop retries on its own. + // The CloudFetch retry settings disable retries, so Volume transfers + // use the SQL ones. let storage_retry = retry_configs[&RequestCategory::Sea].clone(); let http_client = Arc::new( DatabricksHttpClient::with_revocation(http_client_config, retry_configs, revocation) diff --git a/src/statement/executed_async.rs b/src/statement/executed_async.rs index 05172770..a255f7c6 100644 --- a/src/statement/executed_async.rs +++ b/src/statement/executed_async.rs @@ -1342,7 +1342,6 @@ impl AsyncStatementCanceller { impl Drop for ExecutedAsyncStatement { fn drop(&mut self) { - // Its readers cannot report a transfer once it is gone, so stop it. self.cancel_volume(); if self.owning { self.owner_released.store(true, Ordering::Release); diff --git a/src/statement/mutable.rs b/src/statement/mutable.rs index 117dfe41..2c01f7ea 100644 --- a/src/statement/mutable.rs +++ b/src/statement/mutable.rs @@ -307,8 +307,8 @@ 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 execution. + /// The current execution's Volume transfer state, shared with + /// [`StatementCanceller`]. volume: VolumeSlot, } @@ -901,9 +901,6 @@ impl Statement { } } - /// Installs the Volume transfer state of the execution starting now, with - /// the spec's options, and stops the previous execution's transfer. The - /// execution takes the spec's `input_bytes`. fn begin_volume(&mut self) -> Arc { let options = self.spec.volume.as_mut().map(|options| { let input_bytes = options.input_bytes.take(); @@ -1144,7 +1141,6 @@ impl Drop for Statement { if let Some(valid) = self.last_valid.take() { valid.invalidate(); } - // An invalidated handle cannot report a transfer, so stop it. self.current_volume().cancel(); // `last_statement_id` is left as-is. By construction it is // only set immediately before `ExecutedStatement::new` diff --git a/src/statement/spec.rs b/src/statement/spec.rs index 912cc0d2..5ef473a6 100644 --- a/src/statement/spec.rs +++ b/src/statement/spec.rs @@ -234,9 +234,7 @@ pub struct StatementSpec { /// Result wire format. pub result_format: ResultFormat, - /// Volume transfer settings. With them, executing a Volume PUT, GET or - /// REMOVE also runs its storage transfer; see [`VolumeOptions`]. Their - /// `input_bytes` apply to the next execution only. + /// Volume transfer settings; see [`VolumeOptions`]. pub volume: Option, } @@ -435,8 +433,7 @@ impl StatementSpec { self } - /// Set the Volume transfer settings. `None` returns a Volume instruction - /// row without transferring. + /// Set the Volume transfer settings. `None` clears them. pub fn volume(&mut self, options: Option) -> &mut Self { self.volume = options; self diff --git a/src/volume.rs b/src/volume.rs index 50aaff9c..b483782c 100644 --- a/src/volume.rs +++ b/src/volume.rs @@ -56,15 +56,15 @@ const PIPE_READER_POLL: Duration = Duration::from_millis(50); /// readable. /// /// A PUT reads a regular file, or uploads [`input_bytes`](Self::input_bytes) -/// for `PUT '__input_stream__'`. A GET writes the object's content: a gzip -/// `Content-Encoding` is decoded, because it marks the stored bytes as a -/// compressed form of that content. A GET into a file replaces it only after -/// the download succeeds; a failure while copying into an existing file can -/// leave it partly written. An existing file whose folder refuses a temporary -/// file is written directly, so there a failed or cancelled download can leave -/// it truncated or partly written. On Unix a GET also writes into an existing pipe or -/// character device as the download arrives: a pipe waits for a reader up to -/// the idle limit, and a failure after the first bytes reach it is not retried. +/// for `PUT '__input_stream__'`. A GET writes the object's content, decoding +/// a gzip `Content-Encoding`. A GET into a file replaces it only after the +/// download succeeds; a failure while copying into an existing file can leave +/// it partly written. An existing file whose folder refuses a temporary file +/// is written directly, so there a failed or cancelled download can leave it +/// truncated or partly written. On Unix a GET also writes into an existing +/// pipe or character device as the download arrives: a pipe waits for a reader +/// up to the idle limit, and a failure after the first bytes reach it is not +/// retried. /// Cancelling the execution stops the transfer but cannot undo a PUT or REMOVE /// that storage already applied. A GET whose download is already being put in /// place finishes that step; if the call is dropped meanwhile, the step keeps @@ -82,7 +82,7 @@ pub struct VolumeOptions { pub remove_not_found_is_success: bool, /// The content `PUT '__input_stream__'` uploads. Without it, that PUT fails. /// On a [`StatementSpec`](crate::StatementSpec), the next execution takes - /// them, even one that fails or is not a Volume PUT. + /// it, even one that fails or is not a Volume PUT. pub input_bytes: Option, } @@ -123,7 +123,6 @@ pub(crate) struct Storage { retry: RetryConfig, idle_limit: Option, cancellation: CancellationToken, - /// The session's runtime, which runs every transfer. runtime: tokio::runtime::Handle, } @@ -146,8 +145,6 @@ impl Storage { } } - /// State for one execution's transfer. Without options, the execution - /// transfers nothing. pub(crate) fn transfer_state( self: &Arc, mut options: Option, @@ -165,7 +162,6 @@ impl Storage { }) } - /// Stops every transfer of the session. pub(crate) fn cancel_all(&self) { self.cancellation.cancel(); } @@ -179,7 +175,6 @@ impl Storage { } } -/// Stops a spawned transfer when the call driving it is dropped. struct AbortOnDrop(tokio::task::AbortHandle); impl Drop for AbortOnDrop { @@ -207,8 +202,7 @@ impl VolumeState { self.cancellation.cancel(); } - /// Runs the transfer `instruction` describes, once per execution. Without - /// options it does nothing. + /// Runs the transfer `instruction` describes, once per execution. pub(crate) async fn complete( self: &Arc, instruction: Result>, @@ -261,8 +255,6 @@ impl VolumeState { .clone() } - /// Prepares the local side and makes the storage request, returning the - /// local side for a GET to put its download in place. async fn transfer( &self, instruction: Instruction, @@ -378,9 +370,8 @@ impl VolumeState { )) } - /// Writes a GET response body to the download's temporary file, or to its - /// pipe or device. Bytes a pipe or device already took cannot be taken - /// back, so a failure after the first write is not retried. + /// Writes a GET response body. Bytes a pipe or device already took cannot + /// be taken back, so a failure after the first write is not retried. async fn receive( &self, mut response: Response, @@ -676,7 +667,6 @@ fn headers(column: &ArrayRef) -> Result { Ok(headers) } -/// The local side of a transfer, prepared before the first storage request. enum Local { Upload(Upload), Download(Download), @@ -684,7 +674,6 @@ enum Local { } enum Upload { - /// The validated file, read by offset for each request. File { file: Arc, length: u64, @@ -698,8 +687,6 @@ struct Download { name: String, } -/// A GET into a file downloads to `temp` first, so a failed download leaves -/// the file unchanged. enum Destination { /// Overwritten with a copy of `temp`, keeping the file itself. Without /// `temp`, because the folder refuses one, the download writes into it. @@ -904,7 +891,6 @@ impl Local { std::io::copy(&mut source, &mut file) .map(drop) .map_err(|e| { - // A failed GET leaves no new file behind. let _ = std::fs::remove_file(&destination); local_error(e) }) @@ -964,7 +950,6 @@ fn read_at(file: &std::fs::File, buf: &mut [u8], offset: u64) -> std::io::Result } } -/// The URL to follow when a response is a redirect the request should take. fn redirect_target( status: StatusCode, location: Option<&HeaderValue>, @@ -1024,9 +1009,6 @@ fn allowed_path(requested: &Path, roots: &[PathBuf]) -> Result { } } -/// A PUT needs the length a regular file has. A GET also writes into a pipe -/// or character device (see `is_stream`). A directory gets the error the OS -/// gives for reading or writing one. fn unsupported_file(metadata: &std::fs::Metadata, name: &str, allowed: &str) -> Error { let error = if metadata.is_dir() { #[cfg(unix)] @@ -1040,8 +1022,6 @@ fn unsupported_file(metadata: &std::fs::Metadata, name: &str, allowed: &str) -> local_error(error, name) } -/// A pipe or character device, which a GET writes as the download arrives. -/// Block devices and sockets are refused. #[cfg(unix)] fn is_stream(metadata: &std::fs::Metadata) -> bool { use std::os::unix::fs::FileTypeExt; @@ -1168,12 +1148,10 @@ mod tests { )) } - /// One execution's transfer state with `root` allowed. fn state(storage: &Arc, root: &Path) -> Arc { storage.transfer_state(Some(VolumeOptions::new(vec![root.to_owned()], false))) } - /// Runs one execution's transfer of `batch` with `root` allowed. async fn run(storage: &Arc, batch: RecordBatch, root: &Path) -> Result<()> { state(storage, root).complete(Ok(Some(batch))).await } @@ -1226,14 +1204,12 @@ mod tests { .await; } - /// Returns once `server` has received a request. async fn requested(server: &MockServer) { while server.received_requests().await.unwrap().is_empty() { tokio::task::yield_now().await; } } - /// True when the process can write where permissions say it cannot. #[cfg(unix)] fn privileged() -> bool { unsafe { libc::geteuid() == 0 } @@ -1735,7 +1711,6 @@ mod tests { let dir = tempfile::tempdir().unwrap(); let fifo = dir.path().join("fifo"); mkfifo(&fifo); - // The reader opens the pipe only after the download has started. let reader = async { requested(&server).await; let fifo = fifo.clone(); @@ -2058,7 +2033,6 @@ mod tests { )) .unwrap() }; - // Headers may also arrive as a JSON object, and a blank string means none. let json = Instruction::decode(&replace("headers", r#"{"x-test":"yes"}"#)).unwrap(); assert_eq!(json.headers["x-test"], "yes"); let blank = Instruction::decode(&replace("headers", " ")).unwrap(); From d4f6c3fd4ea6f7d7b44b4016ea5685954588cf3f Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Thu, 3 Dec 2026 00:53:18 +0000 Subject: [PATCH 34/43] ci: drop the Windows Volume test job Co-authored-by: Isaac Signed-off-by: Aakash Saravanan --- .github/workflows/pr-checks.yml | 26 -------------------------- 1 file changed, 26 deletions(-) diff --git a/.github/workflows/pr-checks.yml b/.github/workflows/pr-checks.yml index 5f94bef8..2e6848a6 100644 --- a/.github/workflows/pr-checks.yml +++ b/.github/workflows/pr-checks.yml @@ -131,32 +131,6 @@ 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-public-package-proxies - 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 tests - shell: pwsh - run: cargo test --locked --lib volume::tests - c-abi: name: C ABI smoke test runs-on: From 02664c85eb5df37aa55a65d843597396004b7e90 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Thu, 3 Dec 2026 00:53:18 +0000 Subject: [PATCH 35/43] refactor(volume): put new fields last and fix the transfer trigger doc is_volume_operation, SessionInner::storage and ExecutedAsyncStatement::volume move to the end of their structs. VolumeOptions now says a transfer runs for a result the server marks as a Volume operation. Drops four more comments that restate the code. Co-authored-by: Isaac Signed-off-by: Aakash Saravanan --- src/client/sea.rs | 2 +- src/reader/mod.rs | 4 ++-- src/reader/post_processor/mod.rs | 2 +- src/session.rs | 4 ++-- src/statement/executed_async.rs | 10 +++++----- src/statement/spec.rs | 2 +- src/types/sea.rs | 4 ++-- src/volume.rs | 14 +++++--------- 8 files changed, 19 insertions(+), 23 deletions(-) diff --git a/src/client/sea.rs b/src/client/sea.rs index c9348305..9c75d0ae 100644 --- a/src/client/sea.rs +++ b/src/client/sea.rs @@ -2441,7 +2441,6 @@ mod tests { error_details_json: None, }, manifest: Some(ResultManifest { - is_volume_operation: false, format: "ARROW_STREAM".to_string(), schema: ResultSchema { column_count: 0, @@ -2455,6 +2454,7 @@ mod tests { chunks: None, result_compression: Some("LZ4_FRAME".to_string()), is_native_metadata_result: None, + is_volume_operation: false, }), result: None, }; diff --git a/src/reader/mod.rs b/src/reader/mod.rs index 709ccaf3..25ab06f8 100644 --- a/src/reader/mod.rs +++ b/src/reader/mod.rs @@ -1472,7 +1472,6 @@ 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, @@ -1486,6 +1485,7 @@ mod tests { chunks: None, result_compression: None, is_native_metadata_result: None, + is_volume_operation: false, } } @@ -2151,7 +2151,6 @@ 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, @@ -2165,6 +2164,7 @@ mod tests { chunks: None, result_compression: None, is_native_metadata_result: None, + is_volume_operation: false, } } diff --git a/src/reader/post_processor/mod.rs b/src/reader/post_processor/mod.rs index cc3f80cf..b70de30d 100644 --- a/src/reader/post_processor/mod.rs +++ b/src/reader/post_processor/mod.rs @@ -469,7 +469,6 @@ 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, @@ -483,6 +482,7 @@ mod tests { chunks: None, result_compression: None, is_native_metadata_result: None, + is_volume_operation: false, } } diff --git a/src/session.rs b/src/session.rs index 13d36240..dd167829 100644 --- a/src/session.rs +++ b/src/session.rs @@ -97,7 +97,6 @@ pub(crate) struct SessionInner { /// behind the trait object; future variants slot in via /// `TransportMode`. transport: Arc, - storage: Arc, /// Server-issued session identifier. session_id: String, @@ -156,6 +155,7 @@ pub(crate) struct SessionInner { /// [`DefaultOpts::ignore_transactions`]. Multi-statement transactions are /// a Private Preview feature; setting this `false` opts in. ignore_transactions: bool, + storage: Arc, } impl SessionInner { @@ -500,7 +500,6 @@ impl Session { Ok(Session { inner: Arc::new(SessionInner { transport, - storage, session_id: session_info.session_id, config, runtime_handle, @@ -513,6 +512,7 @@ impl Session { // caller opts into explicit transactions via set_autocommit. autocommit: std::sync::atomic::AtomicBool::new(true), ignore_transactions: defaults.ignore_transactions, + storage, }), }) } diff --git a/src/statement/executed_async.rs b/src/statement/executed_async.rs index a255f7c6..935685da 100644 --- a/src/statement/executed_async.rs +++ b/src/statement/executed_async.rs @@ -224,7 +224,6 @@ pub struct ExecutedAsyncStatement { /// Take-once ownership avoids retaining raw payloads after reader construction. pending_result: std::sync::Mutex>, parameter_set_count: usize, - volume: Option>, statement_telemetry: StatementTelemetry, /// Set once result materialisation hands success finalization to /// the returned `ResultStream`. @@ -249,6 +248,7 @@ pub struct ExecutedAsyncStatement { /// firing a wasted cancel+close against an already-finished /// statement. terminal_observed: AtomicBool, + volume: Option>, } /// Map an [`ExecutionTimeout`] onto the async handle's two deadline @@ -338,13 +338,13 @@ impl ExecutedAsyncStatement { latest_status: Arc::new(std::sync::Mutex::new(initial_status)), pending_result: std::sync::Mutex::new(None), parameter_set_count: 0, - volume: None, statement_telemetry, result_stream_owns_success_telemetry: AtomicBool::new(false), client_deadline, poll_timeout_disabled, client_timeout_expired: AtomicBool::new(false), terminal_observed: AtomicBool::new(initial_terminal), + volume: None, } } @@ -416,13 +416,13 @@ impl ExecutedAsyncStatement { latest_status: Arc::new(std::sync::Mutex::new(initial_status)), pending_result: std::sync::Mutex::new(None), parameter_set_count: 0, - volume: None, statement_telemetry: StatementTelemetry::noop(), result_stream_owns_success_telemetry: AtomicBool::new(false), client_deadline: None, poll_timeout_disabled: false, client_timeout_expired: AtomicBool::new(false), terminal_observed: AtomicBool::new(initial_terminal), + volume: None, } } @@ -1280,8 +1280,8 @@ impl ExecutedAsyncStatement { /// Detached canceller for an in-flight async statement. /// /// Holds only the shared session handle, the statement id, the shared -/// [`ValidityFlag`] and the Volume transfer state — **not** the [`ExecutedAsyncStatement`] -/// itself — so a binding can fire a server-side cancel while the handle +/// [`ValidityFlag`] and the Volume transfer state, **not** the [`ExecutedAsyncStatement`] +/// itself, so a binding can fire a server-side cancel while the handle /// is borrowed elsewhere (e.g. parked inside a long-running /// [`ExecutedAsyncStatement::await_result`] that a binding-side lock is /// held across). Produced by [`ExecutedAsyncStatement::canceller`]. diff --git a/src/statement/spec.rs b/src/statement/spec.rs index 5ef473a6..28392979 100644 --- a/src/statement/spec.rs +++ b/src/statement/spec.rs @@ -433,7 +433,7 @@ impl StatementSpec { self } - /// Set the Volume transfer settings. `None` clears them. + /// Set the Volume transfer settings. pub fn volume(&mut self, options: Option) -> &mut Self { self.volume = options; self diff --git a/src/types/sea.rs b/src/types/sea.rs index 2dd34b85..5f303cd8 100644 --- a/src/types/sea.rs +++ b/src/types/sea.rs @@ -184,8 +184,6 @@ 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. @@ -213,6 +211,8 @@ pub struct ResultManifest { /// instead of the SQL statement's raw `SHOW` / information-schema shape. #[serde(default)] pub is_native_metadata_result: Option, + #[serde(default)] + pub is_volume_operation: bool, } /// Schema of the result set. diff --git a/src/volume.rs b/src/volume.rs index b483782c..3bcecdfe 100644 --- a/src/volume.rs +++ b/src/volume.rs @@ -15,8 +15,8 @@ //! Volume PUT, GET and REMOVE file transfers. //! //! The server answers these statements with one row holding a presigned -//! storage URL, request headers and a local path. This module makes the -//! storage request that row describes. +//! storage URL, request headers and, for PUT and GET, a local path. This +//! module makes the storage request that row describes. use crate::client::http::{DatabricksHttpClient, HttpClientConfig}; use crate::client::retry::{calculate_backoff, RequestType, RetryConfig, RetryStrategy}; @@ -49,9 +49,9 @@ const PIPE_READER_POLL: Duration = Duration::from_millis(50); /// Caller settings for Volume file transfers, set on /// [`StatementSpec::volume`](crate::StatementSpec::volume). /// -/// With options set, executing a statement the server answers with a Volume -/// PUT, GET or REMOVE instruction also runs that storage transfer, and the -/// execution fails if the transfer does. Without them, the execution returns +/// With options set, executing a statement whose result the server marks as a +/// Volume PUT, GET or REMOVE also runs its storage transfer, and the execution +/// fails if the transfer does. Without them, the execution returns /// the instruction row and moves no file. Either way the instruction row stays /// readable. /// @@ -115,7 +115,6 @@ impl std::fmt::Debug for VolumeOptions { } } -/// Storage access shared by a session's Volume transfers. pub(crate) struct Storage { config: HttpClientConfig, revocation: Option, @@ -560,7 +559,6 @@ impl VolumeState { } } - /// Runs one read or write, failing if it takes longer than the idle limit. async fn bounded(&self, work: impl std::future::Future>) -> Result { match self.storage.idle_limit { Some(limit) => tokio::time::timeout(limit, work) @@ -989,7 +987,6 @@ fn xml_value<'a>(body: &'a str, tag: &str) -> Option<&'a str> { (!value.contains(['<', '>'])).then_some(value) } -/// The requested path with symlinks resolved, if it is inside an allowed root. fn allowed_path(requested: &Path, roots: &[PathBuf]) -> Result { let name = requested.to_string_lossy(); let path = resolve(requested).map_err(|e| local_error(e, &name))?; @@ -1866,7 +1863,6 @@ mod tests { let error = run(&storage, put, dir.path()).await.unwrap_err(); assert_eq!(error.error_code.as_deref(), Some("VOLUME_LOCAL_FILE_ERROR")); } - // A folder that refuses a new file reports the OS code and the requested path. #[cfg(unix)] if !privileged() { use std::os::unix::fs::PermissionsExt; From c2eef3211520b24f17d7a3a15278543c759408ee Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Thu, 3 Dec 2026 01:38:01 +0000 Subject: [PATCH 36/43] refactor(volume): stop following storage redirects Presigned storage URLs name the exact regional endpoint, and S3 answers a wrong-region request with a 301 that has no Location, so the manual redirect loop never had a redirect to follow. Any 3xx now fails the transfer with its HTTP status. Removes the loop, redirect_target and three redirect tests; one test pins that a 303 to a PUT is not followed. Co-authored-by: Isaac Signed-off-by: Aakash Saravanan --- src/client/http.rs | 2 +- src/volume.rs | 199 +++++++++------------------------------------ 2 files changed, 40 insertions(+), 161 deletions(-) diff --git a/src/client/http.rs b/src/client/http.rs index bb432dc9..2a9a9a8c 100644 --- a/src/client/http.rs +++ b/src/client/http.rs @@ -846,7 +846,7 @@ impl DatabricksHttpClient { } /// Build the client for Volume storage requests: the session's connection - /// settings without a total deadline, and redirects left to the caller. + /// settings without a total deadline or redirect following. pub(crate) fn storage_client( config: &HttpClientConfig, revocation: Option, diff --git a/src/volume.rs b/src/volume.rs index 3bcecdfe..16f7b132 100644 --- a/src/volume.rs +++ b/src/volume.rs @@ -25,10 +25,7 @@ use arrow_array::cast::AsArray; use arrow_array::{Array, ArrayRef, RecordBatch}; use arrow_schema::DataType; use futures::{Stream, StreamExt, TryStreamExt}; -use reqwest::header::{ - HeaderMap, HeaderName, HeaderValue, AUTHORIZATION, CONTENT_LENGTH, COOKIE, LOCATION, - PROXY_AUTHORIZATION, RETRY_AFTER, -}; +use reqwest::header::{HeaderMap, HeaderName, HeaderValue, CONTENT_LENGTH, RETRY_AFTER}; use reqwest::{Client, Method, Response, StatusCode, Url}; use std::io::{Read, Seek}; use std::path::{Path, PathBuf}; @@ -40,7 +37,6 @@ use tokio::sync::{watch, OnceCell}; use tokio_util::bytes::Bytes; use tokio_util::sync::CancellationToken; -const MAX_REDIRECTS: usize = 10; const ERROR_BODY_LIMIT: usize = 4096; const UPLOAD_CHUNK: usize = 256 * 1024; #[cfg(unix)] @@ -300,8 +296,8 @@ impl VolumeState { } } - /// One storage request, following redirects. A failure carries the - /// response's `Retry-After` value. + /// One storage request. A failure carries the response's `Retry-After` + /// value. async fn attempt( &self, client: &Client, @@ -311,62 +307,39 @@ impl VolumeState { strategy: &RetryStrategy, ) -> std::result::Result<(), (Error, Option)> { let method = local.method(); - let mut url = Url::parse(&instruction.url) + let url = Url::parse(&instruction.url) .map_err(|_| (invalid("Invalid Volume storage URL"), None))?; + let (progress, mut progressed) = watch::channel(()); let mut headers = instruction.headers.clone(); - for _ in 0..=MAX_REDIRECTS { - let (progress, mut progressed) = watch::channel(()); - let mut request_headers = headers.clone(); - let mut body = None; - if let Some((chunks, length)) = local.upload() { - request_headers.insert(CONTENT_LENGTH, length.into()); - body = Some(reqwest::Body::wrap_stream(chunks.inspect_ok(move |_| { - progress.send_replace(()); - }))); - } - let mut request = client - .request(method.clone(), url.clone()) - .headers(request_headers); - if let Some(body) = body { - request = request.body(body); - } - let response = self - .idle_bounded(&mut progressed, async { - request.send().await.map_err(|e| storage_error(e, strategy)) - }) + let mut body = None; + if let Some((chunks, length)) = local.upload() { + headers.insert(CONTENT_LENGTH, length.into()); + body = Some(reqwest::Body::wrap_stream(chunks.inspect_ok(move |_| { + progress.send_replace(()); + }))); + } + let mut request = client.request(method.clone(), url).headers(headers); + if let Some(body) = body { + request = request.body(body); + } + let response = self + .idle_bounded(&mut progressed, async { + request.send().await.map_err(|e| storage_error(e, strategy)) + }) + .await + .map_err(|e| (e, None))?; + let status = response.status(); + if status.is_success() + || (method == Method::DELETE + && status == StatusCode::NOT_FOUND + && options.remove_not_found_is_success) + { + return self + .receive(response, local, strategy) .await - .map_err(|e| (e, None))?; - let location = response.headers().get(LOCATION); - if let Some(next) = redirect_target(response.status(), location, &url, &method) - .map_err(|e| (e, None))? - { - if (next.scheme(), next.host_str(), next.port_or_known_default()) - != (url.scheme(), url.host_str(), url.port_or_known_default()) - { - for name in [AUTHORIZATION, COOKIE, PROXY_AUTHORIZATION] { - headers.remove(name); - } - } - url = next; - continue; - } - let status = response.status(); - if status.is_success() - || (method == Method::DELETE - && status == StatusCode::NOT_FOUND - && options.remove_not_found_is_success) - { - return self - .receive(response, local, strategy) - .await - .map_err(|e| (e, None)); - } - return Err(self.http_failure(response, strategy).await); + .map_err(|e| (e, None)); } - Err(( - network("Volume storage request was redirected too many times").with_retryable(false), - None, - )) + Err(self.http_failure(response, strategy).await) } /// Writes a GET response body. Bytes a pipe or device already took cannot @@ -948,39 +921,6 @@ fn read_at(file: &std::fs::File, buf: &mut [u8], offset: u64) -> std::io::Result } } -fn redirect_target( - status: StatusCode, - location: Option<&HeaderValue>, - url: &Url, - method: &Method, -) -> Result> { - let follow = match status { - StatusCode::MOVED_PERMANENTLY - | StatusCode::FOUND - | StatusCode::TEMPORARY_REDIRECT - | StatusCode::PERMANENT_REDIRECT => true, - // A 303 asks for a GET, which would not upload or delete anything. - StatusCode::SEE_OTHER => method == Method::GET, - _ => false, - }; - let Some(location) = location.filter(|_| follow) else { - return Ok(None); - }; - let next = location - .to_str() - .ok() - .and_then(|location| url.join(location).ok()) - .ok_or_else(|| { - network("Volume storage redirect has an invalid location").with_retryable(false) - })?; - if url.scheme() == "https" && next.scheme() != "https" { - return Err( - network("Volume storage redirect cannot downgrade HTTPS to HTTP").with_retryable(false), - ); - } - Ok(Some(next)) -} - fn xml_value<'a>(body: &'a str, tag: &str) -> Option<&'a str> { let (_, rest) = body.split_once(&format!("<{tag}>"))?; let (value, _) = rest.split_once(&format!(""))?; @@ -1432,64 +1372,17 @@ mod tests { } #[tokio::test] - async fn redirects_keep_the_method_and_body_except_see_other_for_writes() { + async fn a_redirect_fails_without_being_followed() { let server = MockServer::start().await; - for status in [301, 307] { - Mock::given(method("PUT")) - .and(path(format!("/put-{status}"))) - .respond_with(ResponseTemplate::new(status).insert_header("location", "/stored")) - .mount(&server) - .await; - } - Mock::given(method("PUT")) - .and(path("/stored")) - .and(body_bytes(b"payload".to_vec())) - .respond_with(ResponseTemplate::new(200)) - .expect(2) - .mount(&server) - .await; - Mock::given(path("/see-other")) - .respond_with(ResponseTemplate::new(303).insert_header("location", "/object")) - .mount(&server) - .await; - let get = ResponseTemplate::new(200).set_body_string("redirected"); - mount(&server, "GET", "/object", get).await; + let see_other = ResponseTemplate::new(303).insert_header("location", "/object"); + mount(&server, "PUT", "/", see_other).await; let dir = tempfile::tempdir().unwrap(); let source = dir.path().join("source"); std::fs::write(&source, b"payload").unwrap(); - let destination = dir.path().join("destination"); - let storage = storage(0, None); - for status in [301, 307] { - let put = instruction("PUT", &format!("{}/put-{status}", server.uri()), &source); - run(&storage, put, dir.path()).await.unwrap(); - } - let see_other = format!("{}/see-other", server.uri()); - let get = instruction("GET", &see_other, &destination); - run(&storage, get, dir.path()).await.unwrap(); - assert_eq!(std::fs::read(&destination).unwrap(), b"redirected"); - let put = instruction("PUT", &see_other, &source); - let error = run(&storage, put, dir.path()).await.unwrap_err(); + let put = instruction("PUT", &server.uri(), &source); + let error = run(&storage(0, None), put, dir.path()).await.unwrap_err(); assert_eq!(error.http_status, Some(303)); - } - - #[tokio::test] - async fn a_cross_origin_redirect_drops_credentials() { - let server = MockServer::start().await; - let other = MockServer::start().await; - Mock::given(wiremock::matchers::header_exists("authorization")) - .respond_with(ResponseTemplate::new(403)) - .mount(&other) - .await; - mount(&other, "PUT", "/object", ResponseTemplate::new(200)).await; - let moved = - ResponseTemplate::new(307).insert_header("location", format!("{}/object", other.uri())); - mount(&server, "PUT", "/", moved).await; - let dir = tempfile::tempdir().unwrap(); - let source = dir.path().join("source"); - std::fs::write(&source, b"payload").unwrap(); - let headers = [("Authorization", "secret")]; - let put = instruction_with_headers("PUT", &server.uri(), Some(&source), &headers); - run(&storage(0, None), put, dir.path()).await.unwrap(); + assert_eq!(server.received_requests().await.unwrap().len(), 1); } #[tokio::test] @@ -1588,20 +1481,6 @@ mod tests { assert!(!error.retryable); } - #[test] - fn redirects_cannot_downgrade_https_to_http() { - let location = HeaderValue::from_static("http://storage/object"); - let error = redirect_target( - StatusCode::FOUND, - Some(&location), - &Url::parse("https://storage/object").unwrap(), - &Method::GET, - ) - .unwrap_err(); - assert!(error.message.contains("downgrade")); - assert!(!error.retryable); - } - #[test] fn local_paths_must_resolve_inside_an_allowed_root() { let dir = tempfile::tempdir().unwrap(); @@ -1992,7 +1871,7 @@ mod tests { let bytes = Upload::Bytes(payload.clone().into()); let joined = |chunks: &[Bytes]| chunks.iter().flat_map(|c| c.to_vec()).collect::>(); for upload in [Local::Upload(file), Local::Upload(bytes)] { - // A retry or redirect starts a new read while an earlier one may still be open. + // A retry starts a new read while an earlier one may still be open. let (mut first, length) = upload.upload().unwrap(); let head = first.try_next().await.unwrap().unwrap(); let (second, _) = upload.upload().unwrap(); From 6df247eac28b702f824e1483c216b8ef986f8da8 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Thu, 3 Dec 2026 01:58:58 +0000 Subject: [PATCH 37/43] refactor(volume): create a new GET destination directly A GET into a new file now creates the file right after the path check and writes into it, and removes it unless the download completes. A cancel waits for the aborted transfer to drop, so the file is gone before the call reports Cancelled. This replaces the temporary file, the no-replace rename, its copy fallback, the file mode and name-prefix handling and the second path check. Co-authored-by: Isaac Signed-off-by: Aakash Saravanan --- src/volume.rs | 163 +++++++++++++------------------------------------- 1 file changed, 40 insertions(+), 123 deletions(-) diff --git a/src/volume.rs b/src/volume.rs index 16f7b132..0b4ff0d2 100644 --- a/src/volume.rs +++ b/src/volume.rs @@ -53,19 +53,21 @@ const PIPE_READER_POLL: Duration = Duration::from_millis(50); /// /// A PUT reads a regular file, or uploads [`input_bytes`](Self::input_bytes) /// for `PUT '__input_stream__'`. A GET writes the object's content, decoding -/// a gzip `Content-Encoding`. A GET into a file replaces it only after the -/// download succeeds; a failure while copying into an existing file can leave +/// a gzip `Content-Encoding`. A GET into a new file removes it if the download +/// fails or is cancelled. A GET into an existing file replaces its content +/// only after the download succeeds; a failure while copying into it can leave /// it partly written. An existing file whose folder refuses a temporary file /// is written directly, so there a failed or cancelled download can leave it /// truncated or partly written. On Unix a GET also writes into an existing -/// pipe or character device as the download arrives: a pipe waits for a reader -/// up to the idle limit, and a failure after the first bytes reach it is not -/// retried. +/// pipe or character device as the download arrives: a pipe waits for a +/// reader up to the idle limit, and a failure after the first bytes reach it +/// is not retried. +/// /// Cancelling the execution stops the transfer but cannot undo a PUT or REMOVE -/// that storage already applied. A GET whose download is already being put in -/// place finishes that step; if the call is dropped meanwhile, the step keeps -/// running after the call returns, and later calls for that execution report -/// `Cancelled`. +/// that storage already applied. A GET whose download is already being copied +/// into an existing file finishes that copy; if the call is dropped meanwhile, +/// the copy keeps running after the call returns, and later calls for that +/// execution report `Cancelled`. #[non_exhaustive] #[derive(Clone, Default)] pub struct VolumeOptions { @@ -230,20 +232,26 @@ impl VolumeState { // block SIGPIPE, a pipe whose reader exits fails the write instead of // killing the host. let (state, options) = (Arc::clone(self), options.clone()); - let task = self + let mut task = self .storage .runtime .spawn(async move { state.transfer(instruction, &options, input_bytes).await }); let _abort = AbortOnDrop(task.abort_handle()); let local = tokio::select! { biased; - _ = self.cancellation.cancelled() => return Err(cancelled()), - joined = task => joined.map_err(|e| { + _ = self.cancellation.cancelled() => { + // Waiting for the aborted transfer to drop removes a new GET + // destination before the call returns. + task.abort(); + let _ = (&mut task).await; + return Err(cancelled()); + } + joined = &mut task => joined.map_err(|e| { Error::internal().message(format!("Volume transfer failed: {e}")) })??, }; - // Putting a download in place cannot be stopped midway, so it runs to the - // end and the outcome reports the file it left. + // Copying a download into an existing file cannot be stopped midway, so + // it runs to the end and the outcome reports the file it left. local.publish().await }) .await @@ -363,7 +371,7 @@ impl VolumeState { temp: Some(target), .. } | Destination::Existing { file: target, .. } - | Destination::New { temp: target, .. } => { + | Destination::New { file: target, .. } => { temp_file = tokio::fs::File::from_std(target.try_clone().map_err(local_error)?); temp_file.set_len(0).await.map_err(local_error)?; temp_file.rewind().await.map_err(local_error)?; @@ -665,13 +673,10 @@ enum Destination { file: std::fs::File, temp: Option, }, - /// `temp`, renamed into place after its path is checked against the - /// allowed roots again. + /// Created for this download, and removed unless the download completes. New { - temp: std::fs::File, + file: std::fs::File, path: tempfile::TempPath, - requested: PathBuf, - roots: Vec, }, /// A pipe or character device, written as the download arrives. It is /// opened once, for the first response, and kept open across retries so @@ -766,25 +771,14 @@ async fn prepare( )) } Err(error) if error.kind() == std::io::ErrorKind::NotFound => { - // Opened here rather than by `tempfile`, which hides the OS code of - // a failure. A fixed prefix keeps the name within the OS limit. - let (temp, path) = tempfile::Builder::new() - .prefix(".volume-get-") - .make_in(parent, |path| { - let mut file = std::fs::OpenOptions::new(); - file.write(true).create_new(true); - // The mode a newly created file gets, rather than owner-only. - #[cfg(unix)] - std::os::unix::fs::OpenOptionsExt::mode(&mut file, 0o666); - file.open(path) - }) - .map_err(local_error)? - .into_parts(); + let file = std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(&path) + .map_err(local_error)?; Destination::New { - temp, - path, - requested, - roots, + file, + path: tempfile::TempPath::try_from_path(path).map_err(local_error)?, } } Err(error) => return Err(local_error(error)), @@ -840,34 +834,8 @@ impl Local { file.set_len(length).map_err(local_error) } Destination::Existing { temp: None, .. } => Ok(()), - Destination::New { - temp, - path, - requested, - roots, - } => { - drop(temp); - let destination = allowed_path(&requested, &roots)?; - match path.persist_noclobber(&destination) { - // Some filesystems support neither a rename that keeps an existing - // file nor hard links, so the download is copied instead. - Err(error) if error.error.kind() != std::io::ErrorKind::AlreadyExists => { - let mut source = - std::fs::File::open(&error.path).map_err(local_error)?; - let mut file = std::fs::OpenOptions::new() - .write(true) - .create_new(true) - .open(&destination) - .map_err(local_error)?; - std::io::copy(&mut source, &mut file) - .map(drop) - .map_err(|e| { - let _ = std::fs::remove_file(&destination); - local_error(e) - }) - } - result => result.map_err(|e| local_error(e.error)), - } + Destination::New { path, .. } => { + path.keep().map(drop).map_err(|e| local_error(e.error)) } #[cfg(unix)] Destination::Stream { .. } => Ok(()), @@ -1231,31 +1199,13 @@ mod tests { } #[tokio::test] - async fn a_get_into_a_new_file_leaves_only_that_file() { + async fn a_failed_get_into_a_new_file_leaves_no_file() { let server = MockServer::start().await; - let get = ResponseTemplate::new(200).set_body_string("content"); - mount(&server, "GET", "/", get).await; + mount(&server, "GET", "/", ResponseTemplate::new(500)).await; let dir = tempfile::tempdir().unwrap(); - let created = dir.path().join("created"); - std::fs::write(&created, b"").unwrap(); - // On Unix, a name near the 255-byte limit still leaves room for the - // temporary file's. - let new = dir.path().join(if cfg!(unix) { - "n".repeat(250) - } else { - "new".into() - }); - let get = instruction("GET", &server.uri(), &new); - run(&storage(0, None), get, dir.path()).await.unwrap(); - assert_eq!(std::fs::read(&new).unwrap(), b"content"); - assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 2); - // It has the mode any newly created file gets, not the temporary file's. - #[cfg(unix)] - { - use std::os::unix::fs::PermissionsExt; - let mode = |path: &Path| std::fs::metadata(path).unwrap().permissions().mode(); - assert_eq!(mode(&new), mode(&created)); - } + let get = instruction("GET", &server.uri(), &dir.path().join("new")); + run(&storage(0, None), get, dir.path()).await.unwrap_err(); + assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 0); } #[tokio::test] @@ -1517,38 +1467,6 @@ mod tests { } } - #[tokio::test] - #[cfg(unix)] - async fn a_new_destination_is_checked_again_when_it_is_created() { - let server = MockServer::start().await; - Mock::given(method("GET")) - .respond_with( - ResponseTemplate::new(200) - .set_body_string("data") - .set_delay(Duration::from_millis(300)), - ) - .mount(&server) - .await; - let dir = tempfile::tempdir().unwrap(); - let root = dir.path().join("root"); - let outside = dir.path().join("outside"); - std::fs::create_dir_all(root.join("sub")).unwrap(); - std::fs::create_dir(&outside).unwrap(); - let get = instruction("GET", &server.uri(), &root.join("sub/file")); - let swap = async { - requested(&server).await; - std::fs::rename(root.join("sub"), dir.path().join("moved")).unwrap(); - std::os::unix::fs::symlink(&outside, root.join("sub")).unwrap(); - }; - let storage = storage(0, None); - let (result, ()) = tokio::join!(run(&storage, get, &root), swap); - assert_eq!( - result.unwrap_err().error_code.as_deref(), - Some("VOLUME_PATH_NOT_ALLOWED") - ); - assert!(!outside.join("file").exists()); - } - #[tokio::test] #[cfg(target_os = "linux")] async fn put_sources_without_a_usable_size_upload_their_content() { @@ -1752,7 +1670,6 @@ mod tests { let get = instruction("GET", &url, &new); let error = run(&storage, get, dir.path()).await.unwrap_err(); std::fs::set_permissions(&locked, PermissionsExt::from_mode(0o755)).unwrap(); - assert!(!error.message.contains(".volume-get-"), "{}", error.message); let details = error.local_error.unwrap(); assert_eq!(details.raw_os_error, Some(libc::EACCES)); assert_eq!(details.path, new.to_str().unwrap()); @@ -1793,7 +1710,7 @@ mod tests { let get = ResponseTemplate::new(200).set_body_bytes(body.clone()); mount(&server, "GET", "/", get).await; let dir = tempfile::tempdir().unwrap(); - // An existing empty file changes length only once the download is put in place. + // An existing empty file changes length only once the download is copied into it. let destination = dir.path().join("destination"); std::fs::write(&destination, b"").unwrap(); let state = state(&storage(0, None), dir.path()); From 055e0ec67814742ce3a6a9129355bde345cece6f Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Thu, 3 Dec 2026 01:46:56 +0000 Subject: [PATCH 38/43] refactor(volume): use request_timeout as the transfer idle limit Removes HttpConfig::storage_read_timeout. A transfer now fails after the session's request_timeout passes without progress, so the setting every binding already maps its socket timeout to also bounds transfers, with no separate knob. Co-authored-by: Isaac Signed-off-by: Aakash Saravanan --- CONNECTION_PARAMETERS.md | 3 +-- NEXT_CHANGELOG.md | 6 +++--- src/config.rs | 8 ++------ src/session.rs | 2 +- src/volume.rs | 4 ++++ tests/v0_volume_wiremock.rs | 13 ++++++++++--- 6 files changed, 21 insertions(+), 15 deletions(-) diff --git a/CONNECTION_PARAMETERS.md b/CONNECTION_PARAMETERS.md index 84a922c6..645c73e8 100644 --- a/CONNECTION_PARAMETERS.md +++ b/CONNECTION_PARAMETERS.md @@ -167,8 +167,7 @@ until implemented) and `External` (a caller-supplied `TokenProvider`). | Field | Description | Default | |-------|-------------|---------| -| `request_timeout` | Per-request timeout (connect + body). Does not apply to Volume file transfers. | `120s` | -| `storage_read_timeout` | Volume file transfers fail after this long without progress; `None` or zero sets no limit. | `Some(900s)` | +| `request_timeout` | Per-request timeout (connect + body). For Volume file transfers, an idle limit: a transfer fails after this long without progress. | `120s` | | `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/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index 6551a879..bf48c6c5 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -25,9 +25,9 @@ changes go in their respective binding's NEXT_CHANGELOG. - Volume `PUT`, `GET` and `REMOVE`: with `StatementSpec::volume` set, executing a statement the server marks as a Volume operation also runs its file transfer. Local paths, with symlinks resolved, must be inside the caller's - allowed directories. `HttpConfig::storage_read_timeout` limits how long a transfer - may go without progress (15 minutes by default). On Unix a GET can also - write into an existing pipe or character device as the download arrives. + allowed directories. A transfer fails after `HttpConfig::request_timeout` + without progress. On Unix a GET can also write into an existing pipe or + character device as the download arrives. ### Changed diff --git a/src/config.rs b/src/config.rs index 21424666..06606f84 100644 --- a/src/config.rs +++ b/src/config.rs @@ -941,13 +941,10 @@ 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. + /// For a Volume file transfer it is an idle limit instead: the transfer + /// fails after this long without progress. pub request_timeout: Duration, - /// Idle limit for Volume file transfers, which `request_timeout` does not - /// bound: a transfer fails after this long without progress. `None` or - /// zero sets no limit. - pub storage_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, @@ -1027,7 +1024,6 @@ impl Default for HttpConfig { Self { sea_response_compression_enabled: false, request_timeout: Duration::from_secs(120), - storage_read_timeout: Some(Duration::from_secs(900)), 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 dd167829..ccfb962c 100644 --- a/src/session.rs +++ b/src/session.rs @@ -396,7 +396,7 @@ impl Session { http_client.config().clone(), http_client.revocation(), storage_retry, - config.http.storage_read_timeout, + Some(config.http.request_timeout), runtime_handle.clone(), )); diff --git a/src/volume.rs b/src/volume.rs index 0b4ff0d2..45e11bd8 100644 --- a/src/volume.rs +++ b/src/volume.rs @@ -63,6 +63,10 @@ const PIPE_READER_POLL: Duration = Duration::from_millis(50); /// reader up to the idle limit, and a failure after the first bytes reach it /// is not retried. /// +/// The idle limit is the session's +/// [`HttpConfig::request_timeout`](crate::HttpConfig::request_timeout): a +/// transfer fails after that long without progress. +/// /// Cancelling the execution stops the transfer but cannot undo a PUT or REMOVE /// that storage already applied. A GET whose download is already being copied /// into an existing file finishes that copy; if the call is dropped meanwhile, diff --git a/tests/v0_volume_wiremock.rs b/tests/v0_volume_wiremock.rs index fdcec66b..67e44e7b 100644 --- a/tests/v0_volume_wiremock.rs +++ b/tests/v0_volume_wiremock.rs @@ -361,7 +361,7 @@ async fn cancellers_and_session_close_stop_a_running_transfer() { } #[tokio::test] -async fn storage_transfer_is_not_bound_by_the_sql_request_timeout() { +async fn the_sql_request_timeout_is_the_transfer_idle_limit() { let server = MockServer::start().await; let dir = tempfile::tempdir().unwrap(); let destination = dir.path().join("download"); @@ -369,9 +369,16 @@ async fn storage_transfer_is_not_bound_by_the_sql_request_timeout() { mount_volume_result(&server, "GET", destination.to_str().unwrap(), true).await; let mut http = HttpConfig::default(); http.request_timeout = Duration::from_secs(1); + http.retry_max_retries = 0; let session = session(&server, http).await; let mut statement = session.statement(); statement.spec().sql("GET").volume(options(dir.path())); - statement.execute().await.unwrap(); - assert_eq!(std::fs::read(&destination).unwrap(), b"data"); + let Err(error) = statement.execute().await else { + panic!("a stalled transfer succeeded"); + }; + assert!( + error.message.contains("made no progress"), + "{}", + error.message + ); } From f399c3f5b13fef1ede656a05fc724294de633de5 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Thu, 3 Dec 2026 01:47:52 +0000 Subject: [PATCH 39/43] refactor(volume): upload a regular file by its reported length Drops the whole read for files that report size 0, which only mattered for procfs sources. Co-authored-by: Isaac Signed-off-by: Aakash Saravanan --- src/volume.rs | 38 +++++++------------------------------- 1 file changed, 7 insertions(+), 31 deletions(-) diff --git a/src/volume.rs b/src/volume.rs index 45e11bd8..ede68959 100644 --- a/src/volume.rs +++ b/src/volume.rs @@ -27,7 +27,7 @@ use arrow_schema::DataType; use futures::{Stream, StreamExt, TryStreamExt}; use reqwest::header::{HeaderMap, HeaderName, HeaderValue, CONTENT_LENGTH, RETRY_AFTER}; use reqwest::{Client, Method, Response, StatusCode, Url}; -use std::io::{Read, Seek}; +use std::io::Seek; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; @@ -715,18 +715,12 @@ async fn prepare( "A Volume PUT reads regular files only", )); } - let mut file = std::fs::File::open(&path).map_err(local_error)?; - if metadata.len() > 0 { - return Ok(Local::Upload(Upload::File { - file: Arc::new(file), - length: metadata.len(), - name, - })); - } - // Files such as procfs entries report no size. - let mut bytes = Vec::new(); - file.read_to_end(&mut bytes).map_err(local_error)?; - Ok(Local::Upload(Upload::Bytes(bytes.into()))) + let file = std::fs::File::open(&path).map_err(local_error)?; + Ok(Local::Upload(Upload::File { + file: Arc::new(file), + length: metadata.len(), + name, + })) } Operation::Get(requested) => { let path = allowed_path(&requested, &roots)?; @@ -1471,24 +1465,6 @@ mod tests { } } - #[tokio::test] - #[cfg(target_os = "linux")] - async fn put_sources_without_a_usable_size_upload_their_content() { - let server = MockServer::start().await; - Mock::given(method("PUT")) - .respond_with(ResponseTemplate::new(200)) - .mount(&server) - .await; - // procfs files report size 0 but have content. - let source = Path::new("/proc/self/cmdline"); - let put = instruction("PUT", &server.uri(), source); - run(&storage(0, None), put, Path::new("/proc")) - .await - .unwrap(); - let requests = server.received_requests().await.unwrap(); - assert_eq!(requests[0].body, std::fs::read(source).unwrap()); - } - #[cfg(unix)] fn mkfifo(path: &Path) { assert!(std::process::Command::new("mkfifo") From f66947ed0b67a164d5f8779c7b7533e5b0164623 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Thu, 3 Dec 2026 02:15:40 +0000 Subject: [PATCH 40/43] docs(kernel_error): say a struct literal must set a new Error field Co-authored-by: Isaac Signed-off-by: Aakash Saravanan --- src/kernel_error.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/kernel_error.rs b/src/kernel_error.rs index b7be386b..38426840 100644 --- a/src/kernel_error.rs +++ b/src/kernel_error.rs @@ -170,9 +170,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). +/// A new field does not break code that uses these setters, but a struct +/// literal must set every field. The type is not `#[non_exhaustive]` +/// because the marker would block the pattern-matching wrappers want. #[derive(Debug, Clone)] pub struct Error { pub code: ErrorCode, From 4eaeb615a166c1e637f884e191418327b37dc411 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Thu, 3 Dec 2026 08:19:57 +0000 Subject: [PATCH 41/43] fix(deps): require tempfile 3.27 for TempPath::try_from_path TempPath::try_from_path first shipped in tempfile 3.27.0, so a consumer whose lockfile resolves an older 3.x failed to build with "tempfile = 3". Co-authored-by: Isaac Signed-off-by: Aakash Saravanan --- Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index b9bfeba0..334bd5e9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -106,7 +106,7 @@ lz4_flex = "0.14" rand = "0.10" # Temporary files for Volume GET downloads -tempfile = "3" +tempfile = "3.27" # Concurrent data structures dashmap = "6" From c5e2b30eeabca78e569074600aac3a627ca6bca4 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Thu, 3 Dec 2026 08:20:23 +0000 Subject: [PATCH 42/43] fix(volume): stop a shared transfer only when its owner gives up The transfer ran inside whichever call started it, so dropping a reader's call aborted it, and the owner's await_result then reported Cancelled. The spawned task now owns the transfer and its publish, and every call waits on its shared outcome. Cancelling the execution stops it, and so does dropping a call from the owning handle, so Ctrl-C and timeouts still stop a sync execute. Dropping an AsyncStatementReader call leaves it running. Co-authored-by: Isaac Signed-off-by: Aakash Saravanan --- src/result_stream.rs | 5 +- src/statement/executed_async.rs | 5 +- src/statement/mutable.rs | 4 +- src/telemetry/statement.rs | 2 +- src/volume.rs | 165 ++++++++++++++++---------------- tests/v0_volume_wiremock.rs | 20 ++++ 6 files changed, 114 insertions(+), 87 deletions(-) diff --git a/src/result_stream.rs b/src/result_stream.rs index 02620f77..7c6e01ff 100644 --- a/src/result_stream.rs +++ b/src/result_stream.rs @@ -647,11 +647,12 @@ impl ResultStream { /// Records whether the server marked this result as a Volume PUT, GET or /// REMOVE and, if so, runs the transfer `volume` holds before any row is - /// read. + /// read. Dropping an `owner` call cancels the transfer. pub(crate) async fn complete_volume( &mut self, manifest: Option<&crate::types::sea::ResultManifest>, volume: Option<&Arc>, + owner: bool, ) -> Result<()> { self.is_volume_operation = manifest.is_some_and(|manifest| manifest.is_volume_operation); let Some(volume) = volume.filter(|_| self.is_volume_operation) else { @@ -661,7 +662,7 @@ impl ResultStream { .peek_first_batch() .await .map(|batch| batch.map(|ResultBatch::Arrow(batch)| batch.clone())); - let result = volume.complete(instruction).await; + let result = volume.complete(instruction, owner).await; if let Err(error) = &result { self.finalize_telemetry(Some(error)); } diff --git a/src/statement/executed_async.rs b/src/statement/executed_async.rs index 935685da..9173f2f7 100644 --- a/src/statement/executed_async.rs +++ b/src/statement/executed_async.rs @@ -1022,7 +1022,7 @@ impl ExecutedAsyncStatement { let mut stream = ResultStream::from_reader(result.reader).await?; stream.attach_telemetry(self.statement_telemetry.clone()); stream - .complete_volume(result.manifest.as_ref(), self.volume.as_ref()) + .complete_volume(result.manifest.as_ref(), self.volume.as_ref(), self.owning) .await?; // SEA carries no row count on the async status either; for a // DML the count rides in the result set. Derive it once @@ -1096,7 +1096,8 @@ impl AsyncStatementReader { /// Poll until terminal and return a fresh result stream. /// /// The session's polling timeout applies to this read. Timing out or - /// dropping the future leaves the server statement running. + /// dropping the future leaves the server statement and any Volume transfer + /// running. pub async fn await_result(&self) -> Result { self.inner.await_result().await } diff --git a/src/statement/mutable.rs b/src/statement/mutable.rs index 2c01f7ea..8216f5f9 100644 --- a/src/statement/mutable.rs +++ b/src/statement/mutable.rs @@ -482,7 +482,7 @@ impl Statement { let mut result_stream = ResultStream::from_reader(result.reader).await?; result_stream.attach_telemetry(telemetry_for_body.clone()); result_stream - .complete_volume(result.manifest.as_ref(), Some(&volume)) + .complete_volume(result.manifest.as_ref(), Some(&volume), true) .await?; // 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 @@ -733,7 +733,7 @@ impl Statement { let mut result_stream = ResultStream::from_reader(result.reader).await?; result_stream.attach_telemetry(telemetry_for_body.clone()); result_stream - .complete_volume(result.manifest.as_ref(), Some(&volume)) + .complete_volume(result.manifest.as_ref(), Some(&volume), true) .await?; let mut status = result.status; let parameter_set_count = exec_params.parameter_sets.len(); diff --git a/src/telemetry/statement.rs b/src/telemetry/statement.rs index 80f65acd..51b0f612 100644 --- a/src/telemetry/statement.rs +++ b/src/telemetry/statement.rs @@ -405,7 +405,7 @@ mod tests { )); let volume = storage.transfer_state(Some(Default::default())); let error = stream - .complete_volume(Some(&manifest), Some(&volume)) + .complete_volume(Some(&manifest), Some(&volume), true) .await .unwrap_err(); diff --git a/src/volume.rs b/src/volume.rs index ede68959..49fcf7cd 100644 --- a/src/volume.rs +++ b/src/volume.rs @@ -24,13 +24,13 @@ use crate::kernel_error::{Error, LocalFileError, Result}; use arrow_array::cast::AsArray; use arrow_array::{Array, ArrayRef, RecordBatch}; use arrow_schema::DataType; -use futures::{Stream, StreamExt, TryStreamExt}; +use futures::future::{BoxFuture, Shared}; +use futures::{FutureExt, Stream, StreamExt, TryStreamExt}; use reqwest::header::{HeaderMap, HeaderName, HeaderValue, CONTENT_LENGTH, RETRY_AFTER}; use reqwest::{Client, Method, Response, StatusCode, Url}; use std::io::Seek; use std::path::{Path, PathBuf}; -use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::Arc; +use std::sync::{Arc, OnceLock}; use std::time::{Duration, Instant}; use tokio::io::{AsyncSeekExt, AsyncWrite, AsyncWriteExt}; use tokio::sync::{watch, OnceCell}; @@ -67,11 +67,11 @@ const PIPE_READER_POLL: Duration = Duration::from_millis(50); /// [`HttpConfig::request_timeout`](crate::HttpConfig::request_timeout): a /// transfer fails after that long without progress. /// -/// Cancelling the execution stops the transfer but cannot undo a PUT or REMOVE -/// that storage already applied. A GET whose download is already being copied -/// into an existing file finishes that copy; if the call is dropped meanwhile, -/// the copy keeps running after the call returns, and later calls for that -/// execution report `Cancelled`. +/// Cancelling the execution stops the transfer, and so does dropping a call +/// that waits on it, unless an [`AsyncStatementReader`](crate::AsyncStatementReader) +/// made the call. Stopping cannot undo a PUT or REMOVE that storage already +/// applied, and a GET whose download is already being copied into an existing +/// file finishes that copy. #[non_exhaustive] #[derive(Clone, Default)] pub struct VolumeOptions { @@ -158,8 +158,7 @@ impl Storage { options, input_bytes: std::sync::Mutex::new(input_bytes), cancellation: self.cancellation.child_token(), - outcome: OnceCell::new(), - started: AtomicBool::new(false), + outcome: OnceLock::new(), }) } @@ -176,13 +175,7 @@ impl Storage { } } -struct AbortOnDrop(tokio::task::AbortHandle); - -impl Drop for AbortOnDrop { - fn drop(&mut self) { - self.0.abort(); - } -} +type Outcome = Shared>>; /// One execution's transfer. Every result stream of the execution shares it, /// so the transfer runs at most once. @@ -192,10 +185,8 @@ pub(crate) struct VolumeState { /// Taken when the transfer starts, so the upload does not outlive it. input_bytes: std::sync::Mutex>, cancellation: CancellationToken, - outcome: OnceCell>, - /// Set when a transfer starts. A call abandoned mid-transfer caches - /// nothing, and the transfer must not run again. - started: AtomicBool, + /// The spawned transfer. Every call waits on it, and only cancellation stops it. + outcome: OnceLock, } impl VolumeState { @@ -203,63 +194,74 @@ impl VolumeState { self.cancellation.cancel(); } - /// Runs the transfer `instruction` describes, once per execution. + /// Runs the transfer `instruction` describes, once per execution. Dropping an + /// `owner` call cancels the transfer; dropping any other call leaves it running. pub(crate) async fn complete( self: &Arc, instruction: Result>, + owner: bool, ) -> Result<()> { let Some(options) = &self.options else { return Ok(()); }; - if let Some(outcome) = self.outcome.get() { - return outcome.clone(); + let outcome = match self.outcome.get() { + Some(outcome) => outcome.clone(), + None => { + // Nothing before the transfer is kept: another result stream of the + // execution may still read the instruction. + let batch = + instruction?.ok_or_else(|| invalid("Missing Volume instruction row"))?; + let instruction = Instruction::decode(&batch)?; + self.outcome + .get_or_init(|| self.spawn(instruction, options.clone())) + .clone() + } + }; + let cancel_on_drop = owner.then(|| self.cancellation.clone().drop_guard()); + let outcome = outcome.await; + if let Some(guard) = cancel_on_drop { + guard.disarm(); } - // Nothing before the transfer is cached: another result stream of the - // execution may still read the instruction. - let batch = instruction?.ok_or_else(|| invalid("Missing Volume instruction row"))?; - let instruction = Instruction::decode(&batch)?; - self.outcome - .get_or_init(|| async { - if self.started.swap(true, Ordering::AcqRel) { - return Err(cancelled()); - } - let input_bytes = self - .input_bytes - .lock() - .unwrap_or_else(|e| e.into_inner()) - .take(); - if matches!(instruction.operation, Operation::Put(None)) && input_bytes.is_none() { - return Err(Error::invalid_argument() - .message("A Volume PUT of __input_stream__ needs input bytes")); - } - // On the session runtime's threads, which kernel-owned runtimes set to - // block SIGPIPE, a pipe whose reader exits fails the write instead of - // killing the host. - let (state, options) = (Arc::clone(self), options.clone()); - let mut task = self - .storage - .runtime - .spawn(async move { state.transfer(instruction, &options, input_bytes).await }); - let _abort = AbortOnDrop(task.abort_handle()); - let local = tokio::select! { - biased; - _ = self.cancellation.cancelled() => { - // Waiting for the aborted transfer to drop removes a new GET - // destination before the call returns. - task.abort(); - let _ = (&mut task).await; - return Err(cancelled()); - } - joined = &mut task => joined.map_err(|e| { - Error::internal().message(format!("Volume transfer failed: {e}")) - })??, - }; - // Copying a download into an existing file cannot be stopped midway, so - // it runs to the end and the outcome reports the file it left. - local.publish().await + outcome + } + + fn spawn(self: &Arc, instruction: Instruction, options: VolumeOptions) -> Outcome { + let state = Arc::clone(self); + // On the session runtime's threads, which kernel-owned runtimes set to + // block SIGPIPE, a pipe whose reader exits fails the write instead of + // killing the host. + let task = self + .storage + .runtime + .spawn(async move { state.run(instruction, &options).await }); + async move { + task.await.unwrap_or_else(|e| { + Err(Error::internal().message(format!("Volume transfer failed: {e}"))) }) - .await - .clone() + } + .boxed() + .shared() + } + + async fn run(&self, instruction: Instruction, options: &VolumeOptions) -> Result<()> { + let input_bytes = self + .input_bytes + .lock() + .unwrap_or_else(|e| e.into_inner()) + .take(); + if matches!(instruction.operation, Operation::Put(None)) && input_bytes.is_none() { + return Err(Error::invalid_argument() + .message("A Volume PUT of __input_stream__ needs input bytes")); + } + // Stopping the transfer drops it, which removes a new GET destination. + let local = tokio::select! { + biased; + _ = self.cancellation.cancelled() => return Err(cancelled()), + local = self.transfer(instruction, options, input_bytes) => local?, + }; + // Copying a download into an existing file cannot be stopped midway, so + // it runs to the end and the outcome reports the file it left. + local.publish().await } async fn transfer( @@ -1056,7 +1058,7 @@ mod tests { } async fn run(storage: &Arc, batch: RecordBatch, root: &Path) -> Result<()> { - state(storage, root).complete(Ok(Some(batch))).await + state(storage, root).complete(Ok(Some(batch)), true).await } /// An instruction row as the server sends it, with headers as a map. @@ -1186,12 +1188,15 @@ mod tests { let put = instruction("PUT", &server.uri(), Path::new("__input_stream__")); let storage = storage(0, None); let without = storage.transfer_state(Some(VolumeOptions::default())); - let error = without.complete(Ok(Some(put.clone()))).await.unwrap_err(); + let error = without + .complete(Ok(Some(put.clone())), true) + .await + .unwrap_err(); assert_eq!(error.code, ErrorCode::InvalidArgument); let bytes = Bytes::from(b"caller bytes".to_vec()); let options = VolumeOptions::default().with_input_bytes(bytes.clone()); let with = storage.transfer_state(Some(options)); - with.complete(Ok(Some(put))).await.unwrap(); + with.complete(Ok(Some(put)), true).await.unwrap(); // The finished transfer no longer holds the upload. assert!(bytes.is_unique()); } @@ -1232,10 +1237,10 @@ mod tests { mount(&server, "DELETE", "/", ResponseTemplate::new(200)).await; let dir = tempfile::tempdir().unwrap(); let state = state(&storage(0, None), dir.path()); - let read = state.complete(Err(Error::network_error())).await; + let read = state.complete(Err(Error::network_error()), true).await; assert!(read.is_err()); state - .complete(Ok(Some(remove(&server.uri())))) + .complete(Ok(Some(remove(&server.uri()))), true) .await .unwrap(); } @@ -1288,7 +1293,7 @@ mod tests { let options = VolumeOptions::new(Vec::new(), remove_not_found_is_success); let result = storage .transfer_state(Some(options)) - .complete(Ok(Some(remove(&server.uri())))) + .complete(Ok(Some(remove(&server.uri()))), true) .await; assert_eq!(result.is_ok(), remove_not_found_is_success); } @@ -1587,7 +1592,7 @@ mod tests { async move { loop { let (mut socket, _) = listener.accept().await.unwrap(); - accepted.fetch_add(1, Ordering::SeqCst); + accepted.fetch_add(1, std::sync::atomic::Ordering::SeqCst); assert!(socket.read(&mut [0; 4096]).await.unwrap() > 0); socket .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\nabc") @@ -1599,7 +1604,7 @@ mod tests { let get = instruction("GET", &url, &dir.path().join("file")); run(&storage(2, None), get, dir.path()).await.unwrap_err(); peer.abort(); - assert_eq!(accepted.load(Ordering::SeqCst), 3); + assert_eq!(accepted.load(std::sync::atomic::Ordering::SeqCst), 3); assert!(!dir.path().join("file").exists()); } @@ -1707,7 +1712,7 @@ mod tests { }) }; let get = instruction("GET", &server.uri(), &destination); - state.complete(Ok(Some(get))).await.unwrap(); + state.complete(Ok(Some(get)), true).await.unwrap(); watcher.join().unwrap(); assert_eq!(std::fs::read(&destination).unwrap().len(), body.len()); } @@ -1732,7 +1737,7 @@ mod tests { let state = state(&storage(0, None), dir.path()); let requested = requested(&server); tokio::time::timeout(Duration::from_secs(10), async { - let transfer = state.complete(Ok(Some(get.clone()))); + let transfer = state.complete(Ok(Some(get.clone())), true); if abandon { tokio::select! { result = transfer => panic!("transfer finished early: {result:?}"), @@ -1748,7 +1753,7 @@ mod tests { }) .await .unwrap(); - let repeated = state.complete(Ok(Some(get))).await.unwrap_err(); + let repeated = state.complete(Ok(Some(get)), true).await.unwrap_err(); assert_eq!(repeated.code, ErrorCode::Cancelled, "abandon={abandon}"); assert_eq!(std::fs::read(&destination).unwrap(), b"old"); } diff --git a/tests/v0_volume_wiremock.rs b/tests/v0_volume_wiremock.rs index 67e44e7b..1dedb553 100644 --- a/tests/v0_volume_wiremock.rs +++ b/tests/v0_volume_wiremock.rs @@ -255,6 +255,26 @@ async fn async_results_of_one_execution_share_one_transfer() { assert_eq!(std::fs::read(&destination).unwrap(), b"data"); } +#[tokio::test] +async fn a_dropped_reader_call_leaves_the_transfer_to_the_owner() { + let server = MockServer::start().await; + let dir = tempfile::tempdir().unwrap(); + let destination = dir.path().join("download"); + mount_object(&server, Duration::from_millis(500), 1).await; + mount_volume_result(&server, "GET", destination.to_str().unwrap(), true).await; + let session = session(&server, HttpConfig::default()).await; + let mut statement = session.statement(); + statement.spec().sql("GET").volume(options(dir.path())); + let executed = statement.submit().await.unwrap(); + let reader = executed.reader().unwrap(); + tokio::select! { + result = reader.await_result() => panic!("the reader finished early: {:?}", result.err()), + () = object_requested(&server) => {} + } + executed.await_result().await.unwrap(); + assert_eq!(std::fs::read(&destination).unwrap(), b"data"); +} + #[tokio::test] async fn an_attached_handle_returns_the_instruction_row_without_transferring() { let server = MockServer::start().await; From 87904964e757bee50cac1caf23200ab61ee5e0d3 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Thu, 3 Dec 2026 08:20:23 +0000 Subject: [PATCH 43/43] fix(statement): close the server statement when a sync execute fails execute and execute_direct record the statement id before building the result stream, running a Volume transfer and reading the row count. When one of those failed, no executed handle owned the id, so dropping the Statement left the server statement open until session close. The failed execute now closes it, as a failed batch already did. Co-authored-by: Isaac Signed-off-by: Aakash Saravanan --- src/statement/mutable.rs | 10 +++++++--- tests/v0_volume_wiremock.rs | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+), 3 deletions(-) diff --git a/src/statement/mutable.rs b/src/statement/mutable.rs index 8216f5f9..1a0344ce 100644 --- a/src/statement/mutable.rs +++ b/src/statement/mutable.rs @@ -515,6 +515,8 @@ impl Statement { .await; if let Err(error) = &mut result { self.finish_failed_batch(error).await; + // A failed execute returns no handle, so close a statement it already ran. + self.invalidate_prior().await; telemetry.finalize(Some(error)); } result @@ -796,6 +798,8 @@ impl Statement { .await; if let Err(error) = &mut result { self.finish_failed_batch(error).await; + // A failed execute returns no handle, so close a statement it already ran. + self.invalidate_prior().await; telemetry.finalize(Some(error)); } result @@ -1142,9 +1146,9 @@ impl Drop for Statement { valid.invalidate(); } self.current_volume().cancel(); - // `last_statement_id` is left as-is. By construction it is - // only set immediately before `ExecutedStatement::new` - // wraps it; if the caller still holds an `ExecutedStatement`, + // `last_statement_id` is left as-is. An execute that sets it + // either wraps it in an executed handle or, on failure, closes + // the statement; if the caller still holds an executed handle, // that handle owns the close-on-drop responsibility. If the // caller dropped the handle before this `Statement`, the // handle's own `Drop` already spawned the close. There is no diff --git a/tests/v0_volume_wiremock.rs b/tests/v0_volume_wiremock.rs index 1dedb553..8de5bc84 100644 --- a/tests/v0_volume_wiremock.rs +++ b/tests/v0_volume_wiremock.rs @@ -275,6 +275,42 @@ async fn a_dropped_reader_call_leaves_the_transfer_to_the_owner() { assert_eq!(std::fs::read(&destination).unwrap(), b"data"); } +#[tokio::test] +async fn a_failed_transfer_closes_the_server_statement() { + for direct in [false, true] { + let server = MockServer::start().await; + let (root, elsewhere) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap()); + let destination = elsewhere.path().join("download"); + mount_volume_result(&server, "GET", destination.to_str().unwrap(), true).await; + let session = session(&server, HttpConfig::default()).await; + let mut statement = session.statement(); + statement.spec().sql("GET").volume(options(root.path())); + let failed = if direct { + statement.execute_direct().await.is_err() + } else { + statement.execute().await.is_err() + }; + assert!(failed, "a GET outside the allowed root fails"); + drop(statement); + tokio::time::timeout(Duration::from_secs(5), async { + while !server + .received_requests() + .await + .unwrap() + .iter() + .any(|request| { + request.method.as_str() == "DELETE" + && request.url.path() == "/api/2.0/sql/statements/stmt-volume" + }) + { + tokio::task::yield_now().await; + } + }) + .await + .unwrap_or_else(|_| panic!("no CloseStatement (direct={direct})")); + } +} + #[tokio::test] async fn an_attached_handle_returns_the_instruction_row_without_transferring() { let server = MockServer::start().await;