Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions NEXT_CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ changes go in their respective binding's NEXT_CHANGELOG.
### Fixed

- `Session::open` authenticates once before resolving feature flags. A failed OAuth token request now fails the open immediately instead of being sent a second time by CreateSession.
- With CloudFetch disabled, sessions open again on warehouses that reject the `can_cloud_download` session setting (Lakehouse Real-Time). Those sessions request `INLINE` results, as 1.4.0 did, so results over the 25 MiB inline limit fail.

---
*Note: When making changes, please add your change under the appropriate
Expand Down
128 changes: 107 additions & 21 deletions src/client/sea.rs
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,10 @@ pub(crate) struct SeaRestTransport {
config: TransportConfig,
session_route: OnceLock<SessionRoute>,
session_version: AtomicI64,
/// Set when CloudFetch is disabled and the warehouse rejected the
/// `can_cloud_download` session conf (Reyden does): the session then
/// requests `INLINE` results instead of paged inline results.
inline_disposition: AtomicBool,
reader_factory: OnceLock<ResultReaderFactory>,
runtime_handle: OnceLock<RuntimeHandle>,
}
Expand Down Expand Up @@ -222,6 +226,7 @@ impl SeaRestTransport {
config,
session_route: OnceLock::new(),
session_version: AtomicI64::new(NO_SESSION_VERSION),
inline_disposition: AtomicBool::new(false),
reader_factory: OnceLock::new(),
runtime_handle: OnceLock::new(),
}
Expand Down Expand Up @@ -672,7 +677,12 @@ impl SeaRestTransport {
session_version: self.current_session_version(),
catalog: params.catalog.clone(),
schema: params.schema.clone(),
disposition: "INLINE_OR_EXTERNAL_LINKS".to_string(),
disposition: if self.inline_disposition.load(Ordering::Relaxed) {
"INLINE"
} else {
"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(),
Expand Down Expand Up @@ -1057,6 +1067,16 @@ impl SeaRestTransport {
}
}

/// Whether a CreateSession error is the server rejecting the `can_cloud_download`
/// session conf itself (Reyden: `[INVALID_CONF_VALUE] The value 'false' in the
/// config "can_cloud_download" is invalid`), not merely mentioning it.
fn rejects_can_cloud_download(error: &Error) -> bool {
Comment thread
oss-reviewer-bot[bot] marked this conversation as resolved.
Resolved
Comment thread
oss-reviewer-bot[bot] marked this conversation as resolved.
Resolved
let message = error.message.to_ascii_lowercase();
error.http_status == Some(400)
&& message.contains("invalid_conf_value")
&& message.contains("config \"can_cloud_download\"")
}

/// Convert a parsed `GetChunksResponse` into the kernel-facing
/// `ChunkLinkFetchResult`. Extracted from `get_result_chunks`
/// so the continuation derivation (top-level vs per-link
Expand Down Expand Up @@ -1141,31 +1161,64 @@ impl Transport for SeaRestTransport {
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()),
schema: schema.map(|s| s.to_string()),
session_confs: session_config,
execution_mode: SessionExecutionMode::Fast,
let build_request = |session_confs: HashMap<String, String>| {
let request_body = CreateSessionRequest {
warehouse_id: None,
catalog: catalog.map(|s| s.to_string()),
schema: schema.map(|s| s.to_string()),
session_confs,
execution_mode: SessionExecutionMode::Fast,
};
self.http_client
.inner()
.request(Method::POST, &url)
.header("Content-Type", "application/json")
.json(&request_body)
.build()
.map_err(|e| {
Error::invalid_argument().message(format!("Failed to build request: {e}"))
})
};

debug!("Creating session at {}", url);

let request = self
.http_client
.inner()
.request(Method::POST, &url)
.header("Content-Type", "application/json")
.json(&request_body)
.build()
.map_err(|e| {
Error::invalid_argument().message(format!("Failed to build request: {e}"))
})?;

let response = self
let response = match self
.http_client
.execute(request, RequestType::CreateSession)
.await?;
.execute(
build_request(session_config.clone())?,
RequestType::CreateSession,
)
.await
{
Ok(response) => response,
Err(e) if !self.config.cloudfetch_enabled && rejects_can_cloud_download(&e) => {
// Reyden rejects `can_cloud_download` but serves INLINE results
// (and fails statements over the inline byte limit).
warn!(
error = %e,
"warehouse rejected can_cloud_download; using INLINE results for this session"
);
session_config.retain(|key, _| !key.eq_ignore_ascii_case("can_cloud_download"));
match self
.http_client
.execute(build_request(session_config)?, RequestType::CreateSession)
Comment thread
oss-reviewer-bot[bot] marked this conversation as resolved.
Resolved
.await
{
Ok(response) => {
self.inline_disposition.store(true, Ordering::Relaxed);
response
}
Err(mut retry_error) => {
retry_error.message = format!(
"{} (CreateSession retried without can_cloud_download after: {})",
retry_error.message, e.message
);
return Err(retry_error);
}
}
}
Err(e) => return Err(e),
};
let realtime = response
.headers()
.get(REALTIME_SESSION_HEADER)
Expand Down Expand Up @@ -2436,6 +2489,39 @@ mod tests {
}
}

