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
55 changes: 55 additions & 0 deletions pyo3/src/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,17 @@ impl Session {
/// `tls_client_cert` + `tls_client_key` (both PEM bytes) configure
/// mutual TLS. The two mTLS fields must be set together.
///
/// Retry/backoff: all optional, default to the kernel's built-in
/// policy (1s/60s backoff, 6 total attempts, 900s budget) when
/// unset. `retry_min_wait_secs` / `retry_max_wait_secs` bound the
/// exponential backoff (and clamp a server `Retry-After`);
/// `retry_max_attempts` is the **total** number of attempts
/// (converted to the kernel's retries-after-first internally, so
/// `0`/`1` both mean a single attempt); `retry_overall_timeout_secs`
/// caps cumulative time across retries. These apply to SQL +
/// CloudFetch requests; token-endpoint (auth) calls keep a fixed
/// fast-fail policy.
///
/// `session_conf` is the server-bound session configuration map
/// — passed through to SEA `session_confs` verbatim. Use for
/// `ANSI_MODE`, `TIMEZONE`, `STATEMENT_TIMEOUT`, query-tag
Expand All @@ -104,6 +115,10 @@ impl Session {
tls_skip_hostname_verify=false,
tls_client_cert=None,
tls_client_key=None,
retry_min_wait_secs=None,
retry_max_wait_secs=None,
retry_max_attempts=None,
retry_overall_timeout_secs=None,
catalog=None,
schema=None,
session_conf=None,
Expand All @@ -128,6 +143,10 @@ impl Session {
tls_skip_hostname_verify: bool,
tls_client_cert: Option<Vec<u8>>,
tls_client_key: Option<Vec<u8>>,
retry_min_wait_secs: Option<u64>,
retry_max_wait_secs: Option<u64>,
retry_max_attempts: Option<u32>,
retry_overall_timeout_secs: Option<u64>,
catalog: Option<String>,
schema: Option<String>,
session_conf: Option<HashMap<String, String>>,
Expand Down Expand Up @@ -180,6 +199,39 @@ impl Session {
None
};

// Build an HttpConfig only when the caller tuned retry/backoff;
// otherwise leave the builder on its defaults (1s/60s/5-retries).
//
// `retry_max_attempts` is the **total** number of attempts
// (matching the connector's `_retry_stop_after_attempts_count`
// and JDBC's count semantics). The kernel's `retry_max_retries`
// counts retries *after* the first attempt, so we convert with
// `max(0, attempts - 1)` here — centralising the off-by-one so
// wrappers can pass an intuitive total. `retry_max_attempts = 0`
// or `1` both mean "one attempt, no retries".
let http_config = if retry_min_wait_secs.is_some()
|| retry_max_wait_secs.is_some()
|| retry_max_attempts.is_some()
|| retry_overall_timeout_secs.is_some()
{
let mut http = databricks_sql_kernel::HttpConfig::default();
if let Some(s) = retry_min_wait_secs {
http.retry_min_wait = std::time::Duration::from_secs(s);
}
if let Some(s) = retry_max_wait_secs {
http.retry_max_wait = std::time::Duration::from_secs(s);
}
if let Some(attempts) = retry_max_attempts {
http.retry_max_retries = attempts.saturating_sub(1);
}
if let Some(s) = retry_overall_timeout_secs {
http.overall_timeout = std::time::Duration::from_secs(s);
}
Some(http)
} else {
None
};

// One tokio runtime per session. Multi-thread so CloudFetch
// chunk downloads can overlap with the main poll loop. Worker
// count left to tokio's default (logical CPU count).
Expand All @@ -206,6 +258,9 @@ impl Session {
if let Some(tls) = tls_config {
builder = builder.tls(tls);
}
if let Some(http) = http_config {
builder = builder.http(http);
}
if catalog.is_some() || schema.is_some() {
let mut defaults = databricks_sql_kernel::DefaultOpts::default();
defaults.catalog = catalog;
Expand Down
112 changes: 108 additions & 4 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -385,6 +385,7 @@ pub struct HttpConfig {
pub request_timeout: Duration,

/// Maximum total time across retries for a single logical RPC.
/// Retrying stops once cumulative elapsed time exceeds this.
pub overall_timeout: Duration,

/// Connection pool size (max idle warm sockets per remote host).
Expand All @@ -395,6 +396,26 @@ pub struct HttpConfig {
/// single host; too low a value forces fresh TLS handshakes when the
/// pool fills.
pub pool_max_idle_per_host: usize,

/// Minimum backoff wait between retry attempts. Also the floor for
/// a server-supplied `Retry-After` and the base of the exponential
/// backoff (`min_wait * 2^attempt`) used when no `Retry-After` is
/// present. Default 1s.
pub retry_min_wait: Duration,

/// Maximum backoff wait between retry attempts. Caps both the
/// exponential backoff and a server-supplied `Retry-After`.
/// Default 60s.
pub retry_max_wait: Duration,

/// Maximum number of retries **after** the initial attempt — a
/// request is attempted at most `retry_max_retries + 1` times.
/// Default 5 (→ 6 total attempts).
///
/// Wrappers exposing a "total attempts" knob (the connector's
/// `_retry_stop_after_attempts_count`, the JDBC driver, …) should
/// map it as `retry_max_retries = max(0, total_attempts - 1)`.
pub retry_max_retries: u32,
}

impl Default for HttpConfig {
Expand All @@ -403,6 +424,12 @@ impl Default for HttpConfig {
request_timeout: Duration::from_secs(120),
overall_timeout: Duration::from_secs(900),
pool_max_idle_per_host: 100,
// Mirror `RetryConfig::default()` so a stock `HttpConfig`
// produces the same retry behaviour the kernel shipped
// before these knobs were configurable.
retry_min_wait: Duration::from_secs(1),
retry_max_wait: Duration::from_secs(60),
retry_max_retries: 5,
}
}
}
Expand Down Expand Up @@ -806,10 +833,40 @@ pub(crate) const SESSION_CONF_ALLOWLIST: &[&str] = &[
"USE_CACHED_RESULT",
];

/// Filter a caller-supplied `session_conf` map against
/// [`SESSION_CONF_ALLOWLIST`]. Unknown keys are dropped with a
/// `tracing::warn!`; known keys are normalized to uppercase (the
/// server echoes uppercase, so SET-readback matches).
/// Case-sensitive session-conf keys that must be sent **verbatim**
/// rather than uppercased. These are dotted `spark.*` Spark confs (as
/// opposed to the short SET-style SQL parameters in
/// [`SESSION_CONF_ALLOWLIST`], which Databricks echoes uppercase).
/// Spark stores `SQLConf` entries under their exact registered
/// lowercase-dotted key, so uppercasing would address the wrong entry.
///
/// Each tuple is `(uppercased_lookup_key, canonical_verbatim_key)`:
/// callers are matched case-insensitively (via the uppercased lookup)
/// but the canonical form is what we send on the wire.
///
/// `spark.sql.thriftserver.metadata.metricview.enabled` enables UC
/// Metric View metadata — when set to `"true"`, `SHOW TABLES`
/// (`Metadata::tables`) returns `METRIC_VIEW` rows and `getColumns`
/// surfaces `measure` columns. Opt-in: the connector sets it from its
/// `enable_metric_view_metadata` kwarg (default off), matching the
/// JDBC driver's `EnableMetricViewMetadata` (default `0`). The kernel
/// already lists `METRIC_VIEW` among its table types; this lets the
/// enabling conf through so the server actually emits the rows.
pub(crate) const SESSION_CONF_CASE_SENSITIVE_ALLOWLIST: &[(&str, &str)] = &[(
"SPARK.SQL.THRIFTSERVER.METADATA.METRICVIEW.ENABLED",
"spark.sql.thriftserver.metadata.metricview.enabled",
)];

/// Filter a caller-supplied `session_conf` map against the allowlists.
/// Unknown keys are dropped with a `tracing::warn!`.
///
/// - Keys in [`SESSION_CONF_ALLOWLIST`] are normalized to **uppercase**
/// (the server echoes uppercase for these SET-style params, so
/// SET-readback matches).
/// - Keys in [`SESSION_CONF_CASE_SENSITIVE_ALLOWLIST`] (dotted
/// `spark.*` confs) are matched case-insensitively but emitted in
/// their **canonical verbatim** form — Spark conf keys are
/// case-sensitive and must not be uppercased.
pub(crate) fn filter_session_conf(
raw: std::collections::HashMap<String, String>,
) -> std::collections::HashMap<String, String> {
Expand All @@ -819,6 +876,13 @@ pub(crate) fn filter_session_conf(
let upper = k.to_ascii_uppercase();
if SESSION_CONF_ALLOWLIST.contains(&upper.as_str()) {
out.insert(upper, v);
} else if let Some((_, canonical)) = SESSION_CONF_CASE_SENSITIVE_ALLOWLIST
.iter()
.find(|(lookup, _)| *lookup == upper.as_str())
{
// Send the canonical lowercase-dotted form verbatim, not
// the caller's casing and not uppercased.
out.insert((*canonical).to_string(), v);
} else {
tracing::warn!(
key = %k,
Expand Down Expand Up @@ -861,6 +925,46 @@ mod tests {
assert_eq!(out.get("TIMEZONE").map(String::as_str), Some("UTC"));
}

#[test]
fn session_conf_filter_passes_metricview_conf_verbatim() {
// The metric-view conf is a dotted spark.* key: it must survive
// the allowlist AND be emitted lowercase-verbatim (NOT
// uppercased like the SET-style params), because Spark conf
// keys are case-sensitive.
let mut raw = std::collections::HashMap::new();
raw.insert(
"spark.sql.thriftserver.metadata.metricview.enabled".to_string(),
"true".to_string(),
);
let out = filter_session_conf(raw);
assert_eq!(
out.get("spark.sql.thriftserver.metadata.metricview.enabled")
.map(String::as_str),
Some("true"),
);
// It must NOT have been uppercased.
assert!(!out.contains_key("SPARK.SQL.THRIFTSERVER.METADATA.METRICVIEW.ENABLED"));
assert_eq!(out.len(), 1);
}

#[test]
fn session_conf_filter_metricview_match_is_case_insensitive() {
// A caller passing the key in any casing is recognised, but the
// canonical lowercase form is always what we send.
let mut raw = std::collections::HashMap::new();
raw.insert(
"SPARK.SQL.THRIFTSERVER.METADATA.METRICVIEW.ENABLED".to_string(),
"true".to_string(),
);
let out = filter_session_conf(raw);
assert_eq!(
out.get("spark.sql.thriftserver.metadata.metricview.enabled")
.map(String::as_str),
Some("true"),
);
assert_eq!(out.len(), 1);
}

#[test]
fn session_conf_allowlist_covers_jdbc_set() {
// Parity check: every key the Java driver accepts must be
Expand Down
96 changes: 92 additions & 4 deletions src/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -600,14 +600,24 @@ fn build_http_client_config(config: &SessionConfig, org_id: Option<String>) -> H
hcc
}

/// Build the per-category retry config for the HTTP client. v0
/// matches the legacy ADBC defaults: global 900s/5-retries with an
/// auth-specific 30s/3-retries override so token endpoint calls
/// fail fast.
/// Build the per-category retry config for the HTTP client.
///
/// The global config is driven by the public [`HttpConfig`] retry
/// knobs (`retry_min_wait` / `retry_max_wait` / `retry_max_retries` /
/// `overall_timeout`), so callers can tune backoff and attempt counts.
///
/// The `Auth` category keeps a **fixed** fast-fail override (30s /
/// 3 retries) regardless of the user's global settings: token-endpoint
/// calls must not inherit a generous `overall_timeout` (e.g. 900s) or
/// they'd hang for many minutes on an unreachable IdP. This matches the
/// legacy ADBC behaviour and is intentionally not user-overridable.
fn build_retry_configs_for_session(
config: &SessionConfig,
) -> std::collections::HashMap<RequestCategory, RetryConfig> {
let global = RetryConfig {
min_wait: config.http.retry_min_wait,
max_wait: config.http.retry_max_wait,
max_retries: config.http.retry_max_retries,
overall_timeout: config.http.overall_timeout,
..RetryConfig::default()
};
Expand Down Expand Up @@ -722,3 +732,81 @@ async fn build_auth_provider(
.message("AuthConfig::External is reserved; v0 wires PAT + OAuthM2M + OAuthU2M only")),
}
}

#[cfg(test)]
mod retry_config_tests {
use super::*;
use crate::client::retry::RequestCategory;
use std::time::Duration;

/// Build a minimal `SessionConfig` with the given `HttpConfig` for
/// exercising `build_retry_configs_for_session` in isolation.
fn config_with_http(http: HttpConfig) -> SessionConfig {
SessionConfig {
connection: ConnectionConfig::new("https://example.databricks.com", "wh123"),
defaults: None,
auth: AuthConfig::Pat {
token: "dapi-test".to_string(),
},
session_conf: Default::default(),
http,
proxy: None,
tls: Default::default(),
result: Default::default(),
logging: Default::default(),
telemetry: Default::default(),
transport: None,
}
}

#[test]
fn http_retry_knobs_flow_into_global_config() {
let http = HttpConfig {
retry_min_wait: Duration::from_secs(3),
retry_max_wait: Duration::from_secs(90),
retry_max_retries: 7,
overall_timeout: Duration::from_secs(600),
..HttpConfig::default()
};
let configs = build_retry_configs_for_session(&config_with_http(http));

// SEA + CloudFetch inherit the user-tuned global config.
for cat in [RequestCategory::Sea, RequestCategory::CloudFetch] {
let c = &configs[&cat];
assert_eq!(c.min_wait, Duration::from_secs(3), "{cat:?} min_wait");
assert_eq!(c.max_wait, Duration::from_secs(90), "{cat:?} max_wait");
assert_eq!(c.max_retries, 7, "{cat:?} max_retries");
assert_eq!(
c.overall_timeout,
Duration::from_secs(600),
"{cat:?} overall_timeout"
);
}
}

#[test]
fn auth_override_stays_fixed_regardless_of_user_knobs() {
// Even with a very generous user overall_timeout, the Auth
// category keeps its fast-fail 30s / 3-retry override so token
// endpoint calls can't hang for the full global budget.
let http = HttpConfig {
retry_max_retries: 99,
overall_timeout: Duration::from_secs(3600),
..HttpConfig::default()
};
let configs = build_retry_configs_for_session(&config_with_http(http));
let auth = &configs[&RequestCategory::Auth];
assert_eq!(auth.overall_timeout, Duration::from_secs(30));
assert_eq!(auth.max_retries, 3);
}

#[test]
fn defaults_preserve_legacy_behaviour() {
let configs = build_retry_configs_for_session(&config_with_http(HttpConfig::default()));
let sea = &configs[&RequestCategory::Sea];
assert_eq!(sea.min_wait, Duration::from_secs(1));
assert_eq!(sea.max_wait, Duration::from_secs(60));
assert_eq!(sea.max_retries, 5);
assert_eq!(sea.overall_timeout, Duration::from_secs(900));
}
}
Loading