From 2bfff99ab9d777867ad013d8527e4baf03a1b9aa Mon Sep 17 00:00:00 2001 From: Vikrant Puppala Date: Mon, 10 Aug 2026 08:51:58 +0000 Subject: [PATCH] fix(cloudfetch): disable via per-statement disposition, not session conf MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Setting `ResultConfig::cloudfetch_enabled = false` made the session unusable: the kernel synthesised a `CAN_CLOUD_DOWNLOAD=false` SEA session conf at CreateSession, which the server accepts at session create but then rejects at the first ExecuteStatement with `[CONFIG_NOT_AVAILABLE] ... SQLSTATE: 42K0I`. SEA has no such session conf. Both the JDBC and Thrift reference drivers control cloud-fetch per request, never via session conf — JDBC's SEA path (`DatabricksSdkClient.getRequest`) picks `disposition = cloudFetch ? INLINE_OR_EXTERNAL_LINKS : INLINE`, and `CAN_CLOUD_DOWNLOAD` appears nowhere in either driver. This change mirrors that: - Thread `cloudfetch_enabled` onto `TransportConfig` (a connection-level setting, read once at `Session::open`). - In `call_execute_api`, select `disposition = INLINE` when disabled, `INLINE_OR_EXTERNAL_LINKS` when enabled. `format` stays `ARROW_STREAM` (the kernel's inline reader consumes Arrow IPC from the response attachment). - Remove the `can_cloud_download` session-conf synthesis in `Session::open` entirely. - Drop `CAN_CLOUD_DOWNLOAD` from the session-conf allowlist so a stray caller-supplied value is filtered out (with a warn) rather than forwarded to the wire where it would poison the session. The result-reader factory already dispatches on what the server returns (attachment -> inline reader), so no reader change is needed. Tests: - New execute-path wiremock tests assert the disposition per `cloudfetch_enabled` (INLINE vs INLINE_OR_EXTERNAL_LINKS); the disabled case is the reproduction that failed before the fix. - Session-path wiremock tests rewritten to assert no `can_cloud_download` ever reaches CreateSession (default, disabled, and stray-user-supplied). - New `filter_session_conf` unit tripwire: `can_cloud_download` is dropped under any casing. Closes #196 Co-authored-by: Isaac Signed-off-by: Vikrant Puppala --- src/client/sea.rs | 36 +++- src/client/transport.rs | 30 ++- src/config.rs | 99 +++++---- src/reader/inline/mod.rs | 4 +- src/reader/inline/streaming.rs | 5 +- src/session.rs | 62 ++---- src/types/cloudfetch.rs | 4 +- src/types/sea.rs | 3 +- tests/v0_execute_wiremock.rs | 101 +++++++++- tests/v0_session_wiremock.rs | 353 ++++++--------------------------- 10 files changed, 300 insertions(+), 397 deletions(-) diff --git a/src/client/sea.rs b/src/client/sea.rs index e0a30143..b5746fa8 100644 --- a/src/client/sea.rs +++ b/src/client/sea.rs @@ -439,16 +439,37 @@ 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 request_body = ExecuteStatementRequest { warehouse_id: self.warehouse_id.clone(), statement: sql.to_string(), session_id: Some(session_id.to_string()), catalog: params.catalog.clone(), schema: params.schema.clone(), - // TODO: INLINE_OR_EXTERNAL_LINKS is not a public API disposition but enables - // returning all chunk links in a single response (requires JDBC user agent). - // Once EXTERNAL_LINKS supports multi-link responses, switch back to it. - disposition: "INLINE_OR_EXTERNAL_LINKS".to_string(), + disposition: disposition.to_string(), format: "ARROW_STREAM".to_string(), wait_timeout: params.wait_timeout.clone(), on_wait_timeout: params.on_wait_timeout.clone(), @@ -1052,12 +1073,13 @@ 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 session conf didn't take effect server-side). + // (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 can_cloud_download session \ - conf and returned a CloudFetch response. Body: {}", + server may have ignored the INLINE disposition and \ + returned a CloudFetch response. Body: {}", chunk_index, body )) })?; diff --git a/src/client/transport.rs b/src/client/transport.rs index a1f7afdf..1a2515e7 100644 --- a/src/client/transport.rs +++ b/src/client/transport.rs @@ -46,6 +46,26 @@ pub(crate) struct TransportConfig { pub poll_timeout: Duration, /// Interval between status polls (default: 500ms). pub poll_interval: Duration, + /// 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`). + pub cloudfetch_enabled: bool, } impl Default for TransportConfig { @@ -53,6 +73,8 @@ impl Default for TransportConfig { Self { poll_timeout: Duration::from_secs(600), poll_interval: Duration::from_millis(500), + // Mirror `ResultConfig::default().cloudfetch_enabled`. + cloudfetch_enabled: true, } } } @@ -342,10 +364,10 @@ pub(crate) trait Transport: Send + Sync + std::fmt::Debug { /// `row_offset`). /// /// Used by the inline-Arrow streaming path that lights up when - /// `ResultConfig.cloudfetch_enabled == false` (i.e. SEA's - /// `can_cloud_download=false` session conf). The server-side - /// response for this path carries Arrow IPC bytes inline in - /// `attachment` rather than emitting `external_links`. + /// `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 + /// in `attachment` rather than emitting `external_links`. /// /// Per the bounded SEA API contract for OSS drivers: /// - `chunk_index` is derived from the *previous* chunk's diff --git a/src/config.rs b/src/config.rs index ac66b516..fa8b9b67 100644 --- a/src/config.rs +++ b/src/config.rs @@ -820,12 +820,18 @@ pub struct ResultConfig { /// large result sets via presigned URLs). Default: `true`. /// /// Setting this to `false` mirrors JDBC's `EnableQueryResultDownload=0` - /// behaviour. At session-create time the kernel sets the - /// `can_cloud_download` session conf to `"false"` so SEA serves - /// **all** result sizes via the inline-Arrow path, regardless of - /// result size — see the SEA inline-Arrow design (DD1) for the wire - /// contract. Users who need inline-only behaviour (e.g. workspaces - /// without cloud-storage egress) should set this to `false`. + /// 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** @@ -967,31 +973,26 @@ pub struct SessionConfig { /// the *client-side* knobs; this map carries everything else. /// /// The kernel passes user-supplied entries through unchanged, - /// **except** for keys synthesised from typed client-side - /// knobs that have a wire counterpart: - /// - /// - [`ResultConfig::cloudfetch_enabled`] `= false` synthesises - /// `can_cloud_download = "false"` (case-insensitive on the - /// key) so SEA serves results inline. If the user already - /// supplied a non-empty `can_cloud_download` value under - /// any casing, the user's value wins and no synthesis - /// happens. The synthesis path also purges empty-string - /// case-variants the user may have left in the map (the - /// server's behaviour for empty values is undefined) so the - /// wire body carries at most one `can_cloud_download`-shaped - /// key. + /// after filtering them against the kernel allowlist (see + /// [`filter_session_conf`] / [`SESSION_CONF_ALLOWLIST`]). The + /// kernel does not synthesise any entries here from typed + /// client-side knobs. /// - /// Future typed-knob → session_conf synthesis follows the - /// same pattern (the wrapping `inject_default(...)` helper can - /// be lifted out once a second knob lands here). + /// 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 stray caller-supplied `can_cloud_download` is dropped + /// by [`filter_session_conf`] (it is not allowlisted). /// - /// **Boolean-valued conf keys** (e.g. `can_cloud_download`) - /// should use the exact strings `"true"` / `"false"`. SEA - /// accepts these literally; other forms (`"True"`, `"yes"`, - /// `"1"`) either fail at session-create or behave as - /// undefined on the server. The kernel does not pre-validate - /// — its posture is "trust the user's session_conf" — so - /// non-canonical values flow to the server as-is. + /// **Boolean-valued conf keys** should use the exact strings + /// `"true"` / `"false"`. SEA accepts these literally; other forms + /// (`"True"`, `"yes"`, `"1"`) either fail at session-create or + /// behave as undefined on the server. The kernel does not + /// pre-validate — its posture is "trust the user's session_conf" — + /// so non-canonical values flow to the server as-is. pub session_conf: HashMap, pub http: HttpConfig, @@ -1014,13 +1015,15 @@ pub struct SessionConfig { /// and uppercased before being sent. pub(crate) const SESSION_CONF_ALLOWLIST: &[&str] = &[ "ANSI_MODE", - // `CAN_CLOUD_DOWNLOAD` is the kernel-synthesised flag (set by - // `Session::open` when `ResultConfig::cloudfetch_enabled = false`) - // telling SEA to serve every result via the inline-Arrow path. - // Listed here so a user-supplied value (with any casing) survives - // the allowlist filter and so the kernel's own synthesis passes - // through normalisation without special-casing. - "CAN_CLOUD_DOWNLOAD", + // NOTE: `CAN_CLOUD_DOWNLOAD` is deliberately NOT allowlisted. SEA has + // no such session conf — it is accepted at CreateSession but rejected + // at the first ExecuteStatement with `CONFIG_NOT_AVAILABLE` (issue + // #196). CloudFetch-disable is expressed per-statement via the SEA + // `disposition` (see `SeaRestTransport::call_execute_api` and + // `TransportConfig::cloudfetch_enabled`), matching both the JDBC and + // Thrift reference drivers. A stray caller-supplied `can_cloud_download` + // is therefore dropped by `filter_session_conf` (with a warn) rather + // than forwarded to the wire where it would break the session. "COLLATION", "ENABLE_PHOTON", "LEGACY_TIME_PARSER_POLICY", @@ -1227,6 +1230,30 @@ mod tests { assert_eq!(out.get("TIMEZONE").map(String::as_str), Some("UTC")); } + #[test] + fn session_conf_filter_drops_can_cloud_download() { + // Regression tripwire for issue #196: `can_cloud_download` is NOT a + // valid SEA session conf (the server rejects it at ExecuteStatement + // with CONFIG_NOT_AVAILABLE). It must be dropped by the allowlist + // filter — never forwarded to the wire — regardless of casing. + // CloudFetch-disable is applied per-statement via the SEA + // disposition instead. If someone re-adds it to the allowlist, this + // test flips RED. + for spelling in [ + "can_cloud_download", + "CAN_CLOUD_DOWNLOAD", + "Can_Cloud_Download", + ] { + let mut raw = std::collections::HashMap::new(); + raw.insert(spelling.to_string(), "false".to_string()); + let out = filter_session_conf(raw); + assert!( + out.is_empty(), + "can_cloud_download ({spelling:?}) must be dropped, got {out:?}" + ); + } + } + #[test] fn session_conf_filter_passes_metricview_conf_verbatim() { // The metric-view conf is a dotted spark.* key: it must survive diff --git a/src/reader/inline/mod.rs b/src/reader/inline/mod.rs index f859e45c..24b3dd4d 100644 --- a/src/reader/inline/mod.rs +++ b/src/reader/inline/mod.rs @@ -30,8 +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 -//! (`can_cloud_download=false` session conf) and the result is +//! 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. mod provider; diff --git a/src/reader/inline/streaming.rs b/src/reader/inline/streaming.rs index 59909e2a..fad6cf68 100644 --- a/src/reader/inline/streaming.rs +++ b/src/reader/inline/streaming.rs @@ -14,8 +14,9 @@ //! `InlineStreamingProvider` — rolling-window prefetch for multi-chunk inline Arrow. //! -//! Lights up when the session has `can_cloud_download = false`. The -//! server returns chunks one at a time via `GET /result/chunks/{idx}` +//! Lights up when CloudFetch is disabled (`cloudfetch_enabled = false`, +//! i.e. the execute request was sent with SEA `disposition = INLINE`). +//! 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 //! consumer so the per-chunk SEA round-trip latency is hidden behind diff --git a/src/session.rs b/src/session.rs index d4ba714c..55f4cc1b 100644 --- a/src/session.rs +++ b/src/session.rs @@ -279,7 +279,15 @@ impl Session { // OnceLock::set. So: construct, wrap in Arc, build factory, // install factory. let defaults = config.defaults.clone().unwrap_or_default(); - let transport_config = TransportConfig::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() + }; let sea = Arc::new(SeaRestTransport::new( http_client.clone(), host.clone(), @@ -303,54 +311,18 @@ impl Session { "creating session" ); - // When CloudFetch is disabled at the kernel layer, advertise this - // capability to SEA via the `can_cloud_download` session conf. - // Per the SEA inline-Arrow design (go/inline-arrow-sea, DD1), this - // tells the server to fall back to the inline-Arrow path for all - // result sizes instead of attempting cloud-fetch and erroring at - // fetch time. - // - // Don't clobber an explicit non-empty user value — if the caller - // wired `can_cloud_download` directly via `session_conf` for any - // reason (e.g., to force inline-Arrow even with CloudFetch enabled - // at the kernel layer), their value wins. - // - // **Case-insensitive key match** because SEA session-conf keys - // are historically case-insensitive on the wire; without this, a - // stray `"Can_Cloud_Download"` from the user would coexist with - // the kernel's canonical-cased `"can_cloud_download"` and we'd - // ship both keys (potentially with different values) — server - // would pick one non-deterministically. - // - // **Empty-string user values are purged**: an empty value is - // ambiguous (server behaviour undefined) and the kernel prefers - // to inject its canonical `"false"` instead of shipping the - // ambiguous empty. Purge-then-insert guarantees the wire body - // carries at most one `can_cloud_download` key regardless of - // case-variants the caller supplied. - let mut session_conf = config.session_conf.clone(); - if !config.result.cloudfetch_enabled { - let has_nonempty_user_value = session_conf - .iter() - .any(|(k, v)| k.eq_ignore_ascii_case("can_cloud_download") && !v.is_empty()); - crate::klog::debug!( - cloudfetch_enabled = false, - user_value_present = has_nonempty_user_value, - "evaluating can_cloud_download injection", - ); - if !has_nonempty_user_value { - // Drop every case-variant (including empty-value ones) - // before inserting the canonical key so we can't ship - // duplicates that differ only in case. - session_conf.retain(|k, _| !k.eq_ignore_ascii_case("can_cloud_download")); - session_conf.insert("can_cloud_download".to_string(), "false".to_string()); - } - } + // CloudFetch-disable is expressed per-statement via the SEA + // `disposition` (threaded onto `TransportConfig` above), NOT via a + // session conf: SEA has no `CAN_CLOUD_DOWNLOAD` conf — sending one + // is accepted at CreateSession but rejected at the first + // ExecuteStatement with `CONFIG_NOT_AVAILABLE` (issue #196). So the + // user's `session_conf` flows to CreateSession untouched; the + // kernel synthesises nothing here. let session_info = transport .create_session( defaults.catalog.as_deref(), defaults.schema.as_deref(), - crate::config::filter_session_conf(session_conf), + crate::config::filter_session_conf(config.session_conf.clone()), ) .await?; diff --git a/src/types/cloudfetch.rs b/src/types/cloudfetch.rs index c18fd452..56406ed9 100644 --- a/src/types/cloudfetch.rs +++ b/src/types/cloudfetch.rs @@ -55,8 +55,8 @@ pub struct CloudFetchConfig { /// 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 at the session level via - /// `can_cloud_download=false`). Analogue of + /// (used when CloudFetch is disabled, i.e. the execute request is + /// sent with SEA `disposition = INLINE`). 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 b4d17e19..0f870bbd 100644 --- a/src/types/sea.rs +++ b/src/types/sea.rs @@ -428,7 +428,8 @@ pub struct GetChunksResponse { /// 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 session was opened with `can_cloud_download=false`. + /// the execute request was sent with SEA `disposition = INLINE` + /// (`cloudfetch_enabled = false`). #[serde(default, deserialize_with = "deserialize_base64_attachment")] pub attachment: Option>, } diff --git a/tests/v0_execute_wiremock.rs b/tests/v0_execute_wiremock.rs index 5756c1ed..34d4a474 100644 --- a/tests/v0_execute_wiremock.rs +++ b/tests/v0_execute_wiremock.rs @@ -26,8 +26,8 @@ use arrow_ipc::writer::StreamWriter; use arrow_schema::{DataType, Field, Schema}; use base64::{engine::general_purpose::STANDARD, Engine}; use databricks_sql_kernel::{ - AuthConfig, ConnectionConfig, ErrorCode, ExecutedStatementHandle, ResultBatch, Session, - TypedValue, + AuthConfig, ConnectionConfig, ErrorCode, ExecutedStatementHandle, ResultBatch, ResultConfig, + Session, TypedValue, }; use serde_json::json; use std::sync::Arc; @@ -50,6 +50,41 @@ async fn open_session(server: &MockServer) -> Session { .expect("Session::open should succeed") } +/// Open a session with a custom [`ResultConfig`]. Used by the +/// disposition tests below to drive `cloudfetch_enabled`. +async fn open_session_with_result(server: &MockServer, result: ResultConfig) -> Session { + Session::builder() + .connection( + ConnectionConfig::from_http_path(server.uri(), "/sql/1.0/warehouses/test_wh") + .expect("valid http_path"), + ) + .auth(AuthConfig::Pat { + token: "dapi_test_token".into(), + }) + .result(result) + .open() + .await + .expect("Session::open should succeed") +} + +/// Read the `disposition` sent on the recorded POST /statements request. +async fn recorded_execute_disposition(server: &MockServer) -> String { + let recorded = server + .received_requests() + .await + .expect("wiremock received_requests must be available"); + let exec = recorded + .iter() + .find(|r| r.url.path() == "/api/2.0/sql/statements" && r.method.as_str() == "POST") + .expect("a POST /statements request was made"); + let body: serde_json::Value = + serde_json::from_slice(&exec.body).expect("execute body must be valid JSON"); + body.get("disposition") + .and_then(|v| v.as_str()) + .expect("execute request must carry a disposition") + .to_string() +} + async fn mount_create_session(server: &MockServer) { Mock::given(method("POST")) .and(path("/api/2.0/sql/sessions")) @@ -295,6 +330,68 @@ async fn execute_succeeded_inline_returns_one_row() { exec.close().await.expect("close"); } +#[tokio::test] +async fn execute_with_cloudfetch_enabled_sends_inline_or_external_links_disposition() { + // Default (cloudfetch_enabled=true): the ExecuteStatement disposition + // must be INLINE_OR_EXTERNAL_LINKS so the server may return CloudFetch + // external links. + 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![1]); + mount_execute(&server, succeeded_inline_body("stmt-cf-on", &batch)).await; + + let session = open_session(&server).await; + let mut stmt = session.statement(); + stmt.spec().sql("SELECT 1 AS n"); + let mut exec = stmt.execute().await.expect("execute"); + drain(exec.result_stream_mut()).await; + exec.close().await.expect("close"); + + assert_eq!( + recorded_execute_disposition(&server).await, + "INLINE_OR_EXTERNAL_LINKS", + ); +} + +#[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. + 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 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("execute must succeed inline with cloudfetch disabled"); + let batches = drain(exec.result_stream_mut()).await; + assert_eq!( + batches[0] + .column(0) + .as_primitive::() + .value(0), + 7 + ); + exec.close().await.expect("close"); + + assert_eq!(recorded_execute_disposition(&server).await, "INLINE"); +} + #[tokio::test] async fn execute_running_then_succeeded_polls_status() { let server = MockServer::start().await; diff --git a/tests/v0_session_wiremock.rs b/tests/v0_session_wiremock.rs index 5a9b7f07..f736cba8 100644 --- a/tests/v0_session_wiremock.rs +++ b/tests/v0_session_wiremock.rs @@ -30,7 +30,7 @@ use databricks_sql_kernel::{ AuthConfig, ConnectionConfig, ErrorCode, HttpConfig, ResultConfig, Session, }; -use wiremock::matchers::{body_partial_json, method, path, query_param}; +use wiremock::matchers::{method, path, query_param}; use wiremock::{Mock, MockServer, ResponseTemplate}; /// Open a session against `mock_server` using a PAT auth provider. @@ -341,296 +341,88 @@ async fn open_session_with_result_cfg( .await } -#[tokio::test] -async fn create_session_with_cloudfetch_disabled_sends_can_cloud_download_false() { - // Per the SEA inline-Arrow design (go/inline-arrow-sea, DD1), when - // the kernel-level `cloudfetch_enabled` flag is false we forward - // `can_cloud_download: "false"` in `session_configuration` so SEA - // routes the session to the inline-Arrow path. - let server = MockServer::start().await; - Mock::given(method("POST")) - .and(path("/api/2.0/sql/sessions")) - .and(body_partial_json(serde_json::json!({ - "session_confs": { "CAN_CLOUD_DOWNLOAD": "false" } - }))) - .respond_with( - ResponseTemplate::new(200) - .set_body_string(r#"{"session_id":"sess-cf-off","warehouse_id":"test_wh"}"#), - ) - .expect(1) - .mount(&server) - .await; - - let mut result = ResultConfig::default(); - result.cloudfetch_enabled = false; - let session = open_session_with_result_cfg(&server, result) - .await - .expect("session open with cloudfetch_enabled=false"); - assert_eq!(session.session_id(), "sess-cf-off"); -} - -#[tokio::test] -async fn create_session_respects_user_supplied_can_cloud_download() { - // If the caller explicitly wired `can_cloud_download` via session - // conf (e.g., to force inline-Arrow even with CloudFetch enabled - // at the kernel layer), the kernel must NOT override that value. - let server = MockServer::start().await; - Mock::given(method("POST")) - .and(path("/api/2.0/sql/sessions")) - .and(body_partial_json(serde_json::json!({ - "session_confs": { "CAN_CLOUD_DOWNLOAD": "true" } - }))) - .respond_with( - ResponseTemplate::new(200) - .set_body_string(r#"{"session_id":"sess-explicit","warehouse_id":"test_wh"}"#), - ) - .expect(1) - .mount(&server) - .await; - - // cloudfetch_enabled=false would normally inject - // can_cloud_download="false". But the user has explicitly set - // "true" via session_conf; the kernel must yield to the user. - let mut session_conf = std::collections::HashMap::new(); - session_conf.insert("can_cloud_download".to_string(), "true".to_string()); - let mut result = ResultConfig::default(); - result.cloudfetch_enabled = false; - let session = Session::builder() - .connection( - ConnectionConfig::from_http_path(server.uri(), "/sql/1.0/warehouses/test_wh") - .expect("valid http_path"), - ) - .auth(AuthConfig::Pat { - token: "dapi_test_token".into(), - }) - .result(result) - .session_conf(session_conf) - .open() - .await - .expect("session must open with user-supplied conf"); - assert_eq!(session.session_id(), "sess-explicit"); -} - -#[tokio::test] -async fn create_session_respects_user_value_case_insensitively() { - // If the caller passes the key with a non-canonical case (e.g. - // `Can_Cloud_Download`), the kernel must recognise it as an - // already-set value and NOT inject a second `can_cloud_download` - // alongside. Otherwise both keys would land in the wire body and - // the server's last-write-wins behaviour would be a coin flip. - // - // Note on key casing: `filter_session_conf` uppercases every - // allowlisted key (the wire normalisation that PR #80 added), so - // the key on the wire is `CAN_CLOUD_DOWNLOAD` regardless of what - // the user supplied — but the user's *value* survives because - // we detect "already set" case-insensitively before injecting. - let server = MockServer::start().await; - Mock::given(method("POST")) - .and(path("/api/2.0/sql/sessions")) - .respond_with( - ResponseTemplate::new(200) - .set_body_string(r#"{"session_id":"sess-case","warehouse_id":"test_wh"}"#), - ) - .mount(&server) - .await; - - let mut session_conf = std::collections::HashMap::new(); - session_conf.insert("Can_Cloud_Download".to_string(), "true".to_string()); - let mut result = ResultConfig::default(); - result.cloudfetch_enabled = false; - Session::builder() - .connection( - ConnectionConfig::from_http_path(server.uri(), "/sql/1.0/warehouses/test_wh") - .expect("valid http_path"), - ) - .auth(AuthConfig::Pat { - token: "dapi_test_token".into(), - }) - .result(result) - .session_conf(session_conf) - .open() +/// Assert that the recorded CreateSession request carries no +/// `can_cloud_download`-shaped key under any casing. Shared by the tests +/// below, which each drive a different `cloudfetch_enabled` / +/// `session_conf` combination — all of which must keep this key off the +/// CreateSession wire (issue #196: SEA has no such session conf). +async fn assert_no_can_cloud_download_on_create(server: &MockServer) { + let recorded = server + .received_requests() .await - .expect("session must open"); - - // Verify the wire request contains exactly one - // can_cloud_download-shaped key, post-uppercase, carrying the - // user-supplied value `"true"`. A regression that double-inserts - // would either produce a second key or override the value to - // `"false"`. - let recorded = server.received_requests().await.unwrap(); + .expect("server must have request log enabled"); let create = recorded .iter() - .find(|r| r.url.path() == "/api/2.0/sql/sessions") - .unwrap(); - let body: serde_json::Value = serde_json::from_slice(&create.body).unwrap(); - let session_conf_obj = body - .get("session_confs") - .and_then(|v| v.as_object()) - .expect("session_confs present"); - let matches: Vec<(&String, &serde_json::Value)> = session_conf_obj - .iter() - .filter(|(k, _)| k.eq_ignore_ascii_case("can_cloud_download")) - .collect(); - assert_eq!( - matches.len(), - 1, - "exactly one can_cloud_download-shaped key must be present; got {matches:?}", - ); - let (key, value) = matches[0]; - assert_eq!( - key, "CAN_CLOUD_DOWNLOAD", - "the allowlist filter uppercases the key on the wire", - ); - assert_eq!( - value.as_str(), - Some("true"), - "the user-supplied value must survive the injection check", - ); + .find(|r| r.url.path() == "/api/2.0/sql/sessions" && r.method.as_str() == "POST") + .expect("a POST /sessions request was made"); + let body: serde_json::Value = + serde_json::from_slice(&create.body).expect("create-session body must be valid JSON"); + if let Some(obj) = body.get("session_confs").and_then(|v| v.as_object()) { + 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={:?}", + obj.get(key), + ); + } + } } #[tokio::test] -async fn create_session_empty_user_value_is_overridden() { - // SEA session-conf semantics for empty-string values are - // undefined, so the kernel treats an explicit empty value as - // "not set" and falls back to injecting its canonical - // `"false"`. This avoids shipping an ambiguous empty string on - // the wire. +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. let server = MockServer::start().await; Mock::given(method("POST")) .and(path("/api/2.0/sql/sessions")) - .and(body_partial_json(serde_json::json!({ - "session_confs": { "CAN_CLOUD_DOWNLOAD": "false" } - }))) .respond_with( ResponseTemplate::new(200) - .set_body_string(r#"{"session_id":"sess-empty","warehouse_id":"test_wh"}"#), + .set_body_string(r#"{"session_id":"sess-cf-off","warehouse_id":"test_wh"}"#), ) .expect(1) .mount(&server) .await; - let mut session_conf = std::collections::HashMap::new(); - session_conf.insert("can_cloud_download".to_string(), "".to_string()); - let mut result = ResultConfig::default(); - result.cloudfetch_enabled = false; - Session::builder() - .connection( - ConnectionConfig::from_http_path(server.uri(), "/sql/1.0/warehouses/test_wh") - .expect("valid http_path"), - ) - .auth(AuthConfig::Pat { - token: "dapi_test_token".into(), - }) - .result(result) - .session_conf(session_conf) - .open() - .await - .expect("session must open"); -} - -#[tokio::test] -async fn create_session_noncanonical_case_with_empty_value_purges_and_injects() { - // Cross-product cell of the case-insensitive / empty-value - // matrix: user passes `"Can_Cloud_Download" -> ""` with - // CloudFetch disabled. The kernel must: - // 1. Recognise the value is empty (treat it as "not set"). - // 2. Purge the case-variant before injecting the canonical - // key — otherwise BOTH `Can_Cloud_Download: ""` and - // `can_cloud_download: "false"` ship in the wire body - // and the server picks one non-deterministically. - // Asserts the recorded body has exactly one - // can_cloud_download-shaped key whose value is `"false"`. - let server = MockServer::start().await; - Mock::given(method("POST")) - .and(path("/api/2.0/sql/sessions")) - .respond_with( - ResponseTemplate::new(200) - .set_body_string(r#"{"session_id":"sess-cross","warehouse_id":"test_wh"}"#), - ) - .mount(&server) - .await; - - let mut session_conf = std::collections::HashMap::new(); - session_conf.insert("Can_Cloud_Download".to_string(), "".to_string()); let mut result = ResultConfig::default(); result.cloudfetch_enabled = false; - Session::builder() - .connection( - ConnectionConfig::from_http_path(server.uri(), "/sql/1.0/warehouses/test_wh") - .expect("valid http_path"), - ) - .auth(AuthConfig::Pat { - token: "dapi_test_token".into(), - }) - .result(result) - .session_conf(session_conf) - .open() + let session = open_session_with_result_cfg(&server, result) .await - .expect("session must open"); + .expect("session open with cloudfetch_enabled=false"); + assert_eq!(session.session_id(), "sess-cf-off"); - let recorded = server.received_requests().await.unwrap(); - let create = recorded - .iter() - .find(|r| r.url.path() == "/api/2.0/sql/sessions") - .unwrap(); - let body: serde_json::Value = serde_json::from_slice(&create.body).unwrap(); - let session_conf_obj = body - .get("session_confs") - .and_then(|v| v.as_object()) - .expect("session_confs present"); - let matches: Vec<(&String, &serde_json::Value)> = session_conf_obj - .iter() - .filter(|(k, _)| k.eq_ignore_ascii_case("can_cloud_download")) - .collect(); - assert_eq!( - matches.len(), - 1, - "exactly one can_cloud_download-shaped key must be present after \ - purge-and-inject; got {matches:?}", - ); - let (key, value) = matches[0]; - assert_eq!( - key, "CAN_CLOUD_DOWNLOAD", - "the allowlist filter uppercases the kernel-injected key on the wire", - ); - assert_eq!( - value.as_str(), - Some("false"), - "the kernel must have injected the canonical \"false\" value", - ); + assert_no_can_cloud_download_on_create(&server).await; } #[tokio::test] -async fn create_session_with_cloudfetch_enabled_respects_user_inline_request() { - // Mirror of `create_session_respects_user_supplied_can_cloud_download`. - // Setup: kernel CloudFetch ENABLED, but the user explicitly wants - // inline-Arrow (sets `can_cloud_download=false` themselves). The - // kernel must not strip the user's value — `session_conf` is the - // user's wire surface and the kernel only ever *injects* on the - // `!cloudfetch_enabled` branch, never overrides. +async fn create_session_drops_user_supplied_can_cloud_download() { + // A caller-supplied `can_cloud_download` (any value, any casing) is + // NOT a valid SEA session conf, so `filter_session_conf` drops it — + // it must never reach the CreateSession wire where it would poison + // every subsequent ExecuteStatement (issue #196). The session still + // opens; the stray key is silently dropped with a warn. let server = MockServer::start().await; Mock::given(method("POST")) .and(path("/api/2.0/sql/sessions")) - .and(body_partial_json(serde_json::json!({ - "session_confs": { "CAN_CLOUD_DOWNLOAD": "false" } - }))) .respond_with( ResponseTemplate::new(200) - .set_body_string(r#"{"session_id":"sess-mirror","warehouse_id":"test_wh"}"#), + .set_body_string(r#"{"session_id":"sess-dropped","warehouse_id":"test_wh"}"#), ) .expect(1) .mount(&server) .await; let mut session_conf = std::collections::HashMap::new(); - session_conf.insert("can_cloud_download".to_string(), "false".to_string()); - // cloudfetch_enabled defaults to true; user is overriding to inline. - let result = ResultConfig::default(); - assert!( - result.cloudfetch_enabled, - "test prereq: ResultConfig defaults to cloudfetch_enabled=true", - ); - Session::builder() + // Non-canonical casing to also exercise the case-insensitive match. + session_conf.insert("Can_Cloud_Download".to_string(), "true".to_string()); + let session = Session::builder() .connection( ConnectionConfig::from_http_path(server.uri(), "/sql/1.0/warehouses/test_wh") .expect("valid http_path"), @@ -638,26 +430,20 @@ async fn create_session_with_cloudfetch_enabled_respects_user_inline_request() { .auth(AuthConfig::Pat { token: "dapi_test_token".into(), }) - .result(result) .session_conf(session_conf) .open() .await - .expect("session must open"); + .expect("session must open even with a stray can_cloud_download"); + assert_eq!(session.session_id(), "sess-dropped"); + + assert_no_can_cloud_download_on_create(&server).await; } #[tokio::test] async fn create_session_with_cloudfetch_enabled_omits_can_cloud_download() { - // The default (cloudfetch_enabled=true) path must NOT inject - // `can_cloud_download` — silently sending it would tell SEA to - // serve every query inline, which would regress the CloudFetch - // concurrent download pipeline for the kernel's primary use case. - // - // We assert this by inspecting the recorded request body and - // verifying that `session_configuration` does NOT contain a - // `can_cloud_download` field with **any** value (not just - // "false"). A regression that injected `"true"` would be just - // as wrong, so the previous one-sided `.expect(0)` check on - // `{"can_cloud_download": "false"}` alone wasn't enough. + // 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/sessions")) @@ -678,30 +464,5 @@ async fn create_session_with_cloudfetch_enabled_omits_can_cloud_download() { .expect("session open with default ResultConfig"); assert_eq!(session.session_id(), "sess-cf-on"); - // Inspect the actual recorded request body to confirm the - // can_cloud_download key is absent regardless of value. - let recorded = server - .received_requests() - .await - .expect("server must have request log enabled"); - let create_session_req = recorded - .iter() - .find(|r| r.url.path() == "/api/2.0/sql/sessions" && r.method.as_str() == "POST") - .expect("a POST /sessions request was made"); - let body: serde_json::Value = serde_json::from_slice(&create_session_req.body) - .expect("create-session body must be valid JSON"); - let session_conf = body - .get("session_confs") - .cloned() - .unwrap_or(serde_json::Value::Null); - if let Some(obj) = session_conf.as_object() { - for key in obj.keys() { - assert!( - !key.eq_ignore_ascii_case("can_cloud_download"), - "session_configuration must not contain a can_cloud_download key on the \ - default path; found key={key:?} value={:?}", - obj.get(key), - ); - } - } + assert_no_can_cloud_download_on_create(&server).await; }