diff --git a/adbc/README.md b/adbc/README.md index 440f8018..7b5bac0f 100644 --- a/adbc/README.md +++ b/adbc/README.md @@ -159,10 +159,11 @@ operation is pending. Client query deadlines and rows-per-block slicing apply equally to synchronous and submitted execution. Dropping a submitted handle or an incompletely consumed reader triggers best-effort server cleanup. -`adbc.databricks.cloudfetch.enabled` is wired to the kernel result -configuration. The current kernel/server combination does not yet support the -`false` path because SEA rejects inline Arrow results; disabling CloudFetch is -therefore not a production-supported configuration in this release. +Set `adbc.databricks.cloudfetch.enabled` to `false` to fetch results through +the SQL connection when the application cannot access cloud storage directly. +Large results are read in pages. +The warehouse must support paged inline delivery; otherwise session creation +or the first statement returns the server's configuration error. ## ADBC behavior diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h index 965c09b6..e167f181 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -595,12 +595,12 @@ KernelStatusCode kernel_session_config_set_u2m_token_cache_config(KernelSessionC * * Recognised keys (case-insensitive): * - "cloudfetch_enabled" = "true"|"false" — false serves every result - * inline (SEA disposition = INLINE), mirroring JDBC EnableQueryResultDownload=0. + * through paged inline delivery without cloud-storage downloads. * - "cloudfetch_link_prefetch_window" = positive integer. * - "cloudfetch_max_chunks_in_memory" = positive integer (bounds peak RSS; * values above the kernel ceiling of 256 are clamped with a warning). * - "inline_max_chunks_in_memory" = positive integer (inline-Arrow prefetch - * window, used when cloudfetch_enabled = false). + * window for paged inline results). * - "complex_types_as_json" = "true"|"false" — render ARRAY / MAP / STRUCT / * VARIANT / GEOMETRY / GEOGRAPHY as JSON text (PySQL * _use_arrow_native_complex_types=False, JDBC complexDatatypeSupport=false). diff --git a/src/c_abi/session.rs b/src/c_abi/session.rs index 73764e74..b3365f49 100644 --- a/src/c_abi/session.rs +++ b/src/c_abi/session.rs @@ -1378,15 +1378,14 @@ pub unsafe extern "C" fn kernel_session_config_set_u2m_token_cache_config( /// Recognised keys (matched case-insensitively), mapping to /// [`ResultConfig`]: /// - `cloudfetch_enabled` = `"true"` / `"false"` — `false` serves every -/// result inline (SEA `disposition = INLINE`), mirroring JDBC's -/// `EnableQueryResultDownload=0`. +/// result through paged inline delivery without cloud-storage downloads. /// - `cloudfetch_link_prefetch_window` = positive integer — presigned URLs /// prefetched ahead of the consumer. /// - `cloudfetch_max_chunks_in_memory` = positive integer — decompressed /// CloudFetch chunks held at once (bounds peak RSS). Values above the /// kernel ceiling (256) are **clamped** with a warning, not rejected. /// - `inline_max_chunks_in_memory` = positive integer — inline-Arrow -/// prefetch window (used when `cloudfetch_enabled = false`). +/// prefetch window for paged inline results. /// - `complex_types_as_json` = `"true"` / `"false"` — render `ARRAY` / /// `MAP` / `STRUCT` / `VARIANT` / `GEOMETRY` / `GEOGRAPHY` as JSON text /// (PySQL `_use_arrow_native_complex_types=False`, JDBC diff --git a/src/client/sea.rs b/src/client/sea.rs index 2a490aac..7003150f 100644 --- a/src/client/sea.rs +++ b/src/client/sea.rs @@ -658,30 +658,6 @@ impl SeaRestTransport { ) -> Result { let url = format!("{}/statements", self.base_url()); - // Select the result disposition per statement from the - // connection-level CloudFetch setting, mirroring the reference - // JDBC driver's SEA path (`DatabricksSdkClient.getRequest`: - // `cloudFetch ? INLINE_OR_EXTERNAL_LINKS : INLINE`). This is the - // authoritative mechanism for disabling cloud-fetch on SEA — - // there is NO `CAN_CLOUD_DOWNLOAD` session conf (the server - // rejects it at ExecuteStatement with `CONFIG_NOT_AVAILABLE`, - // issue #196). - // - // `INLINE`: the server serves every result inline (Arrow bytes in - // the response `attachment`), regardless of size. `format` stays - // `ARROW_STREAM` — the kernel's inline reader consumes Arrow IPC - // from the attachment (the SEA inline-Arrow path), so unlike JDBC - // we keep Arrow rather than switching to `JSON_ARRAY`. - // - // `INLINE_OR_EXTERNAL_LINKS` (the CloudFetch-enabled default): not - // a public API disposition but enables returning all chunk links - // in a single response (requires the JDBC user agent). Once - // EXTERNAL_LINKS supports multi-link responses, switch back to it. - let disposition = if self.config.cloudfetch_enabled { - "INLINE_OR_EXTERNAL_LINKS" - } else { - "INLINE" - }; let (warehouse_id, session_id) = match self.session_route.get() { Some(SessionRoute::Standard { .. }) | None => ( Some(self.warehouse_id.clone()), @@ -696,7 +672,7 @@ impl SeaRestTransport { session_version: self.current_session_version(), catalog: params.catalog.clone(), schema: params.schema.clone(), - disposition: disposition.to_string(), + disposition: "INLINE_OR_EXTERNAL_LINKS".to_string(), format: "ARROW_STREAM".to_string(), wait_timeout: params.wait_timeout.clone(), on_wait_timeout: params.on_wait_timeout.clone(), @@ -1156,10 +1132,15 @@ impl Transport for SeaRestTransport { &self, catalog: Option<&str>, schema: Option<&str>, - session_config: HashMap, + mut session_config: HashMap, ) -> Result { let url = self.warehouse_sessions_url(); + if !self.config.cloudfetch_enabled { + session_config.retain(|key, _| !key.eq_ignore_ascii_case("can_cloud_download")); + session_config.insert("can_cloud_download".to_string(), "false".to_string()); + } + let request_body = CreateSessionRequest { warehouse_id: None, catalog: catalog.map(|s| s.to_string()), @@ -1537,18 +1518,12 @@ impl Transport for SeaRestTransport { )) })?; - // Inline-Arrow path: bytes must be present in `attachment`. - // If the server returned an external_links response on what - // we expected to be the inline path, surface a clear error - // (probably the `disposition = INLINE` on the execute request - // didn't take effect server-side). let bytes = chunks_response.attachment.ok_or_else(|| { Error::data_loss().message(format!( "Inline chunk {} response missing `attachment` field — \ - server may have ignored the INLINE disposition and \ - returned a CloudFetch response. Body: {}", - chunk_index, - String::from_utf8_lossy(&body) + server did not return inline Arrow data and \ + returned a CloudFetch response", + chunk_index )) })?; diff --git a/src/client/transport.rs b/src/client/transport.rs index 8f58cfe7..90f91a75 100644 --- a/src/client/transport.rs +++ b/src/client/transport.rs @@ -67,22 +67,8 @@ pub(crate) struct TransportConfig { /// Whether CloudFetch (cloud-storage-backed result download via /// external links) is enabled for this session. /// - /// This is a **connection-level** setting — like the reference JDBC - /// driver's `EnableQueryResultDownload`, it is read once at session - /// open and applied to every `ExecuteStatement`, not toggled per - /// statement. It selects the SEA `disposition` sent on each execute: - /// `true` → `INLINE_OR_EXTERNAL_LINKS` (results may come back as - /// external CloudFetch links), `false` → `INLINE` (the server serves - /// every result inline, regardless of size). - /// - /// **Why this is `disposition`, not a session conf.** SEA has no - /// `CAN_CLOUD_DOWNLOAD` session conf — sending one is accepted at - /// `CreateSession` but rejected at the first `ExecuteStatement` with - /// `CONFIG_NOT_AVAILABLE` (see issue #196). Both the JDBC and Thrift - /// reference drivers control cloud-fetch per request (SEA - /// `disposition` / Thrift `canDownloadResult`), never via session - /// conf; this mirrors JDBC's SEA path - /// (`DatabricksSdkClient.getRequest`). + /// When false, session creation requests paged inline results without + /// cloud-storage downloads. The value is fixed for the session lifetime. pub cloudfetch_enabled: bool, } @@ -404,10 +390,7 @@ pub(crate) trait Transport: Send + Sync + std::fmt::Debug { /// Fetch one inline-Arrow chunk by `chunk_index` (+ server-side /// `row_offset`). /// - /// Used by the inline-Arrow streaming path that lights up when - /// `ResultConfig.cloudfetch_enabled == false` (i.e. the execute - /// request was sent with SEA `disposition = INLINE`). The - /// server-side response for this path carries Arrow IPC bytes inline + /// Used for paged inline results. The response carries Arrow IPC bytes inline /// in `attachment` rather than emitting `external_links`. /// /// Per the bounded SEA API contract for OSS drivers: diff --git a/src/config.rs b/src/config.rs index b889f052..9c1eb0a9 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1090,30 +1090,9 @@ pub struct ResultConfig { /// Whether to opt into CloudFetch (cloud-storage-backed download of /// large result sets via presigned URLs). Default: `true`. /// - /// Setting this to `false` mirrors JDBC's `EnableQueryResultDownload=0` - /// behaviour. It is a **connection-level** setting: read once at - /// [`Session::open`](crate::Session::open) and applied to every - /// statement by selecting the SEA `disposition` on each - /// `ExecuteStatement` (`false` → `INLINE`, so SEA serves **all** - /// result sizes via the inline-Arrow path regardless of size). This - /// matches how the JDBC and Thrift reference drivers control - /// cloud-fetch (per request), and is deliberately **not** expressed - /// as a session conf — SEA has no `CAN_CLOUD_DOWNLOAD` conf and - /// rejects one at ExecuteStatement with `CONFIG_NOT_AVAILABLE` - /// (issue #196). Users who need inline-only behaviour (e.g. - /// workspaces without cloud-storage egress) should set this to - /// `false`. - /// - /// Disabling CloudFetch routes results to the inline-Arrow - /// path. The kernel today supports the **single-attachment** - /// inline path; the multi-chunk inline path is on the SEA - /// inline-Arrow rollout (DD1) and is tracked as a follow-up - /// (`InlineArrowProvider::new` consumes one attachment, and - /// `src/reader/mod.rs` returns `Error::not_implemented` for - /// inline responses that carry a `next_chunk_internal_link`). - /// Once multi-chunk lands, this path will not match - /// CloudFetch's concurrent chunk-download pipeline - /// (`cloudfetch_max_chunks_in_memory`). + /// Set to `false` for applications without direct access to cloud storage. + /// This connection-level setting requests paged inline Arrow results. + /// Servers without this capability may reject session creation or the first statement. pub cloudfetch_enabled: bool, /// Number of presigned URLs to prefetch ahead of the consumer. @@ -1125,8 +1104,7 @@ pub struct ResultConfig { /// Maximum number of decompressed Arrow chunks the inline-Arrow /// streaming reader holds in memory at once. Analogue of - /// [`Self::cloudfetch_max_chunks_in_memory`] for the inline path - /// (used when [`Self::cloudfetch_enabled`] is `false`). + /// [`Self::cloudfetch_max_chunks_in_memory`] for paged inline results. /// /// The inline path is sequential per the SEA contract — one /// `GetResultData` call at a time — so this knob bounds the @@ -1565,19 +1543,9 @@ pub struct SessionConfig { /// Thrift `configuration`. Typed sub-structs above translate /// the *client-side* knobs; this map carries everything else. /// - /// The kernel passes user-supplied entries through unchanged. The - /// kernel does not synthesise any entries here from typed - /// client-side knobs. - /// - /// In particular, [`ResultConfig::cloudfetch_enabled`] is **not** - /// expressed as a session conf: SEA has no `CAN_CLOUD_DOWNLOAD` - /// conf (it is accepted at CreateSession but rejected at the first - /// ExecuteStatement with `CONFIG_NOT_AVAILABLE`, issue #196). - /// CloudFetch-disable is instead applied per-statement via the SEA - /// `disposition` field, matching the JDBC / Thrift reference - /// drivers. A caller-supplied `can_cloud_download` is still forwarded - /// unchanged because the kernel does not validate server-bound - /// `session_conf` keys. + /// User-supplied entries are passed through, except that disabling + /// CloudFetch in [`ResultConfig`] takes precedence over its corresponding + /// session setting. /// /// **Boolean-valued conf keys** should use the exact strings /// `"true"` / `"false"`. SEA accepts these literally; other forms diff --git a/src/reader/inline/mod.rs b/src/reader/inline/mod.rs index 24b3dd4d..20369a4c 100644 --- a/src/reader/inline/mod.rs +++ b/src/reader/inline/mod.rs @@ -30,9 +30,8 @@ //! case. The server returns one chunk at a time via //! `GET /result/chunks/{idx}?row_offset=N`; the kernel maintains a //! bounded rolling window of pre-decoded chunks ahead of the -//! consumer. Used when CloudFetch is disabled (the execute request -//! was sent with SEA `disposition = INLINE`) and the result is -//! large enough that the server paginates it. +//! consumer. Used when the result is large enough that the server +//! paginates inline delivery. mod provider; mod streaming; diff --git a/src/reader/inline/streaming.rs b/src/reader/inline/streaming.rs index 79a1c933..2f89fb1a 100644 --- a/src/reader/inline/streaming.rs +++ b/src/reader/inline/streaming.rs @@ -14,8 +14,7 @@ //! `InlineStreamingProvider` — rolling-window prefetch for multi-chunk inline Arrow. //! -//! Lights up when CloudFetch is disabled (`cloudfetch_enabled = false`, -//! i.e. the execute request was sent with SEA `disposition = INLINE`). +//! Used for paged inline results, including when CloudFetch is disabled. //! The server returns chunks one at a time via `GET /result/chunks/{idx}` //! with Arrow IPC bytes in `attachment`; this provider keeps a bounded //! number of those chunks decoded and ready in memory ahead of the diff --git a/src/reader/mod.rs b/src/reader/mod.rs index c9532fbf..dd8023c3 100644 --- a/src/reader/mod.rs +++ b/src/reader/mod.rs @@ -199,6 +199,11 @@ impl ResultReaderFactory { // Priority 1: CloudFetch (external_links present) if let Some(ref external_links) = result.external_links { if !external_links.is_empty() { + if !self.config.enabled { + return Err(Error::data_loss().message( + "CloudFetch is disabled, but the server returned cloud-storage result links", + )); + } // `total_chunk_count` is forwarded purely as a // transition-period guard. The link fetcher uses // it only when the server hasn't yet rolled out diff --git a/src/session.rs b/src/session.rs index 1a64a209..ccb3fd0d 100644 --- a/src/session.rs +++ b/src/session.rs @@ -391,11 +391,6 @@ impl Session { // install factory. let defaults = config.defaults.clone().unwrap_or_default(); let transport_config = TransportConfig { - // Thread the connection-level CloudFetch toggle onto the - // transport so every ExecuteStatement picks the right SEA - // disposition (INLINE_OR_EXTERNAL_LINKS vs INLINE). This is - // how cloud-fetch is disabled on SEA — see TransportConfig - // and issue #196; there is no CAN_CLOUD_DOWNLOAD session conf. cloudfetch_enabled: config.result.cloudfetch_enabled, ..TransportConfig::default() }; @@ -423,10 +418,8 @@ impl Session { "creating session" ); - // CloudFetch-disable is expressed per-statement via the SEA - // `disposition` (threaded onto `TransportConfig` above), not via a - // session conf. The kernel synthesises no geospatial session-conf - // entry; caller-supplied server-bound entries pass through unchanged. + // The kernel synthesises no geospatial session-conf entry; + // caller-supplied server-bound entries pass through unchanged. // Resolve connector-service flags after authentication and immediately // before CreateSession. The resolver populates the process-wide // workspace cache; the session retains no private snapshot. @@ -1254,9 +1247,11 @@ fn build_retry_configs_for_session( /// Matched case-insensitively. If a host sets two spellings of the same key /// differing only in case, the lexicographically-last spelling wins /// deterministically and all variants are stripped. +/// An explicit typed CloudFetch disable takes precedence over the mixed bag. fn apply_client_result_overrides(config: &mut SessionConfig) { use crate::config::ClientConfKey; + let cloudfetch_disabled = !config.result.cloudfetch_enabled; // Recognised client keys currently present in session_conf. A key is // "recognised" iff it parses to a ClientConfKey (case-insensitive). let mut present: Vec = config @@ -1288,6 +1283,12 @@ fn apply_client_result_overrides(config: &mut SessionConfig) { ); } } + if cloudfetch_disabled && config.result.cloudfetch_enabled { + crate::klog::warn!( + "Ignoring cloudfetch_enabled=true in session configuration because the client option disables CloudFetch" + ); + config.result.cloudfetch_enabled = false; + } } /// Project the public [`ResultConfig`] (today only carries @@ -2048,6 +2049,23 @@ mod retry_config_tests { ); } + #[test] + fn typed_cloudfetch_disable_takes_precedence_over_session_conf() { + for key in ["cloudfetch_enabled", "CLOUDFETCH_ENABLED"] { + let mut cfg = config_with_session_conf(HashMap::from([ + (key.to_string(), "true".to_string()), + ("TIMEZONE".to_string(), "UTC".to_string()), + ])); + cfg.result.cloudfetch_enabled = false; + apply_client_result_overrides(&mut cfg); + assert!(!cfg.result.cloudfetch_enabled); + assert_eq!( + cfg.session_conf, + HashMap::from([("TIMEZONE".to_string(), "UTC".to_string())]) + ); + } + } + /// All six client-side result knobs are recognised in session_conf, /// applied to the typed ResultConfig, and stripped so none reach the /// wire. Guards the parity between `ClientConfKey::ALL` and the diff --git a/src/types/cloudfetch.rs b/src/types/cloudfetch.rs index 9dfcc9e3..278850c9 100644 --- a/src/types/cloudfetch.rs +++ b/src/types/cloudfetch.rs @@ -71,9 +71,7 @@ pub struct CloudFetchConfig { /// When > 0, consecutive small batches are concatenated into larger batches /// of approximately this many rows before being served to consumers. pub batch_merge_target_rows: usize, - /// Rolling-window bound for the multi-chunk inline-Arrow path - /// (used when CloudFetch is disabled, i.e. the execute request is - /// sent with SEA `disposition = INLINE`). Analogue of + /// Rolling-window bound for multi-chunk inline Arrow results. Analogue of /// [`Self::max_chunks_in_memory`] but for sequential inline /// prefetches rather than parallel cloud downloads. pub inline_max_chunks_in_memory: usize, diff --git a/src/types/sea.rs b/src/types/sea.rs index 977a7b02..8d988dad 100644 --- a/src/types/sea.rs +++ b/src/types/sea.rs @@ -512,9 +512,7 @@ pub struct GetChunksResponse { pub external_links: Option>, /// Inline Arrow IPC bytes (base64-decoded by serde) for the /// inline-Arrow streaming path. Populated when the server - /// returns chunks inline rather than via CloudFetch — i.e. when - /// the execute request was sent with SEA `disposition = INLINE` - /// (`cloudfetch_enabled = false`). + /// returns chunks inline rather than via CloudFetch. #[serde(default, deserialize_with = "deserialize_base64_attachment")] pub attachment: Option>, } diff --git a/tests/v0_c_abi_result_config_wiremock.rs b/tests/v0_c_abi_result_config_wiremock.rs index 442ff88e..79f1c3ca 100644 --- a/tests/v0_c_abi_result_config_wiremock.rs +++ b/tests/v0_c_abi_result_config_wiremock.rs @@ -15,15 +15,8 @@ //! C-ABI wiremock tests for the client-side result-config surface //! (`kernel_session_config_set_client_conf`). //! -//! These prove the client-side knobs actually reach the wire / kernel -//! behaviour through the C ABI — closing the gap where the C ABI -//! previously could not reach `ResultConfig` at all (only the legacy -//! `cloudfetch_max_chunks_in_memory` magic string). The headline check: -//! opening a session with `cloudfetch_enabled = false` via -//! `set_client_conf` makes every `ExecuteStatement` carry SEA -//! `disposition = INLINE` (see #196 for why that, not a -//! `can_cloud_download` session conf, is the correct mechanism), while the -//! default carries `INLINE_OR_EXTERNAL_LINKS`. +//! Verifies result configuration through the C ABI, including paged +//! inline delivery when cloud-storage downloads are disabled. use std::ffi::CString; @@ -176,6 +169,22 @@ fn recorded_execute_disposition(cloudfetch_enabled: Option) -> String { } let recorded = rt.block_on(async { server.received_requests().await.unwrap() }); + let create = recorded + .iter() + .find(|request| request.url.path() == "/api/2.0/sql/warehouses/test_wh/sessions") + .expect("a CreateSession request was made"); + let create_body: serde_json::Value = serde_json::from_slice(&create.body).unwrap(); + let expected = if cloudfetch_enabled == Some(false) { + Some("false") + } else { + None + }; + assert_eq!( + create_body + .pointer("/session_confs/can_cloud_download") + .and_then(|value| value.as_str()), + expected, + ); let exec = recorded .iter() .find(|r| r.url.path() == "/api/2.0/sql/statements" && r.method.as_str() == "POST") @@ -219,13 +228,11 @@ fn recorded_create_session_geospatial_conf(enabled: bool) -> Option { } #[test] -fn c_abi_client_conf_cloudfetch_disabled_sends_inline_disposition() { - // The headline: a C-ABI host that disables CloudFetch via - // set_client_conf("cloudfetch_enabled","false") gets SEA - // `disposition = INLINE` on the wire — proving the client-conf channel - // reaches the execute path (previously unreachable from the C ABI). - // Mirrors the Rust-crate coverage in tests/v0_execute_wiremock.rs. - assert_eq!(recorded_execute_disposition(Some(false)), "INLINE"); +fn c_abi_client_conf_cloudfetch_disabled_supports_paged_arrow_results() { + assert_eq!( + recorded_execute_disposition(Some(false)), + "INLINE_OR_EXTERNAL_LINKS" + ); } #[test] diff --git a/tests/v0_execute_e2e.rs b/tests/v0_execute_e2e.rs index b739b73e..49cda939 100644 --- a/tests/v0_execute_e2e.rs +++ b/tests/v0_execute_e2e.rs @@ -48,6 +48,72 @@ async fn live_session() -> Session { .expect("Session::open against live workspace") } +#[tokio::test] +#[ignore] +async fn cloudfetch_disabled_drains_large_results() { + use arrow_array::{Int64Array, StringArray}; + use sha2::{Digest, Sha256}; + + let host = env_var("DATABRICKS_HOST").expect("DATABRICKS_HOST required"); + let path = env_var("DATABRICKS_HTTP_PATH").expect("DATABRICKS_HTTP_PATH required"); + let token = env_var("DATABRICKS_TOKEN").expect("DATABRICKS_TOKEN required"); + let mut result = ResultConfig::default(); + result.cloudfetch_enabled = false; + let session = Session::builder() + .http_path(host, path) + .auth(AuthConfig::Pat { + token, + identity_federation_client_id: None, + }) + .result(result) + .open() + .await + .expect("open session with CloudFetch disabled"); + let mut statement = session.statement(); + statement + .spec() + .sql("SELECT id, sha2(CAST(id AS STRING), 512) AS payload FROM range(250000) ORDER BY id"); + let mut executed = statement.execute().await.expect("execute large query"); + let mut rows = 0_i64; + let mut payload_bytes = 0; + let mut digest = Sha256::new(); + while let Some(batch) = executed + .result_stream_mut() + .next_batch() + .await + .expect("next batch") + { + let ResultBatch::Arrow(batch) = batch else { + panic!("expected Arrow batch"); + }; + let ids = batch + .column(0) + .as_any() + .downcast_ref::() + .unwrap(); + let payloads = batch + .column(1) + .as_any() + .downcast_ref::() + .unwrap(); + for row in 0..batch.num_rows() { + assert_eq!(ids.value(row), rows); + let payload = payloads.value(row); + payload_bytes += payload.len(); + digest.update(format!("{rows}\t{payload}\n").as_bytes()); + rows += 1; + } + } + assert_eq!(rows, 250_000); + assert_eq!(payload_bytes, 32_000_000); + assert_eq!( + hex::encode(digest.finalize()), + "a25ada4c6c476b53e97eb6e8a945e9ce4c14cc432c7ad672dc6fb607d660c86a", + ); + executed.close().await.expect("close statement"); + session.close().await.expect("close session"); +} + /// Open a live session authenticated via the JWT private-key M2M flow /// (`AuthConfig::OAuthM2MPrivateKey`). /// diff --git a/tests/v0_execute_wiremock.rs b/tests/v0_execute_wiremock.rs index e428abf3..c2afcec4 100644 --- a/tests/v0_execute_wiremock.rs +++ b/tests/v0_execute_wiremock.rs @@ -40,7 +40,7 @@ use std::collections::HashMap; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Arc; use std::time::{Duration, Instant}; -use wiremock::matchers::{method, path}; +use wiremock::matchers::{method, path, query_param}; use wiremock::{Mock, MockServer, Request, Respond, ResponseTemplate}; // ─── Helpers ──────────────────────────────────────────────────────── @@ -1617,19 +1617,36 @@ async fn execute_with_cloudfetch_enabled_sends_inline_or_external_links_disposit } #[tokio::test] -async fn execute_with_cloudfetch_disabled_sends_inline_disposition() { - // Regression test for issue #196. With cloudfetch_enabled=false the - // ExecuteStatement disposition must be INLINE — this is how the kernel - // (like the JDBC / Thrift reference drivers) disables cloud-fetch on - // SEA, NOT via a `can_cloud_download` session conf (which SEA rejects - // at ExecuteStatement with CONFIG_NOT_AVAILABLE). The server then - // serves results inline and the statement succeeds. +async fn execute_with_cloudfetch_disabled_supports_paged_arrow_results() { let server = MockServer::start().await; mount_create_session(&server).await; mount_delete_session(&server).await; mount_close_any_statement(&server).await; let batch = int64_batch("n", vec![7]); - mount_execute(&server, succeeded_inline_body("stmt-cf-off", &batch)).await; + let mut body: serde_json::Value = + serde_json::from_str(&succeeded_inline_body("stmt-cf-off", &batch)).unwrap(); + body["manifest"] + .as_object_mut() + .unwrap() + .remove("total_chunk_count"); + body["manifest"] + .as_object_mut() + .unwrap() + .remove("total_row_count"); + body["result"]["next_chunk_index"] = json!(1); + mount_execute(&server, body.to_string()).await; + Mock::given(method("GET")) + .and(path("/api/2.0/sql/statements/stmt-cf-off/result/chunks/1")) + .and(query_param("row_offset", "1")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "chunk_index": 1, + "row_offset": 1, + "row_count": 1, + "attachment": STANDARD.encode(arrow_ipc_bytes(&int64_batch("n", vec![8]))), + }))) + .expect(1) + .mount(&server) + .await; let mut result = ResultConfig::default(); result.cloudfetch_enabled = false; @@ -1641,6 +1658,7 @@ async fn execute_with_cloudfetch_disabled_sends_inline_disposition() { .await .expect("execute must succeed inline with cloudfetch disabled"); let batches = drain(exec.result_stream_mut()).await; + assert_eq!(batches.len(), 2); assert_eq!( batches[0] .column(0) @@ -1648,9 +1666,163 @@ async fn execute_with_cloudfetch_disabled_sends_inline_disposition() { .value(0), 7 ); + assert_eq!( + batches[1] + .column(0) + .as_primitive::() + .value(0), + 8 + ); exec.close().await.expect("close"); - assert_eq!(recorded_execute_disposition(&server).await, "INLINE"); + assert_eq!( + recorded_execute_disposition(&server).await, + "INLINE_OR_EXTERNAL_LINKS", + ); +} + +#[tokio::test] +async fn execute_with_cloudfetch_disabled_rejects_external_links_without_downloading() { + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_delete_session(&server).await; + Mock::given(method("DELETE")) + .and(path("/api/2.0/sql/statements/stmt-cf-off")) + .respond_with(ResponseTemplate::new(200).set_body_string("{}")) + .expect(1) + .mount(&server) + .await; + let batch = int64_batch("n", vec![7]); + let mut body: serde_json::Value = + serde_json::from_str(&succeeded_inline_body("stmt-cf-off", &batch)).unwrap(); + body["result"] = json!({"external_links": [{ + "external_link": format!("{}/storage/chunk.arrow", server.uri()), + "chunk_index": 0, "row_offset": 0, "row_count": 1, + "byte_count": 100, "expiration": "2099-01-01T00:00:00Z", + }]}); + mount_execute(&server, body.to_string()).await; + Mock::given(method("GET")) + .and(path("/storage/chunk.arrow")) + .respond_with(ResponseTemplate::new(500)) + .expect(0) + .mount(&server) + .await; + let mut result = ResultConfig::default(); + result.cloudfetch_enabled = false; + let session = open_session_with_result(&server, result).await; + let mut stmt = session.statement(); + stmt.spec().sql("SELECT 7 AS n"); + let error = match stmt.execute().await { + Ok(_) => panic!("external links must be rejected when CloudFetch is disabled"), + Err(error) => error, + }; + assert_eq!(error.code, ErrorCode::DataLoss); + assert!( + error.to_string().contains("CloudFetch is disabled"), + "{error}" + ); + stmt.close().await.expect("close statement"); + session.close().await.expect("close session"); + assert_eq!( + wait_for_close_delete(&server, "stmt-cf-off", 1, Duration::from_secs(2)).await, + 1, + ); +} + +#[tokio::test] +async fn cloudfetch_disabled_rejects_continuation_links_without_exposing_them() { + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_delete_session(&server).await; + mount_close_any_statement(&server).await; + let mut body: serde_json::Value = serde_json::from_str(&succeeded_inline_body( + "stmt-cf-off", + &int64_batch("n", vec![7]), + )) + .unwrap(); + body["manifest"] + .as_object_mut() + .unwrap() + .remove("total_chunk_count"); + body["manifest"] + .as_object_mut() + .unwrap() + .remove("total_row_count"); + body["result"]["next_chunk_index"] = json!(1); + mount_execute(&server, body.to_string()).await; + let storage_link = format!( + "{}/storage/chunk.arrow?signature=private-value", + server.uri() + ); + Mock::given(method("GET")) + .and(path("/api/2.0/sql/statements/stmt-cf-off/result/chunks/1")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "external_links": [{ + "external_link": storage_link, + "chunk_index": 1, "row_offset": 1, "row_count": 1, + "byte_count": 100, "expiration": "2099-01-01T00:00:00Z", + }], + }))) + .expect(1) + .mount(&server) + .await; + Mock::given(method("GET")) + .and(path("/storage/chunk.arrow")) + .respond_with(ResponseTemplate::new(500)) + .expect(0) + .mount(&server) + .await; + let mut result = ResultConfig::default(); + result.cloudfetch_enabled = false; + let session = open_session_with_result(&server, result).await; + let mut stmt = session.statement(); + stmt.spec().sql("SELECT 7 AS n"); + let mut exec = stmt.execute().await.expect("initial inline response"); + let error = loop { + match exec.result_stream_mut().next_batch().await { + Ok(Some(_)) => continue, + Ok(None) => panic!("continuation links must be rejected"), + Err(error) => break error, + } + }; + assert_eq!(error.code, ErrorCode::DataLoss); + assert!(error.to_string().contains("missing `attachment`")); + assert!(!error.to_string().contains("private-value")); + assert!(!error.to_string().contains(&storage_link)); + exec.close().await.expect("close statement"); + session.close().await.expect("close session"); +} + +#[tokio::test] +async fn cloudfetch_disabled_preserves_unsupported_server_error() { + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_delete_session(&server).await; + mount_close_any_statement(&server).await; + let mut body: serde_json::Value = serde_json::from_str(&failed_body( + "stmt-unsupported-inline", + "[CONFIG_NOT_AVAILABLE] Configuration can_cloud_download is not available", + "42K0I", + )) + .unwrap(); + body["status"]["error"]["error_code"] = json!("CONFIG_NOT_AVAILABLE"); + mount_execute(&server, body.to_string()).await; + + let mut result = ResultConfig::default(); + result.cloudfetch_enabled = false; + let session = open_session_with_result(&server, result).await; + let mut statement = session.statement(); + statement.spec().sql("SELECT 1"); + let error = match statement.execute().await { + Ok(_) => panic!("unsupported inline delivery must fail"), + Err(error) => error, + }; + assert_eq!(error.code, ErrorCode::SqlError); + assert_eq!(error.sql_state.as_deref(), Some("42K0I")); + assert!(error.message.contains("CONFIG_NOT_AVAILABLE"), "{error}"); + assert!(error.message.contains("can_cloud_download"), "{error}"); + statement.close().await.expect("close statement"); + session.close().await.expect("close session"); } #[tokio::test] diff --git a/tests/v0_session_wiremock.rs b/tests/v0_session_wiremock.rs index d04d0629..7828051d 100644 --- a/tests/v0_session_wiremock.rs +++ b/tests/v0_session_wiremock.rs @@ -345,10 +345,6 @@ async fn open_session_with_result_cfg( .await } -/// Assert that the recorded CreateSession request carries no -/// `can_cloud_download`-shaped key under any casing. Shared by the tests -/// below which prove the typed CloudFetch toggle does not synthesize this -/// session conf. async fn assert_no_can_cloud_download_on_create(server: &MockServer) { let recorded = server .received_requests() @@ -367,9 +363,7 @@ async fn assert_no_can_cloud_download_on_create(server: &MockServer) { for key in obj.keys() { assert!( !key.eq_ignore_ascii_case("can_cloud_download"), - "CreateSession must not carry a can_cloud_download session conf \ - (SEA rejects it at ExecuteStatement, issue #196); found key={key:?} \ - value={:?}", + "unexpected session setting: key={key:?} value={:?}", obj.get(key), ); } @@ -392,15 +386,7 @@ async fn create_session_body(server: &MockServer) -> serde_json::Value { } #[tokio::test] -async fn create_session_with_cloudfetch_disabled_omits_can_cloud_download() { - // Regression test for issue #196. Disabling CloudFetch - // (`cloudfetch_enabled = false`) must NOT synthesise a - // `can_cloud_download` session conf on CreateSession — SEA has no - // such conf and rejects it at the first ExecuteStatement with - // CONFIG_NOT_AVAILABLE, making the session unusable. The disable is - // instead applied per-statement via the SEA `disposition` (covered in - // the execute-path wiremock tests). Here we only assert the session - // opens and the poisoned conf never reaches the wire. +async fn create_session_with_cloudfetch_disabled_requests_inline_results() { let server = MockServer::start().await; Mock::given(method("POST")) .and(path("/api/2.0/sql/warehouses/test_wh/sessions")) @@ -414,12 +400,31 @@ async fn create_session_with_cloudfetch_disabled_omits_can_cloud_download() { let mut result = ResultConfig::default(); result.cloudfetch_enabled = false; - let session = open_session_with_result_cfg(&server, result) + let session = Session::builder() + .connection( + ConnectionConfig::from_http_path(server.uri(), "/sql/1.0/warehouses/test_wh").unwrap(), + ) + .auth(AuthConfig::Pat { + token: "dapi_test_token".into(), + identity_federation_client_id: None, + }) + .result(result) + .session_conf(std::collections::HashMap::from([ + ("Can_Cloud_Download".into(), "true".into()), + ("TIMEZONE".into(), "UTC".into()), + ])) + .open() .await .expect("session open with cloudfetch_enabled=false"); assert_eq!(session.session_id(), "sess-cf-off"); + let body = create_session_body(&server).await; + assert!(body["session_confs"].get("Can_Cloud_Download").is_none()); + assert_eq!(body["session_confs"]["TIMEZONE"], "UTC"); - assert_no_can_cloud_download_on_create(&server).await; + assert_eq!( + body.pointer("/session_confs/can_cloud_download"), + Some(&serde_json::json!("false")), + ); } #[tokio::test] @@ -608,9 +613,6 @@ async fn typed_geospatial_config_does_not_reinterpret_raw_session_conf() { #[tokio::test] async fn create_session_with_cloudfetch_enabled_omits_can_cloud_download() { - // The default (cloudfetch_enabled=true) path must also never send a - // `can_cloud_download` session conf — the kernel synthesises nothing - // here on either branch now. let server = MockServer::start().await; Mock::given(method("POST")) .and(path("/api/2.0/sql/warehouses/test_wh/sessions"))