From 1e97d7876a69e73fe5a97a5a70af03a01f3304d5 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Wed, 18 Nov 2026 03:07:44 +0000 Subject: [PATCH 01/13] feat(http): negotiate HTTP/2 with an HTTP/1.1 opt-out Signed-off-by: Aakash Saravanan --- CONNECTION_PARAMETERS.md | 6 + Cargo.lock | 4 + Cargo.toml | 7 +- NEXT_CHANGELOG.md | 5 + adbc/Cargo.lock | 51 +++++ adbc/README.md | 9 +- adbc/src/config.rs | 14 ++ include/databricks_kernel.h | 5 + napi/Cargo.lock | 1 + napi/NEXT_CHANGELOG.md | 3 + napi/index.d.ts | 2 + napi/src/database.rs | 19 ++ pyo3/Cargo.lock | 27 +++ pyo3/NEXT_CHANGELOG.md | 3 + pyo3/src/session.rs | 9 +- src/c_abi/session.rs | 28 ++- src/client/http.rs | 14 ++ src/config.rs | 5 + src/session.rs | 1 + src/telemetry/manager.rs | 64 ++++-- src/telemetry/runtime.rs | 12 +- tests/http2.rs | 393 ++++++++++++++++++++++++++++++++++++ 22 files changed, 647 insertions(+), 35 deletions(-) create mode 100644 tests/http2.rs diff --git a/CONNECTION_PARAMETERS.md b/CONNECTION_PARAMETERS.md index edcf6001..1adf8d68 100644 --- a/CONNECTION_PARAMETERS.md +++ b/CONNECTION_PARAMETERS.md @@ -125,8 +125,14 @@ until implemented) and `External` (a caller-supplied `TokenProvider`). ## `HttpConfig` — HTTP client (optional) +The `http2_enabled` setting applies to all kernel-owned HTTPS requests: authentication and +discovery, SQL requests, result downloads, feature flags, and telemetry. TLS +negotiates the protocol with each peer. An HTTP proxy can use HTTP/1.1 for +CONNECT while the HTTPS connection inside the tunnel negotiates HTTP/2. + | Field | Description | Default | |-------|-------------|---------| +| `http2_enabled` | Negotiate HTTP/2 for HTTPS with HTTP/1.1 fallback. Set `false` to force HTTP/1.1. | `true` | | `request_timeout` | Per-request timeout (connect + body). | `120s` | | `overall_timeout` | Maximum total time across retries for one logical RPC. | `900s` | | `pool_max_idle_per_host` | Connection-pool size (max idle warm sockets per host). Raise for bursty concurrent workloads. | `100` | diff --git a/Cargo.lock b/Cargo.lock index b8867a94..0262de43 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -655,14 +655,17 @@ dependencies = [ "arrow-select", "async-trait", "base64", + "bytes", "cbc 0.2.1", "chrono", "dashmap", "dirs", "futures", "geo-traits", + "h2", "hex", "hmac 0.13.0", + "http", "jsonwebtoken", "log", "lz4_flex", @@ -2288,6 +2291,7 @@ dependencies = [ "bytes", "futures-core", "futures-util", + "h2", "http", "http-body", "http-body-util", diff --git a/Cargo.toml b/Cargo.toml index f428c382..04e89dc4 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -59,7 +59,7 @@ arrow-ipc = "59" # (which `native-tls` pulls in on Linux) collides with Node's symbols at # module load time and segfaults the process before any Rust code runs. # `rustls` is pure Rust + ring and avoids the conflict entirely. -reqwest = { version = "0.12", default-features = false, features = ["json", "gzip", "stream"] } +reqwest = { version = "0.12", default-features = false, features = ["json", "gzip", "stream", "http2"] } native-tls = { version = "0.2", optional = true } rustls = { version = "0.23.41", optional = true, default-features = false, features = ["ring", "std", "tls12"] } # Enforce TLS dependency minimums for consumers with their own lockfiles. @@ -150,6 +150,9 @@ tokio = { version = "1", features = ["rt-multi-thread", "macros", "net", "io-uti wiremock = "0.6" tempfile = "3" log = "0.4" +bytes = "1" +h2 = "0.4" +http = "1" # Generate JWT test keys in-process to avoid PEM fixtures and an external # `openssl` dependency. `ring` already backs runtime JWT signing. rsa = { version = "0.9", features = ["pem"] } @@ -195,7 +198,7 @@ tokio-rustls = { version = "0.26.4", default-features = false, features = ["ring # guarantee — items 1 and 2 above are. [features] default = ["tls-native"] -tls-native = ["reqwest/native-tls", "dep:native-tls"] +tls-native = ["reqwest/native-tls-alpn", "dep:native-tls"] # `rustls-tls` alone is `reqwest/rustls-tls-webpki-roots` — the bundled Mozilla # root set only, which does NOT read the OS system trust store. `tls-native` # (native-tls → OpenSSL) DOES read `/etc/ssl/...`, so a `tls-rustls` build behind diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index 8577a424..4cec2610 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -16,6 +16,11 @@ changes go in their respective binding's NEXT_CHANGELOG. ### Changed +- HTTPS requests negotiate HTTP/2 with HTTP/1.1 fallback by default. Set + `HttpConfig.http2_enabled` to `false`, or use + `kernel_session_config_set_http2_enabled(config, false)`, to force HTTP/1.1. + Rust ADBC exposes `adbc.databricks.http.http2_enabled`. + - Rust ADBC requests identify themselves as `RustADBCDatabricksDriver/` with an optional partner entry from `adbc.databricks.user_agent_entry` (`adbc.spark.user_agent_entry` is a compatibility alias). `User-Agent` in diff --git a/adbc/Cargo.lock b/adbc/Cargo.lock index 37956eeb..7175b95d 100644 --- a/adbc/Cargo.lock +++ b/adbc/Cargo.lock @@ -1183,6 +1183,21 @@ dependencies = [ "want", ] +[[package]] +name = "hyper-rustls" +version = "0.27.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfa8e654703247911e29c23fbeaa261834bd9bb74efba2f9acddc37bfb127f53" +dependencies = [ + "http", + "hyper", + "hyper-util", + "rustls", + "tokio", + "tokio-rustls", + "tower-service", +] + [[package]] name = "hyper-tls" version = "0.6.0" @@ -2115,10 +2130,12 @@ dependencies = [ "bytes", "futures-core", "futures-util", + "h2", "http", "http-body", "http-body-util", "hyper", + "hyper-rustls", "hyper-tls", "hyper-util", "js-sys", @@ -2180,6 +2197,19 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "rustls" +version = "0.23.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +dependencies = [ + "once_cell", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + [[package]] name = "rustls-pki-types" version = "1.15.1" @@ -2189,6 +2219,17 @@ dependencies = [ "zeroize", ] +[[package]] +name = "rustls-webpki" +version = "0.103.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + [[package]] name = "rustversion" version = "1.0.23" @@ -2646,6 +2687,16 @@ dependencies = [ "tokio", ] +[[package]] +name = "tokio-rustls" +version = "0.26.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9cc2678c2cdd569ef8215e2afd7954ada2ae20b4fdd2c5fe6139a3b02d105db" +dependencies = [ + "rustls", + "tokio", +] + [[package]] name = "tokio-util" version = "0.7.20" diff --git a/adbc/README.md b/adbc/README.md index 7b5bac0f..e27cac40 100644 --- a/adbc/README.md +++ b/adbc/README.md @@ -67,6 +67,13 @@ Exactly one of `adbc.databricks.http_path` and parameter in the HTTP path when the workspace connection details include one. Canonical `adbc.databricks.*` names take precedence over compatibility aliases. +## HTTP transport + +HTTPS requests negotiate HTTP/2 by default, with HTTP/1.1 fallback when the +peer does not support HTTP/2. Set `adbc.databricks.http.http2_enabled` to `false` +to force HTTP/1.1 for all kernel-owned HTTPS requests, including authentication, +query requests, result downloads, and telemetry. + ## Authentication Set `adbc.databricks.auth.type` to one of `pat`, `oauth_m2m`, `oauth_u2m`, @@ -98,7 +105,7 @@ The main database option families are: | Namespace | `adbc.databricks.catalog`, `adbc.databricks.schema` | | Attribution | `adbc.databricks.user_agent_entry` | | Session | `adbc.databricks.session_conf.`, `adbc.databricks.ssp_ansi_mode`, `adbc.databricks.ssp_timezone`, `adbc.databricks.query_tags` | -| HTTP | request/overall timeouts, idle pool size, retry limits/backoff, response compression, JSON custom headers | +| HTTP | HTTP/2 negotiation, request/overall timeouts, idle pool size, retry limits/backoff, response compression, JSON custom headers | | Proxy | URL, username, password, bypass hosts | | TLS/mTLS | CA file or PEM, client certificate/key file or PEM, self-signed and hostname-verification controls | | Logging | filter and file | diff --git a/adbc/src/config.rs b/adbc/src/config.rs index 65b42e9e..baa67bee 100644 --- a/adbc/src/config.rs +++ b/adbc/src/config.rs @@ -399,6 +399,7 @@ impl DatabaseConfig { fn set_http(&mut self, key: &str, value: OptionValue) -> Result<()> { match key { + "adbc.databricks.http.http2_enabled" => self.http.http2_enabled = boolean(value, key)?, "adbc.databricks.http.request_timeout_ms" => { self.http.request_timeout = duration(value, key, false)? } @@ -1692,6 +1693,19 @@ mod tests { } } + #[test] + fn http2_default_and_opt_out_reach_kernel_config() { + let mut config = DatabaseConfig::default(); + set(&mut config, HOST, "https://example.databricks.com"); + set(&mut config, HTTP_PATH, "/sql/1.0/warehouses/warehouse-id"); + set(&mut config, ACCESS_TOKEN, "sentinel-token"); + assert!(config.resolve().unwrap().http.http2_enabled); + for enabled in [false, true] { + set(&mut config, "adbc.databricks.http.http2_enabled", enabled); + assert_eq!(config.resolve().unwrap().http.http2_enabled, enabled); + } + } + #[test] fn http_pool_and_custom_headers_reach_kernel_config() { let mut config = DatabaseConfig::default(); diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h index e167f181..5f25fed0 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -361,6 +361,11 @@ KernelStatusCode kernel_session_config_set_enable_geospatial_support( KernelStatusCode kernel_session_config_set_custom_header(KernelSessionConfig* config, const char* name, const char* value); +/* Negotiate HTTP/2 for all HTTPS requests, with HTTP/1.1 fallback. + * Enabled by default. Set enabled to false to use HTTP/1.1 only. */ +KernelStatusCode kernel_session_config_set_http2_enabled( + KernelSessionConfig* config, bool enabled); + /* Configure whether authenticated SEA responses may use HTTP compression. * Disabled by default. */ KernelStatusCode kernel_session_config_set_sea_response_compression_enabled( diff --git a/napi/Cargo.lock b/napi/Cargo.lock index b7eb6a6d..fd5f4e61 100644 --- a/napi/Cargo.lock +++ b/napi/Cargo.lock @@ -2139,6 +2139,7 @@ dependencies = [ "bytes", "futures-core", "futures-util", + "h2", "http", "http-body", "http-body-util", diff --git a/napi/NEXT_CHANGELOG.md b/napi/NEXT_CHANGELOG.md index d5ca462e..ab4da560 100644 --- a/napi/NEXT_CHANGELOG.md +++ b/napi/NEXT_CHANGELOG.md @@ -14,6 +14,9 @@ layout, or npm publishing. Pure-kernel changes go in the root ### Added +- `ConnectionOptions.enableHttp2` selects HTTP/2 negotiation for HTTPS requests. + It defaults to enabled; set it to `false` to force HTTP/1.1. + ### Changed ### Updated diff --git a/napi/index.d.ts b/napi/index.d.ts index 064f856d..5b2385f9 100644 --- a/napi/index.d.ts +++ b/napi/index.d.ts @@ -518,6 +518,8 @@ export interface ConnectionOptions { * Whether SEA API responses may use HTTP compression. Defaults to false. */ seaResponseCompressionEnabled?: boolean + /** Negotiate HTTP/2 over HTTPS by default. Set false to use HTTP/1.1 only. */ + enableHttp2?: boolean /** * Retry/backoff tuning — all optional. An unset field keeps the kernel's * built-in policy (1s/60s exponential backoff, 6 total attempts, 900s diff --git a/napi/src/database.rs b/napi/src/database.rs index 4a8fbe3f..b0a43770 100644 --- a/napi/src/database.rs +++ b/napi/src/database.rs @@ -388,6 +388,9 @@ pub struct ConnectionOptions { /// Whether SEA API responses may use HTTP compression. Defaults to false. pub sea_response_compression_enabled: Option, + /// Negotiate HTTP/2 over HTTPS by default. Set false to use HTTP/1.1 only. + pub enable_http2: Option, + /// Retry/backoff tuning — all optional. An unset field keeps the kernel's /// built-in policy (1s/60s exponential backoff, 6 total attempts, 900s /// budget). Mirrors the pyo3 binding's `retry_*` kwargs so the Node.js @@ -624,6 +627,9 @@ fn build_tls_config(options: &ConnectionOptions) -> TlsConfig { /// strings. fn build_http_config(options: &mut ConnectionOptions) -> HttpConfig { let mut http = HttpConfig::default(); + if let Some(enabled) = options.enable_http2 { + http.http2_enabled = enabled; + } http.sea_response_compression_enabled = options.sea_response_compression_enabled.unwrap_or(false); http.pool_max_idle_per_host = options @@ -955,6 +961,7 @@ mod tests { client_key_pem: None, custom_headers: None, sea_response_compression_enabled: None, + enable_http2: None, retry_min_wait_secs: None, retry_max_wait_secs: None, retry_max_attempts: None, @@ -1574,6 +1581,18 @@ mod tests { assert_eq!(http.custom_headers[1].1, "Connector/2.0"); } + #[test] + fn http2_option_preserves_default_and_opt_out() { + for enabled in [None, Some(true), Some(false)] { + let mut options = base(); + options.enable_http2 = enabled; + assert_eq!( + build_http_config(&mut options).http2_enabled, + enabled.unwrap_or(true) + ); + } + } + #[test] fn sea_response_compression_option_maps_to_http_config() { let mut defaults = base(); diff --git a/pyo3/Cargo.lock b/pyo3/Cargo.lock index c908c554..80907079 100644 --- a/pyo3/Cargo.lock +++ b/pyo3/Cargo.lock @@ -795,6 +795,12 @@ dependencies = [ "miniz_oxide", ] +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + [[package]] name = "form_urlencoded" version = "1.2.2" @@ -962,6 +968,25 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "h2" +version = "0.4.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d29020232d6aa3fb1daca64c1127cf662cf97f254ae16c18c05b8ab635fc118" +dependencies = [ + "atomic-waker", + "bytes", + "fnv", + "futures-core", + "futures-sink", + "http", + "indexmap", + "slab", + "tokio", + "tokio-util", + "tracing", +] + [[package]] name = "half" version = "2.7.1" @@ -1075,6 +1100,7 @@ dependencies = [ "bytes", "futures-channel", "futures-core", + "h2", "http", "http-body", "httparse", @@ -2051,6 +2077,7 @@ dependencies = [ "bytes", "futures-core", "futures-util", + "h2", "http", "http-body", "http-body-util", diff --git a/pyo3/NEXT_CHANGELOG.md b/pyo3/NEXT_CHANGELOG.md index e0881e54..c0e06b89 100644 --- a/pyo3/NEXT_CHANGELOG.md +++ b/pyo3/NEXT_CHANGELOG.md @@ -13,6 +13,9 @@ changes go in the root `NEXT_CHANGELOG.md`. ### Added +- `Session(enable_http2=False)` forces HTTP/1.1 for HTTPS requests. By default, + connections negotiate HTTP/2 with HTTP/1.1 fallback. + ### Changed ### Updated diff --git a/pyo3/src/session.rs b/pyo3/src/session.rs index c626ee89..5f8bed4f 100644 --- a/pyo3/src/session.rs +++ b/pyo3/src/session.rs @@ -376,6 +376,7 @@ impl Session { tls_client_cert=None, tls_client_key=None, sea_response_compression_enabled=false, + enable_http2=None, request_timeout_secs=None, max_connections=None, retry_min_wait_secs=None, @@ -443,6 +444,7 @@ impl Session { tls_client_cert: Option>, tls_client_key: Option>, sea_response_compression_enabled: bool, + enable_http2: Option, request_timeout_secs: Option, max_connections: Option, retry_min_wait_secs: Option, @@ -560,7 +562,7 @@ impl Session { // connector forwards its `http_headers`, which also carries the // composed `User-Agent`). The kernel applies them before its own // `Authorization` / `x-databricks-org-id`, which always win. - let http_config = build_http_config( + let mut http_config = build_http_config( sea_response_compression_enabled, request_timeout_secs, max_connections, @@ -570,6 +572,11 @@ impl Session { retry_overall_timeout_secs, http_headers, )?; + if let Some(enabled) = enable_http2 { + http_config + .get_or_insert_with(databricks_sql_kernel::HttpConfig::default) + .http2_enabled = enabled; + } let driver_system_configuration = build_driver_system_configuration( driver_name, diff --git a/src/c_abi/session.rs b/src/c_abi/session.rs index b3365f49..17c9f505 100644 --- a/src/c_abi/session.rs +++ b/src/c_abi/session.rs @@ -152,6 +152,7 @@ pub struct KernelSessionConfig { custom_headers: Vec<(String, String)>, /// Whether authenticated SEA responses may use HTTP compression. sea_response_compression_enabled: bool, + http2_enabled: Option, /// Total request timeout (populated by `..._set_request_timeout`). `None` /// keeps [`HttpConfig::default`]'s 120-second timeout. request_timeout: Option, @@ -288,6 +289,7 @@ pub unsafe extern "C" fn kernel_session_config_new( tls: TlsSpec::default(), custom_headers: Vec::new(), sea_response_compression_enabled: false, + http2_enabled: None, request_timeout: None, max_connections: None, retry: None, @@ -610,6 +612,22 @@ pub unsafe extern "C" fn kernel_session_config_set_custom_header( }) } +/// Negotiate HTTP/2 for HTTPS requests by default, with HTTP/1.1 fallback. +/// Set `enabled` to `false` to use HTTP/1.1 only. +/// +/// # Safety +/// `config` must be a live config handle. +#[no_mangle] +pub unsafe extern "C" fn kernel_session_config_set_http2_enabled( + config: *mut KernelSessionConfig, + enabled: bool, +) -> KernelStatusCode { + set_on_config(config, |c| { + c.http2_enabled = Some(enabled); + Ok(()) + }) +} + /// Configure whether authenticated SEA responses may use HTTP compression. /// The default is `false`. /// @@ -1651,6 +1669,7 @@ fn build_session(config: KernelSessionConfig) -> Result Result Self { Self { + http2_enabled: true, sea_response_compression_enabled: false, connect_timeout: Duration::from_secs(30), read_timeout: Duration::from_secs(60), @@ -494,6 +497,7 @@ impl DatabricksHttpClient { } else { "native-tls" }, + http2_enabled = config.http2_enabled, "DatabricksHttpClient initialised" ); @@ -524,6 +528,10 @@ impl DatabricksHttpClient { .user_agent(&config.user_agent) .redirect(redirect); + if !config.http2_enabled { + builder = builder.http1_only(); + } + // Apply TLS configuration if config.tls.enabled == Some(false) { builder = builder.https_only(false); @@ -942,6 +950,12 @@ impl DatabricksHttpClient { match self.client.execute(request).await { Ok(response) => { + debug!( + request_type = ?request_type, + host = ?response.url().host_str(), + http_version = ?response.version(), + "received HTTP response" + ); let status = response.status(); if status.is_success() { diff --git a/src/config.rs b/src/config.rs index 9c1eb0a9..7cb57aa5 100644 --- a/src/config.rs +++ b/src/config.rs @@ -748,6 +748,10 @@ impl std::fmt::Debug for AuthConfig { #[non_exhaustive] #[derive(Debug, Clone)] pub struct HttpConfig { + /// Negotiate HTTP/2 for HTTPS requests, with HTTP/1.1 fallback. + /// Defaults to `true`. Set to `false` to use HTTP/1.1 only. + pub http2_enabled: bool, + /// Whether authenticated SEA requests may negotiate HTTP response compression. /// Defaults to `false` because inline Arrow results are already LZ4-compressed. pub sea_response_compression_enabled: bool, @@ -834,6 +838,7 @@ pub struct HttpConfig { impl Default for HttpConfig { fn default() -> Self { Self { + http2_enabled: true, sea_response_compression_enabled: false, request_timeout: Duration::from_secs(120), overall_timeout: Duration::from_secs(900), diff --git a/src/session.rs b/src/session.rs index 2c1bdd79..26fa2157 100644 --- a/src/session.rs +++ b/src/session.rs @@ -1080,6 +1080,7 @@ fn validate_mtls_endpoint_scheme(config: &SessionConfig) -> Result<()> { /// [`HttpTlsConfig`] via [`HttpTlsConfig::from_public`]. fn build_http_client_config(config: &SessionConfig, org_id: Option) -> HttpClientConfig { HttpClientConfig { + http2_enabled: config.http.http2_enabled, sea_response_compression_enabled: config.http.sea_response_compression_enabled, connect_timeout: Duration::from_secs(30), // The historical internal `read_timeout` field is passed to reqwest's diff --git a/src/telemetry/manager.rs b/src/telemetry/manager.rs index 0b6551e4..d11e2de9 100644 --- a/src/telemetry/manager.rs +++ b/src/telemetry/manager.rs @@ -21,7 +21,22 @@ use std::sync::{Arc, Mutex, OnceLock}; #[derive(Default)] pub(super) struct TelemetryClientManager { - clients: Mutex>, + clients: Mutex>, +} + +#[derive(Clone, PartialEq, Eq, Hash)] +pub(super) struct TelemetryClientKey { + host: String, + http2_enabled: bool, +} + +impl TelemetryClientKey { + pub(super) fn new(host: &str, http2_enabled: bool) -> Self { + Self { + host: host.to_string(), + http2_enabled, + } + } } impl TelemetryClientManager { @@ -32,7 +47,7 @@ impl TelemetryClientManager { pub(super) fn get_or_create( &'static self, - host: &str, + key: &TelemetryClientKey, config: &TelemetryConfig, exporter: Arc, bypass_cache: bool, @@ -47,11 +62,11 @@ impl TelemetryClientManager { } let mut clients = self.clients.lock().expect("poisoned telemetry clients"); - if let Some(holder) = clients.get_mut(host) { + if let Some(holder) = clients.get_mut(key) { holder.session_count += 1; holder.lease_count += 1; return Some(TelemetryClientLease::managed( - host, + key, Arc::clone(&holder.client), self, )); @@ -59,14 +74,14 @@ impl TelemetryClientManager { let client = TelemetryClient::new(config, exporter)?; clients.insert( - host.to_string(), + key.clone(), TelemetryClientHolder { client: Arc::clone(&client), session_count: 1, lease_count: 1, }, ); - Some(TelemetryClientLease::managed(host, client, self)) + Some(TelemetryClientLease::managed(key, client, self)) } #[cfg(test)] @@ -77,13 +92,18 @@ impl TelemetryClientManager { exporter: Arc, bypass_cache: bool, ) -> TelemetryClientLease { - self.get_or_create(host, config, exporter, bypass_cache) - .expect("telemetry runtime should start") + self.get_or_create( + &TelemetryClientKey::new(host, true), + config, + exporter, + bypass_cache, + ) + .expect("telemetry runtime should start") } - fn release_session(&self, host: &str) -> Option> { + fn release_session(&self, key: &TelemetryClientKey) -> Option> { let mut clients = self.clients.lock().expect("poisoned telemetry clients"); - let holder = clients.get_mut(host)?; + let holder = clients.get_mut(key)?; debug_assert!(holder.session_count > 0); // saturating_sub (not `-= 1`) so a future double-decrement degrades // gracefully in release builds, where the debug_assert is compiled out. @@ -95,9 +115,9 @@ impl TelemetryClientManager { } } - fn release_lease(&self, host: &str, session_released: bool) -> LeaseDropAction { + fn release_lease(&self, key: &TelemetryClientKey, session_released: bool) -> LeaseDropAction { let mut clients = self.clients.lock().expect("poisoned telemetry clients"); - let Some(holder) = clients.get_mut(host) else { + let Some(holder) = clients.get_mut(key) else { return LeaseDropAction::None; }; if !session_released { @@ -112,7 +132,7 @@ impl TelemetryClientManager { holder.lease_count = holder.lease_count.saturating_sub(1); if holder.lease_count == 0 { return clients - .remove(host) + .remove(key) .map(|holder| LeaseDropAction::Close(holder.client)) .unwrap_or(LeaseDropAction::None); } @@ -136,7 +156,7 @@ impl TelemetryClientManager { self.clients .lock() .expect("poisoned telemetry clients") - .get(host) + .get(&TelemetryClientKey::new(host, true)) .map(|holder| holder.session_count) } } @@ -158,7 +178,7 @@ enum LeaseDropAction { } pub(super) struct TelemetryClientLease { - host: Option, + key: Option, client: Arc, manager: Option<&'static TelemetryClientManager>, session_released: AtomicBool, @@ -166,12 +186,12 @@ pub(super) struct TelemetryClientLease { impl TelemetryClientLease { fn managed( - host: &str, + key: &TelemetryClientKey, client: Arc, manager: &'static TelemetryClientManager, ) -> Self { Self { - host: Some(host.to_string()), + key: Some(key.clone()), client, manager: Some(manager), session_released: AtomicBool::new(false), @@ -180,7 +200,7 @@ impl TelemetryClientLease { fn unmanaged(client: Arc) -> Self { Self { - host: None, + key: None, client, manager: None, session_released: AtomicBool::new(false), @@ -196,8 +216,8 @@ impl TelemetryClientLease { return; } - let client_to_flush = match (self.manager, self.host.as_deref()) { - (Some(manager), Some(host)) => manager.release_session(host), + let client_to_flush = match (self.manager, self.key.as_ref()) { + (Some(manager), Some(key)) => manager.release_session(key), _ => Some(Arc::clone(&self.client)), }; if let Some(client) = client_to_flush { @@ -210,8 +230,8 @@ impl TelemetryClientLease { impl Drop for TelemetryClientLease { fn drop(&mut self) { let session_released = self.session_released.swap(true, Ordering::AcqRel); - let action = match (self.manager, self.host.as_deref()) { - (Some(manager), Some(host)) => manager.release_lease(host, session_released), + let action = match (self.manager, self.key.as_ref()) { + (Some(manager), Some(key)) => manager.release_lease(key, session_released), _ => LeaseDropAction::Close(Arc::clone(&self.client)), }; match action { diff --git a/src/telemetry/runtime.rs b/src/telemetry/runtime.rs index 1b8f751b..648aead1 100644 --- a/src/telemetry/runtime.rs +++ b/src/telemetry/runtime.rs @@ -15,7 +15,7 @@ use super::circuit_breaker::maybe_wrap_exporter; use super::databricks::{DatabricksTelemetryExporter, TelemetryEndpoint}; use super::exporter::TelemetryExporter; -use super::manager::{TelemetryClientLease, TelemetryClientManager}; +use super::manager::{TelemetryClientKey, TelemetryClientLease, TelemetryClientManager}; use super::models::{ unix_time_millis, DriverAuthFlow, DriverAuthMech, DriverConnectionParameters, DriverErrorInfo, DriverMode, DriverSystemConfiguration, FrontendLogContext, FrontendLogEntry, HostDetails, @@ -66,13 +66,11 @@ impl TelemetryRuntime { connection_params: build_connection_params(connection, auth), auth_type: auth_type(auth), }); + let key = TelemetryClientKey::new(&connection.host, http_client.config().http2_enabled); let (exporter, bypass_cache) = exporter_for_config(config, connection, http_client); - let Some(lease) = TelemetryClientManager::global().get_or_create( - &connection.host, - config, - exporter, - bypass_cache, - ) else { + let Some(lease) = + TelemetryClientManager::global().get_or_create(&key, config, exporter, bypass_cache) + else { return Self::disabled(); }; diff --git a/tests/http2.rs b/tests/http2.rs new file mode 100644 index 00000000..ace76f86 --- /dev/null +++ b/tests/http2.rs @@ -0,0 +1,393 @@ +// 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. + +use bytes::Bytes; +use databricks_sql_kernel::auth::PersonalAccessToken; +use databricks_sql_kernel::client::{ + build_retry_configs, DatabricksHttpClient, HttpClientConfig, RequestType, RetryConfig, +}; +use databricks_sql_kernel::{ + AuthConfig, ConnectionConfig, HttpConfig, Session, TelemetryConfig, TlsConfig, +}; +use http::Version; +use rustls::pki_types::PrivatePkcs8KeyDer; +use std::sync::Arc; +use std::time::Duration; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::net::TcpListener; +use tokio::sync::mpsc; +use tokio::task::{JoinHandle, JoinSet}; +use tokio_rustls::TlsAcceptor; + +struct HttpsServer { + url: String, + certificate: Vec, + requests: mpsc::UnboundedReceiver<(String, Version)>, + task: JoinHandle<()>, +} + +impl Drop for HttpsServer { + fn drop(&mut self) { + self.task.abort(); + } +} + +impl HttpsServer { + async fn start(http2: bool) -> Self { + let identity = rcgen::generate_simple_self_signed(vec!["127.0.0.1".into()]).unwrap(); + let certificate = identity.cert.pem().into_bytes(); + let mut tls = rustls::ServerConfig::builder_with_provider(Arc::new( + rustls::crypto::ring::default_provider(), + )) + .with_safe_default_protocol_versions() + .unwrap() + .with_no_client_auth() + .with_single_cert( + vec![identity.cert.der().clone()], + PrivatePkcs8KeyDer::from(identity.signing_key.serialize_der()).into(), + ) + .unwrap(); + if http2 { + tls.alpn_protocols.push(b"h2".to_vec()); + } + tls.alpn_protocols.push(b"http/1.1".to_vec()); + let acceptor = TlsAcceptor::from(Arc::new(tls)); + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("https://{}", listener.local_addr().unwrap()); + let (versions, received_versions) = mpsc::unbounded_channel(); + let task = tokio::spawn(async move { + let mut connections = JoinSet::new(); + loop { + tokio::select! { + accepted = listener.accept() => { + let socket = accepted.unwrap().0; + let acceptor = acceptor.clone(); + let versions = versions.clone(); + connections.spawn(async move { + let mut stream = acceptor.accept(socket).await.unwrap(); + if stream.get_ref().1.alpn_protocol() == Some(b"h2") { + let mut connection = h2::server::handshake(stream).await.unwrap(); + while let Some(request) = connection.accept().await { + let (request, mut response) = request.unwrap(); + versions.send((request.uri().path().to_string(), request.version())).unwrap(); + let redirect = request.uri().path() == "/redirect"; + let response_head = http::Response::builder() + .status(if redirect { 302 } else { 200 }) + .header("location", "https://example.invalid/authorize") + .body(()) + .unwrap(); + response.send_response(response_head, false).unwrap() + .send_data(Bytes::from_static(b"{\"session_id\":\"session-http2\"}"), true) + .unwrap(); + } + } else { + let mut request = Vec::new(); + let mut byte = [0]; + while !request.ends_with(b"\r\n\r\n") { + if stream.read(&mut byte).await.unwrap_or(0) == 0 { + return; + } + request.push(byte[0]); + } + let path = std::str::from_utf8(&request).unwrap().split_whitespace().nth(1).unwrap().to_string(); + versions.send((path, Version::HTTP_11)).unwrap(); + let redirect = request.starts_with(b"GET /redirect "); + let body = r#"{"session_id":"session-http2"}"#; + let response = format!( + "HTTP/1.1 {}\r\nLocation: https://example.invalid/authorize\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}", + if redirect { "302 Found" } else { "200 OK" }, body.len(), body + ); + stream.write_all(response.as_bytes()).await.unwrap(); + let _ = stream.shutdown().await; + } + }); + } + Some(result) = connections.join_next(), if !connections.is_empty() => { + result.unwrap(); + } + } + } + }); + Self { + url, + certificate, + requests: received_versions, + task, + } + } + + async fn assert_version(&mut self, expected: Version) { + let (_, version) = tokio::time::timeout(Duration::from_secs(5), self.requests.recv()) + .await + .unwrap() + .unwrap(); + assert_eq!(version, expected); + } + + fn client(&self, enabled: bool, proxy: Option) -> DatabricksHttpClient { + let mut config = HttpClientConfig { + http2_enabled: enabled, + read_timeout: Duration::from_secs(5), + ..HttpClientConfig::default() + }; + config.tls.trusted_certificate_pem = Some(self.certificate.clone()); + config.proxy.url = proxy; + let retries = RetryConfig { + max_retries: 0, + overall_timeout: Duration::from_secs(5), + ..RetryConfig::default() + }; + let client = + DatabricksHttpClient::new(config, build_retry_configs(&retries, &Default::default())) + .unwrap(); + client.set_auth_provider(Arc::new(PersonalAccessToken::new("test-token"))); + client + } +} + +#[tokio::test] +async fn https_negotiates_http2_and_supports_http1_fallback_and_opt_out() { + for (server_http2, enabled, expected) in [ + (true, true, Version::HTTP_2), + (false, true, Version::HTTP_11), + (true, false, Version::HTTP_11), + ] { + let mut server = HttpsServer::start(server_http2).await; + let client = server.client(enabled, None); + for request_type in [ + RequestType::CreateSession, + RequestType::CloudFetchDownload, + RequestType::AuthDiscovery, + RequestType::AuthTokenRequest, + RequestType::TelemetryExport, + ] { + let request = client.inner().get(&server.url).build().unwrap(); + let response = if matches!( + request_type, + RequestType::CreateSession | RequestType::TelemetryExport + ) { + client.execute(request, request_type).await + } else { + client.execute_without_auth(request, request_type).await + } + .unwrap(); + assert_eq!(response.version(), expected); + response.bytes().await.unwrap(); + server.assert_version(expected).await; + } + let response = client.inner().get(&server.url).send().await.unwrap(); + assert_eq!(response.version(), expected); + response.bytes().await.unwrap(); + server.assert_version(expected).await; + assert_eq!( + client + .first_redirect_location(&format!("{}/redirect", server.url)) + .await + .unwrap(), + Some("https://example.invalid/authorize".into()) + ); + server.assert_version(expected).await; + } +} + +#[tokio::test] +async fn https_negotiates_inside_an_http1_connect_tunnel() { + for (server_http2, enabled, expected) in [ + (true, true, Version::HTTP_2), + (false, true, Version::HTTP_11), + (true, false, Version::HTTP_11), + ] { + let mut server = HttpsServer::start(server_http2).await; + let authority = server.url.strip_prefix("https://").unwrap().to_string(); + let target = authority.clone(); + let proxy = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let proxy_url = format!("http://{}", proxy.local_addr().unwrap()); + let (sent_head, received_head) = tokio::sync::oneshot::channel(); + let proxy_task = tokio::spawn(async move { + let mut downstream = proxy.accept().await.unwrap().0; + let mut head = Vec::new(); + let mut byte = [0]; + while !head.ends_with(b"\r\n\r\n") { + downstream.read_exact(&mut byte).await.unwrap(); + head.push(byte[0]); + } + let mut upstream = tokio::net::TcpStream::connect(target).await.unwrap(); + downstream + .write_all(b"HTTP/1.1 200 Connection Established\r\n\r\n") + .await + .unwrap(); + sent_head.send(String::from_utf8(head).unwrap()).unwrap(); + let _ = tokio::io::copy_bidirectional(&mut downstream, &mut upstream).await; + }); + let client = server.client(enabled, Some(proxy_url)); + let response = client.inner().get(&server.url).send().await.unwrap(); + assert_eq!(response.version(), expected); + response.bytes().await.unwrap(); + server.assert_version(expected).await; + let head = received_head.await.unwrap(); + assert!( + head.starts_with(&format!("CONNECT {authority} HTTP/1.1\r\n")), + "{head}" + ); + proxy_task.abort(); + } +} + +#[tokio::test] +async fn session_http2_default_and_opt_out_reach_the_https_connection() { + for enabled in [true, false] { + let mut server = HttpsServer::start(true).await; + let mut http = HttpConfig::default(); + assert!(http.http2_enabled); + http.http2_enabled = enabled; + http.overall_timeout = Duration::from_secs(5); + http.retry_max_retries = 0; + let mut tls = TlsConfig::default(); + tls.custom_ca_cert = Some(server.certificate.clone()); + let session = Session::builder() + .connection(ConnectionConfig::new(&server.url, "test-warehouse")) + .auth(AuthConfig::Pat { + token: "test-token".into(), + identity_federation_client_id: None, + }) + .http(http) + .tls(tls) + .open() + .await + .unwrap(); + let expected = if enabled { + Version::HTTP_2 + } else { + Version::HTTP_11 + }; + server.assert_version(expected).await; + session.close().await.unwrap(); + server.assert_version(expected).await; + } +} + +#[tokio::test] +async fn telemetry_respects_each_sessions_http_protocol_setting_on_the_same_host() { + let mut server = HttpsServer::start(true).await; + let mut sessions = Vec::new(); + for enabled in [true, false] { + let mut http = HttpConfig::default(); + http.http2_enabled = enabled; + http.retry_max_retries = 0; + http.overall_timeout = Duration::from_secs(5); + let mut tls = TlsConfig::default(); + tls.custom_ca_cert = Some(server.certificate.clone()); + let mut telemetry = TelemetryConfig::default(); + telemetry.enabled = Some(true); + telemetry.flush_interval = Duration::from_secs(3600); + sessions.push( + Session::builder() + .connection(ConnectionConfig::new(&server.url, "test-warehouse")) + .auth(AuthConfig::Pat { + token: "test-token".into(), + identity_federation_client_id: None, + }) + .http(http) + .tls(tls) + .telemetry(telemetry) + .open() + .await + .unwrap(), + ); + } + for session in sessions.into_iter().rev() { + session.close().await.unwrap(); + } + let mut telemetry_versions = Vec::new(); + while let Ok((path, version)) = server.requests.try_recv() { + if path.starts_with("/telemetry") { + telemetry_versions.push(version); + } + } + assert!( + telemetry_versions.contains(&Version::HTTP_11), + "{telemetry_versions:?}" + ); + assert!( + telemetry_versions.contains(&Version::HTTP_2), + "{telemetry_versions:?}" + ); +} + +#[test] +fn c_abi_http2_default_and_opt_out_reach_the_https_connection() { + use databricks_sql_kernel::c_abi::session::*; + use databricks_sql_kernel::c_abi::KernelStatusCode; + use std::ffi::CString; + use std::ptr; + + let runtime = tokio::runtime::Runtime::new().unwrap(); + for enabled in [None, Some(true), Some(false)] { + let mut server = runtime.block_on(HttpsServer::start(true)); + let url = CString::new(server.url.clone()).unwrap(); + let certificate = server.certificate.clone(); + { + // SAFETY: config and session are initialized by the C ABI; input buffers + // remain alive through the calls that copy them. + unsafe { + let mut config = ptr::null_mut(); + assert_eq!( + kernel_session_config_new(&mut config), + KernelStatusCode::Success + ); + assert_eq!( + kernel_session_config_set_http_path( + config, + url.as_ptr(), + c"/sql/1.0/warehouses/test".as_ptr() + ), + KernelStatusCode::Success + ); + assert_eq!( + kernel_session_config_set_auth_pat(config, c"test-token".as_ptr()), + KernelStatusCode::Success + ); + assert_eq!( + kernel_session_config_set_tls_trusted_certs( + config, + certificate.as_ptr(), + certificate.len() + ), + KernelStatusCode::Success + ); + if let Some(enabled) = enabled { + assert_eq!( + kernel_session_config_set_http2_enabled(config, enabled), + KernelStatusCode::Success + ); + } + let mut session = ptr::null_mut(); + assert_eq!( + kernel_session_open(config, &mut session), + KernelStatusCode::Success + ); + assert_eq!(kernel_session_close(session), KernelStatusCode::Success); + } + } + let expected = if enabled == Some(false) { + Version::HTTP_11 + } else { + Version::HTTP_2 + }; + runtime.block_on(async { + server.assert_version(expected).await; + server.assert_version(expected).await; + }); + } +} From ce03150e033b83a56b1c1e7d26b755dc7eba3c54 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Wed, 18 Nov 2026 19:59:59 +0000 Subject: [PATCH 02/13] feat(http): use HTTP/1.1 for proxy-configured clients Signed-off-by: Aakash Saravanan --- CONNECTION_PARAMETERS.md | 9 +- NEXT_CHANGELOG.md | 4 +- adbc/README.md | 3 +- include/databricks_kernel.h | 2 +- napi/NEXT_CHANGELOG.md | 3 +- napi/index.d.ts | 2 +- napi/src/database.rs | 2 +- pyo3/NEXT_CHANGELOG.md | 3 +- src/client/http.rs | 17 +++- src/config.rs | 1 + tests/http2.rs | 165 ++++++++++++++++++++++++++---------- 11 files changed, 156 insertions(+), 55 deletions(-) diff --git a/CONNECTION_PARAMETERS.md b/CONNECTION_PARAMETERS.md index 1adf8d68..ef76653d 100644 --- a/CONNECTION_PARAMETERS.md +++ b/CONNECTION_PARAMETERS.md @@ -127,12 +127,15 @@ until implemented) and `External` (a caller-supplied `TokenProvider`). The `http2_enabled` setting applies to all kernel-owned HTTPS requests: authentication and discovery, SQL requests, result downloads, feature flags, and telemetry. TLS -negotiates the protocol with each peer. An HTTP proxy can use HTTP/1.1 for -CONNECT while the HTTPS connection inside the tunnel negotiates HTTP/2. +negotiates the protocol with each peer when no proxy is configured. An explicit +HTTP/HTTPS proxy URL or a nonempty `HTTP_PROXY`, `HTTPS_PROXY`, `ALL_PROXY` +(or lowercase equivalent) forces HTTP/1.1 for the entire client. Proxy bypass +rules still select which destinations use the proxy; bypassed destinations also +use HTTP/1.1 on that client. | Field | Description | Default | |-------|-------------|---------| -| `http2_enabled` | Negotiate HTTP/2 for HTTPS with HTTP/1.1 fallback. Set `false` to force HTTP/1.1. | `true` | +| `http2_enabled` | Negotiate HTTP/2 for HTTPS with HTTP/1.1 fallback when no proxy is configured. `false` or a configured proxy forces HTTP/1.1. | `true` | | `request_timeout` | Per-request timeout (connect + body). | `120s` | | `overall_timeout` | Maximum total time across retries for one logical RPC. | `900s` | | `pool_max_idle_per_host` | Connection-pool size (max idle warm sockets per host). Raise for bursty concurrent workloads. | `100` | diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index 4cec2610..4cdeef29 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -16,7 +16,9 @@ changes go in their respective binding's NEXT_CHANGELOG. ### Changed -- HTTPS requests negotiate HTTP/2 with HTTP/1.1 fallback by default. Set +- HTTPS requests negotiate HTTP/2 with HTTP/1.1 fallback by default when no + proxy is configured. Explicit or environment proxy configuration forces + HTTP/1.1 for the entire client. Set `HttpConfig.http2_enabled` to `false`, or use `kernel_session_config_set_http2_enabled(config, false)`, to force HTTP/1.1. Rust ADBC exposes `adbc.databricks.http.http2_enabled`. diff --git a/adbc/README.md b/adbc/README.md index e27cac40..3a98e473 100644 --- a/adbc/README.md +++ b/adbc/README.md @@ -72,7 +72,8 @@ Canonical `adbc.databricks.*` names take precedence over compatibility aliases. HTTPS requests negotiate HTTP/2 by default, with HTTP/1.1 fallback when the peer does not support HTTP/2. Set `adbc.databricks.http.http2_enabled` to `false` to force HTTP/1.1 for all kernel-owned HTTPS requests, including authentication, -query requests, result downloads, and telemetry. +query requests, result downloads, and telemetry. Configured proxies force +HTTP/1.1 for the entire kernel client. ## Authentication diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h index 5f25fed0..b52ef22e 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -362,7 +362,7 @@ KernelStatusCode kernel_session_config_set_custom_header(KernelSessionConfig* co const char* name, const char* value); /* Negotiate HTTP/2 for all HTTPS requests, with HTTP/1.1 fallback. - * Enabled by default. Set enabled to false to use HTTP/1.1 only. */ + * Enabled by default. False or a configured proxy forces HTTP/1.1. */ KernelStatusCode kernel_session_config_set_http2_enabled( KernelSessionConfig* config, bool enabled); diff --git a/napi/NEXT_CHANGELOG.md b/napi/NEXT_CHANGELOG.md index ab4da560..fa7d598b 100644 --- a/napi/NEXT_CHANGELOG.md +++ b/napi/NEXT_CHANGELOG.md @@ -15,7 +15,8 @@ layout, or npm publishing. Pure-kernel changes go in the root ### Added - `ConnectionOptions.enableHttp2` selects HTTP/2 negotiation for HTTPS requests. - It defaults to enabled; set it to `false` to force HTTP/1.1. + It defaults to enabled; set it to `false` to force HTTP/1.1. Configured proxies + force HTTP/1.1 for the entire kernel client. ### Changed diff --git a/napi/index.d.ts b/napi/index.d.ts index 5b2385f9..e67d33c3 100644 --- a/napi/index.d.ts +++ b/napi/index.d.ts @@ -518,7 +518,7 @@ export interface ConnectionOptions { * Whether SEA API responses may use HTTP compression. Defaults to false. */ seaResponseCompressionEnabled?: boolean - /** Negotiate HTTP/2 over HTTPS by default. Set false to use HTTP/1.1 only. */ + /** Negotiate HTTP/2 over HTTPS by default. False or a configured proxy forces HTTP/1.1. */ enableHttp2?: boolean /** * Retry/backoff tuning — all optional. An unset field keeps the kernel's diff --git a/napi/src/database.rs b/napi/src/database.rs index b0a43770..9b2c30a3 100644 --- a/napi/src/database.rs +++ b/napi/src/database.rs @@ -388,7 +388,7 @@ pub struct ConnectionOptions { /// Whether SEA API responses may use HTTP compression. Defaults to false. pub sea_response_compression_enabled: Option, - /// Negotiate HTTP/2 over HTTPS by default. Set false to use HTTP/1.1 only. + /// Negotiate HTTP/2 over HTTPS by default. False or a configured proxy forces HTTP/1.1. pub enable_http2: Option, /// Retry/backoff tuning — all optional. An unset field keeps the kernel's diff --git a/pyo3/NEXT_CHANGELOG.md b/pyo3/NEXT_CHANGELOG.md index c0e06b89..0e330457 100644 --- a/pyo3/NEXT_CHANGELOG.md +++ b/pyo3/NEXT_CHANGELOG.md @@ -14,7 +14,8 @@ changes go in the root `NEXT_CHANGELOG.md`. ### Added - `Session(enable_http2=False)` forces HTTP/1.1 for HTTPS requests. By default, - connections negotiate HTTP/2 with HTTP/1.1 fallback. + connections negotiate HTTP/2 with HTTP/1.1 fallback. Configured proxies force + HTTP/1.1 for the entire kernel client. ### Changed diff --git a/src/client/http.rs b/src/client/http.rs index b404e144..366c3094 100644 --- a/src/client/http.rs +++ b/src/client/http.rs @@ -267,7 +267,7 @@ impl TlsConfig { /// Configuration for the HTTP client. #[derive(Debug, Clone)] pub struct HttpClientConfig { - /// Negotiate HTTP/2 over TLS. When false, use HTTP/1.1 only. + /// Negotiate HTTP/2 over TLS without a proxy. False or a configured proxy uses HTTP/1.1. pub http2_enabled: bool, /// Whether authenticated SEA requests may negotiate HTTP response compression. pub sea_response_compression_enabled: bool, @@ -528,7 +528,20 @@ impl DatabricksHttpClient { .user_agent(&config.user_agent) .redirect(redirect); - if !config.http2_enabled { + let proxy_configured = config.proxy.url.is_some() + || [ + "HTTP_PROXY", + "http_proxy", + "HTTPS_PROXY", + "https_proxy", + "ALL_PROXY", + "all_proxy", + ] + .iter() + .any(|key| std::env::var_os(key).is_some_and(|value| !value.is_empty())); + + // CONNECT tunneling requires HTTP/1.1 on the proxy connection. + if !config.http2_enabled || proxy_configured { builder = builder.http1_only(); } diff --git a/src/config.rs b/src/config.rs index 7cb57aa5..174d22d5 100644 --- a/src/config.rs +++ b/src/config.rs @@ -750,6 +750,7 @@ impl std::fmt::Debug for AuthConfig { pub struct HttpConfig { /// Negotiate HTTP/2 for HTTPS requests, with HTTP/1.1 fallback. /// Defaults to `true`. Set to `false` to use HTTP/1.1 only. + /// A configured proxy forces HTTP/1.1 for every request on the client. pub http2_enabled: bool, /// Whether authenticated SEA requests may negotiate HTTP response compression. diff --git a/tests/http2.rs b/tests/http2.rs index ace76f86..f5313be1 100644 --- a/tests/http2.rs +++ b/tests/http2.rs @@ -24,7 +24,7 @@ use http::Version; use rustls::pki_types::PrivatePkcs8KeyDer; use std::sync::Arc; use std::time::Duration; -use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt}; use tokio::net::TcpListener; use tokio::sync::mpsc; use tokio::task::{JoinHandle, JoinSet}; @@ -34,6 +34,7 @@ struct HttpsServer { url: String, certificate: Vec, requests: mpsc::UnboundedReceiver<(String, Version)>, + acceptor: TlsAcceptor, task: JoinHandle<()>, } @@ -66,6 +67,7 @@ impl HttpsServer { let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); let url = format!("https://{}", listener.local_addr().unwrap()); let (versions, received_versions) = mpsc::unbounded_channel(); + let proxy_acceptor = acceptor.clone(); let task = tokio::spawn(async move { let mut connections = JoinSet::new(); loop { @@ -123,6 +125,7 @@ impl HttpsServer { url, certificate, requests: received_versions, + acceptor: proxy_acceptor, task, } } @@ -165,27 +168,14 @@ async fn https_negotiates_http2_and_supports_http1_fallback_and_opt_out() { ] { let mut server = HttpsServer::start(server_http2).await; let client = server.client(enabled, None); - for request_type in [ - RequestType::CreateSession, - RequestType::CloudFetchDownload, - RequestType::AuthDiscovery, - RequestType::AuthTokenRequest, - RequestType::TelemetryExport, - ] { - let request = client.inner().get(&server.url).build().unwrap(); - let response = if matches!( - request_type, - RequestType::CreateSession | RequestType::TelemetryExport - ) { - client.execute(request, request_type).await - } else { - client.execute_without_auth(request, request_type).await - } + let request = client.inner().get(&server.url).build().unwrap(); + let response = client + .execute(request, RequestType::CreateSession) + .await .unwrap(); - assert_eq!(response.version(), expected); - response.bytes().await.unwrap(); - server.assert_version(expected).await; - } + assert_eq!(response.version(), expected); + response.bytes().await.unwrap(); + server.assert_version(expected).await; let response = client.inner().get(&server.url).send().await.unwrap(); assert_eq!(response.version(), expected); response.bytes().await.unwrap(); @@ -202,39 +192,66 @@ async fn https_negotiates_http2_and_supports_http1_fallback_and_opt_out() { } #[tokio::test] -async fn https_negotiates_inside_an_http1_connect_tunnel() { - for (server_http2, enabled, expected) in [ - (true, true, Version::HTTP_2), - (false, true, Version::HTTP_11), - (true, false, Version::HTTP_11), - ] { +async fn https_uses_http1_through_an_http_proxy() { + assert_connect_proxy(false).await; +} + +#[tokio::test] +async fn https_uses_http1_through_an_https_proxy() { + assert_connect_proxy(true).await; +} + +async fn tunnel( + mut downstream: S, + target: String, + sent_head: tokio::sync::oneshot::Sender, +) { + let mut head = Vec::new(); + let mut byte = [0]; + while !head.ends_with(b"\r\n\r\n") { + downstream.read_exact(&mut byte).await.unwrap(); + head.push(byte[0]); + } + let mut upstream = tokio::net::TcpStream::connect(target).await.unwrap(); + downstream + .write_all(b"HTTP/1.1 200 Connection Established\r\n\r\n") + .await + .unwrap(); + sent_head.send(String::from_utf8(head).unwrap()).unwrap(); + let _ = tokio::io::copy_bidirectional(&mut downstream, &mut upstream).await; +} + +async fn assert_connect_proxy(proxy_tls: bool) { + for (server_http2, enabled) in [(true, true), (false, true), (true, false)] { let mut server = HttpsServer::start(server_http2).await; let authority = server.url.strip_prefix("https://").unwrap().to_string(); let target = authority.clone(); let proxy = TcpListener::bind("127.0.0.1:0").await.unwrap(); - let proxy_url = format!("http://{}", proxy.local_addr().unwrap()); + let proxy_url = format!( + "{}://{}", + if proxy_tls { "https" } else { "http" }, + proxy.local_addr().unwrap() + ); let (sent_head, received_head) = tokio::sync::oneshot::channel(); + let acceptor = server.acceptor.clone(); let proxy_task = tokio::spawn(async move { - let mut downstream = proxy.accept().await.unwrap().0; - let mut head = Vec::new(); - let mut byte = [0]; - while !head.ends_with(b"\r\n\r\n") { - downstream.read_exact(&mut byte).await.unwrap(); - head.push(byte[0]); + let downstream = proxy.accept().await.unwrap().0; + if proxy_tls { + let downstream = acceptor.accept(downstream).await.unwrap(); + assert_ne!( + downstream.get_ref().1.alpn_protocol(), + Some(b"h2".as_slice()) + ); + tunnel(downstream, target, sent_head).await; + } else { + tunnel(downstream, target, sent_head).await; } - let mut upstream = tokio::net::TcpStream::connect(target).await.unwrap(); - downstream - .write_all(b"HTTP/1.1 200 Connection Established\r\n\r\n") - .await - .unwrap(); - sent_head.send(String::from_utf8(head).unwrap()).unwrap(); - let _ = tokio::io::copy_bidirectional(&mut downstream, &mut upstream).await; }); let client = server.client(enabled, Some(proxy_url)); let response = client.inner().get(&server.url).send().await.unwrap(); - assert_eq!(response.version(), expected); + assert_eq!(response.version(), Version::HTTP_11); response.bytes().await.unwrap(); - server.assert_version(expected).await; + server.assert_version(Version::HTTP_11).await; let head = received_head.await.unwrap(); assert!( head.starts_with(&format!("CONNECT {authority} HTTP/1.1\r\n")), @@ -244,6 +261,68 @@ async fn https_negotiates_inside_an_http1_connect_tunnel() { } } +#[test] +fn environment_proxy_configuration_uses_http1_including_bypassed_hosts() { + const CHILD: &str = "DATABRICKS_HTTP2_ENV_TEST_PROTOCOL"; + if let Ok(protocol) = std::env::var(CHILD) { + tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .unwrap() + .block_on(async { + let expected = if protocol == "h2" { + Version::HTTP_2 + } else { + Version::HTTP_11 + }; + let mut server = HttpsServer::start(true).await; + let client = server.client(true, None); + let response = client.inner().get(&server.url).send().await.unwrap(); + assert_eq!(response.version(), expected); + response.bytes().await.unwrap(); + server.assert_version(expected).await; + client + .first_redirect_location(&format!("{}/redirect", server.url)) + .await + .unwrap(); + server.assert_version(expected).await; + }); + return; + } + + let keys = [ + "HTTP_PROXY", + "http_proxy", + "HTTPS_PROXY", + "https_proxy", + "ALL_PROXY", + "all_proxy", + ]; + for selected in keys.into_iter().map(Some).chain([None]) { + let mut command = std::process::Command::new(std::env::current_exe().unwrap()); + command.args([ + "--exact", + "environment_proxy_configuration_uses_http1_including_bypassed_hosts", + "--nocapture", + ]); + for key in keys { + command.env(key, ""); + } + command.env("NO_PROXY", "127.0.0.1").env_remove("no_proxy"); + command.env(CHILD, if selected.is_some() { "http1" } else { "h2" }); + if let Some(key) = selected { + command.env(key, "http://127.0.0.1:9"); + } + let output = command.output().unwrap(); + assert!( + output.status.success(), + "proxy {selected:?}: {}{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); + } +} + #[tokio::test] async fn session_http2_default_and_opt_out_reach_the_https_connection() { for enabled in [true, false] { From d149ff849db1eec94bf5d7f8f420f340c3337d4e Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Wed, 18 Nov 2026 20:08:32 +0000 Subject: [PATCH 03/13] fix(http): resolve protocol before sharing telemetry clients Signed-off-by: Aakash Saravanan --- src/client/http.rs | 30 +++++++------- tests/http2.rs | 98 ++++++++++++++++++++++++++-------------------- 2 files changed, 71 insertions(+), 57 deletions(-) diff --git a/src/client/http.rs b/src/client/http.rs index 366c3094..c5d3ac43 100644 --- a/src/client/http.rs +++ b/src/client/http.rs @@ -481,6 +481,21 @@ impl DatabricksHttpClient { })?; } + // Resolve the protocol before telemetry clients can be shared across sessions. + let proxy_configured = config.proxy.url.is_some() + || [ + "HTTP_PROXY", + "http_proxy", + "HTTPS_PROXY", + "https_proxy", + "ALL_PROXY", + "all_proxy", + ] + .iter() + .any(|key| std::env::var_os(key).is_some_and(|value| !value.is_empty())); + + config.http2_enabled &= !proxy_configured; + // Follow redirects for normal traffic (reqwest's default policy). let client = Self::build_reqwest_client(&config, reqwest::redirect::Policy::default())?; @@ -528,20 +543,7 @@ impl DatabricksHttpClient { .user_agent(&config.user_agent) .redirect(redirect); - let proxy_configured = config.proxy.url.is_some() - || [ - "HTTP_PROXY", - "http_proxy", - "HTTPS_PROXY", - "https_proxy", - "ALL_PROXY", - "all_proxy", - ] - .iter() - .any(|key| std::env::var_os(key).is_some_and(|value| !value.is_empty())); - - // CONNECT tunneling requires HTTP/1.1 on the proxy connection. - if !config.http2_enabled || proxy_configured { + if !config.http2_enabled { builder = builder.http1_only(); } diff --git a/tests/http2.rs b/tests/http2.rs index f5313be1..d2670a08 100644 --- a/tests/http2.rs +++ b/tests/http2.rs @@ -18,7 +18,7 @@ use databricks_sql_kernel::client::{ build_retry_configs, DatabricksHttpClient, HttpClientConfig, RequestType, RetryConfig, }; use databricks_sql_kernel::{ - AuthConfig, ConnectionConfig, HttpConfig, Session, TelemetryConfig, TlsConfig, + AuthConfig, ConnectionConfig, HttpConfig, ProxyConfig, Session, TelemetryConfig, TlsConfig, }; use http::Version; use rustls::pki_types::PrivatePkcs8KeyDer; @@ -358,50 +358,62 @@ async fn session_http2_default_and_opt_out_reach_the_https_connection() { #[tokio::test] async fn telemetry_respects_each_sessions_http_protocol_setting_on_the_same_host() { - let mut server = HttpsServer::start(true).await; - let mut sessions = Vec::new(); - for enabled in [true, false] { - let mut http = HttpConfig::default(); - http.http2_enabled = enabled; - http.retry_max_retries = 0; - http.overall_timeout = Duration::from_secs(5); - let mut tls = TlsConfig::default(); - tls.custom_ca_cert = Some(server.certificate.clone()); - let mut telemetry = TelemetryConfig::default(); - telemetry.enabled = Some(true); - telemetry.flush_interval = Duration::from_secs(3600); - sessions.push( - Session::builder() - .connection(ConnectionConfig::new(&server.url, "test-warehouse")) - .auth(AuthConfig::Pat { - token: "test-token".into(), - identity_federation_client_id: None, - }) - .http(http) - .tls(tls) - .telemetry(telemetry) - .open() - .await - .unwrap(), - ); - } - for session in sessions.into_iter().rev() { - session.close().await.unwrap(); - } - let mut telemetry_versions = Vec::new(); - while let Ok((path, version)) = server.requests.try_recv() { - if path.starts_with("/telemetry") { - telemetry_versions.push(version); + for configurations in [ + [(true, false), (false, false)], + [(true, false), (true, true)], + [(true, true), (true, false)], + ] { + let mut server = HttpsServer::start(true).await; + let mut sessions = Vec::new(); + for (enabled, proxied) in configurations { + let mut http = HttpConfig::default(); + http.http2_enabled = enabled; + http.retry_max_retries = 0; + http.overall_timeout = Duration::from_secs(5); + let mut tls = TlsConfig::default(); + tls.custom_ca_cert = Some(server.certificate.clone()); + let mut proxy = ProxyConfig::default(); + if proxied { + proxy.url = Some("http://127.0.0.1:9".into()); + proxy.bypass_hosts = Some("127.0.0.1".into()); + } + let mut telemetry = TelemetryConfig::default(); + telemetry.enabled = Some(true); + telemetry.flush_interval = Duration::from_secs(3600); + sessions.push( + Session::builder() + .connection(ConnectionConfig::new(&server.url, "test-warehouse")) + .auth(AuthConfig::Pat { + token: "test-token".into(), + identity_federation_client_id: None, + }) + .http(http) + .proxy(proxy) + .tls(tls) + .telemetry(telemetry) + .open() + .await + .unwrap(), + ); + } + for session in sessions.into_iter().rev() { + session.close().await.unwrap(); } + let mut telemetry_versions = Vec::new(); + while let Ok((path, version)) = server.requests.try_recv() { + if path.starts_with("/telemetry") { + telemetry_versions.push(version); + } + } + assert!( + telemetry_versions.contains(&Version::HTTP_11), + "{telemetry_versions:?}" + ); + assert!( + telemetry_versions.contains(&Version::HTTP_2), + "{telemetry_versions:?}" + ); } - assert!( - telemetry_versions.contains(&Version::HTTP_11), - "{telemetry_versions:?}" - ); - assert!( - telemetry_versions.contains(&Version::HTTP_2), - "{telemetry_versions:?}" - ); } #[test] From 33b1b84d5e147145d7c1dd3e8f627c517e0fc6d5 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Wed, 18 Nov 2026 21:41:38 +0000 Subject: [PATCH 04/13] test(http): verify protocol options across TLS backends Signed-off-by: Aakash Saravanan --- .github/workflows/pr-checks.yml | 3 ++ NEXT_CHANGELOG.md | 4 ++ pyo3/src/session.rs | 79 ++++++++++++++++++++++++--------- tests/http2.rs | 46 +++++++++++++++++++ 4 files changed, 111 insertions(+), 21 deletions(-) diff --git a/.github/workflows/pr-checks.yml b/.github/workflows/pr-checks.yml index f07393fe..c77deb73 100644 --- a/.github/workflows/pr-checks.yml +++ b/.github/workflows/pr-checks.yml @@ -238,3 +238,6 @@ jobs: - name: Test client behavior (tls-rustls) run: "cargo test -p databricks-sql-kernel --no-default-features --features tls-rustls --lib client::" + + - name: Test HTTP protocol negotiation (tls-rustls) + run: cargo test -p databricks-sql-kernel --no-default-features --features tls-rustls --test http2 diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index 4cdeef29..51c8c1b2 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -16,6 +16,10 @@ changes go in their respective binding's NEXT_CHANGELOG. ### Changed +- **Breaking (Rust API):** `client::HttpClientConfig` gains `http2_enabled`. + Struct literals must set the field or use `..Default::default()` to enable + HTTP/2 negotiation by default. + - HTTPS requests negotiate HTTP/2 with HTTP/1.1 fallback by default when no proxy is configured. Explicit or environment proxy configuration forces HTTP/1.1 for the entire client. Set diff --git a/pyo3/src/session.rs b/pyo3/src/session.rs index 5f8bed4f..a45e685b 100644 --- a/pyo3/src/session.rs +++ b/pyo3/src/session.rs @@ -161,6 +161,7 @@ fn build_http_config( retry_max_attempts: Option, retry_overall_timeout_secs: Option, http_headers: Option>, + enable_http2: Option, ) -> PyResult> { // Zero means "keep the kernel default", matching the C ABI setter. Use a // float because databricks-sql-python's existing `_socket_timeout` accepts @@ -199,12 +200,16 @@ fn build_http_config( && retry_max_attempts.is_none() && retry_overall_timeout_secs.is_none() && !has_http_headers + && enable_http2.is_none() { return Ok(None); } let mut http = databricks_sql_kernel::HttpConfig::default(); http.sea_response_compression_enabled = sea_response_compression_enabled; + if let Some(enabled) = enable_http2 { + http.http2_enabled = enabled; + } if let Some(timeout) = request_timeout { http.request_timeout = timeout; } @@ -545,8 +550,8 @@ impl Session { None }; - // Build an HttpConfig only when the caller tuned the request timeout, - // retry/backoff, or supplied custom headers; otherwise leave the + // Build an HttpConfig only when the caller tuned transport options, + // compression, retry/backoff, or custom headers; otherwise leave the // builder on its defaults (120s request timeout, // 1s/60s/5-retries, no extra headers). // @@ -562,7 +567,7 @@ impl Session { // connector forwards its `http_headers`, which also carries the // composed `User-Agent`). The kernel applies them before its own // `Authorization` / `x-databricks-org-id`, which always win. - let mut http_config = build_http_config( + let http_config = build_http_config( sea_response_compression_enabled, request_timeout_secs, max_connections, @@ -571,12 +576,8 @@ impl Session { retry_max_attempts, retry_overall_timeout_secs, http_headers, + enable_http2, )?; - if let Some(enabled) = enable_http2 { - http_config - .get_or_insert_with(databricks_sql_kernel::HttpConfig::default) - .http2_enabled = enabled; - } let driver_system_configuration = build_driver_system_configuration( driver_name, @@ -858,21 +859,33 @@ mod send_sync_tests { .is_ok()); } + #[test] + fn http2_kwarg_maps_to_http_config() { + for enabled in [None, Some(true), Some(false)] { + let http = build_http_config(false, None, None, None, None, None, None, None, enabled) + .unwrap(); + match enabled { + None => assert!(http.is_none()), + Some(enabled) => assert_eq!(http.unwrap().http2_enabled, enabled), + } + } + } + #[test] fn request_timeout_kwarg_maps_to_http_config() { let default = databricks_sql_kernel::HttpConfig::default(); assert!( - build_http_config(false, None, None, None, None, None, None, None) + build_http_config(false, None, None, None, None, None, None, None, None) .unwrap() .is_none() ); assert!( - build_http_config(false, Some(0.0), None, None, None, None, None, None) + build_http_config(false, Some(0.0), None, None, None, None, None, None, None) .unwrap() .is_none() ); - let http = build_http_config(false, Some(0.5), None, None, None, None, None, None) + let http = build_http_config(false, Some(0.5), None, None, None, None, None, None, None) .unwrap() .expect("positive request timeout should build an HTTP config"); assert_eq!(http.request_timeout, std::time::Duration::from_millis(500)); @@ -888,40 +901,64 @@ mod send_sync_tests { None, None, None, - None + None, + None, ) .is_err()); - let http = build_http_config(false, Some(one_ns), None, None, None, None, None, None) - .unwrap() - .expect("one-nanosecond request timeout should be accepted"); + let http = build_http_config( + false, + Some(one_ns), + None, + None, + None, + None, + None, + None, + None, + ) + .unwrap() + .expect("one-nanosecond request timeout should be accepted"); assert_eq!(http.request_timeout, std::time::Duration::from_nanos(1)); - assert!(build_http_config(false, Some(-1.0), None, None, None, None, None, None).is_err()); assert!( - build_http_config(false, Some(f64::NAN), None, None, None, None, None, None).is_err() + build_http_config(false, Some(-1.0), None, None, None, None, None, None, None).is_err() ); + assert!(build_http_config( + false, + Some(f64::NAN), + None, + None, + None, + None, + None, + None, + None + ) + .is_err()); } #[test] fn max_connections_kwarg_maps_to_http_config() { let default = databricks_sql_kernel::HttpConfig::default(); - let http = build_http_config(false, None, Some(17), None, None, None, None, None) + let http = build_http_config(false, None, Some(17), None, None, None, None, None, None) .unwrap() .expect("max connections should build an HTTP config"); assert_eq!(http.pool_max_idle_per_host, 17); assert_eq!(http.request_timeout, default.request_timeout); - assert!(build_http_config(false, None, Some(0), None, None, None, None, None).is_err()); + assert!( + build_http_config(false, None, Some(0), None, None, None, None, None, None).is_err() + ); } #[test] fn sea_response_compression_kwarg_maps_to_http_config() { assert!( - build_http_config(false, None, None, None, None, None, None, None) + build_http_config(false, None, None, None, None, None, None, None, None) .unwrap() .is_none() ); - let http = build_http_config(true, None, None, None, None, None, None, None) + let http = build_http_config(true, None, None, None, None, None, None, None, None) .unwrap() .expect("enabling SEA response compression should build an HTTP config"); assert!(http.sea_response_compression_enabled); diff --git a/tests/http2.rs b/tests/http2.rs index d2670a08..746cbe2e 100644 --- a/tests/http2.rs +++ b/tests/http2.rs @@ -159,8 +159,42 @@ impl HttpsServer { } } +fn run_without_proxy_environment(test_name: &str) -> bool { + const CHILD: &str = "DATABRICKS_HTTP2_DIRECT_TEST"; + if std::env::var(CHILD).as_deref() == Ok(test_name) { + return false; + } + let mut command = std::process::Command::new(std::env::current_exe().unwrap()); + command + .args(["--exact", test_name, "--nocapture"]) + .env(CHILD, test_name); + for key in [ + "HTTP_PROXY", + "http_proxy", + "HTTPS_PROXY", + "https_proxy", + "ALL_PROXY", + "all_proxy", + ] { + command.env_remove(key); + } + let output = command.output().unwrap(); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!( + output.status.success() && stdout.contains("1 passed; 0 failed"), + "{test_name}: {stdout}{}", + String::from_utf8_lossy(&output.stderr) + ); + true +} + #[tokio::test] async fn https_negotiates_http2_and_supports_http1_fallback_and_opt_out() { + if run_without_proxy_environment( + "https_negotiates_http2_and_supports_http1_fallback_and_opt_out", + ) { + return; + } for (server_http2, enabled, expected) in [ (true, true, Version::HTTP_2), (false, true, Version::HTTP_11), @@ -325,6 +359,10 @@ fn environment_proxy_configuration_uses_http1_including_bypassed_hosts() { #[tokio::test] async fn session_http2_default_and_opt_out_reach_the_https_connection() { + if run_without_proxy_environment("session_http2_default_and_opt_out_reach_the_https_connection") + { + return; + } for enabled in [true, false] { let mut server = HttpsServer::start(true).await; let mut http = HttpConfig::default(); @@ -358,6 +396,11 @@ async fn session_http2_default_and_opt_out_reach_the_https_connection() { #[tokio::test] async fn telemetry_respects_each_sessions_http_protocol_setting_on_the_same_host() { + if run_without_proxy_environment( + "telemetry_respects_each_sessions_http_protocol_setting_on_the_same_host", + ) { + return; + } for configurations in [ [(true, false), (false, false)], [(true, false), (true, true)], @@ -418,6 +461,9 @@ async fn telemetry_respects_each_sessions_http_protocol_setting_on_the_same_host #[test] fn c_abi_http2_default_and_opt_out_reach_the_https_connection() { + if run_without_proxy_environment("c_abi_http2_default_and_opt_out_reach_the_https_connection") { + return; + } use databricks_sql_kernel::c_abi::session::*; use databricks_sql_kernel::c_abi::KernelStatusCode; use std::ffi::CString; From df16c74d578041eae86a734a87e6c36addc2c1fa Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Wed, 18 Nov 2026 22:16:31 +0000 Subject: [PATCH 05/13] test(http): bound CONNECT proxy request assertions Signed-off-by: Aakash Saravanan --- tests/http2.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/tests/http2.rs b/tests/http2.rs index 746cbe2e..86caa75c 100644 --- a/tests/http2.rs +++ b/tests/http2.rs @@ -286,7 +286,10 @@ async fn assert_connect_proxy(proxy_tls: bool) { assert_eq!(response.version(), Version::HTTP_11); response.bytes().await.unwrap(); server.assert_version(Version::HTTP_11).await; - let head = received_head.await.unwrap(); + let head = tokio::time::timeout(Duration::from_secs(5), received_head) + .await + .expect("proxy did not receive CONNECT") + .unwrap(); assert!( head.starts_with(&format!("CONNECT {authority} HTTP/1.1\r\n")), "{head}" From 7d866a33c62d62d5b9877a5a407872f906de79f1 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Wed, 18 Nov 2026 23:58:07 +0000 Subject: [PATCH 06/13] refactor(http): keep protocol configuration internal Signed-off-by: Aakash Saravanan --- .github/workflows/pr-checks.yml | 3 - CONNECTION_PARAMETERS.md | 13 +- NEXT_CHANGELOG.md | 4 - adbc/README.md | 8 +- src/client/http.rs | 43 ++- tests/http2.rs => src/client/http2_tests.rs | 282 +++++++++----------- src/session.rs | 8 +- src/telemetry/runtime.rs | 2 +- tests/http_client_config.rs | 32 +++ 9 files changed, 208 insertions(+), 187 deletions(-) rename tests/http2.rs => src/client/http2_tests.rs (69%) create mode 100644 tests/http_client_config.rs diff --git a/.github/workflows/pr-checks.yml b/.github/workflows/pr-checks.yml index c77deb73..f07393fe 100644 --- a/.github/workflows/pr-checks.yml +++ b/.github/workflows/pr-checks.yml @@ -238,6 +238,3 @@ jobs: - name: Test client behavior (tls-rustls) run: "cargo test -p databricks-sql-kernel --no-default-features --features tls-rustls --lib client::" - - - name: Test HTTP protocol negotiation (tls-rustls) - run: cargo test -p databricks-sql-kernel --no-default-features --features tls-rustls --test http2 diff --git a/CONNECTION_PARAMETERS.md b/CONNECTION_PARAMETERS.md index ef76653d..4bea2000 100644 --- a/CONNECTION_PARAMETERS.md +++ b/CONNECTION_PARAMETERS.md @@ -125,17 +125,14 @@ until implemented) and `External` (a caller-supplied `TokenProvider`). ## `HttpConfig` — HTTP client (optional) -The `http2_enabled` setting applies to all kernel-owned HTTPS requests: authentication and -discovery, SQL requests, result downloads, feature flags, and telemetry. TLS -negotiates the protocol with each peer when no proxy is configured. An explicit -HTTP/HTTPS proxy URL or a nonempty `HTTP_PROXY`, `HTTPS_PROXY`, `ALL_PROXY` -(or lowercase equivalent) forces HTTP/1.1 for the entire client. Proxy bypass -rules still select which destinations use the proxy; bypassed destinations also -use HTTP/1.1 on that client. +`http2_enabled` covers all kernel HTTPS traffic, including authentication, +SQL, result downloads and telemetry. An explicit proxy URL or nonempty +`HTTP_PROXY`, `HTTPS_PROXY`, `ALL_PROXY` (including lowercase variants) forces +HTTP/1.1, including destinations that bypass the proxy. | Field | Description | Default | |-------|-------------|---------| -| `http2_enabled` | Negotiate HTTP/2 for HTTPS with HTTP/1.1 fallback when no proxy is configured. `false` or a configured proxy forces HTTP/1.1. | `true` | +| `http2_enabled` | HTTP/2 with HTTP/1.1 fallback; `false` forces HTTP/1.1. | `true` | | `request_timeout` | Per-request timeout (connect + body). | `120s` | | `overall_timeout` | Maximum total time across retries for one logical RPC. | `900s` | | `pool_max_idle_per_host` | Connection-pool size (max idle warm sockets per host). Raise for bursty concurrent workloads. | `100` | diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index 51c8c1b2..4cdeef29 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -16,10 +16,6 @@ changes go in their respective binding's NEXT_CHANGELOG. ### Changed -- **Breaking (Rust API):** `client::HttpClientConfig` gains `http2_enabled`. - Struct literals must set the field or use `..Default::default()` to enable - HTTP/2 negotiation by default. - - HTTPS requests negotiate HTTP/2 with HTTP/1.1 fallback by default when no proxy is configured. Explicit or environment proxy configuration forces HTTP/1.1 for the entire client. Set diff --git a/adbc/README.md b/adbc/README.md index 3a98e473..aac2a4e2 100644 --- a/adbc/README.md +++ b/adbc/README.md @@ -69,11 +69,9 @@ Canonical `adbc.databricks.*` names take precedence over compatibility aliases. ## HTTP transport -HTTPS requests negotiate HTTP/2 by default, with HTTP/1.1 fallback when the -peer does not support HTTP/2. Set `adbc.databricks.http.http2_enabled` to `false` -to force HTTP/1.1 for all kernel-owned HTTPS requests, including authentication, -query requests, result downloads, and telemetry. Configured proxies force -HTTP/1.1 for the entire kernel client. +HTTPS requests negotiate HTTP/2 with HTTP/1.1 fallback by default. Set +`adbc.databricks.http.http2_enabled` to `false` to force HTTP/1.1 for all kernel +HTTPS traffic. Configured proxies force HTTP/1.1, including bypassed destinations. ## Authentication diff --git a/src/client/http.rs b/src/client/http.rs index c5d3ac43..0d00bc46 100644 --- a/src/client/http.rs +++ b/src/client/http.rs @@ -267,8 +267,6 @@ impl TlsConfig { /// Configuration for the HTTP client. #[derive(Debug, Clone)] pub struct HttpClientConfig { - /// Negotiate HTTP/2 over TLS without a proxy. False or a configured proxy uses HTTP/1.1. - pub http2_enabled: bool, /// Whether authenticated SEA requests may negotiate HTTP response compression. pub sea_response_compression_enabled: bool, /// Connection timeout duration. @@ -300,7 +298,6 @@ pub struct HttpClientConfig { impl Default for HttpClientConfig { fn default() -> Self { Self { - http2_enabled: true, sea_response_compression_enabled: false, connect_timeout: Duration::from_secs(30), read_timeout: Duration::from_secs(60), @@ -387,6 +384,7 @@ fn build_mtls_identity(cert_pem: &[u8], key_pem: &[u8]) -> Result>, retry_configs: HashMap, } @@ -398,8 +396,16 @@ impl DatabricksHttpClient { /// calling `execute()`. Use `execute_without_auth()` for requests that /// don't need authentication (e.g., OAuth token endpoint calls). pub fn new( + config: HttpClientConfig, + retry_configs: HashMap, + ) -> Result { + Self::new_with_http2(config, retry_configs, true) + } + + pub(crate) fn new_with_http2( mut config: HttpClientConfig, retry_configs: HashMap, + http2_enabled: bool, ) -> Result { // Fold any caller-supplied `User-Agent` custom header into the // effective UA, and remove it from `custom_headers` so it isn't @@ -481,7 +487,7 @@ impl DatabricksHttpClient { })?; } - // Resolve the protocol before telemetry clients can be shared across sessions. + // Keep proxy TLS compatible with reqwest's HTTP/1.1 CONNECT handshake. let proxy_configured = config.proxy.url.is_some() || [ "HTTP_PROXY", @@ -494,10 +500,14 @@ impl DatabricksHttpClient { .iter() .any(|key| std::env::var_os(key).is_some_and(|value| !value.is_empty())); - config.http2_enabled &= !proxy_configured; + let http2_enabled = http2_enabled && !proxy_configured; // Follow redirects for normal traffic (reqwest's default policy). - let client = Self::build_reqwest_client(&config, reqwest::redirect::Policy::default())?; + let client = Self::build_reqwest_client( + &config, + http2_enabled, + reqwest::redirect::Policy::default(), + )?; // Surface which TLS backend was compiled in so oncall debugging // a handshake / unknown-CA report can tell at a glance whether @@ -512,13 +522,13 @@ impl DatabricksHttpClient { } else { "native-tls" }, - http2_enabled = config.http2_enabled, - "DatabricksHttpClient initialised" + http2_enabled, "DatabricksHttpClient initialised" ); Ok(Self { client, config, + http2_enabled, auth_provider: OnceLock::new(), retry_configs, }) @@ -532,6 +542,7 @@ impl DatabricksHttpClient { /// and user-agent configuration. fn build_reqwest_client( config: &HttpClientConfig, + http2_enabled: bool, redirect: reqwest::redirect::Policy, ) -> Result { let mut builder = Client::builder() @@ -543,7 +554,7 @@ impl DatabricksHttpClient { .user_agent(&config.user_agent) .redirect(redirect); - if !config.http2_enabled { + if !http2_enabled { builder = builder.http1_only(); } @@ -754,6 +765,10 @@ impl DatabricksHttpClient { &self.config } + pub(crate) fn http2_enabled(&self) -> bool { + self.http2_enabled + } + /// Returns the underlying reqwest client for building requests. pub fn inner(&self) -> &Client { &self.client @@ -828,7 +843,11 @@ impl DatabricksHttpClient { /// `azure_tenant_id` (which skips discovery entirely). A single hop is /// sufficient for discovery, so no retry is attempted here. pub async fn first_redirect_location(&self, url: &str) -> Result> { - let client = Self::build_reqwest_client(&self.config, reqwest::redirect::Policy::none())?; + let client = Self::build_reqwest_client( + &self.config, + self.http2_enabled, + reqwest::redirect::Policy::none(), + )?; let response = client.get(url).send().await.map_err(|e| { Error::network_error().message(format!("Redirect-probe request to {url} failed: {e}")) })?; @@ -1108,6 +1127,10 @@ impl DatabricksHttpClient { } } +#[cfg(test)] +#[path = "http2_tests.rs"] +mod http2_tests; + #[cfg(test)] #[path = "http_tls_tests.rs"] mod tls_tests; diff --git a/tests/http2.rs b/src/client/http2_tests.rs similarity index 69% rename from tests/http2.rs rename to src/client/http2_tests.rs index 86caa75c..3e5fbf7b 100644 --- a/tests/http2.rs +++ b/src/client/http2_tests.rs @@ -12,14 +12,15 @@ // See the License for the specific language governing permissions and // limitations under the License. -use bytes::Bytes; -use databricks_sql_kernel::auth::PersonalAccessToken; -use databricks_sql_kernel::client::{ +use crate::auth::PersonalAccessToken; +use crate::client::{ build_retry_configs, DatabricksHttpClient, HttpClientConfig, RequestType, RetryConfig, }; -use databricks_sql_kernel::{ - AuthConfig, ConnectionConfig, HttpConfig, ProxyConfig, Session, TelemetryConfig, TlsConfig, +use crate::{ + AuthConfig, ConnectionConfig, HttpConfig, ProxyConfig, Session, SessionBuilder, + TelemetryConfig, TlsConfig, }; +use bytes::Bytes; use http::Version; use rustls::pki_types::PrivatePkcs8KeyDer; use std::sync::Arc; @@ -30,6 +31,16 @@ use tokio::sync::mpsc; use tokio::task::{JoinHandle, JoinSet}; use tokio_rustls::TlsAcceptor; +const PROXY_VARIABLES: [&str; 6] = [ + "HTTP_PROXY", + "http_proxy", + "HTTPS_PROXY", + "https_proxy", + "ALL_PROXY", + "all_proxy", +]; +const CHILD_TEST: &str = "DATABRICKS_HTTP2_TEST"; + struct HttpsServer { url: String, certificate: Vec, @@ -140,7 +151,6 @@ impl HttpsServer { fn client(&self, enabled: bool, proxy: Option) -> DatabricksHttpClient { let mut config = HttpClientConfig { - http2_enabled: enabled, read_timeout: Duration::from_secs(5), ..HttpClientConfig::default() }; @@ -151,32 +161,56 @@ impl HttpsServer { overall_timeout: Duration::from_secs(5), ..RetryConfig::default() }; - let client = - DatabricksHttpClient::new(config, build_retry_configs(&retries, &Default::default())) - .unwrap(); + let client = DatabricksHttpClient::new_with_http2( + config, + build_retry_configs(&retries, &Default::default()), + enabled, + ) + .unwrap(); client.set_auth_provider(Arc::new(PersonalAccessToken::new("test-token"))); client } + + fn session_builder(&self, enabled: Option) -> SessionBuilder { + let mut http = HttpConfig { + overall_timeout: Duration::from_secs(5), + retry_max_retries: 0, + ..HttpConfig::default() + }; + if let Some(enabled) = enabled { + http.http2_enabled = enabled; + } + let tls = TlsConfig { + custom_ca_cert: Some(self.certificate.clone()), + ..TlsConfig::default() + }; + Session::builder() + .connection(ConnectionConfig::new(&self.url, "test-warehouse")) + .auth(AuthConfig::Pat { + token: "test-token".into(), + identity_federation_client_id: None, + }) + .http(http) + .tls(tls) + } } -fn run_without_proxy_environment(test_name: &str) -> bool { - const CHILD: &str = "DATABRICKS_HTTP2_DIRECT_TEST"; - if std::env::var(CHILD).as_deref() == Ok(test_name) { +fn run_with_proxy_environment(test_name: &str, proxy_variable: Option<&str>) -> bool { + if std::env::var(CHILD_TEST).as_deref() == Ok(test_name) { return false; } + let qualified_name = format!("client::http::http2_tests::{test_name}"); let mut command = std::process::Command::new(std::env::current_exe().unwrap()); command - .args(["--exact", test_name, "--nocapture"]) - .env(CHILD, test_name); - for key in [ - "HTTP_PROXY", - "http_proxy", - "HTTPS_PROXY", - "https_proxy", - "ALL_PROXY", - "all_proxy", - ] { - command.env_remove(key); + .args(["--exact", &qualified_name, "--nocapture"]) + .env(CHILD_TEST, test_name) + .env("NO_PROXY", "127.0.0.1") + .env_remove("no_proxy"); + for key in PROXY_VARIABLES { + command.env(key, ""); + } + if let Some(key) = proxy_variable { + command.env(key, "http://127.0.0.1:9"); } let output = command.output().unwrap(); let stdout = String::from_utf8_lossy(&output.stdout); @@ -189,9 +223,10 @@ fn run_without_proxy_environment(test_name: &str) -> bool { } #[tokio::test] -async fn https_negotiates_http2_and_supports_http1_fallback_and_opt_out() { - if run_without_proxy_environment( - "https_negotiates_http2_and_supports_http1_fallback_and_opt_out", +async fn https_negotiates_http2_with_http1_fallback_and_opt_out() { + if run_with_proxy_environment( + "https_negotiates_http2_with_http1_fallback_and_opt_out", + None, ) { return; } @@ -210,10 +245,6 @@ async fn https_negotiates_http2_and_supports_http1_fallback_and_opt_out() { assert_eq!(response.version(), expected); response.bytes().await.unwrap(); server.assert_version(expected).await; - let response = client.inner().get(&server.url).send().await.unwrap(); - assert_eq!(response.version(), expected); - response.bytes().await.unwrap(); - server.assert_version(expected).await; assert_eq!( client .first_redirect_location(&format!("{}/redirect", server.url)) @@ -256,61 +287,62 @@ async fn tunnel( } async fn assert_connect_proxy(proxy_tls: bool) { - for (server_http2, enabled) in [(true, true), (false, true), (true, false)] { - let mut server = HttpsServer::start(server_http2).await; - let authority = server.url.strip_prefix("https://").unwrap().to_string(); - let target = authority.clone(); - let proxy = TcpListener::bind("127.0.0.1:0").await.unwrap(); - let proxy_url = format!( - "{}://{}", - if proxy_tls { "https" } else { "http" }, - proxy.local_addr().unwrap() - ); - let (sent_head, received_head) = tokio::sync::oneshot::channel(); - let acceptor = server.acceptor.clone(); - let proxy_task = tokio::spawn(async move { - let downstream = proxy.accept().await.unwrap().0; - if proxy_tls { - let downstream = acceptor.accept(downstream).await.unwrap(); - assert_ne!( - downstream.get_ref().1.alpn_protocol(), - Some(b"h2".as_slice()) - ); - tunnel(downstream, target, sent_head).await; - } else { - tunnel(downstream, target, sent_head).await; - } - }); - let client = server.client(enabled, Some(proxy_url)); - let response = client.inner().get(&server.url).send().await.unwrap(); - assert_eq!(response.version(), Version::HTTP_11); - response.bytes().await.unwrap(); - server.assert_version(Version::HTTP_11).await; - let head = tokio::time::timeout(Duration::from_secs(5), received_head) - .await - .expect("proxy did not receive CONNECT") - .unwrap(); - assert!( - head.starts_with(&format!("CONNECT {authority} HTTP/1.1\r\n")), - "{head}" - ); - proxy_task.abort(); - } + let mut server = HttpsServer::start(true).await; + let authority = server.url.strip_prefix("https://").unwrap().to_string(); + let target = authority.clone(); + let proxy = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let proxy_url = format!( + "{}://{}", + if proxy_tls { "https" } else { "http" }, + proxy.local_addr().unwrap() + ); + let (sent_head, received_head) = tokio::sync::oneshot::channel(); + let acceptor = server.acceptor.clone(); + let proxy_task = tokio::spawn(async move { + let downstream = proxy.accept().await.unwrap().0; + if proxy_tls { + let downstream = acceptor.accept(downstream).await.unwrap(); + assert_ne!( + downstream.get_ref().1.alpn_protocol(), + Some(b"h2".as_slice()) + ); + tunnel(downstream, target, sent_head).await; + } else { + tunnel(downstream, target, sent_head).await; + } + }); + let client = server.client(true, Some(proxy_url)); + let response = client.inner().get(&server.url).send().await.unwrap(); + assert_eq!(response.version(), Version::HTTP_11); + response.bytes().await.unwrap(); + server.assert_version(Version::HTTP_11).await; + let head = tokio::time::timeout(Duration::from_secs(5), received_head) + .await + .expect("proxy did not receive CONNECT") + .unwrap(); + assert!( + head.starts_with(&format!("CONNECT {authority} HTTP/1.1\r\n")), + "{head}" + ); + proxy_task.abort(); } #[test] -fn environment_proxy_configuration_uses_http1_including_bypassed_hosts() { - const CHILD: &str = "DATABRICKS_HTTP2_ENV_TEST_PROTOCOL"; - if let Ok(protocol) = std::env::var(CHILD) { +fn proxy_environment_uses_http1_for_bypassed_hosts() { + let test_name = "proxy_environment_uses_http1_for_bypassed_hosts"; + if std::env::var(CHILD_TEST).as_deref() == Ok(test_name) { tokio::runtime::Builder::new_current_thread() .enable_all() .build() .unwrap() .block_on(async { - let expected = if protocol == "h2" { - Version::HTTP_2 - } else { + let expected = if PROXY_VARIABLES + .iter() + .any(|key| std::env::var_os(key).is_some_and(|value| !value.is_empty())) + { Version::HTTP_11 + } else { + Version::HTTP_2 }; let mut server = HttpsServer::start(true).await; let client = server.client(true, None); @@ -327,66 +359,20 @@ fn environment_proxy_configuration_uses_http1_including_bypassed_hosts() { return; } - let keys = [ - "HTTP_PROXY", - "http_proxy", - "HTTPS_PROXY", - "https_proxy", - "ALL_PROXY", - "all_proxy", - ]; - for selected in keys.into_iter().map(Some).chain([None]) { - let mut command = std::process::Command::new(std::env::current_exe().unwrap()); - command.args([ - "--exact", - "environment_proxy_configuration_uses_http1_including_bypassed_hosts", - "--nocapture", - ]); - for key in keys { - command.env(key, ""); - } - command.env("NO_PROXY", "127.0.0.1").env_remove("no_proxy"); - command.env(CHILD, if selected.is_some() { "http1" } else { "h2" }); - if let Some(key) = selected { - command.env(key, "http://127.0.0.1:9"); - } - let output = command.output().unwrap(); - assert!( - output.status.success(), - "proxy {selected:?}: {}{}", - String::from_utf8_lossy(&output.stdout), - String::from_utf8_lossy(&output.stderr) - ); + for selected in PROXY_VARIABLES.into_iter().map(Some).chain([None]) { + assert!(run_with_proxy_environment(test_name, selected)); } } #[tokio::test] -async fn session_http2_default_and_opt_out_reach_the_https_connection() { - if run_without_proxy_environment("session_http2_default_and_opt_out_reach_the_https_connection") - { +async fn session_preserves_http2_default_and_opt_out() { + if run_with_proxy_environment("session_preserves_http2_default_and_opt_out", None) { return; } - for enabled in [true, false] { + for enabled in [None, Some(true), Some(false)] { let mut server = HttpsServer::start(true).await; - let mut http = HttpConfig::default(); - assert!(http.http2_enabled); - http.http2_enabled = enabled; - http.overall_timeout = Duration::from_secs(5); - http.retry_max_retries = 0; - let mut tls = TlsConfig::default(); - tls.custom_ca_cert = Some(server.certificate.clone()); - let session = Session::builder() - .connection(ConnectionConfig::new(&server.url, "test-warehouse")) - .auth(AuthConfig::Pat { - token: "test-token".into(), - identity_federation_client_id: None, - }) - .http(http) - .tls(tls) - .open() - .await - .unwrap(); - let expected = if enabled { + let session = server.session_builder(enabled).open().await.unwrap(); + let expected = if enabled.unwrap_or(true) { Version::HTTP_2 } else { Version::HTTP_11 @@ -398,10 +384,8 @@ async fn session_http2_default_and_opt_out_reach_the_https_connection() { } #[tokio::test] -async fn telemetry_respects_each_sessions_http_protocol_setting_on_the_same_host() { - if run_without_proxy_environment( - "telemetry_respects_each_sessions_http_protocol_setting_on_the_same_host", - ) { +async fn telemetry_separates_protocols_on_the_same_host() { + if run_with_proxy_environment("telemetry_separates_protocols_on_the_same_host", None) { return; } for configurations in [ @@ -412,30 +396,20 @@ async fn telemetry_respects_each_sessions_http_protocol_setting_on_the_same_host let mut server = HttpsServer::start(true).await; let mut sessions = Vec::new(); for (enabled, proxied) in configurations { - let mut http = HttpConfig::default(); - http.http2_enabled = enabled; - http.retry_max_retries = 0; - http.overall_timeout = Duration::from_secs(5); - let mut tls = TlsConfig::default(); - tls.custom_ca_cert = Some(server.certificate.clone()); let mut proxy = ProxyConfig::default(); if proxied { proxy.url = Some("http://127.0.0.1:9".into()); proxy.bypass_hosts = Some("127.0.0.1".into()); } - let mut telemetry = TelemetryConfig::default(); - telemetry.enabled = Some(true); - telemetry.flush_interval = Duration::from_secs(3600); + let telemetry = TelemetryConfig { + enabled: Some(true), + flush_interval: Duration::from_secs(3600), + ..TelemetryConfig::default() + }; sessions.push( - Session::builder() - .connection(ConnectionConfig::new(&server.url, "test-warehouse")) - .auth(AuthConfig::Pat { - token: "test-token".into(), - identity_federation_client_id: None, - }) - .http(http) + server + .session_builder(Some(enabled)) .proxy(proxy) - .tls(tls) .telemetry(telemetry) .open() .await @@ -463,12 +437,12 @@ async fn telemetry_respects_each_sessions_http_protocol_setting_on_the_same_host } #[test] -fn c_abi_http2_default_and_opt_out_reach_the_https_connection() { - if run_without_proxy_environment("c_abi_http2_default_and_opt_out_reach_the_https_connection") { +fn c_abi_preserves_http2_default_and_opt_out() { + if run_with_proxy_environment("c_abi_preserves_http2_default_and_opt_out", None) { return; } - use databricks_sql_kernel::c_abi::session::*; - use databricks_sql_kernel::c_abi::KernelStatusCode; + use crate::c_abi::session::*; + use crate::c_abi::KernelStatusCode; use std::ffi::CString; use std::ptr; diff --git a/src/session.rs b/src/session.rs index 26fa2157..dabf5acf 100644 --- a/src/session.rs +++ b/src/session.rs @@ -368,7 +368,12 @@ impl Session { let http_client_config = build_http_client_config(&config, org_id); let retry_configs = build_retry_configs_for_session(&config); let http_client = Arc::new( - DatabricksHttpClient::new(http_client_config, retry_configs).map_err(|e| { + DatabricksHttpClient::new_with_http2( + http_client_config, + retry_configs, + config.http.http2_enabled, + ) + .map_err(|e| { Error::network_error().message(format!("Failed to construct HTTP client: {e}")) })?, ); @@ -1080,7 +1085,6 @@ fn validate_mtls_endpoint_scheme(config: &SessionConfig) -> Result<()> { /// [`HttpTlsConfig`] via [`HttpTlsConfig::from_public`]. fn build_http_client_config(config: &SessionConfig, org_id: Option) -> HttpClientConfig { HttpClientConfig { - http2_enabled: config.http.http2_enabled, sea_response_compression_enabled: config.http.sea_response_compression_enabled, connect_timeout: Duration::from_secs(30), // The historical internal `read_timeout` field is passed to reqwest's diff --git a/src/telemetry/runtime.rs b/src/telemetry/runtime.rs index 648aead1..601c64a3 100644 --- a/src/telemetry/runtime.rs +++ b/src/telemetry/runtime.rs @@ -66,7 +66,7 @@ impl TelemetryRuntime { connection_params: build_connection_params(connection, auth), auth_type: auth_type(auth), }); - let key = TelemetryClientKey::new(&connection.host, http_client.config().http2_enabled); + let key = TelemetryClientKey::new(&connection.host, http_client.http2_enabled()); let (exporter, bypass_cache) = exporter_for_config(config, connection, http_client); let Some(lease) = TelemetryClientManager::global().get_or_create(&key, config, exporter, bypass_cache) diff --git a/tests/http_client_config.rs b/tests/http_client_config.rs new file mode 100644 index 00000000..d7f7d6d3 --- /dev/null +++ b/tests/http_client_config.rs @@ -0,0 +1,32 @@ +// 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. + +use databricks_sql_kernel::client::{DatabricksHttpClient, HttpClientConfig}; +use std::time::Duration; + +#[test] +fn http_client_config_accepts_exhaustive_struct_literals() { + let config = HttpClientConfig { + sea_response_compression_enabled: false, + connect_timeout: Duration::from_secs(30), + read_timeout: Duration::from_secs(60), + max_connections_per_host: 100, + user_agent: "test-client".into(), + proxy: Default::default(), + tls: Default::default(), + org_id: None, + custom_headers: Vec::new(), + }; + DatabricksHttpClient::with_default_retry(config).unwrap(); +} From 4ec44bd56ed530a9efe6ffe88cf7acb208a8be00 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Thu, 19 Nov 2026 03:30:41 +0000 Subject: [PATCH 07/13] fix(telemetry): isolate circuit breakers by protocol policy Signed-off-by: Aakash Saravanan --- CONNECTION_PARAMETERS.md | 7 ++- src/client/http.rs | 4 ++ src/telemetry/circuit_breaker.rs | 97 ++++++++++++++++++++------------ src/telemetry/manager.rs | 2 +- src/telemetry/runtime.rs | 12 ++-- 5 files changed, 75 insertions(+), 47 deletions(-) diff --git a/CONNECTION_PARAMETERS.md b/CONNECTION_PARAMETERS.md index 4bea2000..cb3b4e71 100644 --- a/CONNECTION_PARAMETERS.md +++ b/CONNECTION_PARAMETERS.md @@ -125,11 +125,14 @@ until implemented) and `External` (a caller-supplied `TokenProvider`). ## `HttpConfig` — HTTP client (optional) -`http2_enabled` covers all kernel HTTPS traffic, including authentication, -SQL, result downloads and telemetry. An explicit proxy URL or nonempty +`http2_enabled` covers all HTTPS traffic created by the session, including +authentication, SQL, result downloads and telemetry. An explicit proxy URL or nonempty `HTTP_PROXY`, `HTTPS_PROXY`, `ALL_PROXY` (including lowercase variants) forces HTTP/1.1, including destinations that bypass the proxy. +Standalone `DatabricksHttpClient` constructors negotiate HTTP/2 for HTTPS unless +a proxy is configured. They do not expose a protocol opt-out. + | Field | Description | Default | |-------|-------------|---------| | `http2_enabled` | HTTP/2 with HTTP/1.1 fallback; `false` forces HTTP/1.1. | `true` | diff --git a/src/client/http.rs b/src/client/http.rs index 0d00bc46..9b0d9aae 100644 --- a/src/client/http.rs +++ b/src/client/http.rs @@ -395,6 +395,10 @@ impl DatabricksHttpClient { /// Auth provider must be set separately via `set_auth_provider()` before /// calling `execute()`. Use `execute_without_auth()` for requests that /// don't need authentication (e.g., OAuth token endpoint calls). + /// + /// HTTPS connections negotiate HTTP/2 with HTTP/1.1 fallback unless a proxy is configured. + /// This constructor has no protocol opt-out; session-created clients honor + /// [`HttpConfig::http2_enabled`](crate::HttpConfig::http2_enabled). pub fn new( config: HttpClientConfig, retry_configs: HashMap, diff --git a/src/telemetry/circuit_breaker.rs b/src/telemetry/circuit_breaker.rs index c9ea8c47..ead5f07a 100644 --- a/src/telemetry/circuit_breaker.rs +++ b/src/telemetry/circuit_breaker.rs @@ -13,6 +13,7 @@ // limitations under the License. use super::exporter::{TelemetryExportResult, TelemetryExporter}; +use super::manager::TelemetryClientKey; use super::models::TelemetryRequest; use crate::config::TelemetryConfig; use std::collections::HashMap; @@ -228,31 +229,20 @@ enum CircuitBreakerState { HalfOpen, } -/// Process-global registry of per-host circuit breakers. +/// Process-global registry of circuit breakers. /// -/// The `breakers` map is keyed by `(host, config)` and holds one entry per -/// distinct host a process talks to. Entries are never evicted, so the map -/// grows monotonically for the process lifetime. This is intentional and +/// Entries are never evicted, so the map grows for the process lifetime. This is /// bounded in practice: a kernel process connects to a small, stable set of -/// Databricks workspaces, and each entry is tiny (a `String` key plus an +/// Databricks workspaces, and each entry is tiny (a client key plus an /// `Arc` holding a `Mutex`). If a future /// deployment ever exhibits high host cardinality, add an LRU bound or /// idle-based eviction here. /// -/// Note on the `config` component of the key: telemetry config is effectively -/// **first-writer-wins per host** because `TelemetryClientManager` caches the -/// `TelemetryClient` (and thus its wrapped exporter) by host alone. A second -/// session to an already-connected host reuses the first session's client, so -/// its freshly-built exporter — and the breaker it would have created — is -/// discarded. In practice, then, only one `(host, config)` breaker is reached -/// per host (matching the first-writer-wins behavior of other telemetry knobs -/// such as `batch_size` and `flush_interval`). The `config` in the key is not -/// dead code, though: it still differentiates breakers for `bypass_cache` -/// (test-injected) exporters, which create unmanaged clients that skip the -/// host-only cache. +/// Match the cached client's identity so failures on one protocol policy +/// cannot suppress another policy's telemetry. #[derive(Default)] struct CircuitBreakerManager { - breakers: Mutex>>, + breakers: Mutex>>, } impl CircuitBreakerManager { @@ -261,21 +251,25 @@ impl CircuitBreakerManager { INSTANCE.get_or_init(Self::default) } - fn get_or_create(&self, host: &str, config: CircuitBreakerConfig) -> Arc { + fn get_or_create( + &self, + key: &TelemetryClientKey, + config: CircuitBreakerConfig, + ) -> Arc { let mut breakers = self .breakers .lock() .expect("poisoned telemetry circuit breakers"); Arc::clone( breakers - .entry((host.to_string(), config)) + .entry((key.clone(), config)) .or_insert_with(|| Arc::new(CircuitBreaker::new(config))), ) } } pub(super) fn maybe_wrap_exporter( - host: &str, + key: &TelemetryClientKey, config: &TelemetryConfig, exporter: Arc, ) -> Arc { @@ -285,23 +279,27 @@ pub(super) fn maybe_wrap_exporter( Arc::new(CircuitBreakerTelemetryExporter::new( exporter, - host, + key, circuit_config, )) } struct CircuitBreakerTelemetryExporter { inner: Arc, - host: String, + key: TelemetryClientKey, breaker: Arc, } impl CircuitBreakerTelemetryExporter { - fn new(inner: Arc, host: &str, config: CircuitBreakerConfig) -> Self { + fn new( + inner: Arc, + key: &TelemetryClientKey, + config: CircuitBreakerConfig, + ) -> Self { Self { inner, - host: host.to_string(), - breaker: CircuitBreakerManager::global().get_or_create(host, config), + key: key.clone(), + breaker: CircuitBreakerManager::global().get_or_create(key, config), } } } @@ -314,7 +312,7 @@ impl TelemetryExporter for CircuitBreakerTelemetryExporter { Box::pin(async move { let Some(guard) = self.breaker.before_export() else { tracing::debug!( - host = %self.host, + client = ?self.key, "telemetry circuit breaker open; dropping telemetry batch" ); return Ok(()); @@ -346,7 +344,7 @@ mod tests { let inner = Arc::new(FailingExporter::default()); let exporter = CircuitBreakerTelemetryExporter::new( inner.clone(), - unique_host("open"), + &unique_key("open"), CircuitBreakerConfig { failure_threshold: 2, open_timeout: Duration::from_secs(60), @@ -374,7 +372,7 @@ mod tests { let inner = Arc::new(ScriptedExporter::new(vec![false, true])); let exporter = CircuitBreakerTelemetryExporter::new( inner.clone(), - unique_host("recover"), + &unique_key("recover"), CircuitBreakerConfig { failure_threshold: 1, open_timeout: Duration::from_millis(10), @@ -399,7 +397,7 @@ mod tests { let inner = Arc::new(FailingExporter::default()); let exporter = CircuitBreakerTelemetryExporter::new( inner.clone(), - unique_host("reopen"), + &unique_key("reopen"), CircuitBreakerConfig { failure_threshold: 1, open_timeout: Duration::from_millis(10), @@ -419,7 +417,7 @@ mod tests { // Regression: a half-open probe future dropped mid-`await` (e.g. a // flush cancelled by `tokio::time::timeout` or an aborted timer task) // must not wedge the shared, process-global breaker in HalfOpen forever. - let host = unique_host("cancelled-probe"); + let key = unique_key("cancelled-probe"); let config = CircuitBreakerConfig { failure_threshold: 1, open_timeout: Duration::from_millis(10), @@ -427,16 +425,16 @@ mod tests { // Trip the breaker open through a failing exporter. let failing = Arc::new(FailingExporter::default()); - let failing_exporter = CircuitBreakerTelemetryExporter::new(failing.clone(), host, config); + let failing_exporter = CircuitBreakerTelemetryExporter::new(failing.clone(), &key, config); assert!(failing_exporter.export(sample_request()).await.is_err()); assert_eq!( failing_exporter.breaker.state_for_test(), CircuitBreakerState::Open ); - // A second exporter to the same host+config shares the same breaker. + // A cancelled probe must release the breaker shared by both exporters. let slow = Arc::new(SlowExporter::default()); - let slow_exporter = CircuitBreakerTelemetryExporter::new(slow.clone(), host, config); + let slow_exporter = CircuitBreakerTelemetryExporter::new(slow.clone(), &key, config); // After the timeout, drive a half-open probe and cancel it mid-flight via // `timeout` — this transitions the breaker to HalfOpen and then drops the @@ -552,7 +550,7 @@ mod tests { let failing = Arc::new(FailingExporter::default()); let failing_exporter = CircuitBreakerTelemetryExporter::new( failing.clone(), - unique_host("failing"), + &unique_key("failing"), CircuitBreakerConfig { failure_threshold: 1, open_timeout: Duration::from_secs(60), @@ -561,7 +559,7 @@ mod tests { let healthy = Arc::new(CapturingExporter::default()); let healthy_exporter = CircuitBreakerTelemetryExporter::new( healthy.clone(), - unique_host("healthy"), + &unique_key("healthy"), CircuitBreakerConfig { failure_threshold: 1, open_timeout: Duration::from_secs(60), @@ -582,6 +580,31 @@ mod tests { assert_eq!(healthy.calls.load(Ordering::SeqCst), 1); } + #[tokio::test] + async fn different_protocols_have_independent_breakers() { + let host = format!("telemetry-protocol-{}", std::process::id()); + let config = CircuitBreakerConfig { + failure_threshold: 1, + open_timeout: Duration::from_secs(60), + }; + let failing = CircuitBreakerTelemetryExporter::new( + Arc::new(FailingExporter::default()), + &TelemetryClientKey::new(&host, true), + config, + ); + let healthy = Arc::new(CapturingExporter::default()); + let exporter = CircuitBreakerTelemetryExporter::new( + healthy.clone(), + &TelemetryClientKey::new(&host, false), + config, + ); + + assert!(failing.export(sample_request()).await.is_err()); + assert_eq!(failing.breaker.state_for_test(), CircuitBreakerState::Open); + exporter.export(sample_request()).await.unwrap(); + assert_eq!(healthy.calls.load(Ordering::SeqCst), 1); + } + fn sample_request() -> TelemetryRequest { TelemetryRequest { upload_time: 1, @@ -589,8 +612,8 @@ mod tests { } } - fn unique_host(suffix: &str) -> &'static str { - Box::leak(format!("telemetry-{suffix}-{}", std::process::id()).into_boxed_str()) + fn unique_key(suffix: &str) -> TelemetryClientKey { + TelemetryClientKey::new(&format!("telemetry-{suffix}-{}", std::process::id()), true) } #[derive(Default)] diff --git a/src/telemetry/manager.rs b/src/telemetry/manager.rs index d11e2de9..2ab5ad63 100644 --- a/src/telemetry/manager.rs +++ b/src/telemetry/manager.rs @@ -24,7 +24,7 @@ pub(super) struct TelemetryClientManager { clients: Mutex>, } -#[derive(Clone, PartialEq, Eq, Hash)] +#[derive(Debug, Clone, PartialEq, Eq, Hash)] pub(super) struct TelemetryClientKey { host: String, http2_enabled: bool, diff --git a/src/telemetry/runtime.rs b/src/telemetry/runtime.rs index 601c64a3..8d3d7696 100644 --- a/src/telemetry/runtime.rs +++ b/src/telemetry/runtime.rs @@ -67,7 +67,7 @@ impl TelemetryRuntime { auth_type: auth_type(auth), }); let key = TelemetryClientKey::new(&connection.host, http_client.http2_enabled()); - let (exporter, bypass_cache) = exporter_for_config(config, connection, http_client); + let (exporter, bypass_cache) = exporter_for_config(config, connection, http_client, &key); let Some(lease) = TelemetryClientManager::global().get_or_create(&key, config, exporter, bypass_cache) else { @@ -322,24 +322,22 @@ fn exporter_for_config( config: &TelemetryConfig, connection: &ConnectionConfig, http_client: Arc, + key: &TelemetryClientKey, ) -> (Arc, bool) { #[cfg(test)] { if let Some(exporter) = config.exporter.clone() { - // Test-injected exporters must not enter the global per-host cache: + // Test-injected exporters must not enter the shared telemetry cache: // parallel tests commonly reuse the same mock host with different // capturing exporters, and cache reuse would route events to the // exporter from whichever test created the host client first. - return ( - maybe_wrap_exporter(&connection.host, config, exporter), - true, - ); + return (maybe_wrap_exporter(key, config, exporter), true); } } ( maybe_wrap_exporter( - &connection.host, + key, config, Arc::new(DatabricksTelemetryExporter::new( &connection.host, From 683eabe13141a27c8da99d3276af54544eaff448 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Thu, 19 Nov 2026 03:51:58 +0000 Subject: [PATCH 08/13] refactor(http): simplify protocol tests and documentation Signed-off-by: Aakash Saravanan --- pyo3/src/session.rs | 5 -- src/c_abi/session.rs | 2 +- src/client/http.rs | 8 +-- src/client/http2_tests.rs | 86 +++++++++++--------------------- src/telemetry/circuit_breaker.rs | 14 ++---- 5 files changed, 35 insertions(+), 80 deletions(-) diff --git a/pyo3/src/session.rs b/pyo3/src/session.rs index a45e685b..1046fca7 100644 --- a/pyo3/src/session.rs +++ b/pyo3/src/session.rs @@ -550,11 +550,6 @@ impl Session { None }; - // Build an HttpConfig only when the caller tuned transport options, - // compression, retry/backoff, or custom headers; otherwise leave the - // builder on its defaults (120s request timeout, - // 1s/60s/5-retries, no extra headers). - // // `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` diff --git a/src/c_abi/session.rs b/src/c_abi/session.rs index 17c9f505..18f1f391 100644 --- a/src/c_abi/session.rs +++ b/src/c_abi/session.rs @@ -613,7 +613,7 @@ pub unsafe extern "C" fn kernel_session_config_set_custom_header( } /// Negotiate HTTP/2 for HTTPS requests by default, with HTTP/1.1 fallback. -/// Set `enabled` to `false` to use HTTP/1.1 only. +/// Setting `enabled` to `false` or configuring a proxy forces HTTP/1.1. /// /// # Safety /// `config` must be a live config handle. diff --git a/src/client/http.rs b/src/client/http.rs index 9b0d9aae..5449c78a 100644 --- a/src/client/http.rs +++ b/src/client/http.rs @@ -538,12 +538,8 @@ impl DatabricksHttpClient { }) } - /// Build a `reqwest::Client` from `config` with the given redirect policy. - /// - /// Factored out of `new()` so tenant discovery can obtain a client that - /// does NOT follow redirects (to read the first `/aad/auth` hop's - /// `Location`) while still honouring the workspace's TLS, proxy, timeout, - /// and user-agent configuration. + /// Discovery needs the first redirect's `Location` while retaining the same + /// protocol, TLS, proxy, timeout and user-agent settings as normal requests. fn build_reqwest_client( config: &HttpClientConfig, http2_enabled: bool, diff --git a/src/client/http2_tests.rs b/src/client/http2_tests.rs index 3e5fbf7b..0079c30e 100644 --- a/src/client/http2_tests.rs +++ b/src/client/http2_tests.rs @@ -171,15 +171,13 @@ impl HttpsServer { client } - fn session_builder(&self, enabled: Option) -> SessionBuilder { - let mut http = HttpConfig { + fn session_builder(&self, enabled: bool) -> SessionBuilder { + let http = HttpConfig { + http2_enabled: enabled, overall_timeout: Duration::from_secs(5), retry_max_retries: 0, ..HttpConfig::default() }; - if let Some(enabled) = enabled { - http.http2_enabled = enabled; - } let tls = TlsConfig { custom_ca_cert: Some(self.certificate.clone()), ..TlsConfig::default() @@ -327,60 +325,34 @@ async fn assert_connect_proxy(proxy_tls: bool) { proxy_task.abort(); } -#[test] -fn proxy_environment_uses_http1_for_bypassed_hosts() { - let test_name = "proxy_environment_uses_http1_for_bypassed_hosts"; - if std::env::var(CHILD_TEST).as_deref() == Ok(test_name) { - tokio::runtime::Builder::new_current_thread() - .enable_all() - .build() - .unwrap() - .block_on(async { - let expected = if PROXY_VARIABLES - .iter() - .any(|key| std::env::var_os(key).is_some_and(|value| !value.is_empty())) - { - Version::HTTP_11 - } else { - Version::HTTP_2 - }; - let mut server = HttpsServer::start(true).await; - let client = server.client(true, None); - let response = client.inner().get(&server.url).send().await.unwrap(); - assert_eq!(response.version(), expected); - response.bytes().await.unwrap(); - server.assert_version(expected).await; - client - .first_redirect_location(&format!("{}/redirect", server.url)) - .await - .unwrap(); - server.assert_version(expected).await; - }); - return; - } - - for selected in PROXY_VARIABLES.into_iter().map(Some).chain([None]) { - assert!(run_with_proxy_environment(test_name, selected)); - } -} - #[tokio::test] -async fn session_preserves_http2_default_and_opt_out() { - if run_with_proxy_environment("session_preserves_http2_default_and_opt_out", None) { +async fn proxy_environment_uses_http1_for_bypassed_hosts() { + let test_name = "proxy_environment_uses_http1_for_bypassed_hosts"; + if std::env::var(CHILD_TEST).as_deref() != Ok(test_name) { + for selected in PROXY_VARIABLES.into_iter().map(Some).chain([None]) { + assert!(run_with_proxy_environment(test_name, selected)); + } return; } - for enabled in [None, Some(true), Some(false)] { - let mut server = HttpsServer::start(true).await; - let session = server.session_builder(enabled).open().await.unwrap(); - let expected = if enabled.unwrap_or(true) { - Version::HTTP_2 - } else { - Version::HTTP_11 - }; - server.assert_version(expected).await; - session.close().await.unwrap(); - server.assert_version(expected).await; - } + let expected = if PROXY_VARIABLES + .iter() + .any(|key| std::env::var_os(key).is_some_and(|value| !value.is_empty())) + { + Version::HTTP_11 + } else { + Version::HTTP_2 + }; + let mut server = HttpsServer::start(true).await; + let client = server.client(true, None); + let response = client.inner().get(&server.url).send().await.unwrap(); + assert_eq!(response.version(), expected); + response.bytes().await.unwrap(); + server.assert_version(expected).await; + client + .first_redirect_location(&format!("{}/redirect", server.url)) + .await + .unwrap(); + server.assert_version(expected).await; } #[tokio::test] @@ -408,7 +380,7 @@ async fn telemetry_separates_protocols_on_the_same_host() { }; sessions.push( server - .session_builder(Some(enabled)) + .session_builder(enabled) .proxy(proxy) .telemetry(telemetry) .open() diff --git a/src/telemetry/circuit_breaker.rs b/src/telemetry/circuit_breaker.rs index ead5f07a..feffbf54 100644 --- a/src/telemetry/circuit_breaker.rs +++ b/src/telemetry/circuit_breaker.rs @@ -229,17 +229,9 @@ enum CircuitBreakerState { HalfOpen, } -/// Process-global registry of circuit breakers. -/// -/// Entries are never evicted, so the map grows for the process lifetime. This is -/// bounded in practice: a kernel process connects to a small, stable set of -/// Databricks workspaces, and each entry is tiny (a client key plus an -/// `Arc` holding a `Mutex`). If a future -/// deployment ever exhibits high host cardinality, add an LRU bound or -/// idle-based eviction here. -/// -/// Match the cached client's identity so failures on one protocol policy -/// cannot suppress another policy's telemetry. +/// Protocol policies use separate breakers so one policy's failures cannot +/// suppress the other's telemetry. Entries remain for the process lifetime; +/// processes typically connect to a small, stable set of workspaces. #[derive(Default)] struct CircuitBreakerManager { breakers: Mutex>>, From b62c7bb9a8f27ca30c4320d0500377ab421b3453 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Thu, 19 Nov 2026 17:29:29 +0000 Subject: [PATCH 09/13] refactor(http): simplify protocol policy and transport coverage Signed-off-by: Aakash Saravanan --- CONNECTION_PARAMETERS.md | 3 +- adbc/README.md | 3 +- include/databricks_kernel.h | 2 +- pyo3/src/session.rs | 3 + src/c_abi/session.rs | 48 ++++- src/client/http.rs | 73 ++++---- src/client/http2_tests.rs | 299 ++++++------------------------- src/telemetry/circuit_breaker.rs | 101 +++++------ src/telemetry/manager.rs | 64 +++---- src/telemetry/runtime.rs | 24 +-- 10 files changed, 224 insertions(+), 396 deletions(-) diff --git a/CONNECTION_PARAMETERS.md b/CONNECTION_PARAMETERS.md index cb3b4e71..15d531b9 100644 --- a/CONNECTION_PARAMETERS.md +++ b/CONNECTION_PARAMETERS.md @@ -126,7 +126,8 @@ until implemented) and `External` (a caller-supplied `TokenProvider`). ## `HttpConfig` — HTTP client (optional) `http2_enabled` covers all HTTPS traffic created by the session, including -authentication, SQL, result downloads and telemetry. An explicit proxy URL or nonempty +authentication, SQL and result downloads. Telemetry clients are shared per host +and may reuse an earlier session's HTTP settings. An explicit proxy URL or nonempty `HTTP_PROXY`, `HTTPS_PROXY`, `ALL_PROXY` (including lowercase variants) forces HTTP/1.1, including destinations that bypass the proxy. diff --git a/adbc/README.md b/adbc/README.md index aac2a4e2..cd279b4e 100644 --- a/adbc/README.md +++ b/adbc/README.md @@ -70,8 +70,9 @@ Canonical `adbc.databricks.*` names take precedence over compatibility aliases. ## HTTP transport HTTPS requests negotiate HTTP/2 with HTTP/1.1 fallback by default. Set -`adbc.databricks.http.http2_enabled` to `false` to force HTTP/1.1 for all kernel +`adbc.databricks.http.http2_enabled` to `false` to force HTTP/1.1 for session HTTPS traffic. Configured proxies force HTTP/1.1, including bypassed destinations. +Telemetry may reuse an earlier session's HTTP client for the same host. ## Authentication diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h index b52ef22e..ef462902 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -361,7 +361,7 @@ KernelStatusCode kernel_session_config_set_enable_geospatial_support( KernelStatusCode kernel_session_config_set_custom_header(KernelSessionConfig* config, const char* name, const char* value); -/* Negotiate HTTP/2 for all HTTPS requests, with HTTP/1.1 fallback. +/* Negotiate HTTP/2 for session HTTPS requests, with HTTP/1.1 fallback. * Enabled by default. False or a configured proxy forces HTTP/1.1. */ KernelStatusCode kernel_session_config_set_http2_enabled( KernelSessionConfig* config, bool enabled); diff --git a/pyo3/src/session.rs b/pyo3/src/session.rs index 1046fca7..2bbb5405 100644 --- a/pyo3/src/session.rs +++ b/pyo3/src/session.rs @@ -550,6 +550,9 @@ impl Session { None }; + // Leave the builder's HTTP defaults intact unless a timeout, pool, retry, + // header, compression or protocol option was supplied. + // // `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` diff --git a/src/c_abi/session.rs b/src/c_abi/session.rs index 18f1f391..6533707c 100644 --- a/src/c_abi/session.rs +++ b/src/c_abi/session.rs @@ -1532,12 +1532,16 @@ fn merge_http_config( request_timeout: Option, max_connections: Option, retry: Option, + http2_enabled: Option, ) -> HttpConfig { let mut http = HttpConfig { custom_headers, sea_response_compression_enabled, ..HttpConfig::default() }; + if let Some(enabled) = http2_enabled { + http.http2_enabled = enabled; + } if let Some(t) = request_timeout { http.request_timeout = t; } @@ -1741,17 +1745,14 @@ fn build_session(config: KernelSessionConfig) -> Result bool { - self.http2_enabled - } - /// Returns the underlying reqwest client for building requests. pub fn inner(&self) -> &Client { &self.client @@ -973,24 +963,20 @@ impl DatabricksHttpClient { Error::invalid_argument().message(format!("Failed to build request: {e}")) })?; - debug!( - "{:?}: {} {} (attempt {}/{})", - request_type, - method, - url.as_str().split('?').next().unwrap_or_default(), - attempts, - max_attempts - ); - match self.client.execute(request).await { Ok(response) => { + let status = response.status(); debug!( request_type = ?request_type, host = ?response.url().host_str(), http_version = ?response.version(), + %method, + url = url.as_str().split('?').next().unwrap_or_default(), + attempt = attempts, + max_attempts, + status = status.as_u16(), "received HTTP response" ); - let status = response.status(); if status.is_success() { if attempts > 1 { @@ -1068,6 +1054,14 @@ impl DatabricksHttpClient { )); } Err(mut e) => { + debug!( + "{:?}: {} {} (attempt {}/{})", + request_type, + method, + url.as_str().split('?').next().unwrap_or_default(), + attempts, + max_attempts + ); // reqwest's Display prints the request URL; a presigned URL's query is its credential. if let Some(url) = e.url_mut() { url.set_query(None); @@ -1127,6 +1121,25 @@ impl DatabricksHttpClient { } } +fn resolve_http2( + requested: bool, + proxy: &ProxyConfig, + lookup: impl Fn(&str) -> Option, +) -> bool { + requested + && proxy.url.is_none() + && ![ + "HTTP_PROXY", + "http_proxy", + "HTTPS_PROXY", + "https_proxy", + "ALL_PROXY", + "all_proxy", + ] + .iter() + .any(|key| lookup(key).is_some_and(|value| !value.is_empty())) +} + #[cfg(test)] #[path = "http2_tests.rs"] mod http2_tests; diff --git a/src/client/http2_tests.rs b/src/client/http2_tests.rs index 0079c30e..16417e8d 100644 --- a/src/client/http2_tests.rs +++ b/src/client/http2_tests.rs @@ -16,10 +16,6 @@ use crate::auth::PersonalAccessToken; use crate::client::{ build_retry_configs, DatabricksHttpClient, HttpClientConfig, RequestType, RetryConfig, }; -use crate::{ - AuthConfig, ConnectionConfig, HttpConfig, ProxyConfig, Session, SessionBuilder, - TelemetryConfig, TlsConfig, -}; use bytes::Bytes; use http::Version; use rustls::pki_types::PrivatePkcs8KeyDer; @@ -31,20 +27,10 @@ use tokio::sync::mpsc; use tokio::task::{JoinHandle, JoinSet}; use tokio_rustls::TlsAcceptor; -const PROXY_VARIABLES: [&str; 6] = [ - "HTTP_PROXY", - "http_proxy", - "HTTPS_PROXY", - "https_proxy", - "ALL_PROXY", - "all_proxy", -]; -const CHILD_TEST: &str = "DATABRICKS_HTTP2_TEST"; - struct HttpsServer { url: String, certificate: Vec, - requests: mpsc::UnboundedReceiver<(String, Version)>, + requests: mpsc::UnboundedReceiver, acceptor: TlsAcceptor, task: JoinHandle<()>, } @@ -93,7 +79,7 @@ impl HttpsServer { let mut connection = h2::server::handshake(stream).await.unwrap(); while let Some(request) = connection.accept().await { let (request, mut response) = request.unwrap(); - versions.send((request.uri().path().to_string(), request.version())).unwrap(); + versions.send(request.version()).unwrap(); let redirect = request.uri().path() == "/redirect"; let response_head = http::Response::builder() .status(if redirect { 302 } else { 200 }) @@ -101,7 +87,7 @@ impl HttpsServer { .body(()) .unwrap(); response.send_response(response_head, false).unwrap() - .send_data(Bytes::from_static(b"{\"session_id\":\"session-http2\"}"), true) + .send_data(Bytes::from_static(b"ok"), true) .unwrap(); } } else { @@ -113,10 +99,9 @@ impl HttpsServer { } request.push(byte[0]); } - let path = std::str::from_utf8(&request).unwrap().split_whitespace().nth(1).unwrap().to_string(); - versions.send((path, Version::HTTP_11)).unwrap(); + versions.send(Version::HTTP_11).unwrap(); let redirect = request.starts_with(b"GET /redirect "); - let body = r#"{"session_id":"session-http2"}"#; + let body = "ok"; let response = format!( "HTTP/1.1 {}\r\nLocation: https://example.invalid/authorize\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}", if redirect { "302 Found" } else { "200 OK" }, body.len(), body @@ -142,7 +127,7 @@ impl HttpsServer { } async fn assert_version(&mut self, expected: Version) { - let (_, version) = tokio::time::timeout(Duration::from_secs(5), self.requests.recv()) + let version = tokio::time::timeout(Duration::from_secs(5), self.requests.recv()) .await .unwrap() .unwrap(); @@ -170,64 +155,10 @@ impl HttpsServer { client.set_auth_provider(Arc::new(PersonalAccessToken::new("test-token"))); client } - - fn session_builder(&self, enabled: bool) -> SessionBuilder { - let http = HttpConfig { - http2_enabled: enabled, - overall_timeout: Duration::from_secs(5), - retry_max_retries: 0, - ..HttpConfig::default() - }; - let tls = TlsConfig { - custom_ca_cert: Some(self.certificate.clone()), - ..TlsConfig::default() - }; - Session::builder() - .connection(ConnectionConfig::new(&self.url, "test-warehouse")) - .auth(AuthConfig::Pat { - token: "test-token".into(), - identity_federation_client_id: None, - }) - .http(http) - .tls(tls) - } -} - -fn run_with_proxy_environment(test_name: &str, proxy_variable: Option<&str>) -> bool { - if std::env::var(CHILD_TEST).as_deref() == Ok(test_name) { - return false; - } - let qualified_name = format!("client::http::http2_tests::{test_name}"); - let mut command = std::process::Command::new(std::env::current_exe().unwrap()); - command - .args(["--exact", &qualified_name, "--nocapture"]) - .env(CHILD_TEST, test_name) - .env("NO_PROXY", "127.0.0.1") - .env_remove("no_proxy"); - for key in PROXY_VARIABLES { - command.env(key, ""); - } - if let Some(key) = proxy_variable { - command.env(key, "http://127.0.0.1:9"); - } - let output = command.output().unwrap(); - let stdout = String::from_utf8_lossy(&output.stdout); - assert!( - output.status.success() && stdout.contains("1 passed; 0 failed"), - "{test_name}: {stdout}{}", - String::from_utf8_lossy(&output.stderr) - ); - true } #[tokio::test] async fn https_negotiates_http2_with_http1_fallback_and_opt_out() { - if run_with_proxy_environment( - "https_negotiates_http2_with_http1_fallback_and_opt_out", - None, - ) { - return; - } for (server_http2, enabled, expected) in [ (true, true, Version::HTTP_2), (false, true, Version::HTTP_11), @@ -254,16 +185,6 @@ async fn https_negotiates_http2_with_http1_fallback_and_opt_out() { } } -#[tokio::test] -async fn https_uses_http1_through_an_http_proxy() { - assert_connect_proxy(false).await; -} - -#[tokio::test] -async fn https_uses_http1_through_an_https_proxy() { - assert_connect_proxy(true).await; -} - async fn tunnel( mut downstream: S, target: String, @@ -284,30 +205,23 @@ async fn tunnel( let _ = tokio::io::copy_bidirectional(&mut downstream, &mut upstream).await; } -async fn assert_connect_proxy(proxy_tls: bool) { +#[tokio::test] +async fn https_uses_http1_through_an_https_proxy() { let mut server = HttpsServer::start(true).await; let authority = server.url.strip_prefix("https://").unwrap().to_string(); let target = authority.clone(); let proxy = TcpListener::bind("127.0.0.1:0").await.unwrap(); - let proxy_url = format!( - "{}://{}", - if proxy_tls { "https" } else { "http" }, - proxy.local_addr().unwrap() - ); + let proxy_url = format!("https://{}", proxy.local_addr().unwrap()); let (sent_head, received_head) = tokio::sync::oneshot::channel(); let acceptor = server.acceptor.clone(); let proxy_task = tokio::spawn(async move { let downstream = proxy.accept().await.unwrap().0; - if proxy_tls { - let downstream = acceptor.accept(downstream).await.unwrap(); - assert_ne!( - downstream.get_ref().1.alpn_protocol(), - Some(b"h2".as_slice()) - ); - tunnel(downstream, target, sent_head).await; - } else { - tunnel(downstream, target, sent_head).await; - } + let downstream = acceptor.accept(downstream).await.unwrap(); + assert_ne!( + downstream.get_ref().1.alpn_protocol(), + Some(b"h2".as_slice()) + ); + tunnel(downstream, target, sent_head).await; }); let client = server.client(true, Some(proxy_url)); let response = client.inner().get(&server.url).send().await.unwrap(); @@ -325,155 +239,48 @@ async fn assert_connect_proxy(proxy_tls: bool) { proxy_task.abort(); } -#[tokio::test] -async fn proxy_environment_uses_http1_for_bypassed_hosts() { - let test_name = "proxy_environment_uses_http1_for_bypassed_hosts"; - if std::env::var(CHILD_TEST).as_deref() != Ok(test_name) { - for selected in PROXY_VARIABLES.into_iter().map(Some).chain([None]) { - assert!(run_with_proxy_environment(test_name, selected)); - } - return; - } - let expected = if PROXY_VARIABLES - .iter() - .any(|key| std::env::var_os(key).is_some_and(|value| !value.is_empty())) - { - Version::HTTP_11 - } else { - Version::HTTP_2 - }; - let mut server = HttpsServer::start(true).await; - let client = server.client(true, None); - let response = client.inner().get(&server.url).send().await.unwrap(); - assert_eq!(response.version(), expected); - response.bytes().await.unwrap(); - server.assert_version(expected).await; - client - .first_redirect_location(&format!("{}/redirect", server.url)) - .await - .unwrap(); - server.assert_version(expected).await; -} +#[test] +fn resolves_http2_from_request_and_proxy_configuration() { + use super::{resolve_http2, ProxyConfig}; -#[tokio::test] -async fn telemetry_separates_protocols_on_the_same_host() { - if run_with_proxy_environment("telemetry_separates_protocols_on_the_same_host", None) { - return; + for (requested, url, bypass, expected) in [ + (true, None, None, true), + (false, None, None, false), + (true, Some("https://proxy:8080"), None, false), + (true, Some("http://proxy:8080"), Some("*"), false), + ] { + let proxy = ProxyConfig { + url: url.map(Into::into), + bypass_hosts: bypass.map(Into::into), + ..ProxyConfig::default() + }; + assert_eq!(resolve_http2(requested, &proxy, |_| None), expected); } - for configurations in [ - [(true, false), (false, false)], - [(true, false), (true, true)], - [(true, true), (true, false)], + let proxy = ProxyConfig::default(); + for key in [ + "HTTP_PROXY", + "http_proxy", + "HTTPS_PROXY", + "https_proxy", + "ALL_PROXY", + "all_proxy", ] { - let mut server = HttpsServer::start(true).await; - let mut sessions = Vec::new(); - for (enabled, proxied) in configurations { - let mut proxy = ProxyConfig::default(); - if proxied { - proxy.url = Some("http://127.0.0.1:9".into()); - proxy.bypass_hosts = Some("127.0.0.1".into()); - } - let telemetry = TelemetryConfig { - enabled: Some(true), - flush_interval: Duration::from_secs(3600), - ..TelemetryConfig::default() - }; - sessions.push( - server - .session_builder(enabled) - .proxy(proxy) - .telemetry(telemetry) - .open() - .await - .unwrap(), + for (value, expected) in [ + (None, true), + (Some(""), true), + (Some("http://proxy:8080"), false), + ] { + assert_eq!( + resolve_http2(true, &proxy, |name| if name == key { + value.map(Into::into) + } else { + None + }), + expected, + "{key}={value:?}" ); } - for session in sessions.into_iter().rev() { - session.close().await.unwrap(); - } - let mut telemetry_versions = Vec::new(); - while let Ok((path, version)) = server.requests.try_recv() { - if path.starts_with("/telemetry") { - telemetry_versions.push(version); - } - } - assert!( - telemetry_versions.contains(&Version::HTTP_11), - "{telemetry_versions:?}" - ); - assert!( - telemetry_versions.contains(&Version::HTTP_2), - "{telemetry_versions:?}" - ); - } -} - -#[test] -fn c_abi_preserves_http2_default_and_opt_out() { - if run_with_proxy_environment("c_abi_preserves_http2_default_and_opt_out", None) { - return; - } - use crate::c_abi::session::*; - use crate::c_abi::KernelStatusCode; - use std::ffi::CString; - use std::ptr; - - let runtime = tokio::runtime::Runtime::new().unwrap(); - for enabled in [None, Some(true), Some(false)] { - let mut server = runtime.block_on(HttpsServer::start(true)); - let url = CString::new(server.url.clone()).unwrap(); - let certificate = server.certificate.clone(); - { - // SAFETY: config and session are initialized by the C ABI; input buffers - // remain alive through the calls that copy them. - unsafe { - let mut config = ptr::null_mut(); - assert_eq!( - kernel_session_config_new(&mut config), - KernelStatusCode::Success - ); - assert_eq!( - kernel_session_config_set_http_path( - config, - url.as_ptr(), - c"/sql/1.0/warehouses/test".as_ptr() - ), - KernelStatusCode::Success - ); - assert_eq!( - kernel_session_config_set_auth_pat(config, c"test-token".as_ptr()), - KernelStatusCode::Success - ); - assert_eq!( - kernel_session_config_set_tls_trusted_certs( - config, - certificate.as_ptr(), - certificate.len() - ), - KernelStatusCode::Success - ); - if let Some(enabled) = enabled { - assert_eq!( - kernel_session_config_set_http2_enabled(config, enabled), - KernelStatusCode::Success - ); - } - let mut session = ptr::null_mut(); - assert_eq!( - kernel_session_open(config, &mut session), - KernelStatusCode::Success - ); - assert_eq!(kernel_session_close(session), KernelStatusCode::Success); - } - } - let expected = if enabled == Some(false) { - Version::HTTP_11 - } else { - Version::HTTP_2 - }; - runtime.block_on(async { - server.assert_version(expected).await; - server.assert_version(expected).await; - }); } + assert!(resolve_http2(true, &proxy, |name| (name == "NO_PROXY") + .then(|| "*".into()))); } diff --git a/src/telemetry/circuit_breaker.rs b/src/telemetry/circuit_breaker.rs index feffbf54..c9ea8c47 100644 --- a/src/telemetry/circuit_breaker.rs +++ b/src/telemetry/circuit_breaker.rs @@ -13,7 +13,6 @@ // limitations under the License. use super::exporter::{TelemetryExportResult, TelemetryExporter}; -use super::manager::TelemetryClientKey; use super::models::TelemetryRequest; use crate::config::TelemetryConfig; use std::collections::HashMap; @@ -229,12 +228,31 @@ enum CircuitBreakerState { HalfOpen, } -/// Protocol policies use separate breakers so one policy's failures cannot -/// suppress the other's telemetry. Entries remain for the process lifetime; -/// processes typically connect to a small, stable set of workspaces. +/// Process-global registry of per-host circuit breakers. +/// +/// The `breakers` map is keyed by `(host, config)` and holds one entry per +/// distinct host a process talks to. Entries are never evicted, so the map +/// grows monotonically for the process lifetime. This is intentional and +/// bounded in practice: a kernel process connects to a small, stable set of +/// Databricks workspaces, and each entry is tiny (a `String` key plus an +/// `Arc` holding a `Mutex`). If a future +/// deployment ever exhibits high host cardinality, add an LRU bound or +/// idle-based eviction here. +/// +/// Note on the `config` component of the key: telemetry config is effectively +/// **first-writer-wins per host** because `TelemetryClientManager` caches the +/// `TelemetryClient` (and thus its wrapped exporter) by host alone. A second +/// session to an already-connected host reuses the first session's client, so +/// its freshly-built exporter — and the breaker it would have created — is +/// discarded. In practice, then, only one `(host, config)` breaker is reached +/// per host (matching the first-writer-wins behavior of other telemetry knobs +/// such as `batch_size` and `flush_interval`). The `config` in the key is not +/// dead code, though: it still differentiates breakers for `bypass_cache` +/// (test-injected) exporters, which create unmanaged clients that skip the +/// host-only cache. #[derive(Default)] struct CircuitBreakerManager { - breakers: Mutex>>, + breakers: Mutex>>, } impl CircuitBreakerManager { @@ -243,25 +261,21 @@ impl CircuitBreakerManager { INSTANCE.get_or_init(Self::default) } - fn get_or_create( - &self, - key: &TelemetryClientKey, - config: CircuitBreakerConfig, - ) -> Arc { + fn get_or_create(&self, host: &str, config: CircuitBreakerConfig) -> Arc { let mut breakers = self .breakers .lock() .expect("poisoned telemetry circuit breakers"); Arc::clone( breakers - .entry((key.clone(), config)) + .entry((host.to_string(), config)) .or_insert_with(|| Arc::new(CircuitBreaker::new(config))), ) } } pub(super) fn maybe_wrap_exporter( - key: &TelemetryClientKey, + host: &str, config: &TelemetryConfig, exporter: Arc, ) -> Arc { @@ -271,27 +285,23 @@ pub(super) fn maybe_wrap_exporter( Arc::new(CircuitBreakerTelemetryExporter::new( exporter, - key, + host, circuit_config, )) } struct CircuitBreakerTelemetryExporter { inner: Arc, - key: TelemetryClientKey, + host: String, breaker: Arc, } impl CircuitBreakerTelemetryExporter { - fn new( - inner: Arc, - key: &TelemetryClientKey, - config: CircuitBreakerConfig, - ) -> Self { + fn new(inner: Arc, host: &str, config: CircuitBreakerConfig) -> Self { Self { inner, - key: key.clone(), - breaker: CircuitBreakerManager::global().get_or_create(key, config), + host: host.to_string(), + breaker: CircuitBreakerManager::global().get_or_create(host, config), } } } @@ -304,7 +314,7 @@ impl TelemetryExporter for CircuitBreakerTelemetryExporter { Box::pin(async move { let Some(guard) = self.breaker.before_export() else { tracing::debug!( - client = ?self.key, + host = %self.host, "telemetry circuit breaker open; dropping telemetry batch" ); return Ok(()); @@ -336,7 +346,7 @@ mod tests { let inner = Arc::new(FailingExporter::default()); let exporter = CircuitBreakerTelemetryExporter::new( inner.clone(), - &unique_key("open"), + unique_host("open"), CircuitBreakerConfig { failure_threshold: 2, open_timeout: Duration::from_secs(60), @@ -364,7 +374,7 @@ mod tests { let inner = Arc::new(ScriptedExporter::new(vec![false, true])); let exporter = CircuitBreakerTelemetryExporter::new( inner.clone(), - &unique_key("recover"), + unique_host("recover"), CircuitBreakerConfig { failure_threshold: 1, open_timeout: Duration::from_millis(10), @@ -389,7 +399,7 @@ mod tests { let inner = Arc::new(FailingExporter::default()); let exporter = CircuitBreakerTelemetryExporter::new( inner.clone(), - &unique_key("reopen"), + unique_host("reopen"), CircuitBreakerConfig { failure_threshold: 1, open_timeout: Duration::from_millis(10), @@ -409,7 +419,7 @@ mod tests { // Regression: a half-open probe future dropped mid-`await` (e.g. a // flush cancelled by `tokio::time::timeout` or an aborted timer task) // must not wedge the shared, process-global breaker in HalfOpen forever. - let key = unique_key("cancelled-probe"); + let host = unique_host("cancelled-probe"); let config = CircuitBreakerConfig { failure_threshold: 1, open_timeout: Duration::from_millis(10), @@ -417,16 +427,16 @@ mod tests { // Trip the breaker open through a failing exporter. let failing = Arc::new(FailingExporter::default()); - let failing_exporter = CircuitBreakerTelemetryExporter::new(failing.clone(), &key, config); + let failing_exporter = CircuitBreakerTelemetryExporter::new(failing.clone(), host, config); assert!(failing_exporter.export(sample_request()).await.is_err()); assert_eq!( failing_exporter.breaker.state_for_test(), CircuitBreakerState::Open ); - // A cancelled probe must release the breaker shared by both exporters. + // A second exporter to the same host+config shares the same breaker. let slow = Arc::new(SlowExporter::default()); - let slow_exporter = CircuitBreakerTelemetryExporter::new(slow.clone(), &key, config); + let slow_exporter = CircuitBreakerTelemetryExporter::new(slow.clone(), host, config); // After the timeout, drive a half-open probe and cancel it mid-flight via // `timeout` — this transitions the breaker to HalfOpen and then drops the @@ -542,7 +552,7 @@ mod tests { let failing = Arc::new(FailingExporter::default()); let failing_exporter = CircuitBreakerTelemetryExporter::new( failing.clone(), - &unique_key("failing"), + unique_host("failing"), CircuitBreakerConfig { failure_threshold: 1, open_timeout: Duration::from_secs(60), @@ -551,7 +561,7 @@ mod tests { let healthy = Arc::new(CapturingExporter::default()); let healthy_exporter = CircuitBreakerTelemetryExporter::new( healthy.clone(), - &unique_key("healthy"), + unique_host("healthy"), CircuitBreakerConfig { failure_threshold: 1, open_timeout: Duration::from_secs(60), @@ -572,31 +582,6 @@ mod tests { assert_eq!(healthy.calls.load(Ordering::SeqCst), 1); } - #[tokio::test] - async fn different_protocols_have_independent_breakers() { - let host = format!("telemetry-protocol-{}", std::process::id()); - let config = CircuitBreakerConfig { - failure_threshold: 1, - open_timeout: Duration::from_secs(60), - }; - let failing = CircuitBreakerTelemetryExporter::new( - Arc::new(FailingExporter::default()), - &TelemetryClientKey::new(&host, true), - config, - ); - let healthy = Arc::new(CapturingExporter::default()); - let exporter = CircuitBreakerTelemetryExporter::new( - healthy.clone(), - &TelemetryClientKey::new(&host, false), - config, - ); - - assert!(failing.export(sample_request()).await.is_err()); - assert_eq!(failing.breaker.state_for_test(), CircuitBreakerState::Open); - exporter.export(sample_request()).await.unwrap(); - assert_eq!(healthy.calls.load(Ordering::SeqCst), 1); - } - fn sample_request() -> TelemetryRequest { TelemetryRequest { upload_time: 1, @@ -604,8 +589,8 @@ mod tests { } } - fn unique_key(suffix: &str) -> TelemetryClientKey { - TelemetryClientKey::new(&format!("telemetry-{suffix}-{}", std::process::id()), true) + fn unique_host(suffix: &str) -> &'static str { + Box::leak(format!("telemetry-{suffix}-{}", std::process::id()).into_boxed_str()) } #[derive(Default)] diff --git a/src/telemetry/manager.rs b/src/telemetry/manager.rs index 2ab5ad63..0b6551e4 100644 --- a/src/telemetry/manager.rs +++ b/src/telemetry/manager.rs @@ -21,22 +21,7 @@ use std::sync::{Arc, Mutex, OnceLock}; #[derive(Default)] pub(super) struct TelemetryClientManager { - clients: Mutex>, -} - -#[derive(Debug, Clone, PartialEq, Eq, Hash)] -pub(super) struct TelemetryClientKey { - host: String, - http2_enabled: bool, -} - -impl TelemetryClientKey { - pub(super) fn new(host: &str, http2_enabled: bool) -> Self { - Self { - host: host.to_string(), - http2_enabled, - } - } + clients: Mutex>, } impl TelemetryClientManager { @@ -47,7 +32,7 @@ impl TelemetryClientManager { pub(super) fn get_or_create( &'static self, - key: &TelemetryClientKey, + host: &str, config: &TelemetryConfig, exporter: Arc, bypass_cache: bool, @@ -62,11 +47,11 @@ impl TelemetryClientManager { } let mut clients = self.clients.lock().expect("poisoned telemetry clients"); - if let Some(holder) = clients.get_mut(key) { + if let Some(holder) = clients.get_mut(host) { holder.session_count += 1; holder.lease_count += 1; return Some(TelemetryClientLease::managed( - key, + host, Arc::clone(&holder.client), self, )); @@ -74,14 +59,14 @@ impl TelemetryClientManager { let client = TelemetryClient::new(config, exporter)?; clients.insert( - key.clone(), + host.to_string(), TelemetryClientHolder { client: Arc::clone(&client), session_count: 1, lease_count: 1, }, ); - Some(TelemetryClientLease::managed(key, client, self)) + Some(TelemetryClientLease::managed(host, client, self)) } #[cfg(test)] @@ -92,18 +77,13 @@ impl TelemetryClientManager { exporter: Arc, bypass_cache: bool, ) -> TelemetryClientLease { - self.get_or_create( - &TelemetryClientKey::new(host, true), - config, - exporter, - bypass_cache, - ) - .expect("telemetry runtime should start") + self.get_or_create(host, config, exporter, bypass_cache) + .expect("telemetry runtime should start") } - fn release_session(&self, key: &TelemetryClientKey) -> Option> { + fn release_session(&self, host: &str) -> Option> { let mut clients = self.clients.lock().expect("poisoned telemetry clients"); - let holder = clients.get_mut(key)?; + let holder = clients.get_mut(host)?; debug_assert!(holder.session_count > 0); // saturating_sub (not `-= 1`) so a future double-decrement degrades // gracefully in release builds, where the debug_assert is compiled out. @@ -115,9 +95,9 @@ impl TelemetryClientManager { } } - fn release_lease(&self, key: &TelemetryClientKey, session_released: bool) -> LeaseDropAction { + fn release_lease(&self, host: &str, session_released: bool) -> LeaseDropAction { let mut clients = self.clients.lock().expect("poisoned telemetry clients"); - let Some(holder) = clients.get_mut(key) else { + let Some(holder) = clients.get_mut(host) else { return LeaseDropAction::None; }; if !session_released { @@ -132,7 +112,7 @@ impl TelemetryClientManager { holder.lease_count = holder.lease_count.saturating_sub(1); if holder.lease_count == 0 { return clients - .remove(key) + .remove(host) .map(|holder| LeaseDropAction::Close(holder.client)) .unwrap_or(LeaseDropAction::None); } @@ -156,7 +136,7 @@ impl TelemetryClientManager { self.clients .lock() .expect("poisoned telemetry clients") - .get(&TelemetryClientKey::new(host, true)) + .get(host) .map(|holder| holder.session_count) } } @@ -178,7 +158,7 @@ enum LeaseDropAction { } pub(super) struct TelemetryClientLease { - key: Option, + host: Option, client: Arc, manager: Option<&'static TelemetryClientManager>, session_released: AtomicBool, @@ -186,12 +166,12 @@ pub(super) struct TelemetryClientLease { impl TelemetryClientLease { fn managed( - key: &TelemetryClientKey, + host: &str, client: Arc, manager: &'static TelemetryClientManager, ) -> Self { Self { - key: Some(key.clone()), + host: Some(host.to_string()), client, manager: Some(manager), session_released: AtomicBool::new(false), @@ -200,7 +180,7 @@ impl TelemetryClientLease { fn unmanaged(client: Arc) -> Self { Self { - key: None, + host: None, client, manager: None, session_released: AtomicBool::new(false), @@ -216,8 +196,8 @@ impl TelemetryClientLease { return; } - let client_to_flush = match (self.manager, self.key.as_ref()) { - (Some(manager), Some(key)) => manager.release_session(key), + let client_to_flush = match (self.manager, self.host.as_deref()) { + (Some(manager), Some(host)) => manager.release_session(host), _ => Some(Arc::clone(&self.client)), }; if let Some(client) = client_to_flush { @@ -230,8 +210,8 @@ impl TelemetryClientLease { impl Drop for TelemetryClientLease { fn drop(&mut self) { let session_released = self.session_released.swap(true, Ordering::AcqRel); - let action = match (self.manager, self.key.as_ref()) { - (Some(manager), Some(key)) => manager.release_lease(key, session_released), + let action = match (self.manager, self.host.as_deref()) { + (Some(manager), Some(host)) => manager.release_lease(host, session_released), _ => LeaseDropAction::Close(Arc::clone(&self.client)), }; match action { diff --git a/src/telemetry/runtime.rs b/src/telemetry/runtime.rs index 8d3d7696..1b8f751b 100644 --- a/src/telemetry/runtime.rs +++ b/src/telemetry/runtime.rs @@ -15,7 +15,7 @@ use super::circuit_breaker::maybe_wrap_exporter; use super::databricks::{DatabricksTelemetryExporter, TelemetryEndpoint}; use super::exporter::TelemetryExporter; -use super::manager::{TelemetryClientKey, TelemetryClientLease, TelemetryClientManager}; +use super::manager::{TelemetryClientLease, TelemetryClientManager}; use super::models::{ unix_time_millis, DriverAuthFlow, DriverAuthMech, DriverConnectionParameters, DriverErrorInfo, DriverMode, DriverSystemConfiguration, FrontendLogContext, FrontendLogEntry, HostDetails, @@ -66,11 +66,13 @@ impl TelemetryRuntime { connection_params: build_connection_params(connection, auth), auth_type: auth_type(auth), }); - let key = TelemetryClientKey::new(&connection.host, http_client.http2_enabled()); - let (exporter, bypass_cache) = exporter_for_config(config, connection, http_client, &key); - let Some(lease) = - TelemetryClientManager::global().get_or_create(&key, config, exporter, bypass_cache) - else { + let (exporter, bypass_cache) = exporter_for_config(config, connection, http_client); + let Some(lease) = TelemetryClientManager::global().get_or_create( + &connection.host, + config, + exporter, + bypass_cache, + ) else { return Self::disabled(); }; @@ -322,22 +324,24 @@ fn exporter_for_config( config: &TelemetryConfig, connection: &ConnectionConfig, http_client: Arc, - key: &TelemetryClientKey, ) -> (Arc, bool) { #[cfg(test)] { if let Some(exporter) = config.exporter.clone() { - // Test-injected exporters must not enter the shared telemetry cache: + // Test-injected exporters must not enter the global per-host cache: // parallel tests commonly reuse the same mock host with different // capturing exporters, and cache reuse would route events to the // exporter from whichever test created the host client first. - return (maybe_wrap_exporter(key, config, exporter), true); + return ( + maybe_wrap_exporter(&connection.host, config, exporter), + true, + ); } } ( maybe_wrap_exporter( - key, + &connection.host, config, Arc::new(DatabricksTelemetryExporter::new( &connection.host, From a77a61719bbd3b1cbc94f5a121d1c59e0a2e22f6 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Thu, 19 Nov 2026 18:12:12 +0000 Subject: [PATCH 10/13] fix(http): preserve request diagnostics and cover session opt-out Signed-off-by: Aakash Saravanan --- CONNECTION_PARAMETERS.md | 2 +- adbc/README.md | 1 - src/client/http.rs | 21 +++++++--------- src/client/http2_tests.rs | 49 ++++++++++++++++++++++++++++++++++--- src/config.rs | 12 ++++----- tests/http_client_config.rs | 32 ------------------------ 6 files changed, 60 insertions(+), 57 deletions(-) delete mode 100644 tests/http_client_config.rs diff --git a/CONNECTION_PARAMETERS.md b/CONNECTION_PARAMETERS.md index 15d531b9..2d8623aa 100644 --- a/CONNECTION_PARAMETERS.md +++ b/CONNECTION_PARAMETERS.md @@ -139,7 +139,7 @@ a proxy is configured. They do not expose a protocol opt-out. | `http2_enabled` | HTTP/2 with HTTP/1.1 fallback; `false` forces HTTP/1.1. | `true` | | `request_timeout` | Per-request timeout (connect + body). | `120s` | | `overall_timeout` | Maximum total time across retries for one logical RPC. | `900s` | -| `pool_max_idle_per_host` | Connection-pool size (max idle warm sockets per host). Raise for bursty concurrent workloads. | `100` | +| `pool_max_idle_per_host` | Maximum idle connections retained per host. HTTP/1.1 concurrency can use multiple sockets; HTTP/2 multiplexes requests on a shared connection. This does not limit active requests or HTTP/2 streams. | `100` | | `retry_min_wait` | Minimum backoff between retries; also the floor for a server `Retry-After` and the base of exponential backoff (`min_wait × 2^attempt`). | `1s` | | `retry_max_wait` | Maximum backoff between retries; caps both the exponential backoff and a server `Retry-After`. | `60s` | | `retry_max_retries` | Max retries **after** the first attempt — a request is tried at most `retry_max_retries + 1` times. | `5` (→ 6 total attempts) | diff --git a/adbc/README.md b/adbc/README.md index cd279b4e..f97bdb67 100644 --- a/adbc/README.md +++ b/adbc/README.md @@ -72,7 +72,6 @@ Canonical `adbc.databricks.*` names take precedence over compatibility aliases. HTTPS requests negotiate HTTP/2 with HTTP/1.1 fallback by default. Set `adbc.databricks.http.http2_enabled` to `false` to force HTTP/1.1 for session HTTPS traffic. Configured proxies force HTTP/1.1, including bypassed destinations. -Telemetry may reuse an earlier session's HTTP client for the same host. ## Authentication diff --git a/src/client/http.rs b/src/client/http.rs index f9a28b0d..61745147 100644 --- a/src/client/http.rs +++ b/src/client/http.rs @@ -963,6 +963,15 @@ impl DatabricksHttpClient { Error::invalid_argument().message(format!("Failed to build request: {e}")) })?; + debug!( + "{:?}: {} {} (attempt {}/{})", + request_type, + method, + url.as_str().split('?').next().unwrap_or_default(), + attempts, + max_attempts + ); + match self.client.execute(request).await { Ok(response) => { let status = response.status(); @@ -970,10 +979,6 @@ impl DatabricksHttpClient { request_type = ?request_type, host = ?response.url().host_str(), http_version = ?response.version(), - %method, - url = url.as_str().split('?').next().unwrap_or_default(), - attempt = attempts, - max_attempts, status = status.as_u16(), "received HTTP response" ); @@ -1054,14 +1059,6 @@ impl DatabricksHttpClient { )); } Err(mut e) => { - debug!( - "{:?}: {} {} (attempt {}/{})", - request_type, - method, - url.as_str().split('?').next().unwrap_or_default(), - attempts, - max_attempts - ); // reqwest's Display prints the request URL; a presigned URL's query is its credential. if let Some(url) = e.url_mut() { url.set_query(None); diff --git a/src/client/http2_tests.rs b/src/client/http2_tests.rs index 16417e8d..d791aa6c 100644 --- a/src/client/http2_tests.rs +++ b/src/client/http2_tests.rs @@ -16,6 +16,8 @@ use crate::auth::PersonalAccessToken; use crate::client::{ build_retry_configs, DatabricksHttpClient, HttpClientConfig, RequestType, RetryConfig, }; +use crate::config::{AuthConfig, HttpConfig, TelemetryConfig, TlsConfig}; +use crate::Session; use bytes::Bytes; use http::Version; use rustls::pki_types::PrivatePkcs8KeyDer; @@ -27,6 +29,8 @@ use tokio::sync::mpsc; use tokio::task::{JoinHandle, JoinSet}; use tokio_rustls::TlsAcceptor; +use super::{resolve_http2, ProxyConfig}; + struct HttpsServer { url: String, certificate: Vec, @@ -87,7 +91,7 @@ impl HttpsServer { .body(()) .unwrap(); response.send_response(response_head, false).unwrap() - .send_data(Bytes::from_static(b"ok"), true) + .send_data(Bytes::from_static(br#"{"session_id":"http2-test"}"#), true) .unwrap(); } } else { @@ -101,7 +105,7 @@ impl HttpsServer { } versions.send(Version::HTTP_11).unwrap(); let redirect = request.starts_with(b"GET /redirect "); - let body = "ok"; + let body = r#"{"session_id":"http2-test"}"#; let response = format!( "HTTP/1.1 {}\r\nLocation: https://example.invalid/authorize\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}", if redirect { "302 Found" } else { "200 OK" }, body.len(), body @@ -159,6 +163,10 @@ impl HttpsServer { #[tokio::test] async fn https_negotiates_http2_with_http1_fallback_and_opt_out() { + assert!( + resolve_http2(true, &ProxyConfig::default(), |key| std::env::var_os(key)), + "unset HTTP(S)_PROXY/ALL_PROXY and lowercase equivalents to test direct HTTP/2" + ); for (server_http2, enabled, expected) in [ (true, true, Version::HTTP_2), (false, true, Version::HTTP_11), @@ -185,6 +193,41 @@ async fn https_negotiates_http2_with_http1_fallback_and_opt_out() { } } +#[tokio::test] +async fn session_http2_opt_out_reaches_the_first_request() { + assert!( + resolve_http2(true, &ProxyConfig::default(), |key| std::env::var_os(key)), + "unset HTTP(S)_PROXY/ALL_PROXY and lowercase equivalents to test direct HTTP/2" + ); + let mut server = HttpsServer::start(true).await; + let session = Session::builder() + .http_path(&server.url, "/sql/1.0/warehouses/test") + .auth(AuthConfig::Pat { + token: "test-token".into(), + identity_federation_client_id: None, + }) + .http(HttpConfig { + http2_enabled: false, + request_timeout: Duration::from_secs(5), + overall_timeout: Duration::from_secs(5), + retry_max_retries: 0, + ..HttpConfig::default() + }) + .tls(TlsConfig { + custom_ca_cert: Some(server.certificate.clone()), + ..TlsConfig::default() + }) + .telemetry(TelemetryConfig { + enabled: Some(false), + ..TelemetryConfig::default() + }) + .open() + .await + .unwrap(); + server.assert_version(Version::HTTP_11).await; + session.close().await.unwrap(); +} + async fn tunnel( mut downstream: S, target: String, @@ -241,8 +284,6 @@ async fn https_uses_http1_through_an_https_proxy() { #[test] fn resolves_http2_from_request_and_proxy_configuration() { - use super::{resolve_http2, ProxyConfig}; - for (requested, url, bypass, expected) in [ (true, None, None, true), (false, None, None, false), diff --git a/src/config.rs b/src/config.rs index 174d22d5..e4051747 100644 --- a/src/config.rs +++ b/src/config.rs @@ -766,13 +766,11 @@ pub struct HttpConfig { /// Retrying stops once cumulative elapsed time exceeds this. pub overall_timeout: Duration, - /// Connection pool size (max idle warm sockets per remote host). - /// - /// Defaults to `100`, matching the JDBC driver's `HttpConnectionPoolSize` - /// default. Raise this for workloads that burst many concurrent - /// `executeStatement` calls or CloudFetch chunk downloads against a - /// single host; too low a value forces fresh TLS handshakes when the - /// pool fills. + /// Maximum idle connections retained per host, defaulting to `100`, + /// matching the JDBC driver's `HttpConnectionPoolSize`. + /// Higher values preserve more warm HTTP/1.1 connections between bursts. + /// HTTP/2 requests multiplex on a shared connection; this does not + /// limit active requests or HTTP/2 streams. pub pool_max_idle_per_host: usize, /// Minimum backoff wait between retry attempts. Also the floor for diff --git a/tests/http_client_config.rs b/tests/http_client_config.rs deleted file mode 100644 index d7f7d6d3..00000000 --- a/tests/http_client_config.rs +++ /dev/null @@ -1,32 +0,0 @@ -// 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. - -use databricks_sql_kernel::client::{DatabricksHttpClient, HttpClientConfig}; -use std::time::Duration; - -#[test] -fn http_client_config_accepts_exhaustive_struct_literals() { - let config = HttpClientConfig { - sea_response_compression_enabled: false, - connect_timeout: Duration::from_secs(30), - read_timeout: Duration::from_secs(60), - max_connections_per_host: 100, - user_agent: "test-client".into(), - proxy: Default::default(), - tls: Default::default(), - org_id: None, - custom_headers: Vec::new(), - }; - DatabricksHttpClient::with_default_retry(config).unwrap(); -} From c59563534b578e2c55fc87da09aa9cd5b16e6512 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Thu, 19 Nov 2026 21:07:47 +0000 Subject: [PATCH 11/13] docs(security): clarify h2 advisory exemption Signed-off-by: Aakash Saravanan --- deny.toml | 12 ++---------- osv-scanner.toml | 10 ++-------- 2 files changed, 4 insertions(+), 18 deletions(-) diff --git a/deny.toml b/deny.toml index 95be6715..467b1792 100644 --- a/deny.toml +++ b/deny.toml @@ -38,16 +38,8 @@ ignore = [ # type, so exercising the RSA load+sign path in tests has value. # Re-evaluate when `rsa` ships a constant-time stable release. "RUSTSEC-2023-0071", - # RUSTSEC-2026-0258 — "h2 unbounded empty DATA frames". A DoS advisory - # in `h2 0.4.15`, pulled in transitively via `hyper` <- `reqwest` - # (`cargo tree -i h2`); not a direct dependency and unrelated to this - # crate's code. 0.4.15 is already the latest 0.4.x (a `cargo update -p - # h2` is a no-op), so it cannot be cleared by a bump; clearing it needs - # an upstream `hyper`/`reqwest` release that requires the fixed `h2`. - # The advisory concerns a server-side frame-flood; the kernel is an - # HTTP *client* to Databricks SEA, so the attack surface is not exercised - # here. Pre-existing on `main` (fires against the shared reqwest stack, - # not this PR). Re-evaluate when the reqwest/hyper stack picks up the fix. + # The empty-DATA-frame flood affects HTTP/2 servers; the kernel only + # uses HTTP/2 as a client and runs no h2 server. "RUSTSEC-2026-0258", ] diff --git a/osv-scanner.toml b/osv-scanner.toml index 02316c80..8d0ca29b 100644 --- a/osv-scanner.toml +++ b/osv-scanner.toml @@ -53,21 +53,15 @@ reason = "jsonwebtoken claim-validation bug (CVE-2026-25537) is in the decode pa [[IgnoredVulns]] id = "RUSTSEC-2026-0258" # "h2 unbounded empty DATA frames" — a DoS advisory in `h2 0.4.15`, pulled in -# transitively via `hyper` <- `reqwest` (`cargo tree -i h2`). Not a direct -# dependency and unrelated to this crate's code; pre-existing on `main` (fires -# against the shared reqwest/hyper stack, not this PR). +# transitively via `hyper` <- `reqwest` (`cargo tree -i h2`). # # Not reachable in the way the advisory describes: it concerns a SERVER # accepting a flood of empty DATA frames; the kernel is an HTTP *client* to # Databricks SEA and never runs an h2 server, so the affected entrypoint is # not exposed. # -# Cannot be cleared by a bump: 0.4.15 is already the latest 0.4.x -# (`cargo update -p h2` is a no-op); clearing it needs an upstream -# `reqwest`/`hyper` release that pulls the fixed `h2`. -# # ignoreUntil forces periodic re-review: when it lapses OSV re-reports the # finding, and someone must reconfirm the client-only posture (and re-check # for a reqwest/hyper release carrying the fix) before renewing. ignoreUntil = 2027-02-14 -reason = "h2 (RUSTSEC-2026-0258) DoS is a server-side empty-DATA-frame flood; the kernel is an HTTP client only and runs no h2 server. Transitive via reqwest/hyper, pre-existing on main, latest 0.4.x so no bump available. Re-review on expiry." +reason = "h2 (RUSTSEC-2026-0258) DoS is a server-side empty-DATA-frame flood; the kernel is an HTTP client only and runs no h2 server. Transitive via reqwest/hyper. Re-review on expiry." From 0398a2a9a2dd9021b76d118ea47800c2c2047fda Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Fri, 20 Nov 2026 00:13:20 +0000 Subject: [PATCH 12/13] fix(http): upgrade h2 to a patched release Signed-off-by: Aakash Saravanan --- Cargo.lock | 4 ++-- deny.toml | 3 --- napi/Cargo.lock | 4 ++-- osv-scanner.toml | 16 ---------------- 4 files changed, 4 insertions(+), 23 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 0262de43..a7fce602 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1062,9 +1062,9 @@ dependencies = [ [[package]] name = "h2" -version = "0.4.15" +version = "0.4.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6cb093c84e8bd9b188d4c4a8cb6579fc016968d14c99882163cd3ff402a4f155" +checksum = "7d29020232d6aa3fb1daca64c1127cf662cf97f254ae16c18c05b8ab635fc118" dependencies = [ "atomic-waker", "bytes", diff --git a/deny.toml b/deny.toml index 467b1792..9e34c816 100644 --- a/deny.toml +++ b/deny.toml @@ -38,9 +38,6 @@ ignore = [ # type, so exercising the RSA load+sign path in tests has value. # Re-evaluate when `rsa` ships a constant-time stable release. "RUSTSEC-2023-0071", - # The empty-DATA-frame flood affects HTTP/2 servers; the kernel only - # uses HTTP/2 as a client and runs no h2 server. - "RUSTSEC-2026-0258", ] [licenses] diff --git a/napi/Cargo.lock b/napi/Cargo.lock index fd5f4e61..ec6e602d 100644 --- a/napi/Cargo.lock +++ b/napi/Cargo.lock @@ -997,9 +997,9 @@ dependencies = [ [[package]] name = "h2" -version = "0.4.15" +version = "0.4.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6cb093c84e8bd9b188d4c4a8cb6579fc016968d14c99882163cd3ff402a4f155" +checksum = "7d29020232d6aa3fb1daca64c1127cf662cf97f254ae16c18c05b8ab635fc118" dependencies = [ "atomic-waker", "bytes", diff --git a/osv-scanner.toml b/osv-scanner.toml index 8d0ca29b..45640b57 100644 --- a/osv-scanner.toml +++ b/osv-scanner.toml @@ -49,19 +49,3 @@ id = "GHSA-h395-gr6q-cpjc" # ring-backed 10.x if one exists) before renewing. ignoreUntil = 2027-02-14 reason = "jsonwebtoken claim-validation bug (CVE-2026-25537) is in the decode path; the kernel only signs, never decodes/validates JWTs (verified: no decode/Validation calls in src/). Upgrade to 10.x deferred — it forces rust_crypto (rsa/RUSTSEC-2023-0071 in runtime) or aws_lc_rs (C dep). Re-review on expiry." - -[[IgnoredVulns]] -id = "RUSTSEC-2026-0258" -# "h2 unbounded empty DATA frames" — a DoS advisory in `h2 0.4.15`, pulled in -# transitively via `hyper` <- `reqwest` (`cargo tree -i h2`). -# -# Not reachable in the way the advisory describes: it concerns a SERVER -# accepting a flood of empty DATA frames; the kernel is an HTTP *client* to -# Databricks SEA and never runs an h2 server, so the affected entrypoint is -# not exposed. -# -# ignoreUntil forces periodic re-review: when it lapses OSV re-reports the -# finding, and someone must reconfirm the client-only posture (and re-check -# for a reqwest/hyper release carrying the fix) before renewing. -ignoreUntil = 2027-02-14 -reason = "h2 (RUSTSEC-2026-0258) DoS is a server-side empty-DATA-frame flood; the kernel is an HTTP client only and runs no h2 server. Transitive via reqwest/hyper. Re-review on expiry." From 6c18311751cacec15bafdf9c85d179e01f1cfc86 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Fri, 20 Nov 2026 02:43:00 +0000 Subject: [PATCH 13/13] test(http): verify HTTP/2 setter in C smoke test Signed-off-by: Aakash Saravanan --- CONNECTION_PARAMETERS.md | 3 --- adbc/README.md | 10 ++++------ src/c_abi/session.rs | 20 -------------------- tests/c/session_smoke.c | 2 ++ 4 files changed, 6 insertions(+), 29 deletions(-) diff --git a/CONNECTION_PARAMETERS.md b/CONNECTION_PARAMETERS.md index 2d8623aa..65f8c719 100644 --- a/CONNECTION_PARAMETERS.md +++ b/CONNECTION_PARAMETERS.md @@ -131,9 +131,6 @@ and may reuse an earlier session's HTTP settings. An explicit proxy URL or nonem `HTTP_PROXY`, `HTTPS_PROXY`, `ALL_PROXY` (including lowercase variants) forces HTTP/1.1, including destinations that bypass the proxy. -Standalone `DatabricksHttpClient` constructors negotiate HTTP/2 for HTTPS unless -a proxy is configured. They do not expose a protocol opt-out. - | Field | Description | Default | |-------|-------------|---------| | `http2_enabled` | HTTP/2 with HTTP/1.1 fallback; `false` forces HTTP/1.1. | `true` | diff --git a/adbc/README.md b/adbc/README.md index f97bdb67..ead93dce 100644 --- a/adbc/README.md +++ b/adbc/README.md @@ -67,12 +67,6 @@ Exactly one of `adbc.databricks.http_path` and parameter in the HTTP path when the workspace connection details include one. Canonical `adbc.databricks.*` names take precedence over compatibility aliases. -## HTTP transport - -HTTPS requests negotiate HTTP/2 with HTTP/1.1 fallback by default. Set -`adbc.databricks.http.http2_enabled` to `false` to force HTTP/1.1 for session -HTTPS traffic. Configured proxies force HTTP/1.1, including bypassed destinations. - ## Authentication Set `adbc.databricks.auth.type` to one of `pat`, `oauth_m2m`, `oauth_u2m`, @@ -113,6 +107,10 @@ The main database option families are: | Execution | `adbc.databricks.enable_direct_results` (default `true`); set `false` to use `wait_timeout=0s` and status polling | | Metadata | `adbc.databricks.metadata.escape_catalog_name` | +HTTPS requests negotiate HTTP/2 with HTTP/1.1 fallback by default. Set +`adbc.databricks.http.http2_enabled` to `false` to force HTTP/1.1 for session +HTTPS traffic. Configured proxies force HTTP/1.1, including bypassed destinations. + The optional user-agent entry is appended to the driver-owned identity as `RustADBCDatabricksDriver/ ()`. Set it through `adbc.databricks.user_agent_entry`; `User-Agent` is not accepted in the generic diff --git a/src/c_abi/session.rs b/src/c_abi/session.rs index 6533707c..65d933b5 100644 --- a/src/c_abi/session.rs +++ b/src/c_abi/session.rs @@ -2697,26 +2697,6 @@ mod tests { } } - #[test] - fn set_http2_enabled_records_value() { - unsafe { - let mut config = std::ptr::null_mut(); - assert_eq!( - kernel_session_config_new(&mut config), - KernelStatusCode::Success - ); - assert_eq!(config.as_ref().unwrap().http2_enabled, None); - for enabled in [true, false] { - assert_eq!( - kernel_session_config_set_http2_enabled(config, enabled), - KernelStatusCode::Success - ); - assert_eq!(config.as_ref().unwrap().http2_enabled, Some(enabled)); - } - kernel_session_config_free(config); - } - } - #[test] fn set_sea_response_compression_records_value() { unsafe { diff --git a/tests/c/session_smoke.c b/tests/c/session_smoke.c index f6b78c2c..7af3dcad 100644 --- a/tests/c/session_smoke.c +++ b/tests/c/session_smoke.c @@ -240,6 +240,8 @@ static void test_u2m_and_header_setters(void) { rc = kernel_session_config_set_sea_response_compression_enabled(config, true); CHECK(rc == KernelStatusCode_Success, "set_sea_response_compression_enabled succeeds"); + rc = kernel_session_config_set_http2_enabled(config, false); + CHECK(rc == KernelStatusCode_Success, "set_http2_enabled succeeds"); rc = kernel_session_config_set_custom_header(config, NULL, "v"); CHECK(rc == KernelStatusCode_InvalidArgument, "set_custom_header(NULL name) → InvalidArgument"); rc = kernel_session_config_set_custom_header(config, "X-Foo", NULL);