#[test]
fn rejects_can_cloud_download_requires_http_400_and_names_the_setting() {
let rejection = |status: u16, message: &str| {
Error::from_http_status(status).message(format!("HTTP {status}: {message}"))
};
let reyden = r#"[INVALID_CONF_VALUE] The value 'false' in the config "can_cloud_download" is invalid."#;
assert!(rejects_can_cloud_download(&rejection(400, reyden)));
assert!(rejects_can_cloud_download(&rejection(
400,
r#"[invalid_conf_value] The value 'false' in the config "CAN_CLOUD_DOWNLOAD" is invalid."#
)));
for status in [401, 403, 404, 429, 500, 503] {
assert!(
!rejects_can_cloud_download(&rejection(status, reyden)),
"HTTP {status} must not trigger the INLINE fallback"
);
}
for other in [
r#"[INVALID_CONF_VALUE] The value 'x' in the config "TIMEZONE" is invalid."#,
// Mentions the setting, but another conf is the one rejected.
r#"[INVALID_CONF_VALUE] The value 'x' in the config "TIMEZONE" is invalid. Params: can_cloud_download=false"#,
"can_cloud_download is not supported",
] {
assert!(
!rejects_can_cloud_download(&rejection(400, other)),
"{other}"
);
}
let mut no_status = Error::invalid_argument().message(reyden);
no_status.http_status = None;
assert!(!rejects_can_cloud_download(&no_status));
}

#[test]
fn test_list_table_types() {
let client = create_test_client();
Expand Down
134 changes: 134 additions & 0 deletions tests/v0_execute_wiremock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1681,6 +1681,140 @@ async fn execute_with_cloudfetch_disabled_supports_paged_arrow_results() {
);
}

#[tokio::test]
async fn cloudfetch_disabled_falls_back_to_inline_when_warehouse_rejects_can_cloud_download() {
use wiremock::matchers::body_string_contains;
// Reyden rejects the paged-inline session conf at CreateSession; the
// session must still open and request INLINE results instead.
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/api/2.0/sql/warehouses/test_wh/sessions"))
.and(body_string_contains("can_cloud_download"))
.respond_with(ResponseTemplate::new(400).set_body_json(json!({
"error_code": "INVALID_PARAMETER_VALUE",
"message": "Invalid session params: [INVALID_CONF_VALUE] The value 'false' in the \
config \"can_cloud_download\" is invalid. SQLSTATE: 22022",
})))
.with_priority(1)
.expect(1)
.mount(&server)
.await;
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"}"#),
)
.with_priority(2)
.expect(1)
.mount(&server)
.await;
mount_delete_session(&server).await;
mount_close_any_statement(&server).await;
mount_execute(
&server,
succeeded_inline_body("stmt-inline", &int64_batch("n", vec![7])),
)
.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("inline execute");
let batches = drain(exec.result_stream_mut()).await;
assert_eq!(batches.len(), 1);
exec.close().await.expect("close");
assert_eq!(recorded_execute_disposition(&server).await, "INLINE");
session.close().await.expect("close session");
}

#[tokio::test]
async fn cloudfetch_disabled_surfaces_other_create_session_errors() {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/api/2.0/sql/warehouses/test_wh/sessions"))
.respond_with(ResponseTemplate::new(400).set_body_json(json!({
"error_code": "INVALID_PARAMETER_VALUE",
"message": "Invalid session params: [INVALID_CONF_VALUE] TIMEZONE is invalid.",
})))
.expect(1)
.mount(&server)
.await;
let mut result = ResultConfig::default();
result.cloudfetch_enabled = false;
let error = match 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)
.open()
.await
{
Ok(_) => panic!("unrelated CreateSession rejection must surface"),
Err(error) => error,
};
assert_eq!(error.http_status, Some(400));
assert!(error.message.contains("TIMEZONE"), "{error}");
}

#[tokio::test]
async fn cloudfetch_disabled_fallback_failure_reports_both_errors() {
use wiremock::matchers::body_string_contains;
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/api/2.0/sql/warehouses/test_wh/sessions"))
.and(body_string_contains("can_cloud_download"))
.respond_with(ResponseTemplate::new(400).set_body_json(json!({
"error_code": "INVALID_PARAMETER_VALUE",
"message": "Invalid session params: [INVALID_CONF_VALUE] The value 'false' in the \
config \"can_cloud_download\" is invalid. SQLSTATE: 22022",
})))
.with_priority(1)
.expect(1)
.mount(&server)
.await;
Mock::given(method("POST"))
.and(path("/api/2.0/sql/warehouses/test_wh/sessions"))
.respond_with(ResponseTemplate::new(403).set_body_json(json!({
"error_code": "PERMISSION_DENIED",
"message": "not allowed",
})))
.with_priority(2)
.expect(1)
.mount(&server)
.await;
let mut result = ResultConfig::default();
result.cloudfetch_enabled = false;
let error = match 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)
.open()
.await
{
Ok(_) => panic!("a failed fallback CreateSession must surface"),
Err(error) => error,
};
assert_eq!(error.http_status, Some(403));
assert!(error.message.contains("not allowed"), "{error}");
assert!(
error.message.contains("retried without can_cloud_download"),
"{error}"
);
assert!(error.message.contains("INVALID_CONF_VALUE"), "{error}");
}

#[tokio::test]
async fn execute_with_cloudfetch_disabled_rejects_external_links_without_downloading() {
let server = MockServer::start().await;
Expand Down
Loading