From 13fb05367bb2993fcdaaea259956d2de175e4722 Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Fri, 20 Nov 2026 03:37:03 +0000 Subject: [PATCH 1/9] perf(session): reuse bounded HTTP connection pools across sessions Keep authentication, retries and session state independent while sharing reqwest clients for matching host, transport configuration and runtime. Expire idle clients and bound retention across runtimes and configurations. Signed-off-by: Vu Anh Phung Co-authored-by: Isaac --- Cargo.toml | 2 +- NEXT_CHANGELOG.md | 1 + src/client/http.rs | 41 ++++- src/client/mod.rs | 1 + src/client/pool.rs | 384 +++++++++++++++++++++++++++++++++++++++ src/session.rs | 6 +- tests/v0_session_pool.rs | 343 ++++++++++++++++++++++++++++++++++ 7 files changed, 766 insertions(+), 12 deletions(-) create mode 100644 src/client/pool.rs create mode 100644 tests/v0_session_pool.rs diff --git a/Cargo.toml b/Cargo.toml index f428c382..1e4fb40a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -146,7 +146,7 @@ jsonwebtoken = { version = "9", default-features = false, features = ["use_pem"] pkcs8 = { version = "0.10", features = ["encryption", "pem", "std"] } # PKCS#8 PEM parsing + PBES2 passphrase decryption [dev-dependencies] -tokio = { version = "1", features = ["rt-multi-thread", "macros", "net", "io-util"] } +tokio = { version = "1", features = ["rt-multi-thread", "macros", "net", "io-util", "test-util"] } wiremock = "0.6" tempfile = "3" log = "0.4" diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index 2679ab73..58841fe4 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -16,6 +16,7 @@ changes go in their respective binding's NEXT_CHANGELOG. ### Changed +- Sessions with matching HTTP settings on the same Tokio runtime reuse the HTTP connection pool. Pools are bounded and expire after 90 seconds without a new session; authentication and session state remain independent. - 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/src/client/http.rs b/src/client/http.rs index cac2243b..096807e5 100644 --- a/src/client/http.rs +++ b/src/client/http.rs @@ -113,7 +113,7 @@ fn http_error(status: u16, body: &str, context: impl std::fmt::Display) -> Error /// When `url` is set, the driver uses the specified proxy for all requests, /// overriding `HTTP_PROXY`/`HTTPS_PROXY` environment variables. When `url` /// is `None`, reqwest's default behavior applies (reads env vars automatically). -#[derive(Clone, Default)] +#[derive(Clone, Default, PartialEq, Eq)] pub struct ProxyConfig { /// Proxy URL (e.g., "http://proxy.corp.example.com:8080"). /// When set, overrides HTTP_PROXY/HTTPS_PROXY environment variables. @@ -145,7 +145,7 @@ impl std::fmt::Debug for ProxyConfig { /// All fields default to the most secure settings (`None` = use defaults). /// Relaxing any of these options should only be done in development/testing /// environments. -#[derive(Clone, Default)] +#[derive(Clone, Default, PartialEq, Eq)] pub struct TlsConfig { /// Enable TLS for connections. When `false`, allows plain HTTP. /// Default: true (TLS enabled). @@ -265,7 +265,7 @@ impl TlsConfig { } /// Configuration for the HTTP client. -#[derive(Debug, Clone)] +#[derive(Debug, Clone, PartialEq, Eq)] pub struct HttpClientConfig { /// Whether authenticated SEA requests may negotiate HTTP response compression. pub sea_response_compression_enabled: bool, @@ -395,8 +395,24 @@ 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_pool(config, retry_configs, None) + } + + pub(crate) fn for_session( + host: &str, + config: HttpClientConfig, + retry_configs: HashMap, + ) -> Result { + Self::new_with_pool(config, retry_configs, Some(host)) + } + + fn new_with_pool( mut config: HttpClientConfig, retry_configs: HashMap, + pool_host: Option<&str>, ) -> Result { // Fold any caller-supplied `User-Agent` custom header into the // effective UA, and remove it from `custom_headers` so it isn't @@ -479,7 +495,8 @@ impl DatabricksHttpClient { } // 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, reqwest::redirect::Policy::default(), pool_host)?; // Surface which TLS backend was compiled in so oncall debugging // a handshake / unknown-CA report can tell at a glance whether @@ -514,6 +531,7 @@ impl DatabricksHttpClient { fn build_reqwest_client( config: &HttpClientConfig, redirect: reqwest::redirect::Policy, + pool_host: Option<&str>, ) -> Result { let mut builder = Client::builder() .connect_timeout(config.connect_timeout) @@ -700,9 +718,15 @@ impl DatabricksHttpClient { debug!("HTTP client using default proxy behavior (env vars)"); } - builder.build().map_err(|e| { - Error::invalid_argument().message(format!("Failed to create HTTP client: {e}")) - }) + let build = || { + builder.build().map_err(|e| { + Error::invalid_argument().message(format!("Failed to create HTTP client: {e}")) + }) + }; + match pool_host { + Some(host) => super::pool::shared_client(host, config, build), + None => build(), + } } /// Creates a new HTTP client with default retry configs for all request categories. @@ -805,7 +829,8 @@ 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, reqwest::redirect::Policy::none(), None)?; let response = client.get(url).send().await.map_err(|e| { Error::network_error().message(format!("Redirect-probe request to {url} failed: {e}")) })?; diff --git a/src/client/mod.rs b/src/client/mod.rs index af553abf..6cb603d5 100644 --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -32,6 +32,7 @@ //! [`sea`]: self::sea pub mod http; +mod pool; pub mod retry; pub mod sea; pub(crate) mod transport; diff --git a/src/client/pool.rs b/src/client/pool.rs new file mode 100644 index 00000000..36e6fcd0 --- /dev/null +++ b/src/client/pool.rs @@ -0,0 +1,384 @@ +use std::collections::HashMap; +use std::ffi::OsString; +use std::sync::{Arc, Mutex, OnceLock, Weak}; +use std::time::Duration; + +use reqwest::Client; +use sha2::{Digest, Sha256}; +use tokio::runtime::{Handle, Id}; +use tokio::time::Instant; + +use super::http::HttpClientConfig; +use crate::Result; + +const MAX_RUNTIMES: usize = 16; +const MAX_CLIENTS: usize = 16; +const IDLE_TIMEOUT: Duration = Duration::from_secs(90); +const SWEEP_INTERVAL: Duration = Duration::from_secs(15); +const PROXY_ENV: [&str; 8] = [ + "HTTP_PROXY", + "http_proxy", + "HTTPS_PROXY", + "https_proxy", + "ALL_PROXY", + "all_proxy", + "NO_PROXY", + "no_proxy", +]; + +#[derive(PartialEq, Eq)] +struct PoolKey { + host: String, + config: HttpClientConfig, + proxy_env: [Option; PROXY_ENV.len()], + root_file: Option<(OsString, [u8; 32])>, +} + +impl PoolKey { + fn new(host: &str, config: &HttpClientConfig) -> Option { + let root_file = match std::env::var_os("SSL_CERT_FILE") { + Some(path) => { + let contents = std::fs::read(&path).ok()?; + Some((path, Sha256::digest(&contents).into())) + } + None => None, + }; + Some(Self { + host: host.to_owned(), + config: config.clone(), + proxy_env: PROXY_ENV.map(std::env::var_os), + root_file, + }) + } +} + +struct Entry { + key: PoolKey, + client: Client, + last_used: Instant, +} + +#[derive(Default)] +struct ClientPool { + entries: Mutex>, +} + +impl ClientPool { + fn get(&self, key: &PoolKey) -> Option { + let now = Instant::now(); + let mut entries = self + .entries + .lock() + .unwrap_or_else(|error| error.into_inner()); + entries + .iter_mut() + .find(|entry| entry.key == *key && now.duration_since(entry.last_used) < IDLE_TIMEOUT) + .map(|entry| { + entry.last_used = now; + entry.client.clone() + }) + } + + fn get_or_build(&self, key: PoolKey, build: impl FnOnce() -> Result) -> Result { + if let Some(client) = self.get(&key) { + return Ok(client); + } + let client = build()?; + let now = Instant::now(); + let mut entries = self + .entries + .lock() + .unwrap_or_else(|error| error.into_inner()); + if let Some(entry) = entries + .iter_mut() + .find(|entry| entry.key == key && now.duration_since(entry.last_used) < IDLE_TIMEOUT) + { + entry.last_used = now; + return Ok(entry.client.clone()); + } + let evicted = if entries.len() == MAX_CLIENTS { + let oldest = entries + .iter() + .enumerate() + .min_by_key(|(_, entry)| entry.last_used) + .map(|(index, _)| index) + .unwrap_or(0); + Some(entries.swap_remove(oldest)) + } else { + None + }; + entries.push(Entry { + key, + client: client.clone(), + last_used: now, + }); + drop(entries); + drop(evicted); + Ok(client) + } + + fn expire(&self, now: Instant) { + let mut entries = self + .entries + .lock() + .unwrap_or_else(|error| error.into_inner()); + let mut expired = Vec::new(); + let mut index = 0; + while index < entries.len() { + if now.duration_since(entries[index].last_used) >= IDLE_TIMEOUT { + expired.push(entries.swap_remove(index)); + } else { + index += 1; + } + } + drop(entries); + drop(expired); + } +} + +type Registry = Mutex>>; + +fn registry() -> &'static Registry { + static REGISTRY: OnceLock = OnceLock::new(); + REGISTRY.get_or_init(Registry::default) +} + +fn runtime_pool(runtime: &Handle) -> Option> { + let mut pools = registry().lock().unwrap_or_else(|error| error.into_inner()); + pools.retain(|_, pool| pool.strong_count() != 0); + if let Some(pool) = pools.get(&runtime.id()).and_then(Weak::upgrade) { + return Some(pool); + } + if pools.len() == MAX_RUNTIMES { + return None; + } + let pool = Arc::new(ClientPool::default()); + pools.insert(runtime.id(), Arc::downgrade(&pool)); + runtime.spawn(expire_idle_clients(runtime.id(), pool.clone())); + Some(pool) +} + +async fn expire_idle_clients(runtime_id: Id, pool: Arc) { + loop { + tokio::time::sleep(SWEEP_INTERVAL).await; + pool.expire(Instant::now()); + let mut pools = registry().lock().unwrap_or_else(|error| error.into_inner()); + if Arc::strong_count(&pool) == 1 + && pool + .entries + .lock() + .unwrap_or_else(|error| error.into_inner()) + .is_empty() + { + pools.remove(&runtime_id); + return; + } + } +} + +pub(super) fn shared_client( + host: &str, + config: &HttpClientConfig, + build: impl FnOnce() -> Result, +) -> Result { + if config.max_connections_per_host == 0 + || config.tls.trusted_certificate_path.is_some() + || std::env::var_os("SSL_CERT_DIR").is_some() + { + return build(); + } + let Ok(runtime) = Handle::try_current() else { + return build(); + }; + let Some(key) = PoolKey::new(host, config) else { + return build(); + }; + let Some(pool) = runtime_pool(&runtime) else { + return build(); + }; + pool.get_or_build(key, build) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::Error; + use std::sync::atomic::{AtomicUsize, Ordering}; + + fn key(host: &str) -> PoolKey { + PoolKey { + host: host.to_owned(), + config: HttpClientConfig::default(), + proxy_env: std::array::from_fn(|_| None), + root_file: None, + } + } + + #[tokio::test] + async fn cache_reuses_only_successful_builds() { + let pool = ClientPool::default(); + let builds = AtomicUsize::new(0); + for _ in 0..2 { + assert!(pool + .get_or_build(key("host"), || Err( + Error::invalid_argument().message("bad TLS") + )) + .is_err()); + assert!(pool.entries.lock().unwrap().is_empty()); + } + for _ in 0..3 { + pool.get_or_build(key("host"), || { + builds.fetch_add(1, Ordering::SeqCst); + Ok(Client::new()) + }) + .unwrap(); + } + assert_eq!(builds.load(Ordering::SeqCst), 1); + } + + #[tokio::test] + async fn config_host_environment_and_roots_partition_pools() { + let pool = ClientPool::default(); + pool.get_or_build(key("host"), || Ok(Client::new())) + .unwrap(); + let check = |changed: PoolKey| assert!(pool.get(&changed).is_none()); + check(key("other-host")); + let mut changed = key("host"); + changed.proxy_env[0] = Some("http://other-proxy".into()); + check(changed); + let mut changed = key("host"); + changed.root_file = Some(("root.pem".into(), [1; 32])); + check(changed); + type ConfigChange = Box; + let variants: Vec = vec![ + Box::new(|config| config.connect_timeout += Duration::from_secs(1)), + Box::new(|config| config.read_timeout += Duration::from_secs(1)), + Box::new(|config| config.max_connections_per_host += 1), + Box::new(|config| config.user_agent.push_str(" other")), + Box::new(|config| config.org_id = Some("other-org".into())), + Box::new(|config| { + config + .custom_headers + .push(("x-test".into(), "value".into())) + }), + Box::new(|config| config.sea_response_compression_enabled = true), + Box::new(|config| config.proxy.url = Some("http://proxy".into())), + Box::new(|config| config.proxy.username = Some("user".into())), + Box::new(|config| config.proxy.password = Some("secret".into())), + Box::new(|config| config.proxy.bypass_hosts = Some("other-host".into())), + Box::new(|config| config.tls.enabled = Some(false)), + Box::new(|config| config.tls.allow_self_signed = Some(true)), + Box::new(|config| config.tls.allow_hostname_mismatch = Some(true)), + Box::new(|config| config.tls.trusted_certificate_path = Some("root.pem".into())), + Box::new(|config| config.tls.trusted_certificate_pem = Some(vec![1])), + Box::new(|config| config.tls.client_cert_pem = Some(vec![2])), + Box::new(|config| config.tls.client_key_pem = Some(vec![3])), + ]; + for modify in variants { + let mut changed = key("host"); + modify(&mut changed.config); + check(changed); + } + assert!(pool.get(&key("host")).is_some()); + } + + #[tokio::test] + async fn cache_is_bounded_and_evicts_least_recently_used() { + let pool = ClientPool::default(); + for index in 0..MAX_CLIENTS { + pool.get_or_build(key(&index.to_string()), || Ok(Client::new())) + .unwrap(); + } + assert!(pool.get(&key("0")).is_some()); + pool.get_or_build(key("new-host"), || Ok(Client::new())) + .unwrap(); + assert_eq!(pool.entries.lock().unwrap().len(), MAX_CLIENTS); + assert!(pool.get(&key("0")).is_some()); + assert!(pool.get(&key("1")).is_none()); + assert!(pool.get(&key("new-host")).is_some()); + } + + #[tokio::test] + async fn idle_timeout_is_monotonic_and_access_refreshes_it() { + let pool = ClientPool::default(); + pool.get_or_build(key("host"), || Ok(Client::new())) + .unwrap(); + pool.entries.lock().unwrap()[0].last_used = Instant::now() - IDLE_TIMEOUT; + assert!(pool.get(&key("host")).is_none()); + pool.get_or_build(key("host"), || Ok(Client::new())) + .unwrap(); + pool.expire(Instant::now()); + assert_eq!(pool.entries.lock().unwrap().len(), 1); + let before_access = pool.entries.lock().unwrap()[0].last_used; + assert!(pool.get(&key("host")).is_some()); + assert!(pool.entries.lock().unwrap()[0].last_used >= before_access); + pool.expire(Instant::now() + IDLE_TIMEOUT); + assert!(pool.entries.lock().unwrap().is_empty()); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn a_build_never_holds_the_cache_lock() { + let pool = ClientPool::default(); + pool.get_or_build(key("host"), || { + assert!(pool.entries.try_lock().is_ok()); + Ok(Client::new()) + }) + .unwrap(); + } + + #[test] + fn concurrent_builds_publish_one_client_and_do_not_block_each_other() { + let pool = Arc::new(ClientPool::default()); + let rendezvous = Arc::new((Mutex::new(0), std::sync::Condvar::new())); + let joins: Vec<_> = (0..8) + .map(|_| { + let pool = pool.clone(); + let rendezvous = rendezvous.clone(); + std::thread::spawn(move || { + pool.get_or_build(key("host"), || { + let client = Client::new(); + let (entered, ready) = &*rendezvous; + let mut entered = entered.lock().unwrap(); + *entered += 1; + ready.notify_all(); + let (entered, _) = ready + .wait_timeout_while(entered, Duration::from_secs(5), |count| *count < 8) + .unwrap(); + assert_eq!(*entered, 8, "another builder was blocked by the cache lock"); + Ok(client) + }) + .unwrap(); + }) + }) + .collect(); + for join in joins { + join.join().unwrap(); + } + assert_eq!(pool.entries.lock().unwrap().len(), 1); + } + + #[tokio::test(start_paused = true)] + async fn cleanup_drops_idle_clients_and_exits_without_new_opens() { + let pool = Arc::new(ClientPool::default()); + pool.get_or_build(key("host"), || Ok(Client::new())) + .unwrap(); + let weak = Arc::downgrade(&pool); + let cleanup = tokio::spawn(expire_idle_clients(Handle::current().id(), pool)); + tokio::task::yield_now().await; + tokio::time::advance(IDLE_TIMEOUT + SWEEP_INTERVAL).await; + cleanup.await.unwrap(); + assert!(weak.upgrade().is_none()); + } + + #[tokio::test] + async fn cancelling_cleanup_drops_the_cache() { + let pool = Arc::new(ClientPool::default()); + pool.get_or_build(key("host"), || Ok(Client::new())) + .unwrap(); + let weak = Arc::downgrade(&pool); + let cleanup = tokio::spawn(expire_idle_clients(Handle::current().id(), pool)); + cleanup.abort(); + assert!(cleanup.await.unwrap_err().is_cancelled()); + assert!(weak.upgrade().is_none()); + } +} diff --git a/src/session.rs b/src/session.rs index ac2f462f..6c86341e 100644 --- a/src/session.rs +++ b/src/session.rs @@ -368,9 +368,9 @@ 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| { - Error::network_error().message(format!("Failed to construct HTTP client: {e}")) - })?, + DatabricksHttpClient::for_session(&host, http_client_config, retry_configs).map_err( + |e| Error::network_error().message(format!("Failed to construct HTTP client: {e}")), + )?, ); // 2. Auth provider — async because OAuth flows hit the OIDC diff --git a/tests/v0_session_pool.rs b/tests/v0_session_pool.rs new file mode 100644 index 00000000..11a8526c --- /dev/null +++ b/tests/v0_session_pool.rs @@ -0,0 +1,343 @@ +use databricks_sql_kernel::{AuthConfig, DefaultOpts, HttpConfig, Session, TlsConfig}; +use serde_json::{json, Value}; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex}; +use std::time::Duration; +use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader}; +use tokio::net::TcpListener; + +#[derive(Clone)] +struct RecordedRequest { + connection: usize, + method: String, + headers: Vec, + body: Value, +} + +struct Server { + host: String, + connections: Arc, + requests: Arc>>, + task: tokio::task::JoinHandle<()>, +} + +impl Server { + async fn start() -> Self { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let host = format!("http://{}", listener.local_addr().unwrap()); + let connections = Arc::new(AtomicUsize::new(0)); + let requests = Arc::new(Mutex::new(Vec::new())); + let recorded_connections = connections.clone(); + let recorded_requests = requests.clone(); + let sessions = Arc::new(AtomicUsize::new(0)); + let task = tokio::spawn(async move { + while let Ok((socket, _)) = listener.accept().await { + let connection = recorded_connections.fetch_add(1, Ordering::SeqCst); + let requests = recorded_requests.clone(); + let sessions = sessions.clone(); + tokio::spawn(async move { + let mut socket = BufReader::new(socket); + loop { + let mut start = String::new(); + if socket.read_line(&mut start).await.unwrap_or(0) == 0 { + return; + } + let mut headers = Vec::new(); + let mut length = 0; + loop { + let mut header = String::new(); + if socket.read_line(&mut header).await.unwrap_or(0) == 0 { + return; + } + if header == "\r\n" { + break; + } + let lower = header.to_lowercase(); + if let Some(value) = lower.strip_prefix("content-length:") { + length = value.trim().parse().unwrap(); + } + headers.push(header.trim().to_owned()); + } + let mut body = vec![0; length]; + if socket.read_exact(&mut body).await.is_err() { + return; + } + let parts: Vec<_> = start.split_whitespace().collect(); + let method = parts[0]; + let route = parts[1]; + requests.lock().unwrap().push(RecordedRequest { + connection, + method: method.to_owned(), + headers, + body: serde_json::from_slice(&body).unwrap_or(Value::Null), + }); + let body = if route.contains("feature-flags") { + json!({"flags": [], "ttl_seconds": 900}).to_string() + } else if method == "POST" && route.ends_with("/sessions") { + json!({"session_id": format!("session-{}", sessions.fetch_add(1, Ordering::SeqCst)), "warehouse_id": "test"}).to_string() + } else { + String::new() + }; + let response = format!( + "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nContent-Type: application/json\r\n\r\n{}", + body.len(), body + ); + if socket + .get_mut() + .write_all(response.as_bytes()) + .await + .is_err() + { + return; + } + } + }); + } + }); + Self { + host, + connections, + requests, + task, + } + } +} + +impl Drop for Server { + fn drop(&mut self) { + self.task.abort(); + } +} + +async fn open( + server: &Server, + token: &str, + catalog: &str, + http: HttpConfig, + tls: TlsConfig, +) -> Session { + let mut defaults = DefaultOpts::default(); + defaults.catalog = Some(catalog.to_owned()); + Session::builder() + .http_path(server.host.clone(), "/sql/1.0/warehouses/test") + .auth(AuthConfig::Pat { + token: token.to_owned(), + identity_federation_client_id: None, + }) + .defaults(defaults) + .http(http) + .tls(tls) + .open() + .await + .unwrap() +} + +async fn sessions_share_connections_not_authentication_or_catalogs() { + let server = Server::start().await; + let first = open( + &server, + "dapi_first", + "first_catalog", + HttpConfig::default(), + TlsConfig::default(), + ) + .await; + let second = open( + &server, + "dapi_second", + "second_catalog", + HttpConfig::default(), + TlsConfig::default(), + ) + .await; + assert_ne!(first.session_id(), second.session_id()); + first.close().await.unwrap(); + let third = open( + &server, + "dapi_third", + "third_catalog", + HttpConfig::default(), + TlsConfig::default(), + ) + .await; + second.close().await.unwrap(); + third.close().await.unwrap(); + let requests = server.requests.lock().unwrap(); + assert_eq!( + server.connections.load(Ordering::SeqCst), + 1, + "request connections: {:?}", + requests + .iter() + .map(|request| (&request.method, request.connection)) + .collect::>() + ); + let creates: Vec<_> = requests + .iter() + .filter(|request| request.method == "POST") + .collect(); + assert_eq!(creates.len(), 3); + for (request, (token, catalog)) in creates.iter().zip([ + ("dapi_first", "first_catalog"), + ("dapi_second", "second_catalog"), + ("dapi_third", "third_catalog"), + ]) { + assert!(request + .headers + .iter() + .any(|header| header.eq_ignore_ascii_case(&format!("authorization: Bearer {token}")))); + assert_eq!(request.body["catalog"], catalog); + } +} + +async fn different_headers_timeouts_and_tls_settings_use_separate_connections() { + let server = Server::start().await; + for variant in 0..4 { + let mut http = HttpConfig::default(); + let mut tls = TlsConfig::default(); + match variant { + 1 => http + .custom_headers + .push(("x-tenant".to_owned(), "other".to_owned())), + 2 => http.request_timeout += Duration::from_secs(1), + 3 => tls.accept_self_signed = true, + _ => {} + } + let session = open(&server, "dapi_token", "catalog", http, tls).await; + session.close().await.unwrap(); + } + assert_eq!(server.connections.load(Ordering::SeqCst), 4); +} + +async fn concurrent_sessions_keep_their_authentication_and_catalogs() { + let server = Server::start().await; + let sessions = (0..10).map(|index| { + let server = &server; + async move { + let token = format!("dapi_concurrent_{index}"); + let catalog = format!("catalog_{index}"); + let session = open( + server, + &token, + &catalog, + HttpConfig::default(), + TlsConfig::default(), + ) + .await; + session.close().await.unwrap(); + } + }); + futures::future::join_all(sessions).await; + let requests = server.requests.lock().unwrap(); + let creates: Vec<_> = requests + .iter() + .filter(|request| request.method == "POST") + .collect(); + assert_eq!(creates.len(), 10); + for index in 0..10 { + let catalog = format!("catalog_{index}"); + let request = creates + .iter() + .find(|request| request.body["catalog"] == catalog) + .unwrap(); + assert!(request.headers.iter().any(|header| header + .eq_ignore_ascii_case(&format!("authorization: Bearer dapi_concurrent_{index}")))); + } +} + +async fn separate_runtimes_never_share_clients() { + let server = Server::start().await; + let host = server.host.clone(); + tokio::task::spawn_blocking(move || { + let runtimes: Vec<_> = (0..3) + .map(|_| { + tokio::runtime::Builder::new_multi_thread() + .worker_threads(2) + .enable_all() + .build() + .unwrap() + }) + .collect(); + for runtime in runtimes.iter().rev().chain(runtimes.iter()) { + runtime.block_on(async { + let session = Session::builder() + .http_path(host.clone(), "/sql/1.0/warehouses/test") + .auth(AuthConfig::Pat { + token: "dapi_runtime".into(), + identity_federation_client_id: None, + }) + .open() + .await + .unwrap(); + session.close().await.unwrap(); + }); + } + }) + .await + .unwrap(); + assert_eq!(server.connections.load(Ordering::SeqCst), 3); +} + +async fn changed_root_file_contents_do_not_reuse_old_trust() { + let server = Server::start().await; + let first = open( + &server, + "dapi_token", + "catalog", + HttpConfig::default(), + TlsConfig::default(), + ) + .await; + first.close().await.unwrap(); + let replacement = + rcgen::generate_simple_self_signed(vec!["replacement.invalid".into()]).unwrap(); + std::fs::write( + std::env::var_os("SSL_CERT_FILE").unwrap(), + replacement.cert.pem(), + ) + .unwrap(); + let second = open( + &server, + "dapi_token", + "catalog", + HttpConfig::default(), + TlsConfig::default(), + ) + .await; + second.close().await.unwrap(); + assert_eq!(server.connections.load(Ordering::SeqCst), 2); +} + +#[test] +fn session_pool_end_to_end() { + if std::env::var_os("KERNEL_POOL_TEST_CHILD").is_none() { + let roots = tempfile::NamedTempFile::new().unwrap(); + let certificate = rcgen::generate_simple_self_signed(vec!["test.invalid".into()]).unwrap(); + std::fs::write(roots.path(), certificate.cert.pem()).unwrap(); + let status = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "session_pool_end_to_end", "--nocapture"]) + .env("KERNEL_POOL_TEST_CHILD", "1") + .env("SSL_CERT_FILE", roots.path()) + .env_remove("SSL_CERT_DIR") + .status() + .unwrap(); + assert!(status.success(), "isolated session pool assertions failed"); + return; + } + tokio::runtime::Builder::new_multi_thread() + .worker_threads(2) + .enable_all() + .build() + .unwrap() + .block_on(async { + tokio::time::timeout(Duration::from_secs(20), async { + sessions_share_connections_not_authentication_or_catalogs().await; + concurrent_sessions_keep_their_authentication_and_catalogs().await; + different_headers_timeouts_and_tls_settings_use_separate_connections().await; + separate_runtimes_never_share_clients().await; + changed_root_file_contents_do_not_reuse_old_trust().await; + }) + .await + .unwrap(); + }); +} From 428b49f1ea6b76c9981a5f434add9e751714a24d Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Fri, 20 Nov 2026 03:37:03 +0000 Subject: [PATCH 2/9] test(session): cover pool eviction and reuse bypass boundaries Signed-off-by: Vu Anh Phung Co-authored-by: Isaac --- src/client/pool.rs | 130 +++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 127 insertions(+), 3 deletions(-) diff --git a/src/client/pool.rs b/src/client/pool.rs index 36e6fcd0..af045fa0 100644 --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -243,9 +243,11 @@ mod tests { .unwrap(); let check = |changed: PoolKey| assert!(pool.get(&changed).is_none()); check(key("other-host")); - let mut changed = key("host"); - changed.proxy_env[0] = Some("http://other-proxy".into()); - check(changed); + for index in 0..PROXY_ENV.len() { + let mut changed = key("host"); + changed.proxy_env[index] = Some("http://other-proxy".into()); + check(changed); + } let mut changed = key("host"); changed.root_file = Some(("root.pem".into(), [1; 32])); check(changed); @@ -381,4 +383,126 @@ mod tests { assert!(cleanup.await.unwrap_err().is_cancelled()); assert!(weak.upgrade().is_none()); } + + #[tokio::test(start_paused = true)] + async fn cleanup_retains_recent_clients() { + let pool = Arc::new(ClientPool::default()); + pool.get_or_build(key("host"), || Ok(Client::new())) + .unwrap(); + let weak = Arc::downgrade(&pool); + let cleanup = tokio::spawn(expire_idle_clients(Handle::current().id(), pool)); + tokio::task::yield_now().await; + tokio::time::advance(SWEEP_INTERVAL).await; + tokio::task::yield_now().await; + assert!(!cleanup.is_finished()); + assert!(weak.upgrade().is_some()); + tokio::time::advance(IDLE_TIMEOUT).await; + cleanup.await.unwrap(); + } + + #[tokio::test(start_paused = true)] + async fn cleanup_does_not_detach_a_cache_held_by_a_builder() { + let pool = Arc::new(ClientPool::default()); + let cleanup = tokio::spawn(expire_idle_clients(Handle::current().id(), pool.clone())); + tokio::task::yield_now().await; + tokio::time::advance(SWEEP_INTERVAL).await; + tokio::task::yield_now().await; + assert!(!cleanup.is_finished()); + pool.get_or_build(key("host"), || Ok(Client::new())) + .unwrap(); + drop(pool); + tokio::time::advance(IDLE_TIMEOUT + SWEEP_INTERVAL).await; + cleanup.await.unwrap(); + } + + #[test] + fn dynamic_trust_and_disabled_pooling_bypass_reuse() { + let marker = "KERNEL_POOL_BYPASS_TEST"; + let Some(mode) = std::env::var_os(marker) else { + for mode in ["normal", "directory", "unreadable"] { + let mut child = std::process::Command::new(std::env::current_exe().unwrap()); + child + .args([ + "--exact", + "client::pool::tests::dynamic_trust_and_disabled_pooling_bypass_reuse", + "--nocapture", + ]) + .env(marker, mode) + .env_remove("SSL_CERT_FILE") + .env_remove("SSL_CERT_DIR"); + match mode { + "directory" => { + child.env("SSL_CERT_DIR", "/unreadable/certificate/directory"); + } + "unreadable" => { + child.env("SSL_CERT_FILE", "/unreadable/certificate/file"); + } + _ => {} + } + assert!( + child.status().unwrap().success(), + "bypass test mode {mode} failed" + ); + } + return; + }; + let check = |config: HttpClientConfig, expected| { + let builds = AtomicUsize::new(0); + for _ in 0..2 { + shared_client("host", &config, || { + builds.fetch_add(1, Ordering::SeqCst); + Ok(Client::new()) + }) + .unwrap(); + } + assert_eq!(builds.load(Ordering::SeqCst), expected); + }; + check(HttpClientConfig::default(), 2); + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .unwrap(); + runtime.block_on(async { + check( + HttpClientConfig::default(), + if mode == "normal" { 1 } else { 2 }, + ); + let disabled = HttpClientConfig { + max_connections_per_host: 0, + ..HttpClientConfig::default() + }; + check(disabled, 2); + let mut dynamic = HttpClientConfig::default(); + dynamic.tls.trusted_certificate_path = Some("root.pem".into()); + check(dynamic, 2); + }); + } + + #[test] + fn runtime_registry_is_bounded_and_shutdown_releases_clients() { + let runtimes: Vec<_> = (0..=MAX_RUNTIMES) + .map(|_| { + tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .unwrap() + }) + .collect(); + let mut weak_pools = Vec::new(); + for runtime in &runtimes[..MAX_RUNTIMES] { + let pool = runtime_pool(runtime.handle()).unwrap(); + assert!(Arc::ptr_eq(&pool, &runtime_pool(runtime.handle()).unwrap())); + pool.get_or_build(key("host"), || Ok(Client::new())) + .unwrap(); + weak_pools.push(Arc::downgrade(&pool)); + } + assert!(runtime_pool(runtimes[MAX_RUNTIMES].handle()).is_none()); + drop(runtimes); + assert!(weak_pools.iter().all(|pool| pool.upgrade().is_none())); + let replacement = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .unwrap(); + assert!(runtime_pool(replacement.handle()).is_some()); + } } From 8095b587c6eb4afd7e1a07b4763f9fe4e507822c Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Fri, 20 Nov 2026 03:37:03 +0000 Subject: [PATCH 3/9] fix(session): lease cached HTTP clients exclusively Preserve per-session idle-socket limits and request locality by returning clients only after their HTTP wrapper is dropped. Bound total client age, retain runtime shutdown safety, and isolate socket/configuration tests from connection-establishment races. Address adversarial review R1-1 through R1-9; declare Tokio 1.49 for runtime IDs and document bounded TLS/proxy retention. Signed-off-by: Vu Anh Phung Co-authored-by: Isaac --- Cargo.toml | 4 +- NEXT_CHANGELOG.md | 3 +- src/client/http.rs | 10 +- src/client/http_tls_tests.rs | 9 +- src/client/pool.rs | 577 ++++++++++++++++++++++++----------- src/config.rs | 7 +- tests/v0_session_pool.rs | 114 +++++-- 7 files changed, 513 insertions(+), 211 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 1e4fb40a..a7221cba 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -65,7 +65,7 @@ rustls = { version = "0.23.41", optional = true, default-features = false, featu # Enforce TLS dependency minimums for consumers with their own lockfiles. rustls-webpki = { version = "0.103.16", optional = true, default-features = false } webpki-roots = { version = "1.0.11", optional = true, default-features = false } -tokio = { version = "1", features = ["full", "sync"] } +tokio = { version = "1.49", features = ["full", "sync"] } # Serialization serde = { version = "1", features = ["derive"] } @@ -146,7 +146,7 @@ jsonwebtoken = { version = "9", default-features = false, features = ["use_pem"] pkcs8 = { version = "0.10", features = ["encryption", "pem", "std"] } # PKCS#8 PEM parsing + PBES2 passphrase decryption [dev-dependencies] -tokio = { version = "1", features = ["rt-multi-thread", "macros", "net", "io-util", "test-util"] } +tokio = { version = "1.49", features = ["rt-multi-thread", "macros", "net", "io-util", "test-util"] } wiremock = "0.6" tempfile = "3" log = "0.4" diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index 58841fe4..85dd081e 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -16,7 +16,7 @@ changes go in their respective binding's NEXT_CHANGELOG. ### Changed -- Sessions with matching HTTP settings on the same Tokio runtime reuse the HTTP connection pool. Pools are bounded and expire after 90 seconds without a new session; authentication and session state remain independent. +- Sessions can reuse a matching HTTP connection pool after its previous HTTP client is dropped; live sessions keep exclusive pools and independent idle-socket limits. Idle retention is bounded to 105 seconds (including TLS/proxy configuration), and pools older than five minutes are never reused, bounding system-trust snapshots. - 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 @@ -32,6 +32,7 @@ changes go in their respective binding's NEXT_CHANGELOG. ### Fixed +- Closing a `Session` now frees its transport, HTTP client and tokio runtime handle. A reference cycle between the transport and its result-reader factory kept them alive, so bindings that run one tokio runtime per session (Python) leaked four file descriptors per closed session until the process hit `Too many open files`. - `Session::open` authenticates once before resolving feature flags. A failed OAuth token request now fails the open immediately instead of being sent a second time by CreateSession. - A timed-out or reset CloudFetch download no longer writes the presigned URL's signature (`sig=`, `X-Amz-Signature`) to the log or the returned error. The request URL in those messages now ends at the path, and debug request lines stop at `?`. - Closing an OAuth session (M2M, M2M private key, U2M or Azure service principal) now frees its HTTP client and auth provider. The provider held the HTTP client strongly while the client owned the provider, so the pair and the provider's tokio runtime handle leaked for every closed session. diff --git a/src/client/http.rs b/src/client/http.rs index 096807e5..a2522cca 100644 --- a/src/client/http.rs +++ b/src/client/http.rs @@ -265,7 +265,7 @@ impl TlsConfig { } /// Configuration for the HTTP client. -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Debug, Clone)] pub struct HttpClientConfig { /// Whether authenticated SEA requests may negotiate HTTP response compression. pub sea_response_compression_enabled: bool, @@ -382,7 +382,7 @@ fn build_mtls_identity(cert_pem: &[u8], key_pem: &[u8]) -> Result>, retry_configs: HashMap, @@ -532,7 +532,7 @@ impl DatabricksHttpClient { config: &HttpClientConfig, redirect: reqwest::redirect::Policy, pool_host: Option<&str>, - ) -> Result { + ) -> Result { let mut builder = Client::builder() .connect_timeout(config.connect_timeout) // `read_timeout` is a historical name; reqwest applies this as @@ -724,8 +724,8 @@ impl DatabricksHttpClient { }) }; match pool_host { - Some(host) => super::pool::shared_client(host, config, build), - None => build(), + Some(host) => super::pool::session_client(host, config, build), + None => build().map(super::pool::PooledClient::from), } } diff --git a/src/client/http_tls_tests.rs b/src/client/http_tls_tests.rs index b4b2d8c3..91967781 100644 --- a/src/client/http_tls_tests.rs +++ b/src/client/http_tls_tests.rs @@ -193,7 +193,8 @@ async fn assert_certificate_failure(failure: CertificateFailure) { ) .resolve("expected-host.invalid", address) .build() - .unwrap(); + .unwrap() + .into(); format!("https://expected-host.invalid:{}", address.port()) } else { format!("https://{address}") @@ -395,7 +396,8 @@ async fn dns_failure_preserves_retryable_flag_without_http_retry() { .no_proxy() .dns_resolver(resolver.clone()) .build() - .unwrap(); + .unwrap() + .into(); let request = client .inner() .get("http://missing.invalid/") @@ -472,7 +474,8 @@ async fn cloudfetch_recovers_after_dns_failure() { .no_proxy() .dns_resolver(resolver.clone()) .build() - .unwrap(); + .unwrap() + .into(); let url = format!( "http://storage.invalid:{}/chunk.arrow", server.address().port() diff --git a/src/client/pool.rs b/src/client/pool.rs index af045fa0..ded246d2 100644 --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -1,5 +1,6 @@ use std::collections::HashMap; use std::ffi::OsString; +use std::ops::Deref; use std::sync::{Arc, Mutex, OnceLock, Weak}; use std::time::Duration; @@ -8,12 +9,13 @@ use sha2::{Digest, Sha256}; use tokio::runtime::{Handle, Id}; use tokio::time::Instant; -use super::http::HttpClientConfig; +use super::http::{HttpClientConfig, ProxyConfig, TlsConfig}; use crate::Result; const MAX_RUNTIMES: usize = 16; const MAX_CLIENTS: usize = 16; const IDLE_TIMEOUT: Duration = Duration::from_secs(90); +const MAX_AGE: Duration = Duration::from_secs(300); const SWEEP_INTERVAL: Duration = Duration::from_secs(15); const PROXY_ENV: [&str; 8] = [ "HTTP_PROXY", @@ -26,10 +28,33 @@ const PROXY_ENV: [&str; 8] = [ "no_proxy", ]; +#[derive(PartialEq, Eq)] +struct TransportKey { + connect_timeout: Duration, + read_timeout: Duration, + max_connections_per_host: usize, + user_agent: String, + tls: TlsConfig, + proxy: ProxyConfig, +} + +impl From<&HttpClientConfig> for TransportKey { + fn from(config: &HttpClientConfig) -> Self { + Self { + connect_timeout: config.connect_timeout, + read_timeout: config.read_timeout, + max_connections_per_host: config.max_connections_per_host, + user_agent: config.user_agent.clone(), + tls: config.tls.clone(), + proxy: config.proxy.clone(), + } + } +} + #[derive(PartialEq, Eq)] struct PoolKey { host: String, - config: HttpClientConfig, + config: TransportKey, proxy_env: [Option; PROXY_ENV.len()], root_file: Option<(OsString, [u8; 32])>, } @@ -45,7 +70,7 @@ impl PoolKey { }; Some(Self { host: host.to_owned(), - config: config.clone(), + config: config.into(), proxy_env: PROXY_ENV.map(std::env::var_os), root_file, }) @@ -55,85 +80,149 @@ impl PoolKey { struct Entry { key: PoolKey, client: Client, - last_used: Instant, + created_at: Instant, + idle_since: Instant, +} + +impl Entry { + fn reusable(&self, now: Instant) -> bool { + now.duration_since(self.idle_since) < IDLE_TIMEOUT + && now.duration_since(self.created_at) < MAX_AGE + } +} + +struct Lease { + pool: Arc, + key: PoolKey, + created_at: Instant, +} + +pub(super) struct PooledClient { + client: Client, + lease: Option, +} + +impl From for PooledClient { + fn from(client: Client) -> Self { + Self { + client, + lease: None, + } + } +} + +impl std::fmt::Debug for PooledClient { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + std::fmt::Debug::fmt(&self.client, formatter) + } +} + +impl Deref for PooledClient { + type Target = Client; + + fn deref(&self) -> &Self::Target { + &self.client + } +} + +impl Drop for PooledClient { + fn drop(&mut self) { + if let Some(lease) = self.lease.take() { + lease.pool.put(Entry { + key: lease.key, + client: self.client.clone(), + created_at: lease.created_at, + idle_since: Instant::now(), + }); + } + } +} + +#[derive(Default)] +struct PoolState { + entries: Vec, + closed: bool, } #[derive(Default)] struct ClientPool { - entries: Mutex>, + state: Mutex, } impl ClientPool { - fn get(&self, key: &PoolKey) -> Option { + fn take(&self, key: &PoolKey) -> Option { let now = Instant::now(); - let mut entries = self + let mut state = self.state.lock().unwrap_or_else(|error| error.into_inner()); + let index = state .entries - .lock() - .unwrap_or_else(|error| error.into_inner()); - entries - .iter_mut() - .find(|entry| entry.key == *key && now.duration_since(entry.last_used) < IDLE_TIMEOUT) - .map(|entry| { - entry.last_used = now; - entry.client.clone() - }) + .iter() + .position(|entry| entry.key == *key && entry.reusable(now))?; + Some(state.entries.swap_remove(index)) } - fn get_or_build(&self, key: PoolKey, build: impl FnOnce() -> Result) -> Result { - if let Some(client) = self.get(&key) { - return Ok(client); - } - let client = build()?; - let now = Instant::now(); - let mut entries = self - .entries - .lock() - .unwrap_or_else(|error| error.into_inner()); - if let Some(entry) = entries - .iter_mut() - .find(|entry| entry.key == key && now.duration_since(entry.last_used) < IDLE_TIMEOUT) - { - entry.last_used = now; - return Ok(entry.client.clone()); + fn checkout( + self: &Arc, + key: PoolKey, + build: impl FnOnce() -> Result, + ) -> Result { + let (client, created_at) = match self.take(&key) { + Some(entry) => (entry.client, entry.created_at), + None => (build()?, Instant::now()), + }; + Ok(PooledClient { + client, + lease: Some(Lease { + pool: self.clone(), + key, + created_at, + }), + }) + } + + fn put(&self, entry: Entry) { + let mut state = self.state.lock().unwrap_or_else(|error| error.into_inner()); + if state.closed || !entry.reusable(Instant::now()) { + return; } - let evicted = if entries.len() == MAX_CLIENTS { - let oldest = entries + let evicted = if state.entries.len() == MAX_CLIENTS { + let oldest = state + .entries .iter() .enumerate() - .min_by_key(|(_, entry)| entry.last_used) + .min_by_key(|(_, entry)| entry.idle_since) .map(|(index, _)| index) .unwrap_or(0); - Some(entries.swap_remove(oldest)) + Some(state.entries.swap_remove(oldest)) } else { None }; - entries.push(Entry { - key, - client: client.clone(), - last_used: now, - }); - drop(entries); + state.entries.push(entry); + drop(state); drop(evicted); - Ok(client) } fn expire(&self, now: Instant) { - let mut entries = self - .entries - .lock() - .unwrap_or_else(|error| error.into_inner()); + let mut state = self.state.lock().unwrap_or_else(|error| error.into_inner()); let mut expired = Vec::new(); let mut index = 0; - while index < entries.len() { - if now.duration_since(entries[index].last_used) >= IDLE_TIMEOUT { - expired.push(entries.swap_remove(index)); + while index < state.entries.len() { + if !state.entries[index].reusable(now) { + expired.push(state.entries.swap_remove(index)); } else { index += 1; } } - drop(entries); + drop(state); drop(expired); } + + fn close(&self) { + let mut state = self.state.lock().unwrap_or_else(|error| error.into_inner()); + state.closed = true; + let entries = std::mem::take(&mut state.entries); + drop(state); + drop(entries); + } } type Registry = Mutex>>; @@ -145,7 +234,15 @@ fn registry() -> &'static Registry { fn runtime_pool(runtime: &Handle) -> Option> { let mut pools = registry().lock().unwrap_or_else(|error| error.into_inner()); - pools.retain(|_, pool| pool.strong_count() != 0); + pools.retain(|_, pool| { + pool.upgrade().is_some_and(|pool| { + !pool + .state + .lock() + .unwrap_or_else(|error| error.into_inner()) + .closed + }) + }); if let Some(pool) = pools.get(&runtime.id()).and_then(Weak::upgrade) { return Some(pool); } @@ -158,45 +255,63 @@ fn runtime_pool(runtime: &Handle) -> Option> { Some(pool) } -async fn expire_idle_clients(runtime_id: Id, pool: Arc) { - loop { - tokio::time::sleep(SWEEP_INTERVAL).await; - pool.expire(Instant::now()); - let mut pools = registry().lock().unwrap_or_else(|error| error.into_inner()); - if Arc::strong_count(&pool) == 1 - && pool - .entries - .lock() - .unwrap_or_else(|error| error.into_inner()) - .is_empty() - { - pools.remove(&runtime_id); - return; +struct Cleanup { + pool: Arc, +} + +impl Drop for Cleanup { + fn drop(&mut self) { + self.pool.close(); + } +} + +fn expire_idle_clients( + runtime_id: Id, + pool: Arc, +) -> impl std::future::Future { + let cleanup = Cleanup { pool }; + async move { + loop { + tokio::time::sleep(SWEEP_INTERVAL).await; + cleanup.pool.expire(Instant::now()); + let mut pools = registry().lock().unwrap_or_else(|error| error.into_inner()); + if Arc::strong_count(&cleanup.pool) == 1 + && cleanup + .pool + .state + .lock() + .unwrap_or_else(|error| error.into_inner()) + .entries + .is_empty() + { + pools.remove(&runtime_id); + return; + } } } } -pub(super) fn shared_client( +pub(super) fn session_client( host: &str, config: &HttpClientConfig, build: impl FnOnce() -> Result, -) -> Result { +) -> Result { if config.max_connections_per_host == 0 || config.tls.trusted_certificate_path.is_some() || std::env::var_os("SSL_CERT_DIR").is_some() { - return build(); + return build().map(PooledClient::from); } let Ok(runtime) = Handle::try_current() else { - return build(); + return build().map(PooledClient::from); }; let Some(key) = PoolKey::new(host, config) else { - return build(); + return build().map(PooledClient::from); }; let Some(pool) = runtime_pool(&runtime) else { - return build(); + return build().map(PooledClient::from); }; - pool.get_or_build(key, build) + pool.checkout(key, build) } #[cfg(test)] @@ -208,62 +323,91 @@ mod tests { fn key(host: &str) -> PoolKey { PoolKey { host: host.to_owned(), - config: HttpClientConfig::default(), + config: (&HttpClientConfig::default()).into(), proxy_env: std::array::from_fn(|_| None), root_file: None, } } + async fn finish_cleanup(cleanup: tokio::task::JoinHandle<()>) { + tokio::time::timeout(SWEEP_INTERVAL * 2, cleanup) + .await + .expect("cleanup did not stop") + .unwrap(); + } + #[tokio::test] - async fn cache_reuses_only_successful_builds() { - let pool = ClientPool::default(); + async fn cache_reuses_only_successful_builds_after_return() { + let pool = Arc::new(ClientPool::default()); let builds = AtomicUsize::new(0); for _ in 0..2 { assert!(pool - .get_or_build(key("host"), || Err( + .checkout(key("host"), || Err( Error::invalid_argument().message("bad TLS") )) .is_err()); - assert!(pool.entries.lock().unwrap().is_empty()); + assert!(pool.state.lock().unwrap().entries.is_empty()); } - for _ in 0..3 { - pool.get_or_build(key("host"), || { + let first = pool + .checkout(key("host"), || { + builds.fetch_add(1, Ordering::SeqCst); + Ok(Client::new()) + }) + .unwrap(); + assert!(pool.state.lock().unwrap().entries.is_empty()); + assert_eq!(format!("{first:?}"), format!("{:?}", first.client)); + let second = pool + .checkout(key("host"), || { builds.fetch_add(1, Ordering::SeqCst); Ok(Client::new()) }) .unwrap(); + assert_eq!(builds.load(Ordering::SeqCst), 2); + drop(first); + let third = pool.checkout(key("host"), || panic!("cache miss")).unwrap(); + let fourth = pool + .checkout(key("host"), || { + builds.fetch_add(1, Ordering::SeqCst); + Ok(Client::new()) + }) + .unwrap(); + assert_eq!(builds.load(Ordering::SeqCst), 3); + drop(third); + for _ in 0..3 { + drop( + pool.checkout(key("host"), || panic!("returned client was not reused")) + .unwrap(), + ); } - assert_eq!(builds.load(Ordering::SeqCst), 1); + drop(second); + drop(fourth); + assert_eq!(pool.state.lock().unwrap().entries.len(), 3); } #[tokio::test] - async fn config_host_environment_and_roots_partition_pools() { - let pool = ClientPool::default(); - pool.get_or_build(key("host"), || Ok(Client::new())) - .unwrap(); - let check = |changed: PoolKey| assert!(pool.get(&changed).is_none()); - check(key("other-host")); + async fn only_transport_host_environment_and_roots_partition_pools() { + let original = HttpClientConfig::default(); + let pool = Arc::new(ClientPool::default()); + drop(pool.checkout(key("host"), || Ok(Client::new())).unwrap()); + let check = |changed: PoolKey| assert!(pool.take(&changed).is_none()); for index in 0..PROXY_ENV.len() { let mut changed = key("host"); changed.proxy_env[index] = Some("http://other-proxy".into()); + assert!(changed != key("host")); check(changed); } let mut changed = key("host"); changed.root_file = Some(("root.pem".into(), [1; 32])); + assert!(changed != key("host")); check(changed); + assert!(key("other-host") != key("host")); + check(key("other-host")); type ConfigChange = Box; let variants: Vec = vec![ Box::new(|config| config.connect_timeout += Duration::from_secs(1)), Box::new(|config| config.read_timeout += Duration::from_secs(1)), Box::new(|config| config.max_connections_per_host += 1), Box::new(|config| config.user_agent.push_str(" other")), - Box::new(|config| config.org_id = Some("other-org".into())), - Box::new(|config| { - config - .custom_headers - .push(("x-test".into(), "value".into())) - }), - Box::new(|config| config.sea_response_compression_enabled = true), Box::new(|config| config.proxy.url = Some("http://proxy".into())), Box::new(|config| config.proxy.username = Some("user".into())), Box::new(|config| config.proxy.password = Some("secret".into())), @@ -277,149 +421,210 @@ mod tests { Box::new(|config| config.tls.client_key_pem = Some(vec![3])), ]; for modify in variants { - let mut changed = key("host"); - modify(&mut changed.config); - check(changed); + let mut config = original.clone(); + modify(&mut config); + assert!(TransportKey::from(&config) != TransportKey::from(&original)); + check(PoolKey { + config: (&config).into(), + ..key("host") + }); } - assert!(pool.get(&key("host")).is_some()); + let mut per_request = original.clone(); + per_request.org_id = Some("other-org".into()); + per_request + .custom_headers + .push(("x-test".into(), "value".into())); + per_request.sea_response_compression_enabled = true; + assert!(TransportKey::from(&per_request) == TransportKey::from(&original)); + assert!(pool + .take(&PoolKey { + config: (&per_request).into(), + ..key("host") + }) + .is_some()); } - #[tokio::test] + #[tokio::test(start_paused = true)] async fn cache_is_bounded_and_evicts_least_recently_used() { - let pool = ClientPool::default(); + let pool = Arc::new(ClientPool::default()); for index in 0..MAX_CLIENTS { - pool.get_or_build(key(&index.to_string()), || Ok(Client::new())) - .unwrap(); + drop( + pool.checkout(key(&index.to_string()), || Ok(Client::new())) + .unwrap(), + ); + tokio::time::advance(Duration::from_millis(1)).await; } - assert!(pool.get(&key("0")).is_some()); - pool.get_or_build(key("new-host"), || Ok(Client::new())) - .unwrap(); - assert_eq!(pool.entries.lock().unwrap().len(), MAX_CLIENTS); - assert!(pool.get(&key("0")).is_some()); - assert!(pool.get(&key("1")).is_none()); - assert!(pool.get(&key("new-host")).is_some()); + drop(pool.checkout(key("0"), || panic!("cache miss")).unwrap()); + drop( + pool.checkout(key("new-host"), || Ok(Client::new())) + .unwrap(), + ); + assert_eq!(pool.state.lock().unwrap().entries.len(), MAX_CLIENTS); + assert!(pool.take(&key("0")).is_some()); + assert!(pool.take(&key("1")).is_none()); + assert!(pool.take(&key("new-host")).is_some()); } - #[tokio::test] - async fn idle_timeout_is_monotonic_and_access_refreshes_it() { - let pool = ClientPool::default(); - pool.get_or_build(key("host"), || Ok(Client::new())) - .unwrap(); - pool.entries.lock().unwrap()[0].last_used = Instant::now() - IDLE_TIMEOUT; - assert!(pool.get(&key("host")).is_none()); - pool.get_or_build(key("host"), || Ok(Client::new())) - .unwrap(); + #[tokio::test(start_paused = true)] + async fn idle_timeout_is_monotonic_and_return_refreshes_it() { + let pool = Arc::new(ClientPool::default()); + drop(pool.checkout(key("host"), || Ok(Client::new())).unwrap()); + tokio::time::advance(IDLE_TIMEOUT / 2).await; + drop( + pool.checkout(key("host"), || panic!("idle entry expired early")) + .unwrap(), + ); + tokio::time::advance(IDLE_TIMEOUT / 2).await; + drop( + pool.checkout(key("host"), || { + panic!("return did not refresh idle timeout") + }) + .unwrap(), + ); + tokio::time::advance(IDLE_TIMEOUT).await; + assert!(pool.take(&key("host")).is_none()); + pool.expire(Instant::now()); + assert!(pool.state.lock().unwrap().entries.is_empty()); + } + + #[tokio::test(start_paused = true)] + async fn maximum_age_expires_clients_despite_repeated_checkouts() { + let pool = Arc::new(ClientPool::default()); + let builds = AtomicUsize::new(0); + for _ in 0..=MAX_AGE.as_secs() / 30 { + drop( + pool.checkout(key("host"), || { + builds.fetch_add(1, Ordering::SeqCst); + Ok(Client::new()) + }) + .unwrap(), + ); + tokio::time::advance(Duration::from_secs(30)).await; + } + assert_eq!(builds.load(Ordering::SeqCst), 2); + let active = pool.checkout(key("host"), || panic!("cache miss")).unwrap(); + tokio::time::advance(MAX_AGE).await; + drop(active); pool.expire(Instant::now()); - assert_eq!(pool.entries.lock().unwrap().len(), 1); - let before_access = pool.entries.lock().unwrap()[0].last_used; - assert!(pool.get(&key("host")).is_some()); - assert!(pool.entries.lock().unwrap()[0].last_used >= before_access); - pool.expire(Instant::now() + IDLE_TIMEOUT); - assert!(pool.entries.lock().unwrap().is_empty()); + assert!(pool.state.lock().unwrap().entries.is_empty()); } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn a_build_never_holds_the_cache_lock() { - let pool = ClientPool::default(); - pool.get_or_build(key("host"), || { - assert!(pool.entries.try_lock().is_ok()); - Ok(Client::new()) - }) - .unwrap(); + let pool = Arc::new(ClientPool::default()); + drop( + pool.checkout(key("host"), || { + assert!(pool.state.try_lock().is_ok()); + Ok(Client::new()) + }) + .unwrap(), + ); } #[test] - fn concurrent_builds_publish_one_client_and_do_not_block_each_other() { + fn concurrent_checkouts_build_exclusive_clients_and_bound_returned_clients() { let pool = Arc::new(ClientPool::default()); let rendezvous = Arc::new((Mutex::new(0), std::sync::Condvar::new())); - let joins: Vec<_> = (0..8) + let joins: Vec<_> = (0..MAX_CLIENTS + 4) .map(|_| { let pool = pool.clone(); let rendezvous = rendezvous.clone(); std::thread::spawn(move || { - pool.get_or_build(key("host"), || { + pool.checkout(key("host"), || { let client = Client::new(); let (entered, ready) = &*rendezvous; let mut entered = entered.lock().unwrap(); *entered += 1; ready.notify_all(); let (entered, _) = ready - .wait_timeout_while(entered, Duration::from_secs(5), |count| *count < 8) + .wait_timeout_while(entered, Duration::from_secs(10), |count| { + *count < MAX_CLIENTS + 4 + }) .unwrap(); - assert_eq!(*entered, 8, "another builder was blocked by the cache lock"); + assert_eq!( + *entered, + MAX_CLIENTS + 4, + "another builder was blocked by the cache lock" + ); Ok(client) }) - .unwrap(); + .unwrap() }) }) .collect(); - for join in joins { - join.join().unwrap(); - } - assert_eq!(pool.entries.lock().unwrap().len(), 1); + let clients: Vec<_> = joins.into_iter().map(|join| join.join().unwrap()).collect(); + assert!(pool.state.lock().unwrap().entries.is_empty()); + drop(clients); + assert_eq!(pool.state.lock().unwrap().entries.len(), MAX_CLIENTS); } #[tokio::test(start_paused = true)] async fn cleanup_drops_idle_clients_and_exits_without_new_opens() { let pool = Arc::new(ClientPool::default()); - pool.get_or_build(key("host"), || Ok(Client::new())) - .unwrap(); + drop(pool.checkout(key("host"), || Ok(Client::new())).unwrap()); let weak = Arc::downgrade(&pool); let cleanup = tokio::spawn(expire_idle_clients(Handle::current().id(), pool)); tokio::task::yield_now().await; tokio::time::advance(IDLE_TIMEOUT + SWEEP_INTERVAL).await; - cleanup.await.unwrap(); + finish_cleanup(cleanup).await; assert!(weak.upgrade().is_none()); } #[tokio::test] - async fn cancelling_cleanup_drops_the_cache() { + async fn cancelling_cleanup_closes_cache_even_with_active_clients() { let pool = Arc::new(ClientPool::default()); - pool.get_or_build(key("host"), || Ok(Client::new())) - .unwrap(); - let weak = Arc::downgrade(&pool); - let cleanup = tokio::spawn(expire_idle_clients(Handle::current().id(), pool)); + let client = pool.checkout(key("host"), || Ok(Client::new())).unwrap(); + let cleanup = tokio::spawn(expire_idle_clients(Handle::current().id(), pool.clone())); cleanup.abort(); assert!(cleanup.await.unwrap_err().is_cancelled()); - assert!(weak.upgrade().is_none()); + assert!(pool.state.lock().unwrap().closed); + drop(client); + assert!(pool.state.lock().unwrap().entries.is_empty()); } #[tokio::test(start_paused = true)] - async fn cleanup_retains_recent_clients() { + async fn cleanup_retains_recent_and_checked_out_clients() { let pool = Arc::new(ClientPool::default()); - pool.get_or_build(key("host"), || Ok(Client::new())) - .unwrap(); + let client = pool.checkout(key("host"), || Ok(Client::new())).unwrap(); let weak = Arc::downgrade(&pool); - let cleanup = tokio::spawn(expire_idle_clients(Handle::current().id(), pool)); + let cleanup = tokio::spawn(expire_idle_clients(Handle::current().id(), pool.clone())); + drop(pool); tokio::task::yield_now().await; - tokio::time::advance(SWEEP_INTERVAL).await; + tokio::time::advance(IDLE_TIMEOUT + SWEEP_INTERVAL).await; tokio::task::yield_now().await; assert!(!cleanup.is_finished()); assert!(weak.upgrade().is_some()); - tokio::time::advance(IDLE_TIMEOUT).await; - cleanup.await.unwrap(); - } - - #[tokio::test(start_paused = true)] - async fn cleanup_does_not_detach_a_cache_held_by_a_builder() { - let pool = Arc::new(ClientPool::default()); - let cleanup = tokio::spawn(expire_idle_clients(Handle::current().id(), pool.clone())); - tokio::task::yield_now().await; + drop(client); tokio::time::advance(SWEEP_INTERVAL).await; tokio::task::yield_now().await; assert!(!cleanup.is_finished()); - pool.get_or_build(key("host"), || Ok(Client::new())) - .unwrap(); - drop(pool); tokio::time::advance(IDLE_TIMEOUT + SWEEP_INTERVAL).await; - cleanup.await.unwrap(); + finish_cleanup(cleanup).await; + assert!(weak.upgrade().is_none()); + } + + #[test] + fn shutdown_before_cleanup_is_polled_prevents_late_returns() { + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .unwrap(); + let pool = Arc::new(ClientPool::default()); + let client = pool.checkout(key("host"), || Ok(Client::new())).unwrap(); + runtime.spawn(expire_idle_clients(runtime.handle().id(), pool.clone())); + drop(runtime); + assert!(pool.state.lock().unwrap().closed); + drop(client); + assert!(pool.state.lock().unwrap().entries.is_empty()); } #[test] fn dynamic_trust_and_disabled_pooling_bypass_reuse() { let marker = "KERNEL_POOL_BYPASS_TEST"; let Some(mode) = std::env::var_os(marker) else { - for mode in ["normal", "directory", "unreadable"] { + for mode in ["normal", "directory", "unreadable", "roots"] { + let roots = tempfile::NamedTempFile::new().unwrap(); + std::fs::write(roots.path(), b"first roots").unwrap(); let mut child = std::process::Command::new(std::env::current_exe().unwrap()); child .args([ @@ -437,6 +642,9 @@ mod tests { "unreadable" => { child.env("SSL_CERT_FILE", "/unreadable/certificate/file"); } + "roots" => { + child.env("SSL_CERT_FILE", roots.path()); + } _ => {} } assert!( @@ -446,14 +654,23 @@ mod tests { } return; }; + if mode == "roots" { + let first = PoolKey::new("host", &HttpClientConfig::default()).unwrap(); + std::fs::write(std::env::var_os("SSL_CERT_FILE").unwrap(), b"second roots").unwrap(); + let second = PoolKey::new("host", &HttpClientConfig::default()).unwrap(); + assert!(first != second); + return; + } let check = |config: HttpClientConfig, expected| { let builds = AtomicUsize::new(0); for _ in 0..2 { - shared_client("host", &config, || { - builds.fetch_add(1, Ordering::SeqCst); - Ok(Client::new()) - }) - .unwrap(); + drop( + session_client("host", &config, || { + builds.fetch_add(1, Ordering::SeqCst); + Ok(Client::new()) + }) + .unwrap(), + ); } assert_eq!(builds.load(Ordering::SeqCst), expected); }; @@ -480,6 +697,17 @@ mod tests { #[test] fn runtime_registry_is_bounded_and_shutdown_releases_clients() { + let marker = "KERNEL_POOL_REGISTRY_TEST"; + if std::env::var_os(marker).is_none() { + let status = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "client::pool::tests::runtime_registry_is_bounded_and_shutdown_releases_clients", "--nocapture"]) + .env(marker, "1").status().unwrap(); + assert!( + status.success(), + "isolated runtime registry assertions failed" + ); + return; + } let runtimes: Vec<_> = (0..=MAX_RUNTIMES) .map(|_| { tokio::runtime::Builder::new_current_thread() @@ -492,8 +720,7 @@ mod tests { for runtime in &runtimes[..MAX_RUNTIMES] { let pool = runtime_pool(runtime.handle()).unwrap(); assert!(Arc::ptr_eq(&pool, &runtime_pool(runtime.handle()).unwrap())); - pool.get_or_build(key("host"), || Ok(Client::new())) - .unwrap(); + drop(pool.checkout(key("host"), || Ok(Client::new())).unwrap()); weak_pools.push(Arc::downgrade(&pool)); } assert!(runtime_pool(runtimes[MAX_RUNTIMES].handle()).is_none()); diff --git a/src/config.rs b/src/config.rs index 9c1eb0a9..26844f0c 100644 --- a/src/config.rs +++ b/src/config.rs @@ -761,7 +761,12 @@ 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). + /// Per-session connection pool size (max idle warm sockets per remote host). + /// A live session has exclusive use of its pool. After the HTTP client is + /// dropped, a matching session on the same runtime may reuse that pool. + /// Idle pools, including sockets and TLS/proxy configuration, are retained + /// for up to 105 seconds. New sessions never reuse a pool older than five + /// minutes; system trust is a snapshot until it is rebuilt. /// /// Defaults to `100`, matching the JDBC driver's `HttpConnectionPoolSize` /// default. Raise this for workloads that burst many concurrent diff --git a/tests/v0_session_pool.rs b/tests/v0_session_pool.rs index 11a8526c..ba8d6636 100644 --- a/tests/v0_session_pool.rs +++ b/tests/v0_session_pool.rs @@ -1,5 +1,6 @@ use databricks_sql_kernel::{AuthConfig, DefaultOpts, HttpConfig, Session, TlsConfig}; use serde_json::{json, Value}; +use std::collections::HashSet; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::{Arc, Mutex}; use std::time::Duration; @@ -16,7 +17,6 @@ struct RecordedRequest { struct Server { host: String, - connections: Arc, requests: Arc>>, task: tokio::task::JoinHandle<()>, } @@ -96,7 +96,6 @@ impl Server { }); Self { host, - connections, requests, task, } @@ -132,7 +131,7 @@ async fn open( .unwrap() } -async fn sessions_share_connections_not_authentication_or_catalogs() { +async fn sessions_reuse_returned_pools_not_active_pools_or_session_state() { let server = Server::start().await; let first = open( &server, @@ -163,20 +162,13 @@ async fn sessions_share_connections_not_authentication_or_catalogs() { second.close().await.unwrap(); third.close().await.unwrap(); let requests = server.requests.lock().unwrap(); - assert_eq!( - server.connections.load(Ordering::SeqCst), - 1, - "request connections: {:?}", - requests - .iter() - .map(|request| (&request.method, request.connection)) - .collect::>() - ); let creates: Vec<_> = requests .iter() .filter(|request| request.method == "POST") .collect(); assert_eq!(creates.len(), 3); + assert_ne!(creates[0].connection, creates[1].connection); + assert_ne!(creates[1].connection, creates[2].connection); for (request, (token, catalog)) in creates.iter().zip([ ("dapi_first", "first_catalog"), ("dapi_second", "second_catalog"), @@ -190,9 +182,9 @@ async fn sessions_share_connections_not_authentication_or_catalogs() { } } -async fn different_headers_timeouts_and_tls_settings_use_separate_connections() { +async fn transport_settings_partition_pools_but_per_request_headers_do_not() { let server = Server::start().await; - for variant in 0..4 { + for variant in 0..5 { let mut http = HttpConfig::default(); let mut tls = TlsConfig::default(); match variant { @@ -201,12 +193,40 @@ async fn different_headers_timeouts_and_tls_settings_use_separate_connections() .push(("x-tenant".to_owned(), "other".to_owned())), 2 => http.request_timeout += Duration::from_secs(1), 3 => tls.accept_self_signed = true, + 4 => http + .custom_headers + .push(("User-Agent".to_owned(), "other-agent".to_owned())), _ => {} } let session = open(&server, "dapi_token", "catalog", http, tls).await; session.close().await.unwrap(); } - assert_eq!(server.connections.load(Ordering::SeqCst), 4); + let requests = server.requests.lock().unwrap(); + let creates: Vec<_> = requests + .iter() + .filter(|request| request.method == "POST") + .collect(); + assert_eq!(creates.len(), 5); + for left in 0..creates.len() { + for right in left + 1..creates.len() { + if (left, right) != (0, 1) { + assert_ne!(creates[left].connection, creates[right].connection); + } + } + } + for (index, request) in creates.iter().enumerate() { + assert_eq!( + request + .headers + .iter() + .any(|header| header.eq_ignore_ascii_case("x-tenant: other")), + index == 1 + ); + } + assert!(creates[4] + .headers + .iter() + .any(|header| header.eq_ignore_ascii_case("user-agent: other-agent"))); } async fn concurrent_sessions_keep_their_authentication_and_catalogs() { @@ -216,24 +236,37 @@ async fn concurrent_sessions_keep_their_authentication_and_catalogs() { async move { let token = format!("dapi_concurrent_{index}"); let catalog = format!("catalog_{index}"); - let session = open( + open( server, &token, &catalog, HttpConfig::default(), TlsConfig::default(), ) - .await; - session.close().await.unwrap(); + .await } }); - futures::future::join_all(sessions).await; + let sessions = futures::future::join_all(sessions).await; + futures::future::join_all( + sessions + .into_iter() + .map(|session| async move { session.close().await.unwrap() }), + ) + .await; let requests = server.requests.lock().unwrap(); let creates: Vec<_> = requests .iter() .filter(|request| request.method == "POST") .collect(); assert_eq!(creates.len(), 10); + assert_eq!( + creates + .iter() + .map(|request| request.connection) + .collect::>() + .len(), + 10 + ); for index in 0..10 { let catalog = format!("catalog_{index}"); let request = creates @@ -258,7 +291,8 @@ async fn separate_runtimes_never_share_clients() { .unwrap() }) .collect(); - for runtime in runtimes.iter().rev().chain(runtimes.iter()) { + for index in (0..3).rev().chain(0..3) { + let runtime = &runtimes[index]; runtime.block_on(async { let session = Session::builder() .http_path(host.clone(), "/sql/1.0/warehouses/test") @@ -266,6 +300,11 @@ async fn separate_runtimes_never_share_clients() { token: "dapi_runtime".into(), identity_federation_client_id: None, }) + .defaults({ + let mut defaults = DefaultOpts::default(); + defaults.catalog = Some(index.to_string()); + defaults + }) .open() .await .unwrap(); @@ -275,7 +314,28 @@ async fn separate_runtimes_never_share_clients() { }) .await .unwrap(); - assert_eq!(server.connections.load(Ordering::SeqCst), 3); + let requests = server.requests.lock().unwrap(); + let creates: Vec<_> = requests + .iter() + .filter(|request| request.method == "POST") + .collect(); + assert_eq!(creates.len(), 6); + let groups: Vec> = (0..3) + .map(|index| { + let catalog = index.to_string(); + creates + .iter() + .filter(|request| request.body["catalog"] == catalog) + .map(|request| request.connection) + .collect() + }) + .collect(); + for left in 0..groups.len() { + assert!(!groups[left].is_empty()); + for right in left + 1..groups.len() { + assert!(groups[left].is_disjoint(&groups[right])); + } + } } async fn changed_root_file_contents_do_not_reuse_old_trust() { @@ -305,7 +365,13 @@ async fn changed_root_file_contents_do_not_reuse_old_trust() { ) .await; second.close().await.unwrap(); - assert_eq!(server.connections.load(Ordering::SeqCst), 2); + let requests = server.requests.lock().unwrap(); + let creates: Vec<_> = requests + .iter() + .filter(|request| request.method == "POST") + .collect(); + assert_eq!(creates.len(), 2); + assert_ne!(creates[0].connection, creates[1].connection); } #[test] @@ -331,9 +397,9 @@ fn session_pool_end_to_end() { .unwrap() .block_on(async { tokio::time::timeout(Duration::from_secs(20), async { - sessions_share_connections_not_authentication_or_catalogs().await; + sessions_reuse_returned_pools_not_active_pools_or_session_state().await; concurrent_sessions_keep_their_authentication_and_catalogs().await; - different_headers_timeouts_and_tls_settings_use_separate_connections().await; + transport_settings_partition_pools_but_per_request_headers_do_not().await; separate_runtimes_never_share_clients().await; changed_root_file_contents_do_not_reuse_old_trust().await; }) From 5c70c389f3be2e5dcfae53f8945eb00031f176c2 Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Fri, 20 Nov 2026 04:26:40 +0000 Subject: [PATCH 4/9] test(session): require reuse across sequential opens Cover the Session::open wiring with eight sequential opens and request-used socket IDs, tolerating spare connects. Replacing for_session with new fails the test with exit 101. Signed-off-by: Vu Anh Phung Co-authored-by: Isaac --- tests/v0_session_pool.rs | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/tests/v0_session_pool.rs b/tests/v0_session_pool.rs index ba8d6636..c5653fdf 100644 --- a/tests/v0_session_pool.rs +++ b/tests/v0_session_pool.rs @@ -131,6 +131,34 @@ async fn open( .unwrap() } +async fn sequential_sessions_reuse_returned_clients() { + let server = Server::start().await; + const OPENS: usize = 8; + for _ in 0..OPENS { + let session = open( + &server, + "dapi_token", + "catalog", + HttpConfig::default(), + TlsConfig::default(), + ) + .await; + session.close().await.unwrap(); + tokio::task::yield_now().await; + } + let requests = server.requests.lock().unwrap(); + let creates: Vec<_> = requests + .iter() + .filter(|request| request.method == "POST") + .collect(); + assert_eq!(creates.len(), OPENS); + let connections: HashSet<_> = creates.iter().map(|request| request.connection).collect(); + assert!( + connections.len() < OPENS, + "Session::open rebuilt every returned HTTP client" + ); +} + async fn sessions_reuse_returned_pools_not_active_pools_or_session_state() { let server = Server::start().await; let first = open( @@ -397,6 +425,7 @@ fn session_pool_end_to_end() { .unwrap() .block_on(async { tokio::time::timeout(Duration::from_secs(20), async { + sequential_sessions_reuse_returned_clients().await; sessions_reuse_returned_pools_not_active_pools_or_session_state().await; concurrent_sessions_keep_their_authentication_and_catalogs().await; transport_settings_partition_pools_but_per_request_headers_do_not().await; From c583e8b3ca668b7201cb38cda58035ed371dab45 Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Fri, 20 Nov 2026 04:27:57 +0000 Subject: [PATCH 5/9] fix(http): classify every client setting in the pool key Destructure HttpClientConfig exhaustively, requiring new settings to be classified before compilation succeeds. Test per-request settings independently; adding a future transport field fails with E0027 in TransportKey::from. Signed-off-by: Vu Anh Phung Co-authored-by: Isaac --- src/client/pool.rs | 64 ++++++++++++++++++++++++++++++++-------------- 1 file changed, 45 insertions(+), 19 deletions(-) diff --git a/src/client/pool.rs b/src/client/pool.rs index ded246d2..8c7fbc60 100644 --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -40,13 +40,25 @@ struct TransportKey { impl From<&HttpClientConfig> for TransportKey { fn from(config: &HttpClientConfig) -> Self { + // New settings must be classified as transport or per-request state. + let HttpClientConfig { + connect_timeout, + read_timeout, + max_connections_per_host, + user_agent, + tls, + proxy, + org_id: _, + custom_headers: _, + sea_response_compression_enabled: _, + } = config; Self { - connect_timeout: config.connect_timeout, - read_timeout: config.read_timeout, - max_connections_per_host: config.max_connections_per_host, - user_agent: config.user_agent.clone(), - tls: config.tls.clone(), - proxy: config.proxy.clone(), + connect_timeout: *connect_timeout, + read_timeout: *read_timeout, + max_connections_per_host: *max_connections_per_host, + user_agent: user_agent.clone(), + tls: tls.clone(), + proxy: proxy.clone(), } } } @@ -429,19 +441,33 @@ mod tests { ..key("host") }); } - let mut per_request = original.clone(); - per_request.org_id = Some("other-org".into()); - per_request - .custom_headers - .push(("x-test".into(), "value".into())); - per_request.sea_response_compression_enabled = true; - assert!(TransportKey::from(&per_request) == TransportKey::from(&original)); - assert!(pool - .take(&PoolKey { - config: (&per_request).into(), - ..key("host") - }) - .is_some()); + } + + #[tokio::test] + async fn per_request_settings_each_reuse_the_same_transport() { + let pool = Arc::new(ClientPool::default()); + drop(pool.checkout(key("host"), || Ok(Client::new())).unwrap()); + for variant in 0..3 { + let mut per_request = HttpClientConfig::default(); + match variant { + 0 => per_request.org_id = Some("other-org".into()), + 1 => per_request + .custom_headers + .push(("x-test".into(), "value".into())), + 2 => per_request.sea_response_compression_enabled = true, + _ => unreachable!(), + } + drop( + pool.checkout( + PoolKey { + config: (&per_request).into(), + ..key("host") + }, + || panic!("per-request setting partitioned the transport"), + ) + .unwrap(), + ); + } } #[tokio::test(start_paused = true)] From f61e98236aae8ce471be4995af3370ee3f654ab6 Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Fri, 20 Nov 2026 04:29:45 +0000 Subject: [PATCH 6/9] fix(http): expire idle clients during cache access Sweep all expired entries on take and put, including rejected returns, and drop them after unlocking. Test a current-thread runtime that is never polled; removing either sweep fails the test. Signed-off-by: Vu Anh Phung Co-authored-by: Isaac --- NEXT_CHANGELOG.md | 2 +- src/client/pool.rs | 107 +++++++++++++++++++++++++++++++++++++-------- src/config.rs | 8 ++-- 3 files changed, 94 insertions(+), 23 deletions(-) diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index 85dd081e..5684a3a9 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -16,7 +16,7 @@ changes go in their respective binding's NEXT_CHANGELOG. ### Changed -- Sessions can reuse a matching HTTP connection pool after its previous HTTP client is dropped; live sessions keep exclusive pools and independent idle-socket limits. Idle retention is bounded to 105 seconds (including TLS/proxy configuration), and pools older than five minutes are never reused, bounding system-trust snapshots. +- Sessions can reuse a matching HTTP connection pool after its previous HTTP wrapper is dropped; live sessions keep exclusive pools and independent idle-socket limits. Idle sockets and TLS/proxy configuration expire after 90 seconds, with cleanup within 15 more seconds while the runtime is driven or on the next cache access/shutdown otherwise; pools older than five minutes are never reused, bounding system-trust snapshots. - 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/src/client/pool.rs b/src/client/pool.rs index 8c7fbc60..3e5f431a 100644 --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -156,6 +156,21 @@ struct PoolState { closed: bool, } +impl PoolState { + fn expire(&mut self, now: Instant) -> Vec { + let mut expired = Vec::new(); + let mut index = 0; + while index < self.entries.len() { + if !self.entries[index].reusable(now) { + expired.push(self.entries.swap_remove(index)); + } else { + index += 1; + } + } + expired + } +} + #[derive(Default)] struct ClientPool { state: Mutex, @@ -165,11 +180,15 @@ impl ClientPool { fn take(&self, key: &PoolKey) -> Option { let now = Instant::now(); let mut state = self.state.lock().unwrap_or_else(|error| error.into_inner()); - let index = state + let expired = state.expire(now); + let entry = state .entries .iter() - .position(|entry| entry.key == *key && entry.reusable(now))?; - Some(state.entries.swap_remove(index)) + .position(|entry| entry.key == *key) + .map(|index| state.entries.swap_remove(index)); + drop(state); + drop(expired); + entry } fn checkout( @@ -192,11 +211,15 @@ impl ClientPool { } fn put(&self, entry: Entry) { + let now = Instant::now(); let mut state = self.state.lock().unwrap_or_else(|error| error.into_inner()); - if state.closed || !entry.reusable(Instant::now()) { + let mut expired = state.expire(now); + if state.closed || !entry.reusable(now) { + drop(state); + drop(expired); return; } - let evicted = if state.entries.len() == MAX_CLIENTS { + if state.entries.len() == MAX_CLIENTS { let oldest = state .entries .iter() @@ -204,26 +227,16 @@ impl ClientPool { .min_by_key(|(_, entry)| entry.idle_since) .map(|(index, _)| index) .unwrap_or(0); - Some(state.entries.swap_remove(oldest)) - } else { - None - }; + expired.push(state.entries.swap_remove(oldest)); + } state.entries.push(entry); drop(state); - drop(evicted); + drop(expired); } fn expire(&self, now: Instant) { let mut state = self.state.lock().unwrap_or_else(|error| error.into_inner()); - let mut expired = Vec::new(); - let mut index = 0; - while index < state.entries.len() { - if !state.entries[index].reusable(now) { - expired.push(state.entries.swap_remove(index)); - } else { - index += 1; - } - } + let expired = state.expire(now); drop(state); drop(expired); } @@ -513,6 +526,62 @@ mod tests { assert!(pool.state.lock().unwrap().entries.is_empty()); } + #[test] + fn cache_access_expires_entries_without_polling_the_runtime() { + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .unwrap(); + let _entered = runtime.enter(); + tokio::time::pause(); + let polls = Arc::new(AtomicUsize::new(0)); + for access in 0..3 { + let pool = Arc::new(ClientPool::default()); + let cleanup = expire_idle_clients(runtime.handle().id(), pool.clone()); + let task_polls = polls.clone(); + runtime.spawn(async move { + task_polls.fetch_add(1, Ordering::SeqCst); + cleanup.await; + }); + let created_at = Instant::now(); + let mut expired_key = key("expired"); + expired_key.config.tls.client_key_pem = Some(b"expired-private-key".to_vec()); + expired_key.config.proxy.password = Some("expired-proxy-password".into()); + pool.put(Entry { + key: expired_key, + client: Client::new(), + created_at, + idle_since: created_at, + }); + // Advance the clock without driving Tokio's tasks or IO/timer driver. + futures::executor::block_on(tokio::time::advance(if access == 2 { + MAX_AGE + } else { + IDLE_TIMEOUT + SWEEP_INTERVAL + })); + if access == 0 { + assert!(pool.take(&key("unrelated")).is_none()); + } else { + pool.put(Entry { + key: key("returned"), + client: Client::new(), + created_at: if access == 2 { + created_at + } else { + Instant::now() + }, + idle_since: Instant::now(), + }); + } + assert_eq!( + pool.state.lock().unwrap().entries.len(), + usize::from(access == 1), + "cache access {access} retained expired configuration" + ); + assert_eq!(polls.load(Ordering::SeqCst), 0); + } + } + #[tokio::test(start_paused = true)] async fn maximum_age_expires_clients_despite_repeated_checkouts() { let pool = Arc::new(ClientPool::default()); diff --git a/src/config.rs b/src/config.rs index 26844f0c..e484701d 100644 --- a/src/config.rs +++ b/src/config.rs @@ -764,9 +764,11 @@ pub struct HttpConfig { /// Per-session connection pool size (max idle warm sockets per remote host). /// A live session has exclusive use of its pool. After the HTTP client is /// dropped, a matching session on the same runtime may reuse that pool. - /// Idle pools, including sockets and TLS/proxy configuration, are retained - /// for up to 105 seconds. New sessions never reuse a pool older than five - /// minutes; system trust is a snapshot until it is rebuilt. + /// Idle pools, including sockets and TLS/proxy configuration, expire after + /// 90 seconds. Cleanup runs every 15 seconds while the runtime is driven; + /// otherwise expired pools are released on cache access or runtime shutdown. + /// New sessions never reuse a pool older than five minutes; system trust + /// is a snapshot until it is rebuilt. /// /// Defaults to `100`, matching the JDBC driver's `HttpConnectionPoolSize` /// default. Raise this for workloads that burst many concurrent From 2b3bb7a78125b22ca7e0555b9d12d262a9c1ab3c Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Fri, 20 Nov 2026 04:32:00 +0000 Subject: [PATCH 7/9] feat(http): allow disabling cross-session client reuse Add HttpConfig::reuse_client_across_sessions, defaulting to true. False bypasses only the cross-session cache and preserves within-session keep-alive. Document idle/trust retention and test both behaviors, including two failing mutants. Signed-off-by: Vu Anh Phung Co-authored-by: Isaac --- NEXT_CHANGELOG.md | 2 +- src/config.rs | 27 ++++++++++++++++++++------- src/session.rs | 13 ++++++++----- tests/v0_session_pool.rs | 29 +++++++++++++++++++++++++++++ 4 files changed, 58 insertions(+), 13 deletions(-) diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index 5684a3a9..c999776e 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -16,7 +16,7 @@ changes go in their respective binding's NEXT_CHANGELOG. ### Changed -- Sessions can reuse a matching HTTP connection pool after its previous HTTP wrapper is dropped; live sessions keep exclusive pools and independent idle-socket limits. Idle sockets and TLS/proxy configuration expire after 90 seconds, with cleanup within 15 more seconds while the runtime is driven or on the next cache access/shutdown otherwise; pools older than five minutes are never reused, bounding system-trust snapshots. +- Sessions reuse matching idle HTTP clients by default while keeping exclusive pools and independent idle-socket limits; set `HttpConfig::reuse_client_across_sessions = false` to opt out without disabling keep-alive within a session. After the last HTTP wrapper drops, reuse retains idle sockets and TLS/proxy configuration for up to about 105 seconds while the runtime is driven (otherwise until the next cache access/shutdown), and a new session's system-trust snapshot can be up to 300 seconds old. - 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/src/config.rs b/src/config.rs index e484701d..2179c738 100644 --- a/src/config.rs +++ b/src/config.rs @@ -762,13 +762,8 @@ pub struct HttpConfig { pub overall_timeout: Duration, /// Per-session connection pool size (max idle warm sockets per remote host). - /// A live session has exclusive use of its pool. After the HTTP client is - /// dropped, a matching session on the same runtime may reuse that pool. - /// Idle pools, including sockets and TLS/proxy configuration, expire after - /// 90 seconds. Cleanup runs every 15 seconds while the runtime is driven; - /// otherwise expired pools are released on cache access or runtime shutdown. - /// New sessions never reuse a pool older than five minutes; system trust - /// is a snapshot until it is rebuilt. + /// A live session has exclusive use of its pool. Cross-session reuse is + /// controlled by [`reuse_client_across_sessions`](Self::reuse_client_across_sessions). /// /// Defaults to `100`, matching the JDBC driver's `HttpConnectionPoolSize` /// default. Raise this for workloads that burst many concurrent @@ -777,6 +772,23 @@ pub struct HttpConfig { /// pool fills. pub pool_max_idle_per_host: usize, + /// Reuse an idle HTTP client across compatible sessions on the same runtime. + /// Defaults to `true`. Disabling this preserves keep-alive within a session. + /// + /// After the last HTTP wrapper drops, idle sockets and TLS/proxy configuration + /// may remain for about 105 seconds (90-second expiry plus a 15-second sweep). + /// Cleanup requires a driven runtime; otherwise expiry runs on the next cache + /// access or runtime shutdown. Reused clients are at most 300 seconds old, so + /// a new session's system-trust snapshot can be up to 300 seconds old. + /// + /// ``` + /// use databricks_sql_kernel::HttpConfig; + /// let mut http = HttpConfig::default(); + /// assert!(http.reuse_client_across_sessions); + /// http.reuse_client_across_sessions = false; + /// ``` + pub reuse_client_across_sessions: bool, + /// Minimum backoff wait between retry attempts. Also the floor for /// a server-supplied `Retry-After` and the base of the exponential /// backoff (`min_wait * 2^attempt`) used when no `Retry-After` is @@ -845,6 +857,7 @@ impl Default for HttpConfig { request_timeout: Duration::from_secs(120), overall_timeout: Duration::from_secs(900), pool_max_idle_per_host: 100, + reuse_client_across_sessions: true, // Mirror `RetryConfig::default()` so a stock `HttpConfig` // produces the same retry behaviour the kernel shipped // before these knobs were configurable. diff --git a/src/session.rs b/src/session.rs index 6c86341e..aedb3489 100644 --- a/src/session.rs +++ b/src/session.rs @@ -367,11 +367,14 @@ impl Session { // it for OIDC discovery / token endpoint calls. 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::for_session(&host, http_client_config, retry_configs).map_err( - |e| Error::network_error().message(format!("Failed to construct HTTP client: {e}")), - )?, - ); + let http_client = if config.http.reuse_client_across_sessions { + DatabricksHttpClient::for_session(&host, http_client_config, retry_configs) + } else { + DatabricksHttpClient::new(http_client_config, retry_configs) + }; + let http_client = Arc::new(http_client.map_err(|e| { + Error::network_error().message(format!("Failed to construct HTTP client: {e}")) + })?); // 2. Auth provider — async because OAuth flows hit the OIDC // discovery endpoint. diff --git a/tests/v0_session_pool.rs b/tests/v0_session_pool.rs index c5653fdf..6ec46f58 100644 --- a/tests/v0_session_pool.rs +++ b/tests/v0_session_pool.rs @@ -159,6 +159,34 @@ async fn sequential_sessions_reuse_returned_clients() { ); } +async fn reuse_opt_out_preserves_keep_alive_within_each_session() { + let server = Server::start().await; + const OPENS: usize = 8; + for _ in 0..OPENS { + let mut http = HttpConfig::default(); + http.reuse_client_across_sessions = false; + let session = open(&server, "dapi_token", "catalog", http, TlsConfig::default()).await; + session.close().await.unwrap(); + tokio::task::yield_now().await; + } + let requests = server.requests.lock().unwrap(); + let creates: HashSet<_> = requests + .iter() + .filter(|request| request.method == "POST") + .map(|request| request.connection) + .collect(); + let deletes: HashSet<_> = requests + .iter() + .filter(|request| request.method == "DELETE") + .map(|request| request.connection) + .collect(); + assert_eq!(creates.len(), OPENS, "reuse opt-out was ignored"); + assert!( + !creates.is_disjoint(&deletes), + "reuse opt-out disabled keep-alive within a session" + ); +} + async fn sessions_reuse_returned_pools_not_active_pools_or_session_state() { let server = Server::start().await; let first = open( @@ -426,6 +454,7 @@ fn session_pool_end_to_end() { .block_on(async { tokio::time::timeout(Duration::from_secs(20), async { sequential_sessions_reuse_returned_clients().await; + reuse_opt_out_preserves_keep_alive_within_each_session().await; sessions_reuse_returned_pools_not_active_pools_or_session_state().await; concurrent_sessions_keep_their_authentication_and_catalogs().await; transport_settings_partition_pools_but_per_request_headers_do_not().await; From 1e00d29d684ecca71371185201d8c5f42632221e Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Fri, 20 Nov 2026 04:47:57 +0000 Subject: [PATCH 8/9] docs: remove duplicate transport lifecycle changelog entry Keep the original entry from #434 and remove this branch duplicate. Verified that exactly one transport-cycle entry remains and the reuse opt-out documentation is preserved. Signed-off-by: Vu Anh Phung Co-authored-by: Isaac --- NEXT_CHANGELOG.md | 1 - 1 file changed, 1 deletion(-) diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index c999776e..a5df78e7 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -32,7 +32,6 @@ changes go in their respective binding's NEXT_CHANGELOG. ### Fixed -- Closing a `Session` now frees its transport, HTTP client and tokio runtime handle. A reference cycle between the transport and its result-reader factory kept them alive, so bindings that run one tokio runtime per session (Python) leaked four file descriptors per closed session until the process hit `Too many open files`. - `Session::open` authenticates once before resolving feature flags. A failed OAuth token request now fails the open immediately instead of being sent a second time by CreateSession. - A timed-out or reset CloudFetch download no longer writes the presigned URL's signature (`sig=`, `X-Amz-Signature`) to the log or the returned error. The request URL in those messages now ends at the path, and debug request lines stop at `?`. - Closing an OAuth session (M2M, M2M private key, U2M or Azure service principal) now frees its HTTP client and auth provider. The provider held the HTTP client strongly while the client owned the provider, so the pair and the provider's tokio runtime handle leaked for every closed session. From d5e73dde2672809a50bc347958cb25d4e29cd4b3 Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Fri, 20 Nov 2026 04:55:12 +0000 Subject: [PATCH 9/9] docs(http): explain reuse policy for binding consumers Document the Rust-only opt-out and idle/trust retention in Node/Python release notes, the shared C ABI connection reference and ADBC configuration docs. Validate all five documents name the option and bounds; no runtime or binding API change. Signed-off-by: Vu Anh Phung Co-authored-by: Isaac --- CONNECTION_PARAMETERS.md | 6 ++++++ NEXT_CHANGELOG.md | 2 +- adbc/README.md | 7 +++++++ napi/NEXT_CHANGELOG.md | 2 ++ pyo3/NEXT_CHANGELOG.md | 2 ++ 5 files changed, 18 insertions(+), 1 deletion(-) diff --git a/CONNECTION_PARAMETERS.md b/CONNECTION_PARAMETERS.md index edcf6001..3bea0a41 100644 --- a/CONNECTION_PARAMETERS.md +++ b/CONNECTION_PARAMETERS.md @@ -130,11 +130,17 @@ until implemented) and `External` (a caller-supplied `TokenProvider`). | `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` | +| `reuse_client_across_sessions` | Reuse compatible idle HTTP clients across sessions on one runtime; `false` preserves within-session keep-alive. Rust-only; Node.js, Python, C ABI and ADBC expose no corresponding option. | `true` | | `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) | | `custom_headers` | Extra headers on every request; an ordered `Vec<(String, String)>` (duplicates allowed). `Authorization` / `x-databricks-org-id` are silently dropped (reserved); a `User-Agent` is folded into the effective UA. | `[]` | +With cross-session reuse enabled, idle sockets and TLS/proxy configuration can +remain for about 105 seconds after the last HTTP wrapper drops while the runtime +is driven; otherwise expiry runs on the next cache access or runtime shutdown. +A new session's system-trust snapshot can be up to 300 seconds old. + ## `ProxyConfig` — HTTP/HTTPS proxy (optional) When `url` is `None`, the kernel does not configure a proxy and diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index a5df78e7..2e036c1b 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -16,7 +16,7 @@ changes go in their respective binding's NEXT_CHANGELOG. ### Changed -- Sessions reuse matching idle HTTP clients by default while keeping exclusive pools and independent idle-socket limits; set `HttpConfig::reuse_client_across_sessions = false` to opt out without disabling keep-alive within a session. After the last HTTP wrapper drops, reuse retains idle sockets and TLS/proxy configuration for up to about 105 seconds while the runtime is driven (otherwise until the next cache access/shutdown), and a new session's system-trust snapshot can be up to 300 seconds old. +- Sessions reuse matching idle HTTP clients by default while keeping exclusive pools and independent idle-socket limits; the Rust-only `HttpConfig::reuse_client_across_sessions = false` opt-out preserves keep-alive within a session and currently has no corresponding Node.js, Python, C ABI or ADBC option. After the last HTTP wrapper drops, reuse retains idle sockets and TLS/proxy configuration for up to about 105 seconds while the runtime is driven (otherwise until the next cache access/shutdown), and a new session's system-trust snapshot can be up to 300 seconds old. - 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/README.md b/adbc/README.md index 7b5bac0f..a0e41be8 100644 --- a/adbc/README.md +++ b/adbc/README.md @@ -107,6 +107,13 @@ 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` | +Kernel sessions reuse idle HTTP clients by default. Idle sockets and TLS/proxy +configuration can remain for about 105 seconds after the last HTTP wrapper drops +while the runtime is driven (otherwise until the next cache access/shutdown), +and a new session's system-trust snapshot can be up to 300 seconds old. +The keep-alive-preserving opt-out, `HttpConfig::reuse_client_across_sessions`, +is currently available only through the kernel Rust API; ADBC exposes no option. + 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/napi/NEXT_CHANGELOG.md b/napi/NEXT_CHANGELOG.md index d5ca462e..0326b8e5 100644 --- a/napi/NEXT_CHANGELOG.md +++ b/napi/NEXT_CHANGELOG.md @@ -16,6 +16,8 @@ layout, or npm publishing. Pure-kernel changes go in the root ### Changed +- Kernel sessions reuse idle HTTP clients by default, retaining sockets and TLS/proxy configuration for about 105 seconds after the last HTTP wrapper drops while the runtime is driven (otherwise until the next cache access/shutdown); a new session's system-trust snapshot can be up to 300 seconds old. The keep-alive-preserving opt-out, `HttpConfig::reuse_client_across_sessions = false`, is currently a kernel Rust setting with no Node.js option. + ### Updated ### Fixed diff --git a/pyo3/NEXT_CHANGELOG.md b/pyo3/NEXT_CHANGELOG.md index e0881e54..fe822571 100644 --- a/pyo3/NEXT_CHANGELOG.md +++ b/pyo3/NEXT_CHANGELOG.md @@ -15,6 +15,8 @@ changes go in the root `NEXT_CHANGELOG.md`. ### Changed +- Kernel sessions reuse idle HTTP clients by default, retaining sockets and TLS/proxy configuration for about 105 seconds after the last HTTP wrapper drops while the runtime is driven (otherwise until the next cache access/shutdown); a new session's system-trust snapshot can be up to 300 seconds old. The keep-alive-preserving opt-out, `HttpConfig::reuse_client_across_sessions = false`, is currently a kernel Rust setting with no Python option. + ### Updated ### Fixed