diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h index 8e545518..743f3c12 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -371,8 +371,43 @@ KernelStatusCode kernel_session_config_set_ignore_transactions(KernelSessionConf * * The on-disk format is wire-compatible with the JDBC driver's * EncryptedFileTokenCache (given the same passphrase). */ -KernelStatusCode kernel_session_config_set_token_cache(KernelSessionConfig* config, bool enabled, - const char* passphrase); +KernelStatusCode kernel_session_config_set_u2m_token_cache_config(KernelSessionConfig* config, + bool enabled, + const char* passphrase); + +/* Set one CLIENT-SIDE result knob by name (key = value). + * + * Counterpart to kernel_session_config_set_session_conf: that one carries + * SERVER session confs (ANSI_MODE, TIMEZONE, ...) to the SEA wire; this one + * sets CLIENT-SIDE knobs that tune how the kernel fetches, buffers, and + * post-processes results and are NEVER sent to the server. The two channels + * are deliberately separate (conflating them is what made a client flag + * masquerade as a rejected server conf). + * + * Key/value (rather than one typed setter per knob) so the signature never + * changes as new result knobs are added, and so a host that already has DSN + * / connection-string attributes can forward them in a loop. Unknown keys + * and unparseable values are REJECTED (InvalidArgument + stored error), not + * silently ignored. + * + * Recognised keys (case-insensitive): + * - "cloudfetch_enabled" = "true"|"false" — false serves every result + * inline (SEA disposition = INLINE), mirroring JDBC EnableQueryResultDownload=0. + * - "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). + * - "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). + * - "intervals_as_string" = "true"|"false" — render INTERVAL / DURATION as + * canonical Databricks text (for pyarrow-Python bindings). + * + * A server session-conf key passed here (e.g. "ANSI_MODE") is rejected — + * use kernel_session_config_set_session_conf for those. */ +KernelStatusCode kernel_session_config_set_client_conf(KernelSessionConfig* config, + const char* key, const char* value); /* ─── Session lifecycle ───────────────────────────────────────────────*/ diff --git a/src/c_abi/session.rs b/src/c_abi/session.rs index 0da3efa9..ef52396a 100644 --- a/src/c_abi/session.rs +++ b/src/c_abi/session.rs @@ -26,7 +26,8 @@ use super::{block_on_ffi, KernelStatusCode}; use crate::config::{ - AuthConfig, ConnectionConfig, HttpConfig, ProxyConfig, TlsConfig, TokenCacheConfig, + AuthConfig, ConnectionConfig, HttpConfig, ProxyConfig, ResultConfig, TlsConfig, + TokenCacheConfig, }; use crate::kernel_error::Error; use crate::session::Session; @@ -112,11 +113,19 @@ pub struct KernelSessionConfig { /// with `false`. Maps to [`DefaultOpts::ignore_transactions`]. ignore_transactions: bool, /// On-disk U2M token-cache policy (populated by - /// `kernel_session_config_set_token_cache`). Defaults to enabled with + /// `kernel_session_config_set_u2m_token_cache_config`). Defaults to enabled with /// no passphrase, in which case the cache is encrypted under a /// machine-local derived key. Only U2M auth reads it — PAT and M2M never /// touch the cache. See [`TokenCacheConfig`]. token_cache: TokenCacheConfig, + /// Client-side result-management knobs (CloudFetch / inline streaming + /// tuning, flat-text rendering). Populated by + /// `kernel_session_config_set_client_conf`; defaults to + /// [`ResultConfig::default`]. These are **client-side** behaviours + /// folded into the kernel's `ResultConfig` at `open()` — they never + /// reach the SEA wire (unlike [`Self::session_conf`]). See + /// [`ResultConfig`]. + result: ResultConfig, } /// C-side proxy config captured from `kernel_session_config_set_proxy`. @@ -196,6 +205,8 @@ pub unsafe extern "C" fn kernel_session_config_new( ignore_transactions: true, // Match the reference driver's / JDBC's EnableTokenCache=1. token_cache: TokenCacheConfig::default(), + // Kernel result defaults (CloudFetch enabled, Arrow-native types). + result: ResultConfig::default(), }); std::ptr::write(out, Box::into_raw(config)); KernelStatusCode::Success @@ -656,7 +667,7 @@ pub unsafe extern "C" fn kernel_session_config_set_ignore_transactions( /// point to a NUL-terminated UTF-8 string valid for the duration of the /// call. #[no_mangle] -pub unsafe extern "C" fn kernel_session_config_set_token_cache( +pub unsafe extern "C" fn kernel_session_config_set_u2m_token_cache_config( config: *mut KernelSessionConfig, enabled: bool, passphrase: *const c_char, @@ -670,6 +681,61 @@ pub unsafe extern "C" fn kernel_session_config_set_token_cache( }) } +/// Set one **client-side** result knob by name (`key` = `value`). +/// +/// This is the client-side counterpart to +/// `kernel_session_config_set_session_conf`: that one carries **server** +/// session confs (`ANSI_MODE`, `TIMEZONE`, …) to the SEA wire; this one +/// sets **client-side** knobs that tune how the kernel fetches, buffers, +/// and post-processes results and are **never sent to the server**. The two +/// channels are deliberately separate (see #196 / #226 — conflating them is +/// what made a client flag masquerade as a rejected server conf). +/// +/// A key/value shape (rather than one typed setter per knob) is chosen so +/// the signature never changes as `ResultConfig` grows new knobs, and so a +/// host that already has DSN / connection-string attributes can forward +/// them in a loop. Safety is recovered at runtime: an unknown key or an +/// unparseable value is **rejected** with `InvalidArgument` (and a stored +/// error naming the problem), not silently ignored. +/// +/// 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`. +/// - `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`). +/// - `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`). +/// - `intervals_as_string` = `"true"` / `"false"` — render `INTERVAL` / +/// `DURATION` as canonical Databricks text (for pyarrow-Python bindings). +/// +/// A server session-conf key passed here (e.g. `ANSI_MODE`) is rejected — +/// use `kernel_session_config_set_session_conf` for those. +/// +/// # Safety +/// `config` must be a live config handle; `key` / `value` must be +/// NUL-terminated C strings. +#[no_mangle] +pub unsafe extern "C" fn kernel_session_config_set_client_conf( + config: *mut KernelSessionConfig, + key: *const c_char, + value: *const c_char, +) -> KernelStatusCode { + set_on_config(config, |c| { + let key = required_str(key, "client_conf key")?; + let value = required_str(value, "client_conf value")?; + c.result.apply_client_conf(&key, &value) + }) +} + /// Shared body for the config setters: null-check the handle, clear the /// thread-local error, run `f` against the borrowed config, and store /// any error. @@ -804,6 +870,7 @@ fn build_session(config: KernelSessionConfig) -> Result Result &'static str { + match self { + Self::CloudfetchEnabled => "cloudfetch_enabled", + Self::CloudfetchLinkPrefetchWindow => "cloudfetch_link_prefetch_window", + Self::CloudfetchMaxChunksInMemory => "cloudfetch_max_chunks_in_memory", + Self::InlineMaxChunksInMemory => "inline_max_chunks_in_memory", + Self::ComplexTypesAsJson => "complex_types_as_json", + Self::IntervalsAsString => "intervals_as_string", + } + } + + /// Parse a caller-supplied key string (case-insensitive) into a known + /// key, or `None` if it is not a recognised client-conf key. + pub(crate) fn parse(key: &str) -> Option { + Self::ALL + .iter() + .copied() + .find(|k| key.eq_ignore_ascii_case(k.as_str())) + } +} + +impl ResultConfig { + /// Apply one client-side result knob by name, parsing `value` into the + /// matching typed field. + /// + /// This is the single validated entry point behind the C ABI's + /// `kernel_session_config_set_client_conf` (and any host that forwards + /// DSN / connection-string attributes as key/value pairs). The key is + /// resolved via [`ClientConfKey::parse`] (case-insensitive). + /// + /// Unlike the server `session_conf` map, these knobs are **client-side** + /// and never reach the SEA wire — so this deliberately does NOT accept + /// server conf keys (`ANSI_MODE`, `TIMEZONE`, …); those go through + /// [`filter_session_conf`] instead. Keeping the two channels separate is + /// the point (see #226). + /// + /// # Errors + /// Returns `ErrorCode::InvalidArgument` when: + /// - `key` is not a recognised client-conf key, or + /// - `value` cannot be parsed for that key's type (booleans accept + /// exactly `"true"` / `"false"` case-insensitively; the `usize` + /// windows require a positive integer). + /// + /// A `cloudfetch_max_chunks_in_memory` above + /// [`CLOUDFETCH_MAX_CHUNKS_CEILING`] is **clamped** (with a `warn!`), + /// not rejected — a fat-fingered value must not fail the connection, but + /// it must not drive peak RSS toward OOM either. + pub(crate) fn apply_client_conf(&mut self, key: &str, value: &str) -> crate::Result<()> { + let Some(known) = ClientConfKey::parse(key) else { + return Err(crate::kernel_error::Error::invalid_argument().message(format!( + "unknown client conf key {key:?}; recognised client-side result knobs are {:?}. \ + (Server session confs like ANSI_MODE / TIMEZONE go through session_conf, not here.)", + ClientConfKey::ALL + .iter() + .map(|k| k.as_str()) + .collect::>(), + ))); + }; + + // Booleans accept exactly "true"/"false" (case-insensitive). SEA and + // the reference drivers use these literal forms; anything else is a + // caller error we surface rather than silently coerce. + let parse_bool = |v: &str| -> crate::Result { + match v.trim().to_ascii_lowercase().as_str() { + "true" => Ok(true), + "false" => Ok(false), + _ => Err( + crate::kernel_error::Error::invalid_argument().message(format!( + "client conf '{}' expects \"true\" or \"false\", got {v:?}", + known.as_str(), + )), + ), + } + }; + let parse_positive_usize = |v: &str| -> crate::Result { + match v.trim().parse::() { + Ok(n) if n > 0 => Ok(n), + _ => Err( + crate::kernel_error::Error::invalid_argument().message(format!( + "client conf '{}' expects a positive integer, got {v:?}", + known.as_str(), + )), + ), + } + }; + + // Exhaustive: adding a ClientConfKey variant forces a new arm here. + match known { + ClientConfKey::CloudfetchEnabled => { + self.cloudfetch_enabled = parse_bool(value)?; + } + ClientConfKey::CloudfetchLinkPrefetchWindow => { + self.cloudfetch_link_prefetch_window = parse_positive_usize(value)?; + } + ClientConfKey::CloudfetchMaxChunksInMemory => { + let n = parse_positive_usize(value)?; + let clamped = n.min(CLOUDFETCH_MAX_CHUNKS_CEILING); + if clamped != n { + crate::klog::warn!( + requested = n, + ceiling = CLOUDFETCH_MAX_CHUNKS_CEILING, + "clamping cloudfetch_max_chunks_in_memory to the ceiling \ + (peak RSS scales with this knob)", + ); + } + self.cloudfetch_max_chunks_in_memory = clamped; + } + ClientConfKey::InlineMaxChunksInMemory => { + self.inline_max_chunks_in_memory = parse_positive_usize(value)?; + } + ClientConfKey::ComplexTypesAsJson => { + self.complex_types_as_json = parse_bool(value)?; + } + ClientConfKey::IntervalsAsString => { + self.intervals_as_string = parse_bool(value)?; + } + } + Ok(()) + } +} + // ─── Logging ──────────────────────────────────────────────────────────────── #[non_exhaustive] diff --git a/src/session.rs b/src/session.rs index 55f4cc1b..12bc5658 100644 --- a/src/session.rs +++ b/src/session.rs @@ -888,99 +888,64 @@ fn build_retry_configs_for_session( build_retry_configs(&global, &overrides) } -/// Client-only `session_conf` key that tunes how many decompressed -/// CloudFetch chunks the kernel holds in memory at once (peak RSS on -/// large result sets). It is a **client** knob, not a server SET -/// parameter: it is read by [`apply_client_result_overrides`] before -/// session creation and is deliberately absent from -/// [`SESSION_CONF_ALLOWLIST`](crate::config), so `filter_session_conf` -/// drops it and it never reaches the SEA wire. Exposed this way (rather -/// than as a new C-ABI symbol) so the Go/ODBC consumers can set it -/// through the existing `set_session_conf` entry point. -pub(crate) const CLIENT_CONF_CLOUDFETCH_MAX_CHUNKS: &str = "cloudfetch_max_chunks_in_memory"; - -/// Upper bound applied to a host-supplied -/// [`CLIENT_CONF_CLOUDFETCH_MAX_CHUNKS`] value. Peak RSS grows roughly -/// linearly with this knob (each in-memory chunk is tens of MB), so an -/// unbounded value — a typo like `"1000000"` meant as `"100"`, or a host bug — -/// risks OOM on large result sets. This ceiling (16× the default of 16, and 8× -/// the most aggressive value we've measured) is comfortably above any real -/// tuning yet bounds the blast radius of a fat-fingered value; a request above -/// it is clamped with a `warn!`, mirroring the retry setter's clamp discipline. -pub(crate) const CLOUDFETCH_MAX_CHUNKS_CEILING: usize = 256; - -/// Fold client-only result-management knobs carried in `session_conf` -/// into the typed [`ResultConfig`], then remove them from `session_conf` -/// so they cannot leak onto the SEA wire. +/// Fold any **client-side** result knobs that a host left in `session_conf` +/// into the typed [`ResultConfig`], then strip them so they can't leak onto +/// the SEA wire. /// -/// Today this handles only [`CLIENT_CONF_CLOUDFETCH_MAX_CHUNKS`]. A key -/// that is absent leaves the field at its `ResultConfig` default (16); a -/// present-but-unparseable or zero value is ignored (default preserved) -/// with a warning rather than failing session creation — a -/// best-effort tuning knob should never turn a typo into a connect -/// error. A value above [`CLOUDFETCH_MAX_CHUNKS_CEILING`] is clamped to -/// that ceiling (with a warning) so a fat-fingered value can't drive peak -/// RSS toward OOM. Matched case-insensitively, consistent with the rest of -/// the `session_conf` handling; if a host sets two spellings that differ only -/// in case the lexicographically-last one wins deterministically (and all -/// variants are stripped). +/// This is the legacy / convenience channel: the preferred entry point is +/// the C ABI's `kernel_session_config_set_client_conf` (which sets +/// `ResultConfig` directly), but a host that only has a `session_conf` +/// key/value bag — e.g. one forwarding DSN attributes without sorting them +/// into client vs. server — can still drop a client knob like +/// `cloudfetch_max_chunks_in_memory` in there and have it applied. Any key +/// recognised by [`ResultConfig::apply_client_conf`] (see +/// [`ClientConfKey`](crate::config::ClientConfKey)) is consumed here; +/// unrecognised keys are left for [`filter_session_conf`] to handle as +/// server confs. +/// +/// **Best-effort, never fatal.** A recognised key with an unparseable value +/// is logged at `warn` and skipped (the field keeps its current value) +/// rather than failing session creation — a stray tuning value in the bag +/// must not turn into a connect error. (The typed `set_client_conf` path +/// *does* reject bad values, because there the caller asked for that key +/// explicitly; here the key is ambient in a mixed bag.) Every recognised +/// key is removed regardless of parse outcome, so no client-only key +/// survives into `filter_session_conf` / the wire. +/// +/// 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. fn apply_client_result_overrides(config: &mut SessionConfig) { - // Collect EVERY case-insensitive spelling of the key, not just the first - // one `HashMap` iteration happens to yield. Two variants that differ only - // in case (e.g. `cloudfetch_max_chunks_in_memory` and - // `CloudFetch_Max_Chunks_In_Memory`) would otherwise resolve - // nondeterministically across runs. We sort the matches and let the - // lexicographically-last spelling win — a stable, run-independent rule — - // and remove all of them regardless of parse outcome, so no client-only - // key survives into `filter_session_conf` / the wire. - let mut keys: Vec = config + use crate::config::ClientConfKey; + + // 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 .session_conf .keys() - .filter(|k| k.eq_ignore_ascii_case(CLIENT_CONF_CLOUDFETCH_MAX_CHUNKS)) + .filter(|k| ClientConfKey::parse(k).is_some()) .cloned() .collect(); - if keys.is_empty() { + if present.is_empty() { return; } - keys.sort_unstable(); - if keys.len() > 1 { - crate::klog::warn!( - variants = keys.len(), - "multiple case-variant cloudfetch_max_chunks_in_memory keys set; \ - applying the lexicographically-last spelling deterministically", - ); - } - // Remove every variant; the winner's value drives the override. - let mut raw = String::new(); - for k in &keys { - if let Some(v) = config.session_conf.remove(k) { - raw = v; - } - } - match raw.trim().parse::() { - Ok(n) if n > 0 => { - // Clamp to a sane ceiling: peak RSS scales with this knob, so an - // absurd value (typo / host bug) would otherwise risk OOM. - let clamped = n.min(CLOUDFETCH_MAX_CHUNKS_CEILING); - if clamped != n { - crate::klog::warn!( - requested = n, - ceiling = CLOUDFETCH_MAX_CHUNKS_CEILING, - "clamping cloudfetch_max_chunks_in_memory to the ceiling \ - (peak RSS scales with this knob)", - ); - } - config.result.cloudfetch_max_chunks_in_memory = clamped; - crate::klog::debug!( - max_chunks_in_memory = clamped, - "applied client cloudfetch_max_chunks_in_memory override", - ); - } - _ => { + // Deterministic winner among case-variants: sort so the lexicographically + // -last spelling of each key is applied last (and thus wins). + present.sort_unstable(); + + for spelling in present { + let Some(value) = config.session_conf.remove(&spelling) else { + continue; + }; + // Best-effort: a bad value in the ambient bag is warned-and-skipped, + // never fatal. The key is already removed above so it can't reach the + // wire regardless. + if let Err(e) = config.result.apply_client_conf(&spelling, &value) { crate::klog::warn!( - value = %raw, - "ignoring invalid cloudfetch_max_chunks_in_memory (want a positive integer); \ - keeping the default", + key = %spelling, + value = %value, + error = %e.message, + "ignoring invalid client-side result knob in session_conf; keeping current value", ); } } @@ -1236,7 +1201,9 @@ mod retry_config_tests { #[test] fn cloudfetch_max_chunks_override_applies_and_is_stripped() { let mut cfg = config_with_session_conf(HashMap::from([( - CLIENT_CONF_CLOUDFETCH_MAX_CHUNKS.to_string(), + crate::config::ClientConfKey::CloudfetchMaxChunksInMemory + .as_str() + .to_string(), "4".to_string(), )])); apply_client_result_overrides(&mut cfg); @@ -1289,9 +1256,9 @@ mod retry_config_tests { "the lexicographically-last case variant must win deterministically" ); assert!( - !cfg.session_conf - .keys() - .any(|k| k.eq_ignore_ascii_case(CLIENT_CONF_CLOUDFETCH_MAX_CHUNKS)), + !cfg.session_conf.keys().any(|k| k.eq_ignore_ascii_case( + crate::config::ClientConfKey::CloudfetchMaxChunksInMemory.as_str() + )), "every case variant of the client knob must be stripped, got {:?}", cfg.session_conf ); @@ -1320,7 +1287,9 @@ mod retry_config_tests { fn cloudfetch_max_chunks_invalid_is_ignored_but_stripped() { for bad in ["0", "-1", "abc", ""] { let mut cfg = config_with_session_conf(HashMap::from([( - CLIENT_CONF_CLOUDFETCH_MAX_CHUNKS.to_string(), + crate::config::ClientConfKey::CloudfetchMaxChunksInMemory + .as_str() + .to_string(), bad.to_string(), )])); apply_client_result_overrides(&mut cfg); @@ -1342,26 +1311,83 @@ mod retry_config_tests { fn cloudfetch_max_chunks_above_ceiling_is_clamped() { // Well above the ceiling → clamped down. let mut cfg = config_with_session_conf(HashMap::from([( - CLIENT_CONF_CLOUDFETCH_MAX_CHUNKS.to_string(), + crate::config::ClientConfKey::CloudfetchMaxChunksInMemory + .as_str() + .to_string(), "1000000".to_string(), )])); apply_client_result_overrides(&mut cfg); assert_eq!( - cfg.result.cloudfetch_max_chunks_in_memory, CLOUDFETCH_MAX_CHUNKS_CEILING, + cfg.result.cloudfetch_max_chunks_in_memory, + crate::config::CLOUDFETCH_MAX_CHUNKS_CEILING, "an absurd value must clamp to the ceiling" ); assert!(cfg.session_conf.is_empty()); // Exactly at the ceiling → unchanged (boundary is inclusive). let mut cfg = config_with_session_conf(HashMap::from([( - CLIENT_CONF_CLOUDFETCH_MAX_CHUNKS.to_string(), - CLOUDFETCH_MAX_CHUNKS_CEILING.to_string(), + crate::config::ClientConfKey::CloudfetchMaxChunksInMemory + .as_str() + .to_string(), + crate::config::CLOUDFETCH_MAX_CHUNKS_CEILING.to_string(), )])); apply_client_result_overrides(&mut cfg); assert_eq!( cfg.result.cloudfetch_max_chunks_in_memory, - CLOUDFETCH_MAX_CHUNKS_CEILING, + crate::config::CLOUDFETCH_MAX_CHUNKS_CEILING, + ); + } + + /// 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 + /// session_conf sweep. + #[test] + fn all_client_conf_keys_apply_from_session_conf_and_are_stripped() { + use crate::config::ClientConfKey as K; + let mut cfg = config_with_session_conf(HashMap::from([ + ( + K::CloudfetchEnabled.as_str().to_string(), + "false".to_string(), + ), + ( + K::CloudfetchLinkPrefetchWindow.as_str().to_string(), + "7".to_string(), + ), + ( + K::CloudfetchMaxChunksInMemory.as_str().to_string(), + "9".to_string(), + ), + ( + K::InlineMaxChunksInMemory.as_str().to_string(), + "3".to_string(), + ), + ( + K::ComplexTypesAsJson.as_str().to_string(), + "true".to_string(), + ), + ( + K::IntervalsAsString.as_str().to_string(), + "true".to_string(), + ), + // A benign server param must survive untouched. + ("ansi_mode".to_string(), "true".to_string()), + ])); + apply_client_result_overrides(&mut cfg); + assert!(!cfg.result.cloudfetch_enabled); + assert_eq!(cfg.result.cloudfetch_link_prefetch_window, 7); + assert_eq!(cfg.result.cloudfetch_max_chunks_in_memory, 9); + assert_eq!(cfg.result.inline_max_chunks_in_memory, 3); + assert!(cfg.result.complex_types_as_json); + assert!(cfg.result.intervals_as_string); + // Every client key stripped; only the server param remains. + assert_eq!( + cfg.session_conf.get("ansi_mode").map(String::as_str), + Some("true"), + "server param must survive; got {:?}", + cfg.session_conf ); + assert_eq!(cfg.session_conf.len(), 1, "got {:?}", cfg.session_conf); } /// The client knob is NOT in the server allowlist, so even if it were @@ -1371,7 +1397,9 @@ mod retry_config_tests { #[test] fn cloudfetch_max_chunks_key_is_not_server_allowlisted() { let filtered = crate::config::filter_session_conf(HashMap::from([( - CLIENT_CONF_CLOUDFETCH_MAX_CHUNKS.to_string(), + crate::config::ClientConfKey::CloudfetchMaxChunksInMemory + .as_str() + .to_string(), "4".to_string(), )])); assert!( diff --git a/tests/c/session_smoke.c b/tests/c/session_smoke.c index fbb87540..af383848 100644 --- a/tests/c/session_smoke.c +++ b/tests/c/session_smoke.c @@ -203,6 +203,40 @@ static void test_u2m_and_header_setters(void) { kernel_session_config_free(config); } +/* Client-conf setter accepts known keys, clamps, and rejects bad input. */ +static void test_client_conf_setter(void) { + KernelSessionConfig* config = NULL; + (void)kernel_session_config_new(&config); + + /* Known keys with valid values. */ + KernelStatusCode rc = + kernel_session_config_set_client_conf(config, "cloudfetch_enabled", "false"); + CHECK(rc == KernelStatusCode_Success, "set_client_conf cloudfetch_enabled=false succeeds"); + rc = kernel_session_config_set_client_conf(config, "cloudfetch_max_chunks_in_memory", "32"); + CHECK(rc == KernelStatusCode_Success, "set_client_conf max_chunks=32 succeeds"); + rc = kernel_session_config_set_client_conf(config, "complex_types_as_json", "true"); + CHECK(rc == KernelStatusCode_Success, "set_client_conf complex_types_as_json=true succeeds"); + /* An absurd max_chunks value is clamped (not rejected) to the ceiling. */ + rc = kernel_session_config_set_client_conf(config, "cloudfetch_max_chunks_in_memory", "1000000"); + CHECK(rc == KernelStatusCode_Success, "set_client_conf over-ceiling clamps, not fails"); + + /* Unknown key → InvalidArgument. */ + rc = kernel_session_config_set_client_conf(config, "cloud_fetch_enabled", "false"); + CHECK(rc == KernelStatusCode_InvalidArgument, "set_client_conf(unknown key) → InvalidArgument"); + /* A server session-conf key is not a client conf → rejected here. */ + rc = kernel_session_config_set_client_conf(config, "ANSI_MODE", "true"); + CHECK(rc == KernelStatusCode_InvalidArgument, "set_client_conf(server key) → InvalidArgument"); + /* Unparseable bool → InvalidArgument. */ + rc = kernel_session_config_set_client_conf(config, "cloudfetch_enabled", "flase"); + CHECK(rc == KernelStatusCode_InvalidArgument, "set_client_conf(bad bool) → InvalidArgument"); + + kernel_session_config_free(config); + + /* Null handle / null args → InvalidArgument, no crash. */ + rc = kernel_session_config_set_client_conf(NULL, "cloudfetch_enabled", "false"); + CHECK(rc == KernelStatusCode_InvalidArgument, "set_client_conf(NULL cfg) → InvalidArgument"); +} + /* kernel_init_logging is idempotent and null-tolerant. */ static void test_init_logging(void) { KernelStatusCode rc = kernel_init_logging("WARN", NULL); @@ -264,6 +298,7 @@ int main(void) { test_setter_null_arg_rejected(); test_proxy_and_tls_setters(); test_u2m_and_header_setters(); + test_client_conf_setter(); test_init_logging(); test_is_open_null_guards(); test_submit_stub_rejects(); diff --git a/tests/v0_c_abi_result_config_wiremock.rs b/tests/v0_c_abi_result_config_wiremock.rs new file mode 100644 index 00000000..1151c6e6 --- /dev/null +++ b/tests/v0_c_abi_result_config_wiremock.rs @@ -0,0 +1,254 @@ +// 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. + +//! 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`. + +use std::ffi::CString; + +use databricks_sql_kernel::c_abi::session::{ + kernel_session_close, kernel_session_config_free, kernel_session_config_new, + kernel_session_config_set_auth_pat, kernel_session_config_set_client_conf, + kernel_session_config_set_http_path, kernel_session_new_statement, kernel_session_open, + kernel_session_t, KernelSessionConfig, +}; +use databricks_sql_kernel::c_abi::statement::{ + kernel_executed_statement_close, kernel_executed_statement_t, kernel_statement_execute, + kernel_statement_set_sql, kernel_statement_t, +}; +use databricks_sql_kernel::c_abi::KernelStatusCode; +use serde_json::json; +use wiremock::matchers::{method, path}; +use wiremock::{Mock, MockServer, ResponseTemplate}; + +async fn mount_create_session(server: &MockServer) { + Mock::given(method("POST")) + .and(path("/api/2.0/sql/sessions")) + .respond_with( + ResponseTemplate::new(200) + .set_body_string(r#"{"session_id":"sess-test","warehouse_id":"test_wh"}"#), + ) + .mount(server) + .await; +} + +/// Catch-all DELETE so teardown's fire-and-forget deletes don't 404. +async fn mount_close_any(server: &MockServer) { + Mock::given(method("DELETE")) + .respond_with(ResponseTemplate::new(200).set_body_string("{}")) + .mount(server) + .await; +} + +/// A terminal SUCCEEDED body with an empty result (`total_chunk_count: 0`), +/// materialised from the manifest schema with no Arrow attachment — so +/// execute completes without needing chunk data. +fn succeeded_empty_body(statement_id: &str) -> String { + json!({ + "statement_id": statement_id, + "status": { "state": "SUCCEEDED" }, + "manifest": { + "format": "ARROW_STREAM", + "schema": { "column_count": 1, "columns": [ + { "name": "n", "type_name": "BIGINT", "type_text": "BIGINT", "position": 0 } + ] }, + "total_chunk_count": 0, + "total_row_count": 0, + "total_byte_count": 0, + "truncated": false, + }, + }) + .to_string() +} + +async fn mount_execute(server: &MockServer) { + Mock::given(method("POST")) + .and(path("/api/2.0/sql/statements")) + .respond_with(ResponseTemplate::new(200).set_body_string(succeeded_empty_body("stmt-rc"))) + .mount(server) + .await; +} + +/// Open a session over the C ABI, applying `set_client_conf` first when +/// `cloudfetch_enabled` is `Some`. Returns the raw handle (caller closes). +/// +/// # Safety +/// Caller owns the returned handle and must `kernel_session_close` it. +unsafe fn open_session_c_abi(uri: &str, cloudfetch_enabled: Option) -> *mut kernel_session_t { + let mut config: *mut KernelSessionConfig = std::ptr::null_mut(); + assert_eq!( + kernel_session_config_new(&mut config), + KernelStatusCode::Success + ); + let host = CString::new(uri).unwrap(); + let http_path = CString::new("/sql/1.0/warehouses/test_wh").unwrap(); + assert_eq!( + kernel_session_config_set_http_path(config, host.as_ptr(), http_path.as_ptr()), + KernelStatusCode::Success + ); + let token = CString::new("dapi_test_token").unwrap(); + assert_eq!( + kernel_session_config_set_auth_pat(config, token.as_ptr()), + KernelStatusCode::Success + ); + if let Some(cf) = cloudfetch_enabled { + // Set the one client knob under test by name via the generic + // client-conf setter; other knobs keep their kernel defaults. + let key = CString::new("cloudfetch_enabled").unwrap(); + let value = CString::new(if cf { "true" } else { "false" }).unwrap(); + assert_eq!( + kernel_session_config_set_client_conf(config, key.as_ptr(), value.as_ptr()), + KernelStatusCode::Success + ); + } + let mut session: *mut kernel_session_t = std::ptr::null_mut(); + assert_eq!( + kernel_session_open(config, &mut session), + KernelStatusCode::Success + ); + assert!(!session.is_null()); + session +} + +/// Drive one execute over the C ABI and return the `disposition` string the +/// kernel sent on the recorded POST /statements request. +fn recorded_execute_disposition(cloudfetch_enabled: Option) -> String { + let rt = tokio::runtime::Runtime::new().unwrap(); + let server = rt.block_on(async { + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_close_any(&server).await; + mount_execute(&server).await; + server + }); + let uri = server.uri(); + + unsafe { + let session = open_session_c_abi(&uri, cloudfetch_enabled); + let mut stmt: *mut kernel_statement_t = std::ptr::null_mut(); + assert_eq!( + kernel_session_new_statement(session, &mut stmt), + KernelStatusCode::Success + ); + let sql = CString::new("SELECT 1").unwrap(); + assert_eq!( + kernel_statement_set_sql(stmt, sql.as_ptr()), + KernelStatusCode::Success + ); + let mut exec: *mut kernel_executed_statement_t = std::ptr::null_mut(); + assert_eq!( + kernel_statement_execute(stmt, &mut exec), + KernelStatusCode::Success + ); + kernel_executed_statement_close(exec); + kernel_session_close(session); + } + + let recorded = rt.block_on(async { server.received_requests().await.unwrap() }); + 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() +} + +#[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"); +} + +#[test] +fn c_abi_client_conf_cloudfetch_enabled_sends_inline_or_external_links_disposition() { + assert_eq!( + recorded_execute_disposition(Some(true)), + "INLINE_OR_EXTERNAL_LINKS" + ); +} + +#[test] +fn c_abi_default_result_config_sends_inline_or_external_links_disposition() { + // No set_client_conf call at all → kernel default (CloudFetch on). + assert_eq!( + recorded_execute_disposition(None), + "INLINE_OR_EXTERNAL_LINKS" + ); +} + +#[test] +fn c_abi_set_client_conf_rejects_unknown_key_and_bad_value() { + use databricks_sql_kernel::c_abi::error::{kernel_get_last_error, KernelError}; + unsafe { + let mut config: *mut KernelSessionConfig = std::ptr::null_mut(); + assert_eq!( + kernel_session_config_new(&mut config), + KernelStatusCode::Success + ); + + // Unknown client key → InvalidArgument (not silently ignored). + let bad_key = CString::new("cloud_fetch_enabled").unwrap(); // typo + let val = CString::new("false").unwrap(); + assert_eq!( + kernel_session_config_set_client_conf(config, bad_key.as_ptr(), val.as_ptr()), + KernelStatusCode::InvalidArgument + ); + + // A server session-conf key is NOT a client conf → rejected here + // (it belongs on set_session_conf). This is the channel separation. + let server_key = CString::new("ANSI_MODE").unwrap(); + let server_val = CString::new("true").unwrap(); + assert_eq!( + kernel_session_config_set_client_conf(config, server_key.as_ptr(), server_val.as_ptr()), + KernelStatusCode::InvalidArgument + ); + + // Unparseable value for a known bool key → InvalidArgument. + let key = CString::new("cloudfetch_enabled").unwrap(); + let bad_val = CString::new("flase").unwrap(); // typo + assert_eq!( + kernel_session_config_set_client_conf(config, key.as_ptr(), bad_val.as_ptr()), + KernelStatusCode::InvalidArgument + ); + let mut err = std::mem::MaybeUninit::::uninit(); + assert!( + kernel_get_last_error(err.as_mut_ptr()), + "an error must be stored after a rejected client conf" + ); + assert_eq!( + err.assume_init().code, + KernelStatusCode::InvalidArgument as i32 + ); + + kernel_session_config_free(config); + } +}