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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 37 additions & 2 deletions include/databricks_kernel.h
Original file line number Diff line number Diff line change
Expand Up @@ -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,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium — This PR renames an exported C-ABI symbol — kernel_session_config_set_token_cache → kernel_session_config_set_u2m_token_cache_config — in both the hand-maintained header and src/c_abi/session.rs:670. This is a breaking ABI change: any ODBC/Go host that links against the old symbol name will fail to resolve at load time.

The rename appears unrelated to this PR's stated purpose (client-side result-config knobs) and isn't mentioned in the PR description. If it's intentional, it deserves its own line in the changelog/description and a note that it breaks the previous symbol; if it slipped in from a rebase, it should be dropped from this PR. The rename itself is applied consistently (no dangling references to the old name remain), so this is a scoping/intent concern rather than a build break.

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 ───────────────────────────────────────────────*/

Expand Down
74 changes: 71 additions & 3 deletions src/c_abi/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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`.
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand All @@ -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.
Expand Down Expand Up @@ -804,6 +870,7 @@ fn build_session(config: KernelSessionConfig) -> Result<Session, KernelStatusCod
retry,
ignore_transactions,
token_cache,
result,
} = config;

block_on_ffi(move || {
Expand Down Expand Up @@ -853,6 +920,7 @@ fn build_session(config: KernelSessionConfig) -> Result<Session, KernelStatusCod
.connection(connection)
.auth(auth)
.session_conf(session_conf)
.result(result)
.defaults(crate::config::DefaultOpts {
ignore_transactions,
..Default::default()
Expand Down
163 changes: 163 additions & 0 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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> {
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::<Vec<_>>(),
)));
};

// 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<bool> {
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<usize> {
match v.trim().parse::<usize>() {
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]
Expand Down
Loading
Loading