From f791011a40e49cc2564e08d963800e90923e4832 Mon Sep 17 00:00:00 2001 From: Vikrant Puppala Date: Mon, 10 Aug 2026 09:43:31 +0000 Subject: [PATCH 1/4] feat(c-abi): typed result-config setters for client-side result knobs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The C ABI had no way to reach `ResultConfig`: `KernelSessionConfig` carried none, `build_session` never called `.result(...)`, and the only client-side result knob an ODBC/Go host could influence was `cloudfetch_max_chunks_in_memory`, smuggled as a magic string through `kernel_session_config_set_session_conf` and intercepted by `apply_client_result_overrides`. So `cloudfetch_enabled`, `complex_types_as_json`, `intervals_as_string`, and the prefetch/inline windows were all unreachable from the C ABI — leaving it behind its napi / pyo3 siblings and forcing callers to conflate client knobs with server session confs (the class of bug that produced #196). This adds a typed client-side result-config surface to the C ABI: - `kernel_session_config_set_result_config(cloudfetch_enabled, link_prefetch_window, max_chunks_in_memory, inline_max_chunks_in_memory)` — the CloudFetch / inline tuning group. A `0` on any usize field means "keep the kernel default", and `max_chunks_in_memory` is clamped to the existing `CLOUDFETCH_MAX_CHUNKS_CEILING` (256) with a warn. - `kernel_session_config_set_complex_types_as_json(enabled)` and `kernel_session_config_set_intervals_as_string(enabled)` — the two flat-text rendering booleans (parity with napi/pyo3). `KernelSessionConfig` now carries a `ResultConfig` (defaulted in `_new`), and `build_session` threads it through `.result(...)`. These knobs are client-side only and never reach the SEA wire. The legacy `cloudfetch_max_chunks_in_memory` magic string still works as a fallback, but the typed setter now wins: `apply_client_result_overrides` skips the string value when the field has already been moved off its default (still stripping the key so it can't leak to the wire). Deferred (tracked in #226): the typed `enable_metric_view_metadata` client property (kind-2 client-prop → server-conf mapping) and completing napi/pyo3 to cover all six ResultConfig knobs. Tests: - New `tests/v0_c_abi_result_config_wiremock.rs`: opening a session via the C ABI with `set_result_config(cloudfetch_enabled=false)` makes every ExecuteStatement carry `disposition = INLINE`; enabled / default carry `INLINE_OR_EXTERNAL_LINKS`. Proves the typed path reaches the wire. - `tests/c/session_smoke.c`: new setters compile, link, accept valid input (incl. over-ceiling clamp), and null-guard the handle. - New lib unit test: the typed setter wins over the legacy magic string, and the string key is still stripped. Refs #226 Co-authored-by: Isaac Signed-off-by: Vikrant Puppala --- include/databricks_kernel.h | 43 +++++ src/c_abi/session.rs | 127 +++++++++++++- src/session.rs | 66 +++++++- tests/c/session_smoke.c | 34 ++++ tests/v0_c_abi_result_config_wiremock.rs | 202 +++++++++++++++++++++++ 5 files changed, 462 insertions(+), 10 deletions(-) create mode 100644 tests/v0_c_abi_result_config_wiremock.rs diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h index 8e545518..36e39bca 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -374,6 +374,49 @@ KernelStatusCode kernel_session_config_set_ignore_transactions(KernelSessionConf KernelStatusCode kernel_session_config_set_token_cache(KernelSessionConfig* config, bool enabled, const char* passphrase); +/* Configure client-side result streaming (CloudFetch + inline tuning). + * All four knobs are CLIENT-SIDE — they tune how the kernel fetches and + * buffers results and never reach the SEA wire (unlike + * kernel_session_config_set_session_conf, which carries server confs). + * + * - `cloudfetch_enabled`: when false, every result is served inline (the + * execute request uses SEA disposition = INLINE), mirroring the reference + * JDBC driver's EnableQueryResultDownload=0. Default true. + * - `link_prefetch_window`: presigned CloudFetch URLs prefetched ahead of + * the consumer. 0 => keep the kernel default (10). + * - `max_chunks_in_memory`: max decompressed CloudFetch chunks held in + * memory at once (bounds parallelism and peak RSS). 0 => keep the default + * (16). Values above the kernel ceiling (256) are clamped with a warning. + * - `inline_max_chunks_in_memory`: prefetch window for the inline-Arrow + * path (used when cloudfetch_enabled = false). 0 => keep the default (4). + * + * 0 means "keep the kernel default" for every size_t field, so a host that + * zero-initialises the argument list only changes cloudfetch_enabled. + * + * This is the typed replacement for the legacy cloudfetch_max_chunks_in_memory + * value previously smuggled through kernel_session_config_set_session_conf; + * that fallback still works but this setter takes precedence. */ +KernelStatusCode kernel_session_config_set_result_config(KernelSessionConfig* config, + bool cloudfetch_enabled, + size_t link_prefetch_window, + size_t max_chunks_in_memory, + size_t inline_max_chunks_in_memory); + +/* Render complex-typed result columns (ARRAY / MAP / STRUCT / VARIANT / + * GEOMETRY / GEOGRAPHY) as JSON-text (UTF-8) instead of Arrow-native nested + * types. Default false. Set true for flat-text bindings that can't consume + * Arrow nested types (PySQL _use_arrow_native_complex_types=False, JDBC + * complexDatatypeSupport=false). Client-side only; never on the wire. */ +KernelStatusCode kernel_session_config_set_complex_types_as_json(KernelSessionConfig* config, + bool enabled); + +/* Render INTERVAL / DURATION result columns as canonical Databricks text + * (UTF-8) instead of Arrow interval/duration types. Default false. Set true + * for bindings that hand Arrow batches to pyarrow's Python layer (which + * can't decode Arrow month_interval). Client-side only; never on the wire. */ +KernelStatusCode kernel_session_config_set_intervals_as_string(KernelSessionConfig* config, + bool enabled); + /* ─── Session lifecycle ───────────────────────────────────────────────*/ /* diff --git a/src/c_abi/session.rs b/src/c_abi/session.rs index 0da3efa9..6b7cbb47 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; @@ -117,6 +118,15 @@ pub struct KernelSessionConfig { /// 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_result_config`, + /// `..._set_complex_types_as_json`, and `..._set_intervals_as_string`; + /// 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 +206,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 @@ -670,6 +682,117 @@ pub unsafe extern "C" fn kernel_session_config_set_token_cache( }) } +/// Configure client-side result streaming (CloudFetch + inline tuning). +/// +/// All four knobs are **client-side** — they tune how the kernel fetches +/// and buffers results and never reach the SEA wire (contrast +/// `kernel_session_config_set_session_conf`, which carries server confs). +/// +/// - `cloudfetch_enabled`: when `false`, every result is served inline +/// (the execute request uses SEA `disposition = INLINE`), mirroring the +/// reference JDBC driver's `EnableQueryResultDownload=0`. Default `true`. +/// - `link_prefetch_window`: number of presigned CloudFetch URLs to +/// prefetch ahead of the consumer. `0` ⇒ keep the kernel default (10). +/// - `max_chunks_in_memory`: max decompressed CloudFetch chunks held in +/// memory at once (bounds parallelism and peak RSS). `0` ⇒ keep the +/// default (16). Values above the kernel ceiling +/// ([`CLOUDFETCH_MAX_CHUNKS_CEILING`](crate::session::CLOUDFETCH_MAX_CHUNKS_CEILING), +/// 256) are clamped with a `warn`, since peak RSS scales with this knob. +/// - `inline_max_chunks_in_memory`: prefetch window for the inline-Arrow +/// path (used when `cloudfetch_enabled = false`). `0` ⇒ keep the +/// default (4). +/// +/// **`0` means "keep the kernel default"** for every `usize` field, so a +/// host that zero-initialises the argument list only changes +/// `cloudfetch_enabled`. Maps to [`ResultConfig`]. +/// +/// This is the typed replacement for the legacy +/// `cloudfetch_max_chunks_in_memory` value that was smuggled through +/// `kernel_session_config_set_session_conf`. That fallback still works but +/// this setter takes precedence — see `apply_client_result_overrides` in +/// `src/session.rs`. +/// +/// # Safety +/// `config` must be a live config handle. +#[no_mangle] +pub unsafe extern "C" fn kernel_session_config_set_result_config( + config: *mut KernelSessionConfig, + cloudfetch_enabled: bool, + link_prefetch_window: usize, + max_chunks_in_memory: usize, + inline_max_chunks_in_memory: usize, +) -> KernelStatusCode { + set_on_config(config, |c| { + c.result.cloudfetch_enabled = cloudfetch_enabled; + // `0` ⇒ leave the kernel default in place (a host zeroing its + // struct must not accidentally clamp prefetch/buffer windows to 0). + if link_prefetch_window != 0 { + c.result.cloudfetch_link_prefetch_window = link_prefetch_window; + } + if max_chunks_in_memory != 0 { + let clamped = max_chunks_in_memory.min(crate::session::CLOUDFETCH_MAX_CHUNKS_CEILING); + if clamped != max_chunks_in_memory { + crate::klog::warn!( + requested = max_chunks_in_memory, + ceiling = crate::session::CLOUDFETCH_MAX_CHUNKS_CEILING, + "clamping cloudfetch max_chunks_in_memory to the ceiling \ + (peak RSS scales with this knob)", + ); + } + c.result.cloudfetch_max_chunks_in_memory = clamped; + } + if inline_max_chunks_in_memory != 0 { + c.result.inline_max_chunks_in_memory = inline_max_chunks_in_memory; + } + Ok(()) + }) +} + +/// Render complex-typed result columns (`ARRAY` / `MAP` / `STRUCT` / +/// `VARIANT` / `GEOMETRY` / `GEOGRAPHY`) as JSON-text `Utf8` instead of +/// Arrow-native nested types. Default `false` (Arrow-native). +/// +/// Set `true` for flat-text bindings that can't consume Arrow nested +/// types — mirrors PySQL's `_use_arrow_native_complex_types=False` and the +/// JDBC driver's `complexDatatypeSupport=false`. Maps to +/// [`ResultConfig::complex_types_as_json`]. Client-side only; never on the +/// wire. +/// +/// # Safety +/// `config` must be a live config handle. +#[no_mangle] +pub unsafe extern "C" fn kernel_session_config_set_complex_types_as_json( + config: *mut KernelSessionConfig, + enabled: bool, +) -> KernelStatusCode { + set_on_config(config, |c| { + c.result.complex_types_as_json = enabled; + Ok(()) + }) +} + +/// Render `INTERVAL` / `DURATION` result columns as canonical Databricks +/// text (`Utf8`) instead of Arrow interval/duration types. Default +/// `false`. +/// +/// Set `true` for bindings that hand Arrow batches to pyarrow's Python +/// layer, which can't decode Arrow's `month_interval` type. Maps to +/// [`ResultConfig::intervals_as_string`]. Client-side only; never on the +/// wire. +/// +/// # Safety +/// `config` must be a live config handle. +#[no_mangle] +pub unsafe extern "C" fn kernel_session_config_set_intervals_as_string( + config: *mut KernelSessionConfig, + enabled: bool, +) -> KernelStatusCode { + set_on_config(config, |c| { + c.result.intervals_as_string = enabled; + Ok(()) + }) +} + /// 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 +927,7 @@ fn build_session(config: KernelSessionConfig) -> Result Result() { Ok(n) if n > 0 => { // Clamp to a sane ceiling: peak RSS scales with this knob, so an @@ -1364,6 +1387,31 @@ mod retry_config_tests { ); } + /// The typed setter wins over the legacy magic string: if + /// `cloudfetch_max_chunks_in_memory` has already been moved off its + /// default (as `kernel_session_config_set_result_config` does), a stray + /// magic-string value in session_conf must NOT clobber it — but the key + /// is still stripped so it can't reach the wire. + #[test] + fn typed_result_config_wins_over_legacy_magic_string() { + let mut cfg = config_with_session_conf(HashMap::from([( + CLIENT_CONF_CLOUDFETCH_MAX_CHUNKS.to_string(), + "8".to_string(), + )])); + // Simulate the typed setter having already set a non-default value. + let typed = ResultConfig::default().cloudfetch_max_chunks_in_memory + 7; + cfg.result.cloudfetch_max_chunks_in_memory = typed; + apply_client_result_overrides(&mut cfg); + assert_eq!( + cfg.result.cloudfetch_max_chunks_in_memory, typed, + "typed value must survive; the legacy magic string must not override it" + ); + assert!( + cfg.session_conf.is_empty(), + "the legacy key must still be stripped so it can't reach the wire" + ); + } + /// The client knob is NOT in the server allowlist, so even if it were /// left in session_conf it would be filtered before the wire. This /// pins that invariant so a future allowlist edit can't accidentally diff --git a/tests/c/session_smoke.c b/tests/c/session_smoke.c index fbb87540..dfca027c 100644 --- a/tests/c/session_smoke.c +++ b/tests/c/session_smoke.c @@ -203,6 +203,39 @@ static void test_u2m_and_header_setters(void) { kernel_session_config_free(config); } +/* Result-config setters accept valid input and null-guard the handle. */ +static void test_result_config_setters(void) { + KernelSessionConfig* config = NULL; + (void)kernel_session_config_new(&config); + + /* Full result config: disable CloudFetch, custom windows. */ + KernelStatusCode rc = kernel_session_config_set_result_config(config, false, 20, 32, 8); + CHECK(rc == KernelStatusCode_Success, "set_result_config (explicit) succeeds"); + /* Zeroed size_t fields => keep kernel defaults; only cloudfetch_enabled changes. */ + rc = kernel_session_config_set_result_config(config, true, 0, 0, 0); + CHECK(rc == KernelStatusCode_Success, "set_result_config (zeros keep defaults) succeeds"); + /* An absurd max_chunks value is clamped (not rejected) to the ceiling. */ + rc = kernel_session_config_set_result_config(config, true, 0, 1000000, 0); + CHECK(rc == KernelStatusCode_Success, "set_result_config (over-ceiling clamps, not fails)"); + + rc = kernel_session_config_set_complex_types_as_json(config, true); + CHECK(rc == KernelStatusCode_Success, "set_complex_types_as_json succeeds"); + rc = kernel_session_config_set_intervals_as_string(config, true); + CHECK(rc == KernelStatusCode_Success, "set_intervals_as_string succeeds"); + + kernel_session_config_free(config); + + /* Null handle → InvalidArgument, no crash. */ + rc = kernel_session_config_set_result_config(NULL, false, 0, 0, 0); + CHECK(rc == KernelStatusCode_InvalidArgument, "set_result_config(NULL) → InvalidArgument"); + rc = kernel_session_config_set_complex_types_as_json(NULL, true); + CHECK(rc == KernelStatusCode_InvalidArgument, + "set_complex_types_as_json(NULL) → InvalidArgument"); + rc = kernel_session_config_set_intervals_as_string(NULL, true); + CHECK(rc == KernelStatusCode_InvalidArgument, + "set_intervals_as_string(NULL) → InvalidArgument"); +} + /* kernel_init_logging is idempotent and null-tolerant. */ static void test_init_logging(void) { KernelStatusCode rc = kernel_init_logging("WARN", NULL); @@ -264,6 +297,7 @@ int main(void) { test_setter_null_arg_rejected(); test_proxy_and_tls_setters(); test_u2m_and_header_setters(); + test_result_config_setters(); 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..b3849858 --- /dev/null +++ b/tests/v0_c_abi_result_config_wiremock.rs @@ -0,0 +1,202 @@ +// 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 typed result-config surface +//! (`kernel_session_config_set_result_config`). +//! +//! These prove the typed 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 the typed +//! setter 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_new, kernel_session_config_set_auth_pat, + kernel_session_config_set_http_path, kernel_session_config_set_result_config, + 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_result_config` 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 { + // 0s => keep kernel defaults for the window/chunk knobs. + assert_eq!( + kernel_session_config_set_result_config(config, cf, 0, 0, 0), + 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_set_result_config_disabled_sends_inline_disposition() { + // The headline: a C-ABI host that disables CloudFetch via the typed + // setter gets SEA `disposition = INLINE` on the wire — proving the + // typed result config 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_set_result_config_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_result_config call at all → kernel default (CloudFetch on). + assert_eq!( + recorded_execute_disposition(None), + "INLINE_OR_EXTERNAL_LINKS" + ); +} From f5c5babbf20ec858a9534f8fbb630d1972d25345 Mon Sep 17 00:00:00 2001 From: Vikrant Puppala Date: Mon, 10 Aug 2026 09:55:08 +0000 Subject: [PATCH 2/4] refactor(c-abi): fold all 6 result knobs into one setter; rename token-cache MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Addresses review feedback on the result-config surface: - The split (grouped set_result_config for 4 CloudFetch/inline knobs + two separate boolean setters for complex_types_as_json / intervals_as_string) was inconsistent — all six are fields of the same ResultConfig. Fold complex_types_as_json and intervals_as_string into kernel_session_config_set_result_config as two trailing bool params, so the whole result config is set atomically in one call. Removes kernel_session_config_set_complex_types_as_json and kernel_session_config_set_intervals_as_string. - Rename kernel_session_config_set_token_cache -> kernel_session_config_set_u2m_token_cache_config: the setter configures the U2M (browser-auth) token-cache POLICY (enable + passphrase), which PAT and M2M ignore — the old name implied a generic "token cache" and hid the U2M scope. The _config suffix aligns it with the other grouped policy setters (set_retry_config, set_result_config). Breaking ABI changes (pre-1.0; no external consumers pinned yet). Header, C smoke test, and the C-ABI wiremock test updated accordingly. The grouped setter and renamed symbol both compile and link from C (verified against the cdylib). Refs #226 Signed-off-by: Vikrant Puppala --- include/databricks_kernel.h | 47 +++++++------- src/c_abi/session.rs | 82 +++++++++--------------- tests/c/session_smoke.c | 26 +++----- tests/v0_c_abi_result_config_wiremock.rs | 5 +- 4 files changed, 64 insertions(+), 96 deletions(-) diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h index 36e39bca..250c93dc 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -371,14 +371,17 @@ 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); -/* Configure client-side result streaming (CloudFetch + inline tuning). - * All four knobs are CLIENT-SIDE — they tune how the kernel fetches and - * buffers results and never reach the SEA wire (unlike - * kernel_session_config_set_session_conf, which carries server confs). +/* Configure the client-side result knobs in one call — the full + * ResultConfig surface. Every knob here is CLIENT-SIDE: it tunes how the + * kernel fetches, buffers, and post-processes results and never reaches the + * SEA wire (unlike kernel_session_config_set_session_conf, which carries + * server confs). * + * CloudFetch / inline streaming: * - `cloudfetch_enabled`: when false, every result is served inline (the * execute request uses SEA disposition = INLINE), mirroring the reference * JDBC driver's EnableQueryResultDownload=0. Default true. @@ -390,8 +393,19 @@ KernelStatusCode kernel_session_config_set_token_cache(KernelSessionConfig* conf * - `inline_max_chunks_in_memory`: prefetch window for the inline-Arrow * path (used when cloudfetch_enabled = false). 0 => keep the default (4). * + * Flat-text rendering (for bindings that can't consume Arrow-native types): + * - `complex_types_as_json`: render ARRAY / MAP / STRUCT / VARIANT / + * GEOMETRY / GEOGRAPHY columns as JSON-text (UTF-8). Default false. + * Mirrors PySQL _use_arrow_native_complex_types=False, JDBC + * complexDatatypeSupport=false. + * - `intervals_as_string`: render INTERVAL / DURATION columns as canonical + * Databricks text (UTF-8). Default false. Set true for bindings handing + * Arrow batches to pyarrow's Python layer (which can't decode Arrow + * month_interval). + * * 0 means "keep the kernel default" for every size_t field, so a host that - * zero-initialises the argument list only changes cloudfetch_enabled. + * zero-initialises the argument list gets kernel defaults for the windows + * and only the bool fields take effect. * * This is the typed replacement for the legacy cloudfetch_max_chunks_in_memory * value previously smuggled through kernel_session_config_set_session_conf; @@ -400,22 +414,9 @@ KernelStatusCode kernel_session_config_set_result_config(KernelSessionConfig* co bool cloudfetch_enabled, size_t link_prefetch_window, size_t max_chunks_in_memory, - size_t inline_max_chunks_in_memory); - -/* Render complex-typed result columns (ARRAY / MAP / STRUCT / VARIANT / - * GEOMETRY / GEOGRAPHY) as JSON-text (UTF-8) instead of Arrow-native nested - * types. Default false. Set true for flat-text bindings that can't consume - * Arrow nested types (PySQL _use_arrow_native_complex_types=False, JDBC - * complexDatatypeSupport=false). Client-side only; never on the wire. */ -KernelStatusCode kernel_session_config_set_complex_types_as_json(KernelSessionConfig* config, - bool enabled); - -/* Render INTERVAL / DURATION result columns as canonical Databricks text - * (UTF-8) instead of Arrow interval/duration types. Default false. Set true - * for bindings that hand Arrow batches to pyarrow's Python layer (which - * can't decode Arrow month_interval). Client-side only; never on the wire. */ -KernelStatusCode kernel_session_config_set_intervals_as_string(KernelSessionConfig* config, - bool enabled); + size_t inline_max_chunks_in_memory, + bool complex_types_as_json, + bool intervals_as_string); /* ─── Session lifecycle ───────────────────────────────────────────────*/ diff --git a/src/c_abi/session.rs b/src/c_abi/session.rs index 6b7cbb47..0fec7e70 100644 --- a/src/c_abi/session.rs +++ b/src/c_abi/session.rs @@ -113,7 +113,7 @@ 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`]. @@ -668,7 +668,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, @@ -682,12 +682,16 @@ pub unsafe extern "C" fn kernel_session_config_set_token_cache( }) } -/// Configure client-side result streaming (CloudFetch + inline tuning). +/// Configure the client-side result knobs in one call — the full +/// [`ResultConfig`] surface. /// -/// All four knobs are **client-side** — they tune how the kernel fetches -/// and buffers results and never reach the SEA wire (contrast -/// `kernel_session_config_set_session_conf`, which carries server confs). +/// Every knob here is **client-side**: it tunes how the kernel fetches, +/// buffers, and post-processes results and never reaches the SEA wire +/// (contrast `kernel_session_config_set_session_conf`, which carries +/// server confs). All six fields of the kernel's `ResultConfig` are set in +/// one call so a host configures result behaviour atomically. /// +/// CloudFetch / inline streaming: /// - `cloudfetch_enabled`: when `false`, every result is served inline /// (the execute request uses SEA `disposition = INLINE`), mirroring the /// reference JDBC driver's `EnableQueryResultDownload=0`. Default `true`. @@ -702,9 +706,22 @@ pub unsafe extern "C" fn kernel_session_config_set_token_cache( /// path (used when `cloudfetch_enabled = false`). `0` ⇒ keep the /// default (4). /// +/// Flat-text rendering (for bindings that can't consume the Arrow-native +/// types): +/// - `complex_types_as_json`: render `ARRAY` / `MAP` / `STRUCT` / +/// `VARIANT` / `GEOMETRY` / `GEOGRAPHY` columns as JSON-text `Utf8`. +/// Default `false` (Arrow-native). Mirrors PySQL's +/// `_use_arrow_native_complex_types=False` and JDBC's +/// `complexDatatypeSupport=false`. +/// - `intervals_as_string`: render `INTERVAL` / `DURATION` columns as +/// canonical Databricks text (`Utf8`). Default `false`. Set `true` for +/// bindings that hand Arrow batches to pyarrow's Python layer, which +/// can't decode Arrow's `month_interval` type. +/// /// **`0` means "keep the kernel default"** for every `usize` field, so a -/// host that zero-initialises the argument list only changes -/// `cloudfetch_enabled`. Maps to [`ResultConfig`]. +/// host that zero-initialises the argument list gets kernel defaults for +/// the windows and only the `bool` fields take effect. Maps to +/// [`ResultConfig`]. /// /// This is the typed replacement for the legacy /// `cloudfetch_max_chunks_in_memory` value that was smuggled through @@ -721,6 +738,8 @@ pub unsafe extern "C" fn kernel_session_config_set_result_config( link_prefetch_window: usize, max_chunks_in_memory: usize, inline_max_chunks_in_memory: usize, + complex_types_as_json: bool, + intervals_as_string: bool, ) -> KernelStatusCode { set_on_config(config, |c| { c.result.cloudfetch_enabled = cloudfetch_enabled; @@ -744,51 +763,8 @@ pub unsafe extern "C" fn kernel_session_config_set_result_config( if inline_max_chunks_in_memory != 0 { c.result.inline_max_chunks_in_memory = inline_max_chunks_in_memory; } - Ok(()) - }) -} - -/// Render complex-typed result columns (`ARRAY` / `MAP` / `STRUCT` / -/// `VARIANT` / `GEOMETRY` / `GEOGRAPHY`) as JSON-text `Utf8` instead of -/// Arrow-native nested types. Default `false` (Arrow-native). -/// -/// Set `true` for flat-text bindings that can't consume Arrow nested -/// types — mirrors PySQL's `_use_arrow_native_complex_types=False` and the -/// JDBC driver's `complexDatatypeSupport=false`. Maps to -/// [`ResultConfig::complex_types_as_json`]. Client-side only; never on the -/// wire. -/// -/// # Safety -/// `config` must be a live config handle. -#[no_mangle] -pub unsafe extern "C" fn kernel_session_config_set_complex_types_as_json( - config: *mut KernelSessionConfig, - enabled: bool, -) -> KernelStatusCode { - set_on_config(config, |c| { - c.result.complex_types_as_json = enabled; - Ok(()) - }) -} - -/// Render `INTERVAL` / `DURATION` result columns as canonical Databricks -/// text (`Utf8`) instead of Arrow interval/duration types. Default -/// `false`. -/// -/// Set `true` for bindings that hand Arrow batches to pyarrow's Python -/// layer, which can't decode Arrow's `month_interval` type. Maps to -/// [`ResultConfig::intervals_as_string`]. Client-side only; never on the -/// wire. -/// -/// # Safety -/// `config` must be a live config handle. -#[no_mangle] -pub unsafe extern "C" fn kernel_session_config_set_intervals_as_string( - config: *mut KernelSessionConfig, - enabled: bool, -) -> KernelStatusCode { - set_on_config(config, |c| { - c.result.intervals_as_string = enabled; + c.result.complex_types_as_json = complex_types_as_json; + c.result.intervals_as_string = intervals_as_string; Ok(()) }) } diff --git a/tests/c/session_smoke.c b/tests/c/session_smoke.c index dfca027c..ebc60bb2 100644 --- a/tests/c/session_smoke.c +++ b/tests/c/session_smoke.c @@ -203,37 +203,27 @@ static void test_u2m_and_header_setters(void) { kernel_session_config_free(config); } -/* Result-config setters accept valid input and null-guard the handle. */ +/* Result-config setter accepts valid input and null-guards the handle. */ static void test_result_config_setters(void) { KernelSessionConfig* config = NULL; (void)kernel_session_config_new(&config); - /* Full result config: disable CloudFetch, custom windows. */ - KernelStatusCode rc = kernel_session_config_set_result_config(config, false, 20, 32, 8); + /* Full result config: disable CloudFetch, custom windows, flat-text on. */ + KernelStatusCode rc = + kernel_session_config_set_result_config(config, false, 20, 32, 8, true, true); CHECK(rc == KernelStatusCode_Success, "set_result_config (explicit) succeeds"); - /* Zeroed size_t fields => keep kernel defaults; only cloudfetch_enabled changes. */ - rc = kernel_session_config_set_result_config(config, true, 0, 0, 0); + /* Zeroed size_t fields => keep kernel defaults; bools still take effect. */ + rc = kernel_session_config_set_result_config(config, true, 0, 0, 0, false, false); CHECK(rc == KernelStatusCode_Success, "set_result_config (zeros keep defaults) succeeds"); /* An absurd max_chunks value is clamped (not rejected) to the ceiling. */ - rc = kernel_session_config_set_result_config(config, true, 0, 1000000, 0); + rc = kernel_session_config_set_result_config(config, true, 0, 1000000, 0, false, false); CHECK(rc == KernelStatusCode_Success, "set_result_config (over-ceiling clamps, not fails)"); - rc = kernel_session_config_set_complex_types_as_json(config, true); - CHECK(rc == KernelStatusCode_Success, "set_complex_types_as_json succeeds"); - rc = kernel_session_config_set_intervals_as_string(config, true); - CHECK(rc == KernelStatusCode_Success, "set_intervals_as_string succeeds"); - kernel_session_config_free(config); /* Null handle → InvalidArgument, no crash. */ - rc = kernel_session_config_set_result_config(NULL, false, 0, 0, 0); + rc = kernel_session_config_set_result_config(NULL, false, 0, 0, 0, false, false); CHECK(rc == KernelStatusCode_InvalidArgument, "set_result_config(NULL) → InvalidArgument"); - rc = kernel_session_config_set_complex_types_as_json(NULL, true); - CHECK(rc == KernelStatusCode_InvalidArgument, - "set_complex_types_as_json(NULL) → InvalidArgument"); - rc = kernel_session_config_set_intervals_as_string(NULL, true); - CHECK(rc == KernelStatusCode_InvalidArgument, - "set_intervals_as_string(NULL) → InvalidArgument"); } /* kernel_init_logging is idempotent and null-tolerant. */ diff --git a/tests/v0_c_abi_result_config_wiremock.rs b/tests/v0_c_abi_result_config_wiremock.rs index b3849858..e377264c 100644 --- a/tests/v0_c_abi_result_config_wiremock.rs +++ b/tests/v0_c_abi_result_config_wiremock.rs @@ -112,9 +112,10 @@ unsafe fn open_session_c_abi(uri: &str, cloudfetch_enabled: Option) -> *mu KernelStatusCode::Success ); if let Some(cf) = cloudfetch_enabled { - // 0s => keep kernel defaults for the window/chunk knobs. + // 0s => keep kernel defaults for the window/chunk knobs; the two + // flat-text bools stay at their defaults (false). assert_eq!( - kernel_session_config_set_result_config(config, cf, 0, 0, 0), + kernel_session_config_set_result_config(config, cf, 0, 0, 0, false, false), KernelStatusCode::Success ); } From a1a4271cfd10ba177577f3bef8263d26e30a7f60 Mon Sep 17 00:00:00 2001 From: Vikrant Puppala Date: Mon, 10 Aug 2026 10:21:02 +0000 Subject: [PATCH 3/4] refactor(c-abi): replace set_result_config with generic set_client_conf MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Reworks the C-ABI client-result surface twice over, per review: 1. Signature that never churns. A flat positional set_result_config freezes its argument list, but ResultConfig is #[non_exhaustive] and expected to grow — every new knob would force a breaking signature change or a _v2. Replace it with a generic key/value setter: kernel_session_config_set_client_conf(config, key, value) This is the client-side counterpart to set_session_conf (server confs): the signature is stable as knobs are added, and a host that already has DSN / connection-string attributes can forward them in a loop. Safety is recovered at runtime — an unknown key or unparseable value is REJECTED with InvalidArgument (+ stored error), not silently ignored. Its own key set is client-only, so a server conf like ANSI_MODE passed here is rejected: the two channels stay separate, which is the point of #226. 2. Enum, not magic strings. The kernel-side dispatch is now a ClientConfKey enum (config.rs): the boundary string is parsed once via ClientConfKey::parse (case-insensitive) and apply_client_conf matches on the enum exhaustively — adding a variant won't compile until the new knob is handled, so a knob can't be silently forgotten. as_str() owns the canonical spellings in one place. The C-ABI boundary stays const char* (the wire format is strings) and C/test literals are unchanged — those are the real API input. Also unifies the legacy path: apply_client_result_overrides now sweeps session_conf for ANY recognised client key (via ClientConfKey::parse) and delegates to the same validator, instead of the bespoke cloudfetch_max_chunks_in_memory string parser. CLOUDFETCH_MAX_CHUNKS_CEILING moved to config.rs next to ResultConfig. Breaking ABI (pre-1.0). Header, C smoke test, and the C-ABI wiremock test updated; set_client_conf's disposition-on-the-wire behaviour and its reject-unknown-key / reject-bad-value paths are covered. Full suite + clippy + fmt green; C smoke test links and passes against the cdylib. Refs #226 Signed-off-by: Vikrant Puppala --- include/databricks_kernel.h | 75 +++---- src/c_abi/session.rs | 116 ++++------- src/config.rs | 163 +++++++++++++++ src/session.rs | 252 +++++++++++------------ tests/c/session_smoke.c | 39 ++-- tests/v0_c_abi_result_config_wiremock.rs | 79 +++++-- 6 files changed, 444 insertions(+), 280 deletions(-) diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h index 250c93dc..743f3c12 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -375,48 +375,39 @@ KernelStatusCode kernel_session_config_set_u2m_token_cache_config(KernelSessionC bool enabled, const char* passphrase); -/* Configure the client-side result knobs in one call — the full - * ResultConfig surface. Every knob here is CLIENT-SIDE: it tunes how the - * kernel fetches, buffers, and post-processes results and never reaches the - * SEA wire (unlike kernel_session_config_set_session_conf, which carries - * server confs). - * - * CloudFetch / inline streaming: - * - `cloudfetch_enabled`: when false, every result is served inline (the - * execute request uses SEA disposition = INLINE), mirroring the reference - * JDBC driver's EnableQueryResultDownload=0. Default true. - * - `link_prefetch_window`: presigned CloudFetch URLs prefetched ahead of - * the consumer. 0 => keep the kernel default (10). - * - `max_chunks_in_memory`: max decompressed CloudFetch chunks held in - * memory at once (bounds parallelism and peak RSS). 0 => keep the default - * (16). Values above the kernel ceiling (256) are clamped with a warning. - * - `inline_max_chunks_in_memory`: prefetch window for the inline-Arrow - * path (used when cloudfetch_enabled = false). 0 => keep the default (4). - * - * Flat-text rendering (for bindings that can't consume Arrow-native types): - * - `complex_types_as_json`: render ARRAY / MAP / STRUCT / VARIANT / - * GEOMETRY / GEOGRAPHY columns as JSON-text (UTF-8). Default false. - * Mirrors PySQL _use_arrow_native_complex_types=False, JDBC - * complexDatatypeSupport=false. - * - `intervals_as_string`: render INTERVAL / DURATION columns as canonical - * Databricks text (UTF-8). Default false. Set true for bindings handing - * Arrow batches to pyarrow's Python layer (which can't decode Arrow - * month_interval). - * - * 0 means "keep the kernel default" for every size_t field, so a host that - * zero-initialises the argument list gets kernel defaults for the windows - * and only the bool fields take effect. - * - * This is the typed replacement for the legacy cloudfetch_max_chunks_in_memory - * value previously smuggled through kernel_session_config_set_session_conf; - * that fallback still works but this setter takes precedence. */ -KernelStatusCode kernel_session_config_set_result_config(KernelSessionConfig* config, - bool cloudfetch_enabled, - size_t link_prefetch_window, - size_t max_chunks_in_memory, - size_t inline_max_chunks_in_memory, - bool complex_types_as_json, - bool intervals_as_string); +/* 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 0fec7e70..2303a5b4 100644 --- a/src/c_abi/session.rs +++ b/src/c_abi/session.rs @@ -682,90 +682,58 @@ pub unsafe extern "C" fn kernel_session_config_set_u2m_token_cache_config( }) } -/// Configure the client-side result knobs in one call — the full -/// [`ResultConfig`] surface. +/// Set one **client-side** result knob by name (`key` = `value`). /// -/// Every knob here is **client-side**: it tunes how the kernel fetches, -/// buffers, and post-processes results and never reaches the SEA wire -/// (contrast `kernel_session_config_set_session_conf`, which carries -/// server confs). All six fields of the kernel's `ResultConfig` are set in -/// one call so a host configures result behaviour atomically. +/// 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). /// -/// CloudFetch / inline streaming: -/// - `cloudfetch_enabled`: when `false`, every result is served inline -/// (the execute request uses SEA `disposition = INLINE`), mirroring the -/// reference JDBC driver's `EnableQueryResultDownload=0`. Default `true`. -/// - `link_prefetch_window`: number of presigned CloudFetch URLs to -/// prefetch ahead of the consumer. `0` ⇒ keep the kernel default (10). -/// - `max_chunks_in_memory`: max decompressed CloudFetch chunks held in -/// memory at once (bounds parallelism and peak RSS). `0` ⇒ keep the -/// default (16). Values above the kernel ceiling -/// ([`CLOUDFETCH_MAX_CHUNKS_CEILING`](crate::session::CLOUDFETCH_MAX_CHUNKS_CEILING), -/// 256) are clamped with a `warn`, since peak RSS scales with this knob. -/// - `inline_max_chunks_in_memory`: prefetch window for the inline-Arrow -/// path (used when `cloudfetch_enabled = false`). `0` ⇒ keep the -/// default (4). +/// 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. /// -/// Flat-text rendering (for bindings that can't consume the Arrow-native -/// types): -/// - `complex_types_as_json`: render `ARRAY` / `MAP` / `STRUCT` / -/// `VARIANT` / `GEOMETRY` / `GEOGRAPHY` columns as JSON-text `Utf8`. -/// Default `false` (Arrow-native). Mirrors PySQL's -/// `_use_arrow_native_complex_types=False` and JDBC's -/// `complexDatatypeSupport=false`. -/// - `intervals_as_string`: render `INTERVAL` / `DURATION` columns as -/// canonical Databricks text (`Utf8`). Default `false`. Set `true` for -/// bindings that hand Arrow batches to pyarrow's Python layer, which -/// can't decode Arrow's `month_interval` type. +/// 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). /// -/// **`0` means "keep the kernel default"** for every `usize` field, so a -/// host that zero-initialises the argument list gets kernel defaults for -/// the windows and only the `bool` fields take effect. Maps to -/// [`ResultConfig`]. -/// -/// This is the typed replacement for the legacy -/// `cloudfetch_max_chunks_in_memory` value that was smuggled through -/// `kernel_session_config_set_session_conf`. That fallback still works but -/// this setter takes precedence — see `apply_client_result_overrides` in -/// `src/session.rs`. +/// 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. +/// `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_result_config( +pub unsafe extern "C" fn kernel_session_config_set_client_conf( config: *mut KernelSessionConfig, - cloudfetch_enabled: bool, - link_prefetch_window: usize, - max_chunks_in_memory: usize, - inline_max_chunks_in_memory: usize, - complex_types_as_json: bool, - intervals_as_string: bool, + key: *const c_char, + value: *const c_char, ) -> KernelStatusCode { set_on_config(config, |c| { - c.result.cloudfetch_enabled = cloudfetch_enabled; - // `0` ⇒ leave the kernel default in place (a host zeroing its - // struct must not accidentally clamp prefetch/buffer windows to 0). - if link_prefetch_window != 0 { - c.result.cloudfetch_link_prefetch_window = link_prefetch_window; - } - if max_chunks_in_memory != 0 { - let clamped = max_chunks_in_memory.min(crate::session::CLOUDFETCH_MAX_CHUNKS_CEILING); - if clamped != max_chunks_in_memory { - crate::klog::warn!( - requested = max_chunks_in_memory, - ceiling = crate::session::CLOUDFETCH_MAX_CHUNKS_CEILING, - "clamping cloudfetch max_chunks_in_memory to the ceiling \ - (peak RSS scales with this knob)", - ); - } - c.result.cloudfetch_max_chunks_in_memory = clamped; - } - if inline_max_chunks_in_memory != 0 { - c.result.inline_max_chunks_in_memory = inline_max_chunks_in_memory; - } - c.result.complex_types_as_json = complex_types_as_json; - c.result.intervals_as_string = intervals_as_string; - Ok(()) + let key = required_str(key, "client_conf key")?; + let value = required_str(value, "client_conf value")?; + c.result.apply_client_conf(&key, &value) }) } diff --git a/src/config.rs b/src/config.rs index fa8b9b67..9b59ee07 100644 --- a/src/config.rs +++ b/src/config.rs @@ -915,6 +915,169 @@ impl Default for ResultConfig { } } +/// Upper bound applied to `cloudfetch_max_chunks_in_memory`. 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. +pub(crate) const CLOUDFETCH_MAX_CHUNKS_CEILING: usize = 256; + +/// A recognised client-side result knob — the typed identity of a +/// `set_client_conf` key. +/// +/// The C-ABI boundary (`kernel_session_config_set_client_conf`) is +/// stringly-typed by design (so the ABI never churns and hosts can forward +/// DSN attributes), but the string is parsed **once** into this enum via +/// [`ClientConfKey::parse`] and everything downstream matches on the enum. +/// The `match` in [`ResultConfig::apply_client_conf`] is exhaustive, so +/// adding a variant here won't compile until the new knob is handled — +/// there's no way to silently forget a knob. Each variant maps 1:1 onto a +/// field of [`ResultConfig`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum ClientConfKey { + CloudfetchEnabled, + CloudfetchLinkPrefetchWindow, + CloudfetchMaxChunksInMemory, + InlineMaxChunksInMemory, + ComplexTypesAsJson, + IntervalsAsString, +} + +impl ClientConfKey { + /// Every recognised key, in declaration order. Used for error messages + /// and to pin parity with [`ResultConfig`]'s fields in tests. + pub(crate) const ALL: &'static [ClientConfKey] = &[ + Self::CloudfetchEnabled, + Self::CloudfetchLinkPrefetchWindow, + Self::CloudfetchMaxChunksInMemory, + Self::InlineMaxChunksInMemory, + Self::ComplexTypesAsJson, + Self::IntervalsAsString, + ]; + + /// The canonical wire spelling of this key. + pub(crate) const fn as_str(self) -> &'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 55d98bba..12bc5658 100644 --- a/src/session.rs +++ b/src/session.rs @@ -888,122 +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`], the -/// legacy magic-string channel by which a C-ABI host tuned -/// `cloudfetch_max_chunks_in_memory` before a typed setter existed. A key -/// that is absent leaves the field untouched; a present-but-unparseable or -/// zero value is ignored (current value 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. /// -/// **Precedence: the typed setter wins.** The C-ABI -/// `kernel_session_config_set_result_config` writes -/// `ResultConfig::cloudfetch_max_chunks_in_memory` directly. This helper -/// therefore only applies the magic-string value when the field is still -/// at its default — a host that used the typed setter is never overridden -/// by a stray string, but the string key is still stripped so it can't -/// reach the wire. +/// **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() { - 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; - } - } - // The typed setter takes precedence: if the field has already been moved - // off its default (by `kernel_session_config_set_result_config` or a - // direct `ResultConfig`), don't let the legacy magic string clobber it. - // The key is still stripped above so it never reaches the wire. - if config.result.cloudfetch_max_chunks_in_memory - != ResultConfig::default().cloudfetch_max_chunks_in_memory - { - crate::klog::debug!( - "ignoring legacy cloudfetch_max_chunks_in_memory session_conf value; \ - a typed result config already set this knob", - ); + if present.is_empty() { return; } - 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", ); } } @@ -1259,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); @@ -1312,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 ); @@ -1343,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); @@ -1365,51 +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, ); } - /// The typed setter wins over the legacy magic string: if - /// `cloudfetch_max_chunks_in_memory` has already been moved off its - /// default (as `kernel_session_config_set_result_config` does), a stray - /// magic-string value in session_conf must NOT clobber it — but the key - /// is still stripped so it can't reach the wire. + /// 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 typed_result_config_wins_over_legacy_magic_string() { - let mut cfg = config_with_session_conf(HashMap::from([( - CLIENT_CONF_CLOUDFETCH_MAX_CHUNKS.to_string(), - "8".to_string(), - )])); - // Simulate the typed setter having already set a non-default value. - let typed = ResultConfig::default().cloudfetch_max_chunks_in_memory + 7; - cfg.result.cloudfetch_max_chunks_in_memory = typed; + 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.result.cloudfetch_max_chunks_in_memory, typed, - "typed value must survive; the legacy magic string must not override it" - ); - assert!( - cfg.session_conf.is_empty(), - "the legacy key must still be stripped so it can't reach the wire" + 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 @@ -1419,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 ebc60bb2..af383848 100644 --- a/tests/c/session_smoke.c +++ b/tests/c/session_smoke.c @@ -203,27 +203,38 @@ static void test_u2m_and_header_setters(void) { kernel_session_config_free(config); } -/* Result-config setter accepts valid input and null-guards the handle. */ -static void test_result_config_setters(void) { +/* 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); - /* Full result config: disable CloudFetch, custom windows, flat-text on. */ + /* Known keys with valid values. */ KernelStatusCode rc = - kernel_session_config_set_result_config(config, false, 20, 32, 8, true, true); - CHECK(rc == KernelStatusCode_Success, "set_result_config (explicit) succeeds"); - /* Zeroed size_t fields => keep kernel defaults; bools still take effect. */ - rc = kernel_session_config_set_result_config(config, true, 0, 0, 0, false, false); - CHECK(rc == KernelStatusCode_Success, "set_result_config (zeros keep defaults) succeeds"); + 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_result_config(config, true, 0, 1000000, 0, false, false); - CHECK(rc == KernelStatusCode_Success, "set_result_config (over-ceiling clamps, not fails)"); + 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 → InvalidArgument, no crash. */ - rc = kernel_session_config_set_result_config(NULL, false, 0, 0, 0, false, false); - CHECK(rc == KernelStatusCode_InvalidArgument, "set_result_config(NULL) → InvalidArgument"); + /* 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. */ @@ -287,7 +298,7 @@ int main(void) { test_setter_null_arg_rejected(); test_proxy_and_tls_setters(); test_u2m_and_header_setters(); - test_result_config_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 index e377264c..00beca34 100644 --- a/tests/v0_c_abi_result_config_wiremock.rs +++ b/tests/v0_c_abi_result_config_wiremock.rs @@ -28,9 +28,10 @@ use std::ffi::CString; use databricks_sql_kernel::c_abi::session::{ - kernel_session_close, kernel_session_config_new, kernel_session_config_set_auth_pat, - kernel_session_config_set_http_path, kernel_session_config_set_result_config, - kernel_session_new_statement, kernel_session_open, kernel_session_t, KernelSessionConfig, + 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, @@ -112,10 +113,12 @@ unsafe fn open_session_c_abi(uri: &str, cloudfetch_enabled: Option) -> *mu KernelStatusCode::Success ); if let Some(cf) = cloudfetch_enabled { - // 0s => keep kernel defaults for the window/chunk knobs; the two - // flat-text bools stay at their defaults (false). + // 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_result_config(config, cf, 0, 0, 0, false, false), + kernel_session_config_set_client_conf(config, key.as_ptr(), value.as_ptr()), KernelStatusCode::Success ); } @@ -176,17 +179,17 @@ fn recorded_execute_disposition(cloudfetch_enabled: Option) -> String { } #[test] -fn c_abi_set_result_config_disabled_sends_inline_disposition() { - // The headline: a C-ABI host that disables CloudFetch via the typed - // setter gets SEA `disposition = INLINE` on the wire — proving the - // typed result config reaches the execute path (previously unreachable - // from the C ABI). Mirrors the Rust-crate coverage in - // tests/v0_execute_wiremock.rs. +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_set_result_config_enabled_sends_inline_or_external_links_disposition() { +fn c_abi_client_conf_cloudfetch_enabled_sends_inline_or_external_links_disposition() { assert_eq!( recorded_execute_disposition(Some(true)), "INLINE_OR_EXTERNAL_LINKS" @@ -195,9 +198,57 @@ fn c_abi_set_result_config_enabled_sends_inline_or_external_links_disposition() #[test] fn c_abi_default_result_config_sends_inline_or_external_links_disposition() { - // No set_result_config call at all → kernel default (CloudFetch on). + // 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); + } +} From bc9e25b7e9d64860e78362418721efd1cb2598b6 Mon Sep 17 00:00:00 2001 From: Vikrant Puppala Date: Mon, 10 Aug 2026 10:29:24 +0000 Subject: [PATCH 4/4] docs(c-abi): fix stale setter names in result/client-conf doc comments MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review bot flagged doc comments that still named three setters removed in the refactor to the single generic `kernel_session_config_set_client_conf`: - `KernelSessionConfig::result` field doc named `set_result_config` / `set_complex_types_as_json` / `set_intervals_as_string`. - The C-ABI result-config wiremock test's module doc and `open_session_c_abi` helper doc named `set_result_config`. All updated to name the actual `set_client_conf`. Docs only — no code or behaviour change. Refs #226 Signed-off-by: Vikrant Puppala --- src/c_abi/session.rs | 9 ++++----- tests/v0_c_abi_result_config_wiremock.rs | 20 ++++++++++---------- 2 files changed, 14 insertions(+), 15 deletions(-) diff --git a/src/c_abi/session.rs b/src/c_abi/session.rs index 2303a5b4..ef52396a 100644 --- a/src/c_abi/session.rs +++ b/src/c_abi/session.rs @@ -120,11 +120,10 @@ pub struct KernelSessionConfig { token_cache: TokenCacheConfig, /// Client-side result-management knobs (CloudFetch / inline streaming /// tuning, flat-text rendering). Populated by - /// `kernel_session_config_set_result_config`, - /// `..._set_complex_types_as_json`, and `..._set_intervals_as_string`; - /// 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 + /// `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, } diff --git a/tests/v0_c_abi_result_config_wiremock.rs b/tests/v0_c_abi_result_config_wiremock.rs index 00beca34..1151c6e6 100644 --- a/tests/v0_c_abi_result_config_wiremock.rs +++ b/tests/v0_c_abi_result_config_wiremock.rs @@ -12,18 +12,18 @@ // See the License for the specific language governing permissions and // limitations under the License. -//! C-ABI wiremock tests for the typed result-config surface -//! (`kernel_session_config_set_result_config`). +//! C-ABI wiremock tests for the client-side result-config surface +//! (`kernel_session_config_set_client_conf`). //! -//! These prove the typed client-side knobs actually reach the wire / -//! kernel behaviour through the C ABI — closing the gap where the C ABI +//! 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 the typed -//! setter 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`. +//! 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; @@ -90,7 +90,7 @@ async fn mount_execute(server: &MockServer) { .await; } -/// Open a session over the C ABI, applying `set_result_config` first when +/// Open a session over the C ABI, applying `set_client_conf` first when /// `cloudfetch_enabled` is `Some`. Returns the raw handle (caller closes). /// /// # Safety