From b5f6dda7bbc83438858ab06d7ae96f75f98788b8 Mon Sep 17 00:00:00 2001 From: Mani Kaustubh Mathur Date: Sat, 18 Jul 2026 13:33:40 +0000 Subject: [PATCH 1/4] feat(c-abi): configurable HTTP retry / backoff policy Add kernel_session_config_set_retry_config(min_wait_ms, max_wait_ms, max_retries, overall_timeout_ms) so a C-ABI host can make its own RetryWaitMin / RetryWaitMax / RetryMax / retry-budget policy authoritative instead of the kernel's built-in default. The crate already has exponential backoff with jitter and configurable HttpConfig::retry_* fields, but the C-ABI open path hardcoded ..HttpConfig::default(), so a host's retry surface was silently ignored. - New RetrySpec on KernelSessionConfig, merged into HttpConfig in build_session (co-exists with custom_headers; every other HTTP default is preserved). max_retries == 0 disables retries; overall_timeout_ms == 0 keeps the kernel default 900s budget (non-zero overrides it, matching the pyo3/napi retry_overall_timeout knob). - Rejects min_wait_ms == 0 and max_wait_ms < min_wait_ms as InvalidArgument (a degenerate range must not reach the HTTP client). - Clamps max_retries to u32::MAX - 1 so the client's max_retries + 1 total-attempts computation can't overflow (the napi/pyo3 bindings feed this via saturating_sub(1); the C ABI is the only path that could hand the client a raw u32). Caught by Isaac Review. Benefits ODBC too. Header decl + NEXT_CHANGELOG + C smoke asserts + unit tests (records-knobs incl. the u32::MAX clamp, and bad-range rejection). make check clean (fmt + clippy -D warnings + full suite + C smoke). Co-authored-by: Isaac Signed-off-by: Mani Kaustubh Mathur --- NEXT_CHANGELOG.md | 8 ++ include/databricks_kernel.h | 16 ++++ src/c_abi/session.rs | 179 +++++++++++++++++++++++++++++++++++- tests/c/session_smoke.c | 13 +++ 4 files changed, 211 insertions(+), 5 deletions(-) diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index 28a2d4ab..c0329d3b 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -11,6 +11,14 @@ changes go in their respective binding's NEXT_CHANGELOG. ### Added +- C ABI: `kernel_session_config_set_retry_config()` — expose the crate's existing + HTTP retry knobs (`HttpConfig::retry_min_wait` / `retry_max_wait` / + `retry_max_retries` / `overall_timeout`) over the C ABI so a host can make its own + `RetryWaitMin` / `RetryWaitMax` / `RetryMax` / retry-budget policy authoritative + instead of the kernel default; `max_retries=0` disables retries, and + `overall_timeout_ms=0` keeps the kernel's default 900s budget (non-zero overrides + it, matching the pyo3/napi `retry_overall_timeout` knob). Benefits ODBC too. + ### Updated ### Fixed diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h index cf42e4e6..8c9b00df 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -303,6 +303,22 @@ KernelStatusCode kernel_session_config_set_tls_allow_self_signed(KernelSessionCo KernelStatusCode kernel_session_config_set_tls_skip_hostname_verification(KernelSessionConfig* config, bool skip); +/* Configure the HTTP retry / backoff policy. `min_wait_ms` / `max_wait_ms` + * are the backoff-wait bounds between attempts (the wait is exponential + * with jitter, clamped to this range); `max_retries` is the number of + * retries AFTER the initial attempt (so at most `max_retries + 1` total + * attempts, and `0` disables retries); `overall_timeout_ms` is the cumulative + * retry budget across all attempts (`0` keeps the kernel default of 900s — + * pass non-zero to override, matching the pyo3/napi retry_overall_timeout + * knob). Lets a host's RetryWaitMin / RetryWaitMax / RetryMax / retry-timeout + * surface override the kernel's built-in policy (default 5 retries, 1s..60s, + * 900s budget) when this setter is not called. `min_wait_ms == 0` or + * `max_wait_ms < min_wait_ms` returns InvalidArgument. Benefits ODBC too. */ +KernelStatusCode kernel_session_config_set_retry_config(KernelSessionConfig* config, + uint64_t min_wait_ms, uint64_t max_wait_ms, + uint32_t max_retries, + uint64_t overall_timeout_ms); + /* ─── Session lifecycle ───────────────────────────────────────────────*/ /* diff --git a/src/c_abi/session.rs b/src/c_abi/session.rs index 24a18ef1..124bb585 100644 --- a/src/c_abi/session.rs +++ b/src/c_abi/session.rs @@ -28,6 +28,7 @@ use crate::kernel_error::Error; use crate::session::Session; use std::collections::HashMap; use std::ffi::{c_char, CStr}; +use std::time::Duration; /// Opaque session handle. Boxed [`Session`] on the Rust side. #[repr(C)] @@ -95,6 +96,12 @@ pub struct KernelSessionConfig { /// Extra HTTP headers sent on every request (accumulated by /// `..._set_custom_header`, one `(name, value)` pair per call). custom_headers: Vec<(String, String)>, + /// HTTP retry / backoff knobs (populated by `..._set_retry_config`). + /// `None` keeps the kernel default policy (exponential backoff with + /// jitter, 5 retries, 1s..60s, 900s budget); `Some` lets a host make its + /// own backoff/attempt policy authoritative (a JDBC-style `RetryWaitMin` / + /// `RetryWaitMax` / `RetryMax` surface). + retry: Option, } /// C-side proxy config captured from `kernel_session_config_set_proxy`. @@ -105,6 +112,20 @@ struct ProxySpec { bypass_hosts: Option, } +/// C-side HTTP retry config captured from +/// `kernel_session_config_set_retry_config`. The JDBC-style backoff/attempt +/// knobs a host tunes, plus the cumulative retry budget (`overall_timeout`, to +/// match the pyo3/napi `retry_overall_timeout` surface); every other +/// `HttpConfig` field (per-request timeout, pool size) keeps its default when a +/// retry spec is set. `overall_timeout` is `None` when the host left it 0, so +/// the kernel's default budget (900s) is preserved. +struct RetrySpec { + min_wait: Duration, + max_wait: Duration, + max_retries: u32, + overall_timeout: Option, +} + /// C-side TLS config captured from the `..._set_tls_*` setters. #[derive(Default)] struct TlsSpec { @@ -156,6 +177,7 @@ pub unsafe extern "C" fn kernel_session_config_new( proxy: None, tls: TlsSpec::default(), custom_headers: Vec::new(), + retry: None, }); std::ptr::write(out, Box::into_raw(config)); KernelStatusCode::Success @@ -319,6 +341,61 @@ pub unsafe extern "C" fn kernel_session_config_set_custom_header( }) } +/// Configure the HTTP retry / backoff policy: the minimum and maximum +/// backoff wait between attempts (milliseconds), the maximum number of +/// retries after the initial attempt (so a request is tried at most +/// `max_retries + 1` times), and the cumulative retry budget +/// (`overall_timeout_ms`) across all attempts. Lets a host make its own +/// `RetryWaitMin` / `RetryWaitMax` / `RetryMax` / retry-timeout surface +/// authoritative instead of the kernel's built-in default policy. +/// `max_retries == 0` disables retries (single attempt); the backoff between +/// attempts is still exponential with jitter, clamped to +/// `[min_wait_ms, max_wait_ms]`. `overall_timeout_ms == 0` keeps the kernel's +/// default budget (900s) — pass a non-zero value to override it (matching the +/// pyo3/napi `retry_overall_timeout` knob). When this setter is not called the +/// kernel keeps its default policy (5 retries, 1s..60s, 900s budget). +/// `min_wait_ms == 0` and `max_wait_ms < min_wait_ms` are rejected as +/// `InvalidArgument`. Maps to `HttpConfig::retry_min_wait` / +/// `retry_max_wait` / `retry_max_retries` / `overall_timeout`. +/// +/// # Safety +/// `config` must be a live config handle. +#[no_mangle] +pub unsafe extern "C" fn kernel_session_config_set_retry_config( + config: *mut KernelSessionConfig, + min_wait_ms: u64, + max_wait_ms: u64, + max_retries: u32, + overall_timeout_ms: u64, +) -> KernelStatusCode { + set_on_config(config, |c| { + if min_wait_ms == 0 { + return Err(Error::invalid_argument().message("retry min_wait_ms must be > 0")); + } + if max_wait_ms < min_wait_ms { + return Err( + Error::invalid_argument().message("retry max_wait_ms must be >= min_wait_ms") + ); + } + c.retry = Some(RetrySpec { + min_wait: Duration::from_millis(min_wait_ms), + max_wait: Duration::from_millis(max_wait_ms), + // Clamp to `u32::MAX - 1` so the HTTP client's `max_retries + 1` + // total-attempts computation (src/client/http.rs) can never + // overflow — a debug build would panic and a release build would + // wrap to 0, silently disabling all retries. This matches the + // effective ceiling the napi/pyo3 bindings already enforce (they + // derive the field via `saturating_sub(1)`); the C ABI is the only + // path that could otherwise hand the client an unclamped u32. + max_retries: max_retries.min(u32::MAX - 1), + // 0 => keep the kernel default budget; any non-zero value overrides it. + overall_timeout: (overall_timeout_ms != 0) + .then(|| Duration::from_millis(overall_timeout_ms)), + }); + Ok(()) + }) +} + /// Initialize kernel logging, **process-wide and once**. `level` is one /// of "OFF"/"ERROR"/"WARN"/"INFO"/"DEBUG"/"TRACE" (NULL ⇒ honour /// `RUST_LOG`, default `warn`); `file_path` is a log file (NULL ⇒ stderr). @@ -591,6 +668,7 @@ fn build_session(config: KernelSessionConfig) -> Result Result Date: Sat, 18 Jul 2026 20:04:08 +0000 Subject: [PATCH 2/4] feat(config): tune cloudfetch_max_chunks_in_memory via session_conf MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The kernel holds cloudfetch_max_chunks_in_memory (default 16) decompressed CloudFetch chunks in memory at once, bounding download parallelism and peak RSS. On large decimal-heavy result sets that default drives ~1.2 GB peak RSS (each chunk ~75 MB); lowering it trades a little throughput for a large RSS reduction (e.g. chunks=4 -> ~+449 MB). The field already exists on ResultConfig and feeds the CloudFetch pipeline, but the C ABI exposed no way to set it — a Go/ODBC consumer could not tune it. Expose it as a client-only session_conf key rather than a new C-ABI symbol, so the existing kernel_session_config_set_session_conf entry point carries it: - apply_client_result_overrides(&mut config) runs at the top of Session::open, reads cloudfetch_max_chunks_in_memory from session_conf, folds a valid positive value into config.result, and removes the key from session_conf so it can never reach the SEA wire. - Absent key keeps the ResultConfig default (16); a non-numeric or non-positive value is ignored (default preserved) with a warning rather than failing session creation — a best-effort tuning knob must not turn a typo into a connect error. - The key is deliberately NOT in SESSION_CONF_ALLOWLIST, so even without the strip step filter_session_conf would drop it; a test pins that invariant so a future allowlist edit can't promote it to a server SET param. Matched case-insensitively, consistent with the rest of the session_conf handling. 5 unit tests (apply / case-insensitive / absent-default / invalid-ignored-but-stripped / not-server-allowlisted). make check clean; full suite (798 tests) green. Co-authored-by: Isaac Signed-off-by: Mani Kaustubh Mathur --- src/session.rs | 146 ++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 145 insertions(+), 1 deletion(-) diff --git a/src/session.rs b/src/session.rs index 09e49cd0..b1c56558 100644 --- a/src/session.rs +++ b/src/session.rs @@ -217,7 +217,7 @@ impl Session { /// auth provider, the transport, and the result-reader factory; /// then calls `Transport::create_session` to mint a session id /// on the server. - pub async fn open(config: SessionConfig) -> Result { + pub async fn open(mut config: SessionConfig) -> Result { // Fetch the runtime handle up-front so a misconfigured // caller (e.g. running outside a tokio context) gets a clear // error instead of a panic deep in the transport setup. @@ -227,6 +227,12 @@ impl Session { )) })?; + // Fold client-only result knobs (e.g. cloudfetch_max_chunks_in_memory) + // carried in session_conf into the typed ResultConfig and strip them + // from session_conf, before either the reader factory reads + // config.result (below) or filter_session_conf runs on the wire body. + apply_client_result_overrides(&mut config); + let host = config.connection.host.clone(); let warehouse_id = config.connection.warehouse_id.clone(); let org_id = config.connection.org_id.clone(); @@ -785,6 +791,56 @@ 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"; + +/// 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. +/// +/// Today this handles only [`CLIENT_CONF_CLOUDFETCH_MAX_CHUNKS`]. A key +/// that is absent leaves the field at its `ResultConfig` default (16); a +/// present-but-unparseable or zero value is ignored (default preserved) +/// with a warning rather than failing session creation — a +/// best-effort tuning knob should never turn a typo into a connect +/// error. Matched case-insensitively, consistent with the rest of the +/// `session_conf` handling. +fn apply_client_result_overrides(config: &mut SessionConfig) { + let key = config + .session_conf + .keys() + .find(|k| k.eq_ignore_ascii_case(CLIENT_CONF_CLOUDFETCH_MAX_CHUNKS)) + .cloned(); + let Some(key) = key else { return }; + // Remove it regardless of parse outcome: it is a client knob and must + // never survive into `filter_session_conf` / the wire. + let raw = config.session_conf.remove(&key).unwrap_or_default(); + match raw.trim().parse::() { + Ok(n) if n > 0 => { + config.result.cloudfetch_max_chunks_in_memory = n; + crate::klog::debug!( + max_chunks_in_memory = n, + "applied client cloudfetch_max_chunks_in_memory override", + ); + } + _ => { + crate::klog::warn!( + value = %raw, + "ignoring invalid cloudfetch_max_chunks_in_memory (want a positive integer); \ + keeping the default", + ); + } + } +} + /// Project the public [`ResultConfig`] (today only carries /// CloudFetch knobs; future result-management options slot in here /// too) onto the internal `CloudFetchConfig`. @@ -1008,6 +1064,94 @@ mod retry_config_tests { let hcc = build_http_client_config(&config_with_http(http), None); assert_eq!(hcc.read_timeout, Duration::from_millis(4500)); } + + // ─── Client result-config override (cloudfetch_max_chunks_in_memory) ─── + + /// Build a minimal config carrying the given session_conf, for + /// exercising `apply_client_result_overrides` in isolation. + fn config_with_session_conf(conf: HashMap) -> SessionConfig { + let mut cfg = config_with_http(HttpConfig::default()); + cfg.session_conf = conf; + cfg + } + + /// A valid positive value folds into ResultConfig and the key is + /// stripped from session_conf so it can never reach the SEA wire. + #[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(), + "4".to_string(), + )])); + apply_client_result_overrides(&mut cfg); + assert_eq!(cfg.result.cloudfetch_max_chunks_in_memory, 4); + assert!( + cfg.session_conf.is_empty(), + "client knob must be removed from session_conf, got {:?}", + cfg.session_conf + ); + } + + /// The key is matched case-insensitively, like the rest of the + /// session_conf handling, and still stripped. + #[test] + fn cloudfetch_max_chunks_override_is_case_insensitive() { + let mut cfg = config_with_session_conf(HashMap::from([( + "CloudFetch_Max_Chunks_In_Memory".to_string(), + "8".to_string(), + )])); + apply_client_result_overrides(&mut cfg); + assert_eq!(cfg.result.cloudfetch_max_chunks_in_memory, 8); + assert!(cfg.session_conf.is_empty()); + } + + /// Absent key ⇒ the ResultConfig default (16) is preserved. + #[test] + fn cloudfetch_max_chunks_absent_keeps_default() { + let mut cfg = config_with_session_conf(HashMap::new()); + apply_client_result_overrides(&mut cfg); + assert_eq!( + cfg.result.cloudfetch_max_chunks_in_memory, + ResultConfig::default().cloudfetch_max_chunks_in_memory + ); + } + + /// A non-numeric or zero value is ignored (default preserved, no + /// connect error) but still stripped from session_conf. + #[test] + 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(), + bad.to_string(), + )])); + apply_client_result_overrides(&mut cfg); + assert_eq!( + cfg.result.cloudfetch_max_chunks_in_memory, 16, + "value {bad:?} should keep the default", + ); + assert!( + cfg.session_conf.is_empty(), + "value {bad:?} should still be stripped", + ); + } + } + + /// 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 + /// promote it to a server SET parameter. + #[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(), + "4".to_string(), + )])); + assert!( + filtered.is_empty(), + "client knob must not survive the server allowlist, got {filtered:?}", + ); + } } #[cfg(test)] From f29957733c8f6d79a7212bc8a50cf4e5ffa8dd69 Mon Sep 17 00:00:00 2001 From: Mani Kaustubh Mathur Date: Sun, 19 Jul 2026 11:51:05 +0000 Subject: [PATCH 3/4] =?UTF-8?q?test(c-abi):=20cover=20retry=E2=86=92HttpCo?= =?UTF-8?q?nfig=20merge;=20clamp=20cloudfetch=20chunk=20knob?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Addresses the two Medium findings from the /full-review pass on this PR. - F1: extract the RetrySpec→HttpConfig merge out of build_session into a pure merge_http_config() helper and unit-test it (field-for-field mapping, None overall_timeout keeps the 900s default, retry-only and headers-only configs). The merge is what actually configures live retries and previously had zero coverage. - F2: clamp cloudfetch_max_chunks_in_memory to CLOUDFETCH_MAX_CHUNKS_CEILING (256) with a warn!, mirroring the retry setter's clamp discipline, so a fat-fingered value can't drive peak RSS toward OOM (no downstream guard exists). Adds a boundary test. make check green (fmt + clippy -D warnings + 698 lib tests + C smoke). Co-authored-by: Isaac Signed-off-by: Mani Kaustubh Mathur --- src/c_abi/session.rs | 132 ++++++++++++++++++++++++++++++++++++------- src/session.rs | 60 ++++++++++++++++++-- 2 files changed, 168 insertions(+), 24 deletions(-) diff --git a/src/c_abi/session.rs b/src/c_abi/session.rs index 124bb585..a9bb9cbc 100644 --- a/src/c_abi/session.rs +++ b/src/c_abi/session.rs @@ -656,6 +656,36 @@ fn parse_scopes(s: &str) -> Option> { (!v.is_empty()).then_some(v) } +/// Fold the C-side custom headers and optional [`RetrySpec`] onto a fresh +/// [`HttpConfig`]. Both live on `HttpConfig`, so we start from defaults and set +/// only the fields a setter populated — every other HTTP default (per-request +/// timeout, pool size, and the retry knobs when no `RetrySpec` was set) is +/// preserved. +/// +/// This is the code that actually configures live retries (called from +/// `build_session` whenever headers or a retry spec were set), so it is a pure +/// helper kept unit-testable without a live session. +fn merge_http_config( + custom_headers: Vec<(String, String)>, + retry: Option, +) -> HttpConfig { + let mut http = HttpConfig { + custom_headers, + ..HttpConfig::default() + }; + if let Some(r) = retry { + http.retry_min_wait = r.min_wait; + http.retry_max_wait = r.max_wait; + http.retry_max_retries = r.max_retries; + // Only override the cumulative budget when the host set it; otherwise + // HttpConfig::default()'s 900s is preserved. + if let Some(t) = r.overall_timeout { + http.overall_timeout = t; + } + } + http +} + /// Translate the C-side config into a [`Session`], driving the async /// `Session::open` on the process-wide runtime. Errors are stored in the /// thread-local buffer; the returned `KernelStatusCode` is the mapped @@ -719,27 +749,13 @@ fn build_session(config: KernelSessionConfig) -> Result Date: Mon, 20 Jul 2026 17:18:50 +0000 Subject: [PATCH 4/4] =?UTF-8?q?fix(c-abi):=20address=20review=20=E2=80=94?= =?UTF-8?q?=20doc=20client=20knob,=20warn=20degenerate=20budget,=20determi?= =?UTF-8?q?nistic=20case-variants,=20gate=20test?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Addresses Madhavendra's /full-review findings on #178: - Document the client-only `cloudfetch_max_chunks_in_memory` session_conf key at the C-ABI boundary (header comment near set_session_conf + NEXT_CHANGELOG entry) so the ODBC/Go consumers can discover it. - Retry setter: warn (not reject) when a non-zero overall_timeout_ms is below min_wait_ms — the budget is exhausted before the first backoff so no retries run, but a coherent single-attempt config must not hard-fail a host connect. Document that the retry budget is always bounded (no unbounded sentinel; a large max_retries is still capped by it). - apply_client_result_overrides: collect ALL case-insensitive spellings of the chunk key, apply the lexicographically-last deterministically, and strip every variant — was nondeterministic across HashMap iteration order. - De-duplicate the retry defaults prose: state 900s/5/1s..60s once in the host-facing header; Rust docs now point at HttpConfig::default(). Drop the repeated "matching the pyo3/napi" clause and the merge_http_config call-site comment that restated its own doc. - Add an end-to-end build_session test: a retry-only config with retries disabled must fail its lone attempt against a 503, proving the retry spec reaches the client (a gate regression to headers-only would retry and open). Add a small-budget acceptance test. make check green (fmt + clippy -D warnings + full suite + C smoke). Co-authored-by: Isaac Signed-off-by: Mani Kaustubh Mathur --- NEXT_CHANGELOG.md | 14 ++- include/databricks_kernel.h | 33 +++++-- src/c_abi/session.rs | 189 +++++++++++++++++++++++++++++++----- src/session.rs | 83 ++++++++++++++-- 4 files changed, 280 insertions(+), 39 deletions(-) diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index c0329d3b..d4f1aadb 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -16,8 +16,18 @@ changes go in their respective binding's NEXT_CHANGELOG. `retry_max_retries` / `overall_timeout`) over the C ABI so a host can make its own `RetryWaitMin` / `RetryWaitMax` / `RetryMax` / retry-budget policy authoritative instead of the kernel default; `max_retries=0` disables retries, and - `overall_timeout_ms=0` keeps the kernel's default 900s budget (non-zero overrides - it, matching the pyo3/napi `retry_overall_timeout` knob). Benefits ODBC too. + `overall_timeout_ms=0` keeps the kernel's default budget (non-zero overrides it). + The retry budget is always bounded — a large `max_retries` is still capped by it. + Benefits ODBC too. (Consumed by the Go driver via `WithRetries`, + databricks/databricks-sql-go#412.) +- C ABI: client-only `session_conf` key `cloudfetch_max_chunks_in_memory` — carried + by the existing `kernel_session_config_set_session_conf()` setter (no new symbol), + it bounds how many decompressed CloudFetch chunks the kernel holds in memory at + once (peak RSS on large result sets; default 16). Accepts a positive integer; + a value above the kernel ceiling (256) is clamped, and a non-numeric / non-positive + value is ignored (default preserved) with a warning rather than failing session + creation. The key is client-only — it is consumed before session creation and never + reaches the SEA wire. Benefits ODBC too. ### Updated diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h index 8c9b00df..c235cd14 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -249,7 +249,17 @@ KernelStatusCode kernel_session_config_set_auth_u2m(KernelSessionConfig* config, uint16_t redirect_port, const char* scopes); -/* Add (or overwrite) one server-bound session-conf entry. */ +/* Add (or overwrite) one session-conf entry. Keys are normally server SET + * parameters forwarded on the SEA wire (allowlist-filtered). A small set of + * reserved keys are instead CLIENT-ONLY: they tune the kernel locally, are + * consumed before session creation, and NEVER reach the wire. Client-only keys + * (matched case-insensitively): + * + * cloudfetch_max_chunks_in_memory — positive integer; how many decompressed + * CloudFetch chunks the kernel holds in memory at once (bounds peak RSS on + * large result sets; default 16). A value above the kernel ceiling (256) is + * clamped; a non-numeric / non-positive value is ignored (default kept) with + * a warning — a bad tuning value never fails session open. */ KernelStatusCode kernel_session_config_set_session_conf(KernelSessionConfig* config, const char* key, const char* value); @@ -308,12 +318,21 @@ KernelStatusCode kernel_session_config_set_tls_skip_hostname_verification(Kernel * with jitter, clamped to this range); `max_retries` is the number of * retries AFTER the initial attempt (so at most `max_retries + 1` total * attempts, and `0` disables retries); `overall_timeout_ms` is the cumulative - * retry budget across all attempts (`0` keeps the kernel default of 900s — - * pass non-zero to override, matching the pyo3/napi retry_overall_timeout - * knob). Lets a host's RetryWaitMin / RetryWaitMax / RetryMax / retry-timeout - * surface override the kernel's built-in policy (default 5 retries, 1s..60s, - * 900s budget) when this setter is not called. `min_wait_ms == 0` or - * `max_wait_ms < min_wait_ms` returns InvalidArgument. Benefits ODBC too. */ + * retry budget across all attempts (`0` keeps the kernel default — pass + * non-zero to override it). Lets a host's RetryWaitMin / RetryWaitMax / + * RetryMax / retry-timeout surface override the kernel's built-in policy + * (default 5 retries, 1s..60s, 900s budget) when this setter is not called. + * + * The retry budget is ALWAYS bounded — there is no "unlimited" value. A large + * `max_retries` is still capped by the (default or overridden) budget: if the + * exponential backoff sums past `overall_timeout_ms` the remaining attempts do + * not run, so raise `overall_timeout_ms` alongside a large `max_retries` if you + * want them all to fire. A non-zero `overall_timeout_ms` smaller than + * `min_wait_ms` guarantees ZERO retries (the first backoff already exceeds the + * budget); it is accepted but the kernel logs a warning. + * + * `min_wait_ms == 0` or `max_wait_ms < min_wait_ms` returns InvalidArgument. + * Benefits ODBC too. */ KernelStatusCode kernel_session_config_set_retry_config(KernelSessionConfig* config, uint64_t min_wait_ms, uint64_t max_wait_ms, uint32_t max_retries, diff --git a/src/c_abi/session.rs b/src/c_abi/session.rs index a9bb9cbc..573bbf29 100644 --- a/src/c_abi/session.rs +++ b/src/c_abi/session.rs @@ -98,9 +98,9 @@ pub struct KernelSessionConfig { custom_headers: Vec<(String, String)>, /// HTTP retry / backoff knobs (populated by `..._set_retry_config`). /// `None` keeps the kernel default policy (exponential backoff with - /// jitter, 5 retries, 1s..60s, 900s budget); `Some` lets a host make its - /// own backoff/attempt policy authoritative (a JDBC-style `RetryWaitMin` / - /// `RetryWaitMax` / `RetryMax` surface). + /// jitter; see [`HttpConfig::default`] for the concrete values); `Some` + /// lets a host make its own backoff/attempt policy authoritative (a + /// JDBC-style `RetryWaitMin` / `RetryWaitMax` / `RetryMax` surface). retry: Option, } @@ -114,11 +114,10 @@ struct ProxySpec { /// C-side HTTP retry config captured from /// `kernel_session_config_set_retry_config`. The JDBC-style backoff/attempt -/// knobs a host tunes, plus the cumulative retry budget (`overall_timeout`, to -/// match the pyo3/napi `retry_overall_timeout` surface); every other -/// `HttpConfig` field (per-request timeout, pool size) keeps its default when a -/// retry spec is set. `overall_timeout` is `None` when the host left it 0, so -/// the kernel's default budget (900s) is preserved. +/// knobs a host tunes, plus the cumulative retry budget (`overall_timeout`); +/// every other `HttpConfig` field (per-request timeout, pool size) keeps its +/// default when a retry spec is set. `overall_timeout` is `None` when the host +/// left it 0, so [`HttpConfig::default`]'s budget is preserved. struct RetrySpec { min_wait: Duration, max_wait: Duration, @@ -347,13 +346,23 @@ pub unsafe extern "C" fn kernel_session_config_set_custom_header( /// `max_retries + 1` times), and the cumulative retry budget /// (`overall_timeout_ms`) across all attempts. Lets a host make its own /// `RetryWaitMin` / `RetryWaitMax` / `RetryMax` / retry-timeout surface -/// authoritative instead of the kernel's built-in default policy. -/// `max_retries == 0` disables retries (single attempt); the backoff between -/// attempts is still exponential with jitter, clamped to -/// `[min_wait_ms, max_wait_ms]`. `overall_timeout_ms == 0` keeps the kernel's -/// default budget (900s) — pass a non-zero value to override it (matching the -/// pyo3/napi `retry_overall_timeout` knob). When this setter is not called the -/// kernel keeps its default policy (5 retries, 1s..60s, 900s budget). +/// authoritative instead of the kernel's built-in default policy (see +/// [`HttpConfig::default`] for the values that apply when this setter is not +/// called). `max_retries == 0` disables retries (single attempt); the backoff +/// between attempts is still exponential with jitter, clamped to +/// `[min_wait_ms, max_wait_ms]`. +/// +/// `overall_timeout_ms == 0` keeps the kernel's default budget — pass a +/// non-zero value to override it (matching the pyo3/napi `retry_overall_timeout` +/// knob). There is no sentinel for "no budget": the retry budget is *always* +/// bounded, so a large `max_retries` is still capped by the (default or +/// overridden) budget. If exponential backoff sums past the budget before +/// `max_retries` is reached, the remaining attempts do not run — raise +/// `overall_timeout_ms` alongside a large `max_retries` if you want them all to +/// fire. In particular a non-zero `overall_timeout_ms` smaller than +/// `min_wait_ms` guarantees zero retries (the first backoff already exceeds the +/// budget); this is accepted but logged at `warn`. +/// /// `min_wait_ms == 0` and `max_wait_ms < min_wait_ms` are rejected as /// `InvalidArgument`. Maps to `HttpConfig::retry_min_wait` / /// `retry_max_wait` / `retry_max_retries` / `overall_timeout`. @@ -377,6 +386,20 @@ pub unsafe extern "C" fn kernel_session_config_set_retry_config( Error::invalid_argument().message("retry max_wait_ms must be >= min_wait_ms") ); } + // A non-zero budget below the first backoff wait guarantees zero + // retries (the client stops before the first sleep — src/client/http.rs). + // Accept it (the single attempt is still coherent, and a valid-looking + // config must not hard-fail a host's connect) but warn: the host has + // asked for retries that can never fire. + if overall_timeout_ms != 0 && overall_timeout_ms < min_wait_ms { + crate::klog::warn!( + overall_timeout_ms, + min_wait_ms, + max_retries, + "retry overall_timeout_ms is below min_wait_ms; the retry budget is \ + exhausted before the first backoff, so no retries will run", + ); + } c.retry = Some(RetrySpec { min_wait: Duration::from_millis(min_wait_ms), max_wait: Duration::from_millis(max_wait_ms), @@ -678,7 +701,7 @@ fn merge_http_config( http.retry_max_wait = r.max_wait; http.retry_max_retries = r.max_retries; // Only override the cumulative budget when the host set it; otherwise - // HttpConfig::default()'s 900s is preserved. + // HttpConfig::default()'s budget is preserved. if let Some(t) = r.overall_timeout { http.overall_timeout = t; } @@ -748,12 +771,8 @@ fn build_session(config: KernelSessionConfig) -> Result = config .session_conf .keys() - .find(|k| k.eq_ignore_ascii_case(CLIENT_CONF_CLOUDFETCH_MAX_CHUNKS)) - .cloned(); - let Some(key) = key else { return }; - // Remove it regardless of parse outcome: it is a client knob and must - // never survive into `filter_session_conf` / the wire. - let raw = config.session_conf.remove(&key).unwrap_or_default(); + .filter(|k| k.eq_ignore_ascii_case(CLIENT_CONF_CLOUDFETCH_MAX_CHUNKS)) + .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; + } + } match raw.trim().parse::() { Ok(n) if n > 0 => { // Clamp to a sane ceiling: peak RSS scales with this knob, so an @@ -1128,6 +1153,48 @@ mod retry_config_tests { assert!(cfg.session_conf.is_empty()); } + /// Two spellings differing only in case resolve deterministically to the + /// lexicographically-last one (not whichever HashMap iteration yields + /// first), every variant is stripped, and an unrelated server key survives + /// untouched. Guards against both the nondeterministic-winner bug and an + /// over-broad removal that would wipe legitimate server SET params. + #[test] + fn cloudfetch_max_chunks_duplicate_case_variants_are_deterministic() { + // "cloudfetch_..." (lowercase 'c') sorts after "CloudFetch_..." + // (uppercase 'C') in ASCII, so the lowercase spelling's value (200) + // wins regardless of insertion order; 200 clamps to the ceiling. + let mut cfg = config_with_session_conf(HashMap::from([ + ( + "CloudFetch_Max_Chunks_In_Memory".to_string(), + "8".to_string(), + ), + ( + "cloudfetch_max_chunks_in_memory".to_string(), + "200".to_string(), + ), + // A benign, allowlisted server param that must NOT be removed. + ("ansi_mode".to_string(), "true".to_string()), + ])); + apply_client_result_overrides(&mut cfg); + assert_eq!( + cfg.result.cloudfetch_max_chunks_in_memory, 200, + "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)), + "every case variant of the client knob must be stripped, got {:?}", + cfg.session_conf + ); + assert_eq!( + cfg.session_conf.get("ansi_mode").map(String::as_str), + Some("true"), + "an unrelated server param must survive untouched, got {:?}", + cfg.session_conf + ); + } + /// Absent key ⇒ the ResultConfig default (16) is preserved. #[test] fn cloudfetch_max_chunks_absent_keeps_default() {